Null bytes when reading serial data with ofArduino

Hello,

I have recently been using Arduino with openFrameworks under windows. I thought using Firmata would be a good idea, but when I started making some tests I realised sometimes I was getting null (zero) bytes every 3/4 seconds, and this made analog values flicker over time, and also from time to time I got wrong values of the digital pins.

After checking every possible stage in the process (I tried with processing and it worked, I tried using oF firmata in a mac and it worked too, and I even tried creating my own protocol) I was very surprised when I found the problem was solved, or at least happened less often, when I increased the ms in the windows serial port buffer (under the Device Manager menu).

So I took a look at the code in the original update function in ofArduino.cpp, line 122:

  
    int dataRead=0;  
    // try to empty the _port buffer  
    while (dataRead<512) {  
  
        int byte = _port.readByte();  
  
        // process data....  
        if (byte!=-1) {  
            processData((char)(byte));  
            dataRead++;  
        }  
        // _port buffer is empty  
        else{  
            break;  
        }  
    }  
  

This seemed to me a strange way of reading, so I tried to change it to this one:

  
  
int bytesToRead = _port.available();  
if (bytesToRead>0) {  
  unsigned char* bytesToProcess = new unsigned char[bytesToRead];  
  readBytes(bytesToProcess, bytesToRead);  
  for (int i = 0; i < bytesToRead; i++) {  
        processData((char)(bytesToProcess[i]));  
  }  
  delete[] bytesToProcess;  
}  
  

So instead of reading 512 bytes every time (even if there are usually many less available), I’m just reading the number of bytes available. This fix seems to solve the problem. I don’t know exactly what is wrong with the original way, but i’m sure it doesn’t work properly in the conditions I’ve described. Maybe trying to read many times the serial port when there’s no data ready results in synchronicity errors??

Do you think all this makes any sense?

Thanks

J

yes, it seems way better than the original implementation. have added an issue to github:

http://github.com/openframeworks/openFr-…-/issue/237

gracias Arturo! :slight_smile: