Professional Documents
Culture Documents
#include <AP_Common.h>
#include <AP_Math.h>
#include <AP_Param.h>
#include <AP_Progmem.h>
#include <AP_ADC.h>
#include <AP_InertialSensor.h>
#include <AP_HAL.h>
#include <AP_HAL_AVR.h>
#include <PID.h>
// Radio min/max values for each stick for my radio (worked out at beginning of article)
#define RC_THR_MIN 1070
#define RC_YAW_MIN 1068
#define RC_YAW_MAX 1915
#define RC_PIT_MIN 1077
#define RC_PIT_MAX 1915
#define RC_ROL_MIN 1090
#define RC_ROL_MAX 1913
void setup()
{
// Enable the motors and set at 490Hz update
hal.rcout->set_freq(0xF, 490);
hal.rcout->enable_mask(0xFF);
// PID Configuration
pids[PID_PITCH_RATE].kP(0.7);
pids[PID_PITCH_RATE].kI(1);
pids[PID_PITCH_RATE].imax(50);
pids[PID_ROLL_RATE].kP(0.7);
pids[PID_ROLL_RATE].kI(1);
pids[PID_ROLL_RATE].imax(50);
pids[PID_YAW_RATE].kP(2.7);
pids[PID_YAW_RATE].kI(1);
pids[PID_YAW_RATE].imax(50);
pids[PID_PITCH_STAB].kP(4.5);
http://owenson.me/build-your-own-quadcopter-autopilot/quad.ino Page 1 of 3
25/01/17, 11)33 PM
pids[PID_PITCH_STAB].kP(4.5);
pids[PID_ROLL_STAB].kP(4.5);
pids[PID_YAW_STAB].kP(10);
void loop()
{
static float yaw_target = 0;
// Wait until new orientation data (normally 5ms max)
while (ins.num_samples_available() == 0);
uint16_t channels[8];
rcthr = channels[2];
rcyaw = map(channels[3], RC_YAW_MIN, RC_YAW_MAX, -180, 180);
rcpit = map(channels[1], RC_PIT_MIN, RC_PIT_MAX, -45, 45);
rcroll = map(channels[0], RC_ROL_MIN, RC_ROL_MAX, -45, 45);
// Do the magic
if(rcthr > RC_THR_MIN + 100) { // Throttle raised, turn on stablisation.
// Stablise PIDS
float pitch_stab_output = constrain(pids[PID_PITCH_STAB].get_pid((float)rcpit - pitch,
1), -250, 250);
float roll_stab_output = constrain(pids[PID_ROLL_STAB].get_pid((float)rcroll - roll, 1),
-250, 250);
float yaw_stab_output = constrain(pids[PID_YAW_STAB].get_pid(wrap_180(yaw_target - yaw),
1), -360, 360);
// is pilot asking for yaw change - if so feed directly to rate pid (overwriting yaw stab
output)
if(abs(rcyaw ) > 5) {
yaw_stab_output = rcyaw;
yaw_target = yaw; // remember this yaw for when pilot stops
}
// rate PIDS
long pitch_output = (long) constrain(pids[PID_PITCH_RATE].get_pid(pitch_stab_output -
gyroPitch, 1), - 500, 500);
long roll_output = (long) constrain(pids[PID_ROLL_RATE].get_pid(roll_stab_output -
http://owenson.me/build-your-own-quadcopter-autopilot/quad.ino Page 2 of 3
25/01/17, 11)33 PM
}
}
AP_HAL_MAIN();
http://owenson.me/build-your-own-quadcopter-autopilot/quad.ino Page 3 of 3