Skip to content

4. Embedded Programming

Week’s Goals:

  1. Read datasheets.
  2. Learn about different microcontrollers:
  3. ESP32
  4. Raspberry Pi Pico (RP2040)
  5. STM32
  6. Understand communication protocols.
  7. Learn a new programming language: MicroPython.
  8. Create a simple game.

Additional:

  • Explore interrupts.

1. Group Assignment

We started by exploring the available microcontrollers in our local lab. We listed them to better organize our work. Then, we read a book about microcontrollers.

1.1 Understanding Microcontrollers

What is a Microcontroller?

A microcontroller is a compact integrated circuit that contains a processor, memory, and input/output (I/O) peripherals. It allows us to store and process data efficiently in a single chip.

Feature Microcontroller Microprocessor
Components CPU, memory, and I/O in one chip CPU only, needs external parts
Usage Used in embedded systems Used in computers

Bits and Bytes

A bit is the smallest unit of data in computing, representing either 0 or 1. A byte consists of 8 bits grouped together.

Registers

A register (or memory cell) is a small storage unit in a microcontroller that holds data temporarily.

Special Function Registers (SFR)

These are registers with predefined functions set by the manufacturer.

Memory Types

  • Read-Only Memory (ROM): Stores permanent data, such as firmware.
  • Masked ROM (MROM): Pre-programmed by the manufacturer.
  • One-Time Programmable ROM (OTP ROM): Can be programmed once; if an error occurs, a new chip is needed.
  • UV Erasable Programmable ROM (UV EPROM): Data can be erased using UV light, allowing reprogramming.

  • Random Access Memory (RAM): Stores temporary data that is lost when power is off.
  • Electrically Erasable Programmable ROM (EEPROM): Can be reprogrammed electronically while retaining data even after power loss.

Central Processing Unit (CPU)

The CPU is the core of the microcontroller, responsible for processing instructions and controlling all operations. It consists of:

  • Instruction Decoder: Deciphers program instructions.
  • Arithmetic Logic Unit (ALU): Performs mathematical and logical operations.
  • Accumulator: Temporarily stores data for processing.

Bus System

  • Address Bus: Transfers memory addresses from the CPU to memory.
  • Data Bus: Connects different components inside the microcontroller.

Serial Communication

For short distances, microcontrollers communicate via parallel connections. For longer distances, serial communication is used.

  • Baud Rate: The number of bits transmitted per second (bps).

Common Serial Communication Protocols

  • I2C (Inter-Integrated Circuit): Used for short-distance data exchange between multiple devices.

  • SPI (Serial Peripheral Interface): A fast communication protocol for short distances.

  • UART (Universal Asynchronous Receiver/Transmitter): Uses a single communication line for data exchange.
Feature I2C SPI UART
Communication Type Multi-master, multi-slave Single master, multiple slaves Full-duplex (one-to-one)
Wires 2 (SDA, SCL) 4 (MOSI, MISO, SCLK, SS) 2 (TX, RX)
Speed Medium Fast Slow
Devices Many Few Two
Complexity High Medium Low

Analog-to-Digital Conversion (ADC)

Converts analog signals into digital data that the CPU can process.

Internal Architecture

Von Neumann Architecture

Uses a single memory for both instructions and data, making it slower because the CPU can only access one at a time.

Harvard Architecture

Has separate memory for instructions and data, allowing simultaneous access for faster processing.

RISC (Reduced Instruction Set Computer)

Executes only simple operations (e.g., addition, subtraction) for higher efficiency.

CISC (Complex Instruction Set Computer)

Supports a large number of instructions, enabling more complex operations at high speed.

1.2 How to Choose the Right Microcontroller?

Selecting the right microcontroller can be challenging due to the vast number of options. Consider the following factors:

  • Number of input/output pins needed.
  • Complexity of operations (simple or advanced).
  • Requirement for serial communication.
  • and more..

Once you define your needs, narrow down the options and compare prices.

Steps to Get Started

  1. Select a manufacturer: Choose a microcontroller family that is easy to find.
  2. Study one model: Focus on learning the essentials without getting lost in details.
  3. Solve a practical problem: Applying knowledge to real-world tasks makes it easier to work with other models in the same family.

1.3 PIC Microcontroller Architecture

We explored the architecture of 8-bit PIC microcontrollers. With the knowledge gained from the previous sections, understanding different microcontroller architectures became easier.


2. Seeed Studio RP2040 - Getting Started

RP2040 Technical Information

Overview

The RP2040 is a dual-core ARM Cortex-M0+ microcontroller designed by Raspberry Pi. It features flexible I/O options, low power consumption, and excellent performance for embedded systems and IoT applications.

Key Features:

  • Cores: Dual-core ARM Cortex-M0+ (up to 133 MHz)
  • Memory: 264 KB SRAM
  • I/O Pins: 30 GPIO (26 usable), with support for SPI, I²C, UART, and PWM
  • Power: 1.8V to 3.3V, with low-power sleep modes
  • Maximum Clock Speed: 133 MHz (Dual-core ARM Cortex-M0+)

Step 1: Configure Arduino IDE

  1. Open Arduino IDE and go to Preferences.
  2. In the Additional Board Manager URLs, paste the following link:

https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json

  1. Click OK.

Step 2: Install RP2040 Board

  1. Go to Tools > Board > Boards Manager.
  2. Search for “RP2040”.
  3. Select and install the appropriate board package.

Step 3: Connect and Upload Code

  1. Press and hold button B before connecting the board to your laptop.

  2. Check the port in Tools > Port.

Then upload your code.

Blinking LED

I uploaded this code

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);  
  delay(3000);                      
  digitalWrite(LED_BUILTIN, LOW);   
  delay(3000);                      
}

Animated GIF

Animated GIF

Fading Two LEDs

Animated GIF


3. Working with ESP32-C3

ESP32-C3 Mini Technical Info

The ESP32-C3 is a low-power, cost-effective microcontroller. It is designed for IoT (Internet of Things) applications with features such as Wi-Fi and Bluetooth, high security, and low power consumption.

🔹 Key Features

  • Processor: 32-bit RISC-V Single-Core CPU @ 160 MHz
  • Memory:
  • 384 KB ROM
  • 400 KB SRAM
  • 8 KB RTC SRAM
  • Storage: External Flash (supports QSPI, up to 16 MB)
  • Wireless Connectivity:
  • Wi-Fi 4 (802.11 b/g/n)

Blinking LED

Animated GIF

Controlling RGB LED Using PushButton

Animated GIF

Controlling RGB LED Using Serial “Keyboard”

Animated GIF


Getting to Know MicroPython

MicroPython is a lightweight and efficient programming language designed for microcontrollers. It allows you to run Python on small embedded systems and is perfect for rapid prototyping. This guide will cover basic usage for two popular platforms: Microbit and ESP32.

Microbit Programming using MicroPython

Why I choose it

  • A simple and beginner-friendly microcontroller with built-in sensors (accelerometer, magnetometer, etc.).
  • Perfect for those new to coding, especially younger learners “as me in the micropython language”.

Advantages: - Built-in display and buttons. - No need for additional accessories to get started. - MicroPython is officially supported.

About the BBC micro:bit v2

The micro:bit is Single Board Computer (SBC) that contains an application processor with a variety of on-chip peripherals. Other peripherals are connected to this chip. An interface processor is connected to the application processer and manages communication via the USB interface, including the drag-and-drop code flashing process. The interface processor does not control any of the peripherals on the board but is connected to the application processor on the internal board I2C bus.

  • Processor: ARM Cortex-M0
  • Flash ROM: 256KB
  • RAM: 16KB
  • Speed: 48MHz
  • Display: 5x5 LED matrix
  • General Purpose Input/Output Pins The edge connector is the main interface to external components attached to the micro:bit. This interface has a range of digital, analog, touch, PWM, and serial communications interfaces.
  • Sensors There is one combined motion sensor IC on the micro:bit.
  • Power Supply Power to the micro:bit can be provided by 3 sources: The USB, the battery connector, and the 3V pad on the edge connector.
Item Details
Operating Range 1.8v…3.6v
Operating Current (USB and Battery) 300mA max
Max current provided via edge connector 190mA

Microbit Display

The Microbit’s display consists of a 5x5 matrix of LEDs. You can display text, images, and even custom graphics with just a few lines of code.

I started with a very simple program to display text on the Microbit’s screen. Initially, the code didn’t work because I forgot to add spaces before the commands inside the while True: loop.

Animated GIF

from microbit import *  # Import all necessary functions

while True:
 display.show('HI')
 sleep(100)

Once I got that working, I moved on to display both an image and text:

Animated GIF

This code first displays a happy face for 1 second, clears the display, and then shows the text ‘HI’.

from microbit import *  # Import all necessary functions

while True:
 display.show(Image.HAPPY)
 sleep(1000)
 display.clear()
 display.show('HI')
 sleep(100)

ESP32 Programming using MicroPython

Blinking an LED on ESP32

Animated GIF

import machine 
import time

led = machine.Pin(2, machine.Pin.OUT)

while True:
 led. value (1) # Turn LED on
 time.sleep(1) # Wait 1 second 
 led. value(0) # Turn LED off
 time.sleep (1)

ESP32 oled ssd1306

The SSD1306 OLED is a monochrome display module that supports I2C communication. It’s ideal for displaying text, images, and animations.

📌 SSD1306 Technical Specifications

Feature Details
Resolution 128x64 pixels
Interface I2C (4-wire) or SPI (7-wire)
Operating Voltage 3.3V
Driver IC SSD1306
Supported Colors Monochrome (White or Blue)
Power Consumption Low

🔌 Connecting ESP32 with OLED Display

OLED Pin ESP32 Pin
VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21

This code initializes the SSD1306 OLED display and shows a simple text message.

from machine import Pin, I2C  # import required modules
import ssd1306  # OLED Library

# ESP32 Pin assignment 
i2c = I2C(0, scl=Pin(22), sda=Pin(21))

#initialise OLED display (128x64pixles)
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

oled.text("Hellow", 60, 10)  #desplay text at (x=60,y=10)
oled.text("I am Testing", 20, 30)  
oled.text("The Display :)", 30, 50)           
oled.show()

This extends the previous example by blinking the text.

from machine import Pin, I2C  # Import required modules
import ssd1306  # OLED library
import time  # Import time module for delays

# Initialize I2C interface (ESP32: SCL=22, SDA=21)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))

# Initialize OLED display (128x64 pixels)
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

while True:
    oled.fill(0)  # Clear the screen
    oled.text("Hi", 60, 10)  # Display text at (x=60, y=10)
    oled.text("I'm Testing", 20, 30)
    oled.text("The Code!", 30, 50)
    oled.show()  # Update the display

    time.sleep(1)  # Wait for 1 second

    oled.fill(0)  # Clear the screen
    oled.show()  # Update the display

    time.sleep(1)  # Wait for 1 second

Animated GIF

Files - RP2040_Blinking LED - Fading LED-RP2040 - RGB_serial_ESP32C3

References - Seeed Studio Wiki - XIAO RP2040 - ESP32-C3 Series Datasheet v2.0.