Flight control: PID, cascades, filters and loops · 6 MIN READ

Cascaded control: a position loop on top of a velocity loop

Build an outer position loop that sends velocity setpoints through SetVelocity, explain why inner loops must be faster and where the integrator belongs, and compare P, PI and velocity feedforward when holding a point in wind and following a moving target.

No flight stack controls position with one big loop. PX4 and ArduPilot nest them: position error becomes a velocity setpoint, velocity error an acceleration and tilt, attitude error a body rate, rate error a torque for the mixer. Each loop only has to control something that already responds quickly, because the loop inside it made it so. A companion computer running Go usually sits at the top of this cascade and sends position or velocity setpoints; this lesson writes that outer loop, holds a point in a 4 m/s wind and then follows a target that moves into the wind.

drones · A MAP OF THE IDEA

  1. Target pos and velocity
  2. P + feedforward -> vel
  3. SetVelocity PI loop
  4. Attitude and rate in FC

Useful when

  • Each loop is simple and is tuned on its own, inside out.
  • Go closes only the slow outer loop; the firmware keeps the fast ones.

Watch out

  • An outer loop nearly as fast as the inner one oscillates.
  • Noise in the target velocity passes straight through feedforward.
  • A lost setpoint stream makes PX4 leave offboard mode.

Implementation & operation cost: One small controller per axis, a fixed-rate loop, and a setpoint stream the autopilot can rely on.

01

The cascade and its rates

PX4's multicopter controller is documented as a standard cascade: a P position loop (MPC_XY_P) produces a velocity setpoint, a PID velocity loop produces an acceleration, which becomes a thrust vector and attitude setpoint, a P attitude loop produces body rates, and a PID rate loop produces torques for control allocation. The rate loop runs at the gyro rate in the firmware, far faster than the position loop. The rule of thumb is that each inner loop should be several times, often five to ten times, faster in bandwidth than the loop around it, so the outer loop can treat it as nearly instant. In this simulator SetVelocity's loop is a PI loop on ground velocity that tilts the thrust by up to 35 degrees; its proportional gain of 2.5 per second gives a time constant of about 0.4 s, and it is stepped at 50 Hz. The program's position loop runs at 10 Hz with Kp = 0.5, a time constant of 2 s, five times slower. An outer gain close to the inner loop's bandwidth sees the inner loop's lag as phase loss and oscillates.

02

Hold a point, then follow a target

The program takes off to 10 m in a 4 m/s wind from the west with 1.5 m/s gusts. It first sends velocity zero with no position loop for 20 s, then holds the point with a P loop (Kp 0.5) for 20 s. Then the target starts moving west, into the wind, at 3 m/s, and three outer loops follow it for 30 s each: P alone, PI with Ki 0.1 (integral limited to 5 m/s and frozen while the command is at its limit), and P plus velocity feedforward. Before each of the last two runs the target stops for 15 s, so every run starts from a hover. The position loop runs on every fifth 50 Hz step; altitude has its own P term. Each row reports the largest horizontal distance from the target, and the mean east offset and mean east velocity command over the last 10 s.

go
package main

// Cascaded control: the program closes a position loop at 10 Hz and sends
// velocity setpoints to the autopilot's faster velocity loop (SetVelocity).
// A 4 m/s wind from the west with 1.5 m/s gusts pushes the drone east.
// The drone first holds a point, then follows a target moving upwind.

import (
	"fmt"
	"math"

	"gopherforge.app/drone"
)

// PositionLoop turns a position error into a velocity setpoint.
type PositionLoop struct {
	Kp, Ki      float64
	FeedForward bool    // add the target's own velocity to the command
	MaxSpeed    float64 // limit on the commanded horizontal speed
	MaxI        float64 // limit on the integral's contribution, m/s

	integral drone.Vec3
}

func (c *PositionLoop) Update(target, targetVel, pos drone.Vec3, dt float64) drone.Vec3 {
	err := target.Sub(pos).Horizontal()
	cmd := err.Scale(c.Kp)
	if c.FeedForward {
		cmd = cmd.Add(targetVel.Horizontal())
	}
	if c.Ki > 0 {
		if cmd.Add(c.integral).Len() < c.MaxSpeed { // integrate only while not limited
			c.integral = clampLen(c.integral.Add(err.Scale(c.Ki*dt)), c.MaxI)
		}
		cmd = cmd.Add(c.integral)
	}
	return clampLen(cmd, c.MaxSpeed)
}

type phase struct {
	name   string
	loop   *PositionLoop // nil: no position loop, velocity setpoint zero
	follow bool          // the target moves upwind at 3 m/s
	secs   float64
	quiet  bool // a pause between runs: the target stops, nothing is printed
}

func main() {
	sim := drone.New(drone.Config{Wind: drone.Vec3{X: 4}, Gust: 1.5, Seed: 2})
	d := sim.Drone()
	d.Arm()
	d.TakeOff(10)
	sim.RunUntil(30, func(float64) bool { return d.Arrived() })
	target := d.State().Pos
	targetVel := drone.Vec3{X: -3} // west, into the wind
	sim.Waypoint(target)

	const outerEvery = 5 // physics runs at 50 Hz, the position loop at 10 Hz
	outerDt := outerEvery * sim.Dt()
	pause := phase{"target stops", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, false, 15, true}
	phases := []phase{
		{"velocity 0, no position loop", nil, false, 20, false},
		{"hold, P Kp 0.5", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, false, 20, false},
		{"follow, P Kp 0.5", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, true, 30, false},
		pause,
		{"follow, PI Ki 0.1", &PositionLoop{Kp: 0.5, Ki: 0.1, MaxSpeed: 10, MaxI: 5}, true, 30, false},
		pause,
		{"follow, P + feedforward", &PositionLoop{Kp: 0.5, FeedForward: true, MaxSpeed: 10}, true, 30, false},
	}
	fmt.Printf("wind (4.0, 0.0) m/s, gusts 1.5 m/s; position loop %.0f Hz over SetVelocity\n", 1/outerDt)
	fmt.Println("means over the last 10 s; x off > 0: east of the target, downwind and behind")
	fmt.Printf("%-28s %8s %10s %12s\n", "phase", "max off", "mean x off", "mean cmd vx")
	for _, p := range phases {
		sim.Mark(p.name)
		var cmd drone.Vec3
		var maxOff, sumOff, sumCmd float64
		var n, step int
		t0 := sim.Time()
		sim.Run(p.secs, func(t float64) {
			if p.follow {
				target = target.Add(targetVel.Scale(sim.Dt()))
			}
			pos := d.State().Pos
			if step%outerEvery == 0 {
				cmd = drone.Vec3{}
				if p.loop != nil {
					v := drone.Vec3{}
					if p.follow {
						v = targetVel
					}
					cmd = p.loop.Update(target, v, pos, outerDt)
				}
				cmd.Z = 0.8 * (target.Z - pos.Z) // altitude: a plain P loop
				d.SetVelocity(cmd, 0)
			}
			step++
			maxOff = math.Max(maxOff, pos.Sub(target).Horizontal().Len())
			if t-t0 >= p.secs-10 {
				sumOff += pos.X - target.X // positive: east, downwind of the target
				sumCmd += cmd.X
				n++
			}
		})
		if !p.quiet {
			fmt.Printf("%-28s %6.2f m %8.2f m %8.2f m/s\n", p.name, maxOff, sumOff/float64(n), sumCmd/float64(n))
		}
	}
	d.ReturnHome()
	sim.RunUntil(120, func(float64) bool { return d.State().Landed })
	sim.Save()
}

func clampLen(v drone.Vec3, limit float64) drone.Vec3 {
	if l := v.Len(); l > limit {
		return v.Scale(limit / l)
	}
	return v
}
Read the code

Velocity zero without any position loop stays within 0.18 m: the autopilot's velocity loop has an integral that learned the tilt against the 4 m/s wind during the take-off, and the gusts change slowly enough for it to follow. The P hold stays within 0.12 m with a mean command of 0.00 m/s, so the outer loop never sees the steady wind. Following the target, P alone settles 5.99 m behind while commanding -3.00 m/s: a P loop commands speed only in proportion to error, and 3 / 0.5 = 6 m. PI removes the lag (-0.03 m) after a 4.29 m transient. Feedforward removes it from the start and never falls more than 0.77 m behind.

03

Where the integrator belongs

A steady disturbance is best cancelled by the loop it enters. Wind is a force, it shows up first as a velocity error, and an integral in the velocity loop learns the tilt that cancels it. PX4 is built this way, with a P position loop over a PID velocity loop, so a position setpoint is held in steady wind with no position integral; that is what the hold rows show. A moving reference is different: an outer P loop needs a standing error to command a speed, error = v / Kp. An outer integral removes that lag, but slowly, with overshoot and windup, and it can fight the inner integral in gusts. Feedforward is the better tool: send the target's velocity directly and let P correct only the residual, as PX4's position controller does with the velocity of a trajectory setpoint. Keep an outer integral for errors the inner loop cannot see, such as a target whose velocity you cannot measure.

go
// Observe estimates the target's velocity from its reported positions,
// low-passed so that position noise does not reach the feedforward.
func (f *Follower) Observe(p drone.Vec3, t float64) {
	if f.seen && t > f.lastT {
		raw := p.Sub(f.last).Scale(1 / (t - f.lastT))
		f.vel = f.vel.Add(raw.Sub(f.vel).Scale(f.Alpha))
	}
	f.last, f.lastT, f.seen = p, t, true
}

// Command feeds the velocity forward; P corrects only what is left.
func (f *Follower) Command(pos drone.Vec3, now float64) drone.Vec3 {
	ahead := f.last.Add(f.vel.Scale(now - f.lastT)) // where it is now
	err := ahead.Sub(pos).Horizontal()
	return clampLen(f.vel.Horizontal().Add(err.Scale(f.Kp)), f.MaxSpeed)
}
Read the code

On a real vehicle the target's velocity comes from its own reports or from a camera tracker. Differencing positions amplifies their noise, so the estimate is low-passed with Alpha between 0 and 1, and the last report is extrapolated to the present so that report latency does not become lag. Whatever noise remains in the feedforward goes straight into the velocity setpoint.

04

Setpoints from a companion computer

On a real vehicle the Go program sends setpoints over MAVLink (SET_POSITION_TARGET_LOCAL_NED, which carries position, velocity and acceleration fields, so feedforward travels with the position) or ROS 2 (TrajectorySetpoint), typically at 10 to 50 Hz. PX4 requires a continuous stream of at least 2 Hz before it enters offboard mode and leaves offboard mode when the stream stops for longer than COM_OF_LOSS_T, so the loop must keep sending even when nothing changes. MAVLink local frames are NED while this simulator is ENU: north is the simulator's Y, east its X, and down is minus Z. Prefer sending position setpoints and letting the tuned firmware loops do the work; write your own outer loop when the task needs it, such as following a moving target or centring over a landing pad seen by a camera.

05

Fly it in GopherForge

Use New project > Robotics and simulation > Drone flight, replace main.go with this program (keep mission.go; it is not used here) and Run. Open Output: the replay shows the wind arrow, the waypoint above the take-off point, the hold, and the three runs heading west with a timeline mark for each phase. Try Kp 1.0 and the P lag shrinks to about 3 m; raise the gusts in drone.Config, or move the position loop to 2 Hz by changing outerEvery to 25, and watch the offsets grow.

TAKE THIS WITH YOU

Nest loops so that each controls a quantity the faster loop inside it has already made responsive, and put the integrator where the disturbance enters: the velocity loop's integral cancels steady wind, so a P position loop holds a point. To follow a moving target, feed its velocity forward; a P loop alone lags by v / Kp.

Check your understanding

An outer P position loop with Kp 0.5 follows a target moving steadily at 3 m/s, over a velocity loop that tracks well. How far behind does the drone settle, and what removes the lag?

Go to the source

Progress stays in this browser. No account needed.