Here’s the Arduino code that will turn on an LED when you put your finger on the LDR (Light Dependent Resistor). When the light falling on the LDR decreases (due to the shadow of your finger), the resistance increases, and the Arduino will detect a lower light level. The LED will then turn on.
Wiring Setup:
- LDR (Light Dependent Resistor):
- One leg connected to 5V (or 3.3V on the Nano).
- The other leg connected to A0 (Analog pin), and also connected to GND through a 10kΩ resistor (for voltage division).
- LED:
- Anode (long leg) connected to Pin 13 (or any other digital pin).
- Cathode (short leg) connected to GND through a 220Ω resistor.
Arduino Code:
const int ldrPin = A0; // LDR connected to analog pin A0
const int ledPin = 13; // LED connected to digital pin 13
void setup() {
// Start serial communication for debugging
Serial.begin(9600);
// Set LED pin as output
pinMode(ledPin, OUTPUT);
}
void loop() {
// Read the value from the LDR
int ldrValue = analogRead(ldrPin);
// Print the LDR value to the Serial Monitor for debugging
Serial.println(ldrValue);
// If the LDR value is below a certain threshold (indicating less light)
if (ldrValue < 500) { // Adjust the threshold value if necessary
digitalWrite(ledPin, HIGH); // Turn LED on
} else {
digitalWrite(ledPin, LOW); // Turn LED off
}
// Add a small delay to make the response stable
delay(100);
}
Explanation:
- LDR and LED Setup:
- The LDR value will be higher when there’s more light and lower when you cover it (with your finger).
- The threshold value (
500
) in the code is chosen arbitrarily. You can adjust it depending on the sensitivity of your LDR and the amount of light. If you find that it turns on or off too easily, try changing it.
- Threshold Logic:
- When your finger blocks the LDR, the value decreases, and when the LDR is exposed to more light, the value increases.
- When the
ldrValue
goes below the threshold (e.g.,500
), the LED turns on (digitalWrite(ledPin, HIGH);
). - If the LDR value is higher (more light), the LED turns off (
digitalWrite(ledPin, LOW);
).
- Debugging:
- The LDR value is printed to the Serial Monitor so you can observe how the LDR readings change when you cover it with your finger.
Notes:
- Threshold Value: You may need to adjust the threshold value (
500
) based on the type of LDR you are using. You can use the serial monitor to check the LDR values when it is exposed to light and when covered. - Sensitivity: If you find the LED turns on or off too quickly, you can change the threshold value higher or lower.