Did You Know? Two-button Control
A pair of pushbuttons can be used to control whether a variable counts up or down. Take a look at the while True loop below:
while True: state9 = pin9.read_digital() state6 = pin6.read_digital() if state9 is 1: index = index + 1 if index > 2: index = 0 if state6 is 1: index = index - 1 if index < 0: index = 2
Each if statement also has a nested if statement that restarts the count when it reaches a certain point. When up-counting, when the index variable reaches 3, it gets changed back to 0. When down-counting, when index reaches -1, it gets changed back to 2.
- Review the LED Lights: Intro to Lists's Script and How It Works sections.
- Think about how you used lists and indexes in Blink Sequencing.
If you guessed that counting up or down might work with lists of pins and times, you are right! In the next Your Turn section, that index value will be used to access the 0, 1, and 2 elements in these pin and time lists (below). When counting up, the index variable will be used to fetch pin13, pin14, and pin15, then repeat again starting with pin13. When counting down, the index variable will be used to fetch pin15, pin14, pin13, pin15, pin14, pin13, and so on.
pin = [pin13, pin14, pin15] time = [200, 200, 200]
Your Turn
With this application, you can hold the P9 pushbutton to make the lights turn on and off in a repeating green-yellow-red pattern. If you instead hold down the P6 pushbutton, the lights turn on and off in a repeating red-yellow-green pattern.
- Enter the buttons_make_leds_rotate script into the micro:bit Python Editor.
- Set the project name field to buttons_make_leds_rotate, then click Save.
- Click Send to micro:bit.
- Verify that the on/off sequence is green-yellow-red-green-yellow-red… while the P9 pushbutton is held down.
- Verify that the on/off sequence is red-yellow-green-red-yellow-green... while the P6 pushbutton is held down.