Quantcast
Channel: beginners - openFrameworks
Viewing all articles
Browse latest Browse all 4929

ofSerial fast simple serial read in OF not working properly (and linux problems too)

$
0
0

@as1er wrote:

hi all.

i have a simple arduino protocol sending 3 bytes + message terminator ','

void setup(){
  Serial.begin(9600);
}
int frame = 0;
void loop(){
  Serial.write(frame);
  Serial.write(random(255));
  Serial.write(random(255));
  Serial.write(',');
  delay(33);
  frame=(frame+1)%255;
}

in OF (from github), this is how i am trying to read the bytes (ofApp.cpp):

#include "ofApp.h"

ofSerial	serial;
int			incoming[3];
int			nRead = 0;

//#define SERIALLINUX

void ofApp::setup(){
#ifdef SERIALLINUX
	serial.setup("/dev/ttyUSB0", 9600); //open the first device
#else
	serial.setup(0, 9600); //open the first device
#endif
	
	incoming[0] = incoming[1] = incoming[2] = -1;
}

void ofApp::update(){
	
	if(serial.available()>3){
		unsigned char incomingBytes[4];
		memset(incomingBytes, 0, 4);
		
		while ( (nRead = serial.readBytes(incomingBytes, 4)  > 0)) {

			string datastring = ofToString(incomingBytes);
			
			if(datastring.size()>3  && datastring.at(3) == ','){
				for(int i=0; i<3; i++) { incoming[i] = (int)  datastring.at(i); }
				serial.flush(); // should be used after sucessfull read? less weird packets
			} else {
				cout << "weird packet at frame " << ofGetFrameNum() << " : " << datastring << endl;
			}

			
		}
	}
}

//--------------------------------------------------------------
void ofApp::draw(){
	ofBackground(255);
	string info = "fps: "+ofToString(ofGetFrameRate())+"\n";
	info += "nRead: "+ofToString(nRead)+"\n";
	for(int i=0; i<3; i++) { info += ofToString(i)+"  :  " + ofToString(incoming[i])+"\n"; }
	ofSetColor(0);
	ofDrawBitmapString(info, 10, 10);
}

this code sort of works ok, but there are several problems with it, could you help out?

1 - on Linux systems (debian, lubuntu) app behaves erratically, just once every 100 launches works as expected, most of the times i open the app and only get serial data every 2 seconds. i found a good solid workaround that works every time, but is not good for gallery installations: if you first open Arduino's Serial Monitor, then close it and open the app, it always works as expected.

2 - with this fast code there are a lot of dropped serial packets, which i am guessing due to syncing serial and of, ie, sometimes serial messages larger than 3bytes don't have the message terminator ',' at the right index. should i move to a buffered read a byte at time, then exec if the byte is my terminator approach?

i'd like to avoid other solutions like firmata for instance, which is too heavy weight for my bare bones needs.

thanks for reading and looking forward to hearing your suggestions.

Posts: 10

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 4929

Trending Articles