Jython
Deutsch   English 

4. Interactive Programs using Buttons


The micro:bit has two programmable buttons, which make it possible to interact with the program execution.

The left one is referenced by button_a, the right one by button_b.

The function button_a.is_pressed() returns True if the left button is pressed at the moment of the call (analog for button_b_is pressed()).
 

Example 1: Responding to pressing a button
The program waits in an endless loop until button A or button B is pressed. Then the right or left LED starts flashing with a period of 1s as long as the button is hold down.

# Mr4a.py
from microbit import *
from mbrobot import *
#from mbrobot_plusV2 import *

def blink():
    setLED(1)
    delay(500)
    setLED(0)   
    delay(500)

while True:
    if button_a.is_pressed():
        blink()    
    delay(100) 
► Copy to clipboard
 

Explanations of the program code:

def blink(led): It makes sense to write a function for the flashing of an LED and then to call it with the parameter leftLED or rightLED
if button_a.is_pressed() Returns True while the button is pressed


Example 2: Responding to the click of a button
In an endless while loop you flash the right and left LED with a period of 1 s.. A click on the button A or B interrupts the blinking and a sound is played.

Since the program spends most of the time in the blink function, it cannot notice if you press and release the button during this time. To capture a click in spite of that, you have to use the function button_a.was_pressed(). This function returns True if the button has been clicked any time since the last call. The click is detected as an event, which is registered by the system even if the program is doing something else.

# Mr4b.py
from microbit import *
from mbrobot import *
from music import *

def blink():
    ledLeft.write_digital(1)
    ledRight.write_digital(1)
    delay(500)
    ledLeft.write_digital(0)
    ledRight.write_digital(0)
    delay(500)

while True:
    if button_a.was_pressed():
        play(JUMP_UP)
    if button_b.was_pressed():
        play(JUMP_DOWN)    
    blink()
► Copy to clipboard
 

Explanations of the program code:

if button_a.was_pressed() Returns True if the button has been pressed since the last call.
from music import *: Imports the module music to play sounds
play(JUMP_UP): Plays a short song. Some songs are included in the distribution of TigerJython (see Doc)

Example 3: A moving robot is stopped with a button click
For moving robots it is advantageous to use a while loop which is repeated until a button is pressed.
As long as button A was not pressed, the robot repeats the commands in the while loop. The button click ends the loop and the program continues to the stop() command.

# Mr4c.py
from microbit import *
from mbrobot import *

setSpeed(15)
forward()
while not button_a.was_pressed():
    d = getDistance()
    if d < 10:
        backward()
        delay(1000)
        forward()
    delay(200)
stop() 
► Copy to clipboard
 

Explanations of the program code:

while not button_a.was_pressed() Quasi endless while loop, which is terminated when button A is pressed.

 


Exercises:


1)


The robot is controlled with the buttons as follows:

Whenever the button A is clicked, the robot starts a circular movement. Clicking button B stops the robot.
 


2)


Program an SOS transmitter.
In the Morse alphabet, S is represented by three short signals and O by three long signals. You want to play Morse code using the buttons. When button A is clicked, a short tone is played and the two red LEDs light up briefly. When button B is pressed, a long tone is played and the two red LEDs light up for a long time.

Now, by pressing the buttons, transmit an SOS sequence. If you want to send more in Morse, you can see the coding of single letters in the following program code.


 



3)


The Morse code is used to transmit messages. Letters, punctuation marks and numbers are coded as short signal, long signal and pause. With the built-in speaker you can easily create Morse messages.

a)

Send some short messages using the two buttons as in task 2. Coding of  single letters:

 a : .-    ,  b : -...  ,  c : -.-.  ,  d : -..   ,  e : .     ,
 f : ..-.  ,  g : --.   ,  h : ....  ,  i : ..    ,  j : .---  ,
 k : -.-   ,  l : .-..  ,  m : --    ,  n : -.    ,  o : ---   ,
 p : .--.  ,  q : --.-  ,  r : .-.   ,  s : ...   ,  t : -     ,
 u : ..-   ,  v : ...-  ,  w : .--   ,  x : -..-  ,  y : -.--  ,
 z : --.. 

b)

With the following program you can create Morse messages automatically. It is useful to store the encoding in a Python dictionary. The message is  processed  in transmit() using a for c in text-loop. where each character is coded and played with dot and dash accordingly. Send messages in Morse code at different speeds and try to decipher them.

# Morse.py

from microbit import *
from music import *

dt = 100 
freq = 1000

morse = {
'a':'.-'   , 'b':'-...' , 'c':'-.-.' , 'd':'-..'  , 'e':'.'    ,
'f':'..-.' , 'g':'--.'  , 'h':'....' , 'i':'..'   , 'j':'.---' ,
'k':'-.-'  , 'l':'.-..' , 'm':'--'   , 'n':'-.'   , 'o':'---'  ,
'p':'.--.' , 'q':'--.-' , 'r':'.-.'  , 's':'...'  , 't':'-'    ,
'u':'..-'  , 'v':'...-' , 'w':'.--'  , 'x':'-..-' , 'y':'-.--' ,
'z':'--..' , '1':'.----', '2':'..---', '3':'...--', '4':'....-',
'5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
'0':'-----', '-':'-....-', '?':'..--..', ',':'--..--', ':':'---...',
'=':'-...-'}

def dot():
    pitch(freq, dt)
    delay(dt)

def dash():
    pitch(freq, 3 * dt)
    delay(dt)

def transmit(text):
    for c in text:
        if c == " ":
            delay(4 * dt)
        else:
            c = c.lower()
            if c in morse:
                k = morse[c]
                for x in k:
                    if x == '.':
                        dot()
                    else:
                        dash()
            delay(2 * dt)

transmit("I will be there tonight")
► Copy to clipboard