Arduino Photoresistor Lighting Control

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

Submitted by Anonymous (not verified) on
hi thanks for all the ideas you have shared in here,am grateful...... I am having a problem sending pwm signals to control my dc motors(2) using photoresistors as when I read analog signals to the arduino its not working coz am working on this project to build a light controlled car,I have tried to do the adc testing of the photocell successfully,ran the dc motors with l293d which works fine but now writing a signal which will make the both motors move forward when the both sensors see light,and move left or right. I just want you to give me assistance on how I will write the code in if I have to map and constrain the light values btw 700 to 1023. I really will appreciate what help you share with me. regards Chris

Submitted by daniel burke (not verified) on
great tutorial i had been on an hour looking for how to hook up one of these for my project which is a bar graph for the light level simple but w/e

Submitted by andrew on

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.

Submitted by ma (not verified) on
Could you please re-upload the hook up picture, it does not work anymore.. thank you!!!

Submitted by akss (not verified) on

Thanks man. This is the best example. It would be even better with code formatting fixed.

Add new comment