Hi everyone, this is Madhu Govindarajan from MathWorks. In this blog, I will share how to get started with MATLAB Support package for Arduino and servo motors.
All first time users please follow the instructions here to install the MATLAB Support package for Arduino. Once you have the Support package installed, the next step from the software side is to write the script for controlling the motors.
1) Connect the Arduino Due's Programming Port with a USB cable to the computer that you are running MATLAB on.
2) We need to know the COM port that the Arduino Due is connected to the computer. For Windows Users, Control Panel > Hardware and Sound > Devices and Printers.
3) Create a connection from MATLAB to Arduino Due using the command shown below.
>> a = arduino('com4', 'Due', 'Libraries', 'Adafruit\MotorShieldV2');
Here, the library 'MotorShieldV2' is mentioned during the connection attempt so that the server code can include information related to this Adafruit library. Once the connection is made you can see 'a' (an arduino object) in the Workspace.
4) Create an addon shield connection from MATLAB for the V2 Motor Shield using the following MATLAB commands.
>> addOnShield = addon(arduinoConnect, 'Adafruit\MotorShieldV2');
Just like before, once the connection is established a new object will be created in the Workspace.
5) To Control the Servo motor using the Adafruit Motor Shield and to make it move from 0 degrees to 180 degrees in steps of 36 degrees execute the following commands.
>> servoMotor = servo(addOnShield, 1);
>> for angle = 0:0.2:1 % From minimum 0 degrees to maximum 180 degrees
writePosition(servoMotor, angle);
pause(1);
end
Here just to show that the motor moves in 5 steps I have included the pause command which waits for a second before it continues. I have also included comments here directly (using the % sign).
For ease of use you can follow along with the YouTube video by downloading these files.