Basics

No pins required. These run on a board, on the unix port, on WASM, and in the Pico playground.

Basics

Hello

print('hello, microcontroller')

REPL habits

Paste mode is Ctrl-E, then Ctrl-D to run. help() and help(module) list names. dir(x) works as in CPython.

import sys
print(sys.implementation)
print(sys.platform)
print(sys.version)

Types

n = 2 ** 100          # long ints are fine on most builds
name = 'pico'
buf = bytearray(16)
point = (1, 2)
flags = {{'ok': True}}
print(n, name, buf, point, flags)

Loops

for i in range(5):
    print(i, i * i)

n = 3
while n:
    print(n)
    n -= 1

Functions and classes

def twice(x):
    return x + x

class Counter:
    def __init__(self):
        self.n = 0
    def tick(self):
        self.n += 1
        return self.n

print(twice('ha'), Counter().tick())

Modules

A file util.py on the board becomes import util. Frozen modules are compiled into firmware; you import them the same way.

from micropython import const

BAUD = const(115200)
print(BAUD)

Files

with open('note.txt', 'w') as f:
    f.write('saved on the board
')

print(open('note.txt').read())
print(__import__('os').listdir())

Errors

try:
    1 / 0
except ZeroDivisionError as e:
    print('caught', e)

asyncio

import asyncio

async def ticks():
    for i in range(3):
        print('tick', i)
        await asyncio.sleep(0.2)

asyncio.run(ticks())

On a board, replace the print loop with waiting on a pin or a socket. See hardware and network.