Micropython Basics: MicroPython Language Basics
Table of Contents
Now that your MicroPython board and Thonny IDE are ready, it’s time to learn the language itself. MicroPython is a compact yet powerful version of Python 3, designed to run on small devices like the ESP32, ESP8266, or Raspberry Pi Pico. Despite its small footprint, it retains much of Python’s elegance — clean syntax, easy-to-read code, and intuitive structure.
Whether you’re an absolute beginner or transitioning from Arduino’s C/C++, learning MicroPython gives you a modern and efficient way to program microcontrollers. Let’s start by covering the core building blocks that you’ll use in almost every project — variables, data types, operators, conditions, loops, and functions.
1. Variables and Data Types
Variables are like containers that hold information — numbers, text, or logic values. In MicroPython, you don’t need to declare their data type. The interpreter automatically decides what kind of data you’re working with based on what you assign.
x = 10 # Integer
temperature = 27.5 # Floating-point number
name = "ESP32" # String
is_on = True # Boolean
Each variable has a type:
- int – whole numbers like
5
or-3
- float – decimal numbers like
3.14
- str – strings of text like
"Hello"
- bool – logic values:
True
orFalse
You can check the type of a variable using the type()
function:
print(type(name))
MicroPython also supports collections such as lists and dictionaries — useful for storing multiple values.
# List: an ordered collection
led_pins = [2, 4, 5, 18]
print(led_pins[0]) # Access the first item
# Dictionary: key-value pairs
device_info = {"name": "ESP32", "version": 1.0, "wifi": True}
print(device_info["name"]) # Access value by key
These flexible data structures make your programs more readable and efficient, especially when handling multiple sensors or components.
2. Operators
Operators allow you to perform actions such as calculations, comparisons, and logic decisions. They form the foundation of every MicroPython program that processes data or controls devices.
Arithmetic Operators
These are used to perform mathematical calculations:
a = 10
b = 3
print(a + b) # Addition → 13
print(a - b) # Subtraction → 7
print(a * b) # Multiplication → 30
print(a / b) # Division → 3.3333
print(a % b) # Modulus (remainder) → 1
print(a ** b) # Exponentiation → 1000
Comparison and Logical Operators
These help your program make decisions based on conditions:
x = 5
y = 8
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False
# Logical
print(x < 10 and y < 10) # True
print(x < 3 or y > 5) # True
print(not (x > y)) # True
Combining comparison and logical operators is common when you want your code to react only under specific circumstances — for example, when temperature readings cross a threshold.
3. Conditional Statements (if, elif, else)
Conditional statements let your program make choices. They decide which code to execute depending on whether certain conditions are true or false. Think of it as your microcontroller “thinking” before acting.
temperature = 32
if temperature > 35:
print("Warning: Too hot!")
elif temperature > 25:
print("Comfortable temperature.")
else:
print("It's a bit cold.")
The if
statement checks one condition; elif
provides additional checks,
and else
acts as the default action if none of the previous ones match.
You can also nest if
statements for more complex logic, or use them to control outputs,
like turning an LED on or off based on a sensor reading.
light_level = 120
if light_level < 100:
print("Turning light ON")
else:
print("Turning light OFF")
4. Loops (for and while)
Loops allow you to repeat actions automatically — perfect for tasks like blinking an LED,
checking a sensor, or updating a display. MicroPython supports two main loop types:
for
loops and while
loops.
The for Loop
A for
loop runs a set number of times. It’s commonly used to iterate through ranges or lists.
for i in range(5):
print("Count:", i)
This prints the numbers 0 to 4. You can also loop through a list:
led_pins = [2, 4, 5]
for pin in led_pins:
print("Using pin:", pin)
The while Loop
The while
loop repeats as long as a condition remains true.
Be careful — if the condition never becomes false, the loop will run forever.
count = 0
while count < 3:
print("Looping...", count)
count += 1
In embedded applications, while True:
is often used to keep a program running indefinitely,
such as continuously monitoring a sensor or maintaining network connections.
5. Functions
Functions let you organize your code into reusable, modular pieces. They help make your programs cleaner, easier to understand, and less repetitive.
def greet(name):
print("Hello,", name)
def add(a, b):
return a + b
greet("MicroPython")
result = add(5, 3)
print("Result:", result)
Every function starts with the def
keyword, followed by its name and optional parameters.
You can call the function anytime by using its name.
Functions are especially useful for hardware interaction — such as controlling LEDs or reading sensors —
because you can define reusable routines like turn_on_led()
or read_temperature()
.
You’ve now learned the essential programming concepts that power MicroPython projects. Up next, we’ll apply what you’ve learned to control real hardware — starting with your first classic experiment: Blinking an LED!