bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Following a line with infrared sensors and avoiding obstacles

In A line following robot with a Raspberry Pi camera the robot saw the line with a camera. Most small line following robots do it with something much simpler: a few infrared elements that look straight down at the floor. Here the differential drive robot of A differential drive robot in Chrono gets three of them, and an ultrasonic sensor on its front that measures how far away the nearest obstacle ahead is. It drives around a track, a dark line on light paper, and two boxes stand on the line. The robot follows the line, drives around each box, and comes back to the line behind it.

The robot also carries a camera that looks ahead. It does nothing but show, in the corner of the window, what is in front of the robot; the robot does not use it.

One lap of the track, at twice the speed it ran

One lap, at twice the speed it ran. The line from the front of the robot is the sonar's beam: green, or red when an obstacle is close. The robot's camera image is in the top left corner.

What you need

bitsim built with Chrono, Irrlicht and OpenCV, see Installing bitsim. OpenCV draws the track; nothing reads a stream, so any OpenCV will do. The example needs no network, broker or board.

The pieces

Piece Where What it does
InfraredSensor bitsim infrared elements that tell the colour of the floor under them
CHRONO_InfraredBackend bitsim simulated elements: each reads the floor below where the body carries it
MQTT_InfraredBackend bitsim real elements on a board that publishes their readings over MQTT
UltrasonicSensor bitsim measures the distance to the nearest obstacle ahead
CHRONO_UltrasonicBackend bitsim a simulated sensor: casts rays into the Chrono world
MQTT_UltrasonicBackend bitsim a real sensor on a board that publishes over MQTT
FloorImage::reflectance bitsim how bright a picture of the floor is at a point: what an element sees there
CHRONO_DiffDriveRobot bitsim the robot, with both sensors read from the robot file
InfraredLineFollower bitsim follows the line with the elements
RoundedRectangle bitsim the track
ContactCounter bitsim counts the contacts with the boxes
Driver line_following_infrared_sonar.cpp follows the line and goes around the boxes

The sensors

Infrared elements

An infrared reflectance element, such as a TCRT5000, has an infrared LED and a photo transistor side by side. The LED shines at the floor a few millimetres below, and the transistor measures how much light comes back. White paper reflects most of it and a black line very little. A board reads the transistor with an ADC; divided by the reading over white paper, that is the reflectance, from 0 for black to 1 for white, and that is what an InfraredSensor reads, one value per element. Below its threshold, 0.5, an element is over something dark: is_dark.

The robot file gives the elements as a line-sensor:

Setting Value Meaning
type infrared-array infrared elements that look at the floor
backend SIMULATION or MQTT for real elements, see bitsim_example_line_following_infrared_sonar_mqtt
elements (0.24, 0.04, -0.06), (0.24, 0, -0.06), (0.24, -0.04, -0.06) where they are, from the centre of the chassis, left to right [m]
threshold 0.5 below it, an element is over the line
update_rate 100 /s readings per second

The elements are under the front of the chassis, 0.34 m ahead of the axle and 4 cm apart. The line is 5 cm wide, so when the robot is on it only the middle element sees it, and as it drifts off one way an outer element picks it up before the middle one loses it.

In the simulation the floor is a picture, a FloorImage as in A line following robot with a Raspberry Pi camera. Each element reads the brightness of the pixel below it. The robot passes the picture to its elements with set_floor:

robot.set_floor([&floor](real_t x, real_t y) { return floor.reflectance(x, y); });

The same picture is the texture of the floor in the window, so what you see is what the elements read.

Ultrasonic sensor

An ultrasonic sensor, such as an HC-SR04, sends a short burst of sound and times its echo. The echo comes back from whatever is nearest in a cone about 15 degrees wide, between 2 cm and 4 m away. The robot file gives it as the front-sonar:

Setting Value Meaning
type ultrasonic-range
backend SIMULATION or MQTT for a real sensor
frame_pos (0.27, 0, 0.05) where it is, from the centre of the chassis [m]
min_distance, max_distance 0.02, 4.0 what it can measure [m]
beam_angle, n_rays 15, 5 the cone [deg], and the rays the simulation casts across it
update_rate 20 /s readings per second

The simulated sensor casts five rays across the cone into the Chrono world and reports the nearest hit. Closer than min_distance it reports min_distance, and with nothing in range max_distance. Only bodies with collision enabled reflect the rays, and never the robot's own chassis.

The two sensors read at their own rates: the elements every 10 ms and the sonar every 50 ms. The robot decides what to do whenever the elements read, with the latest sonar reading.

Following the line

The three elements say where the line is. Give the left element the value +1, the middle one 0 and the right one -1; the side of the line \(s\) is the mean value of the elements that see it. The robot turns towards it:

\[\omega = 1.6\,s \ \text{rad/s}, \qquad v = 0.3\,(1 - |s|/2) \ \text{m/s} \]

On the line, \(s = 0\), and the robot drives straight. With the line under the middle and the left elements, \(s = 1/2\), and it turns gently left; under the left element only, \(s = 1\), and it turns harder and slows down. If no element sees the line, the robot turns on the spot towards the side where it saw the line last. After 3 s without it, it gives up.

That is a proportional controller with three steps of error. It never knows how far off the line it is, only on which side, so it wobbles a little, but it is all a three-element board can do.

Going around obstacles

The obstacle avoidance is as simple as it gets, and it relies on one thing the robot knows: the track goes counterclockwise, so the outside of the track, where there is room, is on its right. The Driver:

  1. Follow the line. When the sonar measures less than 0.5 m:
  2. Turn away: turn right on the spot by 60 degrees.
  3. Detour: drive an arc to the left, 1.2 m in radius, at 0.25 m/s. It swings out 0.6 m from the line, around the box, and comes back to the line behind it, crossing it at about 60 degrees. Until the middle element sees the line again it ignores the line and the sonar.
  4. Cross: when the middle element finds the line, drive straight on by 0.34 m, the distance from the elements to the axle, so that the wheels are over the line.
  5. Align: turn right on the spot. The elements sweep across the line, first the right one, then the middle one; when the middle one sees it, the robot faces along the line. Follow it.

Why not follow the line as soon as the middle element finds it? The robot crosses the line at a steep angle, and the left element finds it first. A line follower would turn left, towards the line, and end up following it backwards. Driving on until the wheels are over the line and then turning onto it gets the robot facing the right way whatever the angle.

The numbers come from the size of the robot and the boxes. The sonar is 0.37 m ahead of the axle, so with 0.5 m left the box starts 0.87 m ahead of the axle, and the chassis, 0.38 m from the axle at its corners, can turn on the spot. The arc's widest point is about 1 m ahead, where the box is, and leaves 0.2 m between the box and the wheel. The detour covers about 2 m of track, so a box must stand at least 2 m before a corner.

The robot knows its heading and position from the simulation, as a real robot would from its wheel encoders, or a gyroscope, for the turns.

The robot camera

A camera on the front of the chassis, 7 cm above its centre and tilted 8 degrees down, shows the world from the robot. The window renders the scene twice each frame: once from the main camera, and once from the robot's camera into the top left corner. Only the window uses it.

Running the example

./line_following_infrared_sonar # headless, as fast as it can
./line_following_infrared_sonar --render # in a window, in real time

--record DIR also writes the window to DIR, ten frames for each second of simulation. The movie above was made with

./line_following_infrared_sonar --record frames
ffmpeg -framerate 20 -i frames/frame_%05d.png -vf "fps=10,scale=640:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=64:stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=4:diff_mode=rectangle" line_following_infrared_sonar_lap.gif

It returns 0 if the robot went once around the track without touching a box.

Output

Track 4.40 x 2.80 m, line 0.05 m wide, 2 boxes on it
Infrared: 3 elements, 0.34 m ahead of the axle, 100.00 readings/s
Sonar: 0.02 to 4.00 m, 20.00 readings/s
t [s] x [m] y [m] head [deg] infrared sonar [m] state v [m/s] w [rad/s]
0.01 -1.300 -1.400 0.0 .#. 4.00 follow 0.30 0.00
1.00 -1.069 -1.400 -0.0 .#. 0.57 follow 0.30 0.00
2.00 -0.869 -1.414 -31.4 ... 4.00 turn away 0.00 -1.00
3.00 -0.863 -1.440 -72.1 ... 4.00 detour 0.25 0.21
...
8.00 0.169 -2.043 2.7 ... 4.00 detour 0.25 0.21
...
12.00 1.039 -1.609 49.3 ..# 4.00 cross 0.25 0.00
13.00 1.199 -1.418 49.8 ... 4.00 cross 0.25 0.00
14.00 1.246 -1.363 28.3 ... 4.00 align 0.00 -0.50
...
59.00 -1.505 -1.346 -10.2 .#. 1.01 follow 0.30 0.00
The robot went once around the track in 59.80 s of simulation, 42.93 s of wall time
Detours around boxes: 2 of 2, times it touched a box: 0
While following the line, the elements saw it 100.00 % of the time; the longest time without it was 0.00 s

The infrared column shows which elements see the line, left to right. At 2 s the sonar measured less than 0.5 m and the robot turned away; the motors take a moment to stop, so it overshot the 60 degrees by 12. It swung out to 0.64 m from the line at 8 s, found the line again at 12 s, drove on and turned onto it. At 59 s, back at the start, the sonar hears the first box again.

Real sensors over MQTT

Both sensors have an MQTT backend for real sensors on a board, as the motors of A differential drive robot with real motors do. The board publishes each reading as JSON on a topic of its own:

ultrasonic: {"distance": 62.0, "unit": "cm"}
infrared: {"values": [0.91, 0.12, 0.88]}

unit is m, cm or mm, and m if it is missing. The infrared message has one reflectance per element, in the order of the robot file. Either message can also have a timestamp, in UTC, as "2026-11-18 10:15:02".

Reading the sensor never waits for the board: it takes every message that has arrived since the last read and reports the latest. Until the first message arrives the ultrasonic sensor reads max_distance and the infrared elements read white, so check is_alive(), which is true while messages keep arriving, before trusting a reading. To use them, set the backend in the robot file and connect it:

"front-sonar": {"backend": "MQTT", "broker": "tcp://localhost:1883", "topic": "odysseus/sonar", ...}
"line-sensor": {"backend": "MQTT", "broker": "tcp://localhost:1883", "topic": "odysseus/ir", ...}
auto sonar = std::dynamic_pointer_cast<MQTT_UltrasonicBackend>(robot.get_sonar()->range_backend());
sonar->connect();
A real ultrasonic sensor on a board that publishes its readings over MQTT, as an UltrasoundMessage:
Definition mqtt_ultrasound_backend.h:38

You can try them without a board, with a broker on your computer:

mosquitto_pub -t odysseus/sonar -m '{"distance": 35, "unit": "cm"}'

Things to try

  1. Make STOP_DISTANCE 0.3 m. Does the robot still get around the boxes, and what touches first?
  2. Make DETOUR_RADIUS 0.8 m and 1.6 m. How close does the robot pass the box, and how much track does the detour cover?
  3. Move a box 1 m before a corner. The detour comes back onto the corner, not the straight; does the robot still find the line, and which way does it face?
  4. Give the robot five elements, 2 cm apart, in the robot file, and weigh them in InfraredLineFollower. Does it wobble less?
  5. Narrow the line to 3 cm. With the elements 4 cm apart there are now places where no element sees it; what does the robot do there?
  6. Put a box on the inside of a corner, off the line. The beam is 15 degrees wide; does the sonar hear it as the robot turns, and should the robot react?

The code

// Following a line with infrared sensors and avoiding obstacles
// with an ultrasonic sensor
//
// The differential drive robot of the chrono_diff_drive example drives around a track: a dark
// line on light paper. Three infrared elements under the front of its chassis
// tell it where the line is, and an ultrasonic sensor on its front tells it
// how far the nearest obstacle ahead is. Boxes stand on the track. The robot
// follows the line, and when a box is close it drives around it and comes back
// to the line on the other side.
//
// The robot also carries a camera that looks ahead. It does nothing but show,
// in the corner of the window, what is in front of the robot.
//
// Usage: line_following_infrared_sonar [--render] [--record DIR]
//
// --render shows the simulation in a window, in real time. --record DIR also
// writes the window to DIR as frame_00000.png, frame_00001.png, ..., ten a
// second of simulation; ffmpeg turns them into a video.
#include <chrono/physics/ChBodyEasy.h>
#include <chrono/physics/ChContactMaterialNSC.h>
#include <chrono/physics/ChSystemNSC.h>
#include <chrono_irrlicht/ChVisualSystemIrrlicht.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <memory>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
{
using Point = std::array<real_t, 2>;
const std::string ROBOT_FILE = bitsim::consts::ROBOTS_DIR + "/bitsim_diff_drive_robot.json";
const std::string WINDOW_TITLE = "Line following and obstacle avoidance";
const real_t STEP_SIZE = 0.01; // [s]
const real_t TIME_LIMIT = 150.0; // [s]
const real_t PRINT_PERIOD = 1.0; // [s]
const real_t RENDER_RATE = 30.0; // [frames/s] of simulation in the window
const real_t RECORD_RATE = 10.0; // [frames/s] of simulation written by --record
// The track: a rounded rectangle, centred on the origin, drawn on paper
const real_t TRACK_HALF_LENGTH = 2.2; // [m] along x, to the centre of the line
const real_t TRACK_HALF_WIDTH = 1.4; // [m] along y
const real_t TRACK_CORNER_RADIUS = 0.7; // [m]
const real_t LINE_WIDTH = 0.05; // [m]
const real_t FLOOR_WIDTH = 5.6; // [m] the paper, along x, with room for detours
const real_t FLOOR_HEIGHT = 4.6; // [m] along y
const real_t METRES_PER_PIXEL = 0.005; // of the picture of the paper
const uchar PAPER = 235; // the brightness of the paper
const uchar INK = 25; // and of the line
// The boxes on the track: where their centres are, and their size
const std::vector<Point> OBSTACLES{{0.0, -TRACK_HALF_WIDTH}, {-0.2, TRACK_HALF_WIDTH}};
const real_t OBSTACLE_SIZE = 0.3; // [m] each side of its base
const real_t OBSTACLE_HEIGHT = 0.4; // [m]
// The robot starts on the bottom side of the track and goes counterclockwise
// Following the line
const real_t CRUISE_SPEED = 0.3; // [m/s]
const real_t LINE_TURN_RATE = 1.6; // [rad/s] with only an outer element on the line
const real_t SEARCH_TURN_RATE = 0.8; // [rad/s] while looking for the line
const real_t LOST_TIME = 3.0; // [s] without the line before giving up
// Going around an obstacle
const real_t STOP_DISTANCE = 0.5; // [m] closer than this, go around
const real_t TURN_AWAY_ANGLE = 60.0 * PI / 180; // [rad] to the right, before the detour
const real_t DETOUR_RADIUS = 1.2; // [m] of the arc back to the line
const real_t DETOUR_SPEED = 0.25; // [m/s]
const real_t PIVOT_RATE = 1.0; // [rad/s] turning on the spot
// The camera that looks ahead: where it sits on the chassis, and how it looks
const chrono::ChVector3d CAMERA_POSITION{0.26, 0.0, 0.07}; // from the centre of the chassis
const real_t CAMERA_TILT = 8.0 * PI / 180; // [rad] down from the horizon
const real_t CAMERA_FOV = 60.0 * PI / 180; // [rad] vertical
const int CAMERA_WIDTH = 384; // [pixels] in the window
const int CAMERA_HEIGHT = 216;
// ---------------------------------------------------------------------------
// The track
// ---------------------------------------------------------------------------
// The line on the paper
// The paper, with the line on it. It is both what the infrared elements look
// at and the texture of the floor in the window
{
[](real_t x, real_t y) { return TRACK.distance(x, y) < 0.5 * LINE_WIDTH; }, PAPER, INK);
}
// ---------------------------------------------------------------------------
// Following the line
// ---------------------------------------------------------------------------
// The robot follows the line with bitsim's InfraredLineFollower: the three
// elements, left to right, say where the line is, and the robot turns towards
// it, harder the further out it is. With no element on the line it turns on the
// spot towards where it saw the line last
// ---------------------------------------------------------------------------
// Going around obstacles
// ---------------------------------------------------------------------------
// The simplest detour that works: when the sonar hears a box closer than
// STOP_DISTANCE, turn right on the spot by TURN_AWAY_ANGLE, then drive an arc
// to the left. The arc swings out around the box and comes back to the line
// on the other side of it. When the middle element finds the line, drive on
// until the wheels are over it, turn right on the spot until the middle
// element is on it again, and follow the line.
//
// The track goes counterclockwise, so the outside of it, where there is room,
// is always on the right of the robot.
class Driver
{
public:
enum class State
{
FOLLOW, // follow the line
TURN_AWAY, // turn right on the spot, away from the box
DETOUR, // drive an arc to the left, around the box
CROSS, // drive on until the wheels are over the line
ALIGN // turn right on the spot onto the line
};
// ir_ahead is how far ahead of the axle the infrared elements are
explicit Driver(real_t ir_ahead) : ir_ahead_(ir_ahead) {}
Command command(const InfraredSensor &ir, real_t sonar, const Point &position, real_t heading,
real_t dt)
{
switch (state_)
{
if (sonar < STOP_DISTANCE)
{
turn_to_ = heading - TURN_AWAY_ANGLE;
++n_detours_;
state_ = State::TURN_AWAY;
return command(ir, sonar, position, heading, dt);
}
return follower_.command(ir, dt);
if (turn_towards_(heading))
{
return {0.0, -pivot_rate_(heading)};
}
state_ = State::DETOUR;
[[fallthrough]];
if (ir.is_dark(middle_(ir)))
{
cross_from_ = position;
state_ = State::CROSS;
return command(ir, sonar, position, heading, dt);
}
if (std::hypot(position[0] - cross_from_[0], position[1] - cross_from_[1]) < ir_ahead_)
{
return {DETOUR_SPEED, 0.0};
}
state_ = State::ALIGN;
[[fallthrough]];
// Turning right, the elements sweep across the line: first the
// right one, then the middle one
if (!ir.is_dark(middle_(ir)) || ir.is_dark(ir.n_elements() - 1))
{
return {0.0, -0.5 * PIVOT_RATE};
}
state_ = State::FOLLOW;
return follower_.command(ir, dt);
}
return {};
}
State state() const noexcept { return state_; }
bool has_given_up() const { return follower_.has_given_up(); }
bool is_lost() const { return state_ == State::FOLLOW && follower_.is_lost(); }
uint_t n_detours() const noexcept { return n_detours_; }
private:
static uint_t middle_(const InfraredSensor &ir) { return ir.n_elements() / 2; }
// True while the heading is not yet turn_to_
bool turn_towards_(real_t heading) const
{
return std::abs(std::remainder(turn_to_ - heading, 2.0 * PI)) > 0.02;
}
// Slow down near the heading: the motors take a moment to stop
real_t pivot_rate_(real_t heading) const
{
const real_t error = std::abs(std::remainder(turn_to_ - heading, 2.0 * PI));
return std::clamp(2.0 * error, 0.2, PIVOT_RATE);
}
real_t ir_ahead_;
InfraredLineFollower follower_{FOLLOW_LINE};
real_t turn_to_{0.0};
Point cross_from_{0.0, 0.0};
uint_t n_detours_{0};
};
std::string to_string(Driver::State state)
{
switch (state)
{
return "follow";
return "turn away";
return "detour";
return "cross";
return "align";
}
return "";
}
// ---------------------------------------------------------------------------
// The simulated world
// ---------------------------------------------------------------------------
class World
{
public:
explicit World(const FloorImage &floor)
{
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>(20.0, 20.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_);
for (const auto &p : OBSTACLES)
{
auto box = chrono_types::make_shared<chrono::ChBodyEasyBox>(
OBSTACLE_SIZE, OBSTACLE_SIZE, OBSTACLE_HEIGHT, 500.0, true, true, material);
box->SetPos(chrono::ChVector3d(p[0], p[1], 0.5 * OBSTACLE_HEIGHT));
box->SetFixed(true);
box->GetVisualShape(0)->SetColor(chrono::ChColor(0.85f, 0.45f, 0.1f));
system_.Add(box);
obstacles_.push_back(box);
}
contacts_ = std::make_shared<ContactCounter>(obstacles_);
robot_.load(std::filesystem::path(ROBOT_FILE));
if (!robot_.get_line_sensor() || !robot_.get_sonar())
{
throw std::runtime_error("The robot file " + ROBOT_FILE +
" needs a line-sensor and a front-sonar");
}
robot_.set_floor([&floor](real_t x, real_t y) { return floor.reflectance(x, y); });
robot_.set_world_pose(START[0], START[1], 0.0);
robot_.add_to_sys(system_);
}
void step(const Command &command)
{
robot_.set_velocity(command.v, command.omega);
robot_.update(STEP_SIZE);
system_.DoStepDynamics(STEP_SIZE);
touching_ = contacts_->count(system_) > 0;
}
// Put the paper on the ground, so that the window shows the line: a
// rectangle just above the ground with the picture on it. The top left
// corner of the picture is the corner of the floor with the smallest x and
// the largest y
void show_floor(const std::string &texture)
{
// just above the centre of the ground, which is 0.1 thick
texture);
}
real_t time() const { return system_.GetChTime(); }
Point position() const { return {robot_.axle_center().x(), robot_.axle_center().y()}; }
real_t heading() const { return robot_.heading(); }
bool is_touching_an_obstacle() const { return touching_; }
CHRONO_DiffDriveRobot &robot() { return robot_; }
const CHRONO_DiffDriveRobot &robot() const { return robot_; }
chrono::ChSystemNSC &system() { return system_; }
// How far ahead of the axle centre the middle infrared element is
real_t ir_ahead() const
{
const auto &elements = robot_.get_line_sensor()->infrared_backend()->elements();
const auto &e = elements[elements.size() / 2];
const auto chassis = robot_.get_chassis();
const auto world = chassis->GetFrameRefToAbs().TransformPointLocalToParent(
chrono::ChVector3d(e[0], e[1], e[2]));
const auto ahead = world - robot_.axle_center();
return ahead.x() * std::cos(heading()) + ahead.y() * std::sin(heading());
}
private:
chrono::ChSystemNSC system_;
std::shared_ptr<chrono::ChBodyEasyBox> ground_;
std::vector<std::shared_ptr<chrono::ChBody>> obstacles_;
std::shared_ptr<ContactCounter> contacts_;
CHRONO_DiffDriveRobot robot_;
bool touching_{false};
};
// ---------------------------------------------------------------------------
// The window
// ---------------------------------------------------------------------------
// The world from above the track, with what the robot's camera sees in the
// top left corner. The camera only shows; the robot does not use it
class Display
{
public:
Display(World &world, const FloorImage &floor, const std::string &record)
: world_(world), recorder_(record, RECORD_RATE)
{
// The paper on the ground, as a texture. The visual system takes the
// shapes of the bodies when it starts, so it goes on first.
// Irrlicht reads colour pictures more reliably than grey ones
texture_ = (std::filesystem::temp_directory_path() /
"bitsim_line_following_infrared_sonar_floor.png")
.string();
floor.write_texture(texture_);
world_.show_floor(texture_);
vis_.AttachSystem(&world_.system());
vis_.SetWindowSize(1280, 720);
vis_.SetWindowTitle(WINDOW_TITLE);
vis_.SetCameraVertical(chrono::CameraVerticalDir::Z);
vis_.Initialize();
vis_.AddCamera({0.0, -3.4, 3.0}, {0.0, -0.1, 0.0});
// A soft light: the typical lights wash the white paper 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));
// The robot's camera, in the top left corner. The mouse moves the main
// camera only
robot_camera_.emplace(vis_, CAMERA_FOV, CAMERA_WIDTH, CAMERA_HEIGHT);
}
// Returns false once the window is closed
bool show(const InfraredSensor &ir, real_t sonar, const Driver &driver, const Command &command,
real_t lap)
{
if (!vis_.Run())
{
return false;
}
vis_.BeginScene();
vis_.Render();
draw_sonar_(sonar);
draw_robot_view_();
draw_text_(ir, sonar, driver, command, lap);
vis_.EndScene();
recorder_.record(vis_, world_.time());
return true;
}
private:
// The sonar's beam, as far as the echo came from
void draw_sonar_(real_t sonar)
{
const auto chassis = world_.robot().get_chassis();
const auto &frame = chassis->GetFrameRefToAbs();
const auto sonar_backend =
std::dynamic_pointer_cast<bitsim::sensors::backends::CHRONO_UltrasonicBackend>(
world_.robot().get_sonar()->range_backend());
const chrono::ChVector3d start = frame.TransformPointLocalToParent(
sonar_backend ? sonar_backend->position() : chrono::ChVector3d(0.27, 0, 0.05));
const chrono::ChVector3d dir = frame.TransformDirectionLocalToParent({1.0, 0.0, 0.0});
const auto colour = sonar < STOP_DISTANCE ? chrono::ChColor(1.0f, 0.1f, 0.1f)
: chrono::ChColor(0.2f, 0.8f, 0.2f);
bitsim::utils::render::irr_draw_line(vis_, start, start + dir * sonar, colour);
}
// Render the scene again, into the corner, from the robot's camera
void draw_robot_view_()
{
const auto &frame = world_.robot().get_chassis()->GetFrameRefToAbs();
const chrono::ChVector3d eye = frame.TransformPointLocalToParent(CAMERA_POSITION);
const chrono::ChVector3d look = frame.TransformDirectionLocalToParent(
{std::cos(CAMERA_TILT), 0.0, -std::sin(CAMERA_TILT)});
const chrono::ChVector3d target = eye + look;
robot_camera_->draw(eye, target);
}
void draw_text_(const InfraredSensor &ir, real_t sonar, const Driver &driver,
const Command &command, real_t lap)
{
std::ostringstream text;
text << std::fixed << std::setprecision(1) << "t " << world_.time() << " s lap "
<< 100.0 * lap << " % infrared " << ir.pattern() << " sonar "
<< std::setprecision(2) << sonar << " m " << to_string(driver.state()) << " v "
<< command.v << " m/s w " << command.omega << " rad/s detours "
<< driver.n_detours();
}
World &world_;
FrameRecorder recorder_;
std::string texture_;
chrono::irrlicht::ChVisualSystemIrrlicht vis_;
std::optional<InsetCamera> robot_camera_;
};
// ---------------------------------------------------------------------------
// Running it
// ---------------------------------------------------------------------------
struct Options
{
bool render{false};
std::string record;
};
Options parse(int argc, char **argv)
{
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.record = argv[++i];
options.render = true;
}
else
{
std::cout << "Usage: line_following_infrared_sonar [--render] [--record DIR]\n"
<< " --render show the simulation in a window, in real time\n"
<< " --record DIR also write the window to DIR, " << RECORD_RATE
<< " frames a second" << std::endl;
std::exit(arg == "--help" || arg == "-h" ? 0 : 1);
}
}
return options;
}
int run(const Options &options)
{
const FloorImage floor = draw_floor();
World world(floor);
auto &robot = world.robot();
auto &ir = *robot.get_line_sensor();
auto &sonar = *robot.get_sonar();
std::optional<Display> display;
if (options.render)
{
display.emplace(world, floor, options.record);
}
Driver driver(world.ir_ahead());
std::cout << std::fixed << std::setprecision(2) << "Track " << 2 * TRACK_HALF_LENGTH << " x "
<< 2 * TRACK_HALF_WIDTH << " m, line " << LINE_WIDTH << " m wide, "
<< OBSTACLES.size() << " boxes on it\n"
<< "Infrared: " << ir.n_elements() << " elements, " << world.ir_ahead()
<< " m ahead of the axle, " << 1.0 / ir.backend_ptr()->sampling_period()
<< " readings/s\n"
<< "Sonar: " << sonar.range_backend()->min_distance() << " to "
<< sonar.range_backend()->max_distance() << " m, "
<< 1.0 / sonar.backend_ptr()->sampling_period() << " readings/s\n\n"
<< " t [s] x [m] y [m] head [deg] infrared sonar [m] state "
"v [m/s] w [rad/s]\n";
const real_t ir_period = ir.backend_ptr()->sampling_period();
const real_t sonar_period = sonar.backend_ptr()->sampling_period();
real_t next_ir = 0.0;
real_t next_sonar = 0.0;
real_t next_print = 0.0;
real_t next_frame = 0.0;
// Progress around the track, how long the line was under the elements
// while following it, and whether the robot hit a box
real_t last_angle = std::atan2(START[1], START[0]);
real_t travelled_angle = 0.0;
real_t follow_time = 0.0;
real_t lost_time = 0.0;
real_t longest_lost = 0.0;
real_t lost_since = 0.0;
uint_t n_hits = 0;
bool was_touching = false;
bool completed = false;
bool stopped = false;
bool gave_up = false;
const auto wall_start = std::chrono::steady_clock::now();
while (world.time() < TIME_LIMIT)
{
// Each sensor reads at its own rate. The robot decides what to do
// whenever the infrared elements read
if (world.time() + 1e-9 >= next_sonar)
{
next_sonar += sonar_period;
sonar.read_values();
}
if (world.time() + 1e-9 >= next_ir)
{
next_ir += ir_period;
ir.read_values();
driver.command(ir, sonar.distance(), world.position(), world.heading(), ir_period);
if (driver.has_given_up())
{
gave_up = true;
std::cout << "\nThe robot lost the line for " << LOST_TIME << " s and stops"
<< std::endl;
break;
}
}
world.step(command);
// Statistics
const Point p = world.position();
const real_t angle = std::atan2(p[1], p[0]);
travelled_angle += std::remainder(angle - last_angle, 2.0 * PI);
last_angle = angle;
if (driver.state() == Driver::State::FOLLOW)
{
follow_time += STEP_SIZE;
if (driver.is_lost())
{
lost_time += STEP_SIZE;
lost_since += STEP_SIZE;
longest_lost = std::max(longest_lost, lost_since);
}
else
{
lost_since = 0.0;
}
}
if (world.is_touching_an_obstacle() && !was_touching)
{
++n_hits;
std::cout << " the robot touches a box at t = " << world.time() << " s" << std::endl;
}
was_touching = world.is_touching_an_obstacle();
if (world.time() + 1e-9 >= next_print)
{
next_print += PRINT_PERIOD;
std::cout << std::setw(9) << std::setprecision(2) << world.time()
<< std::setprecision(3) << std::setw(8) << p[0] << std::setw(8) << p[1]
<< std::setw(12) << std::setprecision(1) << world.heading() * 180.0 / PI
<< std::setw(10) << ir.pattern() << std::setw(11) << std::setprecision(2)
<< sonar.distance() << " " << std::left << std::setw(10)
<< to_string(driver.state()) << std::right << std::setw(8) << command.v
<< std::setw(11) << command.omega << std::endl;
}
if (display && world.time() + 1e-9 >= next_frame)
{
next_frame += 1.0 / RENDER_RATE;
if (!display->show(ir, sonar.distance(), driver, command,
std::clamp(travelled_angle / (2.0 * PI), 0.0, 1.0)))
{
stopped = true;
break;
}
// Keep to real time, so that the window shows the robot at its speed
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));
}
}
if (travelled_angle >= 2.0 * PI)
{
completed = true;
break;
}
}
const real_t wall_time =
std::chrono::duration<real_t>(std::chrono::steady_clock::now() - wall_start).count();
std::cout << std::setprecision(2) << "\n"
<< (completed ? "The robot went once around the track"
: stopped ? "Stopped"
: gave_up ? "The robot lost the line"
: "The robot did not get around the track")
<< " in " << world.time() << " s of simulation, " << wall_time << " s of wall time\n"
<< "Detours around boxes: " << driver.n_detours() << " of " << OBSTACLES.size()
<< ", times it touched a box: " << n_hits << "\n"
<< "While following the line, the elements saw it "
<< 100.0 * (1.0 - lost_time / std::max(follow_time, STEP_SIZE))
<< " % of the time; the longest time without it was " << longest_lost << " s"
<< std::endl;
return completed && n_hits == 0 ? 0 : 1;
}
} // namespace line_following_infrared_sonar
int main(int argc, char **argv)
{
try
{
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
Follow a dark line with a row of infrared elements.
Definition infrared_line_follower.h:44
A differential-drive robot in Chrono: a chassis, two driven wheels and a ball caster....
Definition diff_drive_robot.h:52
std::shared_ptr< sensors::InfraredSensor > get_line_sensor() const noexcept
Definition diff_drive_robot.h:290
Counts the contacts that touch any of a set of bodies, such as the obstacles a robot should not hit.
Definition contact_counter.h:32
An image of the floor, centred on the world origin.
Definition downward_camera.h:31
An array of infrared reflectance elements that looks at the floor, to tell its colour: light paper or...
Definition infrared_sensor.h:33
Class for modelling ultrasonic sensors.
Definition ultrasonic_sensor.h:21
A closed track in the plane: a rectangle centred on the origin with its sides along x and y,...
Definition rounded_rectangle.h:20
Writes the window to dir/frame_00000.png, frame_00001.png, ..., rate times a second of simulation,...
Definition irrlicht_scene.h:121
A camera on a robot whose view is drawn in the top left corner of the window. It only shows the scene...
Definition irrlicht_scene.h:88
A path drawn as a line: in the plane, just above the floor, where a robot has been or where it thinks...
Definition irrlicht_scene.h:48
Definition line_following_infrared_sonar.cpp:381
bool show(const InfraredSensor &ir, real_t sonar, const Driver &driver, const Command &command, real_t lap)
Definition line_following_infrared_sonar.cpp:412
Display(World &world, const FloorImage &floor, const std::string &record)
Definition line_following_infrared_sonar.cpp:383
Definition line_following_infrared_sonar.cpp:162
Command command(const InfraredSensor &ir, real_t sonar, const Point &position, real_t heading, real_t dt)
Definition line_following_infrared_sonar.cpp:176
uint_t n_detours() const noexcept
Definition line_following_infrared_sonar.cpp:232
State
Definition line_following_infrared_sonar.cpp:165
@ CROSS
Definition line_following_infrared_sonar.cpp:169
@ DETOUR
Definition line_following_infrared_sonar.cpp:168
@ FOLLOW
Definition line_following_infrared_sonar.cpp:166
@ TURN_AWAY
Definition line_following_infrared_sonar.cpp:167
@ ALIGN
Definition line_following_infrared_sonar.cpp:170
bool is_lost() const
Definition line_following_infrared_sonar.cpp:231
bool has_given_up() const
Definition line_following_infrared_sonar.cpp:230
State state() const noexcept
Definition line_following_infrared_sonar.cpp:229
Driver(real_t ir_ahead)
Definition line_following_infrared_sonar.cpp:174
static FloorImage draw(real_t width, real_t height, real_t metres_per_pixel, const std::function< bool(real_t, real_t)> &is_ink, uchar paper=235, uchar ink=25)
Draw a floor: a grey picture of width x height metres of paper, with ink wherever is_ink(x,...
Definition downward_camera.cpp:32
Definition line_following_infrared_sonar.cpp:281
chrono::ChSystemNSC & system()
Definition line_following_infrared_sonar.cpp:351
real_t time() const
Definition line_following_infrared_sonar.cpp:344
bool is_touching_an_obstacle() const
Definition line_following_infrared_sonar.cpp:347
CHRONO_DiffDriveRobot & robot()
Definition line_following_infrared_sonar.cpp:349
Point position() const
Definition line_following_infrared_sonar.cpp:345
void show_floor(const std::string &texture)
Definition line_following_infrared_sonar.cpp:337
real_t heading() const
Definition line_following_infrared_sonar.cpp:346
real_t ir_ahead() const
Definition line_following_infrared_sonar.cpp:354
void step(const Command &command)
Definition line_following_infrared_sonar.cpp:324
World(const FloorImage &floor)
Definition line_following_infrared_sonar.cpp:283
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
const std::string ROBOTS_DIR
Path to robots definitions.
Definition bitsim_consts.h:42
void add_floor_texture(chrono::ChBody &ground, real_t width, real_t height, real_t z, const std::string &texture)
Put a picture on the ground: a rectangle of width x height [m] centred on the origin of the world,...
Definition irrlicht_scene.cpp:22
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
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
void record(const std::vector< Run > &runs, const std::string &directory)
Definition cart_pole_lqr_mpc.cpp:194
std::map< std::string, std::any > command(real_t v, real_t w)
Definition diff_drive_kinematics.cpp:29
real_t error(const Pose &a, const Pose &b)
Definition ekf_slam.cpp:176
Definition line_following_infrared_sonar.cpp:55
const real_t TRACK_HALF_WIDTH
Definition line_following_infrared_sonar.cpp:84
std::string to_string(Driver::State state)
Definition line_following_infrared_sonar.cpp:258
const real_t PIVOT_RATE
Definition line_following_infrared_sonar.cpp:112
const real_t TRACK_CORNER_RADIUS
Definition line_following_infrared_sonar.cpp:85
const real_t TRACK_HALF_LENGTH
Definition line_following_infrared_sonar.cpp:83
const real_t DETOUR_SPEED
Definition line_following_infrared_sonar.cpp:111
const uchar PAPER
Definition line_following_infrared_sonar.cpp:90
const real_t LINE_WIDTH
Definition line_following_infrared_sonar.cpp:86
const uchar INK
Definition line_following_infrared_sonar.cpp:91
std::array< real_t, 2 > Point
Definition line_following_infrared_sonar.cpp:70
const real_t FLOOR_WIDTH
Definition line_following_infrared_sonar.cpp:87
const real_t PRINT_PERIOD
Definition line_following_infrared_sonar.cpp:78
int run(const Options &options)
Definition line_following_infrared_sonar.cpp:515
FloorImage draw_floor()
Definition line_following_infrared_sonar.cpp:130
const RoundedRectangle TRACK(TRACK_HALF_LENGTH, TRACK_HALF_WIDTH, TRACK_CORNER_RADIUS)
Options parse(int argc, char **argv)
Definition line_following_infrared_sonar.cpp:488
const real_t STOP_DISTANCE
Definition line_following_infrared_sonar.cpp:108
const real_t LINE_TURN_RATE
Definition line_following_infrared_sonar.cpp:103
const real_t RECORD_RATE
Definition line_following_infrared_sonar.cpp:80
const InfraredLineFollower::Parameters FOLLOW_LINE
Definition line_following_infrared_sonar.cpp:145
const real_t CRUISE_SPEED
Definition line_following_infrared_sonar.cpp:102
const std::vector< Point > OBSTACLES
Definition line_following_infrared_sonar.cpp:94
const int CAMERA_HEIGHT
Definition line_following_infrared_sonar.cpp:119
const std::string WINDOW_TITLE
Definition line_following_infrared_sonar.cpp:73
const real_t TIME_LIMIT
Definition line_following_infrared_sonar.cpp:77
const real_t TURN_AWAY_ANGLE
Definition line_following_infrared_sonar.cpp:109
const real_t RENDER_RATE
Definition line_following_infrared_sonar.cpp:79
const int CAMERA_WIDTH
Definition line_following_infrared_sonar.cpp:118
const real_t METRES_PER_PIXEL
Definition line_following_infrared_sonar.cpp:89
const real_t SEARCH_TURN_RATE
Definition line_following_infrared_sonar.cpp:104
bitsim::control::DiffDriveCommand Command
Definition line_following_infrared_sonar.cpp:69
const std::string ROBOT_FILE
Definition line_following_infrared_sonar.cpp:72
const real_t OBSTACLE_HEIGHT
Definition line_following_infrared_sonar.cpp:96
const real_t OBSTACLE_SIZE
Definition line_following_infrared_sonar.cpp:95
const real_t DETOUR_RADIUS
Definition line_following_infrared_sonar.cpp:110
const chrono::ChVector3d CAMERA_POSITION
Definition line_following_infrared_sonar.cpp:115
const real_t CAMERA_FOV
Definition line_following_infrared_sonar.cpp:117
const real_t PI
Definition line_following_infrared_sonar.cpp:75
const real_t LOST_TIME
Definition line_following_infrared_sonar.cpp:105
const real_t CAMERA_TILT
Definition line_following_infrared_sonar.cpp:116
const Point START
Definition line_following_infrared_sonar.cpp:99
const real_t FLOOR_HEIGHT
Definition line_following_infrared_sonar.cpp:88
const real_t STEP_SIZE
Definition line_following_infrared_sonar.cpp:76
frame(fig)
Definition multi_agent_gif.py:29
End lap(uint_t run)
Definition parallel_monte_carlo.cpp:57
What a differential drive robot is told to do: drive at v [m/s] and turn at omega [rad/s],...
Definition infrared_line_follower.h:22
Definition line_following_infrared_sonar.cpp:483
bool render
Definition line_following_infrared_sonar.cpp:484
std::string record
Definition line_following_infrared_sonar.cpp:485