Assignment 7.4
Post date: Jul 15, 2010 10:20:8 PM
This one was actually really fun to play around with once it was finished. I made this car/truck thing:
Quite a masterpiece, huh?
Anyway, here is the code:
ARDUINO CODE:
const int pot1 = 5;
const int pot2 = 4;
void setup () {
Serial.begin(9600); //begin serial communication at 9600 bps
}
void loop () {
//print to serial port
Serial.print(int(analogRead(pot1)*0.249));
Serial.print(',');
Serial.println(int(analogRead(pot2)*0.249));
delay(20);
}
PROCESSING CODE:
import processing.serial.*;
Serial serPort;
int[] dotOrigin;
int[] previousDotOrigin;
void setup () {
// allocate arrays
dotOrigin = new int[2];
previousDotOrigin = new int[2];
size(255, 255); //set size to 255 x 255 pixels, just for convenience
background(255); //set background to white
stroke(0); //set line color to black
strokeWeight(3); //set line thickness to 3 pixels
// set up serial buffer
serPort = new Serial(this, Serial.list()[0], 9600);
serPort.bufferUntil('\n');
}
void draw () {
//the if statement stops the random line jump at the beginning of the sketch
if (previousDotOrigin[0] != 0 || previousDotOrigin[1] != 0) {
//draw line from previous dot to current dot
line(previousDotOrigin[0], previousDotOrigin[1], dotOrigin[0], dotOrigin[1]);
}
}
void serialEvent(Serial serPort) {
//store message from buffer in string
String message = serPort.readStringUntil('\n');
if(message != null) {
//remove whitespace and other nonsense
message = trim(message);
//set previous coordinates to those that are about to be changed
previousDotOrigin = dotOrigin;
//set dot coordinates to what's in the serial message
dotOrigin = int(split(message, ','));
}
}
I had been just drawing a filled ellipse at the coords before but they were often broken up and disconnected, especially when moving quickly, so I switched to drawing a line from the previous coordinates.