MicroPython Reference
A single document reference of the MicroPython API.
Please note that some part of this reference is still in progress and will be updated over time. The article is subject to minor changes.
This reference serves as a "translation" between what is known as the Arduino API, which is documented in the Arduino Language Reference, and the MicroPython API.
The main goal with this reference is to provide an understanding of how to e.g. use common Arduino concepts such as
digitalWrite()
in a MicroPython script.For example:
(Arduino/C++)digitalWrite(pin, HIGH)
(MicroPython)pin.value(1)
The entries are named exactly the same as in the language reference, with the MicroPython syntax, description and code example provided for each entry. It is however important to understand that any given board may not be fully compatible with this reference, as some implementations vary between board/architecture. For example, using PWM on a STM32 board will differ from using it on an ESP32 board.
Note that several entries in the original Language Reference are directly taken from the C++ reference. In the same fashion, many functions located in this reference are taken from the Python reference, and are not MicroPython specific.
Digital I/O
To access digital GPIOs using MicroPython, we use the
Pin
module. To define a pin, we use Pin(pin,type)
.pinMode()
(define as output)output_pin = Pin(pin, Pin.OUT)
input = Pin(pin, Pin.IN)
(define as input pull up)input_pullup = Pin(pin, Pin.IN, Pin.PULL_UP
(define as input pull down)input_pulldown = Pin(pin, Pin.IN, Pin.PULL_DOWN
Parameters:
- pin we want to setpin
- define as input or outputtype
- define as pull up or pull down mode (optional).pullmode
Example:
1from machine import Pin2
3output_pin = Pin(5, Pin.OUT) #define pin4input_pin = Pin(6, Pin.IN, Pin.PULL_UP) #define pin as an input pullup
digitalRead()
pin.value()
Reads the state of a digital pin defined as input.
- Parameters: none.
- Returns: the value of the digital pin (0 or 1).
1from machine import Pin2
3pin = Pin(5, Pin.PULL_UP) #define pin4reading = pin.value() #read pin5
6print(reading) #print state of pin to REPL
digitalWrite()
pin.value(state)
Writes a state to a digital pin defined as an output.
- Parameters: none.
- Returns: the value of the digital pin (0 or 1).
1from machine import Pin2
3pin = Pin(5, Pin.PULL_UP) #define pin4pin.value(1) #set pin to high state
Analog I/O
Configure Input (ADC)
To read an analog input pin, we need to attach a pin to the ADC.
- create the pin.adc_pin = machine.Pin(pin)
- attach it to the ADC.adc = machine.ADC(adc_pin)
Configure Output (PWM)
To write analog values using PWM, we need to define the pin and set the frequency.
pwm = PWM(Pin(15))
pwm.freq(1000)
On STM32 boards (GIGA R1, Portenta H7 etc.), we need to define at as follows:
pin1 = Pin("PC6", Pin.OUT_PP, Pin.PULL_NONE)
timer1 = Timer(3, freq=1000)
channel1 = timer1.channel(1, Timer.PWM, pin=pin1, pulse_width=0)
analogRead()
adc.read_u16()
Attach a pin to an ADC, and read the raw value.
- Returns: - the raw analog value in a 16-bit format (0-65535).
- Parameters: none.
Example:
1import machine2import time3
4adc_pin = machine.Pin("PC4") 5adc = machine.ADC(adc_pin)6
7while True:8 reading = adc.read_u16() 9 print("ADC: ",reading)10
11 time.sleep_ms(1000)
Note: to convert the 16-bit value to a 10-bit value, you can use the following formula:
1# right-shifts the bits and discards the 6 most significant bits2# effectively changing the value range from 0-65535 to 0-10233result = (reading >> 6) & 0x3FF
analogWrite()
pwm.duty_u16(duty)
Writes the duty cycle (0-65535) to a PWM pin.
- Parameters: duty cycle (0-65535).
- Returns: None.
Example:
1from machine import Pin, PWM, ADC2
3pwm = PWM(Pin(15))4duty = 30000 #between 0-655355
6pwm.freq(1000)7
8while True:9 pwm.duty_u16(duty)
analogWrite() (STM32)
channel1.pulse_width(duty)
Writes the duty cycle in percentage (0-100) to a PWM pin.
- Parameters: duty cycle in percentage (0-100).
- Returns: None.
Example:
1import pyb2import time3from pyb import Pin, Timer4
5pin1 = Pin("PC6", Pin.OUT_PP, Pin.PULL_NONE)6timer1 = Timer(3, freq=1000)7channel1 = timer1.channel(1, Timer.PWM, pin=pin1, pulse_width=0)8
9channel1.pulse_width(50) #duty cycle at 50%
Time
To introduce timings & delays, use the
time
module.delay()
time.sleep(seconds)
Creates a delay for the number of specified seconds.
- Parameters: seconds.
- Returns: nothing.
Example:
1import time2
3time.sleep(1) #freeze program for 1 seconds
millis()
time.time()
Returns the number of seconds elapsed since the start of the script.
- Returns: seconds (float).
- Parameters: none.
Example:
1'''2"Blink Without Delay" script.3Blinks an LED attached to pin 5 every second,4without freezing the program.5'''6
7import time8from machine import Pin9
10ledPin = Pin(5, Pin.OUT) 11
12interval = 113previousTime = 014switch = False15
16while True:17 currentTime = time.time()18 19 if currentTime - previousTime >= interval:20 previousTime = currentTime21 22 switch = not switch23 ledPin.value(switch)
Bits and Bytes
bitRead()
bit_value = (variable >> bit_index) & 1
Reads a specific bit of an integer variable.
Parameters:
- an integer variable with numeric value, e.g.variable
12345
- the specific bit we want to read (e.g.bit_index
)5
Returns:
- The value of the specific bit.
Example:
1'''2This example prints out each bit of an 8-bit variable3It stops after 255 (the max value an 8-bit variable can hold)4'''5import time6counter = 07
8bit_length = 8 # 8 bits9while True:10 bits = []11 for bit_index in range(bit_length - 1, -1, -1):12 bit_value = (counter >> bit_index) & 113 bits.append(bit_value)14 print("Binary: ", bits, " DEC: ", counter)15
16 counter += 117 time.sleep(0.01)18 if counter > 255:19 break
bitSet()
variable = variable | (1 << bit_index)
Sets a specific bit of an integer variable.
Parameters:
- an integer variable with numeric value, e.g.variable
12345
- the specific bit we want to read (e.g.bit_index
)5
Returns:
- Nothing.
Example:
1# Example variable2variable = 123453
4# Set the third bit5bit_index = 26
7print()8print("Before setting a bit: ",bin(variable))9print("Before setting a bit: ",variable)10variable = variable | (1 << bit_index)11
12# Print the result13print("After setting a bit: ",bin(variable))14print("After setting a bit: ",variable)
highByte()
leftmost_bit = (variable >> leftmost_bit_index) & 1
Reads the high-order (leftmost) bit of a variable.
Parameters
- an integer variable with numeric value, e.g.variable
255
- the leftmost bit, e.g.leftmost_bit_index
in an 8-bit variable.7
Returns
- the value of the leftmost bit.leftmost_bit
Example:
1# Example variable2variable = 2553
4bit_length = 85# Extract the leftmost bit6leftmost_bit_index = bit_length - 17leftmost_bit = (variable >> leftmost_bit_index) & 18
9# Print the result10print("Leftmost bit: ", leftmost_bit)
lowByte()
rightmost_bit = variable & 1
Reads the low-order (rightmost) bit of a variable.
Parameters
- an integer variable with numeric value, e.g.variable
255
- the rightmost bit,rightmost_bit
in an 8-bit variable.0
Returns
- the value of the rightmost bit, e.g.rightmost_bit
if1
is 255 (255 is 11111111 in binary).variable
Example:
1# Example variable2variable = 2553
4# Extract the rightmost bit5rightmost_bit = variable & 16
7# Print the result8print("Rigthmost bit: ", rightmost_bit)
Advanced I/O
tone() / noTone()
tone(pin,frequency,volume,duration)
noTone(pin,duration)
To use the popular
tone()
and noTone()
functions, we need to define them as functions as they currently are not implemented.Example:
1from machine import Pin, PWM2import time3 4def tone(pin,frequency,volume,duration=None):5 speaker = PWM(Pin(pin))6 speaker.freq(frequency)7 speaker.duty_u16(volume)8 if duration is not None:9 time.sleep(duration)10
11def noTone(pin,duration=None):12 speaker = PWM(Pin(pin))13 speaker.deinit()14 if duration is not None:15 time.sleep(duration)16
17while True:18 tone(5,500,1000,1)19 noTone(5,1)
Math
abs()
abs(value)
Returns the absolute value of a number.
Example:
1result = abs(-5)2print(result)
constrain()
constrain(value, min, max)
Constrains the value to be within a specific range.
Example:
1def constrain(value, lower, upper):2 return max(min(value, upper), lower)3
4result = constrain(10, 0, 5) # Result will be 55print(result)
map()
map(value, in_min, in_max, out_min, out_max)
Maps a value from one range to another.
Example:
1def map(value, in_min, in_max, out_min, out_max):2 return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min3
4result = map(50, 0, 100, 0, 255) # Result is 127.55print(result)
max()
max(value1, value2, value3, valueX)
Returns the highest value among the given parameters. Accepts many arguments separated by comma.
Example:
1result = max(5, 10, 3) # Result will be 102print(result)
min()
min(value1, value2, value3, valueX)
Returns the lowest value among the given parameters. Accepts many arguments separated by comma.
Example:
1result = min(5, 10, 3) # Result will be 32print(result)
pow()
pow(base, exponent)
Raises a number to the power of another.
Example:
1result = pow(2, 3) # Result will be 82print(result)
sq()
sq(value)
Returns the square of a number.
Example:
1result = sq(4) # Result will be 162print(result)
sqrt()
math.sqrt(value)
This function returns the square root of a number.
Example:
1import math2
3result = math.sqrt(16) # Result will be 4.04print(result)
Trigonometry
cos()
math.cos(angle_in_radians)
Calculates the cosine of an angle (in radians). The result will be between -1 and 1.
Example:
1import math2
3# Specify the angle in radians4angle_in_radians = math.radians(45)5
6# Calculate the cosine of the angle7cos_value = math.cos(angle_in_radians)8
9# Print the result10print(f"The cosine of {angle_in_radians} radians is: {cosine_value}")
sin()
math.sin(angle_in_radians)
Calculates the sine of an angle (in radians). The result will be between -1 and 1.
Example:
1import math2
3# Specify the angle in radians4angle_in_radians = math.radians(30)5
6# Calculate the sine of the angle7sine_value = math.sin(angle_in_radians)8
9# Print the result10print(f"The sine of {angle_in_radians} radians is: {sine_value}")
tan()
math.tan(angle_in_radians)
Calculates the tangent of an angle (in radians). The result will be between negative infinity and infinity.
Example:
1import math2
3# Specify the angle in radians4angle_in_radians = math.radians(60)5
6# Calculate the tangent of the angle7tangent_value = math.tan(angle_in_radians)8
9# Print the result10print(f"The tangent of {angle_in_radians} radians is: {tangent_value}")
Characters
isAlpha()
char.isalpha()
Analyse if a single character is alphabetic.
1char = 'a'2if char.isalpha():3 print(f"{char} is alphabetic.")4else:5 print(f"{char} is not alphabetic.")
isAlphaNumeric()
char.isDigit()
and char.isAlpha()
Checks if char is a number or an alphabetic character.
Example:
1# Function to check if a character is alphanumeric2def is_alphanumeric(char):3 return char.isalpha() or char.isdigit()4
5# Example usage6test_char = 'a'7
8if is_alphanumeric(test_char):9 print(f"{test_char} is alphanumeric.")10else:11 print(f"{test_char} is not alphanumeric.")
isAscii()
ord(char) < 128
Checks if character is an ASCII character by checking if the decimal number of the character presented is over 128. If it is over, it is not an ASCII character.
1char = 'Ö'2
3if 0 <= ord(char) < 128:4 print(f"{char} is an ASCII character.")5else:6 print(f"{char} is not an ASCII character.")
isControl()
ord(char) < 32 or ord(char) == 127
Checks whether character presented is less than 32 or 127, which represents control characters.
1char = '\t' # Example: Tab character2
3if 0 <= ord(char) < 32 or ord(char) == 127:4 print(f"{char} is a control character.")5else:6 print(f"{char} is not a control character.")
isDigit()
char.isDigit()
1char = '5'2if char.isdigit():3 print(f"{char} is a digit.")4else:5 print(f"{char} is not a digit.")
isGraph()
Example:
1char = 'A'2
3if char.isprintable() and not char.isspace():4 print(f"{char} is a graph character.")5else:6 print(f"{char} is not a graph character.")
isLowerCase()
Example:
islower()
1char = 'a'2
3if char.islower():4 print("Is lower case.")5else:6 print("Is not lower case.")
isPrintable()
isprintable()
Checks if a character is printable, e.g. any character, including blank space, but not control characters.
Example:
1char = '\t'2
3if char.isprintable():4 print("Is printable.")5else:6 print("Is not printable.")
isPunct()
There is no built-in function for checking punctuation in Python. Instead, we can define a variable containing all punctioation characters, and a function that compares the provided value with it.
Example:
1def isPunct(char):2 punctuation_chars = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"3 return char in punctuation_chars4
5print(isPunct("."))
isSpace()
char.isspace()
Example:
1char = ' '2
3if char.isspace():4 print(f"{char} is a space character.")5else:6 print(f"{char} is not a space character.")
isUpperCase()
char.isupper()
Example:
1char = 'A'2
3if char.isupper():4 print(f"{char} is an uppercase letter.")5else:6 print(f"{char} is not an uppercase letter.")
Random Numbers
random()
random.random()
Produces a random number within the range provided.
Example:
1import random2
3random_integer = random.randint(1, 10)4print("Random integer between 1 and 10:", random_integer)
randomSeed()
seed_value = int(time.time())
and random.seed()
To generate a random seed value, we first use the
time()
module to generate a unique value, and feed it to the random.seed()
generator. The result is that you will always get a unique random number.Example:
1import random2import time3
4# Seed the random number generator with the current time5seed_value = int(time.time())6random.seed(seed_value)7
8# Generate random numbers using the seeded generator9random_number = random.randint(1,100)10print(random_number)
Note that
generates a new value every second. E.g. running time.time()
twice within a second will generate the same value. random.seed()
should not be used repetitively.random.seed()
External Interrupts
attachInterrupt()
interrupt_pin.irq(trigger=mode, handler=function)
Attaches an interrupt to a pin with specified mode.
1from machine import Pin2import time3
4# Define a callback function to be called when the interrupt occurs5def interrupt_callback(pin):6 print("Interrupt occurred on pin", pin_name)7
8# Pin name9pin_name = "PA3"10
11# Define the pin to which you want to attach the interrupt12interrupt_pin = Pin(pin_name, Pin.IN, Pin.PULL_UP) # Replace 2 with the actual pin number you are using13
14# Attach the interrupt to the pin, specifying the callback function and trigger type15interrupt_pin.irq(trigger=Pin.IRQ_FALLING, handler=interrupt_callback)16
17while True:18 print("hello world")19 time.sleep(1)
detachInterrupt()
interrupt_pin.irq(handler=None)
Detaches the active interrupt from specified pin.
Example:
1from machine import Pin2import time3
4# Define a callback function to be called when the interrupt occurs5def interrupt_callback(pin):6 print("Interrupt occurred on pin", pin_name)7 # Detaches the interrupt from the pin8 interrupt_pin.irq(handler=None) 9
10# Pin name11pin_name = "PA3"12
13# Define the pin to which you want to attach the interrupt14interrupt_pin = Pin(pin_name, Pin.IN, Pin.PULL_UP) # Replace 2 with the actual pin number you are using15
16# Attach the interrupt to the pin, specifying the callback function and trigger type17interrupt_pin.irq(trigger=Pin.IRQ_FALLING, handler=interrupt_callback)18
19while True:20 print("hello world")21 time.sleep(1)
Serial (USB)
In the Arduino API, we are accustomed to using
Serial.begin()
and Serial.print()
to send data from a board to a computer.The same API is used for sending and receiving data over UART, using
Serial1
. For UART, see the Serial (UART) section. In MicroPython, to send data over USB, we can use the
print()
function, which prints the content to the REPL. As MicroPython is implemented a bit differently, the REPL also allows you to write commands inside it. The REPL is therefore in many ways, different from the Serial Monitor we are used to in the Arduino IDE.Serial.print()
print(content)
This function prints the content to the REPL.
Example:
1variable = 52
3print("I am a string!") # prints a string4print(variable) # prints value of variable5print(58) # prints a numeric value6print(f"The value is {variable}") # prints a string with a value inserted
Serial1 (UART)
UART communication is initialized using the
UART
object from the machine
module.When sending & receiving data on a hardware UART port on an Arduino board, we use the
class.Serial1
Serial1.begin()
machine.UART(port, baudrate=baud)
Initialize UART communication on specified port (default is
1
), and specified baud rate.Example:
1import machine2import time3
4uart = machine.UART(1, baudrate=57600)
Baud rate
is used as using the common 57600
and 115200
interfered with the Arduino IDE's Serial Monitor.9600
Serial1.available()
uart.any()
Checks if there's any data available on the UART port.
Example:
1import machine2import time3
4uart = machine.UART(1, baudrate=57600)5
6while True:7 if uart.any():8 print("data available")
Serial1.read()
uart.read(1)
Reads one byte from the buffer.
Example:
This example reads the first byte of data from the buffer, stores it into the
received_data
string. When a new line character (\n
) is detected, the received message is printed to the REPL.1import machine2import time3
4
5uart = machine.UART(1, baudrate=57600) 6received_data = ""7
8while True:9 if uart.any():10 data = uart.read(1)11 received_data += data12 13 if received_data and received_data[-1] == '\n':14 print("Received:", received_data[:-1]) # Print the accumulated data (excluding the newline character)15 received_data = "" # Reset the string after printing16 17 time.sleep(0.1)
Serial1.write()
uart.write(message)
Writes / sends data over UART.
Example:
1import machine2import time3
4
5uart = machine.UART(1, baudrate=57600) 6
7while True:8 data_to_send = "Hello World!\n"9 uart.write(data_to_send)10 11 time.sleep(1)
SPI
SPI communication is initialized using the
SPI
object from the machine
module. SPI.begin()
spi = machine.SPI(port, baudrate, polarity, phase)
SPI is initialized by importing the
machine
module and specifying a number of parameters, such as baudrate and polarity.Example:
1import machine2
3spi = machine.SPI(0, baudrate=1000000, polarity=0, phase=0)
SPI.read()
Note that
is not in the Arduino API, as the SPI.read()
handles both outgoing and incoming data.SPI.transfer()
spi.readinto(data_in)
Reads incoming data and stores it in an array. The size of the array needs to be adjusted to match the size of the incoming data size.
Example:
1import machine2import time3
4spi = machine.SPI(0, baudrate=1000000, polarity=0, phase=0)5data_in = bytearray(3)6
7spi.readinto(data_in)8
9print("Received Data:", data_in)
SPI.write()
Note that
is not in the Arduino API, as the SPI.write()
handles both outgoing and incoming data.SPI.transfer()
spi.write(data_out)
Writes data to the SPI bus.
Example:
1import machine2import time3
4spi = machine.SPI(0, baudrate=1000000, polarity=0, phase=0) 5data_out = b'\x01\x02\x03'6
7spi.write(data_out)
SPI.transfer()
spi.write_readinto(data_out, data_in)
Reads & writes data simultaneously, where incoming data is stored in a buffer.
Example:
1import machine2import time3
4spi = machine.SPI(0, baudrate=1000000, polarity=0, phase=0)5
6data_to_send = b'\x01\x02\x03'7
8data_received = bytearray(len(data_to_send))9
10spi.write_readinto(data_to_send, data_received)11
12print("Received Data:", data_received)13
14spi.deinit()
Bit Size
spi.bits = 8
Sets the number of bits per word.
Example:
1spi.bits = 8
Wire / I2C
Wire.begin()
i2c = I2C(port, scl, sda, freq)
Initializes I2C communication on specified port and pins. The
port
and freq
are optional parameters, if left unspecified, default values will be set. 1from machine import I2C2
3i2c = I2C(0, scl=Pin(SCL_PIN), sda=Pin(SDA_PIN), freq=100000)
Wire.available()
i2c.in_waiting()
Checks the number of available bytes to read.
1available_bytes = i2c.in_waiting()2
3print("Available bytes to read: ", available_bytes)
Wire.read()
i2c.readfrom(address, num_bytes)
Reads data in specified number of bytes from a device with the specified address.
1data_in = i2c.readfrom(address, num_bytes)2
3print("I2C data: ", data_in)
Wire.write()
i2c.writeto(address, data_out)
Writes data to specified address.
Example:
1from machine import I2C, Pin2
3# Initialize I2C anc configure device & reg addresses4i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=100000) # Adjust pins and frequency as needed5device_address = 0x686register_address = 0x007
8# The array of bytes to be send out9# This buffer simply stores 1,2,3,410data_out = bytearray([0x01, 0x02, 0x03, 0x04])11
12# Send the device address with the write bit to indicate a write operation13i2c.writeto(device_address, bytearray([register_address]))14
15# Finally, send data to the device16i2c.writeto(device_address, data_out)
Wire.setClock()
The frequency for the clock is set during initialization. See begin() for more info.
SoftI2C
MicroPython has a built in class called
SoftI2C
(as in software I2C). Software I2C does not use a dedicated hardware I2C peripheral, but instead relies on the CPU to handle the clock signal, communication protocol etc.SoftI2C
is available through the machine
module, and uses the same API as hardware I2C, with a few additional methods.
- creates thesofti2c = machine.SoftI2C(scl,sda,freq,timeout)
object with specified pins, frequency and timeout.softi2c
- create the start condition for initializing communication over I2C (SDA goes to LOW while SCL is HIGH).softi2c.start()
- create the stop condition for ending communication over I2C (SDA goes to HIGH while SCL is HIGH).softi2c.stop()
USB HID
Human Interface Device (HID) is currently not supported on any of the Arduino boards.
To use HID functions on Arduino boards that support it (most modern boards), please refer to the Arduino / C++ reference:
Data Types
When declaring variables in MicroPython / Python, you do not need to specify the data type, this is done automatically.
Examples for variable declaration can be seen in the snippet below:
1var_array = [1, 2, 3]2var_bool = True/False3var_unsigned_byte = 2554var_signed_byte = -1285var_char = 'A'6var_double = 3.147var_float = 29.2312328var_int = 21474836479var_long = 214748364710var_short = 3276711var_string = "This is a string"12var_unsigned_int = 429496729513var_unsigned_long = 4294967295
size_t
len(my_array)
There is no direct equivalent to
size_t
, but using the len()
function, you can return the size of an object.Example:
1my_array = [1,2,3,4,5]2
3array_size = len(my_array)4
5print("Size of array is: ", array_size)
void
def my_func():
There is no direct equivalent to
void
, but when defining a function without a return statement, the function is of a "void" type.Example:
1def my_function():2 print("Function executed, nothing returned though!")
Conversion
byte()
bytes(value)
Converts a value to a byte.
Example:
1my_byte = bytes([255])2print(my_byte) # prints \xff which in hex is 255
char()
chr(value)
Converts a value to a char
Example:
1value = 65 # 65 is "A" in ASCII code2char_value = chr(value) # converts a value to char (65 to "A")3print("Char value:", char_value) # prints "A"
float()
float(value)
Example 1:
Converts an integer to float.
1value = 252float_value = float(value)3print("Float value:", float_value) # prints 25.0
Example 2:
Converts a string to float.
1value = "3.14"2float_value = float(value)3print("Float value:", float_value) #prints 3.14
int()
int(value)
Converts a value
Example 1:
Converts a float to int. Rounds the number up/down, e.g.
42.232
= 42
.1value = 42.2322int_value = int(value)3print("Int value:", int_value)
Example 2:
Converts a string to int.
1value = "42"2int_value = int(value)3print("Int value:", int_value)
Local / Global Variables
Variables can either be globally or locally declared:
- Global variables can be accessed anywhere in the program.
- Local variables can only be accessed within the function it is declared.
When creating a program, you can decide whether you want certain variables accessible from anywhere, or just within the function.
The benefit of declaring a local variable is that it uses less memory space (as it is only assigned within the function).
The con of declaring a local variable is that it is not accessible anywhere else in the program.
1global_var = 0 #initial value2
3def my_function():4 local_var = 10 # declare local variable5 print()6 print("(inside function) local_var is: ", local_var)7
8 global_var = local_var + 259 print("(inside function) global_var is updated to: ", global_var)10
11 return global_var12
13global_var = my_function() + 2514print("(outside function) global_var is finally: ", global_var)15
16'''17The line below will cause the script to fail18because it is not declared globally.19'''20#print(local_var)
Sketch
MicroPython uses scripts as opposed to traditional sketches that require the
void loop()
and void setup()
functions.A script can be as simple as a single line that prints "Hello World!"
1print("Hello World!")
loop()
while True:
A loop is not required in a MicroPython script, but is required in order to run a script continuously on the board. To have a loop in a program, we need to use a while loop.
Example:
The example below runs a loop that increases the
value
variable by 1
each time the loop is run. It then prints the value to the REPL, and waits for a second.1import time2value = 03
4while True:5 value += 16 print(value)7 time.sleep(1)
setup()
In MicroPython, there's no equalivent of the
setup()
function. Configurations that are traditionally done in this function can simply be declared at the top of the program.Example:
This script simply declares a pin's pin mode (see pinMode()).
1from machine import Pin2
3output_pin = Pin(5, Pin.OUT)4
5while True:6 #loops forever
Control Structure
Control structures are used to control the flow of a program, i.e. what code will and won't execute. When a condition is met, the specified code block executes.
if
The
if
statement checks if a condition is met, and executes the following block of code.Example:
1x = 102if x > 5:3 print("x is greater than 5")
else
The
else
statement can be used after e.g. an if
statement. If the previous condition is not met, then it will the block of code following the else
statementExample:
1x = 52y = 103
4if x > y:5 print("x is greater")6else:7 print("y is greater")
for
The
for
loop is used to iterate through a sequence, e.g. a range of numbers, a list, or a string. Example 1: Number Range
1for number in range(5):2 print(number)
Example 2: List
1my_list = [10, 20, 30, 40, 50]2for item in my_list:3 print(item)
Example 3: String
1my_string = "Hello World!"2for char in my_string:3 print(char)
while
The while loop is used to repeatedly execute a block of code as long as the specified condition is
True
. Example 1:
1i = 02while i < 5:3 print(i)4 i += 1
Example 2: Infinity Loop
The while loop is critical to MicroPython as it is needed to create the "infinity" loop, i.e. a loop that runs whenever the board is powered.
1while True:2 # your program
break
The
break
statement is used to break out of loops before it ends.Example:
1for i in range(5):2 if i == 3:3 break4 print(i)
continue
The
continue
statement is used to skip to the end of the code block, effectively moving on to the next iteration. This is useful to e.g. filter out specific data points.Example:
This example iterates through a list of numbers. If the number is less than
0
(negative), it will skip it.1my_list = [0, -5, -3, 8, 9 , 11]2for num in my_list:3 if num < 0:4 continue5 print(num)
return
Terminates a function and
return
a value from a function to the calling function.Example:
In this example, we call a function named
add_numbers()
, which takes two parameters. It then returns the processed value, using the return
statement.1def add_numbers(a, b):2 result = a + b3 return result4
5print(add_numbers(5,5))
Operators
Arithmetic Operators
Arithmetic operators are symbols used in programming and mathematics to perform basic arithmetic operations on numerical values.
To assign a new value to any variable, use an assignment operator (single equal sign
=
).1my_variable = 5 # the value of my_variable is now 5
The following arithmetic operators can be used:
(remainder)%
(multiplication)*
(addition)+
(subtraction)-
(division)/
(exponentiation)**
Example:
The script below demonstrates
1remainder = 5 % 10 # remainder is 52multiplication = 10 * 5 # result of multiplication is 503addition = 10 + 5 # result of addition is 154subtraction = 10 - 5 # result of subtraction is 55division = 10 / 5 # result of division is 26exponentiation = 10 ** 5 # result of exponentiation is 10000 (10*10*10*10*10)7
8print("remainder:", remainder)9print("multiplication:", multiplication)10print("addition:", addition)11print("subtraction:", subtraction)12print("division:", division)13print("exponentiation:", exponentiation)
Comparison Operators
Comparison operators are used to compare two values or expressions, and returns a boolean result (
True
or False
)
(equal to)==
(not equal to)!=
(less than)<
(less than or equal to)<=
(greater than)>
(greater than or equal to)>=
The following scripts will compare the
x
with y
variables and print the result in the REPL.Equal to ==
1x = 102y = 53
4if x == y:5 print("x is equal to y")6else:7 print("x is not equal to y")
Not equal to !=
1x = 102y = 53
4if x != y:5 print("x is not equal to y")6else: 7 print("x is equal to y")
Less than <
1x = 102y = 53
4if x < y:5 print("x is smaller than x")6else:7 print("x is not smaller than y")
Less or equal to <=
1x = 102y = 53
4if x <= y:5 print("x is smaller or equal to y")6else: 7 print("x is not smaller or equal to y")
Greater than >
1x = 102y = 53
4if x > y:5 print("x is greater than y")6else:7 print("x is not greater than y")
Greater than or equal to >=
1x = 102y = 53
4if x >= y:5 print("x is greater than or equal to y")6else:7 print("x is not greater than or equal to y")
Boolean Operators
Boolean operators are used to perform logical operations between Boolean values (
True
or False
).Boolean operators are expressed in written format, and not with symbols (
!
, &&
, ||
) like other programming frameworks such as Arduino / C++ use.
(logical not)not
(logical and)and
(logical or)or
The following scripts demonstrates how to use the boolean operators:
Logical
:not
1x = True2
3if not x:4 print("False")5else:6 print("True")
Logical
:and
1x = 72
3if x > 5 and x < 10:4 print("x is greater than 5 AND smaller than 10")
Logical
:or
1x = 52y = 103
4if x == 3 or y == 10:5 print("One condition matched!")
Bitwise Operators
Bitwise operators are used to manipulate individual bits at a binary level. For example, an integer variable that holds the value of
15
is in binary 1111
. With bitwise operators, you can for example change 1111
(15) to 1011
(11).The following bitwise operators are available:
(bitwise and)&
(bitshift left)<<
(bitshift right)>>
(bitwise xor)^
(bitwise or)|
(bitwise not)~
Below are a set of scripts that explains the usage of bitwise operators:
Bitwise and
:&
1a = 5 # 101 in binary2b = 3 # 011 in binary3
4result = a & b5print(result) # Output: 1 (001 in binary)
Bitshift left
:<<
1x = 3 # 11 in binary2
3result = x << 24print(result) # Output: 12 (1100 in binary)
Bitshift right
:>>
1y = 16 # 10000 in binary2
3result = y >> 24print(result) # Output: 4 (100 in binary)
Bitwise xor
:^
1p = 12 # 1100 in binary2q = 7 # 0111 in binary3
4result = p ^ q5print(result) # Output: 11 (1011 in binary)
Bitwise or
:|
1m = 10 # 1010 in binary2n = 5 # 0101 in binary3
4result = m | n5print(result) # Output: 15 (1111 in binary)
Bitwise not
:~
1z = 7 # 0111 in binary2
3result = ~z4print(result) # Output: -8 (1000 in two's complement binary)
Compound Operators
A compound operator combines an arithmetic or bitwise operation with an assignment. For example, instead of writing
x = x +3
, you can write x += 3
, using the compound addition (+) operator. The following compound operators are available:
(compound remainder)%=
(compound bitwise and)&=
(compound multiplication)*=
(compound addition)+=
(compound subtraction)-=
(compound division)/=
(compound bitwise xor)^=
(compound bitwise or)|=
*Please note that increment
and decrement ++
are not available in the Python language. The equalivent is --
and x +=1
.x -=1
Below are a set of scripts that explains the usage of compound operators:
Compound remainder
:%=
1a = 152b = 73
4a %= b5print(a) # Output: 1 (15 % 7)
Compound bitwise and
:&=
1x = 52y = 33
4x &= y5print(x) # Output: 1 (5 & 3)
Compound multiplication
:*=
1num = 82
3num *= 34print(num) # Output: 24 (8 * 3)
Compound addition
:+=
1total = 102
3total += 54print(total) # Output: 15 (10 + 5)
Compound subtraction
:-=
1result = 202
3result -= 84print(result) # Output: 12 (20 - 8)
Compound division
:/=
1value = 302
3value /= 64print(value) # Output: 5.0 (30 / 6)
Compound bitwise xor
:^=
1m = 122n = 73
4m ^= n5print(m) # Output: 11 (12 ^ 7)
Compound bitwise or
:|=
1p = 102q = 53
4p |= q5print(p) # Output: 15 (10 | 5)
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.