The idea was simple, Arduino reads sensors and sends 5 bytes of data, including CR and LF, to Processing. With 9600 bps, I should be able to do this fairly fast, at least faster than the speed of continuous button smashing.
First challenge:
I put about 10ms delay in my Arduino code here and there, and in my Processing sketch, I read the serial data in the draw() function. When I test it, I can see the data clogged up right away. After googling around, I realized the 10ms delay was too fast for Processing to handle. I changed it to 100ms as suggested online and the data clogging disappeared.
Second challenge:
However, with a 100ms delay between updates, the Arduino isn’t fast enough to capture all the button smashing. I found two possible solutions to this challenge, one is to use the standalone serial callback function in Processing because draw() and framerate limits the read speed, and the other one is to rewrite the program on Arduino so it only sends data out when any of the readings changes. The later is similar to the idea of chopping the original 100ms delay into smaller breaks, e.g. 10ms, so sensors are read 10 times more often, and because it only sends data when value changed, the Processing is able to keep up. This solved my problem for now.
...
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
state = digitalRead(pushButton);
sensorValue = digitalRead(fishButton);
// print out the state of the button:
bool sendData = false;
if (state != oldState) {
sendData = true;
oldState = state;
}
if (sensorValue != oldValue) {
sendData = true;
oldValue = sensorValue;
}
if (sendData) {
Serial.print(state);
Serial.print(";");
Serial.println(sensorValue);
}
delay(10);//delay in between reads for stability
}