capteur-lumiere-ldr.ino

Arduino UNO R3 · File : capteur-lumiere-ldr.ino · Language : Arduino · Use case : Mesurer la luminosité avec une LDR et allumer une LED dans le noir

A light-dependent resistor (LDR) wired as a voltage divider on A0 measures ambient light. When the value drops below the threshold, LED 13 turns on: a miniature hallway auto-light.

Hardware

An Arduino Uno R3 (ATmega328P, 5 V, 16 MHz) powered over USB or a 7-12 V barrel jack. 1 LDR (photoresistor) + 1 fixed 10 kΩ resistor + 1 LED + 330 Ω resistor.

Wiring

LDR between 5V and A0, 10 kΩ resistor between A0 and GND (divider). LED + 330 Ω on pin 13 to GND.

How it works

analogRead() converts the divider voltage (0-1023). In the dark the LDR resists a lot, A0 falls toward GND and the value drops. Averaging 8 samples stabilizes the reading.

Running it

In the Arduino IDE, select the « Arduino Uno » board and the matching serial port, then click Upload. Open the serial monitor at 9600 baud to follow the messages.

Variants

Swap the LDR and the resistor for a reading that rises with light, or replace the LED with a relay module to switch real mains lighting.

capteur-lumiere-ldr.ino

// LDR en pont diviseur sur A0 : allumer une LED quand il fait sombre.
const int LDR = A0; // entree analogique 0..1023
const int LED = 13;
const int SEUIL = 500; // 0..1023, a ajuster selon la LDR et la lumiere

unsigned long derniereMesure = 0;

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (millis() - derniereMesure >= 200) { // 5 mesures/s : evite le spam
    derniereMesure = millis();

    // Moyenne de 8 echantillons : filtre le bruit de l'ADC 10 bits.
    long somme = 0;
    for (int i = 0; i < 8; i++) {
      somme += analogRead(LDR);
      delayMicroseconds(100);
    }
    int valeur = somme / 8;

    Serial.print(F("LDR = "));
    Serial.print(valeur);
    if (valeur < SEUIL) {
      digitalWrite(LED, HIGH); // nuit : on eclaire
      Serial.println(F("  -> OBSCURITE"));
    } else {
      digitalWrite(LED, LOW);
      Serial.println(F("  -> jour"));
    }
  }
}

← Back to the board