In this article, I would like to introduce you to the basics of programming in MicroPython using the ESP32 D1 R32. However, you can also easily apply this to other microcontrollers that also work with MicroPython.
Table of Contents
- MicroPython vs. Python
- Structure of the source code in MicroPython
- Commentaries
- Output on the command line
- Creating Variables
- Concatenating Texts
- Loops
- If Statements
- Outlook
MicroPython vs. Python
MicroPython is a full implementation of the Python 3 programming language that runs directly on embedded hardware such as the ESP32 D1 R32 or the Raspberry Pi Pico. While both languages are based on the same foundation, there are some key differences and adaptations that make MicroPython particularly suitable for use in microcontrollers:
Interactive Prompt (REPL): MicroPython provides an interactive prompt (REPL – Read-Eval-Print Loop), which allows commands to be executed immediately over USB-Serial. This is particularly useful for quickly testing and debugging code on the hardware.
Built-in Filesystem: MicroPython includes a built-in filesystem that is stored on the microcontroller’s flash memory. This allows scripts and data to be stored and managed directly on the device.
Module-specific Hardware Access: The ESP32 port of MicroPython includes special modules that allow access to hardware-specific functions of the chip. These include GPIO control, PWM, I2C, SPI, and other peripherals.
Resource Efficiency: MicroPython is designed to run on resource-constrained devices. It uses less memory and computing power compared to a full Python implementation on a desktop computer.
Libraries and Modules: MicroPython includes a selection of standard libraries and module-specific libraries that are useful for developing embedded applications. While some libraries from the standard Python library are missing, there are special libraries optimized for working with microcontrollers.
These differences make MicroPython an ideal choice for programming microcontrollers such as the ESP32 D1 R32, as it combines the power of Python with the efficiency required for embedded systems.
Structure of the source code in MicroPython
In MicroPython there are no brackets for summarizing code blocks, you have to work with indentations. You can choose between spaces and tabs. However, once you have decided on a type, you must continue to use it!
So if you receive the following error message, first check the number of spaces / tabs before your code blocks.
Traceback (most recent call last):
File "<stdin>", line 1
IndentationError: unexpected indent
Commentaries
With comments, you can insert text into your source code that has no influence on the behavior of the code. Comments are usually used to describe complicated code or to make it easier for other developers to access the source code.
You can also comment out code to skip the function / code block.
You can comment out individual lines with a “#” symbol and if you want to create a multi-line comment, you can start and end it with three double quotation marks.
# Here is a one-line comment """ Here you can enter several lines can be commented out at the same time """
If you are using a development environment, comments are always displayed specifically so that they stand out from the actual source code.
You can also add comments after the source code to save space and leave information.
Output on the command line
For debugging and outputting sensor data, we can use the simple yet powerful “print” command.
We can easily pass a text to this command, which will then be displayed on the command line.
print("Hello World!") print("Test")
In the command line, you can see the output of the two texts, each separated by a line break.
You can also pass multiple values to this command by separating them with a comma.
print("Hello World!", "Test")
The values are separated by a comma and displayed on the command line in sequence (separated by a space).
MicroPython – “print” command, multiple values
If you want to use a different separator instead of a space, you can name this separator using the optional parameter “sep=”.
print("Hello World!", "Test", sep="|")
In this case, I use a vertical bar to separate the values. You can also use any other symbols, letters, or numbers.
Creating Variables
In MicroPython or Python, there are no data types. This means that we create new variables simply by writing a name for our new variable followed by a value.
You can also overwrite this value with another value/data type at any time.
You can add, subtract, etc., numbers with the already known mathematical operators and, of course, print this value using the print command.
Concatenating Texts
If you want to concatenate/combine texts, you use the + symbol. This works very simply for texts.
text1 = "Text1" text2 = "Text2" print(text1+text2)
The two texts are simply concatenated and displayed on the command line.
However, if we want to combine a text and a number, we cannot do this as easily.
text1 = "Text1" number1 = 2 print(text1+number1)
The code generates the adjacent error message. This indicates that String & Int cannot be concatenated with the add function.
Traceback (most recent call last): File "", line 3, in TypeError: unsupported types for add: 'str', 'int'
So we must first convert the number to a string. To convert the number 1, we can simply add double quotes at the beginning and end or use the function “str”.
text1 = "Text1" number1 = 2 print(text1+str(number1))
The str function expects a numerical value (integer or floating-point number) and converts it to text and returns it.
You can use this, for example, if you want to display a sensor value on a display with the corresponding symbol behind it.
Loops
If you want to repeat code blocks a certain number of times or indefinitely, you need a loop.
For Loops
To repeat a block 5 times, we can use a for loop.
for i in range(5): print("i is:", i)
You can use the index i within the for loop and respond to it.
The range function gives you a list of numbers from 0 to 4 (a total of 5). If you want the number sequence from 1 to 6, you can adjust this function as follows.
for i in range(1, 6): print("i is:", i)
While Loop
A while loop is used to check an expression to break it within the loop.
number = 5 while(number > 0): print(number) number -= 1
Within the while loop, the variable number is decreased by 1, and at the head of the loop, it is checked if this value is greater than 0. Once the value of the variable number reaches 0, the loop is broken.
Infinite Loop
With the while loop, you can start an infinite loop by passing it a True.
while True: print("Hello World!")
This small code now causes the text “Hello World!” to be continuously displayed on the command line.
Breaking a Loop
If you want to break the loop within the loop, you use the break command. With this call, the loop is immediately exited, and the subsequent code (if any) is executed.
while True: print("Hello World!") break
In this example, the infinite loop starts, outputs the text “Hello World!”, and is immediately broken afterward.
Of course, this code makes little sense, but with a later introduced if statement, a bit more functionality is created.
Skipping Execution within a Loop
If you do not want to break the loop but only want to skip the execution of the loop, you use the continue command. This jumps back to the head and starts from the beginning.
for i in range(1, 6): if i == 2: continue print(i)
In the output, you see that the number 2 was skipped because we check in the code if the current index is equal to 2, and if so, the execution at this point is aborted.
Unlike break, the loop is continued.
If Statements
With if statements, you can create conditional code within your source code. You check an expression within the statement, which has a truth value True/False 1/0.
test = True if test: print("The value of test is True!")
You don’t necessarily have to check with a double equals sign for boolean values; it is sufficient to write the value in.
if test == True: # or if test:
You can also check if a value is False.
if test == False: # or if not test:
You can check numerical values with the following symbols:
- check if a value is greater >
- check if a value is greater than or equal to >=
- check if a value is less <
- check if a value is less than or equal to <=
- check if a value is not equal !=
- check if a value is equal ==
Branches with Else
With the additional else and else if commands, we can add another check to the written if statement. In the case of a boolean variable check, there are only two cases, True or False, but with numerical values, we can also check if the values are greater, less, equal, and not equal.
test = 1 if test > 0: print("The value of test is greater than 0") else: print("The value of test is less than 1")
In the example on the right, the variable test is checked if it is greater than 0. If not (the value is less than 1), the text “The value of test is less than 1” is output.
Additional Checks with Elif
If you want to add more checks, you can do this with elif, but you have to remember that once a statement has led to execution, the other checks are not executed!
test = 17 if test > 0 and test < 10: print("The value of test is between 1 and 9.") elif test >= 10 and test < 20: print("The value of test is between 10 and 19.") elif test >= 20: print("The value of test is greater than or equal to 20.")
In this example, it is checked if the value of the variable test is between certain values or greater than or equal to 20.
Outlook
With this post, I have given you an overview of the MicroPython programming language using examples. However, this is only the “normal” functionality; with microcontrollers, it gets a bit more special as we can control interfaces, GPIO pins, etc., and thus operate sensors/actuators.
I will show you how to control the GPIOs in the next post using simple LEDs, buttons, etc.”