Graphing Your Sensor
When working with a sensor it’s often useful to be able to see a visualization of how your sensor is performing. Tom Igo at ITP wrote a simple Processing Program that does simply that.
Arduino Code:
int sensorPin = 0; // Sensor
int val = 0; // variable to store the value coming from the sensor
void setup() {
Serial.begin(9600);
}
void loop() {
val = analogRead(sensorPin); // read the value from the sensor
Serial.println(val, DEC);
delay(10); // stop the program for some time
}
Processing CODE
/* Serial String Reader
Language: Processing
Reads in a string of characters until gets a linefeed (ASCII 10);
Then Converts the string to a number.
*/
import processing.serial.*;
int linefeed = 10;
Serial myPort;
int sensorValue = 0;
void setup(){
size(800, 600);
// print available serial ports
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600);
myPort.bufferUntil(linefeed);
background(0);
}
// serial Event method is run automatically by processing applet
// whenever the buffer reaches the byte value set in the bufferUntil()
// method in setup()
void serialEvent(Serial myPort){
// read the serial buffer
String myString = myPort.readStringUntil(linefeed);
// if you got any bytes other than linefeed
if (myString !=null){
// trim off the carrige return and convert the string to an integer:
sensorValue = int (trim(myString));
// print it
println(sensorValue);
drawGraph();
}
}
int graphPosition = 0;
void drawGraph(){
// adjust this formula so tht the lineHeight is always less than
// the height of the window
int lineHeight = sensorValue/2;
// draw the line
stroke(50,50,50);
line (graphPosition, height, graphPosition, height – lineHeight);
// at the edge of screen, go back to the beginning
if (graphPosition >= 800){
graphPosition = 0;
background(0);
}else{
graphPosition++;
}
}