General Example
If you are in hurry, and would like to see how to use MatMav to fly a quadcopter equipped with Pixhawk that is running PX4 Firmware, then use the following code as an example.
Please note this is a quick example, and does not demonstrate all features.
Refer to the methods and properties sections for more details.
If you use the following sample code, DO NOT run the whole code at once, as it might results in a CRASH! Run each section individually. Make sure that you understand each section carefully. Each section in a *MATLAB* script starts with double percentage signs %%
Copy the following script to an M-file in your MATLAB. Test section by section.
%% test script for MatMav v2.3+
% by Mohamed Abdlekader
clear;
clc;
%% create object
number_of_targets=2;
mav=MatMav(number_of_targets);
% find available ports
mav.findPorts();
%% Establisg serial connection
% set port name and baudrate
mav.set_COMPORT('/dev/tty.usbserial-DN006YKX'); % on Mac
% or mav.set_COMPORT('COM3'); % on Windows
mav.set_BAUDRATE(57600);
% connect
mav.ConnectSerial();
%% Establish UDP connection
% set local port to listen on
% vehicles will be detected automatically once connected to selected port
mav.set_UDPLOCALPRT(14550);
mav.ConnectUDP();
%% ARM command
target=1;
start=1; % arm
stop=0;% disarm
mav.Arm(target,start)
%% get IMU date
target=1;
mav.get_IMUData(target)
%% get Attitude, in radians
target=1;
mav.get_Attitude(target)
%% get local NED position, in meters
target=1;
mav.get_LocalNED(target)
%% get GPS data, if available
target=1;
mav.get_GPS(target)
%% get vehicle mode
target=1;
mav.get_vehicle_mode(target)
%% stream motion capture data
target=1;
set=1; unset=0;
% set which vehicle/target you would like to send to
mav.set_MocapFlags(target,set)
% positions in NED loca frame, meters
x=1; y=1;z=1;
% quaternion
qw=1; qx=0; qy=0; qz=0;
mav.set_MocapData(target,qw,qx,qy,qz,x,y,z);
start=1; stop=0;
mav.sendMocap(stop); % use stop to stop streaming
%% takeoff
sysID=1;
mav.set_takeoffALT(sysID,-2);
mav.takeoff(sysID);
mav.toggle_OFFB(sysID,1);
%% send position setpoints
target=1;
% position setpoint, xyz in meters, Yaw in rad
x=1;y=1;z=-1; Yaw=0;
mav.set_PositionSetPoints(target,x,y,z,Yaw);
mav.set_setpointsFlags(target,1);
start=1; stop=0;
mav.sendSetPoints(start);
mav.toggle_OFFB(target,start);
%% land
sysID=1;
mav.Land(sysID);
%% set to MANUAL mode/ toggle offboard OFF/ stop setpoint streaming/Disarm
sysID=1;
mav.setManual(sysID)
mav.toggle_OFFB(sysID,0);
mav.sendSetPoints(0);
mav.Arm(sysID,0);
%% disconnect and clean MatMav object
mav.Disconnect();
mav.delete();