LilyPad Light Sensor V2 Hookup Guide

Pages
Contributors: Gella
Favorited Favorite 2

Using Values to Trigger Behaviors

Next, we'll make some decisions in the code based on the light sensor's readings. This example code creates a simple automatic night light that turns on an LED when it’s dark.

We'll use the analogRead() function to get data from the light sensor and compare it to a variable we set for darkness level. When the readings from the light sensor fall below our threshold set for dark, it will turn on the LED.

You can hook up a LilyPad LED to sew tab 5 or use the built-in LED attached to pin 13.

language:c
/******************************************************************************

LilyPad Light Sensor Trigger - Automatic Night Light
SparkFun Electronics

Adapted from Digital Sandbox Experiment 11: Automatic Night Light

This example code reads the input from a LilyPad Light Sensor compares it to
a set threshold named 'dark'. If the light reading is below the threshold,
an LED will turn on.

Light Sensor connections:
   * S tab to A2
   * + tab to +
   * - to -

Connect an LED to pin 5 or use the built-in LED on pin 13

******************************************************************************/
// The dark variable determines when we turn the LEDs on or off. 
// Set higher or lower to adjust sensitivity.
const int darkLevel = 50;

// Create a variable to hold the readings from the light sensor.
int lightValue;

// Set which pin the Signal output from the light sensor is connected to
int sensorPin = A2;

// Set which pin the LED is connected to. 
// Set to 5 if you'd rather hook up your own LED to the LilyPad Arduino.
int ledPin = 13;

void setup()
{
    // Set sensorPin as an INPUT
    pinMode(sensorPin, INPUT);

    // Set LED as outputs
    pinMode(ledPin, OUTPUT);

    // Initialize Serial, set the baud rate to 9600 bps.
    Serial.begin(9600);
}

void loop()
{
    // Read the light sensor's value and store in 'lightValue'
    lightValue = analogRead(sensorPin);

    // Print some descriptive text and then the value from the sensor
    Serial.print("Light value is:");
    Serial.println(lightValue);

    // Compare "lightValue" to the "dark" variable
    if (lightValue <= darkLevel) // If the reading is less then 'darkLevel'
    {
        digitalWrite(ledPin, HIGH); // Turn on LED
    }
    else // Otherwise, if "lightValue" is greater than "dark"
    {
        digitalWrite(ledPin, LOW);  // Turn off LED
    }

    // Delay so that the text doesn't scroll to fast on the Serial Monitor. 
    // Adjust to a larger number for a slower scroll.
    delay(100);
}

If your light sensor isn't triggering correctly, check the output of the Serial Monitor to see if there's a better value for the dark variable than what is set in the example code.