Tech Arcanist
Get in touch

64Chapter 64 of 74

Wheel Odometry: x, y and theta in the Simple Controller

Introduction

In chapter 62 the node simple_controller learned to measure how the robot really moves. It reads the wheel angles on the joint_states topic, works out how far each wheel turned (dp) and how much time passed (dt), and logs the driving speed linear and the turning speed angular. Chapter 63 then showed the idea behind odometry: a distance is a speed added up over many tiny pieces of time (the ∫ sign), and an angle works the same way.

This chapter puts that idea into code. The node now keeps the robot's pose, three numbers that say where the robot is and which way it faces:

  • x_: how far the robot is in front of its starting point, in metres,
  • y_: how far it is to the left of its starting point, in metres,
  • theta_: the direction it faces, in radians.

With every joint_states message the node works out one small step, how far the robot moved (d_s) and how much it turned (d_theta), and adds the step to x, y and theta. Then it logs the three numbers, so they can be watched changing while the robot turns and drives in Gazebo.

The node from chapter 62 must already build and run, with the Gazebo simulation and the controller launch file. This chapter only changes simple_controller.py. It needs no new dependency, because math is part of Python itself (as far as I know).

Where the pieces come from

IdeaWhere it was metSection
counting steps to know where the robot ischapter 59Wheel odometry: counting wheel turns
how an encoder gives the angle of a wheel, and why odometry driftschapter 60The incremental encoder and When odometry goes wrong
dp (new angle minus old angle) and dtchapter 61Change, written Δ, and the wheel speed
jointCallback, linear and angularchapter 62The formulas and How jointCallback links to chapters 59 to 61
adding up small pieces; how far the robot moved; how much it turnedchapter 63Adding up small pieces: the ∫ sign, How far the robot moved, How much the robot turned, Odometry, one reading at a time

The formulas

Every letter first, then the formulas:

LetterMeaningValue here
rwheel radius0.033 m
swheel separation (distance between the two wheels)0.17 m
Δφ (dp_left, dp_right in the code)how far a wheel turned since the last reading: new angle minus old anglein rad
Δs (d_s)how far the robot moved forward in this reading: (r × ΔφR + r × ΔφL) ÷ 2in m
Δθ (d_theta)how much the robot turned in this reading: (r × ΔφR minus r × ΔφL) ÷ sin rad
θ (theta_)the heading: the old θ plus Δθin rad
x (x_)the old x plus Δs × cos θin m
y (y_)the old y plus Δs × sin θin m

Δs and Δθ have the same shape as V and ω of chapter 62, but with Δφ in place of φ̇. Speed × time = distance, and φ̇ × Δt = Δφ, so Δt cancels: the step comes straight from dp, with no division by time. The new θ is used for x and y, so the line that adds to theta comes first.

Two wheels seen from above with the left wheel rolling 0.004575 m and the right wheel 0.005425 m. The orange arrow in the middle is their average, d_s = 0.005 m. The difference divided by s = 0.17 m gives d_theta = 0.005 rad.
Two wheel distances give the step forward (their average) and the turn (their difference divided by s). The numbers are one reading of the drive and turn test below.
One step d_s drawn at the heading theta. The part along x is d_s times cos theta and the part along y is d_s times sin theta. An example with theta = 198.530 rad gives x changing by -0.004099 m and y by -0.002863 m.
One step, split into its x share and its y share. The example is a real reading from the test below.

Writing the code

Open the file

In VS Code, open src, then the bumperbot_controller package folder, then the bumperbot_controller folder inside it, and open simple_controller.py.

The VS Code explorer with src, bumperbot_controller, bumperbot_controller and simple_controller.py marked by a yellow arrow
The path to simple_controller.py: src, bumperbot_controller, bumperbot_controller, simple_controller.py.

The code

The whole node, with the new odometry lines added to the node of chapter 62:

#!/usr/bin/env python3

import rclpy
from rclpy.node import Node
from std_msgs.msg import Float64MultiArray
from geometry_msgs.msg import TwistStamped
from sensor_msgs.msg import JointState
import numpy as np
from rclpy.time import Time
from rclpy.constants import S_TO_NS
import math


class SimpleController(Node):

    def __init__(self):
        super().__init__("simple_controller")

        self.declare_parameter("wheel_radius", 0.033)
        self.declare_parameter("wheel_separation", 0.17)

        self.wheel_radius_ = self.get_parameter("wheel_radius").get_parameter_value().double_value
        self.wheel_separation_ = self.get_parameter("wheel_separation").get_parameter_value().double_value

        self.get_logger().info("Using wheel radius %f" % self.wheel_radius_)
        self.get_logger().info("Using wheel separation %f" % self.wheel_separation_)

        self.left_wheel_prev_pos_ = 0.0
        self.right_wheel_prev_pos_ = 0.0
        self.prev_time_ = None   # set from the first joint_states message

        self.x_ = 0.0
        self.y_ = 0.0
        self.theta_ = 0.0

        self.wheel_cmd_pub_ = self.create_publisher(Float64MultiArray, "simple_velocity_controller/commands", 10)
        self.vel_sub_ = self.create_subscription(TwistStamped, "bumperbot_controller/cmd_vel", self.velCallback, 10)
        self.joint_sub_ = self.create_subscription(JointState, "joint_states", self.jointCallback, 10)

        self.speed_conversion_ = np.array([[self.wheel_radius_/2, self.wheel_radius_/2],
                                           [self.wheel_radius_/self.wheel_separation_, -self.wheel_radius_/self.wheel_separation_]])
        self.get_logger().info("The conversion matrix is %s" % self.speed_conversion_)

    def velCallback(self, msg):
        robot_speed = np.array([[msg.twist.linear.x],
                                [msg.twist.angular.z]])

        wheel_speed = np.matmul(np.linalg.inv(self.speed_conversion_), robot_speed)

        wheel_speed_msg = Float64MultiArray()
        wheel_speed_msg.data = [wheel_speed[1, 0], wheel_speed[0, 0]]

        self.wheel_cmd_pub_.publish(wheel_speed_msg)

    def jointCallback(self, msg):
        now = Time.from_msg(msg.header.stamp)

        # First message, or sim time went backwards (e.g. sim reset): re-seed
        if self.prev_time_ is None or now < self.prev_time_:
            self.left_wheel_prev_pos_ = msg.position[0]
            self.right_wheel_prev_pos_ = msg.position[1]
            self.prev_time_ = now
            return

        dt = (now - self.prev_time_).nanoseconds / S_TO_NS
        if dt == 0.0:   # duplicate stamp
            self.get_logger().warn("Skipping joint state: duplicate stamp",
                                throttle_duration_sec=2.0)
            return

        dp_left = msg.position[0] - self.left_wheel_prev_pos_
        dp_right = msg.position[1] - self.right_wheel_prev_pos_

        self.left_wheel_prev_pos_ = msg.position[0]
        self.right_wheel_prev_pos_ = msg.position[1]
        self.prev_time_ = now

        fi_left = dp_left / dt
        fi_right = dp_right / dt

        linear = (self.wheel_radius_ * fi_right + self.wheel_radius_ * fi_left) / 2
        angular = (self.wheel_radius_ * fi_right - self.wheel_radius_ * fi_left) / self.wheel_separation_

        d_s = (self.wheel_radius_ * dp_right + self.wheel_radius_ * dp_left) / 2
        d_theta = (self.wheel_radius_ * dp_right - self.wheel_radius_ * dp_left) / self.wheel_separation_
        self.theta_ += d_theta
        self.x_ += d_s * math.cos(self.theta_)
        self.y_ += d_s * math.sin(self.theta_)

        self.get_logger().info("linear: %f, angular: %f" % (linear, angular))
        self.get_logger().info("x: %f, y: %f, theta: %f" % (self.x_, self.y_, self.theta_))

def main():
    rclpy.init()

    simple_controller = SimpleController()
    rclpy.spin(simple_controller)

    simple_controller.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()

What is new

  • Line 11: import math, for math.cos and math.sin.
  • Lines 32 to 34: the pose. x_, y_ and theta_ all start at 0.0: the robot is at the origin and faces forward.
  • Lines 84 and 85: the step of this reading: d_s, how far the robot moved, and d_theta, how much it turned. Both are made from dp_left and dp_right.
  • Lines 86 to 88: the adding up. theta_ grows by d_theta, then x_ grows by d_s times the cosine of the heading and y_ by d_s times its sine.
  • Line 91: a second log line that prints x, y and theta.

Everything else is the node of chapter 62, unchanged (lines 55 to 82 are its jointCallback: the first-message check, dt, dp, the speeds).

One reading with real numbers

The last test of this chapter, driving and turning at the same time (linear x 0.5 and angular z 0.5), has the most to show, so here is one reading worked out by hand. The controller makes the right wheel turn at (0.5 + 0.5 × 0.17 ÷ 2) ÷ 0.033 = 16.4394 rad/s and the left wheel at (0.5 minus 0.5 × 0.17 ÷ 2) ÷ 0.033 = 13.8636 rad/s. The "before" values for theta, x and y are read from a line of the log on the screen (the screenshots below).

  1. dp (lines 71 and 72): in 10 ms the right wheel turns 16.4394 × 0.01 = 0.164394 rad and the left wheel 13.8636 × 0.01 = 0.138636 rad.
  2. d_s (line 84): r × dp_right = 0.033 × 0.164394 = 0.005425 m and r × dp_left = 0.033 × 0.138636 = 0.004575 m. So d_s = (0.005425 + 0.004575) ÷ 2 = 0.01 ÷ 2 = 0.005 m.
  3. d_theta (line 85): (0.005425 minus 0.004575) ÷ 0.17 = 0.00085 ÷ 0.17 = 0.005 rad.
  4. theta (line 86): the log shows theta = 198.525000 before, so theta = 198.525 + 0.005 = 198.530 rad.
  5. cos and sin (lines 87 and 88): 198.530 rad is 31 full turns plus 3.7513 rad (a full turn is 2π = 6.2832 rad), and cos and sin repeat after every full turn. cos(198.530) = -0.819841 and sin(198.530) = -0.572591.
  6. x (line 87): x = -0.652450 + 0.005 × (-0.819841) = -0.652450 + (-0.004099) = -0.656549 m.
  7. y (line 88): y = 1.817925 + 0.005 × (-0.572591) = 1.817925 + (-0.002863) = 1.815062 m.

The next log line of the test shows x: -0.656549, y: 1.815062 and theta: 198.530000: the same numbers. The widget below does the same sum for other readings of the screenshots. Tick "use the old theta" and the result is off by about 0.00002: with the old heading (198.525) x would come out as -0.656563, which is not what the screen shows. So the node really does use the new theta, and line 86 must stay above lines 87 and 88.

Code visualizer

Every line explained at three levels, with a step-by-step run, a map, bugs to try and a live picture of the robot adding up its path.

Building and running

Terminal 1: build

Open a terminal and build the workspace:

cd bumperbot_ws
colcon build

What you should see

Starting >>> bumperbot_msgs
Starting >>> bumperbot_controller
Starting >>> bumperbot_cpp_examples
Starting >>> bumperbot_description
Finished <<< bumperbot_description [0.34s]
Finished <<< bumperbot_cpp_examples [0.47s]
Finished <<< bumperbot_controller [0.72s]
Finished <<< bumperbot_msgs [0.78s]
Starting >>> bumperbot_py_examples
Finished <<< bumperbot_py_examples [1.50s]

Summary: 5 packages finished [2.51s]
Terminal with cd bumperbot_ws and colcon build marked by yellow arrows, and the build output ending with 5 packages finished in 2.51 s
The build: 5 packages finished.

Terminal 2: the simulation

Open another terminal, source the workspace and start Gazebo with the robot:

. install/setup.bash
ros2 launch bumperbot_description gazebo.launch.py
Two terminals: the finished build above, and below the source command and the Gazebo launch command
The second terminal: source, then launch the simulation.

Terminal 3: the controllers and the node

Open one more terminal and start the controllers, which also start simple_controller:

. install/setup.bash
ros2 launch bumperbot_controller controller.launch.py
Three terminals: the build, the Gazebo launch, and below them the controller launch command with the first start-up lines
The third terminal launches the controllers; Gazebo keeps running in the pane above.

As soon as the node gets joint_states messages it prints two lines for every message: the speeds (line 90) and the pose (line 91). The robot is not moving yet, so every number is 0 (printed as 0.000000 or -0.000000, which is only how a tiny negative number or a negative zero looks with six digits):

What you should see in terminal 3 (the first lines, the robot standing still)

[simple_controller.py-3] [INFO] [1794958994.696752250] [simple_controller]: linear: -0.000000, angular: -0.000000
[simple_controller.py-3] [INFO] [1794958994.697508608] [simple_controller]: x: -0.000000, y: 0.000000, theta: -0.000000
[simple_controller.py-3] [INFO] [1794958994.705669270] [simple_controller]: linear: 0.000000, angular: -0.000000
[simple_controller.py-3] [INFO] [1794958994.706290914] [simple_controller]: x: -0.000000, y: 0.000000, theta: -0.000000
[simple_controller.py-3] [INFO] [1794958994.716003206] [simple_controller]: linear: 0.000000, angular: -0.000000
[simple_controller.py-3] [INFO] [1794958994.716302968] [simple_controller]: x: -0.000000, y: 0.000000, theta: -0.000000
The three terminals with the controller log in the bottom pane: pairs of lines with linear and angular, and x, y and theta, all close to 0. The pose lines are marked with a white box.
The log of the node while the robot stands still: the pose lines (white box) show x, y and theta at 0.

Sending commands and reading the pose

Three commands, one after the other, each in a fourth terminal that is sourced like the others. Terminal 3 keeps printing the log, so x, y and theta can be watched while the robot moves in Gazebo.

Turn left on the spot

Publish a command that only turns, to the left: linear speed 0 and angular speed 0.5 rad/s.

. install/setup.bash
ros2 topic pub /bumperbot_controller/cmd_vel geometry_msgs/msg/TwistStamped 'header:
  stamp:
    sec: 0
    nanosec: 0
  frame_id: ''
twist:
  linear:
    x: 0.0
    y: 0.0
    z: 0.0
  angular:
    z: 0.5'
Four terminals. The bottom one has the ros2 topic pub command typed over several lines, with a yellow arrow at the frame_id line and angular z 0.5 at the end. In the controller pane above, theta counts up: 111.000000, 111.005000, 111.010000, 111.015000.
The command in terminal 4. Above it the log already shows theta counting up in steps of 0.005.

Theta now grows by 0.005 with every reading, and x and y stay at 0:

What you should see in terminal 3

[simple_controller.py-3] [INFO] [1794959835.866186563] [simple_controller]: linear: 0.000000, angular: 0.500000
[simple_controller.py-3] [INFO] [1794959835.867126201] [simple_controller]: x: -0.000000, y: -0.000000, theta: 152.220000
[simple_controller.py-3] [INFO] [1794959835.874889598] [simple_controller]: linear: 0.000000, angular: 0.500000
[simple_controller.py-3] [INFO] [1794959835.875281919] [simple_controller]: x: -0.000000, y: -0.000000, theta: 152.225000
[simple_controller.py-3] [INFO] [1794959835.887337432] [simple_controller]: linear: 0.000000, angular: 0.500000
[simple_controller.py-3] [INFO] [1794959835.888042188] [simple_controller]: x: -0.000000, y: -0.000000, theta: 152.230000
[simple_controller.py-3] [INFO] [1794959835.897112241] [simple_controller]: linear: 0.000000, angular: 0.500000
[simple_controller.py-3] [INFO] [1794959835.897889527] [simple_controller]: x: -0.000000, y: -0.000000, theta: 152.235000
The controller log with the theta values 152.220000, 152.225000, 152.230000 and 152.235000 inside a white box, while x and y stay at 0
Theta keeps growing, and the robot turns on the spot in Gazebo.

Why 0.005? The wheels turn equally fast in opposite directions, so d_s = 0 and d_theta = (0.033 × 0.012879 minus 0.033 × (-0.012879)) ÷ 0.17 = 0.00085 ÷ 0.17 = 0.005 rad per reading (0.5 rad/s × 0.01 s). That is why x and y do not change: d_s is 0, so d_s × cos and d_s × sin are 0 too. And 152.22 is such a big number because theta is never wrapped back into the range minus π to π: 152.22 rad is about 24 full turns of the test so far (152.22 ÷ 6.2832 = 24.2). The cos and sin of lines 87 and 88 repeat after every full turn, so this does not matter for x and y.

A recording of the turn on the spot: theta counts up and the robot rotates.

Turn the other way

Now the same command with angular z -0.5: the robot turns to the right.

ros2 topic pub /bumperbot_controller/cmd_vel geometry_msgs/msg/TwistStamped 'header:
  stamp:
    sec: 0
    nanosec: 0
  frame_id: ''
twist:
  linear:
    x: 0.0
    y: 0.0
    z: 0.0
  angular:
    z: -0.5'
Four terminals. In the controller pane theta falls: 229.625000, 229.620000, 229.615000, 229.610000. The bottom terminal has the command with angular z -0.5 and a yellow arrow.
The command with angular z -0.5. In the controller pane theta now falls.

What you should see in terminal 3

[simple_controller.py-3] [INFO] [1794960014.305103509] [simple_controller]: linear: -0.000000, angular: -0.714286
[simple_controller.py-3] [INFO] [1794960014.306028972] [simple_controller]: x: 0.000000, y: 0.000000, theta: 229.625000
[simple_controller.py-3] [INFO] [1794960014.317135721] [simple_controller]: linear: 0.000000, angular: -0.384615
[simple_controller.py-3] [INFO] [1794960014.317754045] [simple_controller]: x: 0.000000, y: 0.000000, theta: 229.620000
[simple_controller.py-3] [INFO] [1794960014.332117843] [simple_controller]: linear: 0.000000, angular: -0.500000
[simple_controller.py-3] [INFO] [1794960014.332704598] [simple_controller]: x: 0.000000, y: 0.000000, theta: 229.615000
[simple_controller.py-3] [INFO] [1794960014.342042009] [simple_controller]: linear: 0.000000, angular: -0.500000
[simple_controller.py-3] [INFO] [1794960014.342536761] [simple_controller]: x: 0.000000, y: 0.000000, theta: 229.610000

Theta falls by 0.005 with every reading: d_theta is now (r × dp_right minus r × dp_left) ÷ s with the right wheel turning backward, so it is negative. A little later the log shows the same thing:

Controller log lines with theta values 209.335000, 209.330000, 209.325000 and 209.320000 and angular values -0.500000 and -0.555556
Theta keeps falling: 209.335, 209.330, 209.325, 209.320.

The robot in Gazebo turns the opposite way too. Notice the angular values (-0.500000, -0.555556 ...): they jump a little from line to line, as in chapter 62, because they divide by dt. Theta steps by exactly 0.005 every time, because it adds up dp, not speeds.

A recording of the other direction: theta counts down and the robot turns the other way.

Drive and turn

Finally give a driving speed as well: linear x 0.5 and angular z 0.5. The robot now moves forward while it turns, so x and y change too.

ros2 topic pub /bumperbot_controller/cmd_vel geometry_msgs/msg/TwistStamped 'header:
  stamp:
    sec: 0
    nanosec: 0
  frame_id: ''
twist:
  linear:
    x: 0.5
    y: 0.0
    z: 0.0
  angular:
    z: 0.5'
Four terminals. The bottom one has the command with linear x 0.5 and angular z 0.5 and a yellow arrow at the x: 0.5 line. The controller pane above shows x, y and theta changing: for example x 0.775213, y 1.511793, theta 121.490000.
The command with linear x 0.5 and angular z 0.5. In the controller pane x and y change as well as theta.

What you should see in terminal 3

[simple_controller.py-3] [INFO] [1794960259.208810373] [simple_controller]: linear: 0.500000, angular: 0.500000
[simple_controller.py-3] [INFO] [1794960259.209150851] [simple_controller]: x: 0.775213, y: 1.511793, theta: 121.490000
[simple_controller.py-3] [INFO] [1794960259.221980921] [simple_controller]: linear: 0.500000, angular: 0.500000
[simple_controller.py-3] [INFO] [1794960259.222839718] [simple_controller]: x: 0.772627, y: 1.516072, theta: 121.495000
[simple_controller.py-3] [INFO] [1794960259.231722450] [simple_controller]: linear: 0.500000, angular: 0.500000
[simple_controller.py-3] [INFO] [1794960259.232083299] [simple_controller]: x: 0.770019, y: 1.520338, theta: 121.500000
[simple_controller.py-3] [INFO] [1794960259.246233844] [simple_controller]: linear: 0.500000, angular: 0.500000
[simple_controller.py-3] [INFO] [1794960259.246567878] [simple_controller]: x: 0.767390, y: 1.524591, theta: 121.505000

A little later the log looked like this (the readings used in the worked example above):

Controller log lines: x -0.652450, y 1.817925, theta 198.525000, then x -0.656549, y 1.815062, theta 198.530000, then x -0.660634, y 1.812178, theta 198.535000, then x -0.664705, y 1.809274, theta 198.540000
x, y and theta all change: the robot moves and turns at the same time.

Each reading moves the robot 0.005 m (0.5 m/s × 0.01 s) and turns it 0.005 rad, so it drives along a circle. Its radius is V ÷ ω = 0.5 ÷ 0.5 = 1 m (the path in the widget below). The signs of x and y change as the heading goes round, because cos and sin of the heading change sign.

A recording of drive and turn together: x and y change and the robot moves along a circle.

Three tests, one picture

Pick one of the three commands and drag the reading slider: the picture shows the path, the heading and the lines that terminal 3 would print, with the working for the last reading.

Remember

  • The pose is three numbers on the node: x_ and y_ in metres and theta_ in radians. They all start at 0.0 when the node starts.
  • One reading gives one small step: d_s = (r × dp_right + r × dp_left) ÷ 2 for the way forward, and d_theta = (r × dp_right minus r × dp_left) ÷ s for the turn. They use dp, not the speeds, so dt cancels.
  • Add up in this order: theta_ += d_theta first, then x_ += d_s * math.cos(theta_) and y_ += d_s * math.sin(theta_). Use +=, not =, and give cos and sin radians.
  • Turning left on the spot raises theta by 0.005 per reading (0.5 rad/s × 0.01 s), turning right lowers it, and x and y stay put because d_s is 0. With V = 0.5 and ω = 0.5 the robot drives a circle of radius V ÷ ω = 1 m.
  • Theta is never wrapped, so it can show values such as 152.22. cos and sin repeat every full turn, so x and y are still right.
  • The first message only stores the "before" values, so the pose starts to change from the second message. A repeated stamp (dt = 0) is skipped.
  • Odometry only adds up small steps, so a small error in the wheel radius or the wheel separation grows with the distance driven (chapter 60), and the node starts at (0, 0, 0) wherever the robot is.