WEEK 4

Embedded programming

How the week started

Living in a world saturated with smart gadgets, I realized I’ve always been a passive consumer, never truly curious about the mechanics behind them. It’s a strange feeling to be surrounded by technology every day yet have no idea how it actually functions.

How the week ended

It concluded with me gaining a foundational understanding of embedded programming. Although I didn’t get the opportunity to explore it in depth, watching my batchmates demonstrate what could be achieved truly sparked my interest. From lighting up a series of LEDs to working with OLED displays, and even creating simple games on LED strips and panels, I began to see the exciting possibilities that embedded programming offers.

Week 04’s assignment

Group assignment:

• Demonstrate and compare the toolchains and development workflows for available embedded architectures.

• Document your work to the group work page and reflect on your individual page what you learned.

Group assignment link

Individual assignment:

• Browse through the datasheet for a microcontroller.

• Write and test a program for an embedded system using a microcontroller to interact (with local input &/or output devices) and communicate (with remote wired or wireless connections).

My Understanding of Embedded Systems

AI generated image
View AI Prompt Used

Create an illustration of a cat confused about embedded systems.

At the beginning of this week, I found myself trying to understand the concepts being taught and the expectations of the assignment. After two days of exploration and valuable guidance from our instructor, I was able to gain clarity and develop the work presented below.

In simple terms, an embedded system is a specialized controller designed to perform a dedicated function. Unlike a general-purpose computer that can run many different programs, an embedded system is built for a specific task—combining hardware and software into a single, cohesive unit.

The Hardware:

This includes the physical components, such as LEDs, sensors, and switches. In a basic circuit, a switch simply closes a loop to provide power.

The Microcontroller (The "Brain"):

This is where the logic of the system operates. The microcontroller allows us to bridge the gap between physical components and computational control.

The Software (Firmware):

By writing code and uploading it to the microcontroller, we can define exactly how the hardware behaves. Instead of a light simply being "on" or "off," we can program complex patterns, time durations, or responses to environmental inputs.

Let’s meet a microcontroller

Name: Seeed studio xiao rp2040

The Seeed Studio XIAO RP2040 is a very small microcontroller board (21 × 17.5 mm) based on the Raspberry Pi RP2040 chip.

Features:

It runs at 3.3V, has 2MB Flash and 264KB SRAM, and includes a USB-C port, built-in RGB LED, and SWD pads for debugging.

what does RP2040 mean?

Source: RP2040 Datasheet — Seeed Studio

The post-fix numeral on RP2040 comes from the following:

  1. Number of processor cores (2)
  2. Loosely which type of processor (M0+)
  3. floor(log2(RAM / 16k))
  4. floor(log2(non-volatile memory / 16k)) or 0 if no onboard non-volatile storage
A system overview of the RP2040 chip

A system overview of the RP2040 chip

RP2040 Pinout Diagram

RP2040 Pinout for QFN-56 7x7mm (reduced ePad size)

About RP2040:

  1. Dual-core ARM Cortex-M0+ processor running up to 133 MHz.
  2. 264 KB of on-chip SRAM for data and program storage.
  3. Supports up to 16 MB of external Flash memory via QSPI.
  4. USB 1.1 controller with host and device support.
  5. Programmable I/O (PIO) blocks for custom high-speed interfaces.
  6. Multiple communication interfaces such as UART, SPI, and I2C.
  7. Drag-and-drop programming support using UF2 bootloader.
  8. Built-in Serial Wire Debug (SWD) support.
  9. Low-power operation suitable for embedded applications.
  10. Flexible clock system with PLLs and DMA support.

Source: RP2040 Datasheet

Getting started with Seeed XIAO-RP2040

The RP2040 supports both C/C++ and MicroPython, allowing flexibility in development. For this project, the board is programmed using the Arduino IDE.

⬇ DOWNLOAD ARDUINO ⬇

Initial Hardware Verification Procedure

  1. Pressed and held the BOOT button, then connected the Seeed Studio XIAO RP2040 to the PC using a USB Type-C cable.
  2. Confirmed that the onboard LED turned on to verify the power supply.
  3. Checked if a removable drive was detected on the computer, indicating proper connection and recognition.
The chip is connected

This ensures the board is ready before proceeding with programming.

Drive detected

Arduino IDE Software setup

  1. Downloaded and installed the latest version of the Arduino IDE for Windows (64-bit).
  2. Launched the Arduino application.
  3. Added the Seeed Studio XIAO RP2040 board package through File > Preferences.

Entered the following URL in Additional Boards Manager URLs

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

Raspberry Pi Pico/RP2040 Installation

  1. Navigated to Tools > Board > Boards Manager...
  2. Typed the keyword "RP2040" into the search bar.
  3. Selected the latest version of "Raspberry Pi Pico/RP2040/RP2350"
  4. Installed the package successfully.

BOARD - After installing the board package, I navigated to Tools > Board, found "Seeed Studio XIAO RP2040," and selected it.

PORT - I navigated to Tools > Port and selected the serial port name of the connected Seeed Studio XIAO RP2040. This was likely to be COM3 or higher. This is where we have connecetd our RP2040

Now I have finished setting up the Seeed Studio XIAO RP2040 for Arduino IDE.

Arduino IDE 2.3.x Interface Overview

Navigating the Arduino IDE Interface

When I opened the IDE to program my Seeed Studio XIAO RP2040, I focused on two main areas to manage my code and monitor the hardware status.

The Editor & Toolbar

This served as my primary workspace for writing instructions for the board.

  • Verify: I used this to compile my code and catch any syntax errors before attempting to send it to the board.
  • Upload: Once the code was ready, I clicked this to send the script directly to the XIAO RP2040.
  • Board Selector: I made sure this was set to "Seeed Studio XIAO RP2040" so the IDE knew exactly which hardware it was talking to.

The Sketch Structure:

  • void setup: I placed the code here that only needed to run once, such as defining my pin modes for the LEDs.
  • void loop: This is where I wrote the main logic that repeats indefinitely, allowing me to create continuous blinking patterns.

Understanding Syntax Highlighting in Arduino IDE

While writing the Blink program in Arduino IDE 2.x, I observed different colors in the code editor. These colors help me understand the structure and function of the program.

  • Orange: I see orange used for important Arduino functions such as setup(), loop(), digitalWrite(), delay(), and pinMode(). These are built-in functions that control the behavior of the microcontroller.
  • Cyan (Light Blue): Cyan represents keywords and predefined constants like void, HIGH, LOW, and OUTPUT. These define data types, logic levels, and configuration settings.
  • Grey: Grey indicates comments. Comments are written using // or /* */. They are ignored by the compiler and are used to explain the code.

The color coding improves readability and helps me quickly understand different parts of the program.

The Output Console

I relied on the bottom section of the interface to get real-time feedback on the "health" of my project.

  • Current Status: In my case, the console showed "User abort," which indicated that I had stopped an upload or compilation process midway.
  • Error Tracking: This is where the IDE flagged typos—highlighting them in red text so I could quickly fix them.

Blink Test – Seeed Studio XIAO RP2040

Summary

I tested the Seeed Studio XIAO RP2040 board using the Blink example in Arduino IDE to confirm proper installation and functionality. After selecting the correct board and port, I uploaded the example code. The onboard LED blinking at a fixed interval confirmed successful setup and upload.

1. Basic Requirements

Hardware

  • Seeed Studio XIAO RP2040 board
  • USB Type-C data cable
  • Computer (Windows / Mac / Linux)

Software

  • Arduino IDE installed
  • RP2040 board package installed
  • USB drivers (if required)

2. Board and Port Selection

Select Board:

Tools → Board → Seeed Studio XIAO RP2040

Select Port:

Tools → Port → Select the appropriate COM port
(Port appears only after connecting the board)

3. Blink Example

Open:

File → Examples → 01.Basics → Blink

Important Parameters:

  • LED_BUILTIN – Onboard LED pin
  • pinMode() – Sets the pin as OUTPUT
  • digitalWrite() – Controls LED ON/OFF
  • delay(1000) – 1 second delay

4. Upload Process

  1. Connected the board via USB.
  2. Clicked Verify (✔).
  3. Clicked Upload (→).
  4. Waited for the “Done Uploading” message.

If upload failed:

  • Pressed and held the BOOT button while connecting.
  • Rechecked board selection.
  • Rechecked port selection.

5. Expected Output

The onboard LED blinked continuously:

  • 1 second ON
  • 1 second OFF

I tested out a preset function in Arduino IDE. I remember being told that one need not always create code from scratch; instead, I worked from an existing file to understand the logic and later modified it to suit my specific hardware needs.

Components Used

Breadboard

  • Used for temporary circuit prototyping
  • Center rows are internally connected in groups of five
  • Side rails distribute VCC (+) and GND (–)

Seeed Studio XIAO RP2040

  • Microcontroller based on the RP2040 chip
  • Operates at 3.3V logic
  • Programmed using Arduino IDE and MicroPython
  • Controls LEDs and reads button input

LEDs (Red, Yellow, White)

  • Visual output components
  • Long leg – Anode (+)
  • Short leg – Cathode (–)
  • Requires a current-limiting resistor
  • Brightness: White appears brightest (~3V), Yellow medium, Red slightly dimmer (~2V)

Header Pins

  • Soldered to the board for stable breadboard connections

Jumper Wires

  • Used to connect GPIO pins, power, and ground

Working Principle

  • HIGH signal → LED ON
  • LOW signal → LED OFF

Button-Controlled LED Blinking using Seeed XIAO RP2040

In this experiment, I used the Seeed XIAO RP2040 board and programmed it using the Arduino IDE software.

Software Setup

I installed the Arduino IDE and added the Seeed XIAO RP2040 board package. After selecting the correct board and port, I uploaded the code to the microcontroller.

Hardware Connections

Since the internal pull-up resistor was used:


const int buttonPin = D0;
const int ledPin = D3;

bool isBlinking = false;
bool lastButtonState = HIGH;
unsigned long lastBlinkTime = 0;
const int interval = 500; // Blink speed in milliseconds

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  bool currentButtonState = digitalRead(buttonPin);

  // Check if button is pressed (transition from HIGH to LOW)
  if (currentButtonState == LOW && lastButtonState == HIGH) {
    isBlinking = !isBlinking; // Toggle the state
    
    // Print status to Serial Monitor
    Serial.print("LED Status: ");
    Serial.println(isBlinking ? "BLINKING" : "OFF");
    
    if (!isBlinking) digitalWrite(ledPin, LOW); // Ensure LED is off when disabled
    delay(50); // Debounce delay
  }
  lastButtonState = currentButtonState;

  // Handle the blinking without blocking the code
  if (isBlinking) {
    if (millis() - lastBlinkTime >= interval) {
      lastBlinkTime = millis();
      digitalWrite(ledPin, !digitalRead(ledPin)); // Invert current LED state
    }
  }
}

Working Principle

In the setup() function, I defined the pin modes and started serial communication at 9600 baud rate.

Inside the loop(), I continuously read the button state. When I detected a transition from HIGH to LOW (button press), I toggled a boolean variable that controlled whether the LED should blink.

Non-Blocking Delay

A non-blocking delay is a way to create a time delay in a program without stopping the rest of the code from running. Instead of using delay(), I used millis() to control the blinking interval. This allowed the program to remain responsive while the LED was blinking, since the microcontroller continued checking the button state without pausing execution.

Output

Each time I pressed the button, the LED switched between blinking and off. The current status (BLINKING or OFF) was displayed in the Serial Monitor for confirmation.

Using MicroPython with Seeed XIAO RP2040 (Using Thonny)

Introduction

After working with Arduino IDE, I explored programming the Seeed XIAO RP2040 using MicroPython. Instead of writing C/C++ code like in Arduino, I used Python language to control the board. For this, I installed Thonny IDE and prepared the board for MicroPython programming.

1. Software Requirements

2. Installing Thonny IDE

⬇ DOWNLOAD THONNY ⬇

I followed the official software setup guide provided by Seeed Studio.

Step 1: I downloaded and installed the latest version of Thonny IDE according to my operating system (Windows).

Step 2: After installation, I opened Thonny IDE.

Step 3: I will configure the interpreter in the next step after installing the MicroPython firmware.

3 Opening Thonny and Accessing Settings

Once the installation was complete, I launched Thonny.

Then I went to:

Tools → Options

This opened the Thonny settings window.

4 Selecting the Interpreter

Inside the Options window, I selected the Interpreter tab.

Here, I chose:

This allows Thonny to automatically identify my connected board.

5 Connecting the Seeed Studio XIAO RP2040

Next, I connected my Seeed Studio XIAO RP2040 to the PC.

To install MicroPython firmware:

  1. I pressed and held the BOOT button.
  2. While holding it, I connected the board to my computer using a Type-C cable.
  3. A new drive named RPI-RP2 appeared on my computer.

This confirmed that the board entered bootloader mode.

6 Installing MicroPython Firmware

Back in Thonny, I clicked:

Install or update MicroPython

Thonny automatically detected the board and showed:

I then clicked Install.

After a few seconds, the installation completed and showed Done. Once the firmware installation finished, the device was ready to use with MicroPython in Thonny.

Test Run with Seeed XIAO RP2040 (Using Thonny)

To confirm everything was functioning correctly in Thonny, I executed the prompt directly from the site.

from machine import Pin, Timer
 
led = Pin(25, Pin.OUT)
Counter = 0
Fun_Num = 0
 
def fun(tim):
    global Counter
    Counter = Counter + 1
    print(Counter)
    led.value(Counter%2)
 
tim = Timer(-1)
tim.init(period=1000, mode=Timer.PERIODIC, callback=fun)

Using Thonny to try to fade and change color

In my project, I am simulating the sun moving along a path with its colors changing throughout the day. I am experimenting with the Seeed Studio XIAO RP2040 to control LEDs that fade smoothly between colors, mimicking natural sunlight transitions from dawn to noon to dusk. Using MicroPython, I adjust RGB values and brightness to create a realistic effect of the sun’s journey, producing a dynamic visual representation of daylight progression.


    Write a MicroPython program for the Seeed Studio XIAO RP2040 that
    smoothly fades the onboard NeoPixel from red to a warm yellow over 30 seconds. 
    The program should use the machine, neopixel, and utime libraries. First, turn 
    on the RGB power by setting Pin 11 as an output and driving it HIGH. Then control
    one NeoPixel connected to Pin 12. Define the starting color as (255, 0, 0) (red) 
    and the ending color as (255, 180, 50) (warm yellow). The fade  should happen 
    gradually over 30 seconds using 100 steps for smoothness. Use linear 
    interpolation inside a loop to calculate intermediate RGB values, update the 
    LED color at each step, and add the appropriate delay using utime.sleep().
    After the fade is complete, print "Fade complete". The code should be clean, 
    properly commented, and fully runnable on the board.

  import machine
import neopixel
import utime

# ---------------------------------------------------------
# 1. XIAO RP2040 POWER SETUP
# Pin 11 must be HIGH to provide power to the onboard NeoPixel
# ---------------------------------------------------------
power_pin = machine.Pin(11, machine.Pin.OUT)
power_pin.value(1)

# ---------------------------------------------------------
# 2. NEOPIXEL INITIALIZATION
# The onboard NeoPixel is on Pin 12
# ---------------------------------------------------------
n = neopixel.NeoPixel(machine.Pin(12), 1)

# ---------------------------------------------------------
# 3. COLOR DEFINITIONS & SETTINGS
# ---------------------------------------------------------
START_COLOR = (255, 0, 0)      # Red
END_COLOR   = (255, 180, 50)   # Warm Yellow
STEPS = 100
TOTAL_TIME = 30                # Seconds
STEP_DELAY = TOTAL_TIME / STEPS # 0.3 seconds

def smooth_fade():
    # Get starting RGB values
    r_start, g_start, b_start = START_COLOR
    # Get ending RGB values
    r_end, g_end, b_end = END_COLOR

    print("Starting 30-second fade...")

    for i in range(STEPS + 1):
        # Linear Interpolation Math:
        # Current = Start + (Difference * Percentage_Complete)
        r = int(r_start + (r_end - r_start) * (i / STEPS))
        g = int(g_start + (g_end - g_start) * (i / STEPS))
        b = int(b_start + (b_end - b_start) * (i / STEPS))
        
        # Apply the color
        n[0] = (r, g, b)
        n.write()
        
        # Wait to hit the 30-second target
        utime.sleep(STEP_DELAY)

    print("Fade complete")

# Run the program
smooth_fade()

  

I pasted the promt into thonny.

This step has to be down if the micro-contoller was unplugged "6 Installing MicroPython Firmware" or else you will run into error like i did

Then run the code by pressing F5 or Run -> Run current script

In the above video I edited the time to 10 seconds

Download Week 4 Zip File