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 )