Sends a byte out the serial port, and reads 3 bytes
in.
Sets foregound color, xpos, and ypos of a circle
onstage
using the values returned from the serial port.
Thanks to Daniel Shiffman for the improvements
Updated 21 March 2005
*/
int bgcolor; // background color
int fgcolor; // fill color
Serial port; // the serial port
int[] serialInArray = new int[3]; // where we'll put what we receive
int serialCount = 0; // a count of how many bytes we receive
float xpos, ypos; // Starting position of the ball
boolean firstContact = false; // whether we've heard from the microcontroller
public void setup() {
size(256, 256); // stage size
noStroke(); // no border on the next thing drawn
// Set the starting position of the ball (middle of the stage)
xpos = 40;
ypos = 30;
// print a list of the serial ports, for debugging
port = new Serial(this, "COM1", 9600);
//port = new Serial(this, Serial.list()[0], 9600);
port.write(65); // send a capital A to start the microcontroller sending
}
public void draw() {
background(bgcolor);
fill(255,0,0);
// Draw the shape
rectangle(xpos, ypos, 20, 20);
// 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);
}
}
public void serialEvent() {
processByte((char)port.read());
}
public void processByte(char inByte) {
// add the latest byte from the serial port to
serialCount++;
// if we have 3 bytes:
if (serialCount > 2 ) {
xpos = (float)serialInArray[0];
ypos = (float)serialInArray[1];
fgcolor = (int)serialInArray[2];
// send a capital A to request new sensor
serialCount = 0;
}
}
}