Does serialEvent read data at a constant rate?

Hi, I am trying to measure the rate at which the void serialEvent (Serial myPort) function reads data. The way I am doing this is as follows:

void serialEvent (Serial myPort) {
  time_prev1 = time_now1;
  time_now1 = millis();
  dt = byte(time_now1 - time_prev1);
  myString = myPort.readStringUntil('\n');
  
  // saving the data to a .txt file:
  save2Doc_StringBuilder.append(dt);
  save2Doc_String[counter] = save2Doc_StringBuilder.toString();
  save2Doc_StringBuilder.setLength(0);
  counter++;
}

Strangely, I get the following results (in ms):

4
4
3
4
4
8
2
3
7
3
2
3
37
59
2
15
16
2
15
3
2
2
3
2
3
2
3
0
0
3
0
0
30
4
2

So, I am wondering: Is this normal? Is the rate of the serialEvent meant to be this fluctuating? I also tried putting a delay of 1 ms in my Arduino code loop with which I am sending the data, but I got the same results.

Thanks in advance,

MrImskiy

My view:

There is no guarantee that the operating sytem immediately releases the received data to your Processing sketch.

The operating system might also only have received a part of the data when it releases the data and you have to wait a bit till the next / remaining part is released.

And lastly your Arduino sketch can send it at irregular intervals depending on the code; we don’t know what it does.

Hi @MrImskiy, The operating system (Windows?) is doing lots of things as well as running your sketch. Run TaskManager on the performance and details tabs, and wonder at all that is going on.

There are things you can do to make it better (not perfect):

  • Close all the windows that you are not using.
  • “View Network Connections” and disable all the interfaces.
  • In your sketch, don’t save each result to file, put them in an array of ints, save to file at the end.
  • In your sketch, set low frameRate, e.g. 4, to use as little CPU time as possible.
  • In TaskManager, see the processe(s) that are running Processing, java.exe, javaw.exe (is that all?). Right click, set to realtime priority.
  • Stop the ‘explorer.exe’ processes (after the test, start one with TaskMgr ‘File’, ‘Run New Task’.)

Your Ard is sending each 1mS, but you haven’t said what baud rate you are using or how long the messages are. Check that you are not exceeding what is possible. Characters per second * 8 has to be less than the baud rate. (I don’t know if it can achieve that theoretical maximum. Real serial on wires has start and stop bits, so 8 should be 11, don’t know if that applies here.)

1 Like