Flight control: PID, cascades, filters and loops · 5 MIN READ
Motor mixing for a quad X: thrust and torques to four motors
Map collective thrust and roll, pitch and yaw torque commands to four motor outputs with PX4's Quadrotor X numbering and spin directions, and handle saturation by giving up thrust and yaw before roll and pitch.
Below the rate controller sits the mixer, which PX4 calls control allocation. It knows where each rotor is and which way it spins, and turns four numbers, thrust and three torques, into four motor commands. That is a matrix multiplication until a motor reaches 0 or 1. Then something has to give, and what gives decides whether the vehicle keeps its attitude or rolls over. This lesson writes the mixer, the naive clip and a desaturation with explicit priorities.
drones · A MAP OF THE IDEA
- Roll/pitch spread fits?
- Shrink yaw to fit
- Shift thrust into 0..1
- Check achieved torques
Useful when
- Explicit priorities keep the vehicle upright under saturation.
- Inverting the mix shows what the motors actually produce.
Watch out
- Clipping per motor couples axes and can flip the vehicle.
- Raising thrust at zero throttle (Airmode) can make it climb.
Implementation & operation cost: A small matrix per airframe, a desaturation routine and ground tests with the propellers removed.
Geometry and spin directions
In PX4's Quadrotor X, motor 1 is front right and spins counter-clockwise, motor 2 rear left counter-clockwise, motor 3 front left clockwise and motor 4 rear right clockwise; ArduPilot's Quad X uses the same order. Using the FRD body frame, a positive roll lowers the right side, so it needs more thrust on the left motors 2 and 3; a positive pitch raises the nose, so it needs more thrust on the front motors 1 and 3. Yaw comes from rotor drag torque: a counter-clockwise propeller twists the body clockwise, so yawing right (clockwise seen from above) speeds up motors 1 and 2 and slows 3 and 4. Each output is thrust plus signed shares of the three torques. PX4 builds that matrix from rotor positions and moment coefficients (CA_ROTORn_PX, CA_ROTORn_PY, and CA_ROTORn_KM, positive for counter-clockwise) and uses its pseudo-inverse. The default KM of 0.05 shows why yaw authority is weak: drag torque is small compared with thrust.
Seven commands through the mixer
The program prints the motor table, then mixes seven commands. Thrust is 0..1 and the torques are normalised so that a roll command of 0.1 moves the motors by 0.1. Commands that fit go straight through. For saturated ones the program prints two results: every motor clipped to 0..1 separately, and the desaturated mix. Each line ends with the command the four outputs actually produce, computed by inverting the mix, which is how you see what saturation cost.
package main
// Quad X motor mixing: collective thrust and roll, pitch and yaw torque
// commands become four motor outputs in 0..1. Saturated cases are shown
// clipped naively and desaturated with attitude before yaw before thrust.
import (
"fmt"
"math"
)
// Command is what the attitude and rate controllers ask for. Thrust is
// 0..1; roll, pitch and yaw are normalised torques (FRD body frame:
// positive roll = right side down, pitch = nose up, yaw = nose right).
type Command struct{ Thrust, Roll, Pitch, Yaw float64 }
// Motor is one rotor's share of each torque.
type Motor struct {
Name string
Roll, Pitch, Yaw float64
}
// QuadX uses PX4's numbering for the Quadrotor X airframe.
var QuadX = [4]Motor{
{"1 front right, CCW", -1, +1, +1},
{"2 rear left, CCW", +1, -1, +1},
{"3 front left, CW", +1, +1, -1},
{"4 rear right, CW", -1, -1, -1},
}
type Outputs [4]float64
func torques(c Command, yawScale float64) Outputs {
var a Outputs
for i, m := range QuadX {
a[i] = c.Roll*m.Roll + c.Pitch*m.Pitch + c.Yaw*yawScale*m.Yaw
}
return a
}
func spread(a Outputs) (lo, hi float64) {
lo, hi = a[0], a[0]
for _, v := range a[1:] {
lo, hi = math.Min(lo, v), math.Max(hi, v)
}
return lo, hi
}
// Clipped adds thrust and clamps each motor: the simple, wrong way.
func Clipped(c Command) Outputs {
a := torques(c, 1)
for i := range a {
a[i] = clamp(c.Thrust+a[i], 0, 1)
}
return a
}
// Desaturated keeps roll and pitch if at all possible, gives up yaw next
// and moves collective thrust last.
func Desaturated(c Command) Outputs {
if lo, hi := spread(torques(Command{Roll: c.Roll, Pitch: c.Pitch}, 0)); hi-lo > 1 {
k := 1 / (hi - lo) // even roll and pitch alone do not fit: scale them
c = Command{Thrust: c.Thrust, Roll: c.Roll * k, Pitch: c.Pitch * k}
}
yawScale := 1.0
if lo, hi := spread(torques(c, 1)); hi-lo > 1 {
low, high := 0.0, 1.0 // largest yaw share that still fits
for range 40 {
mid := (low + high) / 2
if lo, hi := spread(torques(c, mid)); hi-lo <= 1 {
low = mid
} else {
high = mid
}
}
yawScale = low
}
a := torques(c, yawScale)
lo, hi := spread(a)
thrust := clamp(c.Thrust, -lo, 1-hi) // shift everything into 0..1
for i := range a {
a[i] = clamp(thrust+a[i], 0, 1)
}
return a
}
// Achieved inverts the mixer: what the four outputs really produce.
func Achieved(o Outputs) Command {
var c Command
for i, m := range QuadX {
c.Thrust += o[i] / 4
c.Roll += o[i] * m.Roll / 4
c.Pitch += o[i] * m.Pitch / 4
c.Yaw += o[i] * m.Yaw / 4
}
return c
}
func (c Command) String() string {
return fmt.Sprintf("T %.2f R %+.2f P %+.2f Y %+.2f", r2(c.Thrust), r2(c.Roll), r2(c.Pitch), r2(c.Yaw))
}
// r2 rounds to 0.01 and turns -0 into 0 so the bisection's last bits
// do not print as -0.00.
func r2(v float64) float64 { return math.Round(v*100)/100 + 0 }
func (o Outputs) String() string {
return fmt.Sprintf("%.2f %.2f %.2f %.2f", o[0], o[1], o[2], o[3])
}
func saturated(c Command) bool {
lo, hi := spread(torques(c, 1))
return c.Thrust+lo < 0 || c.Thrust+hi > 1
}
func main() {
fmt.Println("motors (PX4 Quadrotor X):")
for _, m := range QuadX {
fmt.Printf(" %-19s roll %+.0f pitch %+.0f yaw %+.0f\n", m.Name, m.Roll, m.Pitch, m.Yaw)
}
cases := []struct {
name string
cmd Command
}{
{"hover", Command{Thrust: 0.5}},
{"roll right", Command{Thrust: 0.5, Roll: 0.1}},
{"pitch down, yaw right", Command{Thrust: 0.55, Pitch: -0.1, Yaw: 0.05}},
{"full throttle + roll", Command{Thrust: 0.95, Roll: 0.2}},
{"idle + roll", Command{Thrust: 0.05, Roll: 0.2}},
{"hard yaw at hover", Command{Thrust: 0.5, Yaw: 0.6}},
{"climb, roll and yaw", Command{Thrust: 0.8, Roll: 0.3, Yaw: 0.3}},
}
for _, tc := range cases {
fmt.Printf("%-22s asks %v\n", tc.name, tc.cmd)
if !saturated(tc.cmd) {
o := Desaturated(tc.cmd)
fmt.Printf(" %-12s %v -> %v\n", "mixed", o, Achieved(o))
continue
}
o := Clipped(tc.cmd)
fmt.Printf(" %-12s %v -> %v\n", "clipped", o, Achieved(o))
o = Desaturated(tc.cmd)
fmt.Printf(" %-12s %v -> %v\n", "desaturated", o, Achieved(o))
}
}
func clamp(v, lo, hi float64) float64 { return math.Max(lo, math.Min(hi, v)) }Roll right gives 0.40 0.60 0.60 0.40, and pitch down with a little yaw gives 0.50 0.70 0.40 0.60; both achieve exactly what was asked. At full throttle with roll, clipping yields 0.75 1.00 1.00 0.75, which achieves only R +0.13 at T 0.88; desaturation lowers thrust to 0.80 and keeps R +0.20. At idle with roll, clipping again cuts the roll to +0.13, while desaturation raises thrust to 0.20 and keeps it. Hard yaw is limited to Y +0.50 either way. In the last case clipping produces P +0.10 that nobody asked for and only R +0.20; desaturation keeps R +0.30 and P +0.00 and gives up yaw (+0.20) and thrust (0.50).
Desaturation and its priorities
The desaturating mixer applies the priorities in order. Roll and pitch come first: losing them means a tilt the vehicle cannot correct. If even they do not fit into the 0..1 range, they are scaled down together, which keeps the direction of the correction. Yaw comes next: the program finds the largest share of the yaw command that still fits, since losing yaw only lets the heading drift. Thrust comes last: the collective is moved to the nearest value at which every motor lies in 0..1. PX4 offers both behaviours through CA_METHOD (pseudo-inverse with output clipping, or with sequential desaturation). At the top it reduces thrust. At the bottom, with Airmode off it reduces the torque instead, so at zero throttle no attitude correction is possible; with MC_AIRMODE it raises thrust, as the idle case above does, which keeps control at zero throttle but can make a badly tuned vehicle climb after the throttle is cut.
a := torques(c, yawScale) // roll, pitch and yaw share per motor
lo, hi := spread(a) // their range now fits in 1
thrust := clamp(c.Thrust, -lo, 1-hi) // nearest thrust that fits
for i := range a {
a[i] = clamp(thrust+a[i], 0, 1)
}After roll, pitch and yaw have been made to fit, the lowest motor needs thrust of at least -lo and the highest at most 1 - hi. Clamping the requested thrust into that interval moves all four outputs by the same amount, so the torques are untouched and only the collective changes.
From normalised outputs to motors
Outputs in 0..1 reach the ESCs as PWM pulses, OneShot or DShot. Thrust grows roughly with the square of rotor speed, so equal steps in output are not equal steps in thrust; PX4 compensates with a thrust model parameter (THR_MDL_FAC). A minimum output keeps motors spinning in flight, and battery sag lowers the maximum thrust, so a vehicle saturates more often late in a flight. Go meets mixing outside the firmware: in simulators, in log analysis that recomputes achieved torques from recorded motor outputs to find saturation, and in tools for new frame geometries. Test motor order and direction on the ground with the propellers removed.
Fly it in GopherForge
The simulator models the airframe as a point mass whose thrust tilts, without attitude dynamics or individual motors, so there is nothing to mix and this program does not use it. Run it in any project, or create New project > Robotics and simulation > Drone flight, replace main.go with it (mission.go can stay) and Run to read the table in the console. To connect it to a flight, call Desaturated(Command{Thrust: u}) with the thrust a SetThrust loop computes and add a roll command, then count how often a hard climb saturates the motors.
TAKE THIS WITH YOU
A quad X mixer adds thrust and signed roll, pitch and yaw shares per motor, with signs set by rotor position and spin direction. When outputs saturate, never clip motors one by one: keep roll and pitch, cut yaw, then shift the collective, and check what the outputs achieve by inverting the mix.
Check your understanding
A quad X mixer cannot fit a command into 0..1 on every motor. In what order should a desaturating mixer give things up?
Go to the source
Progress stays in this browser. No account needed.