Timestamped light logger (ESP32-C3)
Log light levels with the time from a DS3231 on an ESP32-C3, and mark each reading dark or light, all on one I²C bus.
Sensors · Intermediate
In a real product: Plant growth monitor (Agriculture): Logs light levels with timestamps to show how much sun a crop gets.
Two I²C chips share two wires: a DS3231 for the time and a BH1750 for the light. Each answers only at its own address, so the ESP32-C3 talks to both over GPIO 8 and 9 with no extra pins. The result is a data logger: one line of comma-separated values every two seconds, ready to paste into a spreadsheet.
What you'll learn
- Two devices on one I²C bus, told apart by address (0x68 and 0x23)
- The ESP32-C3's default I²C pins, and 3.3 V parts on a 3.3 V board
- Logging as CSV with a timestamp from a real-time clock rather than
millis() - A threshold with hysteresis on a measurement in real units (lux)
How it works
Wire.begin() uses the C3's default pins, SDA on GPIO 8 and SCL on GPIO 9. Both modules have their own pull-ups, and both run from the board's 3.3 V. At start-up the sketch sets the clock if its oscillator-stop flag says the time was lost.
Every two seconds the sketch reads the time and the light and prints 2026-10-18 21:00:02,412.5,light. The LED on GPIO 4 is a night light: it comes on below 50 lx and goes off only above 80 lx, so a reading hovering around one value does not make it flicker.
Try this
- Drag the light down below 50 lx, then up to 60: the LED stays on until 80.
- Print only when the state changes, with the time it changed: a log of dusk and dawn.
- Use the DS3231's alarm 2 (minutes) to log once a minute, waking on INT/SQW instead of polling.
sketch.ino
// An ESP32-C3 logging light (BH1750) with the time (DS3231) as CSV, both on I2C (SDA 8, SCL 9). The LED on GPIO 4 is
// a night light: on below 50 lx, off above 80 lx.
#include <Wire.h>
#include <RTClib.h>
#include <BH1750.h>
RTC_DS3231 rtc;
BH1750 meter;
const int NIGHT_LIGHT = 4;
bool dark = false;
void setup() {
Serial.begin(115200);
pinMode(NIGHT_LIGHT, OUTPUT);
Wire.begin();
if (!rtc.begin() || !meter.begin()) {
Serial.println("A sensor is missing");
while (true) delay(1000);
}
if (rtc.lostPower()) rtc.adjust(DateTime(2026, 10, 18, 21, 0, 0));
Serial.println("time,lux,state");
delay(180); // the first measurement takes 120 ms
}
void loop() {
float lux = meter.readLightLevel();
if (!dark && lux < 50) dark = true;
else if (dark && lux > 80) dark = false;
digitalWrite(NIGHT_LIGHT, dark);
char stamp[] = "YYYY-MM-DD hh:mm:ss";
rtc.now().toString(stamp);
Serial.printf("%s,%.1f,%s\n", stamp, lux, dark ? "dark" : "light");
delay(2000);
}