micro:bit Night Light: Sun or Moon
The LED display also measures the light around it: in a bright room it shows a sun, and when it gets dark a bright moon appears and works as a night light. display.read_light_level reads the light. No extra parts are needed.

Video
Circuit Diagram

Source Code
1# ─────────────────────────────────────────
2# BlueGrays · bluegrays.com
3# micro:bit Night Light: Sun or Moon
4# ─────────────────────────────────────────
5# The LED display also measures the light around it. In a bright room it
6# shows a sun; when it gets dark a bright moon appears and works as a
7# night light. No extra parts are needed.
8#
9# Pins:
10# LED -> Onboard 5x5 LED display, also senses light
11
12from microbit import *
13
14# ============ SETTINGS ============
15DARK_LEVEL = 40 # Below this counts as dark, 0-255
16CHECK_MS = 500 # Wait between readings (ms)
17
18SUN = Image("90909:09990:99999:09990:90909")
19MOON = Image("09990:99900:99000:99900:09990")
20
21while True:
22 light = display.read_light_level()
23 if light < DARK_LEVEL:
24 display.show(MOON)
25 else:
26 display.show(SUN)
27 sleep(CHECK_MS)
28FAQ
Where is the light sensor?
There is no separate light sensor. LEDs can sense the light falling on them as well as give off light, and the micro:bit uses the LEDs of the display as sensors in short gaps. read_light_level gives a value from 0 (dark) to 255 (very bright).
How do I set the threshold for my room?
Add the line display.scroll(light) to the code for a while and read the numbers with the room lit and with the lights off. Set DARK_LEVEL somewhere between those two numbers. The larger the number, the less dark it has to get before the lamp comes on.
How do I put this code on the micro:bit?
The code is MicroPython. Open the micro:bit Python Editor (python.microbit.org) on a computer, delete the code that is there and paste this one. Connect the board with a USB cable and press Send to micro:bit. If that button does not work, use Save to download the .hex file and copy it to the drive called MICROBIT. You can rebuild the same project with blocks in MakeCode, but this code cannot be pasted there.
Does it work on the older micro:bit (V1) too?
The code is written for the micro:bit V2. Projects that only use the LED display, buttons A and B and the accelerometer also run on a V1. The speaker, the microphone and the touch logo exist only on the V2, so code that uses them gives an error on a V1. If your board has a speaker on the back and a gold logo on the front, it is a V2.
