Skip to content
Physical AI
Chapter 04 26 min read

Robot Sensors and Data Interfaces

IMUs, encoders, coordinate frames, projected gravity, and why real sensor data is noisy, biased and late.

A walking robot never knows its own state. It knows a few dozen numbers that its sensors report, each slightly wrong, slightly late and expressed in some particular coordinate frame. This chapter explains what those numbers are: what an IMU and a joint encoder actually measure, why a robot cannot simply measure its own velocity, how orientation is represented, what projected gravity is and why locomotion policies use it, and how sensor data travels as arrays, packets and messages. It also shows how MuJoCo produces virtual sensor readings, and why they are cleaner than anything real hardware will deliver.

State, measurements and ground truth

Start with a distinction that runs through the whole site.

  • The state of a robot is everything needed to predict its future motion: the position and orientation of its base, all joint angles, and all of their velocities. For a floating-base robot with 12 joints that is 19 position numbers (with a quaternion) and 18 velocity numbers, as Chapter 3 explained.
  • A measurement is what a sensor reports: a physical quantity, converted to a number, with errors.
  • Ground truth is the exact state. A simulator has it for free, because the state is its memory. A real robot never has it. Even a motion-capture lab only gives a better measurement.

Some state variables are measured directly and well (joint angles). Some are measured directly but imperfectly (angular velocity). Some are not measured at all and must be estimated from other measurements (orientation, linear velocity, position in the room). Knowing which is which is the core skill of this chapter.

Coordinate frames

A vector such as "velocity = 0.5 m/s" is meaningless until you say in which frame. A coordinate frame is an origin plus three perpendicular axes. Robots use several:

  • The world frame (also called the inertial or global frame) is fixed to the ground. Its z axis points up, against gravity. It does not move when the robot moves.
  • The body frame (or base frame) is fixed to the robot's torso or pelvis. It moves and rotates with the robot. The usual robotics convention, from ROS REP 103, is x forward, y left, z up.
  • Sensor frames are fixed to each sensor. An IMU chip is soldered onto a board at some position and angle on the body, and it reports everything along its own axes. Software has to rotate the readings into the body frame using the known mounting transform.

Body frame versus world frame

Suppose the robot leans forward 10° and its IMU reports gravity. In the world frame, gravity is always (0,0,−9.81)(0, 0, -9.81) m/s². In the body frame, the same vector has a forward component, because the robot's "down" is no longer the world's "down". Neither description is more correct. They are the same physical vector written in two coordinate systems.

The conversion is a rotation matrix RR (3×3). With the convention used on this site,

vworld=R vbody,vbody=R⊤vworld.v_{world} = R\, v_{body}, \qquad v_{body} = R^\top v_{world}.

RR is orthonormal: its columns are unit vectors at right angles to each other, R⊤R=IR^\top R = I, and its determinant is +1+1. Its columns are simply the body's x, y and z axes written in world coordinates. That makes R⊤R^\top (the transpose) its inverse, which is cheap to compute.

Roll, pitch and yaw

Orientation has three degrees of freedom, and the most intuitive way to describe it is with three angles:

  • Roll ϕ\phi: rotation about the body's forward (x) axis. Leaning sideways.
  • Pitch θ\theta: rotation about the body's left (y) axis. Leaning forward or backward. With z up and y left, positive pitch tips the nose down.
  • Yaw ψ\psi: rotation about the vertical (z) axis. Turning to face a different direction.

These are Euler angles, and their order matters. This site uses the common Z-Y-X convention: first yaw about the world z axis, then pitch about the new y axis, then roll about the newest x axis:

R=Rz(ψ) Ry(θ) Rx(ϕ).R = R_z(\psi)\,R_y(\theta)\,R_x(\phi).

Euler angles are easy to read but awkward to compute with. At pitch ±90°\pm 90°, roll and yaw rotate about the same axis and one degree of freedom disappears. This is called gimbal lock. Angles also wrap around: 179°179° and −179°-179° are 2° apart, not 358°. For these reasons estimators and simulators store orientation as a rotation matrix or as a unit quaternion q=(w,x,y,z)q = (w, x, y, z), four numbers with w2+x2+y2+z2=1w^2 + x^2 + y^2 + z^2 = 1. A rotation by angle α\alpha about unit axis n^\hat n is q=(cos⁡α2, n^sin⁡α2)q = (\cos\tfrac{\alpha}{2},\ \hat n \sin\tfrac{\alpha}{2}). MuJoCo stores quaternions in exactly this (w,x,y,z)(w, x, y, z) order.

Move the sliders below. The solid arrows are the IMU's body frame, the faint arrows are the world frame. The rotation matrix, quaternion and projected gravity update together, because they are three encodings of the same orientation.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

How roll, pitch and yaw define the orientation of an IMU's body frame relative to the world frame, and how the same orientation is written as a rotation matrix, a quaternion and a projected-gravity vector.

How it works

The three sliders are Z-Y-X Euler angles (yaw about world z, then pitch about the new y, then roll about the new x). They are converted to a rotation matrix R = Rz(ψ)·Ry(θ)·Rx(φ) that maps body-frame vectors into the world frame. The columns of R are the body axes expressed in world coordinates, which is exactly how the solid arrows are drawn.

The quaternion is computed from R with Shepperd's method and shown in MuJoCo's [w, x, y, z] order. Projected gravity is Rᵀ·[0, 0, −1], which is minus the bottom row of R. The world uses the robotics convention x forward, y left, z up; the scene rotates it so z points up on screen.

Adjustable parameters

  • Roll φ (−180° to 180°)
  • Pitch θ (−90° to 90°)
  • Yaw ψ (−180° to 180°)
  • Show world axes
  • Show gravity

Known limitations

  • Pure visualization: orientation is set by sliders, not estimated from sensor data.
  • Euler angles have a singularity at pitch ±90° (gimbal lock). Estimators work with quaternions or rotation matrices internally for this reason.

Equations

R=Rz(ψ) Ry(θ) Rx(ϕ),vworld=R vbodyR = R_z(\psi)\,R_y(\theta)\,R_x(\phi), \qquad v_{world} = R\,v_{body}
R⊤R=I,det⁡R=+1R^\top R = I, \qquad \det R = +1
gb=R⊤[00−1]=[sin⁡θ−sin⁡ϕcos⁡θ−cos⁡ϕcos⁡θ]g_b = R^\top \begin{bmatrix}0\\0\\-1\end{bmatrix} = \begin{bmatrix}\sin\theta\\ -\sin\phi\cos\theta\\ -\cos\phi\cos\theta\end{bmatrix}
q=[cos⁡α2, n^ sin⁡α2]q = \big[\cos\tfrac{\alpha}{2},\ \hat n\,\sin\tfrac{\alpha}{2}\big]

Core update rule

// lib/sim/ch04-imu.ts
const R = eulerToMatrix(roll, pitch, yaw);   // Rz · Ry · Rx
const q = matrixToQuat(R);                   // [w, x, y, z]
const g = [-R[2][0], -R[2][1], -R[2][2]];    // Rᵀ · [0, 0, −1]

Explained in Chapter 4: Sensors & Data

The IMU

An inertial measurement unit (IMU) is a small package, often a single chip a few millimetres across, that combines:

  • a 3-axis gyroscope, measuring angular velocity, and
  • a 3-axis accelerometer, measuring specific force (explained below).

That combination is a 6-axis IMU. A 9-axis IMU adds a magnetometer, which measures the Earth's magnetic field and can give a heading. Magnetometers are unreliable near motors and steel, so legged robots often do without one. Most robot IMUs are MEMS devices (micro-electro-mechanical systems): tiny silicon structures whose motion is measured electrically. They are cheap, light and fast, and they have significant noise and bias compared with the fibre-optic or ring-laser gyroscopes used in aircraft.

The IMU sits on the robot's base, usually near the pelvis. On Asimov, Menlo documents a MuJoCo bridge that reads two simulated IMU signals, imu_ang_vel and imu_lin_acc: the angular velocity from the gyroscope and the linear acceleration from the accelerometer.

Gyroscope

A MEMS gyroscope contains a vibrating proof mass. When the chip rotates, the Coriolis effect pushes the vibrating mass sideways, and the size of that sideways motion is proportional to the rotation rate. The output is the angular velocity ω\omega of the sensor, in rad/s (or °/s), expressed in the sensor's own frame.

Three properties make the gyroscope the most valuable sensor on a walking robot:

  1. It measures a state variable directly. The base's angular velocity is part of the robot's state, and the gyroscope reads it with no integration.
  2. It is the same everywhere on a rigid body. Every point on a rigid torso rotates at the same rate, so the gyro does not care where on the torso it is mounted (only how it is oriented).
  3. It is fast. IMUs typically sample at hundreds to thousands of hertz with little internal delay.

Its main weakness is bias: a small, slowly changing offset. A gyro bias of 0.01 rad/s looks harmless, but if you integrate it to get an angle, after 60 s the angle is off by 0.6 rad, about 34°.

Accelerometer

A MEMS accelerometer contains a proof mass on tiny springs. When the chip accelerates, the springs flex, and the deflection is measured. The surprise for beginners is what it reads when it is not moving.

Sit an accelerometer flat on a table. It reads about +9.81+9.81 m/s² upward, not zero. The table pushes up on the chip, the chip pushes up on the proof mass, and the springs deflect exactly as they would if the chip were accelerating upward at 1 g in empty space. Drop the chip and it reads zero during free fall, even though it is accelerating downward at 9.81 m/s².

What an accelerometer measures is called specific force: the acceleration minus gravity, expressed in the sensor frame,

fbody=R⊤ (aworld−gworld),gworld=(0,0,−9.81) m/s2.f_{body} = R^\top\,(a_{world} - g_{world}), \qquad g_{world} = (0, 0, -9.81)\ \text{m/s}^2.

At rest (aworld=0a_{world} = 0) this gives fbody=R⊤(0,0,9.81)f_{body} = R^\top (0, 0, 9.81): the accelerometer is a gravity-direction sensor when the robot is still. When the robot moves, the reading is a mix of gravity and real acceleration that the sensor itself cannot separate. This is Einstein's equivalence principle in a chip.

Angular velocity versus linear velocity

A rigid body has two kinds of velocity:

  • Angular velocity ω\omega (rad/s) describes how fast it rotates. There is one angular velocity for the whole body.
  • Linear velocity vv (m/s) describes how fast a point moves. Different points on a rotating body move at different speeds:
vP=vC+ω×rCP,v_P = v_C + \omega \times r_{CP},

where vCv_C is the velocity of some reference point CC and rCPr_{CP} is the vector from CC to PP. A robot spinning in place at 2 rad/s has zero velocity at its centre and 0.6 m/s at a point 0.3 m away.

The IMU's gyroscope measures ω\omega directly. No sensor in an IMU measures vv. The accelerometer at point PP measures the acceleration of that point,

aP=aC+α×rCP+ω×(ω×rCP),a_P = a_C + \alpha \times r_{CP} + \omega \times (\omega \times r_{CP}),

which includes a centripetal term ω×(ω×r)\omega\times(\omega\times r) and a tangential term α×r\alpha \times r that have nothing to do with how fast the robot is travelling. A robot driving in a straight line at a constant 1 m/s produces an accelerometer reading of zero in the horizontal axes, exactly the same as a robot standing still.

In the experiment below, the blue square is an IMU mounted off-centre on a robot base seen from above. Move it around: the gyro reading never changes, while the speed of the IMU point and the acceleration it feels do.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Why a gyroscope gives the body's angular velocity directly (the same at every point of a rigid body) while linear velocity depends on where you look (v = v_c + ω × r) and is not measured by an IMU at all.

How it works

A planar rigid body (a robot base seen from above) is driven with a commanded turn rate and forward speed, each following its command with a 0.25 s first-order lag so accelerations stay finite. The body pose is integrated at 240 Hz.

For the base centre and for an IMU mounted at offset r along the body x axis, the code computes the world-frame velocity v = v_c + ω × r and acceleration a = a_c + α × r − ω² r. The accelerometer reading is that acceleration rotated into the body frame (gravity is vertical and does not appear in this horizontal view). The gyro reading is ω.

Adjustable parameters

  • Motion: spin in place, straight, circle
  • Turn rate ω (−3 to 3 rad/s)
  • Forward speed (0–1 m/s)
  • IMU offset r (0–0.4 m)

Known limitations

  • Planar (2-D) motion only; gravity and the vertical axis are left out.
  • The IMU is ideal: no noise, bias or latency.

Equations

ωIMU=ωbody(same everywhere on a rigid body)\omega_{IMU} = \omega_{body} \quad \text{(same everywhere on a rigid body)}
vP=vC+ω×rCPv_P = v_C + \omega \times r_{CP}
aP=aC+α×rCP+ω×(ω×rCP)a_P = a_C + \alpha \times r_{CP} + \omega \times (\omega \times r_{CP})

Core update rule

// lib/sim/ch04-imu.ts — point P at body offset r
const vx = b.vx - b.omega * ry;                       // v = v_c + ω × r
const vy = b.vy + b.omega * rx;
const ax = b.ax - b.alpha * ry - b.omega ** 2 * rx;   // centripetal + tangential
const ay = b.ay + b.alpha * rx - b.omega ** 2 * ry;
gyro = b.omega;                                       // identical at every point

Explained in Chapter 4: Sensors & Data

Why an accelerometer does not give you velocity

It is tempting to think: velocity is the integral of acceleration, the accelerometer measures acceleration, so integrate it. Three separate problems stand in the way.

  1. It measures specific force, not acceleration. Gravity is mixed into every reading. To recover the true acceleration you must compute aworld=R fbody+gworlda_{world} = R\,f_{body} + g_{world}, which needs the orientation RR, which itself has to be estimated. Any orientation error leaks gravity into the result. A tilt error of just 1° leaks 9.81sin⁡1°≈0.179.81 \sin 1° \approx 0.17 m/s² into the horizontal axes, which is larger than many real accelerations of a walking robot.
  2. The integration constant is unknown. Integration gives a change in velocity, v(t)=v(0)+∫0ta dtv(t) = v(0) + \int_0^t a\,dt. Without knowing v(0)v(0), the starting velocity, the result is meaningless. A robot powered on while being carried has no way to know it started moving.
  3. Errors accumulate. Every reading has noise and bias. Integration adds them up forever, which is the subject of the next section.

That is why "base linear velocity" is the one part of the state that walking robots struggle with most. It has to be estimated by combining the IMU with leg kinematics (when a foot is planted, its velocity is approximately zero, which constrains the base velocity), or with cameras, or not used at all.

Asimov's actor (the policy that runs on the robot) deliberately excludes base linear velocity from its 45 observations. Base linear velocity is given only to the critic, as privileged information available in simulation.

Why integrating acceleration drifts

Suppose the accelerometer has a constant bias bb after gravity removal. Then the measured acceleration is a+ba + b and the integrated velocity and position errors are

δv(t)=b t,δp(t)=12 b t2.\delta v(t) = b\,t, \qquad \delta p(t) = \tfrac{1}{2}\,b\,t^2 .

The velocity error grows linearly and the position error grows quadratically. With a modest residual bias of b=0.05b = 0.05 m/s² (about 5 mg):

TimeVelocity error b tb\,tPosition error 12bt2\tfrac12 b t^2
1 s0.05 m/s0.025 m
10 s0.5 m/s2.5 m
60 s3 m/s90 m

White noise behaves differently. Each sample adds an independent random error nk Δtn_k\,\Delta t, so the velocity error performs a random walk. Its standard deviation grows with the square root of time,

σv(t)=σ Δt  t,\sigma_v(t) = \sigma\,\sqrt{\Delta t\; t},

where σ\sigma is the per-sample noise and Δt\Delta t the sample interval. Datasheets call this "velocity random walk". Bias dominates in the long run because tt outgrows t\sqrt t, and in practice biases also wander with temperature, so they cannot be calibrated away once and forgotten.

The experiment below integrates a simulated 200 Hz accelerometer. The true and estimated curves use the same integrator, so every bit of difference is sensor error. Try the orientation-error slider: a fraction of a degree is enough to swamp a small bias.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Why integrating acceleration to get velocity and position drifts: a constant bias b gives a velocity error b·t and a position error b·t²/2, white noise adds a random walk, and a small orientation error leaks gravity into the horizontal axis.

How it works

A robot moves along a line with a known acceleration profile. A simulated 200 Hz accelerometer reports the true acceleration plus a constant bias, Gaussian white noise and g·sin(δ) from an orientation error δ (the part of gravity that is not subtracted correctly).

The true and the measured accelerations are integrated with the same semi-implicit Euler scheme, so every difference between the curves comes from sensor error. The random numbers come from a seeded generator (mulberry32), so a run is reproducible and the unit tests can check the statistics.

Adjustable parameters

  • True motion: still, shuttle, start–stop
  • Bias b (−0.2 to 0.2 m/s²)
  • White noise σ per sample (0–0.3 m/s²)
  • Orientation error (0–3°)
  • Noise seed

Known limitations

  • One axis. Real dead reckoning is 3-D, and orientation errors also grow over time because the gyro drifts.
  • Bias is constant here. Real biases change with temperature and time (see the bias-drift slider in the next experiment).
  • No corrections such as zero-velocity updates, leg odometry or external position fixes, which is exactly what real estimators add.

Equations

ameas=atrue+b+gsin⁡δ+nk,nk∼N(0,σ2)a_{meas} = a_{true} + b + g\sin\delta + n_k, \quad n_k \sim \mathcal N(0, \sigma^2)
v^(t)−v(t)=(b+gsin⁡δ) t+∑knk Δt\hat v(t) - v(t) = (b + g\sin\delta)\,t + \sum_k n_k\,\Delta t
p^(t)−p(t)≈12(b+gsin⁡δ) t2,std⁡[v^−v]=σΔt t\hat p(t) - p(t) \approx \tfrac12 (b + g\sin\delta)\,t^2, \qquad \operatorname{std}[\hat v - v] = \sigma\sqrt{\Delta t\, t}

Core update rule

// lib/sim/ch04-sensors.ts — one 5 ms sample
aTrue = trueAccel(profile, t);
aMeas = aTrue + bias + g * Math.sin(tiltError) + noise * gaussian(rng);
vTrue += aTrue * dt;  pTrue += vTrue * dt;
vEst  += aMeas * dt;  pEst  += vEst  * dt;   // same integrator, so error = sensor error

Explained in Chapter 4: Sensors & Data

Real systems fight drift by correcting the integral whenever another source of information is available: a foot is known to be stationary (zero-velocity update), a camera recognises a landmark, or the leg kinematics constrain the base velocity. Pure inertial dead reckoning over more than a few seconds is not practical with MEMS sensors.

Encoders: joint position and joint velocity

Every actuated joint has an encoder that measures its angle. Two common kinds are:

  • Incremental encoders count ticks as the shaft turns. They only measure change, so the robot needs a homing procedure at start-up.
  • Absolute encoders (often magnetic, reading a magnet on the shaft) report the absolute angle immediately.

Resolution is given in bits or counts per revolution. A 14-bit absolute encoder has 214=163842^{14} = 16384 counts per revolution, so one count is 2π/16384≈0.000382\pi / 16384 \approx 0.00038 rad (0.022°). That is fine for position: a 0.4 m leg link moves its tip about 0.15 mm per count.

Joint position is therefore measured directly and accurately. Joint velocity usually is not. Most systems compute it by differencing successive positions, q˙≈(qk−qk−1)/Δt\dot q \approx (q_k - q_{k-1}) / \Delta t. At 200 Hz (Δt=5\Delta t = 5 ms), a change of one count looks like 0.00038/0.005≈0.0770.00038 / 0.005 \approx 0.077 rad/s. Velocity readings are quantized in steps of that size, and differencing amplifies any position noise. Firmware typically low-pass filters the result, which smooths the noise but adds delay.

Where the encoder sits matters too. An encoder on the motor side of a gearbox with ratio NN has NN times finer joint resolution, but it cannot see gearbox backlash or flexing between motor and joint.

On Asimov, joint position and velocity observations are grouped by CAN timing into groups 1–3, so joints in different groups are read at slightly different times. Menlo does not publish which joints belong to which group or the timing offsets. Chapter 5 covers why this matters.

Sensor fusion

No single sensor gives a good orientation estimate:

  • Integrating the gyroscope gives orientation that is smooth and responsive, but it drifts because of bias.
  • The accelerometer at rest gives the direction of gravity, and therefore roll and pitch, with no drift. But during motion it is corrupted by real accelerations, so it is noisy and wrong in the short term.

These weaknesses are complementary: one is good at high frequencies, the other at low frequencies. Sensor fusion combines them. The simplest version is a complementary filter, which trusts the gyro for fast changes and slowly pulls the estimate towards the accelerometer's gravity direction:

complementary_filter.py
import numpy as np
 
def complementary_update(roll, pitch, gyro, accel, dt, alpha=0.98):
    """One update of a roll/pitch complementary filter.
 
    gyro:  body angular velocity [wx, wy, wz] in rad/s
    accel: specific force [fx, fy, fz] in m/s^2 (reads ~[0, 0, 9.81] when level and still)
    Uses a small-angle approximation for the gyro step, fine for gentle tilts.
    """
    # 1. Predict: integrate the gyro (smooth, but drifts).
    roll_g = roll + gyro[0] * dt
    pitch_g = pitch + gyro[1] * dt
    # 2. Measure tilt from the gravity direction (no drift, but noisy during motion).
    roll_a = np.arctan2(accel[1], accel[2])
    pitch_a = np.arctan2(-accel[0], np.hypot(accel[1], accel[2]))
    # 3. Blend: mostly gyro in the short term, accelerometer in the long term.
    return (alpha * roll_g + (1 - alpha) * roll_a,
            alpha * pitch_g + (1 - alpha) * pitch_a)
python

With alpha = 0.98 at 200 Hz, the accelerometer correction has a time constant of about Δt α/(1−α)≈0.25\Delta t\,\alpha/(1-\alpha) \approx 0.25 s: gyro bias is corrected within a fraction of a second, while brief accelerations during a footstep barely disturb the estimate.

Production filters do the same thing more carefully. Mahony's filter (2008) runs a feedback correction on the rotation group and estimates gyro bias. Madgwick's filter (2010) uses a gradient-descent correction on quaternions and is popular on small processors. Extended Kalman filters weigh each sensor by its modelled noise and can also fuse leg kinematics to estimate base velocity. Kok, Hol and Schön's tutorial (2017) is an excellent derivation of all of these.

Yaw is unobservable from gravity

Gravity points straight down whatever direction the robot faces, so the accelerometer carries no information about yaw. Without a magnetometer, camera or other heading reference, the yaw estimate is pure gyro integration and drifts without bound. This is one reason locomotion policies avoid absolute yaw as an input.

Projected gravity

Projected gravity is the direction of gravity expressed in the robot's body frame, as a unit vector:

gb=R⊤[00−1]=[sin⁡θ−sin⁡ϕcos⁡θ−cos⁡ϕcos⁡θ].g_b = R^\top \begin{bmatrix} 0 \\ 0 \\ -1 \end{bmatrix} = \begin{bmatrix} \sin\theta \\ -\sin\phi\cos\theta \\ -\cos\phi\cos\theta \end{bmatrix}.

It answers a simple question for the robot: which way is down, from my point of view?

  • Standing level: gb=(0,0,−1)g_b = (0, 0, -1).
  • Pitched 10° nose-down: gb≈(0.174,0,−0.985)g_b \approx (0.174, 0, -0.985). Gravity has a forward component.
  • Rolled 10° (left side up, so leaning to the right): gb≈(0,−0.174,−0.985)g_b \approx (0, -0.174, -0.985).

Because Rz(ψ)⊤R_z(\psi)^\top leaves the vertical axis unchanged, yaw cancels out completely. Projected gravity encodes roll and pitch, and nothing else. Its three numbers have only two degrees of freedom, since they always form a unit vector.

Why would a policy want this instead of roll and pitch angles?

  • No singularities or wrap-around. The components are smooth functions of orientation everywhere. Euler angles jump at ±180° and break down at ±90° pitch.
  • Yaw invariance is exactly right. Walking forward should not depend on whether the robot faces north or east. Giving the policy yaw would force it to learn that yaw does not matter, and absolute yaw drifts anyway.
  • It is what balance depends on. Falling over is a question of tilt relative to gravity, and gbg_b measures that directly.
  • Well scaled for a neural network. Each component lies between −1 and 1.

When the robot is still, projected gravity is just the normalised, negated accelerometer reading: gb≈−fbody/∥fbody∥g_b \approx -f_{body}/\lVert f_{body} \rVert. During walking, footstep impacts and body accelerations corrupt the accelerometer, so a fusion filter is needed. In simulation, the orientation is known exactly, so projected gravity can be computed from the simulator's quaternion:

projected_gravity.py
import numpy as np
 
def projected_gravity(quat_wxyz):
    """Unit gravity direction in the body frame: R^T @ [0, 0, -1].
    quat_wxyz: body orientation (w, x, y, z), e.g. from a MuJoCo framequat sensor."""
    w, x, y, z = quat_wxyz
    # Minus the third row of the rotation matrix built from the quaternion.
    return -np.array([2 * (x * z - w * y),
                      2 * (y * z + w * x),
                      1 - 2 * (x * x + y * y)])
 
print(projected_gravity([1, 0, 0, 0]))   # level -> [-0. -0. -1.]
python

Projected gravity is one of the three-dimensional inputs in Asimov's 45-element actor observation. In Menlo's processor-in-the-loop setup, a MuJoCo bridge sends imu_ang_vel and imu_lin_acc to the firmware over UDP, and the hardware FusionX path computes projected gravity for the policy. The policy therefore receives projected gravity from the same fusion code in simulation testing as on the real robot.

That last point is a good example of the sim-to-real principle from Chapter 1: rather than handing the policy a perfect simulated gravity vector, the processor-in-the-loop setup routes raw IMU signals through the real estimator, so the policy sees the estimator's actual behaviour. Menlo does not publish FusionX's algorithm, so this site does not describe its internals.

Watch the three numbers below while the robot turns in place: they do not move. Then switch to nod or sway.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

That projected gravity encodes roll and pitch but not yaw: turning in place leaves all three numbers unchanged, while nodding or swaying changes them.

How it works

A robot base follows a scripted orientation: a steady turn (yaw only), a nod (pitch), a sway (roll), or a walking-like mix of sway, a small pitch bob and a slow turn. At each frame the orientation is turned into a rotation matrix and projected gravity g_b = Rᵀ·[0, 0, −1] is computed and plotted.

The plumb indicator shows the horizontal components (g_x, g_y) in the body frame: the dot moves in the direction that 'down' points relative to the robot.

Adjustable parameters

  • Motion: turn, nod, sway, walk
  • Tilt amplitude (0–60°)

Known limitations

  • The motions are scripted, not simulated dynamics.
  • On a real robot projected gravity is estimated by a sensor-fusion filter and carries its own errors, especially during strong accelerations.

Equations

gb=R⊤[0,0,−1]⊤g_b = R^\top [0, 0, -1]^\top
Rz(ψ)⊤[0,0,−1]⊤=[0,0,−1]⊤  ⇒  gb is independent of ψR_z(\psi)^\top [0,0,-1]^\top = [0,0,-1]^\top \;\Rightarrow\; g_b \text{ is independent of } \psi

Core update rule

const { roll, pitch, yaw } = attitude(scenario, t);
const g = projectedGravity(eulerToMatrix(roll, pitch, yaw));
// g depends on roll and pitch only

Explained in Chapter 4: Sensors & Data

Sensor errors

Every real measurement differs from the truth. The main error types, with typical units:

ErrorWhat it isTypical unitEffect
NoiseRandom, sample-to-sample fluctuation, roughly zero-meanrad/s, m/s² (or per √Hz as a density)Fuzz on the signal; random walk when integrated
BiasConstant or slowly varying offsetrad/s, m/s², mgLinear error growth when integrated once, quadratic when twice
DriftSlow change of bias over time and temperaturerad/s/√s (bias instability, bias random walk)Calibration goes stale
Scale factor errorGain slightly different from nominal% or ppmError proportional to the signal
QuantizationRounding to the nearest digital step (1 LSB)counts, LSBStaircase; limits finite-difference velocity
Measurement latencyTime between the physical event and the value reaching softwaremsThe controller reacts to the past
Finite sampling frequencyValues exist only at discrete instantsHzFast events can be missed or aliased

Sampling frequency

A sensor sampled at frequency fsf_s produces a value every 1/fs1/f_s seconds. The Nyquist limit says that only signal content below fs/2f_s/2 can be represented. Faster content does not disappear; it aliases into false low-frequency signals unless it is filtered out before sampling. Foot impacts produce high-frequency vibration, so IMUs usually include configurable low-pass filters, which in turn add a little delay.

Between samples, software keeps using the last value it received. That zero-order hold behaves like an additional average delay of half a sample period: 2.5 ms at 200 Hz, 10 ms at 50 Hz.

Measurement latency

Latency comes from many places: the sensor's internal filter, the bus transfer, driver code, and the time a value waits before the next control cycle uses it. Latency is particularly harmful to feedback control, as the Chapter 1 experiment showed. If the body rotates at 2 rad/s and the gyro reading is 10 ms old, the controller's picture of the orientation is behind by 0.02 rad (about 1.1°). Those numbers are illustrative; real budgets depend on the hardware. Chapter 5 traces the path in detail.

The experiment below starts from an ideal signal, the kind a simulator provides, and lets you add each error source one at a time.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

How noise, constant bias, bias drift, quantization, a finite sampling frequency and latency each change the signal a controller receives, compared with the perfect value a simulator can provide.

How it works

An ideal gyro signal (a sum of sinusoids plus an occasional step) is generated at 1 kHz. A sensor model samples it at the chosen frequency, adds bias, a bias random walk and white noise, and rounds the result to a quantization step (one least-significant bit). Each sample then waits in a delivery queue for the chosen latency.

Between deliveries the software keeps seeing the last delivered value (zero-order hold), which produces the staircase. The RMS error over the last 2 s summarises the combined effect. The presets are illustrative orders of magnitude, not values from any datasheet.

Adjustable parameters

  • Sampling frequency (25, 50, 100, 200, 1000 Hz)
  • White noise σ (0–0.2 rad/s)
  • Constant bias (−0.2 to 0.2 rad/s)
  • Bias random walk (0–0.05 rad/s/√s)
  • Quantization step (0–0.1 rad/s)
  • Latency (0–100 ms)

Known limitations

  • Latency is a constant delay. Real buses add jitter and occasionally drop or reorder packets (see Chapter 5).
  • No anti-aliasing filter, so high-frequency content aliases at low sampling rates, as it would without one.
  • Noise is white and Gaussian. Real sensors also show flicker noise, vibration pickup and temperature effects.

Equations

yk=Q(x(tk)+b+β(tk)+nk),tk=k/fsy_k = Q\big(x(t_k) + b + \beta(t_k) + n_k\big), \quad t_k = k / f_s
β(t+Δt)=β(t)+σβΔt w,w∼N(0,1)\beta(t + \Delta t) = \beta(t) + \sigma_\beta \sqrt{\Delta t}\, w, \quad w \sim \mathcal N(0,1)
software sees yk for t∈[tk+τ, tk+1+τ)\text{software sees } y_k \text{ for } t \in [t_k + \tau,\ t_{k+1} + \tau)
Q(x)=Δ⋅round⁡(x/Δ)Q(x) = \Delta \cdot \operatorname{round}(x / \Delta)

Core update rule

// lib/sim/ch04-sensors.ts
driftBias += biasWalk * Math.sqrt(dt) * gaussian(rng);
if (t >= nextSample) {                                 // ADC sample at rateHz
  const v = quantize(ideal + bias + driftBias + noise * gaussian(rng), lsb);
  pipeline.push({ t, v });
  nextSample += 1 / rateHz;
}
while (pipeline[0]?.t <= t - latency) output = pipeline.shift().v;  // delivery

Explained in Chapter 4: Sensors & Data

Ground-truth state in simulation

In a simulator, ground truth is free: the base position, linear velocity, contact forces and foot heights can all be read exactly from memory. This creates a temptation and an opportunity.

The temptation is to give the policy observations that do not exist on the robot, such as exact base linear velocity or contact forces. The policy will learn to depend on them and fail on hardware.

The opportunity is to use ground truth where it does not have to exist on the robot: during training. In actor-critic reinforcement learning, the critic only helps train the policy and is thrown away at deployment, so it can safely see privileged information.

Asimov's critic receives 19 privileged values on top of the actor's 45: base linear velocity (3), foot height (2), foot air time (2), binary foot contact (2), foot contact forces (6), toe joint position (2) and toe joint velocity (2), for a critic input of 64.

Chapter 9 explains this asymmetric arrangement in detail.

How MuJoCo generates virtual sensor readings

MuJoCo sensors are declared in the <sensor> section of the model and are computed from the exact simulated state during mj_step (or mj_forward). Most body-mounted sensors attach to a site, a massless frame placed on a body exactly where the real sensor sits. The output is written into data.sensordata.

MJCF sensorAttached toOutputReal counterpart
gyrosite3: angular velocity in the site frame (rad/s)IMU gyroscope
accelerometersite3: linear acceleration minus gravity, in the site frame (m/s²)IMU accelerometer
framequatobject (e.g. site)4: orientation quaternion (w, x, y, z), world frame by defaultOutput of a fusion filter
velocimetersite3: linear velocity in the site frame (m/s)None on an IMU. This is ground truth
jointposhinge or slide joint1: joint positionEncoder
jointvelhinge or slide joint1: joint velocityDifferentiated encoder
touch, force, torquesiteContact normal force; force/torque at a siteFoot pressure sensor, load cell

Here is a minimal floating base with an IMU site and four sensors. The gyro and accelerometer are named after the signals Menlo's bridge reads; this is an illustrative model, not Asimov's model file.

imu_demo.xml
<mujoco model="imu_demo">
  <option timestep="0.005"/>
  <worldbody>
    <light pos="0 0 3"/>
    <geom name="floor" type="plane" size="2 2 0.1"/>
    <body name="base" pos="0 0 0.5">
      <freejoint/>
      <geom type="box" size="0.15 0.1 0.05" mass="5"/>
      <!-- The IMU chip: 2 cm forward, 3 cm above the base origin. -->
      <site name="imu" pos="0.02 0 0.03"/>
    </body>
  </worldbody>
  <sensor>
    <gyro          name="imu_ang_vel" site="imu"/>
    <accelerometer name="imu_lin_acc" site="imu"/>
    <framequat     name="imu_quat"    objtype="site" objname="imu"/>
    <velocimeter   name="imu_vel"     site="imu"/>
  </sensor>
</mujoco>
xml
read_imu.py
import numpy as np
import mujoco
 
model = mujoco.MjModel.from_xml_path("imu_demo.xml")
data = mujoco.MjData(model)
 
for _ in range(400):                      # 2 s: the box drops onto the floor and settles
    mujoco.mj_step(model, data)
mujoco.mj_forward(model, data)            # make sensordata consistent with the final state
 
gyro = data.sensor("imu_ang_vel").data.copy()
acc = data.sensor("imu_lin_acc").data.copy()
quat = data.sensor("imu_quat").data.copy()
print(acc)    # at rest: approximately [0, 0, 9.81], i.e. gravity reads as "up"
print(gyro)   # approximately [0, 0, 0]
 
# MuJoCo's values are exact. Real-sensor errors must be added by your code:
rng = np.random.default_rng(0)
gyro_bias = rng.normal(0.0, 0.01, size=3)                # fixed per episode (illustrative)
noisy_gyro = gyro + gyro_bias + rng.normal(0.0, 0.02, size=3)
python

Three details are worth knowing:

  • The accelerometer includes gravity, exactly like a real one. A MuJoCo accelerometer at rest reads about +9.81+9.81 along the site's up axis.
  • The velocimeter is ground truth. It reports the site's linear velocity perfectly. It is useful for rewards and critics, but no real IMU has one, so it should not be an actor input.
  • Noise is your job. Each sensor element accepts a noise attribute (a standard deviation), stored as model.sensor_noise. MuJoCo does not apply it: native sensor noise was removed from the engine, and the field is kept only as a convenient place to store a standard deviation for your own code (see the MuJoCo changelog). The values written to sensordata are always noiseless, so training environments add noise, bias, delay and quantization themselves, as in the last two lines above.

How sensor data is represented

Sensor values take several forms between the chip and the policy.

Numerical arrays

Inside software, sensor data is a vector of floating-point numbers. MuJoCo's sensordata is a flat float64 array with every sensor concatenated in declaration order. A policy's observation is also a flat vector, usually float32, assembled in a fixed order that must be identical in training and deployment. A single misplaced element (say, swapping two joints) produces a policy that runs without error but behaves nonsensically.

Asimov's actor observation has 45 elements: base angular velocity (3), projected gravity (3), velocity command vx,vy,ωzv_x, v_y, \omega_z (3), joint positions (12), joint velocities (12) and previous actions (12). Observation normalization is enabled.

Of those 45 numbers, only the joint positions come from a sensor that measures them directly and well. Angular velocity is direct but noisy. Joint velocities are usually differentiated. Projected gravity is the output of a fusion filter. The command comes from the operator, and previous actions come from the policy's own memory.

Binary packets

On the wire, sensors do not send floats in text. They send binary packets: fixed layouts of bytes. A MEMS IMU typically reports raw 16-bit integers that firmware scales into physical units. For example, a gyro configured for ±2000 °/s full scale maps that range onto −32768…32767, about 16.4 counts per °/s. Firmware may then pack several values, with a timestamp, into a frame. Here is a hypothetical 28-byte frame:

imu_packet.py
import struct
 
# Illustrative layout, little-endian: uint32 timestamp (µs) + 6 float32 values.
IMU_FMT = "<I6f"                        # 4 + 6*4 = 28 bytes
assert struct.calcsize(IMU_FMT) == 28
 
def pack_imu(t_us, gyro, acc):
    return struct.pack(IMU_FMT, t_us, *gyro, *acc)
 
def unpack_imu(buf):
    t_us, gx, gy, gz, ax, ay, az = struct.unpack(IMU_FMT, buf)
    return t_us, (gx, gy, gz), (ax, ay, az)
 
pkt = pack_imu(1_250_000, (0.01, -0.02, 0.30), (0.1, 0.0, 9.81))
print(len(pkt), unpack_imu(pkt))
python

Byte order, field order, scaling and units are a contract between sender and receiver. None of it is visible in the bytes themselves. Classic CAN frames carry at most 8 data bytes, so data such as this has to be split across frames or packed as scaled integers. The layout above is invented for illustration. Menlo does not publish Asimov's packet formats.

Software interfaces

Above the bytes sit software interfaces that give the data names and types:

  • ROS defines standard messages such as sensor_msgs/Imu (orientation quaternion, angular velocity, linear acceleration, each with a covariance matrix and a timestamped header) and sensor_msgs/JointState (names, positions, velocities, efforts).
  • Linux SocketCAN exposes CAN buses as network sockets, so programs read and write CAN frames with ordinary socket calls.
  • UDP sockets carry small datagrams with low overhead and no delivery guarantee, which suits streaming sensor values where a late packet is useless anyway.

Menlo's processor-in-the-loop setup uses virtual CAN via SocketCAN, the same software interface as the real actuator stack, and sends IMU signals from the MuJoCo bridge to the firmware over UDP. CAN delay and jitter injection are used to test timing robustness.

Using the same interface in simulation and on hardware is deliberate: the firmware and policy code cannot tell whether the bytes came from MuJoCo or from real sensors. Chapter 5 covers buses, packets and timing in depth, and Chapter 6 puts the whole simulated sensor path together.

Practical example: one observation, end to end

Follow one control cycle of a walking robot built like Asimov, using the documented observation layout.

  1. Sensing. The IMU samples its gyroscope and accelerometer. Joint encoders are read over the CAN bus, in groups, a fraction of a millisecond apart.
  2. Conversion. Firmware scales raw counts into rad/s, m/s² and rad, applies calibration (bias, axis alignment), and rotates IMU readings into the base frame.
  3. Estimation. The fusion filter updates orientation from the gyro and accelerometer and produces projected gravity. Joint velocities are differenced and filtered.
  4. Assembly. Software builds the 45-element vector: angular velocity, projected gravity, command, joint positions, joint velocities, previous actions. Each element is normalised with statistics saved from training.
  5. Inference. At 50 Hz the policy maps this vector to 12 commanded joint targets (Chapter 8).

In simulation, step 1 is replaced by MuJoCo's sensors, and every error in steps 1–3 is either modelled (noise, bias, delay, CAN grouping, the real FusionX path) or missing. Anything missing is a sim-to-real gap.

Limitations and common misconceptions

“An accelerometer at rest reads zero.”

It reads +g+g upward, about 9.81 m/s². It reads zero in free fall. It measures specific force, not acceleration.

“The IMU measures the robot's velocity.”

It measures angular velocity directly and linear acceleration (plus gravity) at one point. Linear velocity has to be estimated, and integrating the accelerometer alone drifts within seconds.

“Projected gravity tells the robot which way it is facing.”

It encodes roll and pitch only. Yaw has no effect on it. Heading requires a magnetometer, vision or gyro integration with drift.

“Simulated sensors are realistic because the physics is realistic.”

MuJoCo computes sensor values exactly from the simulated state. Noise, bias, drift, quantization, sampling and latency exist only if your code adds them.

“The gyro's mounting position matters.”

For angular velocity on a rigid body, only the mounting orientation matters. Position matters for the accelerometer, which picks up centripetal and tangential acceleration at its location.

Limitations of this chapter's simplified models: the experiments use one or two axes, Gaussian white noise and constant delays. Real IMUs also show temperature-dependent bias, vibration rectification, cross-axis coupling and scale-factor errors, and real buses add jitter and dropped messages. Allan-variance analysis is the standard way to characterise a real IMU's noise and bias behaviour.

Key takeaways

Key takeaways

  • Vectors only make sense in a frame. vworld=R vbodyv_{world} = R\,v_{body}, and RR is orthonormal, so R−1=R⊤R^{-1} = R^\top.
  • Roll, pitch and yaw are readable but have singularities. Quaternions (w,x,y,z)(w, x, y, z) and rotation matrices are used internally.
  • The gyroscope measures angular velocity directly, and it is the same everywhere on a rigid body. The accelerometer measures specific force, including gravity.
  • No IMU sensor measures linear velocity. Integrating acceleration needs a known orientation and a known starting velocity, and drifts: bias gives errors of b tb\,t in velocity and 12bt2\tfrac12 b t^2 in position.
  • Projected gravity gb=R⊤[0,0,−1]g_b = R^\top [0, 0, -1] encodes roll and pitch, not yaw. On Asimov it comes from the hardware FusionX path.
  • Encoders measure joint position well. Joint velocity is usually differentiated and filtered.
  • Simulators provide exact ground truth. Real data has noise, bias, drift, quantization, latency and finite sampling, and the policy must be trained on data that looks like that.

References and further reading