🛠 Thermomètre de lumière : LDR, seuils et hystérésis
Objectives
Set up a real analog sensor (LDR photoresistor in a voltage divider), calibrate a threshold in real-world conditions using the Serial Monitor, and avoid oscillation around the threshold thanks to hysteresis. Intermediate level: moving from "reading" to "interpreting".
Hardware
- 1 Arduino UNO R3 + USB-B cable
- 1 LDR + 1 10 kΩ resistor (voltage divider: 5 V — LDR — A1 — 10 kΩ — GND)
- 1 LED + 330 Ω on pin 12 (darkness indicator)
- A variable light source (desk lamp) for calibration.
Complete code
// LDR sur A1 (pont diviseur avec 10 k), LED témoin sur pin 12.
const uint8_t LDR = A1;
const uint8_t TEMOIN = 12;
// Hystérésis : deux seuils distincts pour éviter le clignotement.
const int SEUIL_OBSCURITE = 300; // en dessous : nuit
const int SEUIL_JOUR = 400; // au-dessus : jour
bool nuit = false;
void setup {
pinMode(TEMOIN, OUTPUT);
Serial.begin(115200);
}
void loop {
int v = analogRead(LDR); // 0 = noir, 1023 = pleine lumière (selon montage)
if (!nuit && v < SEUIL_OBSCURITE) {
nuit = true;
Serial.print(F("Nuit -> ")); Serial.println(v);
} else if (nuit && v > SEUIL_JOUR) {
nuit = false;
Serial.print(F("Jour -> ")); Serial.println(v);
}
digitalWrite(TEMOIN, nuit ? HIGH : LOW);
Serial.print(F("ldr=")); Serial.println(v);
delay(100);
}
Expected verification
The Serial Monitor (115200) displays a stable value that increases when you bring the lamp closer and decreases when you cover the LDR with your hand. The indicator LED turns on below ~300 and only turns off above ~400: between the two, no state change — hysteresis is working.
Common errors
- Voltage divider wired backwards (10 kΩ on top, LDR on bottom): the logic is inverted, thresholds "don't work" — always calibrate by looking at the actual values first.
- A single threshold without hysteresis: the LED flickers constantly when light levels hover near the threshold (ADC noise ±5 units).
- Forgetting F for Serial.print strings: each literal consumes the precious 2 KB of SRAM on the ATmega328P.
- delay(100) too long: you miss fast transitions; too short, you flood the Monitor.
- LDR without a fixed resistor: connecting the LDR alone between A1 and 5 V never yields 0, the divider is essential.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-poussoir.inoArduinopwm-fade.inoArduinocapteur-lumiere-ldr.inoArduinoservo-balayage.inoArduinoruban-neopixel.inoArduino