Processing - missing serial data from Arduino, using readStringUntil()

Viewed 431

I've been trying to create an oscilloscope for serial data from my Arduino. In the Arduino serial plotter I can get a good waveform up to suitable frequencies, but when I try send the data to Processing it doesn't receive all the data from the Arduino. Is there a way around this?

Arduino

const int analogIn = A6;
int integratorOutput = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(3, OUTPUT);
  pinMode(2, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  
  integratorOutput = analogRead(analogIn);
  Serial.println(integratorOutput);
}

Processing

void serialEvent (Serial port) {
  // get the ASCII string:
  String inString = port.readStringUntil('\n');
  if (inString != null) {
    inString = trim(inString);                // trim off whitespaces.
    inByte = float(inString);           // convert to a number.
    inByte = map(inByte, 0, 1023, 100, height-100); //map to the screen height.
    println(inByte);
    newData = true; 
  } 
}

Thanks!

1 Answers

It's because readStringUntil is a non blocking function. Let's assume Arduino is printing a line: 12345\n The serial port at 115200 bits per seconds is relatively slow, so it's possible that the at some point the receiving buffer contains only a part of the message, for example: 1234. When the port.readStringUntil('\n') is executed it doesn't encounter a \n in the buffer so it fails and returns a NULL. You can solve this problem by using bufferUntil as in this example

Related