Commit | Line | Data |
---|---|---|
a3a3e374 H |
1 | // |
2 | // This example shows one way of using an LED as a light sensor. | |
3 | // You will need to wire up your components as such: | |
4 | // | |
5 | // + digital2 | |
6 | // | | |
7 | // < | |
8 | // > 100 ohm resistor | |
9 | // < | |
10 | // | | |
11 | // | | |
12 | // ----- | |
13 | // / \ LED, maybe a 5mm, clear plastic is good | |
14 | // ----- | |
15 | // | | |
16 | // | | |
17 | // + digital3 | |
18 | // | |
19 | // What we are going to do is apply a positive voltage at digital2 and | |
20 | // a low voltage at digital3. This is backwards for the LED, current will | |
21 | // not flow and light will not come out, but we will charge up the | |
22 | // capacitance of the LED junction and the Arduino pin. | |
23 | // | |
24 | // Then we are going to disconnect the output drivers from digital2 and | |
25 | // count how long it takes the stored charge to bleed off through the | |
26 | // the LED. The brighter the light, the faster it will bleed away to | |
27 | // digital3. | |
28 | // | |
29 | // Then just to be perverse we will display the brightness back on the | |
30 | // same LED by turning it on for a millisecond. This happens more often | |
31 | // with brighter lighting, so the LED is dim in a dim room and brighter | |
32 | // in a bright room. Quite nice. | |
33 | // | |
34 | // (Though a nice idea, this implementation is flawed because the refresh | |
35 | // rate gets too long in the dark and it flickers disturbingly.) | |
36 | // | |
37 | #define LED_N_SIDE 2 | |
38 | #define LED_P_SIDE 3 | |
39 | ||
40 | void setup() | |
41 | {} | |
42 | ||
43 | void loop() | |
44 | { | |
45 | unsigned int j; | |
46 | ||
47 | // Apply reverse voltage, charge up the pin and led capacitance | |
48 | pinMode(LED_N_SIDE,OUTPUT); | |
49 | pinMode(LED_P_SIDE,OUTPUT); | |
50 | digitalWrite(LED_N_SIDE,HIGH); | |
51 | digitalWrite(LED_P_SIDE,LOW); | |
52 | ||
53 | // Isolate the pin 2 end of the diode | |
54 | pinMode(LED_N_SIDE,INPUT); | |
55 | digitalWrite(LED_N_SIDE,LOW); // turn off internal pull-up resistor | |
56 | ||
57 | // Count how long it takes the diode to bleed back down to a logic zero | |
58 | for ( j = 0; j < 30000; j++) { | |
59 | if ( digitalRead(LED_N_SIDE)==0) break; | |
60 | } | |
61 | // You could use 'j' for something useful, but here we are just using the | |
62 | // delay of the counting. In the dark it counts higher and takes longer, | |
63 | // increasing the portion of the loop where the LED is off compared to | |
64 | // the 1000 microseconds where we turn it on. | |
65 | ||
66 | // Turn the light on for 1000 microseconds | |
67 | digitalWrite(LED_P_SIDE,HIGH); | |
68 | digitalWrite(LED_N_SIDE,LOW); | |
69 | pinMode(LED_P_SIDE,OUTPUT); | |
70 | pinMode(LED_N_SIDE,OUTPUT); | |
71 | delayMicroseconds(1000); | |
72 | // we could turn it off, but we know that is about to happen at the loop() start | |
73 | } |