jump to navigation

Light Sensor Circuit Code with Arduino May 20, 2010

Posted by Tom Frobish in Physical Computing.

Alrighty, so I’m finally posting the code I made for the light sensor circuit.  If you can read C++ then the schematic is basically posted in the code.  Essentially, the code just reads the resistance from the photo resistor and depending on the range, it’ll light up the corresponding light.  To help with a smoother transistion between the reads, I also told the arduino to smooth the data meaning it’ll take the average of every 10 samples.

I will make this is the summer and link the vid on here from youtube since I can’t post videos on this blog.

If you want to make a light sensor, here’s the code to do it (All you’d need to do is change the “if” “else” values to calibrate the sensor):

const int numReadings = 10;
const int ledPin = 13;
const int ledBlue = 5;
const int ledYellow = 4;
const int ledGreen = 3;
const int ledOrange = 2;
const int ledRed = 8;
int readings[numReadings];
int index = 0;
int total = 0;
int average = 0;
int inputPin = 0;
void setup()
{ Serial.begin(9600);
for (int thisReading = 0; thisReading <numReadings; thisReading++)
readings[thisReading] = 0;
pinMode(ledPin, OUTPUT);
pinMode(ledBlue, OUTPUT);
pinMode(ledYellow, OUTPUT);
pinMode(ledGreen, OUTPUT);
pinMode(ledOrange, OUTPUT);
pinMode(ledRed, OUTPUT);
pinMode(inputPin, INPUT);
void loop() {
total= total – readings[index];
readings[index] = analogRead(inputPin);
total= total + readings[index];
index = index +1;
if (index >= numReadings)
index = 0;
average = total / numReadings;
Serial.println(average, DEC);
if (average < 506)
{digitalWrite(ledRed, LOW);}
else {digitalWrite(ledRed, HIGH);}
if (average < 489 || average >= 506)
{digitalWrite(ledOrange, LOW);}
else {digitalWrite(ledOrange, HIGH);}
if (average < 472 || average >= 489)
{digitalWrite(ledYellow, LOW);}
else {digitalWrite(ledYellow, HIGH);}
if (average < 455 || average >= 472)
{digitalWrite(ledGreen, LOW);}
else {digitalWrite(ledGreen, HIGH);}
if (average < 438 || average >= 455)
{digitalWrite(ledBlue, LOW);}
else {digitalWrite(ledBlue, HIGH);}
if (average < 421 || average >= 438)
{digitalWrite(ledPin, LOW);}
else {digitalWrite(ledPin, HIGH);}


No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: