Atahan GüneyEEE

ProjectsProjeler / SW-02

Desktop tool · UART telemetry & DSPMasaüstü aracı · UART telemetrisi ve DSP

SerialScope

A Python desktop tool for microcontroller labs. It plots incoming UART data live, filters it in real time with an adjustable low-pass filter, and sends new parameters back to the board while the board keeps streaming.

Mikrodenetleyici laboratuvarları için bir Python masaüstü aracı. Gelen UART verisini canlı çiziyor, ayarlanabilir bir alçak geçiren filtreyle gerçek zamanlı filtreliyor ve kart veri göndermeye devam ederken ona yeni parametreler yolluyor.

Python 3PySerialTkinter / ttkMatplotlibthreadingcollections.dequeArduino · ESP32 · STM32

The problem

In the microcontroller labs the sensor readings were noisy, and the loop for trying a new filter was slow: change a constant in the C code, compile, flash, open the serial monitor, squint at the numbers. Changing a PID setpoint meant the same loop again. The Arduino serial plotter shows the data but can't filter it, export it or send anything back.

The idea behind SerialScope was simple: keep the firmware dumb, let it stream raw values and accept a few text commands, and do the filtering, plotting and tuning on the PC where changing a number takes a second.

Problem

Mikrodenetleyici laboratuvarlarında sensör okumaları gürültülüydü ve yeni bir filtreyi denemenin döngüsü yavaştı: C kodunda bir sabiti değiştir, derle, karta yükle, seri monitörü aç, sayılara göz kısarak bak. Bir PID ayar noktasını değiştirmek de aynı döngü demekti. Arduino'nun seri çizicisi veriyi gösteriyor ama filtreleyemiyor, dışa aktaramıyor ve karta bir şey gönderemiyor.

SerialScope'un arkasındaki fikir basitti: firmware'i sade tut, ham değerleri göndersin ve birkaç metin komutunu kabul etsin; filtreleme, çizim ve ayarlamayı ise bir sayıyı değiştirmenin bir saniye sürdüğü PC tarafında yap.

SerialScope window: connection and DSP controls on the left, a live plot of a noisy raw signal, its EMA-filtered version and a reference channel in the centre, tuning sliders and a UART monitor on the right.

Simulation mode: raw CH1, EMA-filtered CH1 and the CH2 reference.Simülasyon modu: ham CH1, EMA ile filtrelenmiş CH1 ve CH2 referansı.

Architecture

MCU→ UART →reader thread→deque buffer→Tk main loop→EMA + plot + CSV

The main design problem in a tool like this is that reading the serial port blocks, and Tkinter must only be touched from its own thread. If you read the port inside the GUI loop, the window freezes; if you update the GUI from the reader thread, it crashes at random.

So SerialScope uses a producer–consumer setup. A background thread does nothing except read lines from PySerial, parse them and append them to a fixed-length collections.deque. The Tk main loop wakes up on a timer, takes what is in the buffer, applies the filter and redraws the Matplotlib plot. Because the deque has a maximum length, old samples fall off the end on their own and memory use stays flat no matter how long the session runs.

Commands go the other way: sliders and macro buttons write short ASCII lines to the same port.

Mimari

MCU→ UART →okuyucu thread→deque tamponu→Tk ana döngüsü→EMA + grafik + CSV

Bu tür bir araçtaki asıl tasarım problemi şu: seri portu okumak bloklayan bir işlem, Tkinter'a ise sadece kendi thread'inden dokunulmalı. Portu GUI döngüsünün içinde okursanız pencere donuyor; GUI'yi okuyucu thread'den güncellerseniz rastgele çöküyor.

Bu yüzden SerialScope üretici-tüketici yapısı kullanıyor. Arka plandaki bir thread sadece PySerial'den satır okuyor, ayrıştırıyor ve sabit uzunluklu bir collections.deque'ya ekliyor. Tk ana döngüsü bir zamanlayıcıyla uyanıyor, tamponda ne varsa alıyor, filtreyi uyguluyor ve Matplotlib grafiğini yeniden çiziyor. Deque'nun bir maksimum uzunluğu olduğu için eski örnekler kendiliğinden düşüyor ve oturum ne kadar uzun sürerse sürsün bellek kullanımı sabit kalıyor.

Komutlar ters yönde gidiyor: kaydırıcılar ve makro butonları aynı porta kısa ASCII satırları yazıyor.

The EMA low-pass filter

The filter is an exponential moving average, which is the discrete version of a first-order RC low-pass:

y[n] = α·x[n] + (1 − α)·y[n−1]        0 < α ≤ 1

It needs one multiply-add per sample and one stored value, which is why it is so common on microcontrollers. A small α means heavy smoothing and more lag; α = 1 means no filtering at all. Comparing it with an RC circuit gives a time constant of τ = Ts(1 − α)/α, so the cut-off frequency is roughly

f_c ≈ α·f_s / (2π(1 − α))       # ≈ α·f_s / 2π for small α

In the app, α is a slider and the raw and filtered signals are drawn on the same axes. Seeing the lag grow while the noise shrinks taught me more about the trade-off than the formula did.

EMA alçak geçiren filtresi

Filtre, birinci dereceden RC alçak geçiren filtrenin ayrık hali olan üstel hareketli ortalama:

y[n] = α·x[n] + (1 − α)·y[n−1]        0 < α ≤ 1

Örnek başına bir çarpma-toplama ve saklanan tek bir değer istiyor; mikrodenetleyicilerde bu kadar yaygın olmasının sebebi de bu. Küçük α daha güçlü yumuşatma ve daha fazla gecikme demek; α = 1 ise hiç filtreleme yok demek. Bir RC devresiyle karşılaştırınca zaman sabiti τ = Ts(1 − α)/α çıkıyor, yani kesim frekansı yaklaşık olarak

f_c ≈ α·f_s / (2π(1 − α))       # küçük α için ≈ α·f_s / 2π

Uygulamada α bir kaydırıcı ve ham sinyal ile filtrelenmiş sinyal aynı eksende çiziliyor. Gürültü azalırken gecikmenin arttığını gözle görmek, bu ödünleşimi bana formülden daha iyi öğretti.

The protocol

I kept the protocol as plain text on purpose. It can be typed by hand in any serial terminal, read in a log, and parsed on the board with a few lines of C.

DirectionFormatExample
MCU → PCcomma-separated values, one line per sample25.40,22.10
PC → MCUKEY:valueSETPOINT:25.0, GAIN:5.0
PC → MCUcommandsCMD:ESTOP

A minimal board-side loop for an Arduino looks like this (illustrative):

void loop() {
  float raw = analogRead(A0) * (5.0 / 1023.0);
  Serial.print(raw); Serial.print(','); Serial.println(setpoint);
  if (Serial.available()) {
    String line = Serial.readStringUntil('\n');
    if (line.startsWith("SETPOINT:")) setpoint = line.substring(9).toFloat();
  }
  delay(20);   // ~50 samples per second
}

Protokol

Protokolü bilerek düz metin olarak tuttum. Herhangi bir seri terminalde elle yazılabiliyor, log'da okunabiliyor ve kartta birkaç satır C ile ayrıştırılabiliyor.

YönBiçimÖrnek
MCU → PCvirgülle ayrılmış değerler, her örnek bir satır25.40,22.10
PC → MCUANAHTAR:değerSETPOINT:25.0, GAIN:5.0
PC → MCUkomutlarCMD:ESTOP

Bir Arduino için en basit kart tarafı döngüsü şöyle görünüyor (örnek amaçlı):

void loop() {
  float raw = analogRead(A0) * (5.0 / 1023.0);
  Serial.print(raw); Serial.print(','); Serial.println(setpoint);
  if (Serial.available()) {
    String line = Serial.readStringUntil('\n');
    if (line.startsWith("SETPOINT:")) setpoint = line.substring(9).toFloat();
  }
  delay(20);   // saniyede ~50 örnek
}

Virtual MCU mode

There is a built-in simulator that produces a noisy sensor signal and reacts to the same commands. I added it for two reasons: I wanted to work on the tool without a board on the desk, and I wanted anyone who downloads it to see what it does in ten seconds. It also turned out to be useful for testing, because the simulated signal is known, so I can check that the filtered output looks the way the formula says it should.

What I learned

  • Threads and GUIs: one thread owns the GUI, everything else talks to it through a queue or buffer.
  • A bounded buffer is the easiest way to make a long-running tool not leak memory.
  • Plain-text protocols cost a few extra bytes but save hours of debugging.
  • Simple filters are worth understanding fully before reaching for complex ones. An EMA with the right α solved most of the noise problems I had in the labs.

Sanal MCU modu

Gürültülü bir sensör sinyali üreten ve aynı komutlara tepki veren yerleşik bir simülatör var. Bunu iki sebeple ekledim: masada kart olmadan da araç üzerinde çalışabilmek istedim ve indiren herkesin aracın ne yaptığını on saniyede görebilmesini istedim. Test için de faydalı oldu, çünkü simüle edilen sinyal bilindiği için filtrelenmiş çıktının formülün söylediği gibi görünüp görünmediğini kontrol edebiliyorum.

Ne öğrendim

  • Thread'ler ve arayüzler: arayüzün sahibi tek bir thread'dir, diğer her şey onunla bir kuyruk ya da tampon üzerinden konuşur.
  • Uzun süre çalışan bir aracın bellek sızdırmaması için en kolay yol sınırlı bir tampon kullanmak.
  • Düz metin protokoller birkaç byte fazlaya mal oluyor ama saatlerce hata ayıklamaktan kurtarıyor.
  • Karmaşık filtrelere geçmeden önce basit olanları tam olarak anlamak gerekiyor. Doğru α değeriyle bir EMA, laboratuvarlarda yaşadığım gürültü problemlerinin çoğunu çözdü.