In this programming Arduino using Matlab tutorial, you will learn how to use the analog input and output feature of Arduino using Matlab language. Arduino UNO and most of other Arduino board has 10 bit ADC module inside it. In Arduino UNO board which we are using, there are six analog pins labelled with alias from A0 to A5. We can use these pins for real-time data acquisition from arduino to matlab. Mostly these analog pins are used to acquire signals from sensors, for example, LM35 temperature sensor, MQ-2 gas sensor and others. Once we have obtained the signal as varying voltage data from this analog pins we can make use of it to take other action.
This is the second part of tutorials series Programming Arduino using Matlab. To see the first part of the tutorial see led blinking tutorial and second part tutorial Push Button controlling LED.
Wiring Diagram
Below is shown the schematic diagram of connecting the LED, 220Ohm resistor to the digital pin 10, connecting the 10KOhm potentiometer to the analog pin A0.
Matlab Program for Arduino
The following is the Matlab program code for Arduino that reads in the voltage variation from the 10KOhm POT and sends the equivalent PWM signal to the digital pin 10. This program code is saved as a matlab script file readvolt.m.
clear;
clc;
disp('use CRTL+C to exit')
ard = arduino();
while 1
v = readVoltage(ard, 'A0');
writePWMVoltage(ard, 'D10', v);
disp(v);
end
In the program code above, we created an arduino object ard using the arduino() function. This binds Matlab and Arduino board connection. In the while loop we have used the readVoltage() function to read in the voltage. This function first argument is to be the arduino object ard and the second parameter is the analog pin. After reading in the voltage and saved in a variable v, we use the writePWMVoltage() function to pass in the voltage read v as the third parameter. The first parameter is the ard object and the second parameter is the digital pin 10.
Real-time data acquisition from Arduino to Matlab
As shown in the picture below and video demonstration, you can see that voltage sensed by Arduino is aquired and displayed on the Matlab prompt window in real time.
Video demonstration
Watch the following video to see how Matlab is used to acquire analog signal from Arduino and display value in real time.