nimbuscode.dev/blog/posts/micropython-for-beginners
C:\> cat BLOG/MICROPYTHON_BEGINNERS.md

MicroPython for Beginners: Getting Started with Microcontrollers

Introduction to MicroPython

MicroPython is a lean and efficient implementation of the Python 3 programming language optimized to run on microcontrollers and in constrained environments. If you're familiar with Python, you'll find MicroPython immediately accessible, as it includes a subset of the Python standard library specifically rewritten for microcontrollers.

While traditional embedded programming often requires knowledge of C or C++, MicroPython offers a gentler learning curve while still providing impressive performance for most IoT (Internet of Things) applications. This makes it an excellent choice for beginners and experienced developers alike.

In this guide, we'll walk through everything you need to get started with MicroPython, from choosing the right hardware to writing your first programs and building a simple project.

Required Hardware

To follow along with this tutorial, you'll need a microcontroller that supports MicroPython. Here are some popular options:

  • ESP32 Development Board - Powerful, with built-in WiFi and Bluetooth (recommended for beginners)
  • ESP8266 NodeMCU - More affordable, with WiFi capabilities
  • Raspberry Pi Pico - Excellent performance at a low cost
  • PyBoard - The official MicroPython board, but more expensive

For this tutorial, we'll be using an ESP32 development board, which offers the best balance of features, community support, and affordability. You'll also need:

  • Micro-USB cable for connecting the microcontroller to your computer
  • Breadboard for prototyping
  • A few LEDs (different colors)
  • 220-330 ohm resistors
  • Jumper wires

Setting Up Your Environment

Before we can start programming with MicroPython, we need to:

  1. Flash the MicroPython firmware onto our ESP32
  2. Set up a development environment to write and upload code

Installing MicroPython Firmware

First, download the latest MicroPython firmware for your board from the official MicroPython downloads page.

To flash the firmware, we'll use a tool called esptool, which you can install with pip:

pip install esptool

Next, connect your ESP32 to your computer and run these commands (replacing COM port as needed):

esptool.py --port COM5 erase_flash
esptool.py --port COM5 --baud 460800 write_flash -z 0x1000 esp32-20220117-v1.18.bin

Note: On macOS and Linux, the port will look like /dev/ttyUSB0 or /dev/cu.SLAB_USBtoUART instead of COM5.

Setting Up Thonny IDE

The simplest way to get started with MicroPython programming is using Thonny, a Python IDE that works great with MicroPython:

  1. Download and install Thonny IDE for your operating system
  2. Open Thonny and go to Tools → Options → Interpreter
  3. Select "MicroPython (ESP32)" from the dropdown menu
  4. Select the correct port for your device
  5. Click OK to save the settings

You should now be able to see the MicroPython REPL (Read-Eval-Print Loop) in the Thonny shell window, which means your connection is working.

Your First MicroPython Program

Let's start with the traditional "Hello World" example. In Thonny, create a new file and enter this code:

# First MicroPython Program
print("Hello from MicroPython!")

# Let's see some basic MicroPython capabilities
import utime
for i in range(5):
    print(f"Counting: {i}")
    utime.sleep(1)  # Sleep for 1 second

print("Done!")

Save this file as hello.py on your computer. Now, to run this on the ESP32:

  1. Click the green "Run" button in Thonny
  2. When prompted, choose "MicroPython device"

You should see the output in the Thonny shell window, with the numbers appearing one second apart:

Hello from MicroPython!
Counting: 0
Counting: 1
Counting: 2
Counting: 3
Counting: 4
Done!

Congratulations! You've just run your first MicroPython program on a microcontroller.

Simple LED Blinking Project

Now let's do something more interesting - controlling hardware. We'll create a simple circuit to blink an LED, which is the "Hello World" of hardware programming.

Circuit Setup

Connect your components as follows:

  1. Connect the longer leg (anode) of the LED to GPIO pin 2 on the ESP32 through a 220-ohm resistor
  2. Connect the shorter leg (cathode) of the LED directly to GND (ground)
LED Circuit Diagram

Simple LED circuit with ESP32

LED Blinking Code

Create a new file in Thonny with this code:

# LED Blinking Example
from machine import Pin
import utime

# Set up the LED on GPIO pin 2
led = Pin(2, Pin.OUT)

# Blink the LED 10 times
for i in range(10):
    led.value(1)  # Turn LED on
    print("LED ON")
    utime.sleep(0.5)  # Wait for half a second
    
    led.value(0)  # Turn LED off
    print("LED OFF")
    utime.sleep(0.5)  # Wait for half a second

print("Blinking complete!")

Save this file as blink.py and run it on your ESP32. You should see the LED blinking on and off, with corresponding messages in the Thonny shell.

Making the LED Blink Forever

To make the LED continue blinking until the device is reset, we can use an infinite loop:

# Continuous LED Blinking
from machine import Pin
import utime

led = Pin(2, Pin.OUT)

# Infinite loop - will run until the device is reset
while True:
    led.value(not led.value())  # Toggle the LED state
    utime.sleep(0.5)  # Wait for half a second

This code uses a neat trick: not led.value() toggles the LED's state from on to off or off to on with each loop iteration.

Working with Sensors

MicroPython really shines when you connect sensors to your microcontroller. Let's look at how you might read data from a simple temperature sensor.

For a DHT11 or DHT22 temperature and humidity sensor, you would use code like this:

# Reading from DHT temperature sensor
from machine import Pin
import dht
import utime

# Initialize the DHT sensor on Pin 4
sensor = dht.DHT22(Pin(4))
# For DHT11, use: sensor = dht.DHT11(Pin(4))

while True:
    try:
        sensor.measure()  # Get new readings
        temperature = sensor.temperature()
        humidity = sensor.humidity()
        
        print(f"Temperature: {temperature}°C, Humidity: {humidity}%")
        
    except Exception as e:
        print(f"Error reading sensor: {e}")
    
    utime.sleep(2)  # Wait 2 seconds between readings

This example demonstrates how MicroPython makes it straightforward to interface with sensors and display their readings.

Next Steps in Your MicroPython Journey

Now that you've gotten your feet wet with MicroPython, here are some suggested next steps:

  • Connect to WiFi - ESP32 and ESP8266 have built-in WiFi capabilities that you can leverage with MicroPython's network library
  • Explore More Sensors - Try connecting different sensors like light sensors, motion detectors, or soil moisture sensors
  • Build a Web Server - Create a simple web interface to control your microcontroller over your local network
  • Connect to IoT Platforms - Send your sensor data to platforms like Adafruit IO, ThingSpeak, or Home Assistant
  • Power Management - Learn how to optimize your code for battery-powered applications

MicroPython is an excellent gateway into the world of embedded systems and IoT. With the skills you've learned in this tutorial, you're well on your way to creating your own smart devices and automation projects.

Stay tuned for more advanced MicroPython tutorials where we'll dive deeper into topics like networking, displays, and integrating with IoT platforms!

Comments (0)

Sort by: