Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Micropython

Learn Micropython - 10 Code Examples & CST Typing Practice Test

MicroPython is a lean and efficient implementation of Python 3 designed to run on microcontrollers and small embedded systems. It enables developers to write Python code for hardware with minimal overhead while maintaining Python syntax and semantics.

View all 10 Micropython code examples →
MicroPython Counter and LED Theme ToggleMicroPython Temperature Sensor MonitorMicroPython Button Press CounterMicroPython LED BlinkerMicroPython Light Sensor AlertMicroPython Buzzer AlertMicroPython Motor ControlMicroPython Distance Sensor MonitorMicroPython Humidity Sensor MonitorMicroPython Multi-Sensor Dashboard

Learn MICROPYTHON with Real Code Examples

Updated Nov 21, 2025

Explain

MicroPython allows Python code execution on resource-constrained devices like ESP32, ESP8266, STM32, and RP2040.

It provides direct access to hardware peripherals, including GPIO pins, PWM, ADC/DAC, I2C, SPI, and UART.

Ideal for embedded prototyping, IoT projects, and educational applications.

Core Features

Runs on resource-constrained microcontrollers

Direct access to hardware and peripherals

Filesystem access via onboard storage or USB

Event-driven and procedural programming support

Interoperable with MicroPython libraries and extensions

Basic Concepts Overview

Modules for hardware access (machine, network, uos, etc.)

REPL for interactive experimentation

boot.py and main.py for startup scripts

Event-driven and polling mechanisms for sensors

Support for networking protocols (HTTP, MQTT, WebSockets)

Project Structure

main.py - primary script executed at boot

boot.py - optional initialization script

lib/ - user or third-party MicroPython libraries

data/ - storage for logs or configuration

assets/ - optional resources such as images or fonts

Building Workflow

Flash MicroPython firmware to the board

Write scripts using Python syntax

Test peripherals interactively with REPL

Use libraries for sensors, actuators, and network modules

Deploy main.py to execute automatically on boot

Difficulty Use Cases

Beginner: simple LED or buzzer control

Intermediate: sensor data collection with storage

Advanced: controlling multiple peripherals with event handling

Expert: networked IoT devices with automation

Enterprise: small-scale embedded prototypes or custom devices

Comparisons

More general-purpose than CircuitPython, supports more boards

Requires slightly more setup and programming knowledge

Smaller abstraction for beginners compared to CircuitPython

Higher flexibility for advanced embedded applications

Optimized for performance and memory on constrained devices

Versioning Timeline

2013 - MicroPython created by Damien George

2014-2016 - Expansion to STM32 and ESP8266 boards

2017-2019 - Stable releases and library expansion

2020-2023 - Support for more microcontrollers (RP2040, ESP32, etc.)

2025 - Mature ecosystem with active community and libraries

Glossary

main.py - primary script executed on boot

boot.py - optional initialization script

REPL - interactive Python shell

machine module - hardware access API

Pin - microcontroller I/O interface

Installation Setup

Download the appropriate MicroPython firmware for your board

Flash the firmware to the microcontroller using tools like esptool or dfu-util

Connect the board via USB to a computer

Access REPL using serial terminal software

Upload scripts and libraries to the board's filesystem

Environment Setup

Install firmware on supported microcontroller

Connect board via USB

Ensure required libraries in lib/

Write main.py for application logic

Test peripherals and networking

Config Files

main.py - primary script

boot.py - initialization tasks

lib/ - peripheral libraries

data/ - persistent data files

assets/ - optional resources

Cli Commands

Use esptool.py or dfu-util to flash firmware

Access REPL via serial terminal

Upload scripts using ampy or rshell

Reset board to run scripts

Monitor serial output for debugging

Internationalization

Supports UTF-8 string handling

No built-in localization features

Documentation primarily in English

Works on boards globally

Community may provide localized guides

Accessibility

Python syntax familiar to developers

REPL enables interactive experimentation

Cross-platform development tools

Libraries simplify peripheral integration

Educational documentation widely available

Ui Styling

LEDs and displays provide primary interface

No native GUI support

Dashboards via connected PC possible

Visual feedback for sensors via displays

Focus on simplicity and hardware interactivity

State Management

Variables in main.py maintain device state

Sensor readings updated via loops or interrupts

Actuators controlled according to logic

REPL allows inspecting and modifying state

Persistent data stored in files if needed

Data Management

Read raw sensor data via machine module

Process and optionally store data

Transmit data via networking modules

Ensure memory-efficient handling

Log data for debugging or analysis

Architecture

Microcontroller runs MicroPython interpreter

Hardware modules provide GPIO, PWM, ADC, etc.

REPL for interactive access

Filesystem for scripts and libraries

Optional communication modules for networking (Wi-Fi/Ethernet)

Rendering Model

Board boots MicroPython interpreter

main.py executed automatically

Hardware controlled via machine module

REPL allows live testing

Scripts process inputs and control peripherals

Architectural Patterns

Single-threaded, event-driven scripting

REPL-based live interaction

Filesystem-based code deployment

Modular libraries for sensors and actuators

Optional networking for IoT integration

Real World Architectures

IoT sensor nodes with Wi-Fi

Robotics prototypes

Environmental monitoring systems

Educational microcontroller kits

Automation projects for small-scale embedded devices

Design Principles

Lightweight and efficient for microcontrollers

Maintain Python 3 syntax where possible

Provide direct hardware access

Interactive REPL for testing and debugging

Modular and extensible via libraries

Scalability Guide

Modularize scripts using functions and classes

Use libraries for repetitive hardware tasks

Optimize loops and memory usage

Combine multiple peripherals efficiently

Distribute functionality across multiple boards if needed

Migration Guide

Port scripts from standard Python carefully

Adjust hardware-specific pin mappings

Update library usage for MicroPython

Test main.py functionality on target board

Validate all sensor and actuator interactions

Performance Notes

Limited by microcontroller CPU speed and RAM

Suitable for lightweight sensor and actuator control

Heavy computation may require optimization or external modules

Efficient for low-power applications

Memory and garbage collection must be monitored on small boards

Security Notes

Secure Wi-Fi connections require proper SSL/TLS handling

Physical access to boards can compromise data

Firmware should be obtained from trusted sources

Sensitive data handling requires explicit programming

Network exposure must be controlled for IoT devices

Monitoring Analytics

Use REPL for real-time debugging

Monitor sensor and actuator outputs

Log critical events to files

Validate network connectivity

Analyze performance for optimization

Code Quality

Comment and structure scripts clearly

Validate sensor readings before acting

Use modular functions for repeated actions

Test scripts under multiple conditions

Ensure memory-efficient and stable code

Practical Examples

Blinking LEDs and buttons

Temperature, humidity, and environmental monitoring

Controlling motors and servos

Basic IoT data logging and Wi-Fi reporting

Robotics or small automation systems

Troubleshooting

Check firmware compatibility with your board

Verify correct pin configuration

Ensure libraries match MicroPython version

Use REPL for step-by-step debugging

Reset board if scripts fail to run

Testing Guide

Test hardware modules individually

Use REPL to monitor sensor and actuator responses

Validate scripts before deployment

Simulate communication scenarios

Ensure main.py executes correctly on boot

Deployment Options

Standalone embedded applications

Battery-powered IoT prototypes

Robotics and automation projects

Networked data collection systems

Educational and maker kits

Tools Ecosystem

Thonny, uPyCraft, VS Code for development

ampy, rshell, or WebREPL for file management

Official MicroPython libraries and modules

REPL for interactive testing

Community sample scripts and tutorials

Integrations

Sensors (temperature, light, humidity, motion)

Displays (OLED, LCD, TFT)

Motors, servos, and actuators

Wi-Fi and Ethernet modules

MQTT, HTTP, and WebSocket networking

Productivity Tips

Keep scripts modular

Test hardware modules individually

Use REPL for iterative development

Document hardware and code

Update libraries and firmware regularly

Challenges

Managing limited RAM and storage

Debugging hardware interactions

Ensuring reliable network connectivity

Porting code across different boards

Optimizing scripts for low-power devices

Learning Path

Learn Python fundamentals

Understand microcontroller architecture and GPIO

Install and configure MicroPython on boards

Experiment with peripherals and sensors

Build small IoT or automation projects

Skill Improvement Plan

Week 1: Python basics and REPL experimentation

Week 2: GPIO, PWM, ADC, DAC basics

Week 3: Sensor integration and data logging

Week 4: Networking and communication modules

Week 5: Deploy complete MicroPython scripts with automation

Interview Questions

What is MicroPython and which boards support it?

How do MicroPython and CircuitPython differ?

Explain main.py and boot.py scripts

How do you access GPIO, ADC, or PWM in MicroPython?

What are best practices for REPL debugging?

Cheat Sheet

import machine, time - core modules

led = machine.Pin(2, machine.Pin.OUT); led.value(1) - turn on LED

adc = machine.ADC(machine.Pin(36)); value = adc.read()

PWM: pwm = machine.PWM(machine.Pin(5)); pwm.duty(512)

Network: import network; station = network.WLAN(network.STA_IF)

Books

Programming with MicroPython

MicroPython for the Internet of Things

Mastering MicroPython

MicroPython Projects for Beginners

Hands-On MicroPython for Embedded Systems

Tutorials

Getting Started with MicroPython

GPIO, PWM, and ADC Basics

Reading Sensors and Controlling Actuators

Networking with MicroPython

Building Complete Embedded Projects

Official Docs

MicroPython Official Documentation

MicroPython Boards and Ports

MicroPython Libraries Reference

MicroPython Forum and GitHub

Networking and Hardware Guides

Community Links

MicroPython Forum

GitHub MicroPython Repositories

Reddit r/micropython

Maker and embedded electronics communities

Educational MicroPython resources

Community Support

Official MicroPython forum

MicroPython GitHub repository

Reddit r/micropython

Maker and embedded system communities

Educational electronics forums

Monetization

Educational kits and courses

IoT and embedded device prototyping

Maker projects and hobbyist devices

Robotics and automation services

STEM education and workshops

Future Roadmap

Expanded board support

Enhanced networking and IoT capabilities

Optimizations for memory and performance

Improved library ecosystem

Community-driven contributions and tutorials

When Not To Use

Applications requiring high-level GUI or desktop libraries

Large-scale production embedded systems without optimization

Performance-critical real-time control

Tasks requiring large memory or multi-threading

Complex industrial automation beyond prototyping

Final Summary

MicroPython brings Python 3 to microcontrollers and embedded systems.

Supports GPIO, PWM, ADC/DAC, networking, and peripherals.

Ideal for prototyping, IoT, robotics, and education.

Lightweight and efficient for constrained hardware.

Offers REPL and scripting for rapid development and testing.

Faq

Is MicroPython beginner-friendly?

Yes, but it assumes some understanding of Python and microcontrollers.

Can MicroPython run on all boards?

No, only supported boards with sufficient memory and compatible firmware.

Do I need Python experience?

Basic Python knowledge helps but not strictly required.

Can MicroPython handle networking?

Yes, with Wi-Fi/Ethernet capable boards and networking modules.

Is it suitable for commercial embedded production?

Primarily used for prototyping and small-scale devices, not full industrial production.

Code Sample Descriptions

1

MicroPython Counter and LED Theme Toggle

from machine import Pin

count = 0
isDark = False

led = Pin(2, Pin.OUT)

def updateUI():
    print(f"Counter: {count}")
    if isDark:
        led.value(1)
        print("Theme: Dark")
    else:
        led.value(0)
        print("Theme: Light")

def increment():
    global count
    count += 1
    updateUI()

def decrement():
    global count
    count -= 1
    updateUI()

def reset():
    global count
    count = 0
    updateUI()

def toggleTheme():
    global isDark
    isDark = not isDark
    updateUI()

updateUI()
increment()
increment()
toggleTheme()
decrement()
reset()

Demonstrates a simple counter with theme toggling using MicroPython variables and microcontroller GPIO control (LED indicator).

Let’s Try →
2

MicroPython Temperature Sensor Monitor

import random
temp = random.randint(20,35)  # Simulated sensor
print(f"Temperature: {temp}")
if temp > 30:
    print("Warning: High Temperature!")

Reads temperature from a sensor and prints alerts.

Let’s Try →
3

MicroPython Button Press Counter

presses = 0

def buttonPressed():
    global presses
    presses += 1
    print(f"Button pressed: {presses}")

buttonPressed()
buttonPressed()
buttonPressed()

Counts the number of button presses and prints the count.

Let’s Try →
4

MicroPython LED Blinker

from machine import Pin
import time
led = Pin(2, Pin.OUT)
for i in range(3):
    led.value(1)
    print("LED ON")
    time.sleep(0.5)
    led.value(0)
    print("LED OFF")
    time.sleep(0.5)

Blinks an LED on and off three times.

Let’s Try →
5

MicroPython Light Sensor Alert

from machine import Pin
import random
led = Pin(2, Pin.OUT)
lightLevel = random.randint(0,100)
if lightLevel < 50:
    led.value(1)
    print("LED ON")
else:
    led.value(0)
    print("LED OFF")
print(f"Light Level: {lightLevel}")

Monitors light sensor and turns on LED if it is dark.

Let’s Try →
6

MicroPython Buzzer Alert

import random
sensorValue = random.randint(50,150)
if sensorValue > 100:
    print("Buzzer ON")
else:
    print("Buzzer OFF")
print(f"Sensor: {sensorValue}")

Activates buzzer if a threshold value is exceeded.

Let’s Try →
7

MicroPython Motor Control

motorActive = True
if motorActive:
    print("Motor ON")
else:
    print("Motor OFF")
motorActive = False
if motorActive:
    print("Motor ON")
else:
    print("Motor OFF")

Starts and stops a motor based on a condition.

Let’s Try →
8

MicroPython Distance Sensor Monitor

import random
distance = random.randint(5,20)
if distance < 10:
    print("Alert: Object too close!")
print(f"Distance: {distance}")

Reads a distance sensor and prints alerts if object is too close.

Let’s Try →
9

MicroPython Humidity Sensor Monitor

import random
humidity = random.randint(20,80)
if humidity < 30:
    print("Too Dry!")
if humidity > 70:
    print("Too Humid!")
print(f"Humidity: {humidity}")

Monitors humidity and prints if it is too high or low.

Let’s Try →
10

MicroPython Multi-Sensor Dashboard

from machine import Pin
import random
led = Pin(2, Pin.OUT)
temp = random.randint(25,35)
light = random.randint(0,100)
if temp>30 or light<50:
    led.value(1)
    print("LED ON")
else:
    led.value(0)
    print("LED OFF")
print(f"Temp: {temp}, Light: {light}")

Reads multiple sensors and updates LED/buzzer accordingly.

Let’s Try →

Frequently Asked Questions about Micropython

What is Micropython?

MicroPython is a lean and efficient implementation of Python 3 designed to run on microcontrollers and small embedded systems. It enables developers to write Python code for hardware with minimal overhead while maintaining Python syntax and semantics.

What are the primary use cases for Micropython?

Embedded systems programming. IoT device prototyping. Sensor data acquisition and control. Educational microcontroller projects. Robotics and automation scripting

What are the strengths of Micropython?

Python syntax makes embedded programming accessible. Efficient for low-power, low-memory devices. Wide support for many microcontroller boards. Interactive REPL allows rapid testing and debugging. Strong open-source community support

What are the limitations of Micropython?

Limited performance for compute-intensive tasks. Smaller standard library than full Python. Memory constraints require careful code management. Fewer high-level abstractions compared to CircuitPython for beginners. Complexity increases with advanced peripheral integration

How can I practice Micropython typing speed?

CodeSpeedTest offers 10+ real Micropython code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.