Assignment 7.4

Post date: Jul 08, 2010 11:28:9 PM

This program requires two potentiometers, one connected to analog pin 1 and the other connected to analog pin 2. It uses the values of those potentiometers to determine the coordinates of an ellipse. An ellipse is drawn every time the draw method is run, though the background is not reset, so each ellipse drawn is shown until the program is reset. This creates the appearance of a line being drawn.

Here are the codes:

Arduino:

int potPin1 = 1; // set up variables

int potPin2 = 2;

int val = 0;

void setup() {

Serial.begin(9600); // begin serial communication at 9600 bps

}

void loop() {

val = analogRead(potPin1); // read potPin1 and store its value in val

Serial.print(val, DEC); // print the value of val

Serial.print(","); // separate the values with a comma

val = analogRead(potPin2);

Serial.println(val, DEC);

}

Processing:

import processing.serial.*; // import Processing library

Serial myPort; // set up variables

float xpos;

float ypos;

void setup() {

size(600, 600); // set window size to 600 x 600 pixels

myPort = new Serial(this, Serial.list()[0], 9600);

myPort.bufferUntil('\n'); // store myPort's values in a buffer until the value is reached

background(225); // sets background color to white

}

void draw() {

fill(0); // set fill color to black

stroke(0); // set stroke color to black

ellipse(xpos, ypos, 5, 5); // draw ellipse

}

void serialEvent(Serial myPort) {

String myString = myPort.readStringUntil('\n'); // read the serial buffer

if (myString != null) { // if it gets any bytes other than the linefeed,

myString = trim(myString);

int sensors[] = int(split(myString, ',')); // split the string at the commas

for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) {

print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t"); // print the values

}

println(); // add a linefeed after all the sensor values are printed

if (sensors.length > 1) {

xpos = map(sensors[0], 0, 1023, 0, 600); // adjust the values so the ellipse will stay in the window

ypos = map(sensors[1], 0, 1023, 0, 600);

}

}

}

Note:

If the potentiometer is adjusted too quickly, the circles will have a gap between them like a break in the line. If you just slow down and don't try to race someone you should be fine.