Tilt a drone camera until it looks straight down, and the picture can start to spin while the motors jerk. A robot wrist can do the same in the middle of a weld. Nothing is broken. The fault is in how the orientation is stored: as three angles, which fail at one pose. This lesson shows why they fail and what to store in their place: a quaternion, four numbers that describe one turn about one axis. You will use it to hold a drone camera steady and to move a tool smoothly from one orientation to another. #robotics #quaternions #orientation-control
Learning Objectives
By the end of this lesson, you will be able to:
Identify gimbal lock in Euler angle representations and explain why it causes loss of control
Construct unit quaternions from axis-angle representations and compose rotations via quaternion multiplication
Implement SLERP interpolation for smooth orientation transitions in robotic systems
Apply quaternion operations to rotate vectors and compose sequential 3D rotations without singularities
Compare Euler angles, rotation matrices, and quaternions for different robotic applications
Real-World Engineering Challenge: Drone Gimbal Stabilization and Surgical Tool Orientation
A camera drone tilts and turns in the wind, and the camera must stay level. A gimbal does this work: it is a mount with three motors, one inside the next, that turns the camera against the motion of the drone body. A surgical robot has a similar task. It must turn its tool from one orientation to another with no sudden jump. Both machines need a way to store an orientation that works at every pose.
The Orientation Control Challenge
Engineering Question: How do we store an orientation, and move between two orientations, so that a drone gimbal or a surgical tool never loses the ability to turn in some direction?
Why Not Just Use Euler Angles Everywhere?
The familiar way to store an orientation is three angles: yaw (turn left or right), pitch (tilt up or down) and roll (lean sideways). They are called Euler angles. People read them easily, and for small turns they work well.
They have one weak pose. The three turns are made one after another, each about its own axis, and when the middle turn reaches 90 degrees the first and third axes lie on one line. Two motors then do the same thing, and one direction of turning is lost. This is gimbal lock. Near it, the motors must spin very fast to make a small turn. A quaternion has no such pose.
Fundamental Theory: Quaternion-Based Orientation
Euler Angles Review: Roll, Pitch, Yaw
Euler angles describe an orientation as three turns made one after another. The most common order in robotics and aerospace is ZYX:
Turn about the Z-axis (the vertical axis) by the yaw angle .
Turn about the Y-axis, in the position the first turn left it, by the pitch angle .
Turn about the X-axis, in the position the first two turns left it, by the roll angle .
The three angles are in degrees or radians. Each turn can be written as a rotation matrix, a 3 by 3 table of numbers that turns a vector (see 3D Rotation Matrices and Spatial Transformations). Multiplying the three matrices gives one matrix for the whole orientation:
Written out in full (the next part uses it):
The Gimbal Lock Problem
Think of a drone gimbal as three rings, one inside the next: the yaw ring outside, the pitch ring in the middle, and the roll ring inside, holding the camera. The pitch ring carries the roll axis with it.
Pitch = 0Pitch = 90 degreesyaw axisyaw axisroll axispitch axispitchroll axisaxis3 axes in 3 directionsyawandrollononeline3 directions of turning2 directions of turning
When the pitch ring turns , the roll axis points straight down, along the yaw axis. The yaw motor and the roll motor now turn the camera in the same way, and no motor can turn it about the third direction. One degree of freedom (one independent direction of motion) is lost. This is gimbal lock. It occurs in any Euler angle sequence when the middle turn reaches .
The matrix shows the same thing. Put into , so that and :
The identities and shorten each entry:
Only the difference appears. Yaw with roll gives the same matrix as yaw with roll , because . Two motors turn, but only one number of the orientation changes. The program below checks this.
# Demonstrating gimbal lock with Euler angles
import numpy as np
from scipy.spatial.transform import Rotation
# 'ZYX' in capital letters: each turn is about the axis as the earlier turns left it
# Normal case: pitch = 45 degrees (no gimbal lock)
print(f"\n R1 (yaw=40, pitch=90, roll=30) vs R2 (yaw=50, pitch=90, roll=40):")
print(f" Same rotation? {np.allclose(r1.as_matrix(), r2.as_matrix())}")
print(f" (Both have yaw-roll = 10°, producing identical orientations)")
Quaternion Definition
Any orientation can be reached from any other by a single turn: choose the right axis, and turn about it by the right angle. A quaternion stores that single turn in four numbers. One number carries the size of the angle, and three carry the direction of the axis. Because it stores one turn, and not three turns in a row, there is no middle turn that can bring two axes onto one line. Gimbal lock cannot occur.
The four numbers also follow rules of multiplication, and these rules let a program combine two turns into one. A quaternion has one ordinary number (the scalar part) and three more, , and (the vector part). None of them has a unit:
The symbols , , mark the three places of the vector part. They behave like the imaginary unit of complex numbers, but there are three of them:
The multiplication rules follow from these identities:
Unit Quaternions and the Rotation Constraint
Only a quaternion of length 1 represents a turn. It is called a unit quaternion:
Four numbers with one condition leave three free values, which is exactly what an orientation needs. Rounding errors slowly change the length, so a program divides the quaternion by its length from time to time. This is called normalizing.
One fact causes many program errors: and (all four signs changed) represent the same turn. It is called the double cover, and it returns in the part on SLERP.
Quaternion from Axis-Angle Representation
Take a turn by an angle about an axis. Write the axis as a vector of length 1, . The scalar part of the quaternion is the cosine of half the angle. The vector part is the axis multiplied by the sine of half the angle:
A turn: axis and angleThe quaternion: four numbersn (axis, length 1)q=[w,x,y,z ]thetasin(theta/2) * n(angle of the turn)cos(theta/2)
To make one turn and then another, multiply their quaternions. The product is one quaternion for the combined turn. Write and , where is the vector part. The product uses the dot product () and the cross product () of the two vector parts:
Written out with the four numbers of each, and , this is 16 multiplications:
import numpy as np
from scipy.spatial.transform import Rotation
# Compose two rotations: 90° about Z, then 90° about X
r1 = Rotation.from_euler('z',90,degrees=True) # First rotation
r2 = Rotation.from_euler('x',90,degrees=True) # Second rotation
print(f"\nReversed order quaternion: {r_reversed.as_quat().round(4)}")
print(f"Same as combined? {np.allclose(r_combined.as_quat(), r_reversed.as_quat())}")
Quaternion Conjugate and Inverse
To undo a turn, turn back about the same axis by the same angle. The conjugate does this: it keeps and changes the sign of , and .
The inverse is the quaternion that undoes . In general it is the conjugate divided by the length squared. For a unit quaternion the length is 1, so the inverse is the conjugate:
A turn followed by its inverse is no turn at all: , the identity quaternion.
Rotating Vectors with Quaternions
A quaternion can turn a vector , for example the direction in which a camera points. Write the vector as a quaternion with a scalar part of zero, , and multiply it from both sides:
The scalar part of the result is zero again, and its vector part is the turned vector. The program below turns by about the Z-axis and gets .
import numpy as np
from scipy.spatial.transform import Rotation
# Rotate vector [1, 0, 0] by 90° about Z-axis
# Expected result: [0, 1, 0]
r = Rotation.from_euler('z',90,degrees=True)
v_original = np.array([1, 0, 0])
v_rotated = r.apply(v_original)
print(f"Original vector: {v_original}")
print(f"Rotation: 90° about Z")
print(f"Rotated vector: {v_rotated.round(4)}")
# Multiple vectors at once
vectors = np.array([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[1, 1, 0]
])
rotated = r.apply(vectors)
print(f"\nBatch rotation results:")
for v, rv inzip(vectors, rotated):
print(f" {v} -> {rv.round(4)}")
SLERP: Spherical Linear Interpolation
To move a tool from one orientation to another, the natural motion is one steady turn about one fixed axis. SLERP (spherical linear interpolation) calculates the orientations along that turn. Interpolation means finding the values between a start and an end. Moving each Euler angle steadily from its start to its end does not give this motion: the tool changes speed and swings wide.
Take the start , the end and a fraction that runs from 0 (start) to 1 (end). SLERP mixes the two quaternions with weights that keep the result at length 1:
Here , in radians, and is the ordinary dot product of the two sets of four numbers. is half the angle of the turn from the start to the end. At the formula gives , and at it gives .
Double-Cover in Practice: Always Check the Dot Product
The double cover ( and are the same orientation) is the most common cause of quaternion errors. Ask SLERP to go from to and the tool should stay still, but it makes a full turn, because SLERP takes the long way round. scipy.spatial.transform.Slerp handles this for you. If you write SLERP yourself, you must guard against it:
defslerp_safe(q0, q1, t):
# q0, q1 are np.array([x, y, z, w]), already unit quaternions
dot = np.dot(q0, q1)
if dot <0.0: # Take the shorter arc.
q1 =-q1
dot =-dot
if dot >0.9995: # Nearly identical: linear interpolation.
result = q0 + t * (q1 - q0)
return result / np.linalg.norm(result)
omega = np.arccos(dot)
s0 = np.sin((1- t) * omega) / np.sin(omega)
s1 = np.sin(t * omega) / np.sin(omega)
return s0 * q0 + s1 * q1
The same check belongs in any controller that follows a target orientation. In every control cycle, calculate and change the sign of the target if the result is negative. Without the check, the robot can turn almost a full circle between two close orientations.
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation, Slerp
print("Euler interpolation has variable speed and may produce unexpected paths")
System Application: Quaternion-Based Gimbal Stabilization
To keep the camera pointing the same way, the gimbal must make exactly the turn that cancels the motion of the drone body. An IMU (inertial measurement unit, a sensor that reports how the body is oriented) gives the body orientation as a quaternion. One quaternion multiplication gives the turn the gimbal must make, and SLERP limits how fast the gimbal moves toward it.
Problem Setup
A camera drone is surveying land from the air. Wind gusts roll and pitch the drone body, but the camera must keep pointing straight down. The gimbal control loop runs 100 times a second (100 Hz), and in each cycle it must calculate the turn that corrects the camera.
Given:
Camera desired orientation: pointing straight down, in order ( about the X-axis from level)
Drone body orientation, measured by the IMU: a quaternion that changes with time
The gimbal turn must satisfy : the body turn followed by the gimbal turn gives the desired orientation
Solution: multiply both sides from the left by the inverse of the body quaternion, which is its conjugate.
Check one case by hand. A gust rolls the body about the X-axis. The gimbal must undo the and then turn more: about X. As a quaternion this is . In SciPy, q_body.inv() * q_desired gives this turn for the same case. It prints all four signs changed, which is the same orientation.
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation, Slerp
print(f"Ideal correction (instant): max error = {camera_error.max():.4f}°")
print(f"Rate-limited (SLERP): max error = {camera_error_smooth.max():.2f}°")
print(f"Rate-limited (SLERP): mean error = {camera_error_smooth.mean():.2f}°")
Extending to Surgical Robot Tool Orientation
A surgical robot turns its tool from one pose to another, for example from a viewing angle to a cutting angle. The formula is the one used for the gimbal: . The surgical system adds a sequence of orientations (SLERP from the first to the second, then from the second to the third), a limit on how fast the tool turns near tissue, and a position that must change together with the orientation.
Each of the three forms has a place. Choose by what the number is used for.
Use quaternions for what the controller stores and calculates: IMU data, fast control loops, and any motion that must pass smoothly through every orientation.
Use rotation matrices when a turn comes together with a shift in position, as in the link-by-link transformations of a robot arm (the DH parameters), or when other software expects 3x3 or 4x4 matrices.
Use Euler angles only where a person meets the number (joystick input, a display), or for small tilts where gimbal lock is far away. Convert them to quaternions or matrices before any calculation.
Store orientations as quaternions inside the program, and convert to the other forms only where data enters or leaves.
Normalize quaternions regularly: . Do it every control cycle in a fast loop (100 Hz or faster), or whenever . The rounding error of one multiplication is tiny (about in double precision). The larger effect comes from updating the quaternion with the turn rate from a gyroscope over a time step , , which makes the length grow at every step. After a few hundred steps without normalizing, the length can be several percent too large.
Check the sign when you compare or blend quaternions. Because and are the same orientation, keep , or check the sign of the dot product before SLERP, so that the motion takes the short way.
Summary
Key Takeaways:
Euler angles lose one direction of turning when the middle turn reaches , because two of the three axes then lie on one line. This is gimbal lock.
A unit quaternion with stores one turn about one axis, and has no such pose
Quaternion multiplication combines two turns, and the conjugate undoes a turn
SLERP gives a steady turn between two orientations, by the short way if the dot product is checked first
Show Euler angles to people, use rotation matrices where a turn comes with a shift in position, and store quaternions inside the controller
Comments
Loading comments...
Predict first
A camera gimbal has three motors, one inside the next: yaw (outside), pitch (middle) and roll (inside, holding the camera). You turn the pitch motor until the camera looks straight down. In how many different directions can the motors still turn the camera?
See it: tilt the middle motor and two axes come together
Yaw axis to roll axis
Roll motor speed for a 10°/s turn
Different directions of turning
Left: the three motor axes, with the yaw angle at zero. The camera looks along the roll axis. Right: the speed the roll motor needs to turn the camera at 10°/s about the level forward line, the line the roll axis had at pitch 0°. The speed is 10 / cos(pitch). At 90° no speed is enough.
Check yourself
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. A robot wrist must turn 120° about the Z-axis. Which unit quaternion, written [w, x, y, z], stores this turn?
2. A tool is at q0 = [1, 0, 0, 0], which means no turn. A sensor reports the target as [−0.985, 0, 0, −0.174]. That is a turn of 20° about Z with all four signs changed. Your own SLERP code does not check the sign of the dot product. How far does the tool turn on its way to the target?
3. A pallet-wrapping arm blends from one tool orientation to the next 200 times a second. Its screen must show the operator how far the tool is tilted. Which forms of orientation fit the two jobs?
yawpitchrollyawpitchrollPitch 0°: three directionsPitch 90°: only two
starttargetShort way: 20°Long way: 340°q and −q are the same pose.Check the sign before SLERP.
Watch it build: yaw, then pitch, then roll
XYZxyzxyzxyzxyzOrder Z, Y, Xyaw 40° about zpitch 45° about yroll 30° about xR = RZ RY RXone matrix
The body frame x, y, z starts on the fixed frame. Three turns follow, in the order Z, Y, X.
Yaw: 40° about the vertical z axis. x and y swing round in the floor plane.
Pitch: 45° about the new y axis, where the yaw left it. x tips 45° down.
Roll: 30° about the newest x axis. y and z turn round it.
Each turn is a matrix. Their product, in the same order, is one matrix for the orientation.
Pitch = 0°Pitch = 90°yaw axispitch axisroll axisyaw axispitch axisroll axisone line3 axes in 3 directions3 directions of turningyaw and roll on one line2 directions of turningAt 90° of pitch the roll axis lies on the yaw axis, and one direction of turning is lost.
A turn: axis and angleThe quaternion: four numbersnaxis, length 1θangle of the turnq =wxyzcos(θ/2)sin(θ/2) · n90° about Z: q = [0.707, 0, 0, 0.707]Half the angle goes into the quaternion: cos(θ/2) and sin(θ/2) times the axis.
Found this useful?
Discussion
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
Text size
←→
Previous and next card. On a turned card: Not yet, I knew it
SpaceEnter
Turn the card, show the answer
123
Overview, Recap, Test me
HomeEnd
First and last card
Esc
Close
← → or scroll · N notes · F full screen · B blank0:00
My notes on this page
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
Notes on earlier wording
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.
Comments