Skip to content

Instantly share code, notes, and snippets.

@i3130002
Last active January 26, 2022 07:37
Show Gist options
  • Save i3130002/8a5d30c68bac5eee5731f1d6bc96a6b8 to your computer and use it in GitHub Desktop.
Save i3130002/8a5d30c68bac5eee5731f1d6bc96a6b8 to your computer and use it in GitHub Desktop.
Python Serial Plotter

Python Serial Plotter High Frequency UART Plot AVR Arduino

This code plots serial data using mathplotlib and with high frequency. You might use it as a crude oscilloscope

import serial
from threading import Thread
import threading
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

serialPort = "/dev/ttyUSB0"
serialBaud = 115200

print('Trying to connect to: ' + str(serialPort) +
      ' at ' + str(serialBaud) + ' BAUD.')
serialConnection = serial.Serial(serialPort, serialBaud, timeout=4)
print('Connected')

plotXSize = 10000
isRun = True
serialData = []
plotData = list(range(-plotXSize, 1024+1))[-plotXSize:]

serialDataLock = threading.Lock()


def readerThreadWorker():
    global plotData, serialData
    time.sleep(1.0)
    while (isRun):
        time.sleep(0.1)
        serialDataLock.acquire()
        data = serialData.copy()
        serialData = []
        serialDataLock.release()
        if len(data) == 0:
          continue
        plotData.extend(data)
        plotData = plotData[-plotXSize:]
        print(len(data) / 0.1, "Data/Second")


def writerThreadWorker():
    global serialData
    time.sleep(1.0)
    serialConnection.reset_input_buffer()
    while (isRun):
        data = serialConnection.readline()[:-1]
        data = int(str(data, 'utf-8', 'ignore'))
        serialDataLock.acquire()
        serialData.append(data)
        serialDataLock.release()


writerThread = Thread(target=writerThreadWorker)
writerThread.start()
readerThread = Thread(target=readerThreadWorker)
readerThread.start()


x = list(range(1, plotXSize+1))
y = plotData

# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y)  # Returns a tuple of line objects, thus the comma

while 1:
    line1.set_ydata(np.array(plotData))
    ax.set_ylim([max(0,min(plotData)), max(plotData)])
    fig.canvas.draw()
    fig.canvas.flush_events()
    time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment