Here is our final arduino code:
#include <Stdio.h>
int xCoord;
int yCoord;
char coords[10];//Limits string to a certain number of characters
void setup()
{
Serial.begin(9600);
}
void loop()
{
xCoord = analogRead(0);
yCoord = analogRead(1);
sprintf(coords, "%d,%d", xCoord, yCoord);//creates the string "number,number"
Serial.println(coords);//sends string to the serial port
delay(50);//dalay the next string for 50 miliseconds
}
And our processing final code:
import processing.serial.*;
Serial myPort;
String buff = "";
String buff1 = "";
String buff2 = "";
int index = 0;
int NEWLINE = 10;
// Store the last 256 values received so we can graph them.
int[] valuesx = new int[1001];
int[] valuesy = new int[1001];
void setup()
{
size(900, 900);
println(Serial.list());
String portName = Serial.list()[5];
myPort = new Serial(this, portName, 9600);
// If you know the name of the port used by the Arduino board, you
// can specify it directly like this.
//port = new Serial(this, "COM1", 9600);
}
void draw()
{
background(0);
stroke(255);
// Graph the stored values by drawing a lines between them.
for (int i = 0; i < 255; i++){
stroke(i);
strokeWeight(2);
line(900 - valuesx[i], 900 - valuesy[i],900 - valuesx[i + 1],900 - valuesy[i + 1]);
}
while (myPort.available() > 0)
serialEvent(myPort.read());
}
void serialEvent(int serial)
{
if (serial != NEWLINE) {
// Store all the characters on the line.
buff += char(serial);
}
else {
// The end of each line is marked by two characters, a carriage
// return and a newline. We're here because we've gotten a newline,
// but we still need to strip off the carriage return.
buff = buff.substring(0, buff.length()-1);
index = buff.indexOf(",");
buff1 = buff.substring(0, index);
buff2 = buff.substring(index+1, buff.length());
// Parse the String into an integer. We divide by 4 because
// analog inputs go from 0 to 1023 while colors in Processing
// only go from 0 to 255.
int x = Integer.parseInt(buff1)/2;
int y = Integer.parseInt(buff2)/2;
// Clear the value of "buff"
buff = "";
// Shift over the existing values to make room for the new one.
for (int i = 0; i < 1000; i++)
{
valuesx[i] = valuesx[i + 1];
valuesy[i] = valuesy[i + 1];
}
// Add the received value to the array.
valuesx[555] = x;
valuesy[555] = y;
}
}
I pretty much completely understand what going on in the Arduino code but I don't entirely understand the processing code when it gets into the parsing information part.
Tuesday, October 23, 2012
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment