I'm trying to use an LDR to control an LED. I've successfully created an pushbutton-controlled LED, as shown in Example 02 of Getting Started with Arduino. Here's the code:
#define LED 13
#define BUTTON 7
int val = 0;
int old_val = 0;
int state = 0;
void setup()
{
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT);
}
void loop()
{
val = digitalRead(BUTTON);
if ((val == HIGH) && (old_val == LOW)) {
state = 1-state;
delay(50);
}
old_val = val;
if (state == 1) {
digitalWrite(LED, HIGH);
} else {
digitalWrite(LED, LOW);
}
}
But when I replace the pushbutton with an LDR, the LED stays on constantly, and it doesn't matter if I cover the LDR. A photo of my configuration is attached. Can anybody help me make the LDR control the LED?
It might be that the LDR is never closed circuit.... use your multi-meter to check its resistance in full light and full dark. It could be that it's not "as closed" or "as open" as a switch, which is obviously a closed circuit when pressed and open circuit when not. So you night not be getting crisp ons and offs here, in a digital sense. Try it on an analog pin and then you can set the threshold between "light" and "dark" anywhere between 0 and 1023.
That's just off the top of my head.... off to work now, early morning here.
BTW1: Curious as to why you have an external LED on pin 13 to ground when the board has one built in, especially since it doesn't seem to have a current limiting resistor in series.
BTW2: As well as the photo, it's an idea to post a schematic of the circuit?- and / or a Fritzing pic.
Thanks. I'm working from the Getting Started with Arduino kit, so I don't have a multi-meter. Can you recommend a workaround? Or, could you recommend an inexpensive, beginner friendly multi-meter?
Re BTW1: I'm just trying to following the instructions line-by-line in Getting Started with Arduino.