Micropython STM32 Programming Guide
Micropython STM32 Programming Guide
First Edition
Sarful Hassan
Preface
Welcome to the MicroPython STM32 Programming Guide, designed to simplify
and enhance your journey in programming STM32 microcontrollers using
MicroPython. This book bridges the gap between Python's simplicity and the
powerful STM32 development ecosystem, making it suitable for beginners and
professionals alike.
MicroPython offers an intuitive way to work with hardware, allowing developers to
prototype faster, learn embedded systems concepts easily, and reduce development
complexity. This book focuses on the STM32 NUCLEO-F446RE, providing hands-
on guidance, practical examples, and structured learning.
Whether you're a hobbyist, a student, or an experienced engineer, this guide equips
you with the knowledge and tools to master MicroPython programming on STM32
boards.
Each chapter is accompanied by practical examples and exercises to help you apply
the concepts learned.
Release Notes
This is the First Edition of the MicroPython STM32 Programming Guide. Future
editions may include expanded support for other STM32 boards, topics on
integration with cloud platforms for IoT, and additional chapters on advanced
debugging and optimization.
How to Contact Us
For inquiries, feedback, or technical support, contact us at:
Email: [email protected]
Website: mechatronicslab.net
We value your input and are committed to enhancing your learning experience.
Copyright (MechatronicsLAB)
© 2024 MechatronicsLAB. All rights reserved. No part of this book may be
reproduced, stored, or transmitted in any form without prior written permission from
MechatronicsLAB.
Disclaimer
This book is provided "as is" without warranty of any kind. While every effort has
been made to ensure accuracy, MechatronicsLAB and the authors are not
responsible for any errors or omissions. Use this guide and its examples at your own
risk.
Table of Contents
Introduction to MicroPython
Getting to Know STM32 NUCLEO-F446RE
Setting Up the Development Environment
Basic MicroPython Syntax
Digital I/O in STM32
Analog I/O in STM32
Advanced I/O in STM32
Time Functions in STM32
Constants and Variables
Data Types in STM32
Data Type Conversion
Control Structures in STM32
Arithmetic Operators in STM32
Comparison Operators in STM32
Boolean Operators in STM32
Compound Operators in STM32 NUCLEO-F446RE with MicroPython
Bitwise Operators in STM32
Random Number Generation in STM32
Communication Protocols in STM32
Print Statements in STM32
Introduction to MicroPython
Chapter Overview
MicroPython is a lean, efficient implementation of Python designed specifically for
microcontrollers and embedded systems. It allows developers to write Python code to control
hardware, making it accessible and easy to create embedded applications. This chapter
introduces the basics of MicroPython, its features, reasons for using it with STM32
microcontrollers, and a step-by-step guide to installing and setting up MicroPython on the
STM32 NUCLEO-F446RE board.
Chapter Goal
● Understand the core concepts and features of MicroPython.
● Learn why MicroPython is an excellent choice for STM32 microcontrollers.
● Follow a step-by-step guide to install and set up MicroPython on STM32 NUCLEO-
F446RE.
5. Cost-Effective Solution
Key Features
1. Microcontroller: STM32F401RET6
32-bit ARM Cortex-M4 processor with a Floating Point Unit (FPU).
Operates at a clock speed of 84 MHz.
2. Memory:
512 KB Flash Memory for program storage.
96 KB SRAM for efficient data handling.
3. Power Supply:
Operates at 3.3V internally.
Supports external input voltage of 7V-12V via VIN.
USB-powered with an onboard voltage regulator.
4. Onboard Debugger: Integrated ST-LINK/V2-1 supporting SWD and JTAG
protocols.
5. Pin Compatibility:
Arduino UNO R3 headers for shield integration.
STM32 Morpho headers for access to all GPIOs and peripherals.
6. LEDs and Buttons:
LD1: USB communication indicator.
LD2: User-programmable LED.
LD3: Power indicator.
Two Push Buttons: One for reset and another for user control.
Pinout Configuration
1. Arduino-Compatible Headers
Two rows of male headers (CN7 and CN10) provide access to extended GPIOs
and peripherals.
Technical Specifications
Feature Details
Microcontroller STM32F401RET6 (ARM Cortex M4)
Architecture ARM Cortex M4 with Floating Point Unit
(FPU)
Clock Speed 84 MHz
Memory 512 KB Flash, 96 KB SRAM
GPIO Pins 50
ADC 12-bit, 16 channels
Timers 16-bit (6), 32-bit (2)
Communication 4x USART/UART, 3x I2C, 3x SPI
Interfaces
USB Support USB 2.0 Full-Speed
RTC Integrated 32kHz oscillator with calibration
Power Input 7V-15V (VIN), USB-powered
Operating Voltage 1.7V-3.6V (MCU), 3.3V system
Power Consumption 2.4 µA (standby without RTC)
Crystal Oscillators Internal (16 MHz), External (4-26 MHz)
Onboard Debugger ST-LINK/V2-1, supports SWD and JTAG
Hardware Details
1. Microcontroller: STM32F401RET6
High-performance ARM Cortex-M4 core.
Supports complex mathematical operations with its Floating Point
Unit (FPU).
Low power consumption for efficient applications.
2. Arduino Compatibility
Pinout matches Arduino UNO R3, making it easy to use existing
Arduino shields.
Simplifies development for users transitioning from Arduino to
STM32.
3. STM32 Morpho Headers
Provides access to all the microcontroller's GPIOs and peripherals.
Useful for advanced projects requiring additional functionality.
4. Integrated Debugger
ST-LINK/V2-1 allows for debugging and programming without
external hardware.
Supports firmware upgrade for added features.
5. LEDs and Buttons
LEDs:
LD1: USB communication activity.
LD2: Programmable for user-defined functions.
LD3: Power indication.
Buttons:
User button for custom input.
Reset button for restarting the MCU.
Power Supply Options
Performance Highlights
Speed and Efficiency: With an 84 MHz clock and advanced peripherals, the
STM32 Nucleo-F401RE offers superior performance compared to many 8-bit
development boards.
Versatility: Combines Arduino compatibility with advanced STM32 features for
a wide range of applications.
Debugging Capability: Built-in ST-LINK debugger supports real-time debugging
and step-through code execution.
Setting Up the Development Environment
Chapter Overview
A properly configured development environment is essential for efficient programming,
debugging, and testing with MicroPython on the STM32 NUCLEO-F446RE. This chapter covers
the required tools, installing and configuring popular MicroPython IDEs (such as Thonny and
uPyCraft), setting up serial communication for REPL access, and basic commands for using the
REPL to develop and interact with MicroPython code.
Chapter Goal
● Understand the tools and software required for STM32 MicroPython development.
● Install and configure IDEs (Thonny, uPyCraft) for MicroPython development.
● Set up serial communication for MicroPython REPL access.
● Learn essential REPL commands for testing and debugging.
1. Download Thonny: Visit https://thonny.org and download the installer for your
operating system (Windows, macOS, or Linux).
2. Install Thonny: Run the downloaded installer and follow the prompts to install
Thonny on your computer.
Configuring Thonny for MicroPython
4. Confirm Connection:
1. Click Run or press F5 to execute the code. The output should display in the
REPL.
1. Download uPyCraft: You can find the installer for uPyCraft on DFRobot's
website.
2. Install uPyCraft: Run the installer and follow the prompts to install the IDE on
your system.
Configuring uPyCraft for MicroPython
○ Go to Tools > Board and choose STM32F4 (or similar compatible option if
STM32 NUCLEO-F446RE is not listed).
1. Click Download and Run to execute the code on your STM32 board. The output
will appear in the REPL.
○ In PuTTY: Open PuTTY, select Serial as the connection type, and set the
COM port and baud rate.
○ In Tera Term: Open Tera Term, select Serial, choose the correct COM port,
and set the baud rate.
5. Access the REPL: Once connected, you should see the >>> prompt, indicating
that REPL is ready. You can now enter commands directly into the REPL.
2. Assigning Variables
○ Description: Controls GPIO pins directly from the REPL, which is useful for
hardware testing.
Example:
>>> from machine import Pin
>>> led = Pin(13, Pin.OUT)
>>> led.value(1) # Turns the onboard LED on
5. Accessing Help
○ Command: help()
○ Description: Displays help information about MicroPython commands and
functions.
Example:
>>> help()
6. Importing Modules
2. Data Types:
○ You can define functions with def and import modules with import , just
like in Python.
○ Many standard modules like math , time , and random are available in
MicroPython.
5. Exception Handling:
1. Limited Libraries:
○ MicroPython has a subset of the Python standard library. Some libraries,
especially those requiring large memory (like pandas , numpy , or scipy ),
are not available.
2. No __main__ Module:
3. Hardware-Specific Modules:
6. File Handling:
for i in range(5):
led.on() # Turn LED on
time.sleep(1) # Wait for 1 second
led.off() # Turn LED off
time.sleep(1)
1. Save the Code: Save the file with a .py extension (e.g., blink_led.py ).
2. Run the Code:
Rules
● Initialize GPIO Pins Correctly: Set each GPIO pin as input or output based on its use.
● Use Pull-Up or Pull-Down Resistors for Inputs: Stabilize input readings by
configuring internal pull-up or pull-down resistors.
● Control Outputs with on() and off() : These methods simplify setting outputs high
or low.
● Debounce Button Inputs: For stable readings, use a delay to debounce button presses.
● Optimize Code for Performance: Avoid unnecessary loops and delays to maximize
efficiency.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Configure pin = Pin(pin_number, led = Pin("A1",
GPIO as Pin.OUT) Pin.OUT)
Output
2 Configure pin = Pin(pin_number, button = Pin("A2",
GPIO as Pin.IN, Pin.PULL_UP) Pin.IN,
Input Pin.PULL_UP)
3 Set Output pin.on() led.on()
High
4 Set Output pin.off() led.off()
Low
5 Toggle pin.value(not pin.value()) led.value(not
Output State led.value())
6 Read value = pin.value() button_state =
Digital button.value()
Input
7 Delay time.sleep(seconds) time.sleep(0.1)
Topic Explanations
1. Configure GPIO as Output
What is Configuring GPIO as Output?
Configuring a GPIO pin as an output allows the STM32 NUCLEO-F446RE to control external
devices, such as LEDs or relays, by setting the pin to high or low.
Use Purpose
● Control Digital Devices: Activates or deactivates LEDs, motors, or other components.
● Provide High or Low Signals: Outputs binary signals that drive external devices.
Syntax
pin = Pin(pin_number, Pin.OUT)
Syntax Explanation
● Pin: MicroPython class for GPIO control.
● pin_number: The specific pin identifier, such as "A1" .
● Pin.OUT: Configures the pin as an output, enabling it to drive external devices.
● Pin Class: Allows MicroPython to manage GPIO functionality on the specified pin.
● Pin.OUT Mode: Sets the pin to output mode, making it capable of outputting high or
low signals.
Simple Code Example
from machine import Pin
led = Pin("A1", Pin.OUT) # Configures pin A1 as an output for LED
Syntax Explanation
● Pin: MicroPython GPIO class.
● pin_number: The specific pin to configure as input (e.g., "A2" ).
● Pin.IN: Configures the pin as an input to read incoming signals.
● Pin.PULL_UP / Pin.PULL_DOWN: Internal resistors to stabilize the input state by
defaulting it to high or low.
● Pull-Up/Down Resistors: Useful for preventing floating inputs that can lead to
unreliable readings.
● Input Mode: Configures the pin for reading digital input signals.
Simple Code Example
from machine import Pin
button = Pin("A2", Pin.IN, Pin.PULL_UP) # Configures pin A2 as input with pull-up
Syntax Explanation
● pin: The output pin.
● on(): Method that sets the pin to a high (1) state, sending voltage to the connected
device.
● High State: Provides power to the component, equivalent to setting pin.value(1) .
Simple Code Example
led.on() # Sets the LED to high (on)
Code Example Explanation
● Turns on the LED: The LED connected to led is set to high, powering the LED.
Notes
● Use on() instead of manually setting pin.value(1) for clarity.
Warnings
● Exceeding current limits for the pin may damage the microcontroller.
4. Set Output Low
What is Setting Output Low?
Setting an output pin to low (0) deactivates the connected component, such as turning an LED
off by pulling the pin to ground.
Use Purpose
● Turn Off LEDs or Other Components: Sends a low signal to deactivate the device.
● Control Digital Outputs: Provides a low output to control the device.
Syntax
pin.off()
Syntax Explanation
● pin: The output pin.
● off(): Method that sets the pin’s state to low (0), grounding the connected component.
● Low State: Equivalent to pin.value(0) , turning off the component.
Simple Code Example
led.off() # Sets the LED to low (off)
Syntax Explanation
● pin: The output pin.
● value(): Method to get or set the pin’s current state.
● not: Logical operator that inverts the current state.
● Toggle Logic: Alternates the output state each time the code executes.
Simple Code Example
led.value(not led.value()) # Toggles LED state
while True:
if button.value() == 0: # Check if button is pressed (active-low)
led.value(not led.value()) # Toggle LED state
time.sleep(0.2) # Debounce delay
Save and Run
1. Save the code as main.py on your STM32 NUCLEO.
2. Run the script; pressing the button toggles the LED’s state.
Check Output
The LED should toggle on and off with each button press, demonstrating how to control digital
inputs and outputs on the STM32 NUCLEO-F446RE using MicroPython.
Rules
● Select the Correct ADC Pin: ADC-compatible pins on the STM32 NUCLEO are
limited, so ensure you’re using a compatible pin (e.g., "A1" for ADC).
● Adjust PWM Frequency for Different Devices: LEDs, motors, and servos respond
differently to PWM; choose an appropriate frequency.
● Use Proper Conversion and Scaling: ADC readings range from 0 to 4095 (12-bit
resolution); PWM duty cycles use 0 to 65535.
● Averaging for Stability: Reducing noise is essential when reading from sensors;
average multiple samples for smoother data.
● Avoid Rapid Sampling: Introducing delays between ADC reads improves accuracy by
reducing noise.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Configure adc = sensor = ADC(Pin("A1"))
ADC ADC(Pin(pin_number))
(Analog
Input)
2 Read value = adc.read_u16() sensor_value =
ADC sensor.read_u16()
Value
3 Configure pwm = led_pwm =
PWM PWM(Pin(pin_number), PWM(Pin("A2"),
Output freq=freq) freq=1000)
4 Set PWM pwm.duty_u16(value) led_pwm.duty_u16(32768)
Duty
Cycle
5 Set PWM pwm.freq(freq) led_pwm.freq(2000)
Frequency
6 Delay time.sleep(seconds) time.sleep(0.1)
Topic Explanations
1. Configure ADC (Analog Input)
What is Configuring ADC for Analog Input?
The ADC (Analog-to-Digital Converter) enables the STM32 to interpret varying analog voltages
by converting them into a digital value. With MicroPython, ADC configuration allows reading of
analog signals, typically with a range of 0V to 3.3V, and converting them to a digital value
between 0 and 4095 (for 12-bit resolution).
Use Purpose
● Read Sensor Data: Convert sensor readings (e.g., temperature, light) to digital values.
● Analyze Voltage Levels: Allows the STM32 to measure varying signals in real-time.
Syntax
adc = ADC(Pin(pin_number))
Syntax Explanation
● ADC: A MicroPython class that enables analog-to-digital conversion on the specified
pin.
● Pin: Specifies the pin number for ADC.
● pin_number: Identifier for the analog input pin, like "A1" for the STM32 NUCLEO-
F446RE.
● ADC Object: Configures the pin to receive analog signals, allowing analog data to be
read as digital values.
● Pin Class: Ensures the correct configuration of the pin to support analog input.
Simple Code Example
from machine import ADC, Pin
sensor = ADC(Pin("A1")) # Configures pin A1 for analog input
Syntax Explanation
● value: Stores the digital value of the analog reading.
● adc: The ADC object created for the analog input pin.
● read_u16(): Reads the analog value as a 16-bit integer (0–65535) for higher precision.
● Precision: Although the STM32’s ADC is 12-bit (0–4095), read_u16() outputs a 16-
bit value to allow for more granular scaling.
● Scaling: This 16-bit representation (0–65535) can be scaled down to interpret 12-bit
values more precisely.
Simple Code Example
sensor_value = sensor.read_u16() # Reads analog value from sensor
Code Example Explanation
● Reads ADC Value: sensor_value contains the current analog reading as a digital
value.
Notes
● To convert the 16-bit ADC value to voltage: (sensor_value / 65535) * 3.3 .
● Averaging multiple readings can help reduce noise.
Syntax Explanation
● PWM: MicroPython class for setting up PWM on a GPIO pin.
● Pin: Specifies the GPIO pin for PWM output.
● pin_number: Identifier for the PWM-capable pin, such as "A2" .
● freq: Frequency in Hertz (Hz), setting the PWM toggle rate.
● PWM Frequency: Frequency defines how often the PWM signal completes a cycle;
different frequencies are better suited for different applications (e.g., 1 kHz for LEDs,
20 kHz for motors).
● Pin Class: Configures the specified pin for PWM output.
Simple Code Example
from machine import PWM, Pin
led_pwm = PWM(Pin("A2"), freq=1000) # Configures pin A2 for PWM output at 1 kHz
Syntax Explanation
● pwm: The PWM object initialized for output.
● duty_u16(): Method to set the PWM duty cycle.
● value: A 16-bit value (0–65535) representing the duty cycle, where 0 is 0% and 65535
is 100%.
● Duty Cycle Value: Higher values result in longer “on” times per cycle, creating a
brighter or faster effect.
● 16-Bit Range: Allows precise duty cycle adjustments, suitable for sensitive
applications like smooth dimming.
Simple Code Example
led_pwm.duty_u16(32768) # Sets duty cycle to 50% for half brightness
Syntax Explanation
● pwm: The PWM object.
● freq: Desired frequency in Hertz (Hz), setting the number of cycles per second.
● Frequency Range: Low frequencies (100 Hz) for visual effects, high frequencies (2
kHz and above) for motors.
● Impact on Devices: Higher frequencies create smoother analog effects, ideal for
sensitive applications.
Simple Code Example
led_pwm.freq(500) # Sets PWM frequency to 500 Hz
Rules
● Use Interrupts for Immediate Response: Avoid using polling in time-critical
applications; use interrupts for efficient event-driven programming.
● Set Correct Baud Rates for UART: Ensure matching baud rates between devices for
reliable communication.
● Address I2C Devices Correctly: Use the correct I2C addresses for each device on the
I2C bus to avoid conflicts.
● Match SPI Settings: Configure SPI mode, clock polarity, and phase to match the
peripheral requirements.
● Optimize Code for Each Communication Protocol: Understand the unique
characteristics of each protocol (UART, I2C, SPI) for optimal implementation.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Configure pin = Pin(pin_number, Pin.IN, button = Pin("A1", Pin.IN,
GPIO Pin.PULL_UP) Pin.PULL_UP)
with
Interrupt
2 Set pin.irq(trigger=Pin.IRQ_FALLING, button.irq(trigger=Pin.IRQ_FALLING,
Interrupt handler=callback) handler=callback)
Callback
3 Configure uart = UART(uart_number, uart = UART(2, baudrate=9600)
UART baudrate=baud_rate)
4 Send uart.write(data) uart.write("Hello")
UART
Data
5 Read data = uart.read() received_data = uart.read()
UART
Data
6 Configure i2c = I2C(i2c_number, i2c = I2C(1, scl=Pin("B8"),
I2C scl=Pin(scl_pin), sda=Pin("B9"))
sda=Pin(sda_pin))
7 Scan I2C devices = i2c.scan() devices = i2c.scan()
Bus
8 Send I2C i2c.writeto(address, data) i2c.writeto(0x40, b'\x01')
Data
9 Read I2C data = i2c.readfrom(address, data = i2c.readfrom(0x40, 2)
Data nbytes)
10 Configure spi = SPI(spi_number, spi = SPI(1, baudrate=500000)
SPI baudrate=baud_rate,
polarity=polarity, phase=phase)
11 Send SPI spi.write(data) spi.write(b'\x01\x02')
Data
12 Read SPI data = spi.read(nbytes) data = spi.read(2)
Data
Topic Explanations
1. Configure GPIO with Interrupt
What is Configuring GPIO with Interrupt?
Interrupts allow the STM32 to respond immediately to changes in GPIO input, such as button
presses. By setting a GPIO pin with an interrupt, the microcontroller can pause normal execution
to respond to the event, and then resume normal operation.
Use Purpose
● Immediate Event Detection: Detects button presses, sensor triggers, or other input
changes in real-time.
● Avoid Polling: Reduces the need for constantly checking the pin state, saving
processing power.
Syntax
pin = Pin(pin_number, Pin.IN, Pin.PULL_UP)
pin.irq(trigger=Pin.IRQ_FALLING, handler=callback)
Syntax Explanation
● Pin: The GPIO class used to configure the pin as an input.
● pin_number: Identifier for the GPIO pin, such as "A1" .
● Pin.IN: Sets the pin as an input.
● Pin.PULL_UP: Adds a pull-up resistor to stabilize the input.
● irq(): Method to configure an interrupt on the pin.
● trigger: Specifies when the interrupt should activate, such as Pin.IRQ_FALLING (on
a low signal).
● handler: Function to call when the interrupt triggers.
Simple Code Example
from machine import Pin
import time
2. Configure UART
What is Configuring UART?
UART (Universal Asynchronous Receiver/Transmitter) is a communication protocol for serial
data exchange between the STM32 and other devices, such as computers, GPS modules, or
Bluetooth modules. UART is commonly used for sending and receiving data in text format.
Use Purpose
● Communicate with Other Devices: Sends data to and receives data from peripherals.
● Debugging and Monitoring: Transfers data between the STM32 and a serial monitor
on a computer.
Syntax
uart = UART(uart_number, baudrate=baud_rate)
Syntax Explanation
● UART: MicroPython class for configuring UART communication.
● uart_number: UART interface number on the STM32 (usually 1 , 2 , or 3 ).
● baudrate: Communication speed in bits per second, such as 9600 or 115200.
Simple Code Example
from machine import UART
uart = UART(2, baudrate=9600) # Set up UART2 with 9600 baud rate
Code Example Explanation
● Configures UART with 9600 Baud Rate: Prepares UART2 for communication at a
standard baud rate, allowing data to be transmitted or received.
Notes
● Ensure matching baud rates between devices for reliable communication.
● UART can be used to send and receive data continuously in a loop.
Warnings
● Use uart.read() carefully to avoid buffer overflow.
3. Configure I2C
What is Configuring I2C?
I2C (Inter-Integrated Circuit) is a protocol used for communication between multiple devices
over two wires: SDA (data) and SCL (clock). Each device has a unique address on the bus,
allowing multiple devices to communicate with the STM32.
Use Purpose
● Connect Multiple Peripherals: Interfaces with devices like sensors, displays, and
EEPROMs.
● Communicate Using Addressing: Each device has a unique address for selective
communication.
Syntax
i2c = I2C(i2c_number, scl=Pin(scl_pin), sda=Pin(sda_pin))
Syntax Explanation
● I2C: MicroPython class for configuring I2C communication.
● i2c_number: Specifies the I2C interface number.
● scl: Defines the clock line (SCL) pin.
● sda: Defines the data line (SDA) pin.
Simple Code Example
from machine import I2C, Pin
i2c = I2C(1, scl=Pin("B8"), sda=Pin("B9")) # Set up I2C1 with B8 (SCL) and B9 (SDA)
Code Example Explanation
● Sets Up I2C with SCL on B8 and SDA on B9: Configures I2C1 for communication
with external devices.
Notes
● Use i2c.scan() to detect devices and get their addresses.
● Devices on the I2C bus must have unique addresses.
Warnings
● Incorrect pin connections can cause communication failure.
4. Configure SPI
What is Configuring SPI?
SPI (Serial Peripheral Interface) is a synchronous protocol for high-speed communication
between devices. It uses three lines (MOSI, MISO, SCK) and often a fourth line (CS) for chip
select, enabling communication with one device at a time on the bus.
Use Purpose
● High-Speed Communication: Interfaces with devices like displays, memory chips,
and sensors requiring fast data transfer.
● Allows Multiple Devices: Uses chip select (CS) to communicate with multiple
peripherals.
Syntax
spi = SPI(spi_number, baudrate=baud_rate, polarity=polarity, phase=phase)
Syntax Explanation
● SPI: MicroPython class for configuring SPI communication.
● spi_number: Specifies the SPI interface number.
● baudrate: Communication speed.
● polarity: Sets the idle state of the clock line.
● phase: Determines the clock phase for data capture.
Simple Code Example
from machine import SPI, Pin
spi = SPI(1, baudrate=500000) # Set up SPI1 with 500 kHz baud rate
Code Example Explanation
● Configures SPI1 with 500 kHz Baud Rate: Prepares SPI1 for high-speed data
transfer.
Notes
● Configure polarity and phase to match device requirements.
● Use separate CS lines for each SPI device.
Warnings
● Incorrect settings for polarity and phase may lead to corrupted data.
while True:
# Check if data is available to read
if uart.any():
received_data = uart.read()
print("Received:", received_data)
Rules
● Use Delays Appropriately: Avoid excessive delays in real-time applications where
responsiveness is crucial.
● Use Time Measurement for Precise Control: Measure elapsed time for tasks like
benchmarking and event scheduling.
● Set RTC Correctly: Configure the RTC with the correct date and time to ensure
accurate timekeeping.
● Avoid Blocking Code: Consider non-blocking alternatives for time-sensitive
applications instead of traditional delays.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Delay time.sleep(seconds) time.sleep(1)
2 Millisecond time.sleep_ms(ms) time.sleep_ms(500)
Delay
3 Microsecond time.sleep_us(us) time.sleep_us(1000)
Delay
4 Measure start = start = time.ticks_ms(); elapsed
Elapsed Time time.ticks_ms() =
time.ticks_diff(time.ticks_ms(),
start)
5 Get Current time.ticks_ms() current_ms = time.ticks_ms()
Time in
Milliseconds
6 Get Current time.ticks_us() current_us = time.ticks_us()
Time in
Microseconds
7 Initialize rtc = RTC() rtc = RTC()
RTC
Topic Explanations
1. Delay
What is Delay?
A delay pauses the execution of the program for a specified time. It’s a simple way to control the
timing of tasks, such as blinking an LED or waiting for an event.
Use Purpose
● Control Task Timing: Delays are commonly used in loops for timing control, like
creating a blinking LED effect.
● Prevent Rapid Execution: Delays reduce CPU load by slowing down the execution of
specific tasks.
Syntax
time.sleep(seconds)
Syntax Explanation
● time: The MicroPython module for time-related functions.
● sleep(): Function that pauses program execution.
● seconds: The number of seconds to delay, specified as a floating-point value for sub-
second delays.
Simple Code Example
import time
time.sleep(1) # Pauses the program for 1 second
Code Example Explanation
● 1-Second Delay: Pauses execution for exactly one second.
Notes
● Delays can be fractional, such as time.sleep(0.5) for a half-second delay.
● Avoid long delays in time-sensitive applications.
Warnings
● Excessive delays can block other tasks and make the program unresponsive.
2. Millisecond Delay
What is Millisecond Delay?
A millisecond delay pauses the program for a specified number of milliseconds. This provides
finer control over timing in applications where a one-second delay is too long.
Use Purpose
● Precise Timing Control: Useful for creating short, precise delays.
● Control LED Blinking: Ideal for creating fast blink effects or timing events with
millisecond precision.
Syntax
time.sleep_ms(ms)
Syntax Explanation
● sleep_ms(): Function that pauses program execution in milliseconds.
● ms: Integer specifying the number of milliseconds to delay.
Simple Code Example
import time
time.sleep_ms(500) # Pauses the program for 500 milliseconds (0.5 seconds)
3. Microsecond Delay
What is Microsecond Delay?
A microsecond delay pauses the program for a specified number of microseconds. This is used
for extremely precise timing, typically in high-speed applications like signal generation.
Use Purpose
● High-Precision Timing: Useful for precise control over timing-sensitive tasks.
● Signal Generation: Ideal for bit-banging protocols or generating waveforms.
Syntax
time.sleep_us(us)
Syntax Explanation
● sleep_us(): Function that pauses program execution in microseconds.
● us: Integer specifying the number of microseconds to delay.
Simple Code Example
import time
time.sleep_us(1000) # Pauses the program for 1000 microseconds (1 millisecond)
Code Example Explanation
● 1 ms Delay in Microseconds: Provides a 1-millisecond delay with microsecond
precision.
Notes
● Use only when necessary, as microsecond delays consume significant processing
power.
● Ideal for precise timing applications, but avoid in non-critical code.
Warnings
● High-frequency delays can reduce CPU efficiency for other tasks.
5. Initialize RTC
What is RTC Initialization?
The Real-Time Clock (RTC) is a hardware clock that keeps track of date and time. Initializing
the RTC on the STM32 allows accurate timekeeping, even when the microcontroller is in low-
power modes.
Use Purpose
● Time and Date Management: Keeps track of real-world time and date.
● Event Scheduling: Useful for applications that need to log data with timestamps.
Syntax
rtc = RTC()
Syntax Explanation
● RTC: MicroPython class for configuring the Real-Time Clock.
● rtc: The object created for handling RTC operations.
Simple Code Example
from machine import RTC
rtc = RTC() # Initialize RTC
Syntax Explanation
● datetime(): Method for setting the RTC date and time.
● year, month, day, weekday: Date components.
● hour, minute, second, subseconds: Time components.
Simple Code Example
rtc.datetime((2024, 11, 10, 1, 15, 30, 45, 0)) # Set date and time
Syntax Explanation
● rtc: The RTC object.
● datetime(): Method to read the current RTC date and time, returning a tuple with date
and time components.
Simple Code Example
current_time = rtc.datetime()
print("Current Time:", current_time)
# Initialize RTC
rtc = RTC()
rtc.datetime((2024, 11, 10, 1, 15, 30, 0, 0)) # Set date and time
while True:
# Calculate elapsed time in seconds
elapsed_ms = time.ticks_diff(time.ticks_ms(), start)
elapsed_s = elapsed_ms / 1000
Rules
● Use Uppercase for Constants: Write constants in uppercase letters to distinguish them
from variables.
● Initialize Variables Before Use: Avoid errors by always assigning an initial value to
variables before using them.
● Choose Descriptive Names: Use meaningful names for constants and variables to
improve code readability.
● Use Constants for Fixed Values: Replace hardcoded values with constants for easier
maintenance and understanding.
● Update Variables as Needed: Variables can change as the program executes, while
constants should remain fixed.
Syntax Table
Serial Topic Code Snippet Simple
No Example
1 Define a CONSTANT_NAME = PI = 3.14159
Constant value
2 Declare a variable_name = value counter = 0
Variable
3 Reassign a variable_name = counter = 5
Variable new_value
4 Define var1, var2 = value1, x, y = 10, 20
Multiple value2
Variables
5 Global global variable_name global counter
Variable within a function
Declaration
6 Local Variable variable_name inside a def func():
Declaration function local_var = 5
7 Increment a variable_name += counter += 1
Variable increment_value
Topic Explanations
1. Define a Constant
What is a Constant?
A constant is a fixed value that doesn’t change throughout the program. Constants are useful for
storing values that are referenced multiple times and should remain consistent, such as
configuration settings or mathematical constants.
Use Purpose
● Define Unchanging Values: Constants improve code clarity by representing fixed
values that don’t need to be reassigned.
● Avoid Magic Numbers: Replace hardcoded values with named constants to make code
easier to read and maintain.
Syntax
CONSTANT_NAME = value
Syntax Explanation
● CONSTANT_NAME: Name of the constant, typically in uppercase letters to indicate
it is fixed. Use meaningful names that describe the purpose of the constant.
○ Examples: PI , MAX_SPEED , LED_BRIGHTNESS_LIMIT .
● = (Assignment Operator): Used to assign a fixed value to the constant.
● value: The unchanging data assigned to the constant. This value can be of any data
type, such as integers, floats, strings, or lists.
● Uppercase Convention: Constants are typically written in uppercase to signal that they
are not meant to change.
● Descriptive Names: Choose names that clearly indicate the constant’s purpose in the
code, making it easy for other programmers to understand its use.
Simple Code Example
PI = 3.14159 # Define the mathematical constant pi
2. Declare a Variable
What is Variable Declaration?
Declaring a variable in MicroPython means creating a named reference to store data. Unlike
constants, variables can change during the program execution, making them suitable for values
that vary over time.
Use Purpose
● Store Dynamic Data: Variables hold data that may need to be updated, such as sensor
readings, user inputs, or calculation results.
● Track Program State: Variables are often used to track counters, flags, or status
information.
Syntax
variable_name = value
Syntax Explanation
● variable_name: The name given to the variable, which should be descriptive of its
purpose. Variable names should be written in lowercase or lowercase with
underscores.
○ Examples: counter , sensor_value , user_name .
● = (Assignment Operator): Used to assign an initial value to the variable.
● value: The initial value assigned to the variable, which can be of any data type (e.g.,
integers, floats, strings, or lists) and can be modified later.
● Descriptive Naming: The variable name should reflect its role or the data it holds,
making the code more readable.
● Initial Value: Variables should be initialized to a starting value before they are used in
the program, as uninitialized variables can cause runtime errors.
Simple Code Example
counter = 0 # Initialize a counter variable with a starting value of 0
3. Reassign a Variable
What is Variable Reassignment?
Variable reassignment is updating the value stored in a variable with a new one. Reassigning
variables allows the program to store new data dynamically as conditions change.
Use Purpose
● Update Program State: Modify values to keep track of changing data, such as a count,
position, or user input.
● Respond to Inputs: Change variable values based on interactions with the environment
or user inputs.
Syntax
variable_name = new_value
Syntax Explanation
● variable_name: Name of the variable to be updated. The name should match an
existing variable that has been previously declared.
○ Examples: counter , sensor_value , user_name .
● = (Assignment Operator): Used to assign a new value to the variable.
● new_value: The new data or value assigned to the variable, replacing the previous
value.
● Reassignable Values: Unlike constants, variables can be reassigned with new data as
needed, allowing flexibility in programming.
● Single Line Reassignment: In MicroPython, reassignment is done directly on a single
line without additional syntax.
Simple Code Example
counter = 0 # Initial value
counter = 5 # Update counter to a new value
Syntax Explanation
● var1, var2: Names of the variables being initialized. Each name should be descriptive
of the variable’s purpose.
○ Examples: x, y , width, height , min_val, max_val .
● = (Assignment Operator): Used to assign values to multiple variables simultaneously.
● value1, value2: Initial values assigned to each variable. The values can be of any data
type and do not need to match in type.
● Paired Initialization: The number of variables on the left side of = must match the
number of values on the right.
● Tuple Unpacking: In Python, this method is also known as tuple unpacking when used
with tuples or lists.
Simple Code Example
x, y = 10, 20 # Sets x to 10 and y to 20
Check Output
Turning the potentiometer should adjust the LED brightness, with a maximum brightness level
set by MAX_BRIGHTNESS .
Rules
● Choose the Right Data Type for the Task: Use lists for ordered data, dictionaries for
key-value pairs, and tuples for fixed collections.
● Use Integer and Float for Numeric Operations: Ensure that calculations are handled
with the correct number type.
● Apply String Methods Carefully: Strings are immutable; operations return new
strings rather than modifying the original.
● Avoid Mixing Data Types: Mixing types in operations can lead to unexpected results
or errors.
● Use Boolean for True/False Conditions: Use booleans for conditions and flags in
control flow.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Integer variable_name = 10 count = 10
2 Float variable_name = 3.14 pi = 3.14159
3 String variable_name = "text" name = "Alice"
4 List variable_name = [item1, numbers = [1, 2, 3,
item2, item3] 4]
5 Tuple variable_name = (item1, coordinates = (10,
item2, item3) 20)
6 Dictionary variable_name = {key1: student = {"name":
value1, key2: value2} "Alice", "age": 20}
7 Boolean variable_name = True is_active = True
or False
Topic Explanations
1. Integer
What is an Integer?
An integer is a whole number without any decimal or fractional part. It can be positive, negative,
or zero and is often used in counting, indexing, and arithmetic operations.
Use Purpose
● Counting and Indexing: Ideal for tracking counts, indices, or positions.
● Basic Arithmetic: Used in calculations that do not require fractions or decimals.
Syntax
variable_name = integer_value
Syntax Explanation
● variable_name: Name of the variable to store the integer.
○ Examples: count , index , num_apples .
● = (Assignment Operator): Used to assign an integer value to the variable.
● integer_value: An integer without a decimal, such as 10 , -5 , or 0 .
● Integer Data Type: Used for numbers without decimals, ideal for discrete quantities.
● Assignment: Assign the integer directly to the variable.
Simple Code Example
count = 10 # Initialize count as an integer with value 10
2. Float
What is a Float?
A float is a number with a decimal point, allowing representation of fractional values. Floats are
commonly used in calculations that require precision, such as measurements or percentages.
Use Purpose
● Precision Calculations: Used for values that include fractions, such as pi or
percentages.
● Scientific Data: Ideal for measurements and calculations requiring decimal places.
Syntax
variable_name = float_value
Syntax Explanation
● variable_name: Name of the variable that will hold the float value.
○ Examples: pi , temperature , weight .
● = (Assignment Operator): Assigns a float value to the variable.
● float_value: A number with a decimal, such as 3.14 , -1.5 , or 0.0 .
● Floating-Point Data Type: Supports decimal places and fractions for precise values.
● Decimal Representation: Floats must include a decimal point (e.g., 3.0 instead of
3 ).
Simple Code Example
pi = 3.14159 # Assigns the value of pi as a float
3. String
What is a String?
A string is a sequence of characters, such as text or alphanumeric data, enclosed in single or
double quotes. Strings are often used for names, messages, or any data that includes text.
Use Purpose
● Store Text Data: Use strings for names, messages, and identifiers.
● Display Information: Ideal for outputting readable information to the user.
Syntax
variable_name = "string_value"
Syntax Explanation
● variable_name: Name of the variable holding the string.
○ Examples: name , message , status .
● = (Assignment Operator): Assigns the string value to the variable.
● string_value: Text enclosed in single or double quotes, such as "Hello" or '123' .
● Text Data Type: Strings represent text or character sequences.
● Quotation Marks: Strings must be enclosed in single ( ' ) or double ( " ) quotes.
Simple Code Example
name = "Alice" # Assigns a string with the name Alice
Code Example Explanation
● Stores Name as a String: The name variable holds the text "Alice" and can be
displayed or manipulated as needed.
Notes
● Strings are immutable; methods return new strings instead of modifying the original.
● Common operations include concatenation ( + ), slicing ( [] ), and length checking
( len() ).
Warnings
● Strings with both single and double quotes inside require escape characters (e.g., "She
said, \"Hello\"" ).
4. List
What is a List?
A list is an ordered collection of elements, which can be of different data types. Lists are
mutable, meaning items can be added, removed, or changed.
Use Purpose
● Store Collections of Data: Use lists to group related items, such as sensor readings or
user inputs.
● Dynamic Data Structures: Lists can change size, making them ideal for variable-
length data.
Syntax
variable_name = [item1, item2, item3]
Syntax Explanation
● variable_name: Name of the list variable.
○ Examples: numbers , names , temperatures .
● = (Assignment Operator): Assigns a list of items to the variable.
● [item1, item2, item3]: List elements enclosed in square brackets, separated by
commas. Elements can be any data type.
● Ordered Collection: Lists maintain the order of elements as inserted.
● Mutable Structure: Elements can be added, removed, or changed in the list.
Simple Code Example
numbers = [1, 2, 3, 4] # List of integers
Syntax Explanation
● variable_name: Name of the tuple variable.
○ Examples: coordinates , point , dimensions .
● = (Assignment Operator): Assigns the tuple of elements to the variable.
● (item1, item2, item3): Tuple elements enclosed in parentheses, separated by commas.
● Immutable Structure: Once defined, the elements of a tuple cannot be changed.
● Fixed Length: Tuples have a set length, which can’t be altered.
Simple Code Example
coordinates = (10, 20) # Tuple with x and y coordinates
Code Example Explanation
● Defines Coordinates as a Tuple: coordinates holds fixed values for x and y positions.
Notes
● Tuples are commonly used to group related but unchangeable data.
● Access elements with index syntax, like coordinates[0] .
# Variables
data_log = [] # List to store readings
count = 0 # Count of readings
# Increment count
count += 1
Rules
● Convert Data as Needed: Convert data types based on usage requirements, such as
converting integers to strings for display.
● Use Integer and Float Conversions for Calculations: Convert values to the
appropriate numeric type for mathematical operations.
● Convert Strings for Display: Use string conversion when displaying numbers or non-
string data.
● Avoid Unnecessary Conversions: Only convert data types when necessary to save
processing time and memory.
● Use Boolean Conversion for Conditions: Convert values to booleans for conditions
and control flow.
Syntax Table
Serial Topic Code Snippet Simple
No Example
1 Integer int(value) int("10")
Conversion
2 Float Conversion float(value) float("3.14")
3 String Conversion str(value) str(100)
4 Boolean bool(value) bool(1)
Conversion
5 List to Tuple tuple(list_variable) tuple([1, 2,
Conversion 3])
6 Tuple to List list(tuple_variable) list((4, 5, 6))
Conversion
7 ASCII Character ord(char) ord("A")
to Integer
8 Integer to ASCII chr(integer) chr(65)
Character
Topic Explanations
1. Integer Conversion
What is Integer Conversion?
Integer conversion changes a value to an integer type. It’s commonly used when you need to
perform arithmetic or when a floating-point or string value needs to be treated as a whole
number.
Use Purpose
● Perform Calculations: Convert values to integers to perform operations like counting,
indexing, and other discrete calculations.
● Remove Decimal Points: Converting a float to an integer discards the decimal part.
Syntax
int(value)
Syntax Explanation
● int(): The built-in function for converting a value to an integer.
● value: The input data to convert, which can be a float, string representing an integer, or
boolean.
○ Examples: "10" , 3.14 , True .
● String or Float to Integer: Converts compatible strings or floats by truncating decimal
points.
● Boolean to Integer: Converts True to 1 and False to 0 .
Simple Code Example
number = int("10") # Converts the string "10" to an integer 10
2. Float Conversion
What is Float Conversion?
Float conversion changes a value to a floating-point type, which supports decimal places. This is
useful when more precision is needed for calculations.
Use Purpose
● Precise Calculations: Converts values to floats to include decimal places in
calculations.
● Convert Numeric Strings to Floats: Converts compatible strings to floats for
arithmetic.
Syntax
float(value)
Syntax Explanation
● float(): The function for converting a value to a float.
● value: The input data to convert, which can be an integer or a string representing a
float.
○ Examples: "3.14" , 100 , "0.5" .
● String or Integer to Float: Allows precision in calculations by representing numbers
with decimals.
● Whole Numbers: Whole numbers can be converted to floats, resulting in values like
3.0 or 100.0 .
Simple Code Example
pi_value = float("3.14") # Converts the string "3.14" to a float
3. String Conversion
What is String Conversion?
String conversion changes a value to a string, enabling text representation of numbers, booleans,
lists, and more.
Use Purpose
● Display Non-String Data: Use string conversion to prepare data for display in text
format.
● Combine Text and Numbers: Convert numbers to strings for concatenation with other
text.
Syntax
str(value)
Syntax Explanation
● str(): The built-in function for converting values to strings.
● value: The input data to convert, which can be any data type, including integers, floats,
booleans, and lists.
○ Examples: 100 , 3.14 , [1, 2, 3] .
● Non-String to String: Transforms data into string format for display or storage.
● Universal Conversion: Almost all data types can be converted to a string.
Simple Code Example
text_value = str(100) # Converts the integer 100 to the string "100"
Syntax Explanation
● bool(): The function for converting a value to a boolean.
● value: The input data to convert, which can be any type, including integers, strings,
lists, and floats.
○ Examples: 0 , "hello" , [] .
● Non-Zero and Non-Empty to True: All non-zero numbers, non-empty strings, and
non-empty collections are True .
● Zero and Empty to False: Zero, empty collections, None , and False are converted
to False .
Simple Code Example
is_active = bool(1) # Converts the integer 1 to boolean True
# Constants
NUM_READINGS = 5
# Variables
data_log = [] # List to store formatted sensor readings
count = 0 # Counter for readings
Rules
● Use Conditions for Decision-Making: Use if , elif , and else statements to control
program flow based on conditions.
● Choose the Right Loop Type: Use for loops for a fixed number of iterations and
while loops for condition-based repetition.
● Define Functions for Reusability: Functions make code modular and reusable,
improving readability.
● Avoid Excessive Nesting: Excessive nested loops and conditions reduce code
readability.
● Use break and continue Judiciously: Use these to control loop behavior, but avoid
excessive use for better readability.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 if if condition: if temperature > 25:
Statement
2 elif elif condition: elif temperature == 25:
Statement
3 else else: else:
Statement
4 for Loop for item in iterable: for i in range(5):
5 while Loop while condition: while sensor_value <
500:
6 break break if x > 10: break
7 continue continue if x == 0: continue
Topic Explanations
1. if Statement
What is an if Statement?
The if statement is a conditional structure that runs specific code when a given condition is
True . If the condition evaluates as True , the code block within the if statement executes; if
not, the program skips it.
Use Purpose
● Make Decisions: Run code selectively when certain conditions are met.
● Control Flow: Directs program flow based on variables or input values.
Syntax
if condition:
# Code to execute if condition is True
Syntax Explanation
● if: The keyword starting the conditional statement.
● condition: An expression that evaluates to True or False .
● : (Colon): Starts the indented block of code.
● Indented Block: The code that runs if the condition is True . Proper indentation is
required in Python.
Simple Code Example
temperature = 30
if temperature > 25:
print("It's hot!")
2. elif Statement
What is an elif Statement?
The elif statement checks additional conditions after an initial if condition has evaluated as
False . It allows for multiple conditions to be tested in sequence.
Use Purpose
● Check Multiple Conditions: Allows checking multiple conditions in sequence.
● Provide Alternatives: Executes different blocks of code depending on conditions.
Syntax
if condition1:
# Code for condition1
elif condition2:
# Code for condition2
Syntax Explanation
● elif: Short for "else if," used to add an alternative condition.
● condition2: The new condition checked if condition1 is False .
● Indented Block: Code to execute if the elif condition is True .
Simple Code Example
temperature = 25
if temperature > 25:
print("It's hot!")
elif temperature == 25:
print("It's moderate.")
3. else Statement
What is an else Statement?
The else statement provides a default block of code that executes when no preceding if or elif
conditions are met.
Use Purpose
● Default Action: Specifies a default action when no conditions are satisfied.
● Catch-All: Ensures code execution even if no conditions are True .
Syntax
if condition1:
# Code for condition1
else:
# Code if no conditions are met
Syntax Explanation
● else: Begins the default block of code.
● : (Colon): Starts the else block.
● Indented Block: Code that runs if all other conditions are False .
Simple Code Example
temperature = 20
if temperature > 25:
print("It's hot!")
else:
print("It's cold.")
4. for Loop
What is a for Loop?
A for loop iterates over items in a sequence, such as a list, tuple, or range, and executes code for
each item.
Use Purpose
● Iterate Over Sequences: Perform actions on each item in a collection.
● Fixed Iterations: Use for tasks with a predetermined number of repetitions.
Syntax
for item in iterable:
# Code to execute for each item
Syntax Explanation
● for: Starts the loop.
● item: Represents each item in the sequence during each iteration.
● in: Keyword specifying the sequence to iterate over.
● iterable: A sequence, like a list or range, to loop through.
Simple Code Example
for i in range(5):
print("Iteration:", i)
5. while Loop
What is a while Loop?
A while loop executes code as long as a specified condition remains True . This loop is useful
when the number of iterations is not predetermined.
Use Purpose
● Conditional Repetition: Repeat actions until a condition changes.
● Dynamic Loops: Ideal for loops that depend on changing conditions.
Syntax
while condition:
# Code to execute while condition is True
Syntax Explanation
● while: Starts the loop.
● condition: Expression controlling the loop; if True , the loop continues.
● Indented Block: Code to execute as long as the condition is True .
Simple Code Example
counter = 0
while counter < 5:
print("Counter:", counter)
counter += 1
6. break
What is break ?
The break statement immediately exits the loop, regardless of the loop condition. It is often
used to terminate loops early based on a specific condition.
Use Purpose
● Exit Loop Prematurely: Allows ending a loop when a condition is met.
● Optimize Loops: Avoid unnecessary iterations once a goal is achieved.
Syntax
for item in iterable:
if condition:
break
Syntax Explanation
● for/while loop: break can be used in both for and while loops.
● condition: Specifies when to break out of the loop.
● break: Ends the loop immediately when the condition is met.
Simple Code Example
for i in range(10):
if i == 5:
break
print(i)
Syntax Explanation
● for/while loop: continue can be used in both for and while loops.
● condition: Specifies when to skip the current iteration.
● continue: Moves to the next iteration without executing the remaining loop code.
Simple Code Example
for i in range(5):
if i == 2:
continue
print(i)
while True:
# Read sensor value
sensor_value = potentiometer.read_u16()
Rules
● Use Correct Operators for Calculations: Choose the appropriate operator (e.g., + , -
, * , / ) based on the calculation type.
● Avoid Integer Division When Decimal Results Are Needed: Use / for floating-point
division and // for integer-only results.
● Apply Parentheses for Clarity: Use parentheses to ensure calculations are performed
in the correct order.
● Combine Operators for Complex Calculations: Chain operators in a single
expression for more complex math.
● Be Mindful of Division by Zero: Division by zero raises an error; use conditions to
prevent it.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Addition result = a + b sum = 10 + 5
2 Subtraction result = a - b difference = 10 - 5
3 Multiplication result = a * b product = 10 * 5
4 Division result = a / b quotient = 10 / 5
5 Floor Division result = a // b quotient = 10 // 3
6 Modulus result = a % b remainder = 10 %
3
7 Exponentiation result = a ** b power = 2 ** 3
8 Using Parentheses result = (a + b) * c total = (10 + 5) * 2
Topic Explanations
1. Addition ( + )
What is Addition?
The addition operator ( + ) adds two numbers together. It is one of the most basic operations and
is used in many types of calculations, such as summing sensor readings or combining counts.
Use Purpose
● Combine Values: Used to add numerical values.
● Summing Data: Useful for totals and cumulative sums.
Syntax
result = a + b
Syntax Explanation
● a + b: Adds two values, a and b , and stores the result in result .
● + (Addition Operator): Performs addition between a and b .
Simple Code Example
a = 10
b=5
sum_result = a + b # Result is 15
2. Subtraction ( - )
What is Subtraction?
The subtraction operator ( - ) subtracts one number from another. It is commonly used for
calculating differences, adjusting counts, and reducing values.
Use Purpose
● Calculate Differences: Finds the difference between values.
● Decrease Counts: Useful for reducing a total by a certain amount.
Syntax
result = a - b
Syntax Explanation
● a - b: Subtracts b from a and stores the result in result .
● - (Subtraction Operator): Performs subtraction between a and b .
Simple Code Example
a = 10
b=5
difference = a - b # Result is 5
3. Multiplication ( * )
What is Multiplication?
The multiplication operator ( * ) multiplies two numbers. It is used for scaling values, calculating
products, and generating sequences.
Use Purpose
● Calculate Products: Finds the product of two values.
● Scale Values: Adjusts values by multiplying with a constant.
Syntax
result = a * b
Syntax Explanation
● a * b: Multiplies a and b and stores the result in result .
● * (Multiplication Operator): Performs multiplication between a and b .
Simple Code Example
a = 10
b=5
product = a * b # Result is 50
4. Division ( / )
What is Division?
The division operator ( / ) divides one number by another, yielding a floating-point result. It’s
commonly used in calculations that require precision, such as averaging values.
Use Purpose
● Calculate Ratios: Finds the ratio between two values.
● Average Data: Used in dividing sums to find averages.
Syntax
result = a / b
Syntax Explanation
● a / b: Divides a by b and stores the result in result .
● / (Division Operator): Performs division between a and b .
Simple Code Example
a = 10
b=5
quotient = a / b # Result is 2.0
6. Modulus ( % )
What is Modulus?
The modulus operator ( % ) returns the remainder of a division. It’s commonly used for
determining if a number is even or odd and for cyclic calculations.
Use Purpose
● Find Remainders: Returns the remainder after division.
● Check Even/Odd: number % 2 == 0 for even numbers, number % 2 == 1 for odd
numbers.
Syntax
result = a % b
Syntax Explanation
● a % b: Divides a by b and returns the remainder.
● % (Modulus Operator): Finds the remainder of division.
Simple Code Example
a = 10
b=3
remainder = a % b # Result is 1
7. Exponentiation ( ** )
What is Exponentiation?
The exponentiation operator ( ** ) raises a number to the power of another. This is commonly
used in scientific calculations and generating powers.
Use Purpose
● Calculate Powers: Raise numbers to powers.
● Square and Cube Values: Calculate squares, cubes, and other powers.
Syntax
result = a ** b
Syntax Explanation
● a ** b: Raises a to the power of b and stores the result in result .
● ** (Exponentiation Operator): Performs exponentiation on a and b .
Simple Code Example
a=2
b=3
power = a ** b # Result is 8
Syntax Explanation
● (a + b): Parentheses around a + b ensure this operation is performed first.
● * c: Multiplies the result of (a + b) by c .
Simple Code Example
a = 10
b=5
c=2
total = (a + b) * c # Result is 30
while True:
# Read sensor value
sensor_value = potentiometer.read_u16()
# Display calculations
print(f"Sensor Value: {sensor_value}, Percentage: {percentage:.2f}%, Brightness: {brightness}")
Rules
● Use Comparison Operators for Decision-Making: Apply these operators in
conditions to control program flow based on relationships.
● Combine with Logical Operators: Use logical operators to evaluate multiple
comparisons simultaneously.
● Avoid Unnecessary Comparisons: Only compare values when necessary to maintain
efficiency.
● Ensure Compatible Data Types: Use comparison operators on compatible data types
to avoid errors.
● Use Comparison Results in Conditions: Comparison operators return booleans, which
can be used directly in if , while , and other conditional statements.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Equal to ( == ) result = a == b is_equal = (10 == 5)
2 Not equal to result = a != b not_equal = (10 != 5)
( != )
3 Greater than result = a > b is_greater = (10 > 5)
(>)
4 Less than ( < ) result = a < b is_less = (10 < 5)
5 Greater than or result = a >= b is_greater_equal = (10
equal to ( >= ) >= 5)
6 Less than or result = a <= b is_less_equal = (10 <=
equal to ( <= ) 5)
7 Using if a == b: if sensor_value ==
Comparison in target:
if
Topic Explanations
1. Equal to ( == )
What is == ?
The == operator checks if two values are equal. It returns True if the values are the same, and
False otherwise. This operator is often used to confirm a specific condition or state in
conditional statements.
Use Purpose
● Check Equality: Used to verify if two values are identical.
● Control Flow: Often used in if statements to branch code execution.
Syntax
result = a == b
Syntax Explanation
● a == b: Compares a and b for equality.
● == (Equal to Operator): Returns True if a and b are equal; False otherwise.
Simple Code Example
a = 10
b=5
is_equal = (a == b) # Result is False
2. Not equal to ( != )
What is != ?
The != operator checks if two values are not equal. It returns True if the values are different,
and False if they are the same.
Use Purpose
● Check Inequality: Used to determine if two values are not identical.
● Control Flow: Commonly used to handle cases where values differ.
Syntax
result = a != b
Syntax Explanation
● a != b: Checks if a and b are not equal.
● != (Not Equal to Operator): Returns True if a and b are not equal; False
otherwise.
Simple Code Example
a = 10
b=5
not_equal = (a != b) # Result is True
Code Example Explanation
● Compares 10 and 5: Since 10 is not equal to 5, not_equal is True .
Notes
● != can be used with various data types, including numbers and strings.
● Often used in loops and conditions.
Warnings
● Do not use != with data types that cannot be directly compared, as it may cause errors.
Syntax Explanation
● a > b: Checks if a is greater than b .
● > (Greater Than Operator): Returns True if a is greater than b ; False otherwise.
Simple Code Example
a = 10
b=5
is_greater = (a > b) # Result is True
Syntax Explanation
● a < b: Checks if a is less than b .
● < (Less Than Operator): Returns True if a is less than b ; False otherwise.
Simple Code Example
a = 10
b=5
is_less = (a < b) # Result is False
Syntax Explanation
● a >= b: Checks if a is greater than or equal to b .
● >= (Greater Than or Equal to Operator): Returns True if a is greater than or equal
to b ; False otherwise.
Simple Code Example
a = 10
b=5
is_greater_equal = (a >= b) # Result is True
Syntax Explanation
● a <= b: Checks if a is less than or equal to b .
● <= (Less Than or Equal to Operator): Returns True if a is less than or equal to b ;
False otherwise.
Simple Code Example
a = 10
b=5
is_less_equal = (a <= b) # Result is False
7. Using Comparison in if
What is Comparison in if ?
Comparison operators are often used directly in if statements to evaluate conditions and control
program flow. The if statement will execute the code block only if the comparison condition is
True .
Use Purpose
● Control Program Flow: Allows branching based on specific conditions.
● Evaluate Conditions: Used in control structures like if , while , and loops.
Syntax
if a == b:
# Code to execute if a equals b
Syntax Explanation
● if: Starts the conditional statement.
● a == b: Condition to check if a equals b .
● : (Colon): Starts the indented block for the if statement.
● Indented Block: Code executed if the condition is True .
Simple Code Example
sensor_value = 500
target = 500
if sensor_value == target:
print("Sensor is at target value.")
Notes
● Comparison conditions in if statements determine which code executes.
● Can be combined with elif and else for more complex branching.
Warnings
● Ensure conditions are logically correct to avoid unintended behavior.
while True:
# Read sensor value
sensor_value = potentiometer.read_u16()
Rules
● Use and to Require Multiple Conditions: Use and when all conditions need to be
True for the entire expression to be True .
● Use or to Allow Any Condition: Use or when at least one condition needs to be
True for the expression to be True .
● Use not to Invert Conditions: Use not to negate or invert a condition, turning True
to False and vice versa.
● Combine Boolean Operators: Combine and , or , and not for complex logical
expressions.
● Use Parentheses for Clarity: When using multiple Boolean operators, use parentheses
to ensure the correct order of operations.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 and Operator result = condition1 is_valid = (age > 18 and
and condition2 has_license)
2 or Operator result = condition1 can_enter = (age >= 18
or condition2 or with_parent)
3 not Operator result = not is_minor = not (age >=
condition 18)
4 Combining (condition1 and (age > 18 and
Boolean condition2) or has_license) or
Operators condition3 with_supervisor
5 Using if (condition1 and if (sensor1 > 500 and
Boolean condition2): sensor2 < 500):
Operators in
if
Topic Explanations
1. and Operator
What is the and Operator?
The and operator checks if multiple conditions are all True . It returns True only if all
conditions connected by and are True ; otherwise, it returns False .
Use Purpose
● Require All Conditions: Use and when all conditions must be met for the result to be
True .
● Combine Conditions: Enables multiple requirements in a single expression.
Syntax
result = condition1 and condition2
Syntax Explanation
● condition1 and condition2: Evaluates to True if both condition1 and condition2
are True .
● and (Logical AND Operator): Connects two conditions, resulting in True only if
both conditions are met.
Simple Code Example
age = 20
has_license = True
is_valid_driver = (age >= 18 and has_license) # Result is True
2. or Operator
What is the or Operator?
The or operator checks if at least one of multiple conditions is True . It returns True if any
condition is True , and only returns False if all conditions are False .
Use Purpose
● Allow Any Condition: Use or when any one of multiple conditions can satisfy the
requirement.
● Combine Alternative Conditions: Enables flexibility by accepting any one of multiple
conditions.
Syntax
result = condition1 or condition2
Syntax Explanation
● condition1 or condition2: Evaluates to True if either condition1 or condition2 is
True .
● or (Logical OR Operator): Connects two conditions, resulting in True if at least one
condition is met.
Simple Code Example
age = 16
with_parent = True
can_enter = (age >= 18 or with_parent) # Result is True
Syntax Explanation
● not condition: Evaluates to True if condition is False , and to False if condition is
True .
● not (Logical NOT Operator): Inverts the condition’s boolean value.
Simple Code Example
age = 15
is_minor = not (age >= 18) # Result is True
Syntax Explanation
● (condition1 and condition2) or condition3: Combines and and or operators,
evaluated based on parentheses.
● Logical Operators: Combine multiple Boolean operators in a single expression for
detailed conditions.
Simple Code Example
age = 20
has_license = True
with_supervisor = False
can_drive = (age >= 18 and has_license) or with_supervisor # Result is True
Syntax Explanation
● if (condition1 and condition2): Evaluates if both conditions are True .
● : (Colon): Starts the indented block for the if statement.
● Indented Block: Code executed if the conditions are met.
Simple Code Example
sensor1 = 600
sensor2 = 400
if (sensor1 > 500 and sensor2 < 500):
print("Sensor values are within the desired range.")
while True:
# Read values from both potentiometers
sensor1_value = pot1.read_u16()
sensor2_value = pot2.read_u16()
Rules
● Use Compound Operators for Efficiency: Compound operators simplify code by
combining arithmetic and assignment in a single step.
● Choose the Right Operator: Use += , -= , *= , /= , //= , %= , and **= based on
the type of calculation.
● Use in Loops and Iterations: Compound operators are particularly useful in loops for
updating values.
● Be Mindful of Data Types: Ensure compatibility with the data type of the variable to
avoid errors.
● Avoid Overuse in Complex Expressions: Excessive use can make code harder to read
if overused in complex calculations.
Syntax Table
Serial Topic Code Snippet Simple
No Example
1 Addition Assignment variable += counter += 1
( += ) value
2 Subtraction Assignment ( - variable -= balance -=
=) value 100
3 Multiplication Assignment variable *= total *= 2
( *= ) value
4 Division Assignment ( /= ) variable /= average /= 10
value
5 Floor Division Assignment variable //= num_items
( //= ) value //= 3
6 Modulus Assignment variable %= remainder
( %= ) value %= 4
7 Exponentiation variable **= power **= 2
Assignment ( **= ) value
Topic Explanations
1. Addition Assignment ( += )
What is Addition Assignment?
The addition assignment operator ( += ) adds a specified value to a variable and then assigns the
result back to the same variable. It is commonly used for counters and cumulative sums.
Use Purpose
● Increment Counters: Efficiently increases counters or accumulates totals.
● Simplify Accumulation: Adds values to a variable without repeating the variable
name.
Syntax
variable += value
Syntax Explanation
● variable += value: Adds value to variable and assigns the result back to variable .
● += (Addition Assignment Operator): Combines addition and assignment.
Simple Code Example
counter = 0
counter += 1 # Result is 1
2. Subtraction Assignment ( -= )
What is Subtraction Assignment?
The subtraction assignment operator ( -= ) subtracts a specified value from a variable and assigns
the result back to the same variable.
Use Purpose
● Decrement Counters: Efficiently decreases counters or reduces totals.
● Simplify Reduction: Reduces values in a variable without repeating the variable name.
Syntax
variable -= value
Syntax Explanation
● variable -= value: Subtracts value from variable and assigns the result back to
variable .
● -= (Subtraction Assignment Operator): Combines subtraction and assignment.
Simple Code Example
balance = 1000
balance -= 100 # Result is 900
3. Multiplication Assignment ( *= )
What is Multiplication Assignment?
The multiplication assignment operator ( *= ) multiplies a variable by a specified value and
assigns the result back to the variable.
Use Purpose
● Scale Values: Useful for scaling values or calculations requiring repeated
multiplication.
● Simplify Multiplication: Multiplies a variable by a factor without repeating the
variable name.
Syntax
variable *= value
Syntax Explanation
● *variable = value: Multiplies variable by value and assigns the result back to
variable .
● *= (Multiplication Assignment Operator): Combines multiplication and assignment.
Simple Code Example
total = 50
total *= 2 # Result is 100
4. Division Assignment ( /= )
What is Division Assignment?
The division assignment operator ( /= ) divides a variable by a specified value and assigns the
result back to the variable. This operation always produces a floating-point result.
Use Purpose
● Divide Totals: Useful for averaging or reducing values in iterative calculations.
● Simplify Division: Divides a variable by a divisor without repeating the variable name.
Syntax
variable /= value
Syntax Explanation
● variable /= value: Divides variable by value and assigns the result back to variable .
● /= (Division Assignment Operator): Combines division and assignment.
Simple Code Example
average = 100
average /= 10 # Result is 10.0
Syntax
variable //= value
Syntax Explanation
● variable //= value: Divides variable by value , rounds down, and assigns the result
back to variable .
● //= (Floor Division Assignment Operator): Combines floor division and assignment.
Simple Code Example
num_items = 10
num_items //= 3 # Result is 3
6. Modulus Assignment ( %= )
What is Modulus Assignment?
The modulus assignment operator ( %= ) finds the remainder when a variable is divided by a
specified value and assigns the result back to the variable.
Use Purpose
● Calculate Remainders: Useful for cyclic calculations and determining divisibility.
● Simplify Modulus Calculation: Finds the remainder without repeating the variable
name.
Syntax
variable %= value
Syntax Explanation
● variable %= value: Calculates variable modulo value and assigns the remainder
back to variable .
● %= (Modulus Assignment Operator): Combines modulus and assignment.
Simple Code Example
remainder = 10
remainder %= 3 # Result is 1
Syntax Explanation
● **variable = value: Raises variable to the power of value and assigns the result back
to variable .
● **= (Exponentiation Assignment Operator): Combines exponentiation and
assignment.
Simple Code Example
power = 2
power **= 3 # Result is 8
Project Code
from machine import ADC, Pin, PWM
import time
while True:
# Read sensor value
sensor_value = potentiometer.read_u16()
Check Output
The LED brightness will increase or decrease based on the potentiometer's position, with
adjustments handled through compound operators.
Rules
● Use Bitwise Operators for Low-Level Control: Apply these operators when direct bit
manipulation is needed.
● Choose Operators Carefully: Select the correct operator based on the type of
manipulation, such as masking with & or setting bits with | .
● Combine Operators for Complex Bit Manipulations: Bitwise operators can be
combined to perform complex bit manipulations.
● Ensure Compatibility with Integer Types: Bitwise operations work only on integers,
so avoid using other data types.
● Use Binary Representation for Clarity: When working with bitwise operators, binary
literals can make code clearer and easier to debug.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Bitwise AND result = a & b masked = value &
(&) 0x0F
2 Bitwise OR (` `) `result = a
3 Bitwise XOR result = a ^ b toggle = value ^ 0xFF
(^)
4 Bitwise NOT result = ~a inverted = ~value
(~)
5 Left Shift ( << ) result = a << n shifted = value << 2
6 Right Shift result = a >> n shifted = value >> 1
( >> )
Topic Explanations
1. Bitwise AND ( & )
What is Bitwise AND?
The bitwise AND operator ( & ) compares each bit of two integers and returns 1 if both
corresponding bits are 1 ; otherwise, it returns 0 . This operator is often used for masking bits.
Use Purpose
● Mask Specific Bits: Used to isolate certain bits in a value.
● Clear Bits: Clears specific bits by ANDing with 0 s.
Syntax
result = a & b
Syntax Explanation
● a & b: Compares the binary bits of a and b , keeping only the bits where both are 1 .
● & (Bitwise AND Operator): Performs bitwise AND between two integers.
Simple Code Example
value = 0b1101 # Binary: 1101
mask = 0b0101 # Binary: 0101
masked = value & mask # Result is 0b0101 (binary 0101, decimal 5)
Code Example Explanation
● Masks Value: Only the bits where both value and mask are 1 remain in the result.
Notes
● Commonly used in embedded programming for isolating bits.
● Bitwise AND with 0x0F often masks the lower 4 bits of a byte.
Warnings
● Ensure both operands are integers for compatibility.
2. Bitwise OR ( | )
What is Bitwise OR?
The bitwise OR operator ( | ) compares each bit of two integers and returns 1 if either bit is 1 .
It’s often used to set specific bits in a value.
Use Purpose
● Set Specific Bits: Used to turn on specific bits without changing other bits.
● Combine Flags: Used to merge bit flags or settings.
Syntax
result = a | b
Syntax Explanation
● a | b: Compares the binary bits of a and b , setting each bit to 1 if either is 1 .
● | (Bitwise OR Operator): Performs bitwise OR between two integers.
Simple Code Example
value = 0b0101 # Binary: 0101
mask = 0b1000 # Binary: 1000
combined = value | mask # Result is 0b1101 (binary 1101, decimal 13)
3. Bitwise XOR ( ^ )
What is Bitwise XOR?
The bitwise XOR operator ( ^ ) compares each bit of two integers and returns 1 if the bits are
different. This operator is useful for toggling bits.
Use Purpose
● Toggle Specific Bits: Changes specific bits without affecting others.
● Error Detection: Commonly used in checksum and error detection algorithms.
Syntax
result = a ^ b
Syntax Explanation
● a ^ b: Compares the binary bits of a and b , setting each bit to 1 if they are different.
● ^ (Bitwise XOR Operator): Performs bitwise XOR between two integers.
Simple Code Example
value = 0b1010 # Binary: 1010
toggle = value ^ 0b1111 # Result is 0b0101 (binary 0101, decimal 5)
4. Bitwise NOT ( ~ )
What is Bitwise NOT?
The bitwise NOT operator ( ~ ) inverts each bit in an integer, turning 1 s into 0 s and 0 s into
1 s. This operation returns the two’s complement of the integer, which effectively negates it.
Use Purpose
● Invert Bits: Used to flip all bits in a binary value.
● Negate Integer: Negates a number by returning its two’s complement.
Syntax
result = ~a
Syntax Explanation
● ~a: Inverts each bit in a .
● ~ (Bitwise NOT Operator): Flips all bits, turning 1 s to 0 s and 0 s to 1 s.
Simple Code Example
value = 0b0101 # Binary: 0101
inverted = ~value # Result is -0b0110 (two’s complement of 0b1010)
Syntax Explanation
● a << n: Shifts a to the left by n bits, adding n zeros to the right.
● << (Left Shift Operator): Moves bits to the left, multiplying the value by 2^n .
Simple Code Example
value = 0b0001 # Binary: 0001
shifted = value << 2 # Result is 0b0100 (binary 0100, decimal 4)
Syntax Explanation
● a >> n: Shifts a to the right by n bits, discarding n bits from the right.
● >> (Right Shift Operator): Moves bits to the right, dividing the value by 2^n .
Simple Code Example
value = 0b1000 # Binary: 1000
shifted = value >> 2 # Result is 0b0010 (binary 0010, decimal 2)
Code Example Explanation
● Shifts Right by 2: The result, 0b0010 , is 2 in decimal.
Notes
● Commonly used for dividing by powers of 2.
● Shifting right by 1 divides the number by 2 .
Check Output
The LEDs connected to pins D2-D5 will sequentially light up, shifting from one end to the other.
This pattern demonstrates the use of bitwise shifts to control hardware.
Math Operations in STM32
Chapter Overview
Mathematical functions and constants are essential for embedded programming, allowing for
data processing, calculations, and control of devices. MicroPython's math module includes a set
of common mathematical operations such as square roots, powers, logarithms, trigonometric
functions, and constants like π (pi) and e. This chapter covers each math function available in
MicroPython, with syntax, detailed explanations, examples, and a practical project to
demonstrate these concepts.
Chapter Goal
● Gain a solid understanding of mathematical functions in the MicroPython math
module.
● Learn to apply various math operations for data processing and calculations.
● Implement a practical project that uses math operations to analyze sensor data in real
time.
Rules
● Import the Math Module: Use import math to access MicroPython’s math functions.
● Use Constants for Accurate Calculations: Constants like math.pi and math.e
ensure precision in calculations.
● Apply Functions Based on Input Requirements: Use functions such as sqrt for roots
and sin for trigonometric calculations.
● Handle Negative Values Carefully: Functions like sqrt and log require positive
inputs.
● Use Floating-Point Numbers for Precise Calculations: Ensure correct types to avoid
integer truncation in division and other operations.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Square Root result = root = math.sqrt(16)
( sqrt ) math.sqrt(x)
2 Power ( pow ) result = cube = math.pow(2, 3)
math.pow(x, y)
3 Exponential result = exp_val = math.exp(2)
( exp ) math.exp(x)
4 Natural result = ln_val = math.log(10)
Logarithm ( log ) math.log(x)
5 Trigonometric result = sine_val =
Sine ( sin ) math.sin(x) math.sin(math.pi / 2)
6 Trigonometric result = cos_val = math.cos(0)
Cosine ( cos ) math.cos(x)
7 Trigonometric result = tan_val =
Tangent ( tan ) math.tan(x) math.tan(math.pi / 4)
8 Constant pi math.pi circumference = 2 *
math.pi * radius
9 Constant e math.e growth = initial *
math.e ** rate
Topic Explanations
1. Square Root ( sqrt )
What is Square Root?
The sqrt function computes the square root of a number, returning the value that, when
multiplied by itself, gives the input number.
Use Purpose
● Calculate Roots: Used when square roots are needed, such as in geometric
calculations.
● Optimize Code: Avoids using **0.5 or manual multiplication for square roots.
Syntax
result = math.sqrt(x)
Syntax Explanation
● math.sqrt() : This function is part of the math module, so the math module must be
imported first.
● x : Represents the number whose square root you want to calculate. This must be a non-
negative number for the function to work.
● result : Stores the square root of x as a floating-point number.
Simple Code Example
import math
value = 16
root = math.sqrt(value) # Result is 4.0
Code Example Explanation
● Calculates Square Root of 16: The result, 4.0 , is stored in root .
Notes
● Always returns a floating-point number.
● Input should be non-negative; passing a negative number will raise an error.
2. Power ( pow )
What is Power?
The pow function raises a number to a specified exponent, equivalent to x**y .
Use Purpose
● Exponentiation: Calculates squares, cubes, and other powers.
● Simplify Calculations: Avoids repetitive multiplication.
Syntax
result = math.pow(x, y)
Syntax Explanation
● math.pow() : This function calculates the power of a number, requiring two arguments.
● x : Represents the base, or the number you want to raise.
● y : Represents the exponent, the power to which x will be raised.
● result : Stores the result of raising x to the power of y as a floating-point number.
Simple Code Example
import math
value = 2
power_val = math.pow(value, 3) # Result is 8.0
Code Example Explanation
● Calculates 2 Raised to the Power of 3: The result, 8.0 , is stored in power_val .
Notes
● Returns a float, even for integer powers.
● Can be used with fractional exponents for roots.
3. Exponential ( exp )
What is Exponential?
The exp function computes e raised to the power of x , where e is the base of the natural
logarithm (approximately 2.71828).
Use Purpose
● Growth Calculations: Commonly used in physics, biology, and financial applications.
● Evaluate Exponential Functions: Useful for exponential growth and decay.
Syntax
result = math.exp(x)
Syntax Explanation
● math.exp() : Part of the math module, calculates the power of e, the base of natural
logarithms.
● x : Represents the exponent for e in the expression e^x .
● result : Stores the value of e raised to the power of x as a floating-point number.
Simple Code Example
import math
value = 2
exp_val = math.exp(value) # Result is approximately 7.389
Syntax Explanation
● math.log() : Part of the math module, calculates the natural logarithm of a positive
number.
● x : Represents the positive input value for which you want the natural logarithm.
● result : Stores the natural logarithm of x as a floating-point number.
Simple Code Example
import math
value = 10
ln_val = math.log(value) # Result is approximately 2.302
Syntax Explanation
● math.sin() : Calculates the sine of an angle expressed in radians.
● x : Represents the angle in radians for which you want the sine value.
● result : Stores the sine of x as a floating-point number.
Simple Code Example
import math
angle = math.pi / 2
sine_val = math.sin(angle) # Result is 1.0
Syntax Explanation
● math.cos() : Calculates the cosine of an angle expressed in radians.
● x : Represents the angle in radians for which you want the cosine value.
● result : Stores the cosine of x as a floating-point number.
Simple Code Example
import math
angle = 0
cos_val = math.cos(angle) # Result is 1.0
Syntax Explanation
● math.tan() : Calculates the tangent of an angle in radians.
● x : Represents the angle in radians for which you want the tangent value.
● result : Stores the tangent of x as a floating-point number.
Simple Code Example
import math
angle = math.pi / 4
tan_val = math.tan(angle) # Result is approximately 1.0
8. Constant pi
What is pi ?
The constant pi represents the mathematical constant π (3.14159), commonly used in
trigonometry, geometry, and wave calculations.
Use Purpose
● Circle Calculations: Used in formulas for circumference and area of circles.
● Define Periods in Wave Functions: Important for periodic calculations.
Syntax
math.pi
9. Constant e
What is e ?
The constant e represents the base of the natural logarithm, approximately 2.71828. It is often
used in exponential growth models and logarithmic calculations.
Use Purpose
● Exponential Growth Models: Widely used in finance, biology, and physics.
● Evaluate e-based Expressions: Forms the base for natural logarithmic functions.
Syntax
math.e
while True:
# Read sensor value
sensor_value = sensor.read_u16()
# Calculate square root, natural log, and sine of the sensor value
root = math.sqrt(sensor_value)
log_value = math.log(sensor_value + 1) # Adding 1 to avoid log(0)
sine_value = math.sin(sensor_value * math.pi / 65535) # Scale to 0-π
Rules
● Use String Functions for Character Manipulation: Use functions like ord() , chr() ,
isalpha() , isdigit() for character handling.
● Handle Upper and Lowercase Carefully: Use upper() and lower() to standardize
case as needed.
● Validate Characters for Input Control: Check properties of characters (e.g., is it a
digit or letter) to ensure valid inputs.
● Use ASCII Conversions: Use ord() and chr() to convert between characters and
their ASCII values.
● Be Mindful of Unicode in Text Processing: Only use ASCII characters if the
embedded system doesn’t support extended Unicode.
Syntax Table
Serial Topic Code Snippet Simple
No Example
1 Convert ascii_value = ascii_val =
Character to ord(character) ord('A')
ASCII ( ord )
2 Convert ASCII character = char = chr(65)
to Character chr(ascii_value)
( chr )
3 Check if is_alpha = 'A'.isalpha()
Alphabetic character.isalpha()
( isalpha )
4 Check if Digit is_digit = '5'.isdigit()
( isdigit ) character.isdigit()
5 Convert to uppercase = 'a'.upper()
Uppercase character.upper()
( upper )
6 Convert to lowercase = 'A'.lower()
Lowercase character.lower()
( lower )
7 Check if is_alnum = 'A5'.isalnum()
Alphanumeric character.isalnum()
( isalnum )
8 Strip stripped = string.strip() ' text '.strip()
Whitespaces
( strip )
Topic Explanations
1. Convert Character to ASCII ( ord )
What is ord ?
The ord function converts a single character to its corresponding ASCII (or Unicode) integer
value.
Use Purpose
● ASCII Conversion: Used to find the ASCII value of a character for encoding or
protocol processing.
● Data Analysis: Useful when checking or manipulating characters based on their ASCII
values.
Syntax
ascii_value = ord(character)
Syntax Explanation
● ord() : The function that takes a single character as input.
● character : A single character (string of length 1) whose ASCII value is desired.
● ascii_value : Stores the integer ASCII value of character .
Simple Code Example
character = 'A'
ascii_value = ord(character) # Result is 65
Syntax Explanation
● upper() : Converts all lowercase letters in a string to uppercase.
● character : A string you want to convert to uppercase.
● uppercase : Stores the converted uppercase string.
Simple Code Example
character = 'a'
uppercase = character.upper() # Result is 'A'
Syntax Explanation
● lower() : Converts all uppercase letters in a string to lowercase.
● character : A string you want to convert to lowercase.
● lowercase : Stores the converted lowercase string.
Simple Code Example
character = 'A'
lowercase = character.lower() # Result is 'a'
Syntax Explanation
● isalnum() : Checks if all characters in the string are either letters or digits.
● character : A string to check for alphanumeric content.
● is_alnum : Boolean result, True if all characters are alphanumeric, otherwise False .
Simple Code Example
character = 'A5'
is_alnum = character.isalnum() # Result is True
Syntax Explanation
● strip() : Removes any leading and trailing spaces from a string.
● string : The string you want to clean.
● stripped : Stores the cleaned version of the string.
Simple Code Example
text = ' hello '
stripped = text.strip() # Result is 'hello'
while True:
user_input = read_user_input().strip() # Clean the input
is_valid = True
# Display results
if is_valid:
print(f"Valid Input: {user_input}")
else:
print("Error: Input must be uppercase and alphanumeric.")
Rules
● Import the Random Module: Use import random to access the random number
functions.
● Use Appropriate Functions Based on Data Type: Choose between randint ,
random , and uniform based on the type of random value required.
● Set Random Seed for Reproducibility: Use seed() if you need reproducible random
sequences.
● Handle Floating-Point Operations Carefully: Be mindful of rounding when using
random floats in comparisons.
● Avoid Using Random in Sensitive Security: For high-security applications, use
dedicated cryptographic random functions instead of random .
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Generate rand_num = rand_int =
Random random.randint(a, b) random.randint(1,
Integer 10)
( randint )
2 Generate rand_num = rand_float =
Random random.random() random.random()
Float
( random )
3 Generate rand_num = rand_float =
Random random.uniform(a, b) random.uniform(1.0,
Float in 5.0)
Range
( uniform )
4 Select rand_elem = rand_item =
Random random.choice(sequence) random.choice([1, 2,
Element 3])
( choice )
5 Shuffle random.shuffle(sequence) random.shuffle([1, 2,
Sequence 3])
( shuffle )
6 Set random.seed(value) random.seed(10)
Random
Seed
( seed )
Topic Explanations
1. Generate Random Integer ( randint )
What is randint ?
The randint function generates a random integer within a specified range, including both
endpoints. This function is useful for generating discrete random values, such as selecting
random items or steps.
Use Purpose
● Random Selection in Ranges: Used for generating random numbers within specific
limits.
● Discrete Random Choices: Ideal for games, simulations, or other cases needing whole
numbers.
Syntax
rand_num = random.randint(a, b)
Syntax Explanation
● random.randint() : Generates a random integer in the inclusive range [a, b] .
● a : The start of the range (included).
● b : The end of the range (included).
● rand_num : Stores the generated random integer.
Simple Code Example
import random
rand_int = random.randint(1, 10) # Result is a random integer from 1 to 10
Code Example Explanation
● Generates Random Integer from 1 to 10: A random integer is generated and stored in
rand_int .
Notes
● Useful when random whole numbers are needed within specific bounds.
● Commonly used in loops or conditions for random selections.
Syntax Explanation
● random.random() : Generates a random float in the range [0.0, 1.0) .
● rand_num : Stores the generated random float.
Simple Code Example
import random
rand_float = random.random() # Result is a random float between 0.0 and 1.0
Syntax Explanation
● random.uniform() : Generates a random float in the inclusive range [a, b] .
● a : The start of the range.
● b : The end of the range.
● rand_num : Stores the generated random float.
Simple Code Example
import random
rand_float = random.uniform(1.0, 5.0) # Result is a random float between 1.0 and 5.0
Syntax Explanation
● random.choice() : Chooses a random item from a given sequence.
● sequence : The list or tuple from which to select a random element.
● rand_elem : Stores the randomly selected element.
Simple Code Example
import random
rand_item = random.choice([1, 2, 3]) # Result is a random choice from the list [1, 2, 3]
Syntax Explanation
● random.seed() : Sets the seed value for the random number generator.
● value : An integer seed to initialize the random generator. Same seed produces the
same sequence.
Simple Code Example
import random
random.seed(10) # Sets the seed to 10, producing a predictable sequence
# Main loop to blink LED with random intervals and random states
while True:
# Set LED state to ON or OFF randomly
led.value(random.choice([0, 1]))
# Wait for a random delay between 0.1 and 1.0 seconds
delay = random.uniform(0.1, 1.0)
print(f"LED state: {led.value()}, Delay: {delay:.2f} seconds")
Check Output
The LED on pin D2 will turn on and off at random intervals, simulating unpredictable behavior
based on random values.
Syntax Table
Serial Protocol Code Snippet Simple Example
No
1 UART uart = UART(port, uart = UART(1, 9600)
Initialize baudrate)
2 UART uart.write(data) uart.write(b'Hello')
Send
Data
3 UART data = uart.read(size) data = uart.read(5)
Read
Data
4 I2C i2c = I2C(port, i2c = I2C(1,
Initialize freq=freq) freq=400000)
5 I2C Scan devices = i2c.scan() devices = i2c.scan()
6 I2C Read data = data =
Data i2c.readfrom(addr, i2c.readfrom(0x3C, 4)
size)
7 I2C i2c.writeto(addr, data) i2c.writeto(0x3C,
Write b'\x00\x01')
Data
8 SPI spi = SPI(port, spi = SPI(1,
Initialize baudrate=baudrate) baudrate=1000000)
9 SPI Send spi.write(data) spi.write(b'\xAA\xBB')
Data
10 SPI Read data = spi.read(size) data = spi.read(2)
Data
Topic Explanations
1. UART (Universal Asynchronous Receiver/Transmitter)
What is UART?
UART is a simple, asynchronous, serial communication protocol that sends and receives data
byte-by-byte between two devices. It’s often used to communicate with PCs, microcontrollers,
and GPS modules.
Use Purpose
● Simple Data Transfer: Used for transmitting and receiving data without a clock signal.
● Two-Way Communication: Allows bidirectional data transfer with minimal wiring
(TX and RX pins).
Syntax
uart = UART(port, baudrate)
uart.write(data)
data = uart.read(size)
Syntax Explanation
● UART(port, baudrate) : Initializes the UART on a specific port with a given
baudrate .
● port : UART port number (e.g., 1).
● baudrate : Communication speed in bits per second (e.g., 9600, 115200).
● write(data) : Sends data as bytes to the connected device.
● read(size) : Reads size bytes of data received over UART.
Simple Code Example
from machine import UART
# Send data
uart.write(b'Hello')
Syntax Explanation
● SPI(port, baudrate=baudrate) : Initializes the SPI communication on a specific port
and baudrate .
● port : SPI port number (e.g., 1).
● baudrate : SPI clock speed in bits per second.
● write(data) : Sends data as bytes over SPI.
● read(size) : Reads size bytes from the SPI bus.
Simple Code Example
from machine import SPI
# Send data
spi.write(b'\xAA\xBB')
Project Code
from machine import I2C, Pin
import time
Rules
● Use print for Debugging and Data Display: Leverage print to check variable
values and display program progress.
● Format Strings for Clarity: Use formatting options to make output clear and easy to
read.
● Combine Data Types in Output: Use f-strings or format() to combine strings with
other data types.
● Limit Print Frequency in Loops: Minimize excessive prints in tight loops to avoid
slowing down the program.
● Use Escape Characters for Formatting: Use \n for newlines and \t for tabs to
structure the output.
Syntax Table
Serial Topic Code Snippet Simple Example
No
1 Basic Print print(value) print("Hello")
2 Print print(value1, value2, ...) print("Temp:", 25)
Multiple
Values
3 Print with print(value1, value2, print("Hello", "World",
Separator sep="separator") sep="-")
4 Print with print(value, print("Loading",
End end="end_character") end="...")
5 Print print("format" % print("Temp: %d C" %
Formatted values) temp)
String ( % )
6 Print with print(" print("Temp: {}
format() {}".format(value)) C".format(temp))
7 Print with print(f"text {value}") print(f"Temp: {temp}
f-strings C")
8 Escape \n , \t , \\ print("Hello\nWorld")
Characters
Topic Explanations
1. Basic Print
What is Basic Print?
The print function outputs a specified value or variable to the console. It is commonly used to
display text or data, making it essential for debugging and providing real-time feedback in
embedded systems.
Use Purpose
● Display Messages: Used to display simple text or messages.
● Debugging: Helps check variable values and program flow.
Syntax
print(value)
Syntax Explanation
● print() : The function that outputs text or variable values to the console.
● value : The value or text to print.
Simple Code Example
print("Hello, World!")
Syntax Explanation
● print() : Outputs the specified values.
● value1, value2, ... : Multiple values separated by commas. Each value is printed with a
space in between.
Simple Code Example
temp = 25
print("Temperature:", temp)
Syntax Explanation
● sep : Optional argument defining the separator between values.
● "separator" : Specifies the separator string (e.g., "-" or "," ).
Simple Code Example
print("Hello", "World", sep="-")
Syntax Explanation
● end : Optional argument specifying the character to print at the end.
● "end_character" : Custom end character, such as an ellipsis ( "..." ).
Simple Code Example
print("Loading", end="...")
Syntax Explanation
● "format" % values : Format string containing placeholders ( %d for integers, %f for
floats, etc.).
● values : Values corresponding to each placeholder.
Simple Code Example
temp = 25
print("Temperature: %d C" % temp)
Code Example Explanation
● Prints "Temperature: 25 C": Inserts the value of temp into the formatted string.
Notes
● Supports %d for integers, %f for floats, %s for strings.
● Useful for controlling numeric precision with %.2f for two decimal places.
Warnings
● Ensure format specifiers match the data type of variables.
Syntax Explanation
● "{}".format(value) : Uses {} as placeholders in the string, replaced with values
provided in format() .
Simple Code Example
temp = 25
print("Temperature: {} C".format(temp))
Syntax Explanation
● f"text {value}" : The f before the string allows embedding variables within {}
directly in the string.
Simple Code Example
temp = 25
print(f"Temperature: {temp} C")
8. Escape Characters
What are Escape Characters?
Escape characters are special sequences in strings that represent whitespace, newlines, tabs, or
special symbols.
Use Purpose
● Format Output: Allows multi-line strings or tabbed layouts.
● Insert Special Characters: Enables displaying special characters, such as quotation
marks or backslashes.
Syntax
● \n : Newline
● \t : Tab
● \\ : Backslash
Syntax Explanation
● \n : Moves to the next line.
● \t : Adds a tab space.
● \\ : Prints a backslash character.
Simple Code Example
print("Hello\nWorld")
print("Item\tPrice")
print("Backslash: \\")