Physical Interaction Design Using Processing

 

Serial Read and Graph (datalogger)

Here's a serial example that takes in a single byte and graphs it on the screen. It's useful for seeing the curve of an analog sensor over time.

/*
Datalogger
 by Tom Igoe
 
 This program takes raw bytes from the serial port at 9600 baud and graphs them.
 To start/stop the graph, click the mouse.
 
 No graphing is done when the incoming value is below a constant threshold.
 You can only change the threshold in code.  I haven't made a UI for that.
 
 Created 20 April 2005
 Updated 5 July 2005
 */

import processing.serial.*;

Serial myPort;  // The serial port

// initial variables:
int i = 1;                   // counter
int inByte = -1;             // data from serial port

void setup () {
  size(400, 300);        // window size

  // List all the available serial ports
  println(Serial.list());
  // I know that the third port in the serial list on my mac
  // is always my  Keyspan adaptor, so I open Serial.list()[2].
  // Open whatever port is the one you're using.
  myPort = new Serial(this, Serial.list()[2], 9600);
  
  // set inital background:
  background(0);
}
void draw () {
  if (myPort.available() > 0) {
    inByte = myPort.read();
    serialEvent();
  }
}

void serialEvent () {
  // draw the line:
  stroke(0,255,0);
  line(i, height, i, height - inByte);
  // at the edge of the screen, go back to the beginning:
  if (i >= width) {
    i = 0;
    background(0); 
  } 
  else {
    i++;
  }
}