/* Serial call-and-response for v.90 by Tom Igoe 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 */ PImage candle; PImage picture; float i=0; float p=0; int range=255; //range of the dimmer int rand = 10; //detrmines the range of the flickering float n = 10; //# of images String pic = "picture0.gif"; import processing.serial.*; 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 boolean firstContact = false; // whether we've heard from the microcontroller void setup() { // 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, "COM1", 9600); port = new Serial(this, Serial.list()[0], 9600); port.write(65); // send a capital A to start the microcontroller sending candle = loadImage("candlelight.jpg"); size(candle.width, candle.height); background(0); picture = loadImage(pic); fill(0); } void draw() { // 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); } //p=dist(mouseX, mouseY, width/2, height-130); //range=height; colorMode(HSB, range); i=p+rand-random(2*rand); tint (i); image(candle, 0, 0); if(p==0) { pic = "picture" + int(1+random(n)) + ".jpg"; picture = loadImage(pic); } rect(width/2-picture.width/2-5, 25, picture.width+10, picture.height+10); image(picture, width/2-picture.width/2, 30); } 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 > 2 ) { p = (float)serialInArray[0]; println(p); //xpos = (float)serialInArray[0]; //ypos = (float)serialInArray[1]; //fgcolor = (int)serialInArray[2]; // send a capital A to request new sensor readings: port.write(65); // reset serialCount: serialCount = 0; } }