A simple, but fun, application of the BBC Micro:bit is to build a set of pedestrian traffic lights. You push the button, the lights cycle to red, it goes pip-pip-pip then the lights cycle back to green.
Pin 0 goes to the active piezo buzzer, pins 13, 14, 15 are the G, Y, R LEDs and the "cross" switch is on pin 16. The LEDs have series 330R resistors (the current must be limited to less than 5mA for the micro:bit), and the switch has a pull up resistor of 10k to 3V.
Code
# Traffic lights
# pins 330R-LED-GND: 13 green, 14 yellow, 15 red, 16 switch(10k pull-up, active LOW)
# import the micropython library
from microbit import *
# set period of pin 0 pwm output
pin0.set_analog_period(400)
pin0.write_analog(0)
while True:
# green on
pin13.write_digital(1)
display.show("G")
# wait for switch
if pin16.read_digital() != 1:
# green off, yellow on
pin13.write_digital(0)
pin14.write_digital(1)
display.show("Y")
sleep(2000)
# yellow off, red on, pip-pip-pip
pin14.write_digital(0)
pin15.write_digital(1)
display.show("R")
pin0.write_analog(200)
sleep(8000)
# yellow on, red remains on, pip off
pin14.write_digital(1)
display.show("Y")
pin0.write_analog(0)
sleep(2000)
# red & yellow off
pin14.write_digital(0)
pin15.write_digital(0)
# loop
Press the button to cross the road
No comments:
Post a Comment