Automatic lamp (BH1750)
Measure light in lux with a BH1750 and dim a lamp up as the room gets darker, smoothed so it does not flicker.
Sensors · Beginner
In a real product: Smart street light (Energy): Dims up as daylight fades, measured in lux, so the lamp uses only the energy it needs.
A photoresistor tells you "darker" or "lighter"; a BH1750 tells you how much light there is, in lux, already calibrated. That makes thresholds mean something: a desk needs about 300 lx, a corridor 100.
What you'll learn
- Reading a digital light sensor over I²C with its library
- Mapping a measurement onto a PWM output
- Smoothing a reading with an exponential moving average, so the output does not jump
How it works
meter.begin() puts the sensor in continuous high-resolution mode: it measures every 120 ms, at 1 lx a count, and readLightLevel() returns the latest result in lux. Below 400 lx the lamp starts to come on, fully on in the dark.
Raw readings move with every shadow, so the sketch keeps a smoothed value: each new reading moves it a quarter of the way. That is an exponential moving average, the cheapest filter there is: one variable and one line of code.
Try this
- Click the sensor and drag the light down: the LED fades up over about a second.
- Change the smoothing from 0.25 to 0.05: slower, steadier.
- Wire ADDR to 5V and start it with
meter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE, 0x5C).
sketch.ino
// A BH1750 measures the light; the LED on pin 9 brightens as it gets darker, below 400 lx.
#include <Wire.h>
#include <BH1750.h>
BH1750 meter;
const int LAMP = 9;
float smooth = -1;
void setup() {
Serial.begin(9600);
Wire.begin();
if (!meter.begin()) {
Serial.println("No BH1750");
while (true) {}
}
pinMode(LAMP, OUTPUT);
}
void loop() {
if (meter.measurementReady(true)) { // true: wait the longest a measurement can take
float lux = meter.readLightLevel();
smooth = smooth < 0 ? lux : smooth + 0.25 * (lux - smooth);
int level = smooth >= 400 ? 0 : (int)(255 * (400 - smooth) / 400);
analogWrite(LAMP, level);
Serial.print(lux, 1);
Serial.print(" lx, smoothed ");
Serial.print(smooth, 1);
Serial.print(", lamp ");
Serial.println(level);
}
}