Skip to content

Week 05: Embedded programming

This week I worked on defining my final project idea and started to getting used to the documentation process.

Group Assignment

We researched various types of microcontroller boards and compared their features. Additionally, we explored different programming languages and compared how many of them can be used to program the same microcontrollers, visit our Group Website.

Individual Assignment

↪ Hardware Setup and Comparison

Click to download Arduino IDE and Thonny

Feature Arduino IDE Thonny
Language C++ Python
Ease of Use Moderate Beginner-friendly
Primary Use Microcontrollers (e.g., Arduino) Python programming and microcontrollers
Debugger Limited Built-in
Learning Curve Steeper Gentle
Community Strong for Arduino Active Python and MicroPython

☆ Important

If you’re using Python with Thonny and have the same microcontroller, I recommend the following to display messages on the microcontroller screen: Create a file named ssd1306.py and save it to the microcontroller device. You can obtain the file from this website or download it here.

☆ Don’t forget to link the microcontroller!

↝ Using Arduino IDE

Set Up
  • Do the same using this Website, but make sure that you choose ESP32S3.

  • Navigate to File > Preferences.

  • Fill “Additional Boards Manager URLs” with the url below: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

  • Navigate to Tools > Board > Boards Manager.

  • Type the keyword “esp32” in the search box, select the Espressif one, and install it.

  • Navigate to Tools > Board > ESP32 and select “XIAO_ESP32C3”. The list of board is a little long and you need to roll to the buttom to reach it.

Result

Coding
  • I codded this using C++.
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on (HIGH is the voltage level)
  delay(500);                      // wait for a second
  digitalWrite(LED_BUILTIN, LOW);   // turn the LED off by making the voltage LOW
  delay(500);                      // wait for a second
}

↝ Using Thonny

Set Up
  • Navigate Run > Configure Interpreter.

  • Set these values and install.

  • Navigate ****, set these values and install.

  • If the shell appears like this, it means you’re on the right track.

Result

Coding
  • I codded this using Python.
import machine
import time
import ssd1306

# Initialize the LED
led = machine.Pin(26, machine.Pin.OUT)

# Initialize I2C for the OLED display
i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))  # Adjust pins as necessary
oled = ssd1306.SSD1306_I2C(128, 64, i2c)  # Adjust resolution as necessary

while True:
    # Turn the LED on
    led.value(1)
    oled.fill(0)  # Clear the display
    oled.text('On!', 1, 10)  # Display "On!"
    oled.show()  # Update the display
    time.sleep(1)

    # Turn the LED off
    led.value(0)
    oled.fill(0)  # Clear the display
    oled.text('Off!', 1, 10)  # Display "Off!"
    oled.show()  # Update the display
    time.sleep(1)

↪ Warriors’ Rest

For the upcoming codes, all you need to do is one thing.

↪ Activities

Press on Activities to download.

↝ Easy Mode:

C++ Code


The code uses random numbers to control an LED’s on and off times. It initializes serial communication and ensures different random values each time with randomSeed(). The LED’s timing is printed to the serial monitor and repeats continuously. Click to download

int randNumber;
int randDel;

// the setup function runs once when you press reset or power the board 
void setup () {
    // initialize digital pin LED_BULLTIN as an output.
    pinMode (LED_BUILTIN, OUTPUT);

    Serial.begin(9600);
    // if analog input pin 0 is unconnected, random analog
    // noise will cause the call to randomSeed() to generate
    // different seed numbers each time the sketch runs.
    // randomSeed() will then shuffle the random function.
    randomSeed(analogRead(0));
}
// the loop function runs over and over again forever 
void loop() {
    randNumber = random(1,6); // Random value from 1 to 5
    randDel = random(1,6); // Random value from 1 to 5
    digitalWrite(LED_BUILTIN, HIGH);        // turn the LED on (HIGH is the voltage level)
    delay(randDel*1000);                             // wait for a second
    Serial.println(randDel);
    digitalWrite(LED_BUILTIN, LOW);        // turn the LED on (HIGH is the voltage level)
    Serial.println(randNumber);
    delay(randNumber*1000);  
}
Python Code


The code controls an LED and an OLED display using random values for timing. It seeds the random number generator with an ADC reading and generates random on/off durations for the LED. These durations are displayed on the OLED screen and repeated indefinitely. Click to download

import machine
import time
import random
import ssd1306

# Initialize the LED pin
led = machine.Pin(26, machine.Pin.OUT)  # Use the built-in LED pin

# Initialize I2C for the OLED display
i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))  # Adjust pins as necessary
oled = ssd1306.SSD1306_I2C(128, 64, i2c)  # Adjust resolution as necessary

# Seed the random number generator
random.seed(machine.ADC(0).read())  # Use ADC0 for seeding

while True:
    rand_number = random.randint(1, 5)  # Random value from 1 to 5
    rand_del = random.randint(1, 5)      # Random value from 1 to 5

    led.value(1)  # Turn the LED on
    oled.fill(0)  # Clear the display
    oled.text('On for ', 0, 10)  # Display "On for"
    oled.text(str(rand_del) + ' sec', 0, 20)  # Display the random delay
    oled.show()  # Update the display
    time.sleep(rand_del)  # Wait for rand_del seconds

    led.value(0)  # Turn the LED off
    oled.fill(0)  # Clear the display
    oled.text('Off for ', 0, 10)  # Display "Off for"
    oled.text(str(rand_number) + ' sec', 0, 20)  # Display the random duration
    oled.show()  # Update the display
    time.sleep(rand_number)  # Wait for rand_number seconds

↝ Medium Mode:

I’ve upgraded this question to an advanced one, because the normal one is for Noobs.

C++ Code


The code converts a user-provided message into Morse code using the built-in LED. It defines durations for dots, dashes, and gaps, and encodes each letter’s Morse code with specific delays. The message is sent letter by letter, with the LED turning on and off accordingly. Click to download

long dot = 1000; // Duration of a dot
long dash = 2000; // Duration of a dash
long dgap = 500; // Duration of a gap between dots and dashes
long lgap = 3000; // Duration of a gap between letters
long wgap = 5000; // Duration of a gap between words

long code[26][4] = {
    {dot, dash, 0, 0}, // A
    {dash, dot, dot, dot}, // B
    {dash, dot, dash, dot}, // C
    {dash, dot, dot, 0}, // D
    {dot, 0, 0, 0}, // E
    {dot, dot, dash, dot}, // F
    {dash, dash, dot, 0}, // G
    {dot, dot, dot, dot}, // H
    {dot, dot, 0, 0}, // I
    {dot, dash, dash, dash}, // J
    {dash, dot, dash, 0}, // K
    {dot, dash, dot, dot}, // L
    {dash, dash, 0, 0}, // M
    {dash, dot, 0, 0}, // N
    {dash, dash, dash, 0}, // O
    {dot, dash, dash, dot}, // P
    {dash, dash, dot, dash}, // Q
    {dot, dash, dot, 0}, // R
    {dot, dot, dot, 0}, // S
    {dash, 0, 0, 0}, // T
    {dot, dot, dash, 0}, // U
    {dot, dot, dot, dash}, // V
    {dot, dash, dash, 0}, // W
    {dash, dot, dot, dash}, // X
    {dash, dot, dash, dash}, // Y
    {dash, dash, dot, dot} // Z
};

void setup() {
    pinMode(LED_BUILTIN, OUTPUT); // Use built-in LED for Morse code
    Serial.begin(9600); // Start serial communication at 9600 baud
    Serial.println("Enter a word to send in Morse code:");
}

void loop() {
    if (Serial.available() > 0) {
        String message = Serial.readStringUntil('\n'); // Read input until newline
        message.toUpperCase(); // Convert to uppercase
        sendMorse(message); // Send the message in Morse code
        Serial.println("Enter another word to send in Morse code:");
    }
}

void sendMorse(String message) {
    for (int i = 0; i < message.length(); i++) {
        char letter = message[i];
        if (letter >= 'A' && letter <= 'Z') {
            int index = letter - 'A';
            for (int j = 0; j < 4; j++) {
                if (code[index][j] == 0) break; // End of letter
                digitalWrite(LED_BUILTIN, HIGH);
                delay(dgap);
                digitalWrite(LED_BUILTIN, LOW);
                delay(code[index][j]);
            }
            delay(lgap); // Gap between letters
        } else if (letter == ' ') {
            delay(wgap); // Gap between words
        }
    }
}
Python Code

Working on it..

↝ Hard Mode:

C++ Code


The code controls the built-in LED based on a user-defined delay time input through the Serial Monitor. It updates the blinking interval of the LED with each valid integer input. The LED blinks on and off with delays of 100 milliseconds for “on” and 1000 milliseconds for “off.” Click to download

void setup() {
  // Initialize digital pin LED_BUILTIN as an output
  pinMode(LED_BUILTIN, OUTPUT);

  // Start serial communication
  Serial.begin(9600);
}

// Variable to store the user-defined delay
int delayTime = 1; // Default delay time (1 second)

void loop() {
  // Check if there is input from the Serial Monitor
  if (Serial.available() > 0) {
    // Read the input as a string
    String input = Serial.readString();

    // Convert the input string to an integer
    int newDelayTime = input.toInt();

    // Validate the input
    if (newDelayTime > 0) {
      delayTime = newDelayTime; // Update the delay time
    }
  }

  // Blink the LED
  digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
  delay(delayTime*100);               // Wait for the specified delay time
  digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
  delay(delayTime*1000);               // Wait for the specified delay time
}
Python Code


The code controls an LED and an OLED display with a user-defined delay time. A separate thread prompts the user to input a new delay, updating the LED’s on/off timing. The main loop displays the LED’s state and duration on the OLED screen while controlling the LED’s blinking. Click to download

import machine
import time
import ssd1306
import _thread

# Initialize the LED pin
led = machine.Pin(26, machine.Pin.OUT)  # Use the built-in LED pin (adjust pin number as necessary)

# Initialize I2C for the OLED display
i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))  # Adjust pins as necessary
oled = ssd1306.SSD1306_I2C(128, 64, i2c)  # Adjust resolution as necessary

# Variable to store the user-defined delay
delay_time = 1  # Default delay time (1 second)

# Function to prompt for user input
def prompt_for_delay():
    global delay_time
    while True:
        print("Enter new delay time in seconds (or press Enter to keep current):")
        input_line = input().strip()  # Use input() to read from the console
        if input_line:
            try:
                new_delay_time = int(input_line)
                if new_delay_time > 0:
                    delay_time = new_delay_time  # Update the delay time
            except ValueError:
                pass  # Ignore invalid input silently

# Start the input thread
_thread.start_new_thread(prompt_for_delay, ())

# Main loop
while True:
    # Turn the LED on
    led.value(1)
    oled.fill(0)  # Clear the display
    oled.text("LED ON", 0, 0)
    oled.text(f"Duration: {delay_time:.1f} sec", 0, 10)  # Display ON duration
    oled.show()
    time.sleep(delay_time)  # Wait for the specified ON duration

    # Turn the LED off
    led.value(0)
    oled.fill(0)  # Clear the display
    oled.text("LED OFF", 0, 0)
    oled.text(f"Duration: {delay_time:.1f} sec", 0, 10)  # Display OFF duration
    oled.show()
    time.sleep(delay_time)  # Wait for the specified OFF duration

Keywords

Keywords Meanings
Microcontroller A compact integrated circuit designed to govern a specific operation in an embedded system.
Micropython A tiny open source Python programming language interpretor that runs on small embedded development boards.

Last update: December 12, 2024