by Sensor Workshop class fall 2005

This Processing code Sends a byte out the serial port, and reads 2 bytes in. Then it combines the bytes into a single value. This way, you can send a 10-bit value from a microcontroller and receive it properly in Processing. This example assumes the microcontroller is sending the most significant byte first, and the least significant byte second.

Thanks to Daniel Shiffman for the improvements.

It works well with the Processing Two Byte Sender example.

// Serial call-and-response for v.91
// by sensor workshop Class

//  in Processing

// Sends a byte out the serial port, and reads 2 bytes in.
// Combines the bytes into a single value
// Thanks to Daniel Shiffman for the improvements.

// Updated 20 sept. 2005

import processing.serial.*;

int bgcolor;			     // Background color
int fgcolor;			     // Fill color
Serial port;                         // The serial port
int[] serialInArray = new int[2];    // Where we'll put what we receive
int serialCount = 0;                 // A count of how many bytes we receive
boolean firstContact = false;        // Whether we've heard from the microcontroller
int bigVariable = 0;

void setup() {
  size(256, 256);  // Stage size
  noStroke();      // No border on the next thing drawn


  // Print a list of the serial ports, for debugging purposes:
  println(Serial.list());

  // I know that the first port in the serial list on my mac
  // is always my  Keyspan adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  port = new Serial(this, Serial.list()[0], 9600);
  port.write(65);    // Send a capital A to start the microcontroller sending
}

void draw() {
  background(bgcolor);
  fill(fgcolor);
  // Get any new serial data
  while (port.available() > 0) {
    serialEvent();
    // Note that we heard from the microntroller:
    firstContact = true;

  }
  // If there's no serial data, send again until we get some.
  // (in case you tend to start Processing before you start your 
  // external device):
  if (firstContact == false) {
    delay(300);
    port.write(65);
  }
}

void serialEvent() {
  processByte((char)port.read());
}

void processByte(char inByte) {
  // Add the latest byte from the serial port to array:
  serialInArray[serialCount] = inByte;
  serialCount++;
  // If we have 3 bytes:
  if (serialCount > 1 ) {
    bigVariable = (serialInArray[0] * 256) + serialInArray[1]; 
    println(bigVariable); 
    // Send a capital A to request new sensor readings:
    port.write(65);
    // Reset serialCount:
    serialCount = 0;
  }
}