Skip to content

Instantly share code, notes, and snippets.

@tanyuan
Created April 13, 2016 00:58
Show Gist options
  • Save tanyuan/e6b56344e04d9f28c402395c12306acd to your computer and use it in GitHub Desktop.
Save tanyuan/e6b56344e04d9f28c402395c12306acd to your computer and use it in GitHub Desktop.
Robust serial transmitting between Processing and Arduino

Send a big number from Processing to Arduino through serial

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment