Lux night lamp on an Arduino Uno
A BH1750 light meter on I2C and an LED on a PWM pin: the darker the room, the brighter the lamp, with the reading in lux on the serial monitor. The whole build, an Arduino Uno and 3 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
BeginnerRuns in your browser. Free, and no account needed.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Lux night lamp: a BH1750 light meter on I2C, and an LED that gets brighter
// as the room gets darker.
//
// A4, A5 SDA and SCL to the BH1750 (GY-302 module, address 0x23)
// pin 9 through 220 ohm to the LED's anode; its cathode to GND
// 5V/GND the module (it has its own 3.3 V regulator and pull-ups)
//
// An LDR in a divider gives a number that depends on the resistor and the
// cell. The BH1750 gives lux: its count is the light times 1.2, so the
// library's readLightLevel() is count / 1.2 and nothing else. A classroom is
// a few hundred lux, a cloudy day outdoors a few thousand, full sun past the
// 54612 the chip can count to.
//
// # The lamp
//
// Under 20 lux the lamp is full on; over 500 it is off; in between it fades,
// in whole numbers:
//
// brightness = 255 x (500 - lux) / 480
//
// readLightLevelCentis() gives the lux in hundredths, because this board has
// no floating point to do the sum with.
#include <Wire.h>
#include <BH1750.h>
const int LAMP = 9;
const long DARK = 20;
const long BRIGHT = 500;
BH1750 lightMeter;
void setup() {
Serial.begin(115200);
Serial.println("Mokxi Arduino Uno: BH1750 lux night lamp");
Wire.begin();
if (!lightMeter.begin()) {
Serial.println("no BH1750: check SDA, SCL and power");
}
pinMode(LAMP, OUTPUT);
}
void loop() {
if (lightMeter.measurementReady()) {
long lux = lightMeter.readLightLevelCentis() / 100;
int level;
if (lux <= DARK) {
level = 255;
} else if (lux >= BRIGHT) {
level = 0;
} else {
level = (int)(255 * (BRIGHT - lux) / (BRIGHT - DARK));
}
analogWrite(LAMP, level);
Serial.print("light ");
Serial.print(lux);
Serial.print(" lx lamp ");
Serial.println(level);
}
delay(200);
}
Parts list
5 parts, plus the jumper wires. Every one is in the editor's parts bin.
- 1 × Arduino Uno R3
- 1 × Full-size breadboard
- 1 × Light sensor, BH1750
- 1 × Resistor, 220 Ω
- 1 × LED, yellow
How it is wired
6 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Arduino Uno R3 pin SCL; Light sensor, BH1750 pin SCL
- Arduino Uno R3 pin SDA; Light sensor, BH1750 pin SDA
- Arduino Uno R3 pin 9; Resistor, 220 Ω pin 1
- Arduino Uno R3 pin 5V; Light sensor, BH1750 pin VCC
- Ground: Arduino Uno R3 pin GND; Light sensor, BH1750 pin GND; LED, yellow pin C
- Resistor, 220 Ω pin 2; LED, yellow pin A
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.