Mini Project: Light switch
Objective
The goal is to use the button as an on/off switch for the LED. Press the button, and the LED turns on (LED should STAY on until button pressed again). Press the button again, and the LED turns off (STAYS off).
Components
1 Metro M0 Express
1 breadboard
7 wires
2 resistors (330 ohms)
1 LED light
1 push button
Concepts
Wiring
We are going to be using the same circuit as we did in the Button and LED exercise. The diagrams are provided again here for reference.
4 pin push button
2 pin push button
Coding/Programming
import board
from digitalio import DigitalInOut, Direction, Pull
import time
led = DigitalInOut(__________)
button = DigitalInOut(__________)
led.direction = Direction.__________
button.direction = Direction.__________
button.pull = Pull.UP #Pull: defines the pull of a digital input pin
buttonState = False
ledState = False
while True:
buttonState = button.value
if buttonState and ledState:
#button is pressed and led is currently on
led.value = __________
ledState = __________
elif buttonState and not ledState:
#button is pressed and led is currently off
led.value = __________
ledState = __________
time.sleep(0.01)
Solution
import board
from digitalio import DigitalInOut, Direction, Pull
import time
led = DigitalInOut(board.D13)
button = DigitalInOut(board.D2)
led.direction = Direction.OUTPUT
button.direction = Direction.INPUT
button.pull = Pull.UP #Pull: defines the pull of a digital input pin
buttonState = False
ledState = False
while True:
buttonState = button.value
if buttonState and ledState:
#button is pressed and led is currently on
led.value = False
ledState = False
elif buttonState and not ledState:
#button is pressed and led is currently off
led.value = True
ledState = True
time.sleep(0.01)