cseeber
cseeber

Reputation: 63

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

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;
  }
}

Upvotes: 4

Views: 1414

Answers (1)

Krzysztof Nowak
Krzysztof Nowak

Reputation: 153

It's because readStringUntil is a nonblocking function. Let's assume Arduino is printing a line: 12345\n The serial port at 115,200 bits per second 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.

Upvotes: 5

Related Questions