# Plotting a real time graph of sensor data from Arduino on Processing, MatLab or Python

I have an accelerometer connected to my Arduino Due to spit out data on my serial monitor as described in my earlier post. I'm trying to find a sketch I could use to plot a continuous real-time graph on either Processing, MatLab or using Python MatPlot.

The accelerometer data is stored in arrays of `xArray[k]` for the x-coordinate values, `yArray[k]` for the y-coordinate values and `zArray[k]` for the z-coordinate values. How can I plot a real-time graph of these values? Thanks in advance.

I hope this is helpful to you.

First, you need to read about serial communication between matlab and arduino. You need to establish communication between those two first.

Then take note of the format of the data coming out of your Accelerometer. In my case, I'm working with IMU and my data format is as an example: #YPR = 2.34, 13.23, -2.20

Then, from Matlab, you need to write a script to be able to read this string and identify any floating-point value.

This is what I did in Matlab. YPR = Yaw, Pitch, Roll

``````data = fscanf(s);              %Read Data from Serial
[Y(count),P(count),R(count)] = strread(data, '#YPR = %f,%f,%f');
``````

Then you have to set up the plot and force matlab to update the plot in real time.

``````%set() is used to set graphic object properties
set(plotGraph1,'XData',time,'YData',Y,'color','r');
set(plotGraph2,'XData',time,'YData',P,'color','g');
set(plotGraph3,'XData',time,'YData',R,'color','b');
drawnow;           %force matlab to updata plot instantaneously
``````

The link below is a good place for you to get going. But you need to make some modifications to it though.

https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/

• Thanks @goddar..will have a look and tell you how it turned out. Cheers
Oct 30, 2015 at 16:37
• So @goddar ..I tried out the matlab code but I couldn't get it working properly, I mucked around with that of python , could only get it reading out values rather slowly and with the unbuffered data sketch in my first post arduino.stackexchange.com/questions/17206/… but when I tried it with the buffered data sketch it froze.....the data couldn't even read out but there were no errors on the stacktrace. Below is the python sketch
Nov 1, 2015 at 11:19
• Sorry for the late reply. I did some work on this mainly on Matlab and Im not that familiar with python. In the matlab you have to make sure that you set matching COM port and baud rate. You can use Test and Measurement Tool toolbox to check whether connection is made between your device and the computer. Once connected, you should first try to read the data continuously without plotting it yet. Once you can get there, just follow the link that I provide above. You need to do some modifications to it. Nov 16, 2015 at 10:57
• In Matlab, set InputBufferSize to 50000 and set ReadAsyncMode to 'continuous'. Nov 16, 2015 at 10:58
`````` import serial #import Serial Library
import numpy  # Import numpy
import matplotlib.pyplot as plt #import matplotlib library
from drawnow import *

accelX = []
accelY = []
accelZ = []

arduinoData = serial.Serial('COM4', 115200)
plt.ion()    #Tell matplotlib you want interactive mode to plot live data
cnt = 0
def makeFig():         #Create a function that makes our desired plot
#plt.ylim(0,1000)                #Set the limit on the y axis
plt.title('Sensor data')         #Set the title
plt.grid(True)                   #Set The grid
plt.ylabel('Axis Acceleration')  #Label the y axis
plt.plot(accelX,'ro-', label='Raw X Acceleration') #Set the line plot
plt.ylim(0, 1000)
plt.legend(loc = 'upper left')
plt2 = plt.twinx()  #Create a new object of plt2
plt2.plot(accelY, 'b^-', label='Raw Y Acceleration')
#plt2.ylim(0,1000)
plt2.legend(loc='center right')
plt2.ticklabel_format(useOffset=False) #Compel matplotlib not to autoscale
#plt3 = plt.twinx()
plt.plot(accelZ, 'go-', label='Raw Z Acceleration')
plt.legend(loc='upper right')
plt.ylim(0,1000)

while True: #While loop that loops forever
while(arduinoData.inWaiting() == 0):   #Wait here until there is data
pass #do nothing
dataArray = arduinoString.strip().strip('\n')  #Split into an array
# Ensure that you are not working on empty line
if arduinoString:
dataArray = arduinoString.split(",")
# Ensure that index is not out of range
if len(dataArray) > 1:
xAxis = int(dataArray) #Convert first element to int insert in xAxis
yAxis = int(dataArray) #Convert second element to int insert in yAxis
zAxis = int(dataArray) #Convert third element to int insert in zAxis
print xAxis, ",", yAxis, ",", zAxis
accelX.append(xAxis)   #Build our x axis array by appending to accelX
accelY.append(yAxis)   #Build our y axis array by appending to accelY
accelZ.append(zAxis)   #Build our z axis array by appending to accelZ
drawnow(makeFig)       #Call drawnow to update our live graph
plt.pause(.0000001)
cnt=cnt+1
if(cnt>50):
accelX.pop(0)
accelY.pop(0)
accelZ.pop(0)
``````
• Hi all, so after tweaking that sketch, it did generate the graph for the buffered data but it's still rather slow but it works..If anyone has an idea that could make it plot the graph faster please do help out. Thanks