Motor control with MATLAB
On Arduino Uno
Hardware & Software:
• Arduino Uno
• Micro servo motor
• Arduino USB & Jumper cables
• MATLAB student suite.
Getting started with Arduino Uno and MATLAB
Install the MATLAB and simulink arduino support packages from
Step 1
MATLAB add-on installers
Note: User will be prompted to
reinstall if they had already installed
the package. Otherwise, proceed
with the fresh install and click
“next”.
Log in to Mathwoks account and “accept” the license
Step 2
agreement.
Install all the support packages required. After successful
installation, MATLAB will prompt user to install the USB drivers
Step 3
for Arduino. Proceed to install these as well. Once done, user can
start using the Arduino board with MATLAB
Connect the Arduino board to the
development machine and check for
Step 4
the assigned COM port under Device
Manager (Windows OS machines).
Connect the servo motor to the board with the 5V line (red)
connected to the 5V supply on the board, GND (black) to GND on
Step 5
the board and the motor control line connected to Digital pin 4
(PWM) of the board.
In the MATLAB command window, create an arduino object & a
Step 6 servo object assigned to pin D4 (Digital Out, PWM) of the arduino
board.
a = arduino('com31', 'uno', 'Libraries', 'Servo');
s = servo(a, 'D4');
The “Servo” library from the support package is used here. There
are other libraries that can also be used with the motor control
shield. As soon as the servo object is created, the motor spins
once.
Create a new script and type the following code. This will spin
the motor from 0-180 degrees once in steps of 18 degrees.
Step 7
Please refer to the datasheet of the motor to calculate steps and
angles.
Un-comment the “flag” and the “while” loop lines to make an
infinite loop.
To quit the infinite loop, press Ctrl + C on the command window.
clearvars
a = arduino('com31', 'uno', 'Libraries', 'Servo');
s = servo(a, 'D4');
%flag = 1;
%while flag
for angle = 0:0.1:1
writePosition(s, angle);
current_pos = readPosition(s);
current_pos = current_pos*180;
fprintf('Current motor position is %d degrees\n', current_pos);
pause(1);
end
%end
Final Result: