The same light sensor can report different numbers when turned toward a wall, moved behind a plastic cover, or shaded by its own cable. Before adding automatic room lighting, build a small placement experiment: measure a marked reference position, change one optical condition, then return to the reference. This A–B–A sequence helps separate a placement change from a lamp or daylight change.
Our sensor is the Adafruit BH1750 STEMMA QT breakout, product ID4681, connected to an Espressif ESP32-DevKitC V4 fitted with an ESP32-WROOM-32E module. The complete program uses official MicroPython1.26.0 and raw commands, with no third-party driver. We measure illuminance, light falling on a surface, expressed in lux. A lux reading describes that sensor plane; it is not the lamp’s electrical power, total luminous output or a plant-growth measurement.
Use the exact breakout, not an assumed bare-chip circuit
Adafruit’s PID4681 includes a regulator, level shifting, bus pullups and the BH1750’s support circuit. Its documented VIN accepts3–5V. This build supplies VIN with the ESP32’s3.3V rail and keeps every external bus line at that logic level. The bare ROHM BH1750FVI has a2.4–3.6V operating supply range: the breakout’s5V allowance must never be transferred to a loose chip or an undocumented GY-302 board.
The currently available Adafruit guide links a ROHM-authored November2011 revisionD technical note through a distributor mirror. That is the chip document used here. A current direct ROHM document/lifecycle endpoint was not retrievable in this review, and a targeted manufacturer errata search found no applicable separate sheet. We therefore do not claim that revisionD is the newest possible silicon notice or that every market-labelled BH1750 module is identical. Match the PID4681 board and inspect its actual markings before assembly.
Four wires and a known optical fixture
GPIO means general-purpose input/output: the numbered controller pins used for the bus. USB means Universal Serial Bus, the computer connection carrying power and console data. I²C, Inter-Integrated Circuit, is the two-wire addressable command bus; SDA names serial data and SCL serial clock.
- Espressif ESP32-DevKitC V4/WROOM-32E with MicroPython1.26.0; Adafruit BH1750 PID4681; short labelled jumper wires or a correctly mapped STEMMA QT cable.
- A steady enclosed desk lamp, a non-reflective card with0/30/60/90degree marks, ruler, and a removable clear plastic window coupon. Use an ordinary visible lamp at a comfortable viewing level; direct sunlight readily defeats this small experiment.
- A mount that holds the centre of the sensor’s optical face fixed while its angle changes. Record lamp-to-sensor distance, window gap and the board face that points toward the source.
- A computer for the USB console and a direct-current (DC) voltmeter for checking supply/idle bus levels. An independent lux meter is optional and must be identified if actually used.

| ESP32 board label | PID4681 label | Job |
|---|---|---|
| 3V3 | VIN | One3.3V supply from the USB-powered development board. |
| GND | GND | Common return and signal reference. |
| GPIO21 | SDA | Bidirectional I²C serial data. |
| GPIO22 | SCL | I²C serial clock; the program requests100kHz. |
| No connection | 3Vo,ADDR | Do not join two regulator outputs. Leave the address jumper open for0x23. |
I²C, Inter-Integrated Circuit, lets the controller address the sensor over two signal wires. The seven-bit default address is0x23; pulling ADDR high or closing the board jumper selects0x5C. Our program deliberately uses0x23 and does not silently search for another device. A bus scan can identify an acknowledgement, not establish that the correct light sensor or support circuit is present.
The module already has10kΩ pullups on its external SDA/SCL lines. Each carries approximately3.3/10000=0.33mA when low; additional boards can put pullups in parallel. Do not add another pair reflexively. The published board schematic identifies an AP2112K-3.3 regulator,10µF input/output capacitors,100nF chip bypass and a1kΩ/1µF DVI network. DVI is the chip’s interface-reference/reset input. Leave these assembled support parts alone; a software reset command clears data and does not reproduce every power-up requirement.
Change one thing while holding the centre fixed
First choose an indoor setup without moving daylight patches. Let the lamp reach a repeatable condition, then mark its position and the sensor centre. Route cables behind the sensor so they do not sweep across its view. Keep your hand, screen and body out of the light path when pressing Enter. A shiny white workbench can reflect enough light to spoil a neat angle model.

For the angle run, A is the board facing the lamp. B is30degrees, then60degrees in a separate triplet, then90degrees if the reading remains useful. Rotate about the sensor centre rather than swinging the entire board on a long arm. The latter also changes distance and makes the result ambiguous. Record which axis you rotate: the package and board can have different responses along different axes.
For the window run, keep the angle unchanged and place the coupon at a fixed recorded gap. A has no coupon; B has it installed; A2 removes it again. Do not simultaneously change angle, distance and window. The observed ratio includes reflection, scattering, spectral changes and fixture geometry. It is a result for this coupon, source and orientation, not a universal material-transmission constant.
A nominal lux value and a guarded relative result
The program fixes measurement-time register MTreg=69 and selects one-time high-resolution mode0x20. At these settings its nominal conversion is lux=raw/1.2. The setting matters: changing integration time or selecting high-resolution mode2 changes the conversion. Extra decimal places produced by division do not establish extra optical accuracy.
Each position collects five conversions. Their arithmetic mean is only accepted if all five are useful. Raw65535 is labelled RANGE_LIMIT with no lux estimate; it can be clipped and cannot tell us the actual brightness above that limit. Counts0–3 are labelled DARK_LIMIT, a conservative comparison policy informed by the documented dark output, and also excluded from ratios. This is not a diagnosis of a broken sensor. Keep the reference comfortably above the near-dark region, for example above50 nominal lux, rather than trying to measure window attenuation against a nearly zero baseline.
Let A1 and A2 be the mean reference readings before and after B. We calculate Aref=(A1+A2)/2, drift=|A2−A1|/Aref, then, only when accepted, ratio=B/Aref. Our maximum drift is5%. That is an experiment rule, not a ROHM accuracy specification. A1=400,A2=404 and B=280 nominal lux gives Aref=402, drift≈0.995% and ratio≈0.6965. Those are invented calculation inputs, not measured results.
If A1=400 and A2=460, drift≈13.95% and the program refuses the ratio. Averaging those references cannot prove what happened while B was being measured. Even passing the rule cannot rule out a brief flicker or shade during B, so repeat independent triplets. The same sensor’s gain can cancel partly in a ratio; clipping, offset, angular response and source-spectrum changes do not automatically cancel.
Complete program and command boundaries
Save the file as light_placement.py on the ESP32. Run import light_placement; light_placement.main() from the MicroPython console. The prompts explicitly name A1,B,A2; copy every reported reading and the conditions into the blank sheet. The program is an interactive trial, not a time-stamped unattended logger. Record trial time in the worksheet and start a fresh triplet after an interruption.
For every conversion, the program powers on, clears old data, explicitly programs the high and low MTreg fields, and issues the selected measurement command. Each opcode gets its own STOP-terminated bus transaction, as required by this chip. It waits200ms, beyond the180ms specified maximum at the fixed setting, then reads exactly two bytes. It never relabels an earlier good sample as a new reading after a bus fault.
Download full MicroPython code (ZIP; file: batch-005/code/esp32-bh1750-placement.py) · Blank placement worksheet (ZIP; file: batch-005/code/esp32-bh1750-placement-observations-blank.csv)
"""Adafruit BH1750 PID4681 placement lab; ESP32 MicroPython1.26.0.
One-time H-resolution, MTreg69; no external driver required.
Host injection exercises this same code; not a sensor simulator.
"""
ADDRESS = 0x23
WAIT_MS = 200
MTREG = 69
def decode(raw):
if len(raw) != 2:
raise ValueError("short light read")
count = (raw[0] << 8) | raw[1]
if count == 65535:
return {"state": "RANGE_LIMIT", "raw": count, "lux_nominal": None}
state = "DARK_LIMIT" if count <= 3 else "VALID"
return {"state": state, "raw": count, "lux_nominal": count / 1.2}
class Light:
def __init__(self, bus, sleep_ms):
self.bus = bus
self.sleep_ms = sleep_ms
def command(self, value):
# One opcode per STOP-terminated transaction, as the chip requires.
if self.bus.writeto(ADDRESS, bytes((value,)), stop=True) != 1:
raise OSError("short command acknowledgement")
def measure(self):
self.command(0x01) # Power on; reset is not accepted in power down.
self.command(0x07) # Clear old data; not a complete register reset.
self.command(0x40 | (MTREG >> 5))
self.command(0x60 | (MTREG & 31))
self.command(0x20) # One-time high-resolution mode, not mode2.
self.sleep_ms(WAIT_MS) # >180ms specified maximum at MTreg69.
return decode(self.bus.readfrom(ADDRESS, 2))
def capture(light, label, samples=5):
if label not in ("A1", "B", "A2") or type(samples) is not int or not 1 <= samples <= 20:
raise ValueError("need A1/B/A2 and1..20 samples")
readings = []
try:
for _ in range(samples):
readings.append(light.measure())
light.sleep_ms(50)
except (OSError, ValueError) as error:
return {"label": label, "state": "FAULT", "readings": readings,
"lux_nominal": None, "error": str(error)}
states = [r["state"] for r in readings]
state = "VALID" if all(s == "VALID" for s in states) else "LIMITED"
return {"label": label, "state": state, "readings": readings,
"lux_nominal": (sum(r["lux_nominal"] for r in readings) / samples
if state == "VALID" else None)}
def compare(triplet, drift_limit=0.05):
if not 0 <= drift_limit <= 1:
raise ValueError("drift limit outside0..1")
if len(triplet) != 3 or [r.get("label") for r in triplet] != ["A1", "B", "A2"]:
return {"state": "SEQUENCE_INVALID", "ratio": None}
if any(r.get("state") != "VALID" for r in triplet):
return {"state": "READINGS_INVALID", "ratio": None}
a1, b, a2 = [r.get("lux_nominal") for r in triplet]
if any(type(v) not in (int, float) or not 0 < v < 65535 / 1.2 for v in (a1, b, a2)):
return {"state": "NUMBERS_INVALID", "ratio": None}
baseline = (a1 + a2) / 2
drift = abs(a2 - a1) / baseline
if drift > drift_limit:
return {"state": "BASELINE_MOVED", "ratio": None,
"baseline_lux_nominal": baseline, "relative_drift": drift}
return {"state": "COMPARISON_ACCEPTED", "ratio": b / baseline,
"baseline_lux_nominal": baseline, "relative_drift": drift,
"meaning": "relative placement result for this run, not calibrated transmission"}
def trial(light, ask=input, output=print):
collected = []
instructions = (("A1", "Place bare sensor at marked reference A; keep hands away. Enter:"),
("B", "Change only window OR angle at B, preserving centre/distance. Enter:"),
("A2", "Restore exact reference A, remove window if used. Enter:"))
for label, message in instructions:
ask(message)
row = capture(light, label)
collected.append(row)
output(row)
result = compare(collected)
output(result)
return result
def main():
from machine import Pin, SoftI2C
from time import sleep_ms
bus = SoftI2C(sda=Pin(21), scl=Pin(22), freq=100000, timeout=50000)
light = Light(bus, sleep_ms)
print("FixedMTreg69, one-time H-resolution. A–B–A;5% drift rule is experimental policy.")
try:
while True:
trial(light)
if input("Another triplet? y/N:").lower() != "y":
break
except KeyboardInterrupt:
print("Stopped. Discard incomplete triplet; rerun fromA1.")
if __name__ == "__main__":
main()
Run it, then challenge the interpretation
- Disconnect power, check the exact labels and connect the four wires. Keep3Vo and ADDR open. Power from the ESP32 USB connector only; verify VIN/GND polarity and3.3V idle bus levels.
- Run one unchanged A–B–A triplet, leaving the board at A for all three prompts. The ratio should be examined for repeatability before claiming a placement effect. A ratio near one is an expected hypothesis, not an author-supplied result.
- Perform one angle triplet at a time, restoring the same marked reference before A2. Repeat each angle at least three times and compare the spread, not just one printed ratio.
- Repeat with only the window changed. Record its material, thickness if known, spacing, orientation and surface condition. Do not tune MTreg to force the result to match your expectation.
- For a controlled invalid trial, intentionally change the lamp position before A2 and observe the drift decision. A passing threshold is still not proof of optical stability.
- For an electrical fault, switch off all power, disconnect SDA and restart. Expect FAULT and READINGS_INVALID. Restore wiring with power off and rerun from A1. Do not hot-plug supply leads while other bus wires remain driven.
If RANGE_LIMIT appears, choose a dimmer or more distant ordinary source and repeat the complete geometry. If DARK_LIMIT appears, increase useful illumination. This lesson does not infer ultraviolet exposure, eye safety, irradiance in watts per square metre or photosynthetically active radiation from lux. It also does not prescribe a cosine correction that turns any enclosure into a calibrated lux meter.
What was checked and what still needs the bench
The host tests execute this exact delivered code. They check command bytes and STOP boundaries, two consecutive reconfigurations, failures at every command/read position, short acknowledgements, malformed reads, dark/saturated cases, mean calculation, sequence order, bad numeric inputs, drift rejection and the complete three-prompt trial. They also inject a failure after a successful first capture and verify that it cannot become a valid comparison. The host bus has no photodiode, rise time, regulator dropout or lamp spectrum; those remain real experiments.
Challenge: the window ratio is0.70 under one lamp. Can every later reading simply be divided by0.70?
Only as an explicitly limited correction under conditions you have qualified. A different source spectrum, angle, gap, contamination or near-limit reading may change the relationship. Keep the raw reading and condition record, and validate a correction against repeated independent trials before using it to control a room.
Sources and useful foundations
- Adafruit PID4681 pinouts and downloads, including the manufacturer’s chip document.
- ROHM BH1750FVI November2011 RevD, distributor-hosted manufacturer document: modes, conversion, integration time, command boundaries and power-up limitations.
- Adafruit’s published PID4681 schematic: support components and nets; our diagrams are original functional drawings.
- Espressif DevKitC V4 and MicroPython1.26.0 bus API.
The interactive lessons explain the resistor, capacitor and bus foundations. This placement test is a separate task from a light-threshold controller: first establish what the sensor sees at its final mounting location, then decide what a room-control threshold should mean.



