Adding a light sensor

From SquidBee

Jump to: navigation, search

Reading a light sensor

LDR sensor

A light sensor (LDR or Light Dependent Resistor) is a simple component that provides a variable resistance that changes with light, which we can read into the Arduino board as an analog value. In this example, that value controls the rate at which an LED blinks.

Material nedeed:

Arduino board
LDR
1 kohm resistor
Breadboard
3 cables
1 led connected to pin 13 in Arduino (if your Arduino board doesn't have it already)

We connect three wires to the Arduino board. The first goes to ground from one of the pins of the LDR. The second goes from 5 volts to one of the pins of the 1 kohm resistor, the other pin of the resistor goes to the free pin in the LDR. The third goes from analog input 2 to the LDR pin that is connected to the resistor.

analog sensor connection
analog sensor connection





By changing the amount of light in the LDR, we change the amount of resistance on the LDR, witch changes the voltage value, giving us a different analog input. We'll read different values between 0 (for 0V) and 1023 (for 5V).










Code

 
/* Light sensor
 * ------------------ 
 *
 * turns on and off a light emitting diode(LED) connected to digital  
 * pin 13. The amount of time the LED will be on and off depends on
 * the value obtained by analogRead() that is depending of the amount
 * of light in the LDR
 *
 */

int LDR = 2;       // select the input pin for the LDR
int ledPin = 13;   // select the pin for the LED
int val = 0;       // variable to store the value coming from the sensor

void setup() {
  pinMode(LDR, INPUT);       // declare the LDR as an INPUT
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
}

void loop() {
  val = analogRead(LDR);       // read the value from the sensor
  digitalWrite(ledPin, HIGH);  // turn the ledPin on
  delay(val);                  // stop the program for some time
  digitalWrite(ledPin, LOW);   // turn the ledPin off
  delay(val);                  // stop the program for some time
}
Personal tools