Search code examples
pythonmicropythonbbc-microbit

Why does this code display 'A' on start without any input?


This is a morse code translator for microbit but it displays 'A' on start

from microbit import *
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', '--..--': ', ', '.-.-.-': '.', '..--..': '?', '-..-.': '/', '-....-': '-', '-.--.': '(', '-.--.-': ')'}

message=''
while True:
    morseChr=''
    if button_a.is_pressed:
        morseChr+='.'
    if button_b.is_pressed:
        morseChr+='-'
    if button_a.is_pressed and button_b.is_pressed:
        message+=morse[morseChr]
        display.show(message)
        sleep(1000*len(message))
        display.clear()

I expect it to translate the button presses into a message but it just shows 'A'


Solution

  • There are two problems with your current logic:

    First, whenever you press A and B simultaneously, .- will be added to your message. To avoid that, use an else if and move the A and B case first (because that should be higher priority than just A or B).

    Secondly, you can actually never add any other character to your message than an A, because your morseChar is reset to an empty string in each loop. You would need to move the variable outside of the loop to keep track of the previous input.

    Further, is_pressed is a function according to the microbit documentation.

    The resulting code would look like this:

    message=''
    morseChr=''
    
    while True:
        if button_a.is_pressed() and button_b.is_pressed():
    
            # First check if the entered char is actually valid
            if morseChr not in morse:
                morseChr='' # reset chars to avoid being stuck here endlessly
                # maybe also give feedback to the user that the morse code was invalid
                continue
    
            # add the char to the message
            message += morse[morseChr]
            morseChr=''
    
            display.show(message)
            sleep(1000*len(message))
            display.clear()
    
        elif button_a.is_pressed():
            morseChr+='.'
    
        elif button_b.is_pressed():
            morseChr+='-'