Plotting Real Time Analog Voltage in Matlab using Arduino is easy. In this tutorial we will show how to plot analog voltage in Matlab using Arduino in real time. This is useful if you want to analyze the analog signal in Matlab.
We show two examples here. The first one shows the real time graph of analog voltage signal obtained by varying potentiometer. The second one shows the real time graph of audio voltage signal obtained by playing a music in PC.
Real Time Analog Voltage in Matlab using Arduino and Potentiometer
Connect a potentiometer of 10K ohm to the Arduino analog pin A2. The center wire is connected to the A2 pin, the remaining two ends from the potentiometer is connected to ground and 5V power supply. This is as shown below.
Matlab Program code to display real time analog signal
The matlab code to display real time analog signal from arduino is below.
% create arduino object
a = arduino();
% Create a figure window to monitor the live data
tmax = 50; % Total time for data collection in seconds
xlabel ('Time (s)'), ylabel('Voltage');
axis([0 tmax+1 -0.5 1.5]);
% set initial index value, starting value
k = 0; %index
v = 0; %voltage
t = 0; %time
tic % Start timer
while toc <= tmax
k = k + 1;
v(k) = readVoltage(a,'A2');
t(k) = toc;
% Now plot the data
if k > 1
line([t(k-1) t(k)],[v(k-1) v(k)]);
%press ctrl+c to exit
Before you can run this code you must install Arduino hardware support for Matlab. Then by creating an Arduino object you can use the function like readVoltage(). This is similar to analogRead function in Arduino IDE(see how to read analog signal with Arduino). Now connect the Arduino USB to your computer and run the above code.
You should real time analog voltage graph like the one shown below.
Real Time Analog Voltage in Matlab using Arduino and Headphone
In this example we connect headphone jack to PC and the other end of the headphone wire to the Arduino analog pin A2. There are 3 wires in the audio wire from the headphone. Two of them are for left and right audio and one is for ground. Connect either the left or right signal wire to the pin A2 of Arduino and the ground wire to ground of Arduino.
The setup is shown below.
Once you have connected the wires and Arduino USB to your computer, play some music and run the following above matlab code(change the y-axis limits to 1.5V in the code above). You should obtain the real time audio signal plot in Matlab as shown below.
So in this way you can plot analog signal in Matlab using Arduino.
If you like this post, share it. Also don’t forget to subscribe. Any comments is appreciated.