I want to use Processing to read serial data from my Arduino, but first i want to understand how it interacts with the serial buffer.
According to the documentation, Serial.readString() returns all information in the serial buffer. But how does it recognize when to stop reading? For example, in the code below:
import processing.serial.*;
Serial myPort; // The serial port
void setup() {
// List all the available serial ports:
printArray(Serial.list());
// Open the port you are using at the rate you want:
myPort = new Serial(this, Serial.list()[0], 9600);
}
void draw() {
while (myPort.available() > 0) {
String inBuffer = myPort.readString();
if (inBuffer != null) {
println(inBuffer);
}
}
}
If I continuously send the string “Hello” from my arduino, my output in Processing is as such:
Hello
Hello
Hello
My question is, how does Serial.readString() know to wait for the full string before println()? Why does it not println char by char, as soon as the first “H” is received, as is expected when I print to the serial monitor in Arduino?
Please bear with me as i’m completely new to Processing, thanks.
if ( myPort.available() > 0) { // If data is available,
val = myPort.read(); // read it and store it in val
}
to handle full lines
void serialEvent(Serial myPort) { // if want to see what the arduino is answering:
String arduinoline = myPort.readStringUntil(10);
if ( arduinoline != null ) print(arduinoline);
}
I see there are serial methods of controlling how the buffer is read, thanks for the resources.
I’m still curious how serial.readString() knows when to terminate the string? Having a function which recognizes the end of a character stream sounds useful but I want to know how that works. Does it rely on a delay after the serial stream? If so how much is the delay?
I am not sure if you are asking about how to use the available functions to read data immediately as it arrives or if you want to explore the details of the operation done by the Processing Serial library. If it is the second, you can always explore the source code available in Github. You can study the SerialEvent() as it shows how the handling of streaming data is done.
The part you will need to understand is mainly within the body of that specific function. However, before you go into this part of the source code, you need to understand readStringUntil() as in when to use it and how to use it with the available functions.
A challenge for you, if you are interested, is to use a Thread to simulate incoming serial data.