Ambient Light and Automatic Lighting Control
Ambient Light and Automatic Lighting Control
Overview
Section titled “Overview”“Switch the lights on when it gets dark” sounds trivial, yet field failures almost never come from the light sensor — they come from thresholds and the load-side circuit. By the end of this section you will be able to:
- Weigh photoresistors (LDR) against digital lux sensors (BH1750 class) in terms of cost and, more importantly, deliverability
- Design light control logic with hysteresis and time confirmation, eliminating chatter at the threshold
- Isolate the sensing side from the lamp load, and define what the lamps should do when the sensor fails
- Build a calibration and acceptance method that ships as documentation, instead of trimming potentiometers on site
Prerequisites
Section titled “Prerequisites”Before starting this section, make sure you:
- Completed Sections 2 and 3 of Chapter 25
- Have an LDR module (AO/DO) or a BH1750 module
- Have a reference lux meter (if not, do relative two-point comparison in one fixed position; a phone app is not a calibration reference)
Key Concepts
Section titled “Key Concepts”The difference is not price, it is whether you must calibrate
Section titled “The difference is not price, it is whether you must calibrate”| Aspect | LDR photoresistor | BH1750-class digital part |
|---|---|---|
| Interface | Analogue, needs a divider into ADC | I2C, returns lux directly |
| Output quantity | Resistance/voltage — not illuminance | lux (typically 1–65535 lx) |
| Linearity | Poor; resistance varies roughly logarithmically | Handled internally, close to linear |
| Calibration effort | Needs a mapping against a lux meter, or fixed thresholds | Factory calibrated |
| Unit-to-unit consistency | Visible batch spread and ageing | Small batch spread |
| Spectral response | Roughly photopic but skewed (more sensitive to red) | Corrected towards the human eye |
| Cost | Lowest | Medium and usually still acceptable |
My rule: whenever the behaviour is customer-visible (when the lights come on), choose the digital lux part. LDR suits teaching demos and internal informational alerts. The reason is not accuracy but deliverability — a lux figure can go into an acceptance document; a raw ADC count cannot.
Using an LDR correctly
Section titled “Using an LDR correctly”- Typical parts (GL5528 class) sit in the tens of kΩ under indoor light and can exceed 1 MΩ in darkness; use the manufacturer’s curve for your exact part
- Divider orientation defines the sign of the response: LDR in the upper leg means “brighter = larger reading”; in the lower leg it is inverted. Write it into the wiring sheet
- The fixed resistor sets where sensitivity concentrates: to make the dusk-to-night band most responsive, choose a fixed resistor near the LDR resistance at that illuminance
- In darkness the node is very high impedance and picks up noise — add 100 nF to ground before the pin, or use a digital part
Using a BH1750 correctly
Section titled “Using a BH1750 correctly”- Common I2C address 0x23; scan the bus first to confirm it is reachable
- Measurement modes include continuous/single and high/low resolution; high-resolution mode is about 1 lx with a ceiling at 65535 lx
- Orientation and obstruction dominate the error: when mounted inside an enclosure, the light inlet’s size, position and enclosure colour can introduce errors of several times, so calibration must happen in the final assembly, not on a breakout board
- Direct sunlight saturates the range; if you must distinguish “clear noon” from “overcast noon”, move to a diffused position or a higher-range device
Light control is really about not bouncing back
Section titled “Light control is really about not bouncing back”A single threshold will oscillate near the trip point: the lamp turns on, its own light falls back on the sensor, the condition clears, the lamp turns off — repeat forever. Three measures are mandatory:
- Hysteresis: separate turn-on and turn-off points, e.g. on below 30 lx, off above 80 lx
- Time confirmation: the condition must hold continuously for some seconds, rejecting car headlights, lightning and a passing person
- Minimum switching interval: a guard time between transitions (e.g. 30 s), protecting both the lamp/relay lifetime and the logic
These are not optional. The most common light-control complaint at acceptance — “the lights flicker at dusk” — always traces back to one or more of these three being missing.
Keep the sensor side and the load side apart
Section titled “Keep the sensor side and the load side apart”The load is a lamp, switched via relay, contactor or TRIAC on the mains side, and none of that interference belongs near the sensor:
- Drive lamps through a relay or MOSFET, with an independent supply, common ground, and separate routing
- Add flyback and snubber protection for inductive loads (ballasts, motors); with TRIACs watch zero-cross switching and heat dissipation
- If sensor supply and lamp supply are separate domains, record that in the wiring sheet as power domains
- Safety boundary: a manual override must always remain available for automatic lighting — a basic maintenance and evacuation requirement
Define the fail-safe state
Section titled “Define the fail-safe state”What should the lamps do when the sensor fails, the value sticks, or the bus goes silent? The application decides, and it must be documented:
| Application | Suggested fail-safe | Reasoning |
|---|---|---|
| Escape routes / stairwell lighting | Stay lit on failure | Safety first, tolerate the energy cost |
| Grow lights / greenhouse | Stay off on failure | Wrong extra light disrupts crop cycles |
| Advertising and display cases | Keep last state, or off | Balance energy and safety |
| Machine station lighting | Stay lit and raise an alarm | Prevents operator mistakes |
In firmware this becomes watchdog logic: when sensor_status=fail exceeds a configured time, drive the output into the predefined state and report.
Implementation
Section titled “Implementation”LDR divider reading and resistance conversion
Section titled “LDR divider reading and resistance conversion”const uint8_t LDR_PIN = 35; // ADC1const float R_FIXED = 10000.0f; // LDR in the lower leg, 10 kΩ upperconst float V_DIV = 3.28f; // measured supply voltage
float ldrResistance() { float v = analogRead(LDR_PIN) * V_DIV / 4095.0f; if (v <= 0.01f) return 1e9f; // darkness: effectively open if (v >= V_DIV - 0.01f) return 1.0f; // extreme light: effectively short return R_FIXED * v / (V_DIV - v); // device in the lower leg}An LDR only gives relative quantities: for threshold control, measure the “lights on” and “lights off” resistance points on the final assembly, store them as code constants, and note the measurement date and conditions in a comment.
Light-control state machine with hysteresis and time confirmation
Section titled “Light-control state machine with hysteresis and time confirmation”enum LightState { LIGHT_OFF, LIGHT_ON };
const uint16_t LX_TURN_ON = 30; // turn on below this (calibrated on the assembly)const uint16_t LX_TURN_OFF = 80; // turn off above this, creating hysteresisconst unsigned long CONFIRM_MS = 15000; // condition must hold 15 sconst unsigned long MIN_GAP_MS = 30000; // minimum interval between switches
LightState state = LIGHT_OFF;unsigned long conditionSinceMs = 0; // 0 means the condition is not currently metunsigned long lastSwitchMs = 0;
void updateLighting(uint16_t lux, bool luxValid) { if (!luxValid) { // sensor failed: apply the predefined fail-safe if (millis() - lastSwitchMs > 60000) { state = (state == LIGHT_ON) ? LIGHT_OFF : LIGHT_ON; setLamp(state == LIGHT_ON); lastSwitchMs = millis(); conditionSinceMs = 0; reportFault("lux sensor invalid, fail-safe applied"); } return; }
// What must hold to switch depends on the current state: // lit → is it bright enough to justify switching off; off → is it dark enough to switch on bool satisfied = (state == LIGHT_ON) ? (lux >= LX_TURN_OFF) : (lux <= LX_TURN_ON);
if (!satisfied) { conditionSinceMs = 0; return; } // condition broke: restart timing if (conditionSinceMs == 0) conditionSinceMs = millis(); // first satisfied sample
bool heldLongEnough = millis() - conditionSinceMs >= CONFIRM_MS; bool gapElapsed = millis() - lastSwitchMs >= MIN_GAP_MS;
if (heldLongEnough && gapElapsed) { state = (state == LIGHT_ON) ? LIGHT_OFF : LIGHT_ON; setLamp(state == LIGHT_ON); lastSwitchMs = millis(); conditionSinceMs = 0; }}The three ideas are deliberately separated: threshold depends on state, hold-time accumulates in conditionSinceMs, and the guard interval is enforced by lastSwitchMs. Note that all time values are unsigned long holding millis() — never store a timestamp in uint16_t; it wraps after 65 seconds and is the sneakiest bug class in state machines like this.
BH1750 reading with validity
Section titled “BH1750 reading with validity”#include <BH1750.h>#include <Wire.h>
BH1750 lightMeter;float lastLux = NAN;
void setup() { Wire.begin(); if (lightMeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) { Serial.println("BH1750 ready"); } else { Serial.println("BH1750 not found (check 0x23 and pull-ups)"); }}
void sampleLux() { float lux = lightMeter.readLightLevel(); // most implementations return -1 or NaN on failure if (lux < 0 || isnan(lux)) { lastLux = NAN; return; } // invalid: hand it to the fail-safe layer lastLux = lux;}BH1750 library APIs vary slightly between implementations (readLightLevel() is the common one); adjust that line to your library’s header if the build fails. The validity rule never changes: invalid readings become NAN — do not keep propagating the last good lux value.
Verification
Section titled “Verification”Sensing and calibration checks
Section titled “Sensing and calibration checks”| Check | Expected result | Verified |
|---|---|---|
| Turn-on / turn-off points measured on the final assembly | Two lux values (or two LDR resistances) recorded and coded in | |
| Vary light around the threshold | No lamp flicker (hysteresis and confirmation working) | |
| Sweep a torch / car headlight past it | No switch (15 s confirmation holds) | |
| Cover then uncover | Switch timing matches the calibration, no cumulative drift | |
| Disconnect the sensor (unplug or wrong I2C address) | Fail-safe state applied and reported, not “carry on as before” | |
| 72 h continuous run | No false actions; no night flicker |
Load-side and safety checks
Section titled “Load-side and safety checks”| Check | Expected result | Verified |
|---|---|---|
| Manual override | Always overrides automatic control | |
| 100 load switching cycles | No relay contact welding, no controller resets | |
| Shared rail versus separate rail comparison | Controller stays up with a separate rail (proving power domain split is needed) | |
| Reset with the load disconnected | Boots into the predefined state, not a random one |
Troubleshooting
Section titled “Troubleshooting”Issue 1: lights flicker at dusk
Section titled “Issue 1: lights flicker at dusk”Symptoms: a few seconds of on/off while ambient light sits near the threshold.
Causes: single threshold; lamp light falling back onto the sensor; no time confirmation.
Solutions:
- Add hysteresis (e.g. on at 30 lx, off at 80 lx) and reposition the sensor out of the lamp’s direct light
- Add time confirmation and a minimum switching interval
- If lamp reflection cannot be avoided, widen hysteresis to at least 1.5 × the measured on/off delta
Issue 2: lights on in daytime, or not on at night
Section titled “Issue 2: lights on in daytime, or not on at night”Symptoms: the whole trip point has shifted.
Possible causes: dust or aged enclosure shading the sensor; LDR ageing; calibration performed on a bare breakout board while the assembled optics differ.
Solutions:
- Calibrate on the final assembly, documenting the optical path, inlet size and calibration conditions
- Recalibrate periodically (especially outdoors and in dusty sites), storing calibration dates in firmware
- Add a “baseline drifting low” alarm to prompt cleaning or replacement
Issue 3: the value never changes
Section titled “Issue 3: the value never changes”Symptoms: constant reading; covering the sensor does nothing.
Possible causes: I2C address conflict or insufficient pull-ups (first read succeeds, then nothing updates); LDR pin is not an ADC channel or sits on ADC2; stale cached value in software.
Solutions:
- Scan the bus to confirm the device is present; power-cycle to see whether it recovers, indicating a stuck bus
- Check pull-ups (around 4.7 kΩ for I2C) and bus length
- Move ADC sampling to ADC1 and A/B test with Wi-Fi disabled
Issue 4: lighting works but the controller reboots occasionally
Section titled “Issue 4: lighting works but the controller reboots occasionally”Symptoms: reset messages appear right when the lamp switches.
Cause: load switching drags the rail down, or TRIAC/relay interference couples into the sensor and controller side.
Solutions:
- Separate supply rails for load and controller, tied by common ground, with local decoupling on the load
- Flyback diode across relay coils; check zero-cross and RC snubber on TRIAC designs
- Route signal wiring away from mains wiring; add opto-isolation where needed
Best Practices
Section titled “Best Practices”- Do: choose a digital lux part whenever the action is customer-visible, and put lux figures into the acceptance document
- Do: require hysteresis + time confirmation + minimum switching interval in every light-control design
- Do: calibrate on the finished assembly and document the optical path, inlet dimensions, date and environment
- Do: define the fail-safe state and keep a manual override — both are deliverables, not extras
- Don’t: use a phone lux app as the calibration reference
- Don’t: place the sensor where it can see the lamp it controls
- Don’t: feed lamp loads and the controller from the same thin supply run
Summary
Section titled “Summary”Key points of this section:
- LDR gives relative values, digital parts give lux — the difference is what you can put in an acceptance document
- Calibrate in the final assembly; a breakout-board threshold does not transfer
- Three mandatory measures for stable light control: hysteresis, time confirmation, minimum switching interval; missing one produces “flicker at dusk”
- Isolate sensor side from load side and always keep a manual override
- Define the fail-safe state up front —
sensor_status=failmust cause an action, not reuse of stale values
Next section: proximity and presence — what reflective IR, PIR and mmWave radar can each see, and what none of them can.
We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.
💡 Mention tutorial.imagrove.com in your Alibaba chat with us — get 10% off your custom project quote.
First published attutorial.imagrove.com/sensor-module-selection/09-ambient-light-and-automatic-lighting-control/Please credit Imagrove and link back to this page when quoting or republishing.
Questions or issues with this tutorial?
Sign in with GitHub to leave a comment. If a step fails for you, tell us — we verify it and update the tutorial.
© Imagrove · ESP32 IoT Tutorial