3

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'

node_modules
  • 4,790
  • 6
  • 21
  • 37
YEp d
  • 154
  • 1
  • 9
  • 2
    If this is a long term project you may want to consider storing your Morse dictionary in an external file as it might save you a headache or two in the future. – Reez0 Jun 26 '19 at 08:27
  • I don't see why this question is being up voted. It's a simple and obvious bug – phil Jun 28 '19 at 09:14

1 Answers1

6

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+='-'
Fitzi
  • 1,641
  • 11
  • 17