Skip to content

5. Input & Output device

This week, I explored the use of MicroPython to control various input/output devices, diving deeper into embedded programming. My focus was on creating precise control over these devices to understand their behavior and capabilities better.

LED & Buzzer & Motor

I developed a MicroPython code that turns on multiple devices simultaneously, such as LEDs, buzzers, and sensors, for a few seconds. The goal was to synchronize their operations and test their responses. Here’s a snippet of the code used:

from machine import Pin
import time
LED=Pin(26,Pin.OUT)
Buzzer=Pin(15,Pin.OUT)
motor=Pin(13,Pin.OUT)

motor.value(1)
Buzzer.value(1)
LED.value(1)
time.sleep(3)

Result:

Tone with Buzzer

This time, rather than simply turning on the buzzer, I experimented further by modifying the code to play a specific melody. The melody chosen was “Moonlight Sonata,” which required precise tuning of the buzzer’s frequencies to replicate the musical notes accurately. The challenge was in timing the notes and managing the transitions smoothly, which pushed me to better understand the PWM (Pulse Width Modulation) functionalities in MicroPython.

code:

from machine import Pin, PWM
import time

# Define note frequencies (in Hz)
C4 = 261
D4 = 294
E4 = 329
F4 = 349
G4 = 392
A4 = 440
B4 = 494
C5 = 523

# Note duration in seconds
whole = 1.0
half = 0.5
quarter = 0.25
eighth = 0.125

# Define the PWM pin for the buzzer
buzzer = PWM(Pin(15), freq=440, duty=512)

# Function to play a note
def play_tone(frequency, duration):
    if frequency == 0:  # Rest
        time.sleep(duration)
    else:
        buzzer.freq(frequency)
        buzzer.duty(512)  # 50% duty cycle
        time.sleep(duration)
        buzzer.duty(0)  # Turn off buzzer
        time.sleep(0.05)  # Short delay between notes

# Moonlight Sonata melody (first few notes)
melody = [
    (C4, quarter), (E4, quarter), (G4, quarter), (C5, quarter),
    (C4, quarter), (E4, quarter), (G4, quarter), (C5, quarter),
    (C4, quarter), (E4, quarter), (G4, quarter), (C5, quarter),
    (B4, quarter), (G4, quarter), (E4, quarter), (C4, quarter)
]

# Play the melody
for note, duration in melody:
    play_tone(note, duration)

# Turn off the buzzer
buzzer.deinit()

Result:

This week’s experiments deepened my understanding of MicroPython and its potential in controlling I/O devices. Working with sound and music showcased the creative possibilities of microcontrollers beyond basic tasks.


Last update: September 14, 2024