[Fixed] Strong delay when reading Serial Input

edited February 2016 in Arduino

Problem solved by using serialEvent(), parsing the data and storing it in an array within serialEvent and then looping through that array and sending values to firmata in the draw() loop.

*

Hi Everyone, I'm in a bit of a time-crunch, so I'm hoping someone here can help me.

I need to read data from Arduino_1, check if values are higher than a threshold and then send them to another Arduino_2. Arduino_1is running code that I cannot change (it is also doing other things, I do not have whatever code is running on it, and I am worried I might break things if I start messing with it). Arduino_2 is running standard Firmata.

The problem I have is that currently there is a really high delay caused by the way I am Parsing the data. (I know its my parsing, because I have seen this work perfectly and the only thing that has changed is the code I am trying to recreate right now).

The incoming datastream from Arduino_1 looks like this (copy+paste form Arduino IDE):

...
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 2, 
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 1, 
3, 2, 2, 2, 2, 2, 1, 2, 
...

Its at 9700 Baud and I guess (but honestly have no idea) that there are 10ms delays between each line.

I am parsing it like so:

 if ( serial.available() > 0) 
  {  // If data is available,
    val = serial.readStringUntil('\n');        
    if (val!=null) {
      motorStates = split(val, ',');
      if (motorStates.length == 9) { //I don't understand why its 9. But it works. 
        for (int i = 0; i<motorStates.length; i++) {
          if (int(trim(motorStates[i]))>3) {
            binaryMotorStates[i]=1;
          } else {
            binaryMotorStates[i]=0;
          }
        }
      }
     send();  //send values to Arduino
    }

The send function either uses Firmata directly, or sends out an OSC message to a second sketch which then writes to the Arduino using Firmata (using seperate sketches for sending and receiving has fixed some timing errors for me in the past). The check for the length of the array is only necessary if I have this code snippet running in the draw function. I have tried this both within serial.event as well as in draw and I get the same delays.

Any suggestions on what to try next, or better ways of parsing my data stream? I'm pretty sure that I'm making a mess of the parsing, I'd love alternate suggestions on how to do that.

Sign In or Register to comment.