You’re going to build a smart nightlight using an RGB LED. You are to build on top of the last circuit and replace the LED with an RGB LED to change colors when the night light turns on! Pay close attention to the value of darkness and the logic of the if-else statement.
1 Metro M0 Express
1 breadboard
1 RGB LED
1 Photoresistor
3 Resistors (330 ohms)
1 Resistor (10K ohms)
Wires
Follow the circuit diagram provided to wire the Metro M0 Express.
Note:
For common anode RGB LED, connect the longest leg to 3.3V (instead of ground).
For common cathode RGB LED, connect the longest leg to ground.
import board
import pulseio
import time
import random
from analogio import AnalogIn
led1 = pulseio.PWMOut(board.D5)
led2 = pulseio.PWMOut(board.D4)
led3 = pulseio.PWMOut(board.D3)
lightLevel = AnalogIn(board.A1)
isLedOn = False
lastUpdate = 0
darkness = 10000
changeColorTime = 2
while True:
print((lightLevel.value, ))
time.sleep(0.1)
if (lightLevel.value < darkness):
print("Good Night!")
if (not isLedOn):
led1.duty_cycle = random.randint(20, 55000)
led2.duty_cycle = random.randint(20, 55000)
led3.duty_cycle = random.randint(20, 55000)
isLedOn = True
lastUpdate = time.monotonic()
time.sleep(0.1)
elif (time.monotonic() > lastUpdate + changeColorTime):
led1.duty_cycle = random.randint(20, 55000)
led2.duty_cycle = random.randint(20, 55000)
led3.duty_cycle = random.randint(20, 55000)
isLedOn = True
lastUpdate = time.monotonic()
time.sleep(0.1)
else:
print("Rise and Shine!")
led1.duty_cycle = 20
led2.duty_cycle = 20
led3.duty_cycle = 20
isLedOn = False
time.sleep(0.1)
import board
import pulseio
import time
import random
from analogio import AnalogIn
led1 = pulseio.PWMOut(__________)
led2 = pulseio.PWMOut(__________)
led3 = pulseio.PWMOut(__________)
lightLevel = AnalogIn(__________)
isLedOn = False
lastUpdate = 0
darkness = 10000
changeColorTime = 2
while True:
print((lightLevel.value, ))
time.sleep(0.1)
if (lightLevel.value < darkness):
print("Good Night!")
if (not isLedOn):
led1.duty_cycle = random.randint(20, 55000)
led2.duty_cycle = random.randint(20, 55000)
led3.duty_cycle = random.randint(20, 55000)
isLedOn = __________
lastUpdate = time.monotonic()
time.sleep(0.1)
elif (time.monotonic() > lastUpdate + changeColorTime):
led1.duty_cycle = random.randint(20, 55000)
led2.duty_cycle = random.randint(20, 55000)
led3.duty_cycle = random.randint(20, 55000)
isLedOn = __________
lastUpdate = time.monotonic()
time.sleep(0.1)
else:
print("Rise and Shine!")
led1.duty_cycle = 20
led2.duty_cycle = 20
led3.duty_cycle = 20
isLedOn = __________
time.sleep(0.1)