We would like to send a big number (0-1023) from Processing to Arduino (which can only read 0-255 at a time).
In Processing:
import processing.serial.*;
Serial arduino;
void sentEvent(int data) {
// Only write serial port when Arduino says yes
if (receiveEvent() != 1) {
// CRTICAL: always clear buffer; otherwise write() might stuck
arduino.clear();
return;
}
// Mark starting point
arduino.write(0xfe);
// Arduino can only read one byte (0-255) at a time
// So we divide the big number into two parts
arduino.write(data/256);
arduino.write(data%256);
}
int receiveEvent() {
int enable = arduino.read(); // might be -1 sometimes
return enable;
}
In Arduino:
int receiveEvent() {
if (Serial.available() > 0) {
//0xff is a header marker
if (Serial.read() == 0xfe) {
while (Serial.available() <= 0); // Empty loop to avoid non-sense values
int multiplier = Serial.read();
while (Serial.available() <= 0);
int remainder = Serial.read();
return (256 * multiplier + remainder);
}
}
}
void sendEvent(bool enable) {
Serial.write(enable);
}