This tutorial is the first prerequisite in the Cybersecurity Series. It is not needed in order to build and use the cyber:bot robot, but it builds useful skills!
This tutorial introduces some ways to communicate with your micro:bit module through a computer. It’s a lot like texting, but you’ll be exchanging messages with your micro:bit instead of another person. The app for this is called a terminal, and it’s part of both the python.microbit.org online editor, and Mu.
You will use a terminal to communicate with the micro:bit in two ways: REPL, and Serial. REPL is an interactive programming mode that allows you to make the micro:bit execute MicroPython statements you type into the terminal. Serial is a mode where a script can make the micro:bit send you messages, ask questions, process your answers, and display results.
You will need:
Complete these tutorials first:
You will be able to write MicroPython scripts that make your micro:bit receive, process and respond to text and numeric values you type into a terminal app. Along the way, you will build basic skills for tutorials on these subjects (and more coming soon!)
The terminal apps that are built into python.microbit.org online editor and the Mu software give you two ways to interact with your micro:bit:
Most of the Cybersecurity tutorials will utilize the terminal to interact with a micro:bit while its program is running. For example, if the micro:bit picks up any radio messages, it will now be able to display them quickly in the terminal.
In computing, a terminal is “A combination of a keyboard and output device (such as a video display unit) by which data can be entered into or output from a computer or electronic communications system” according to Merriam Webster [7].
Large computers with numerous “terminals” connected to them used to be common in business and academics. Each terminal had a monitor and keyboard, and sometimes other devices.
Image source: "DEC VT100 [8]" by Gorthmog is licensed under CC BY-SA 4.0 [9]
With the advent of more sophisticated computers and networks, terminal emulator apps like the windows command prompt became common.
The “terminals” built into python.microbit.org and Mu are also considered computer terminal emulator apps, even though they are communicating with a microcontroller.
Hardware terminals are still in use today. For example, an ATM (Automated Teller Machine) is a terminal that’s connected to the bank’s system. At the ATM, a user can access their bank account and interact with a bank to withdraw or deposit money, check account balances, etc.
Image source: "ATM_750x1300.jpg [8]" by Rfc1394 [10] is released into Public Domain [11]
In this activity, you will put the micro:bit into REPL mode and make it evaluate MicroPython statements that you type into the terminal pane.
Looking at your editor’s terminal pane, you can tell if it’s in REPL mode by looking for the REPL prompt symbol >>>. This prompt shows you where to type a MicroPython statement, just to the right of the symbol. Then, when you press Enter the micro:bit will evaluate the statement and you’ll be able to see the result immediately in the same terminal. No need to flash a script!
In the example below, print("Hello Terminal!") was typed at the REPL prompt. After pressing the Enter key, the micro:bit evaluated it, and printed "Hello Terminal!" on the line below. The online editor is shown on the left, Mu on the right.
For either the online editor or Mu:
IMPORTANT: If you are using the python.microbit.org online editor:
The python.microbit.org online editor and Mu editor terminal panes look different, and the steps to enter REPL mode also differ.
In the online editor, you need to start a WebUSB connection before opening the terminal. You will only have to do this once per session, and also every time you disconnect and reconnect the USB cable.
The online editor’s terminal opens into “Serial” mode. In this mode, the terminal will only display messages from a script that’s running. When the terminal is open, switching to REPL is easy. Either click CTRL + D for REPL button, or click the terminal pane and press CTRL + C on your keyboard.
TIP: After clicking Open Serial, the label on the button will change to Close Serial. When you click Close Serial, the terminal pane will disappear, and you will be able to work with code in the editor pane again. Close Serial does not disconnect WebUSB.
In Mu, the REPL button opens a terminal pane and puts the micro:bit into REPL mode.
Now that you’ve got REPL open, it’s time to type some MicroPython statements and see the results.
As of this writing, the micro:bit module hosts MicroPython v.1.9.2. For more information on MicroPython and the REPL feature, please see the information located here: https://docs.micropython.org/en/v1.9.2/esp8266/reference/repl.html [13]
The print function is similar to some of the display methods you experimented with in Writing micro:bit Programs [14]. The main difference is that instead of outputting characters or images to the micro:bit module’s LED display, the print function transmits characters to a terminal.
The print function can display a variety of objects as text in a terminal, and it can also accept more than one object separated by commas. For example, if a variable named n stores the value 5, you can write a statement like print("n = ", n), and it will display n = 5.
Tip: The print function is built into the python interpreter, so your sketches won’t have to include any modules to use it.
You might have noticed that another REPL prompt appeared below the result of your last print statement. Let’s try making REPL print something different.
REPL is not limited to single lines. For example, if you type from microbit import * at the REPL prompt, the MicroPython interpreter in the micro:bit will import the micro:bit module. Then, you can type statements that use MicroPython functions and methods. The next example makes use of the microbit module’s sleep function.
You can also type compound statements into REPL. Compound statements are ones where one line has a colon and the lines below it are indented. Some examples include if… statements and for… loops. This next example also has a for… loop.
As you’ve now seen, print function calls can be entered at the REPL prompt to display messages and values. MicroPython scripts can also use print to display messages and values as the scripts run. This can be helpful for displaying longer messages, and also for displaying what’s happening to values at certain points in your script. And, since you flash the script to the micro:bit, your code travels with your device.
In this activity, you will print messages, values, and combinations of both in the terminal.
The Online Editor has to be connected to the micro:bit before it can display text messages. If the second button from the left displays “Disconnect”, it means that the micro:bit is connected. If it displays “Connect”, it means the micro:bit is not connected and you need to connect it.
Now that the online editor is connected, you can run a script that prints a message and open the terminal to see that message. With this connection, you can also flash scripts into the micro:bit by simply clicking the online editor’s Flash button. (No more switching to a file browser and dragging files into the micro:bit drive!)
# print_to_terminal.py from microbit import * sleep(1000) print("Hello Terminal!")
After clicking “Send CTRL-D to reset”, the first message the terminal displays is soft reboot. That’s letting you know that the terminal is doing the equivalent of pressing and releasing the micro:bit module’s Reset button, (which is next to its USB connector). After that, the micro:bit runs the script and whenever it executes a print statement, the result appears in the terminal. In this case, it’s the Hello Terminal! message.
If the script ends by running out of statements, the terminal then displays technical information about the micro:bit, followed by a prompt to type help() for more info, and ends with the REPL prompt. Whenever “CTRL-D to reset” is clicked, the micro:bit will restart the script and display these lines again.
To reset the micro:bit, you can also click the black Terminal pane and press CTRL+D (CMD+D in Mac).
To exit a running script and go straight to the REPL prompt, you can also click the “Send CTRL-C for REPL.”
In Mu, there’s a REPL button that opens a terminal pane and puts the micro:bit into REPL mode. To run a script and see its print statements, simply click the terminal pane and then press CTRL + D. You can also press and release the micro:bit module’s Reset button. It’s the button right next to the micro:bit’s USB socket.
# print_to_terminal.py from microbit import * sleep(1000) print("Hello Terminal!")
You should see Hello Terminal! appear in the REPL terminal. To learn more about the other messages, read the section titled Inside the Terminal Display earlier on this page.
Mum on Mu — This is the last time that the Cybersecurity lessons will refer to the Mu application, however Mu’s REPL is able to handle all of these lessons in the same way that the online editor’s terminal does.
What if you want to display a different message in the online editor? Try modifying the text in between the parentheses and quotation marks after the print command.
The micro:bit’s print function is completely different from the display object and its methods. One of those outputs is not as fast as the other. The display methods are for the 5x5 LED grid, and each call has to display each character long enough for a human to read it. In contrast, the micro:bit print function can send characters very rapidly, with each character taking only about 1/10,000th of a second to transmit.
You might have noticed that print can display values stored by variables, along with strings of characters. That same functionality is also available when you add print calls to scripts.
# print_value_to_terminal.py from microbit import * sleep(1000) print("Hello Terminal!") value = 10 print("value = ", value)
Let’s try a countdown timer in the terminal using a while loop. The while statement repeatedly executes statements that are indented immediately below it. The loop repeats “while” its condition is true. In this program, the while loop repeats while the value variable is greater than or equal to 0.
# print_looped_terminal_values.py from microbit import * sleep(1000) print("Hello Terminal!") value = 5 while value > 0: print("value = ", value) sleep(1000) value = value - 1 print("Blastoff!")
You might have been wondering if there’s a way to type messages into the terminal and send them to the micro:bit. Well, there is — with the help of the input function.
# enter_a_message.py from microbit import * sleep(1000) message = input("Enter some text: ") print("message = ", message)
The input function can send a prompt, like "Enter some text: ", receive the characters you type, and return them as a string. That string normally gets stored in a variable with a statement like message = input("Enter some text: "). The text you type (up to when you press Enter) will get stored in the message variable, and MicroPython will automatically set that variable’s type to string. For more on data types, see the Remember and Use Values [15] page.
Customize the example script to ask for and store your name.
Did you use your real name? Don't worry, the micro:bit is not collecting your personal information! But do keep in mind that there are social aspects to cybersecurity, not just technical!
Let’s say you’re working on a project where you have to enter the cyber:bot robot’s left and right wheel speeds into the terminal. It might seem like all you’d have to do would be to type in numbers like 50 and 100. The problem is that those numbers are received as strings of characters “50” and “100” then stored in string variables. Before your script can use those values to set robot wheel speeds, it needs to convert them from string to int values with the int() function.
Enter, save, and flash this script:
# enter_a_value.py from microbit import * sleep(1000) text = input("Enter a value: ") value = int(text) print("value = ", value)
If you typed 23 in response to the prompt, the text = input("Enter a value: ") statement stored “23” in the text variable. This is a string of characters, not a usable number. The next line, value = int(text), converts the “23” string to the integer 23 and stores it in the value variable.
Think about this as two steps. First, the int(text) function call takes the text variable, which stores the “23” string, and returns the int value 23. That result gets copied to the int variable named value. Keep in mind that MicroPython automatically sets the variable type to int since that’s the kind of object the int() function returns.
Next, print("value = ", value) prints "Value = . Then, the print function has to convert the int value 23 stored by value into the character string “23” before sending it to the terminal.
The most important point in this exercise is that you entered characters that the script was able to convert to values it can use to make calculations, control repetitions, and more.
Now that your micro:bit scripts can receive values from the terminal, let’s put those values to work in an app. This first example is a countdown timer that allows you to set the number of seconds in the countdown.
# countdown_timer.py from microbit import * sleep(1000) text = input("Enter seconds to count down: ") value = int(text) message = input("Enter message after countdown: ") while value >= 0: print(value) sleep(1000) value = value - 1 print(message)
First, the script captures the text representation of a number you type into the terminal. This gets converted into an int value that the script can store and use for counting repetitions. This int value gets stored in the value variable.
text = input("Enter seconds to count down: ") value = int(text)
The text you type in response to the message prompt gets stored as a string of characters in the message variable, which is a string.
message = input("Enter message after countdown: ")
Since the value variable now stores an int variable, it can use it to control how many times this while loop repeats:
while value >= 0: print(value) sleep(1000) value = value - 1
After the while loop is done, your custom message gets displayed.
print(message)
This is another way of using text and values from the terminal — a calculator app.
# calculator.py from microbit import * sleep(1000) while True: text = input("Enter first integer a: ") a = int(text) op = input("Enter operation + - * /: ") text = input("Enter second integer b: ") b = int(text) if op == "+": c = a + b elif op == "-": c = a - b elif op == "*": c = a * b elif op == "/": c = a / b print("a", op, "b = ", c) print(" ")
Interval timers repeatedly count down the same amount of time, and are used to control the amount of time one has to repeatedly run a sprint or swim a lap, including rest. They are also used in stretching after a workout so that each stretch is only done for a fixed amount of time.
It helps to break this program into steps. Here is some pseudo-code that you can work from to build the program:
Outer loop always repeats
Get the countdown seconds and store in an int variable.
Get the reps and store in an int variable.
while reps > 0
copy countdown seconds to a temporary variable.
Print start interval message
while temporary variable > 0
Print temporary variable
Wait a second
Subtract 1 from temporary variable.
Subtract 1 from reps
Print done with set
Hint: Make the indentation levels in the pseudo code match the indentation levels in your code.
Links
[1] https://microbit.org/guide/firmware
[2] https://python.microbit.org/v/2
[3] https://learn.parallax.com/tutorials/robot/cyberbot/get-started-microbit-and-python
[4] https://learn.parallax.com/node/1925
[5] https://learn.parallax.com/tutorials/robot/cyberbot/dictionary-primer
[6] https://learn.parallax.com/tutorials/robot/cyberbot/cybersecurity-radio-basics
[7] https://www.merriam-webster.com/dictionary/terminal
[8] https://en.wikipedia.org/wiki/File:DEC_VT100_terminal_transparent.png
[9] https://creativecommons.org/licenses/by-sa/4.0/deed.en
[10] https://en.wikipedia.org/wiki/User:Rfc1394
[11] https://en.wikipedia.org/wiki/en:public_domain
[12] https://microbit.org/guide/firmware/
[13] https://docs.micropython.org/en/v1.9.2/esp8266/reference/repl.html
[14] https://learn.parallax.com/tutorials/robot/cyberbot/writing-microbit-programs
[15] https://learn.parallax.com/tutorials/robot/cyberbot/writing-microbit-programs/remember-and-use-values