Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to make a Raspberry Pi Pico project that blinks a light in morse code. How would I get the separate character from the "word" variable?

from machine import Pin
from time import sleep
led = Pin(0, Pin.OUT)


def dot():
    led.value(1)
    sleep(0.5)
    led.value(0)
    sleep(2)


def dash():
    led.value(1)
    sleep(1)
    led.value(0)
    sleep(2)


# 0.5 Seconds = Dot
# 1 Second = Dash

# word to be translated
word = "Hi"

>Solution :

You can treat a string in Python as a list, for example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

word = "Hi"
print(word[0])
print(word[1])
#H
#i

Knowing this, you can iterate over a string:

word = "Hi"
for letter in word:
   print(letter)

#H
#i

For your problem, you can also map all the letters with their respective codes:


# 0 -> dot
# 1 -> dash
codes = {
   "A": (0, 1),
   "B": (1, 0, 0, 0),
   "C": (1, 0, 1, 0)
}

word = "AC"

for letter in word:
    morse_codes = codes[letter]
    print(morse_codes)
}
#(0, 1)
#(1, 0, 1, 0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading