0% found this document useful (0 votes)
20 views10 pages

5-Plotting Real Time Serial Data On A GUI

The document outlines a lab experiment for creating a GUI using Python to facilitate serial communication with an Arduino. It details the safety rules, the process of establishing a connection, and the implementation of a real-time plotting feature using libraries like Matplotlib and Tkinter. Additionally, it includes code snippets for setting up the GUI, handling user input, and plotting data received from the Arduino.

Uploaded by

Anila Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views10 pages

5-Plotting Real Time Serial Data On A GUI

The document outlines a lab experiment for creating a GUI using Python to facilitate serial communication with an Arduino. It details the safety rules, the process of establishing a connection, and the implementation of a real-time plotting feature using libraries like Matplotlib and Tkinter. Additionally, it includes code snippets for setting up the GUI, handling user input, and plotting data received from the Arduino.

Uploaded by

Anila Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

_________________________________________________________________________

DEPARTMENT OF AVIONICS ENGINEERING

SUBJECT : Control Systems Lab


SUBJECT CODE : 305312
LAB NO : 05

TITLE : Creating a GUI using Python

SUBMITTED TO : Ms. Anila Ali Ahmed


SEMESTER :
SECTION : B

Marks Obtained
Group Member Group Member Group Member
1 2 3

NAME
REGISTRATION NUMBER
LAB REPORT
PERFORMANCE
TOTAL MARKS

DEADLINE:

DATE OF SUBMISSION:

________________________________________________________________________
Experiment # 05 Page 1 of 10
Control Systems Lab
_________________________________________________________________________

General Safety rules:


Execution of lab experiments is more important than performing accurate experiments
and constructing neat circuits. The first step towards safety is to know the lab itself which
means you must know where the fire extinguishers, electric main safety breaker are and
where the emergency exits. You should also be aware of all the equipment present in the
lab. Following are some rules which you must follow to avoid any unfortunate event.
 Do not wear rings, watches, bracelets, necklaces, and other metal objects in the
lab.
 Make sure your hands are dry
 Make sure your shoes are dry
 Always power down the electrical equipment, disconnect the power cords and
wait for a few seconds before touching the exposed wires
 Make sure all the experimental setup is disconnected from the power supply
before turning it on
 Even if your circuit is of 5 volts, do not consider it less dangerous
 Do not forget to turn off all the equipment after the experiment
 Always get instructions on how to use the new equipment
 Be careful with the soldering iron station, it can cause serious burns and fire
 While using the soldering iron, place it in the special iron stand, not on the table

________________________________________________________________________
Experiment # 05 Page 2 of 10
Control Systems Lab
_________________________________________________________________________

Title: Creating a GUI using Python

Arduino and Python Serial Communication - Adding User Input

In the previous lab we learned how to establish serial communication between the
Arduino UNO and the computer. However the code we used in the previous example
outputs serial data all the time. In this task we are going to output serial data only when it
is requested, by looking for a specific character, in this case-‘g’. Once we receive ‘g’ we
are going to return a data point. This gives us a lot more control over code. Examine the
following code from top to bottom.

We start out by declaring our variables. We have sensorValue which is going to be the
data that's coming from the Arduino, and then we have CH our user input this is going to
be the character that we're looking for to signal when we want to transmit a data point.
Then we move on to the void setup which establishes our serial connection and our baud
rate which is 9600.
Moving into the void loop we enter the main section of our code remember the goal is to
add more control we only want to get information when we request it and that's what the
first main if statement does it monitors if we get a user input and if we get a user input it
executes the codes within the main ifs parenthesis and if not it just waits until it does get
one it does nothing. To determine if we get a user request to get a data point we're going
________________________________________________________________________
Experiment # 05 Page 3 of 10
Control Systems Lab
_________________________________________________________________________

to utilize the available function. What this available function does is returns the amount
of information that's on the serial input, it returns the number of bytes that it received so
if the value of serial.available() is not greater than zero it means we did not receive any
bytes or any user information once serial.available() becomes greater than zero we know
that we have information on the serial buffer so we want to execute the lines within the
parentheses we first encounter a serial.read() what this does is reads the first byte that's on
the buffer and assigns it to user input with the user input we now know what is on the
buffer and we compare it to a known value that's what the second if statement does it
compares the user input to the letter ‘g’ and if it's equal it reads the data point off the
Arduinos third pin which is assigned to data and then once we get that data we print it to
the serial bus now that we've gone through this code let's take a look at the result. Upload
the code to the Arduino, go to serial monitor notice how the data is no longer free
streaming we're only outputting data when we get the input of the character ‘g’ and if this
input is not the character ‘g’ we ignore the input.

Plotting Real Time Serial Data on Python GUI

In the previous lab we obtained the continuous voltage from potentiometer through
Arduino to the serial port of our Arduino UNO. We also learned how to plot serial data in
a python plot. In this lab we will plot with help of a GUI.

First of all we will be importing a few libraries such as

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


from matplotlib.figure import Figure
import tkinter as tk
import numpy as np
import serial as sr

1. matplotlib
Matplotlib provides a special package in order to support plotting on a GUI. We
can access that package by using backends_TKAGG. In this module there is a
FigureCanvasTkAgg which provides support for displaying the data on a GUI.

2. tkinter
It is a Python GUI ID. We will be creating GUI using TK

3. numpy

4. serial
This module is used to communicate with the serial port.

________________________________________________________________________
Experiment # 05 Page 4 of 10
Control Systems Lab
_________________________________________________________________________

Next we start with the code. First of all we write the code for the Main GUI

The code for Main GUI


#-----Main GUI code-----
root = tk.Tk()
root.title('Real Time Plot')
root.configure(background = 'light blue')
root.geometry("700x500") # set the window size

We need to create the object using root = tk.Tk (). It will create a root object. Then we
use root.title(‘’) to specify the title to our window. Next we configure the attributes of our
GUI like what should be the size of the this GUI or the colour of the background. So in
root configuration, we set the background as blue and we are making geometry 700 by
500 pixels.

Now in order to run the GUI, we write this “Run GUI” command, root.mainloop(), so
actually what is happening here is that GUI enter is like a loop itself. So when we run it
our main loop keeps on running which displays all the widgets on this GUI, like buttons
etc.

root.mainloop()

If we run it, a window like below opens up.

________________________________________________________________________
Experiment # 05 Page 5 of 10
Control Systems Lab
_________________________________________________________________________

Now will populate this particular window with the help of plots and buttons etc.
Now we will create a figure object

#------create Plot object on GUI----------


# add figure canvas
fig = Figure();
ax = fig.add_subplot(111)

#ax = plt.axes(xlim=(0,100),ylim=(0, 120)); #displaying only 100


samples
ax.set_title('Serial Data');
ax.set_xlabel('Sample')
ax.set_ylabel('Voltage')
ax.set_xlim(0,100)
ax.set_ylim(-0.5,6)
lines = ax.plot([],[])[0]

First of all we will create this figure object so that we will create a canvas to plot the data.
We create a figure object and then we create the axis for subplot. Next we set its
title,xlabel, ylabel, then we are limiting xlimit to 100, because we are targeting to display
only the 100 elements. It would be a moving plot kind of thing. Then we have limit y-
axis because voltage will be varying from 0 to 5 volt only, we make it to minus 0.5 to 5
so that we have a visualization of 0 as well.

Next is the most important thing because we are interested to display our running plot
that means we are changing the lines within the plot so there are two ways like we
cleared the previous plot and then create a new one so in that case whatever we have
written that goes off and it looks kind like a window is updating itself. In contrast we
don't want that kind of plot we want a plot to be static that means access to be straight.
Again only the lines within the plot should be varying, that is why we got this ‘lines’
object from the plot, it gives an array in which we can set x data and the y data. lines =
ax.plot([],[])[0]

canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.


canvas.get_tk_widget().place(x = 10,y=10, width = 500,height = 400)
canvas.draw()

Now we have created the canvas using FigureCanvasTkAgg, for corresponding figure
(first argument of the function) and with the master obviously the root (second argument
of the function) because we want to display it on on the root window.

________________________________________________________________________
Experiment # 05 Page 6 of 10
Control Systems Lab
_________________________________________________________________________

Next we specify its place and then we create/draw the graph so these are the commands
to display the graph on a GUI. Now let’s run it and see how it looks like

A plot window appears up on the GUI as shown above.

Now the next task is to create two buttons to start and stop plotting the data that we are
getting through the Arduino.

We will be creating two button when we push the start button, the plot should start up and
when we press close button so the plot should stop.
Now we will create buttons, we will be using tinker widgets of button.

#----------create button---------
root.update();
start = tk.Button(root, text = "Start", font =
('calbiri',12),command = lambda: plot_start())
start.place(x = 100, y = 450 )

root.update();
stop = tk.Button(root, text = "Stop", font = ('calbiri',12), command
= lambda:plot_stop())
stop.place(x = start.winfo_x()+start.winfo_reqwidth() + 20, y = 450)

________________________________________________________________________
Experiment # 05 Page 7 of 10
Control Systems Lab
_________________________________________________________________________

root.update() is to update them whatever we have put previously. Otherwise sometimes it


gives absurd results.
Then we create the start button using tk.button(), this function has got a couple of
arguments. First goes the window name og our GUI, where we want to create the button,
the next argument expects the name of the button, and then the font of the text of the
button. Finally comes the argument that contains the function that is to be performed
once the button is pressed. As we want a particular function to be executed as soon as we
press this start. The information of that function is created here, we create it using lambda
function otherwise this function run as soon as we started.

Next we have placed it at x value 100 and Y value of 450. Similarly we are putting a stop
button with respect to our start button. And the placement of stop button has been done
with reference to the x and y positions of the start button.

Next we will start with the serial port because as soon as this window starts we want it to
establish a link with the serial port of our Arduino.

#----start serial port----


s = sr.Serial('COM6',9600);
s.reset_input_buffer()

Here we specify the com port of our Arduino uno and then provide the baud rate.
Reset_input_buffer() is used to flush whatever input data and garbage input it may have
already

________________________________________________________________________
Experiment # 05 Page 8 of 10
Control Systems Lab
_________________________________________________________________________

Next we will create the definitions of the function which will be executing upon pressing
the start/stop buttons. We may use a while loop for this task as it keeps on plotting but
there is a problem with this GUI. If we use infinite loop or a loop there, it freezes the
window and only that loops keeps on running and nothing else continues to work, like no
other buttons. So we have this option to do it using root.after(). Root.after() executes a
particular function at a regular interval of time.

Next we define the plot function.

#------global variables
data = np.array([])
cond = False

#-----plot data-----
def plot_data():
global cond, data

if (cond == True):

a = s.readline()
a.decode()

if(len(data) < 100):


data = np.append(data,float(a[0:4]))
else:
data[0:99] = data[1:100]
data[99] = float(a[0:4])

lines.set_xdata(np.arange(0,len(data)))
lines.set_ydata(data)

canvas.draw()

root.after(1,plot_data)

We set the condition to false. Here we will be using a Boolean variable ‘cond’. The cond
variable goes fasle the plot data function does nothing. And when the cond is equal to
true the function plot data reads a new line, decodes it to string, converts to float, appends
to the data array if the array length is less than 100. When the array hass been filled till
100 samples, the else code here is shifting the sample 1 till 99 to sample number 0 till 98

________________________________________________________________________
Experiment # 05 Page 9 of 10
Control Systems Lab
_________________________________________________________________________

and discarding the sample number 0. Next it appends the fresh data read from serial port
to sample 99. In this way the plot appears to be updating and real time.
Next we create the definitions of start and stop buttons.

def plot_start():
global cond
cond = True
s.reset_input_buffer()

def plot_stop():
global cond
cond = False

Here we use global condition and we will make condition equals to true because only
then a plot will start and again we flush the garbage data using reset input buffer function.
Similarly we define plot stop function.

Below is the plotted data received from the Arduino.

Task for the lab report.

1. Implement the code learned in the lab and reproduce your results with voltage
signal varying from 0-5 V.

________________________________________________________________________
Experiment # 05 Page 10 of 10
Control Systems Lab

You might also like