Monday, May 23, 2011

Photo Resistor and LEDs

The SuperBlink sketch allowed us to create a number of LED animations/transitions. But it is only a matter of time before you opt for something more interactive. In this tutorial, we will make use of a photo resistor (or light dependent resistor : LDR) to create an exciting LED display.

Photo resistors are variable resistors which change resistance depending on the amount of light hitting the sensor. When you move your hand closer to the sensor, you tend to block an increasing amount of light, which increases the resistance of the photo resistor. As you move your hand away, the amount of light hitting the surface of the photo resistor increases, thus decreasing the resistance.

The change in the resistance of the LDR, will affect the voltage being read at one of the Arduino's Analog Input pins (A0). As resistance increases, the voltage drops (and vice versa).

V = IR

V = Voltage, I = Current, R = Resistance
The voltage reading will be used to select which LED to turn on


The Video





We now have the power to control which LED we want to light up. This would look very nice with different coloured LEDs, but unfortunately I am stuck with the Yellow and Red ones from the Sparkfun Inventor's Kit.

Fritzing Sketch


    Image created using Fritzing : http://fritzing.com



Arduino Code


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* ========================================================
    Project : Photo resistor (Light dependent resistor) and LEDs
     Author : ScottC
    Created : 23rd May 2011
Description : Use a photo resistor to create an LED animation.
============================================================
*/

//Define the analog pin the photo resistor is connected to (A0)
int photoRPin = 0;

void setup() {
    //initialise the LED Pins as OUTPUTS
    for (int i=4; i<14; i++){
      pinMode (i, OUTPUT);
    }
}

void loop(){
    //Turn off all the LEDs before continuing
    for (int i=4; i<14; i++){
      digitalWrite(i, LOW);
    }
    
 /* Read the light level:
     Adjust the analog reading values ranging from 120 to 600
     to span a range of 4 to 13. The analog reading of 120
     is when there is maximum resistance, and the value of 600
     is when there is minimum resistance. These analog readings
     may vary from photo resistor to photo resistor, and therefor
     you may need to adjust these values to suit your particular
     LDR. */
    int photoRead = map(analogRead(photoRPin), 120, 600, 4, 13);
    
    /* Make sure the value of photoRead does not go beyond the values
      of 4 and 13 */
    int ledPin = constrain(photoRead, 4, 13);
    
    /* Turn the LED on for a fraction of a second */
    digitalWrite(ledPin, HIGH);
    delay(10);
    digitalWrite(ledPin, LOW);
}
    



If you liked this tutorial - please support me here:




No comments:

Post a Comment