By Jeff Gray, February 2008

Three sensors. The first sensor is averaged by a given buffer size (limit). Uses an ArrayList as the storage container for the averaging.

Arduino Code

int an1, an2, an3 = 0;

void setup() {
  Serial.begin(19200);
}

void loop() {
  an1 = analogRead(0);
  delay(5); 
  an2 = analogRead(1);
  delay(5); 
  an3 = analogRead(2);
  Serial.print("X");
  Serial.println(an1,DEC);
  Serial.print("Y");
  Serial.println(an2,DEC);
  Serial.print("Z");
  Serial.println(an3,DEC);
  delay(15);               
}

Processing Code

import processing.serial.*;

String buff = "";
int val = 0;
int NEWLINE = 10;
int xPos,yPos,zPos = 0;
int displaySize = 2;
int an1, an2, an3;

Serial port;

ArrayList storage = new ArrayList();
int limit = 40;

void setup(){
  background(80);
  size(800,600);
  smooth();

  port = new Serial(this, Serial.list()[0], 19200);
}

void draw(){
  // new background over old
  fill(80,5);
  noStroke();
  rect(0,0,width,height);

  // wipe out a small area in front of the new data
  fill(80);
  rect(xPos+displaySize,0,50,height);

  // check for serial, and process
  while (port.available() > 0) {
    serialEvent(port.read());
  }
}


void serialEvent(int serial) { 
  if(serial != '\n') { 
    buff += char(serial);
  } else {
    int curX = buff.indexOf("X");
    int curY = buff.indexOf("Y");
    int curZ = buff.indexOf("Z");


    if(curX >=0){
      String val = buff.substring(curX+1);
      an1 = Integer.parseInt(val.trim());
      xPos++;

      Pos tempValue = new Pos(an1);
      storage.add(tempValue);
      if(storage.size() >= limit){
        int avgBuffer = 0;
        for(int i=0;i<storage.size();i++){
          Pos t = (Pos)storage.get(i);
          avgBuffer += t.value;
        }
        // keep at limit
        storage.remove(0);
        // make average out of buffer
        int avg = avgBuffer / limit;
        stroke(255);
        fill(255);
        ellipse(xPos,avg+20,displaySize,displaySize);
      }
      println("X: " + an1);
      if(xPos > width) xPos = 0;
      stroke(255,0,0);
      fill(255,0,0);
      ellipse(xPos,an1+20,displaySize,displaySize);

    }    
    if(curY >=0){
      String val = buff.substring(curY+1);
      an2 = Integer.parseInt(val.trim());
      yPos++;
      println("Y: " + an2);
      if(yPos > width) yPos = 0;
      stroke(0,255,0);
      fill(0,255,0);
      ellipse(yPos,an2-255,displaySize,displaySize);
    }
    if(curZ >=0){
      String val = buff.substring(curZ+1);
      an3 = Integer.parseInt(val.trim());
      zPos++;
      println("Z: " + an3);
      if(zPos > width) zPos = 0;
      stroke(0,0,255);
      fill(0,0,255);
      ellipse(zPos,an3-255,displaySize,displaySize);
    }

    // Clear the value of "buff"
    buff = "";
  }
}

class Pos {
  int value;

  Pos(int _in){
    value = _in;
  }
}