I had worked on something similar. The sensor code is from an example I found before... I think on the Arduino site... I don't remember.
Anyway, I used separate code for the board and for Processing. Because the reading is based on how long it takes the LED to 'discharge', a dark room will cause a longer delay in updating the reading.
The Processing sketch simply scales the read value to the display window and shows it as a line plot.
You'll notice that the light will blink when there is less light.
Arduino code:
Quote:#define LED_N_SIDE 2
#define LED_P_SIDE 5
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned int j;
// Apply reverse voltage, charge up the pin and led capacitance
pinMode(LED_N_SIDE,OUTPUT);
pinMode(LED_P_SIDE,OUTPUT);
digitalWrite(LED_N_SIDE,HIGH);
digitalWrite(LED_P_SIDE,LOW);
// Isolate the pin 2 end of the diode
pinMode(LED_N_SIDE,INPUT);
digitalWrite(LED_N_SIDE,LOW); // turn off internal pull-up resistor
// Count how long it takes the diode to bleed back down to a logic zero
for ( j = 0; j < 30000; j++) {
if ( digitalRead(LED_N_SIDE)==0) break;
}
Serial.println(j);//send reading to Processing
// Turn the light on for 1000 microseconds
digitalWrite(LED_P_SIDE,HIGH);
digitalWrite(LED_N_SIDE,LOW);
pinMode(LED_P_SIDE,OUTPUT);
pinMode(LED_N_SIDE,OUTPUT);
delayMicroseconds(1000);
}
Processing code:
Quote:// Capacitive LED touch sensor
import processing.serial.*;
Serial port;
String buff = "";
int NEWLINE = 10;
int px = 0;
int peak = 0;
int threshold = 50;
int[] values = new int[512];
int val = 0;
void mouseReleased() {
px = mouseX;
}
void setup() {
size(512, 512);
textFont(createFont("Arial", 14),14);
println("Available serial ports:");
println(Serial.list());
port = new Serial(this, "COM5", 9600);
frameRate(30);
}
void draw()
{
background(54);
// Graph the stored values by drawing a line between them.
stroke(0,255,0);
for (int i = 0; i < 511; i++) {
line(i, values[i], (i + 1), values[i + 1]);
}
while (port.available() > 0)
serialEvent(port.read());
stroke(0,128,192);
fill(255);
line(px,0,px,height);
text(values[px],20,10);
}
void serialEvent(int serial) {
//println(serial);
if (serial != NEWLINE) {
// Store all the characters on the line.
buff += char(serial);
} else {
//println(buff);
buff = buff.trim();//sometimes gets strange readings
val = int(buff);
//println(val);//debug
//Could use peak and threshold for a light change trigger
//if (val > peak) peak = val;
// Clear the value of "buff"
buff = "";
// Shift over the existing values to make room for the new one.
for (int i = 0; i < 511; i++) {
values[i] = values[i + 1];
}
// Add the received value to the array.
values[511] = (int)map(val, 0, 30000, 0, 511);//val;
}
}