One of the things I've been wanting to do with the Arduino was automatic lighting or run something based on light levels (sunrise, sunset). I grabbed a photoresistor and tried to figure out how I could accomplish this.
First, let's take a look at the hookup. A photoresistor and 1K resistor are hooked up in series. Arduino +5V goes to the photoresistor and ground goes to the 1K resistor. The junction where the photoresistor and the 1K meet is where Arduino pin #5 goes. Here's a picture of the hookup:
Click For Larger Image
Here's the video of everything in action. I also explain in detail what's happening.
Let's take a look at the code. We take an analog reading which can be anywhere between 0 and 1023. I played around with the amount of light in the room and found that 970 was when I would want the light on. The constrain function was used so that only values between 970 and 1023 would be allowed (anything less returns 0). The map function was used to map those values to a PWM value (0 - 255). After that's done we just write to the PWM pin.
Try it out for yourself... it's really quite fun.
int light;
int ledPin = 11;
int photoresistor = 5;
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop()
{
light = analogRead(photoresistor);
light = constrain(light, 990, 1023);
light = map(light, 990, 1023, 0, 255);
analogWrite(ledPin, light);
Serial.println(light);
}
Comments
hi thanks for all the ideas
great tutorial i had been on
I'm not exactly sure what you
I'm not exactly sure what you mean by contraining values. A simple if statement should do the job. That being said, try breaking the project down into 2 parts (light sensor and motors), get them both working and than combine them.
Could you please re-upload
Sorry about that. It should
Thanks man. This is the best
Thanks man. This is the best example. It would be even better with code formatting fixed.
Thanks for pointing that out.
Add new comment