Sandrocottus
Sandrocottus

Reputation: 533

Python/MatPlotLib: How to add button to plot live data from serial port

I am learning to plot live graphs using matplotlib, and so far have managed to read live data from serial port and plot it.

Following is my code:-

import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *

import binascii
import serial
import time

x = []
y = []
plt.ion()
cnt=0

z1baudrate = 9600
z1port = 'COM6'

z1serial = serial.Serial(port=z1port, baudrate=z1baudrate)
z1serial.timeout = 1

print (z1serial.is_open)

def makeFig():
    plt.ylim(0,150)
    plt.title('Live Data')
    plt.grid(True)
    plt.ylabel('Temperature')
    plt.plot(x, y, 'ro-', label='F')
    plt.legend(loc='upper left')

if z1serial.is_open:
    while True:
        size = z1serial.inWaiting()
        if size:
            data = z1serial.read(1)
            data = (ord(data))
            print (data)
            if data:
                cnt = cnt+1
                x.append(cnt)
                y.append(data)
                drawnow(makeFig)
                plt.pause(.000001)
                cnt=cnt+1
                if(cnt>50):
                  x.pop(0)
                  y.pop(0)
            z1serial.flushInput()
            z1serial.flushOutput()

        else:
            print ('no data')
        time.sleep(1)
else:
    print ('z1serial not open')

I want to two buttons on the live graph, Start and Stop

Pressing Stop button would stop the live plotting, leaving behind a blank graph.

Pressing Start button would start the live plotting again.

I referred to the link < Matplotlib Python: How to add panel button> but couldn't use it properly to add to my code.

How can I add the buttons to the live plot?

Thanks in advance!

Upvotes: 0

Views: 1008

Answers (0)

Related Questions