How to Use LDR with Arduino: Simple Guide and Example
To use an
LDR with Arduino, connect it as a voltage divider with a resistor to an analog input pin, then read the light level using analogRead(). The value changes with light intensity, allowing your Arduino to respond to light conditions.Syntax
Use analogRead(pin) to get the LDR sensor value from the analog pin. The LDR is connected in a voltage divider circuit with a resistor to measure changing resistance as voltage.
pin: The analog input pin number where the LDR is connected.analogRead(): Reads voltage level (0-1023) corresponding to light intensity.
arduino
int sensorValue = analogRead(A0);Example
This example reads the LDR value from analog pin A0 and prints the light level to the Serial Monitor every second.
arduino
void setup() { Serial.begin(9600); // Start serial communication } void loop() { int ldrValue = analogRead(A0); // Read LDR sensor Serial.print("LDR Value: "); Serial.println(ldrValue); // Print value to monitor delay(1000); // Wait 1 second }
Output
LDR Value: 523
LDR Value: 510
LDR Value: 498
... (values change with light)
Common Pitfalls
Common mistakes include:
- Not using a resistor with the LDR, which can damage the Arduino or give wrong readings.
- Connecting the LDR to a digital pin instead of an analog pin.
- Forgetting to set up serial communication before printing.
- Not using a voltage divider circuit, which is necessary to convert resistance changes into readable voltage.
arduino
/* Wrong: LDR connected directly to 5V and analog pin without resistor */ // int ldrValue = analogRead(A0); // May give unstable readings /* Right: LDR connected in voltage divider with 10k resistor */ int ldrValue = analogRead(A0);
Quick Reference
| Component | Connection |
|---|---|
| LDR | One leg to 5V, other leg to analog pin A0 and resistor |
| Resistor (10kΩ) | Between analog pin A0 and GND |
| Arduino Pin | A0 (analog input) |
| Function | analogRead(A0) to read light level |
Key Takeaways
Connect the LDR in a voltage divider circuit with a resistor to an analog pin.
Use analogRead() to get light intensity values from the LDR.
Always include a resistor to protect the Arduino and get stable readings.
Print values via Serial Monitor to observe light changes.
Avoid connecting the LDR directly to digital pins or without a resistor.