Photocell
Responding to Light
The Photocell is a variable resistor that changes value based on how much light is shining on it. With this you could invent a simple light intensity meter. You could invent something that turns on lights at night or invent an alarm clock that wakes you up at daylight, an electronic Rooster!
Arduino Code
Sample code to read the light and print to the laptop screen using Serial.print. We read the value at A0 and print it, then we do some maths to convert it to a percentage value and print it again.
float light=0.0; void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println("Hello World"); delay(2000); } void loop() { // put your main code here, to run repeatedly: light=analogRead(A0); Serial.println(light, DEC); light=100*light/1023; //map to 0-100% Serial.println(light, DEC); }
Review
If you need to review Arduino programming and the basic circuits see the digital Electronics Lesson
Move Servo with Light Level
Using the Servo circuit we set up in the Servo Lesson we will make the servo move based on the input light level.
This code should move the servo with light intensity.
#include <Servo.h> Servo myservo; float light=0.0; void setup(){ myservo.attach(9);//connect pin 9 with the control line myservo.write(90);// move servos to center position -> 90° Serial.begin(9600); Serial.println("Set up Complete"); delay(1000); } void loop(){ light=analogRead(A0); light=180*light/1023; Serial.println(light, DEC); myservo.write(light); delay(30); }