Two-button Control


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.  

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 script buttons_make_leds_rotate (python.microbit.org/v/2 matches the screencaptures).
  • Set the Script Name field to buttons_make_leds_rotate.
  • Click Load/Save, and then click Download Project Hex to save your work.  
  • Close the Load/Save dialog box after downloading the .hex file.
  • In the python.microbit.org editor, click Connect, and then click Flash.   
  • 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.