Position, Orientation and Feedback
Robotics Fundamentals
Course 1 · Chapter 6 · Position, Orientation and Feedback
Robotics Fundamentals 5 was about the sensors that look outward: distance, line, light and camera. This chapter is about the sensors that look inward and answer three questions every moving robot has to ask. How far have my wheels turned, and how fast? Which way am I facing, and am I tilted? And so, where am I? The answers are the robot's pose (its position and heading), and they are the raw material for everything in Robotics Fundamentals 7 onwards: a robot cannot correct an error it cannot measure. We start with encoders, which count wheel turns (the odometry of Robotics Fundamentals 4 depends on them), then the inertial measurement unit (gyroscope, accelerometer and compass), then the central trick of the chapter: no single sensor is trustworthy, but two sensors with opposite weaknesses can be combined into one good one (sensor fusion). We then use that to improve dead reckoning, see why GPS is not the answer indoors, tidy up reference frames and angle wrapping, and finish with why all of this matters: feedback.
Sensor specifications in this chapter (counts per revolution, scale factors, noise densities, GPS accuracy, update rates, magnetic field strengths) are typical or approximate values from memory, for the low-cost parts used on small robots. They vary widely between models, so read the datasheet of the part you buy. The formulas (resolution, quantisation, integration, atan2 tilt, the complementary filter and its time constant, the frame rotation, angle wrapping) are standard and exact for the idealised models described.
1. Pose, and two ways of knowing it
On a flat floor a robot's pose has three numbers: (x, y, θ), a position and a heading, as in Robotics Fundamentals 4. A flying or tilting robot adds height, pitch and roll. There are two families of sensor for finding it, and the difference between them runs through the whole chapter.
| Relative (incremental) sensing | Absolute sensing | |
|---|---|---|
| What it tells you | How much the pose has changed since the last reading | Where you are, or which way you face, now, against something fixed |
| Examples | Incremental encoders, gyroscope, wheel odometry | Compass, GPS, absolute encoder, potentiometer, a wall or beacon at a known place |
| Error behaviour | Small, smooth readings, but the small errors are added up and the total drifts without limit | Each reading has its own error, which does not accumulate, but readings are noisier, slower or sometimes unavailable |
| Best at | Fast changes, short times | Slow changes, long times |
The two columns are complementary. Relative sensors are good in the short term and bad in the long term; absolute sensors are the reverse. Nearly every technique in this chapter is a way of using an absolute reference to rein in the drift of a relative one.
2. Incremental (quadrature) encoders
A wheel encoder is attached to a motor or wheel shaft and produces a train of pulses as the shaft turns. A magnetic encoder has a small ring magnet on the shaft and two Hall sensors beside it; an optical encoder has a slotted disc passing between a light source and a detector. A single pulse train tells you how far the shaft has turned but not which way. The fix is to use two sensors placed so that their signals are a quarter of a cycle (90 degrees) apart. These are the A and B channels, and the arrangement is called quadrature.
Counting every edge: 1x, 2x and 4x decoding
One full cycle of A has two edges, and B adds two more, so a cycle has four transitions. The CPR (cycles, or lines, per revolution) printed in a datasheet counts cycles of one channel. You choose how much of the signal to use: counting only the rising edge of A gives 1× (one count per cycle); counting both edges of A gives 2×; counting every edge of both A and B gives 4×, which is four times the resolution from the same encoder and is the usual choice. Watch the vocabulary: some datasheets quote “pulses per revolution” (PPR, one channel), others quote counts after 4× decoding. Always check which, because it changes every number below by a factor of four. In this chapter CPR means cycles per revolution of one channel, and the counts per revolution are 4 × CPR.
Because the encoder sits on the fast motor shaft, the gearbox multiplies the resolution for free: a fraction of a millimetre per count is typical, much finer than the sloppiness of the wheel and the floor. The price is the count rate: 4848 changes a second, each of which must be seen. A program that checks the pins in a loop (polling) will miss some, and a missed state breaks the count. The remedy is an interrupt: the hardware stops the main program the instant a pin changes, runs a very short routine, and returns. Interrupts are covered in Basic Electronics 10, together with the rules for writing a short interrupt routine; many microcontrollers also have a hardware counter that decodes quadrature with no software at all, and a dedicated decoder chip is another option.
Decoding in pseudocode
The decoder keeps the last state and looks up the move from the old state to the new one in a table. This is hardware-neutral Python-style pseudocode; the interrupt wiring is left to Programming for Robotics.
Speed from counts, and the quantisation error
Speed is the change in count over a time interval, v = Δcount × dcount / Δt, and it is the number the control loop of Robotics Fundamentals 7 will use. But counts are whole numbers. In one interval the encoder can only report 38 or 39 counts, never 38.8. Over a window of N counts the reading can be wrong by about one count, so the relative error is about 1 / N. This is quantisation error, and it is worst at low speed and over short intervals.
What encoders cannot tell you
- Where the wheel is, not where the robot is. The encoder counts shaft turns. If the wheel slips on the floor, or lifts, or the gearbox has backlash, the count says one thing and the ground says another (Robotics Fundamentals 4 section 6).
- The starting position. An incremental encoder starts at zero whenever the power comes on. It counts changes, so it cannot know where the shaft was. That is the job of the absolute sensors below.
- Missed counts. A noisy line, a slow interrupt or a long delay with interrupts switched off drops counts, and the count is wrong from then on, silently. A dropped state shows up as a jump of two in the table above.
- Index pulse. Many encoders add a third channel, Z (index), that pulses once per revolution, which gives an absolute reference once per turn.
3. Absolute encoders and potentiometers
An absolute encoder reports the shaft angle directly, and still knows it after the power is cycled. A disc carries several concentric tracks of coded patterns, read together, so each position has a unique code; n tracks give 2n positions in one turn. Codes are usually Gray code, in which only one bit changes between neighbouring positions, so a reading taken exactly at a boundary is at worst one position out, not wildly wrong. Many low-cost absolute encoders are magnetic and send their number over a digital bus. They are used at joints (Robotics Fundamentals 9), where the arm must know its angle at switch-on without searching for a home position.
The simplest absolute angle sensor is the potentiometer (Basic Electronics 3): a resistive track and a wiper on the shaft form a voltage divider whose output is proportional to angle, read by an ADC (Basic Electronics 7 and 10). Its limits are the limited travel (typically 270 or 300 degrees, approximate), the dead zone at the end of the track, wear, and the noise of a sliding contact. Hobby servos use one internally to close their own position loop.
4. The inertial measurement unit (IMU)
An IMU is a small chip (usually mounted on a breakout board and read over a serial bus such as I2C or SPI, mentioned in Basic Electronics 10) that combines several motion sensors, normally a three-axis gyroscope, a three-axis accelerometer, and sometimes a three-axis magnetometer (compass). Each measures a different thing, each is flawed in a different way, and the flaws are what the next section exploits. The sensors are tiny vibrating or flexing structures (MEMS) whose motion is converted to a voltage, then digitised inside the chip, so you receive integers and a scale factor that converts them to units.
Gyroscope: rate of turn
A gyroscope measures angular rate: how fast the robot is turning, in degrees per second (or radians per second), about each axis. It does not measure angle. To get the heading you integrate: add up the rate multiplied by the time step.
Drift from bias
A real gyro never reads exactly zero when still. It has a bias (zero-rate offset): a small constant rate that it reports even when stationary. It also has random noise on every sample. Integrating noise gives a slow random wander, but integrating a bias gives a steady run-away, because a constant added each step makes a straight-line growth in the angle.
Accelerometer: tilt from gravity
An accelerometer measures acceleration along each axis, in units of g (one g is 9.81 m/s2) or m/s2. Importantly, it cannot tell gravity from motion: a robot standing still reads one g, straight up, and that reading is exactly what lets us find the tilt. Tipping the robot moves part of gravity from one axis to another. With the sensor flat, az reads 1 g and the others read 0; tilted, the ratio of the axes gives the angle. Use atan2, not a plain arctangent, because atan2 takes both numbers separately, gives the correct quadrant (a full range of angle instead of just −90 to +90 degrees) and does not divide by zero.
The accelerometer is therefore accurate on average and over the long term (gravity does not drift) but wrong during motion, whenever the robot accelerates, brakes, turns a corner or bumps over a floor joint, and noisy from motor vibration. A simple safeguard is to trust the tilt only when the magnitude is close to 1 g, and ignore it otherwise; but as the example shows, a push below that threshold still slips through, so a better answer is needed. It is the exact opposite of the gyroscope: the gyro is smooth and fast but drifts; the accelerometer is noisy and fooled by motion but does not drift.
Magnetometer: the compass
A magnetometer measures the magnetic field along each axis, in microtesla (µT) or gauss (1 gauss = 100 µT). The Earth's field is roughly 25 to 65 µT in total (approximate, depending on where you are), with the horizontal part, the part that points toward magnetic north, typically about 15 to 30 µT in mid-latitudes. With the sensor flat, the heading follows from the two horizontal axes:
A compass is an absolute heading with no drift, which is its great value, but a robot is a hostile place for one. Motor wires carry currents that make fields of their own (and the field changes with the motor current, so it cannot be calibrated away entirely), steel frames, batteries and the reinforced concrete of a building all bend the field, and the reading can jump near a large metal object. Mount the sensor away from the motors and wires, and treat it as a slow, rough correction rather than a precise one.
Units, scale factors and sample rate
| Sensor | Measures | Typical units and scale (approximate) | Typical sample rate | Strong at | Weak at |
|---|---|---|---|---|---|
| Gyroscope | Rate of turn | Degrees per second; 131 LSB per degree/s on the ±250 range | 100 to 1000 Hz or more | Fast, smooth, short-term heading and tilt change | Bias: drifts without limit |
| Accelerometer | Acceleration (gravity plus motion) | g; 16384 LSB per g on the ±2 g range | 100 to 1000 Hz or more | Long-term tilt (roll and pitch); no drift | Wrong when accelerating; noisy; no heading |
| Magnetometer | Magnetic field | µT; a fraction of a µT per LSB | 10 to 100 Hz | Absolute heading; no drift | Disturbed by motors, steel, wiring; needs calibration |
Always read the sample rate and the scale you have set. A rate of 100 Hz means dt = 0.01 s, and the integration above depends on dt being right. Choosing a larger measurement range (±2000 degrees/s instead of ±250) stops a fast spin from saturating the sensor, but it makes each LSB coarser, so pick the smallest range that the robot's real motion will not exceed.
5. Sensor fusion in plain words
Sensor fusion means combining several imperfect measurements into one better estimate. The idea is not about averaging. It is about each sensor covering the other's weakness. The gyro is good at changes (the high-frequency part of the motion) but cannot hold an angle for long; the accelerometer is poor at changes (noisy, fooled by motion) but right about the angle on average (the low-frequency part). The obvious strategy: trust the gyro in the short term and the accelerometer in the long term.
The complementary filter
The simplest way to do that is one line. At each step, integrate the gyro as usual, then pull the result a small fraction of the way toward the angle the accelerometer gives. The gyro term supplies the fast changes; the accelerometer term slowly drags the angle back to the truth and cancels the drift.
Here is the filter as hardware-neutral Python-style pseudocode.
The Kalman filter, conceptually
The Kalman filter is the more powerful relative of the complementary filter. It does the same job, and no matrix algebra is needed to understand what it does. It keeps two things: a best estimate (here, the angle, and also the gyro's bias) and a measure of how uncertain that estimate is. Each step has two halves. In predict, it moves the estimate forward using a model (the gyro rate), and the uncertainty grows, because every prediction adds error. In update, it takes a measurement (the accelerometer angle), compares it with the prediction, and corrects the estimate by a fraction of the difference, where the fraction is the Kalman gain. The gain is worked out each step from the two uncertainties: a trustworthy measurement gets a large gain; a noisy one, or a confident prediction, a small one. That is the improvement over the complementary filter, whose alpha is one fixed number chosen by hand. The Kalman filter changes its trust as conditions change (for example, it can trust the accelerometer less when the readings are noisy), and it can estimate the gyro's bias as a by-product. Its cost is complexity: a model, noise figures to be chosen, and more computation. For a small robot that only needs tilt, the complementary filter is usually enough; the Kalman filter earns its place when you fuse many sensors with different rates and accuracies (wheel odometry, IMU and GPS, for example). It is the foundation of most professional navigation software.
6. Dead reckoning
Dead reckoning means estimating where you are by starting from a known point and adding up your own motion, with no outside reference. Robotics Fundamentals 4 built it from wheel encoders: from the ticks of each wheel, ds = (dR + dL) / 2 gives the distance moved and dθ = (dR − dL) / L gives the heading change, where L is the track width. That second line is the weak point. It divides a small difference of two large numbers by a small number, so a one-per-cent error in either wheel, or in L, or a slip on one side, becomes a heading error.
The improvement is natural once we have a gyroscope: take the distance from the wheels and the heading from the gyro. The distance is a well-behaved measurement (equal slip on both wheels affects it only moderately), but the heading is the part that suffers from slip and an inexact track width, and a gyro does not care about the floor. The pose update of Robotics Fundamentals 4 is unchanged except that dθ comes from the gyro (rate × dt), or from a fusion of the gyro with the wheels.
Why the position error grows so fast
A heading error is not just an error in the direction; every metre travelled after it carries the robot sideways. If the heading is off by e radians, a straight run of length s ends up s sin e to one side of where it should. If the heading error itself keeps growing as the robot moves, the sideways error grows faster than linearly.
Worked example: heading from the wheels against the gyro
A robot drives three laps of a 1 m square (12 turns of 90 degrees, 1080 degrees in total), taking 180 s. The real track width is 150 mm, but the program uses 152 mm. The gyro was calibrated at power-up and is left with a residual bias of 0.05 degrees/s.
7. GPS and its limits
The Global Positioning System (and its relatives, together called GNSS) is the obvious absolute position sensor for a robot outdoors: a receiver listens to satellites and works out its latitude and longitude. For robots the limits matter more than the principle.
| Property | Typical value (approximate) | Consequence for a robot |
|---|---|---|
| Accuracy, open sky | About 2 to 5 m for a low-cost receiver | Fine for a lawn mower crossing a field; hopeless for a 1 m wide corridor or driving up to a door |
| Near buildings, trees | Often much worse, with jumps of 10 m or more | Signals bounce off walls (multipath) and arrive late, and the position moves although the robot has not |
| Indoors, underground | No fix at all | The satellite signals are very weak and do not pass through roofs and walls, so GPS cannot be the sole answer for an indoor robot |
| Update rate | 1 Hz for many cheap modules; 5 to 10 Hz for better ones | At 1 m/s a robot moves 1 m between fixes; at 1 Hz and 10 m/s, 10 m. Far too slow for steering by itself |
| Heading | Only from motion: the direction between successive fixes | Useless when the robot is stopped or slow (the noise of metres swamps a movement of centimetres) |
| Start-up | From seconds to a minute or more to find a first fix | The robot cannot navigate at once |
| RTK GPS | 1 to 2 cm, and 5 to 20 Hz, with a nearby base station or correction service | Used for farm and survey machines; costs more, needs a clear sky and a radio or network link to the corrections, and fails indoors like ordinary GPS |
A degree of latitude is about 111 km on the ground, so 0.00001 degrees (the last digit most modules print) is about 1.11 m. The north-south and east-west steps are not equal: a degree of longitude shrinks with the cosine of the latitude, so it is about 111.32 × cos 55 = 63.9 km at 55 degrees north. GPS is best used for what it is good at: a slow, absolute, drift-free position, fused with the fast but drifting estimate of wheel odometry and the IMU (this is the standard job for a Kalman filter).
8. Absolute positioning: landmarks and beacons
Dead reckoning drifts, and an absolute fix resets the drift. Indoors, where there is no GPS, a robot gets its absolute fixes from places and objects whose position it already knows.
- Landmarks are features of the environment at known places: a wall (an ultrasonic or laser distance reading tells you the distance from it, which corrects the coordinate perpendicular to the wall), a corner, a door frame, a line crossing a marked junction, a coloured mark, or a printed marker that a camera can read together with its position and orientation. Meeting a landmark whose location is on the robot's map lets the robot replace its drifted estimate with a fresh one, at least in that one direction.
- Beacons are active devices at known places that the robot measures its distance or direction to: infrared or radio transmitters, ultra-wideband (UWB) anchors, or acoustic pingers. Distances to three beacons fix a position (trilateration: the position is where three circles meet), and the beacons never drift. The costs are the infrastructure to install and the noise in the range readings.
Worked example: a robot has driven 10 m along a corridor and its odometry has put it 0.3 m too far along. At the end an ultrasonic sensor measures 0.50 m to the end wall where the map says it should be 0.80 m. The wall reading says the robot is 0.30 m further than it thought, so the robot corrects its position along the corridor by 0.30 m. That fixes the along-corridor coordinate only; the sideways coordinate and the heading need a second landmark (a side wall) to correct. Landmarks used this way, together with maps, are the subject of Robotics Fundamentals 8 (localisation).
9. Reference frames and angle wrapping
Every measurement has a frame of reference. Wheel odometry works in the robot frame (x forward, y to the left, origin at the robot), a lidar reading is in the sensor's frame, and the pose of the robot is in the world frame (fixed to the room, or to the starting point). To use a measurement from one frame in another, rotate it by the robot's heading and shift it by its position. A point (xr, yr) in the robot frame is, in the world frame:
Angle wrapping
An angle of 190 degrees and an angle of −170 degrees point the same way, yet to a computer they are numbers 360 apart. If a robot is facing −170 degrees and wants to face 170 degrees, the subtraction target minus heading gives 340 degrees, and a robot that believed it would turn the long way round, almost a full circle, when 20 degrees the other way would do. The cure is to wrap every angle difference into one standard range, usually −π to +π radians (−180 to +180 degrees).
Make a habit of wrapping differences of angles (errors) and the final angle after every update; it is the same wrap that appeared in the pose update of Robotics Fundamentals 4. Tilt angles in the range −90 to +90 usually do not need it, but headings always do.
10. Why feedback matters
Everything in this chapter is a way of measuring what the robot actually did, as opposed to what it was told to do. That difference is the heart of robot control. Compare two ways of driving 0.6 m.
A robot with no feedback is relying on every part being exactly as it was at the factory, and the world never is. With feedback the robot is told its own error, and can correct it. Doing that well is harder than it sounds: how hard should it correct, how quickly, and how can it avoid overcorrecting and swinging back and forth? That is the subject of Robotics Fundamentals 7.
11. Challenges
Quick reference
- Relative sensors (encoder, gyro, odometry) are smooth but drift; absolute sensors (compass, GPS, absolute encoder, landmark) do not drift but are noisier or unavailable. Fusion uses one to correct the other.
- Quadrature: A and B 90 degrees apart; four states per cycle (forward 00, 10, 11, 01); 4× decoding counts every edge. Counts per wheel revolution = 4 × CPR × gear; resolution = 360 / (CPR × 4 × gear); distance per count = πD / (CPR × 4 × gear). Use interrupts (Basic Electronics 10).
- Speed: v = Δcount × dcount / Δt; quantisation error about 1 / N counts per interval; a longer interval is finer but more delayed; time the gap at low speed.
- Absolute: n-bit encoder 360 / 2n; potentiometer T / 2n over travel T; absolute sensors keep their reading through a power cycle.
- Gyro: rate = raw / sensitivity; angle += rate × dt; a bias b gives error b t (0.5 degrees/s is 30 degrees a minute); measure the bias at rest and subtract it.
- Accelerometer: tilt = atan2 of the axes (pitch = atan2(ax, √(ay2 + az2))); check |a| = 1 g; wrong while accelerating; no heading.
- Compass: heading = atan2(my, mx); hard-iron offset = (max + min) / 2; disturbed by motors and steel; needs tilt compensation.
- Complementary filter: angle = α (angle + gyro × dt) + (1 − α) accel_angle; τ = α dt / (1 − α); a gyro bias b leaves an error τ b. Kalman filter: predict with a model, update with a measurement, by a gain set from the uncertainties.
- Dead reckoning: distance from the wheels, heading from the gyro; sideways error s sin e, and a growing heading error makes position error grow as s2. Wheel heading error scales with turning, gyro error with time.
- GPS: metres of error, 1 to 10 Hz, no signal indoors, no heading at low speed; RTK gives centimetres with corrections. 0.00001 degrees of latitude is about 1.11 m.
- Frames: x(world) = x + xr cos θ − yr sin θ, y(world) = y + xr sin θ + yr cos θ. Wrap angle differences to −π..+π with atan2(sin a, cos a); average angles with sines and cosines.
- Feedback: open loop trusts the commands; closed loop measures the result and corrects the error.
Next, Robotics Fundamentals 7 uses everything measured here to close the loop. Control: making a robot do what you want. It covers open loop against closed loop, the simple on-off (bang-bang) controller, PID control with a worked example, how to tune it, and why a badly tuned robot oscillates, overshoots or becomes unstable, all driven by the encoder speed and gyro heading from this chapter.