bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
A differential drive robot in Chrono

The kinematics of a differential drive worked out where a differential drive robot goes from its forward speed and turning rate, with a model of its motion. Here the robot is a simulated body in Chrono, CHRONO_DiffDriveRobot, the robot that the later examples drive with their sensors. It drives a short script, and the example compares where it goes with where the kinematic model says it should.

The robot driving its script

The robot drives straight, turns on the spot by a quarter of a turn, drives a third of a circle of radius 1 m and stops. The yellow line is where its axle centre went, the cyan one where the kinematic model says it should have gone. The squares are 25 cm.

What you need

bitsim built with Chrono, and with Irrlicht to see the robot; see Installing bitsim.

The robot

The robot comes from its robot file, robots/bitsim_diff_drive_robot.json: its chassis, plates and wheels, two DC gear motors with encoders, and its sensors, which this example does not use. Load it, place it, and add it to a Chrono system:

CHRONO_DiffDriveRobot robot;
robot.load(bitsim::consts::ROBOTS_DIR + "/bitsim_diff_drive_robot.json");
robot.set_world_pose(0.0, 0.0, 0.0); // the axle centre at (x, y), facing yaw
robot.add_to_sys(system);
const std::string ROBOTS_DIR
Path to robots definitions.
Definition bitsim_consts.h:42

The robot needs a floor to drive on: here a fixed box with friction 0.8. Then at every step:

robot.set_velocity(v, omega); // [m/s] ahead, [rad/s] to the left
robot.update(dt); // the motors' speed controllers, and their torque on the wheels
system.DoStepDynamics(dt);

set_velocity turns the command into a speed for each wheel, with wheels of radius \(r\) that are \(L\) apart:

\[\omega_L = \frac{v - \omega L / 2}{r}, \qquad \omega_R = \frac{v + \omega L / 2}{r} \]

Each motor's speed controller then sets its voltage to reach that speed. The wheels are driven by the torque of the motors, and the robot moves because they grip the floor. axle_center() and heading() say where it is.

The kinematic model

DiffDriveDynamics is the model of The kinematics of a differential drive. Given the same commands, it says where the robot would be if its wheels turned at once at the speed they were told and never slipped.

Running the example

./chrono_diff_drive # headless
./chrono_diff_drive --render # in a window, in real time
./chrono_diff_drive --record DIR # and write the window to DIR, ten pictures a second

It returns 0 if the robot ends within 10 cm of the model.

Output

Robot: robots/bitsim_diff_drive_robot.json
wheels of radius 0.100 m, 0.400 m apart
t [s] command v [m/s] w [rad/s] x [m] y [m] yaw [deg] model x model y model yaw off [m]
0.00 straight 0.00 -0.00 -0.000 0.000 -0.0 0.001 0.000 0.0 0.001
0.50 straight 0.25 -0.00 0.066 0.000 -0.0 0.150 0.000 0.0 0.084
1.00 straight 0.37 -0.00 0.227 -0.000 -0.0 0.300 0.000 0.0 0.073
1.50 straight 0.38 0.00 0.418 -0.000 -0.0 0.450 0.000 0.0 0.032
2.00 straight 0.35 -0.00 0.601 -0.000 -0.0 0.600 0.000 0.0 0.001
...
4.00 straight 0.29 0.00 1.204 -0.000 -0.0 1.200 0.000 0.0 0.004
4.50 turn on the spot 0.05 0.62 1.286 0.003 9.4 1.200 0.000 22.5 0.086
5.00 turn on the spot -0.05 0.98 1.282 -0.001 33.0 1.200 0.000 45.0 0.082
5.50 turn on the spot -0.06 1.05 1.262 -0.022 62.7 1.200 0.000 67.5 0.066
6.00 turn on the spot -0.03 0.94 1.257 -0.043 91.5 1.200 0.000 90.0 0.072
6.50 arc 0.23 0.36 1.243 0.007 109.7 1.189 0.149 98.6 0.152
7.00 arc 0.35 0.11 1.183 0.145 115.5 1.155 0.296 107.2 0.153
...
12.50 arc 0.30 0.30 -0.164 0.909 -161.5 -0.170 0.929 -158.3 0.021
13.00 stop 0.29 0.29 -0.302 0.851 -152.9 -0.300 0.866 -150.0 0.015
13.50 stop 0.04 0.09 -0.371 0.812 -147.8 -0.300 0.866 -150.0 0.089
14.00 stop -0.07 -0.02 -0.359 0.820 -147.1 -0.300 0.866 -150.0 0.075
At the end the robot is 0.034 m and 1.8 deg off the kinematic model, 0.159 m at most

v and w are how fast the simulated robot moves and turns, not what it was told.

  • The motors take time. Told 0.3 m/s from standing, the robot is at 0.25 m/s after half a second. Their speed controllers then overshoot, to 0.38 m/s, and settle after about 3 s.
  • The robot does not stop at once. When the turn starts it is still rolling at 0.29 m/s, and it rolls on by 8 cm before it turns on the spot. Then it turns slowly at first and too fast later, 1.05 rad/s against \(\pi/4\) = 0.79, and ends the quarter turn only 1.5 degrees past it.
  • Errors made early stay. The heading at the start of the arc is 11 degrees ahead of the model's, so the arc starts 15 cm away from the model's. Once the speeds settle, the two arcs come together again.

The kinematic model is right about where steady commands take the robot, but not about how it gets from one command to the next. For that you need the motors; see A brushless DC motor and A differential drive robot with real motors. Then robots measure where they are instead of trusting the commands: Odometry from the wheel encoders.

Things to try

  1. Make speed_kp in the robot file twice as big. Does the overshoot grow or shrink?
  2. Make the friction of the floor 0.2. Where does the robot slip, and what happens to the error?
  3. Add a fifth segment that drives backwards, {"back", -0.3, 0.0, 2.0}.
  4. Give the kinematic model the speeds the robot really has, from world.velocity(), instead of the commands. How far apart do they end?

The code

// A first look at CHRONO_DiffDriveRobot, the robot that the later examples drive. It is loaded from
// its robot file, put on the ground, and driven through a short script: straight ahead, a turn on
// the spot, an arc and a stop. Each command is a forward speed and a turning rate. The example
// compares where the simulated robot goes with where DiffDriveDynamics, the kinematic model of
// diff_drive_kinematics, says the commands should take it.
//
// Usage: chrono_diff_drive [--render] [--record DIR]
//
// --render shows the robot in a window, in real time. --record DIR writes the window to DIR, ten
// pictures a second.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_CHRONO
#include <chrono/physics/ChBodyEasy.h>
#include <chrono/physics/ChSystemNSC.h>
#ifdef BITSIM_IRRLICHT
#include <chrono_irrlicht/ChIrrTools.h>
#include <chrono_irrlicht/ChVisualSystemIrrlicht.h>
#endif
#include <any>
#include <array>
#include <chrono>
#include <cmath>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
{
const std::string ROBOT_FILE = bitsim::consts::ROBOTS_DIR + "/bitsim_diff_drive_robot.json";
const real_t STEP_SIZE = 0.002; // [s]
const real_t PRINT_PERIOD = 0.5; // [s]
const real_t RECORD_RATE = 10.0; // [pictures/s]
const real_t RENDER_RATE = 30.0; // [frames/s]
// A part of the script: drive at v [m/s], turning at omega [rad/s], for duration [s]
struct Segment
{
std::string name;
};
const std::vector<Segment> SCRIPT{
{"straight", 0.3, 0.0, 4.0},
{"turn on the spot", 0.0, PI / 4.0, 2.0}, // a quarter of a turn
{"arc", 0.3, 0.3, 2.0 * PI / 3.0 / 0.3}, // a third of a circle of radius 1 m
{"stop", 0.0, 0.0, 1.5},
};
// Where the robot is: the centre of its axle and its heading
struct Pose
{
};
class World
{
public:
{
system_.SetGravitationalAcceleration(
chrono::ChVector3d(0.0, 0.0, -bitsim::consts::maths::G));
system_.SetCollisionSystemType(chrono::ChCollisionSystem::Type::BULLET);
system_.SetSolverType(chrono::ChSolver::Type::BARZILAIBORWEIN);
system_.GetSolver()->AsIterative()->SetMaxIterations(40);
auto material = chrono_types::make_shared<chrono::ChContactMaterialNSC>();
material->SetFriction(0.8f);
material->SetRestitution(0.1f);
ground_ = chrono_types::make_shared<chrono::ChBodyEasyBox>(10.0, 10.0, 0.1, 1000.0, true,
true, material);
ground_->SetPos(chrono::ChVector3d(0.0, 0.0, -0.05));
ground_->SetFixed(true);
ground_->GetVisualShape(0)->SetColor(chrono::ChColor(0.45f, 0.45f, 0.42f));
system_.Add(ground_);
robot_.load(std::filesystem::path(ROBOT_FILE));
robot_.set_world_pose(0.0, 0.0, 0.0);
robot_.add_to_sys(system_);
}
void step(real_t v, real_t omega)
{
// set_velocity turns (v, omega) into a target speed for each wheel's motor, and update
// runs the motors' speed controllers and puts their torque on the wheels
robot_.set_velocity(v, omega);
robot_.update(STEP_SIZE);
system_.DoStepDynamics(STEP_SIZE);
}
Pose pose() const
{
const auto c = robot_.axle_center();
return {c.x(), c.y(), robot_.heading()};
}
// The speed of the chassis along its heading [m/s], and its turning rate [rad/s]
std::array<real_t, 2> velocity() const
{
const auto chassis = robot_.get_chassis();
const auto vel = chassis->GetPosDt();
const real_t yaw = robot_.heading();
return {vel.x() * std::cos(yaw) + vel.y() * std::sin(yaw), chassis->GetAngVelParent().z()};
}
real_t time() const { return system_.GetChTime(); }
chrono::ChSystemNSC &system() { return system_; }
const CHRONO_DiffDriveRobot &robot() const { return robot_; }
private:
chrono::ChSystemNSC system_;
std::shared_ptr<chrono::ChBodyEasyBox> ground_;
CHRONO_DiffDriveRobot robot_;
};
// The kinematic model: the pose that the commands give, if the wheels turned at once at the speed
// they are told and never slipped
{
public:
Kinematics() : model_(DiffDriveDynamics::DynamicVersion::V1, false)
{
model_.set_time_step(STEP_SIZE);
}
void step(real_t v, real_t omega)
{
const std::map<std::string, std::any> input{{"v", std::any(v)},
{"w", std::any(omega)},
{"errors", std::any(std::array<real_t, 2>{})}};
model_.integrate(input);
}
Pose pose() const
{
return {model_.get_x_position(), model_.get_y_position(), model_.get_orientation()};
}
private:
DiffDriveDynamics model_;
};
real_t angle_diff(real_t a, real_t b) { return std::remainder(a - b, 2.0 * PI); }
#ifdef BITSIM_IRRLICHT
class Display
{
public:
Display(World &world, const std::string &record) : world_(world), recorder_(record, RECORD_RATE)
{
vis_.AttachSystem(&world_.system());
vis_.SetWindowSize(1280, 720);
vis_.SetWindowTitle("A differential drive robot in Chrono");
vis_.SetCameraVertical(chrono::CameraVerticalDir::Z);
vis_.Initialize();
vis_.AddCamera({0.45, -1.3, 1.25}, {0.45, 0.45, 0.0});
// A soft light: the typical lights wash the colours out
vis_.AddLightDirectional(60.0, 60.0, chrono::ChColor(0.45f, 0.45f, 0.45f),
chrono::ChColor(0.05f, 0.05f, 0.05f),
chrono::ChColor(0.55f, 0.55f, 0.55f));
}
// Returns false once the window is closed
bool show(const Pose &truth, const Pose &model, const Segment &segment)
{
if (!vis_.Run())
{
return false;
}
truth_.push_back({truth.x, truth.y, 0.01});
model_.push_back({model.x, model.y, 0.012});
vis_.BeginScene();
vis_.Render();
// A grid of 25 cm squares, for scale
chrono::irrlicht::tools::drawGrid(&vis_, 0.25, 0.25, 16, 16,
chrono::ChCoordsysd(chrono::ChVector3d(0.0, 0.0, 0.002)),
chrono::ChColor(0.6f, 0.6f, 0.6f));
draw_trail_(model_, chrono::ChColor(0.2f, 0.8f, 0.9f));
draw_trail_(truth_, chrono::ChColor(1.0f, 0.85f, 0.2f));
const auto v = world_.velocity();
std::ostringstream text;
text << std::fixed << std::setprecision(2) << "t = " << world_.time() << " s "
<< segment.name << ": v = " << segment.v << " m/s, omega = " << segment.omega
<< " rad/s robot: v = " << v[0] << " m/s, omega = " << v[1]
<< " rad/s off the model: " << std::setprecision(3)
<< std::hypot(truth.x - model.x, truth.y - model.y)
<< " m yellow: the robot, cyan: the model";
vis_.EndScene();
recorder_.record(vis_, world_.time());
return true;
}
private:
void draw_trail_(const std::vector<chrono::ChVector3d> &trail, const chrono::ChColor &colour)
{
for (std::size_t i = 1; i < trail.size(); ++i)
{
bitsim::utils::render::irr_draw_line(vis_, trail[i - 1], trail[i], colour, 3.0);
}
}
World &world_;
chrono::irrlicht::ChVisualSystemIrrlicht vis_;
bitsim::utils::render::FrameRecorder recorder_;
std::vector<chrono::ChVector3d> truth_;
std::vector<chrono::ChVector3d> model_;
};
#endif
struct Options
{
bool render{false};
std::string record;
};
int run(const Options &options)
{
World world;
Kinematics kinematics;
const auto &data = world.robot().get_data();
std::cout << std::fixed << std::setprecision(3) << "Robot: " << ROBOT_FILE << "\n"
<< " wheels of radius " << data.wheel_radius << " m, " << data.axle_length
<< " m apart\n\n";
#ifdef BITSIM_IRRLICHT
std::optional<Display> display;
if (options.render)
{
display.emplace(world, options.record);
}
#else
if (options.render)
{
std::cerr << "--render and --record need bitsim configured with BITSIM_IRRLICHT=ON\n";
return 1;
}
#endif
std::cout << " t [s] command v [m/s] w [rad/s] x [m] y [m] yaw [deg]"
" model x model y model yaw off [m]\n";
real_t max_off = 0.0;
real_t next_print = 0.0;
real_t next_frame = 0.0;
real_t segment_end = 0.0;
const auto wall_start = std::chrono::steady_clock::now();
for (const auto &segment : SCRIPT)
{
segment_end += segment.duration;
while (world.time() < segment_end - 0.5 * STEP_SIZE)
{
world.step(segment.v, segment.omega);
kinematics.step(segment.v, segment.omega);
const Pose truth = world.pose();
const Pose model = kinematics.pose();
const real_t off = std::hypot(truth.x - model.x, truth.y - model.y);
max_off = std::max(max_off, off);
if (world.time() + 1e-9 >= next_print)
{
next_print += PRINT_PERIOD;
const auto v = world.velocity();
std::cout << std::setw(9) << std::setprecision(2) << world.time() << " "
<< std::left << std::setw(17) << segment.name << std::right
<< std::setw(9) << v[0] << std::setw(11) << v[1] << std::setprecision(3)
<< std::setw(8) << truth.x << std::setw(8) << truth.y
<< std::setprecision(1) << std::setw(11) << truth.yaw * 180.0 / PI
<< std::setprecision(3) << std::setw(10) << model.x << std::setw(10)
<< model.y << std::setprecision(1) << std::setw(11)
<< model.yaw * 180.0 / PI << std::setprecision(3) << std::setw(10) << off
<< "\n";
}
#ifdef BITSIM_IRRLICHT
if (display && world.time() + 1e-9 >= next_frame)
{
next_frame += 1.0 / RENDER_RATE;
if (!display->show(truth, model, segment))
{
return 0;
}
const real_t ahead =
world.time() -
std::chrono::duration<real_t>(std::chrono::steady_clock::now() - wall_start)
.count();
if (ahead > 0.0)
{
std::this_thread::sleep_for(std::chrono::duration<real_t>(ahead));
}
}
#else
(void)next_frame;
#endif
}
}
const Pose truth = world.pose();
const Pose model = kinematics.pose();
std::cout << std::setprecision(3) << "\nAt the end the robot is "
<< std::hypot(truth.x - model.x, truth.y - model.y) << " m and "
<< std::setprecision(1) << std::abs(angle_diff(truth.yaw, model.yaw)) * 180.0 / PI
<< " deg off the kinematic model, " << std::setprecision(3) << max_off
<< " m at most\n";
// The motors need a moment to reach a new speed, and overshoot it, so on the way the robot
// is some centimetres off the model. By the end the errors mostly cancel: more than 10 cm
// would mean that something is wrong with the robot or its file
return std::hypot(truth.x - model.x, truth.y - model.y) < 0.1 ? 0 : 1;
}
} // namespace chrono_diff_drive
int main(int argc, char **argv)
{
using namespace chrono_diff_drive;
Options options;
for (int i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
if (arg == "--render")
{
options.render = true;
}
else if (arg == "--record" && i + 1 < argc)
{
options.render = true;
options.record = argv[++i];
}
else
{
std::cerr << "Usage: chrono_diff_drive [--render] [--record DIR]\n";
return 1;
}
}
return run(options);
}
#else
#include <iostream>
int main()
{
std::cerr << "You need PROJECTCHRONO configured with "
<< "bitsim in order to run this example "
<< "Reconfigure bitsim and set ENABLE_CHRONO=ON" << std::endl;
return 1;
}
#endif
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
DiffDriveDynamics class. Describes the motion of a differential drive robot in the plane: the centre ...
Definition diff_drive_dynamics.h:39
A differential-drive robot in Chrono: a chassis, two driven wheels and a ball caster....
Definition diff_drive_robot.h:52
Definition chrono_diff_drive.cpp:175
bool show(const Pose &truth, const Pose &model, const Segment &segment)
Definition chrono_diff_drive.cpp:192
Display(World &world, const std::string &record)
Definition chrono_diff_drive.cpp:177
Definition chrono_diff_drive.cpp:147
Pose pose() const
Definition chrono_diff_drive.cpp:162
Kinematics()
Definition chrono_diff_drive.cpp:149
void step(real_t v, real_t omega)
Definition chrono_diff_drive.cpp:154
Definition chrono_diff_drive.cpp:85
Pose pose() const
Definition chrono_diff_drive.cpp:119
void step(real_t v, real_t omega)
Definition chrono_diff_drive.cpp:110
std::array< real_t, 2 > velocity() const
Definition chrono_diff_drive.cpp:126
chrono::ChSystemNSC & system()
Definition chrono_diff_drive.cpp:135
const CHRONO_DiffDriveRobot & robot() const
Definition chrono_diff_drive.cpp:136
World()
Definition chrono_diff_drive.cpp:87
real_t time() const
Definition chrono_diff_drive.cpp:134
int main()
Definition discounted_returns.cpp:19
Pieces of an Irrlicht window for a robot simulation: a texture on the floor, a path drawn behind a ro...
const real_t G
Acceleration due to gravity m/secs.
Definition bitsim_consts.h:68
const real_t PI
The PI constant.
Definition bitsim_consts.h:63
@ off
Definition logger.h:51
void irr_draw_world_axes(chrono::irrlicht::ChVisualSystemIrrlicht &vis, real_t scale)
Definition irrlicht_utils.cpp:65
void irr_draw_line(chrono::irrlicht::ChVisualSystemIrrlicht &vis, const chrono::ChVector3d &start, const chrono::ChVector3d &end, const chrono::ChColor &color, real_t thickness)
Definition irrlicht_utils.cpp:19
void draw_status_bar(chrono::irrlicht::ChVisualSystemIrrlicht &vis, const std::string &text)
Write text on a light bar along the bottom of the window. Call this between Render() and EndScene().
Definition irrlicht_scene.cpp:151
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
void record(const std::vector< Run > &runs, const std::string &directory)
Definition cart_pole_lqr_mpc.cpp:194
Definition chrono_diff_drive.cpp:46
const real_t RENDER_RATE
Definition chrono_diff_drive.cpp:58
const std::vector< Segment > SCRIPT
Definition chrono_diff_drive.cpp:69
real_t angle_diff(real_t a, real_t b)
Definition chrono_diff_drive.cpp:171
const std::string ROBOT_FILE
Definition chrono_diff_drive.cpp:54
const real_t STEP_SIZE
Definition chrono_diff_drive.cpp:55
const real_t PRINT_PERIOD
Definition chrono_diff_drive.cpp:56
const real_t PI
Definition chrono_diff_drive.cpp:53
int run(const Options &options)
Definition chrono_diff_drive.cpp:249
const real_t RECORD_RATE
Definition chrono_diff_drive.cpp:57
EKFSlam::Pose Pose
Definition ekf_slam.cpp:57
Definition chrono_diff_drive.cpp:244
std::string record
Definition chrono_diff_drive.cpp:246
bool render
Definition chrono_diff_drive.cpp:245
Definition chrono_diff_drive.cpp:78
real_t x
Definition chrono_diff_drive.cpp:79
real_t y
Definition chrono_diff_drive.cpp:80
real_t yaw
Definition chrono_diff_drive.cpp:81
real_t omega
Definition chrono_diff_drive.cpp:65
std::string name
Definition chrono_diff_drive.cpp:63
real_t v
Definition chrono_diff_drive.cpp:64
real_t duration
Definition chrono_diff_drive.cpp:66