Wednesday, May 20, 2015

Using sensors


For this project we are going to make a circuit that automatically turns on a light when it is dark.  The starter and budget packs come with a LDR (light dependent resistor) or photoresistor which we will use.  We will be reading an analog input so we will be using two different types of pins; the digital I/O (input/output) pin for the LED and an analog input pin for the LDR.  The analog pins are marked by A# and we will be using A0.
A LDR or photoresistor



There are 4 variables we will use, two to specify pins, one for the value of the LDR and one for the cutoff limit. Since val will be specified in the main loop we do not need to give it an initial value.

int ldr = A0;
int led = 13;
int limit = 800;
int val;


The setup method is identical to the blink code.  Remember all pins are inputs by default so we don't need to specify anything else.

void setup(){


The first thing that we need to do is read the value of the LDR using analogRead() and save it into the variable val.  analogRead will return a value between 0 and 1023.

val = analogRead(ldr);

The way our circuit is set up is the value decreases as the brightness decreases so we need to see if our value is less than the limit and if it is turn the light on, otherwise we need to turn the light off.



The wiring of an LDR is identical to the button, the only difference is the cable is attached to A0 rather than pin 2.  If you light doesn't turn off increase the limit variable in your code.  If it never comes on check your wiring, a value of 500 should be low enough to get the light to come on.  If you want the light to come on when it gets even darker reduce the value for limit.  If you make limit less than 0 the light will never come on but if you make limit greater than 1023 then the light will never go off!

No comments:

Post a Comment