Lab 09

python -m pip install matplotlib
python -m pip install numpy

Code for Pico - 8b UART generator

import sys
import math
 
SAMPLE_COUNT = 1000
FREQ = 20          # 20 Hz
AMPL = 120         # amplitude (max ±120)
OFFSET = 128       # offset 8bit 
 
def clip8(v):
    if v < 0: return 0
    if v > 255: return 255
    return v
 
def generate_sine():
    for i in range(SAMPLE_COUNT):
        t = i / SAMPLE_COUNT
        y = math.sin(2 * math.pi * FREQ * t)
        val = clip8(int(OFFSET + AMPL * y))
        sys.stdout.write(str(val) + ",")
    sys.stdout.write("\n")
 
def generate_square():
    for i in range(SAMPLE_COUNT):
        t = i / SAMPLE_COUNT
        y = 1 if math.sin(2 * math.pi * FREQ * t) >= 0 else -1
        val = clip8(int(OFFSET + AMPL * y))
        sys.stdout.write(str(val) + ",")
    sys.stdout.write("\n")
 
def generate_triangle():
    for i in range(SAMPLE_COUNT):
        t = (i / SAMPLE_COUNT) * FREQ
        # trojúhelník 0–1 → -1..1
        y = 2 * abs(2 * (t % 1) - 1) - 1
        val = clip8(int(OFFSET + AMPL * y))
        sys.stdout.write(str(val) + ",")
    sys.stdout.write("\n")
 
print("Pico 8bit test generator ready.")
 
while True:
    cmd = sys.stdin.read(1)
 
    if cmd == "a":
        generate_sine()
    elif cmd == "b":
        generate_square()
    elif cmd == "c":
        generate_triangle()
    else:
        sys.stdout.write("ERR\n")

Code for PC - draw the signal

import serial
import numpy as np
import matplotlib.pyplot as plt
 
PORT = "/dev/cu.usbmodem1101"   # COM port
BAUD = 115200
 
def get_samples(cmd):
    """Send command ('a','b','c') and receive CSV with samples."""
    with serial.Serial(PORT, BAUD, timeout=3) as ser:
        ser.write(cmd.encode())         # send command
        line = ser.readline().decode()  # receive data
        parts = line.strip().split(",")
 
        # validata data - interval 0–255
        samples = [int(x) for x in parts if x.isdigit()]
        return np.array(samples)
 
def plot_signal(samples, title):
    plt.figure(figsize=(12,4))
    plt.plot(samples, drawstyle="steps-pre")
    plt.ylim(-10, 265)
    plt.title(title)
    plt.xlabel("sample")
    plt.ylabel("value (0–255)")
    plt.grid(True)
    plt.show()
 
# ===== run =====
print("Connecting to Pico on", PORT)
 
cmd = input("Command (a=sine, b=square, c=triangle): ").strip()
 
if cmd not in ("a","b","c"):
    print("Unknown command.")
    exit()
 
samples = get_samples(cmd)
print("Received samples:", len(samples))
 
titles = {"a": "Sinus", "b": "Square", "c": "Rectangle"}
plot_signal(samples, titles[cmd])

courses/be2m37mam/labs/09.txt · Last modified: 2025/11/27 13:14 by viteks