Thursday, March 1, 2012

Automatic Light Switch

  • A photocell is connected to the ADC pin A0 with a pull down resistor
  • Pin 13 is connected to a NPN transistor, which drives the high-powered LED.

Covering the photocell turns on a light.

The code (I made from scratch):
int ledPin = 13;
int photoPin = A0;
int photo = 0;
int photo2 = 0;

void setup() {
  pinMode(ledPin, OUTPUT);

void loop() {
  photo = analogRead(photoPin);
  if(photo <= 200){
    photo2 = photo;
    photo = analogRead(photoPin);
    if(abs(photo - photo2) < 50){
      digitalWrite(ledPin, HIGH);
      Serial.print(" ");
    digitalWrite(ledPin, LOW);

  • "photo" is the value of the photocell (ranges from 0 to around 500 in normal ambient light; covering the cell slightly with a hand yields values around 150).
  • If the value ever drops below 200 (or becomes 200), the chip stores the value into another variable. After waiting 3 seconds to eliminate any accidental triggerings, the chip reads the photocell's value again. If the difference between the previous value and the current value is less than 50, the LED turns on.
  • Otherwise, the LED turns off.
  • The commented serial outputs were for determining the range of the photocell's value and debugging.

No comments:

Post a Comment