Thursday, October 15, 2009

Moving Box Arduino/Serial

I was just messing around this afternoon trying to learn processing and came up with this sketch. It allows you to use a variable sensor to move a box or other object in processing.

/*
Sensor Graphing Sketch

This sketch takes raw bytes from the serial port at 9600 baud and graphs them.

Created 20 April 2005
Updated 5 August 2008
by Tom Igoe
Modified 14 October 2009
by Chris Anthony
*/

import processing.serial.*;
int xpos = 0;
int xpos2 = 0;
int smallByte = 0;

Serial myPort; // The serial port
int graphXPos = 1; // the horizontal position of the graph:

void setup () {
size(600, 500); // window size

// List all the available serial ports
println(Serial.list());
// I know that the fisrt port in the serial list on my mac
// is usually my Arduino module, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);

// set inital background:
background(48,31,65);
}
void draw () {
// nothing happens in draw. It all happens in SerialEvent()

}

void serialEvent (Serial myPort) {
// get the byte:

int inByte = myPort.read();
// print it:
println(inByte);

smallByte = inByte/10; //divide by 10 so that it goes slower

xpos = xpos2 + smallByte;
background(48,31,65); //important this goes here
rect(xpos, 20, 75, 75);
if (xpos > width) {
xpos = 0;
}
xpos2 = xpos; //swap variables

}

Here is product in action...