Arduino / Processing - LDR

Submitted by aaron on Fri, 06/17/2011 - 15:33

Stumped for hours as to why I couldn't get processing to read my arduino's serial port I stumbled across a code sample in the processing docs that didn't use serialEvent.  Then it worked fine!  This code simply sets the background color to match the value being sent over the serial port from an Arduino that is sampling a LDR (light sensor).
Also helpful : http://www.sundh.com/blog/2011/05/get-processing-and-arduino-to-talk/comment-page-1/
 

import processing.serial.*;

final int LINE_FEED = 10;
Serial arduinoPort;
int brightness= 0;

void setup(){
  size(400,400);
  println(Serial.list());
  String arduinoPortName = "/arduino/port/here";
  println("Using "+arduinoPortName);
  arduinoPort = new Serial(this, arduinoPortName, 9600);
  arduinoPort.bufferUntil(LINE_FEED);
  println("Setup Done!");
}

void draw(){
  if(arduinoPort.available() > 0){
    String sensor_brightness = arduinoPort.readStringUntil(LINE_FEED);
    if(sensor_brightness != null){
      sensor_brightness = sensor_brightness.trim();
      println(sensor_brightness);
      brightness = 255 - Integer.parseInt(sensor_brightness);
      if(brightness < 0){ brightness = 0; }
      if(brightness > 255){ brightness = 255; }
      background(brightness);
    }
  }   
}

 

Copyright © 2011, Aaron Blondeau

Drupal theme by Kiwi Themes.