|
bitsim
Model, simulate, estimate and control robots in C++
|
bitsim models the sensors of a small mobile robot. Each sensor can be simulated, so that a robot in a Chrono world senses that world, or real, a sensor on a board that sends its readings over MQTT. The application reads both the same way, so the code that drives a simulated robot drives a real one too.
This page lists the sensors bitsim supports, what each of them reads, how the simulated ones are modelled and what that model leaves out, and the messages the real ones send.
| Sensor | Measures | Values | Simulated by | Real, over | Robot file |
|---|---|---|---|---|---|
| UltrasonicSensor | distance to the nearest obstacle along its beam | 1, [m] | CHRONO_UltrasonicBackend | MQTT_UltrasonicBackend | front-sonar, rear-sonar |
| InfraredSensor | reflectance of the floor under each element | one per element, in [0, 1] | CHRONO_InfraredBackend | MQTT_InfraredBackend | line-sensor |
| IMUSensor | specific force and angular velocity | 6, [m/s²] and [rad/s] | CHRONO_IMUBackend | MQTT_IMUBackend | imu |
| DownwardCamera | an image of the floor ahead | an image | itself, from a FloorImage | front-camera | |
| camera stream | images from a real camera | an image | MJPEG_HTTPCameraBackend, MJPEG over HTTP | ||
| wheel encoders | the angle each wheel has turned | one per motor, [rad] | SIM_DCMotorBackend | MQTT_DCMotorBackend | motors |
The wheel encoders are part of the motors, not sensors of their own, and with DiffDriveOdometry they give the robot's pose; see bitsim_sensors_odometry. DiffDriveEKF fuses all of them; see bitsim_sensors_fusion.
What each needs when bitsim is built; Installing bitsim says how to build it:
| Backend | Needs |
|---|---|
| the simulated ultrasonic, infrared and IMU backends | ENABLE_CHRONO |
| the MQTT backends | ENABLE_MQTT |
| DownwardCamera, FloorImage | ENABLE_OPENCV |
| MJPEG_HTTPCameraBackend | ENABLE_OPENCV, and an OpenCV built with FFmpeg |
| SIM_DCMotorBackend, DiffDriveOdometry | nothing; a robot that the motors drive needs ENABLE_CHRONO |
| MQTT_DCMotorBackend | ENABLE_MQTT |
| DiffDriveEKF | nothing |
The examples that use them:
| Example | Sensors |
|---|---|
| A simulated ultrasonic sensor | a simulated ultrasonic sensor on its own |
| A real ultrasonic sensor over MQTT | a real ultrasonic sensor that publishes over MQTT |
| A differential drive robot with real motors | real motors on a board, whose encoders report over MQTT |
| A line following robot with a Raspberry Pi camera | the camera stream from a Raspberry Pi, and the robot's DownwardCamera |
| Following a line with infrared sensors and avoiding obstacles | the infrared elements and the ultrasonic sensor |
| Turning by the gyroscope of an IMU | the IMU, with the sensors of the line following example |
| Odometry from the wheel encoders | the wheel encoders for odometry, with the sensors of the IMU example |
| Sensor fusion with an extended Kalman filter | all of them, the camera, the infrared elements, both ultrasonic sensors, the IMU and the encoders, fused with an extended Kalman filter |
A sensor is two objects:
Every sensor type has a create(backend_type, name) that makes the backend from its name:
| Name | Backend |
|---|---|
| SIMULATION | the simulated backend. CHRONO, its old name, works too |
| MQTT | the backend for a real sensor on a board |
CHRONO_DiffDriveRobot reads its sensors from the sensors section of its robot file, robots/bitsim_diff_drive_robot.json. It attaches each one to the chassis, draws it in the Irrlicht window, enables it, and hands it back:
| Section | type | Read back with |
|---|---|---|
| front-sonar | ultrasonic-range | get_sonar |
| rear-sonar | ultrasonic-range | get_rear_sonar |
| line-sensor | infrared-array | get_line_sensor |
| imu | imu | get_imu |
| front-camera | downward-camera | get_camera |
A section is skipped if it is missing or has "enable": false. Each has a backend, a name, an update_rate in readings per second, and dimensions and color for the box that shows it. Positions are in metres from the centre of the chassis, x ahead, y to the left and z up. The settings of each sensor are below.
An ultrasonic sensor, such as an HC-SR04, sends a burst of sound and times its echo. It reads the distance to the nearest thing that reflects the sound in a cone in front of it.
Values: one, the distance [m], between min_distance and max_distance. Closer than min_distance it reads min_distance; with nothing in range, max_distance.
CHRONO_UltrasonicBackend casts rays into the Chrono world with its collision system. The sensor sits at frame_pos on its body and looks along the body's x axis turned by yaw about z: 0 ahead, 180 behind. It casts n_rays rays fanned evenly across beam_angle in the body's x-y plane, and reads the distance to the nearest hit:
\[d = \mathrm{clamp}\left(\min_{k} d_k,\ d_{\min},\ d_{\max}\right), \qquad \theta_k = \beta \left(\frac{k}{n - 1} - \frac{1}{2}\right),\ k = 0 \dots n-1 \]
where \(d_k\) is the distance along ray \(k\), at angle \(\theta_k\) from where it looks, to the first body it hits, and \(\beta\) is the beam angle. With one ray, the default, it looks straight ahead only.
| Setting | Robot file | Meaning |
|---|---|---|
| position | frame_pos (or mounted_position) | where it is on the body [m] |
| direction | yaw | where it looks, about the body's z axis from x [deg]; 0 if missing |
| range | min_distance, max_distance | what it can measure [m]; 0.02 and 4 for an HC-SR04 |
| beam | beam_angle, n_rays | the width of the cone [deg], and the rays cast across it |
| rate | update_rate | readings per second |
The robot file has two: front-sonar on the front of the chassis, and rear-sonar at [-0.27, 0, 0.05] with "yaw": 180, looking behind. Both cast 5 rays across 15 degrees, up to 4 m, 20 times a second.
What the model leaves out:
MQTT_UltrasonicBackend reads an UltrasoundMessage:
unit is m, cm or mm, and m if it is missing; the backend reads metres either way. timestamp, in UTC, is optional. Until the first message it reads max_distance. See bitsim_sensors_mqtt.
An infrared reflectance element, such as a TCRT5000, has an infrared LED and a photo transistor side by side, a few millimetres above the floor. The transistor measures how much of the LED's light the floor reflects: most of it for white paper, little for a black line. Line following robots have a row of them under their front.
Values: one per element, the reflectance, from 0 for black to 1 for white. An element whose value is below the sensor's threshold, 0.5 by default, is over something dark: is_dark.
CHRONO_InfraredBackend carries the elements on a Chrono body. The floor is a function that gives the reflectance at each point of the world, and each element reads it at the point straight below it:
\[v_i = \mathrm{clamp}\left(F(x_i, y_i),\ 0,\ 1\right), \qquad (x_i, y_i, z_i) = T_{\text{body}}\, p_i \]
where \(p_i\) is where element \(i\) is on the body and \(T_{\text{body}}\) the pose of the body. Set the floor with set_floor, or for a robot with CHRONO_DiffDriveRobot::set_floor. For a floor that is a picture, FloorImage::reflectance gives the brightness of the pixel at a point, its luma divided by 255, and white outside the picture:
| Setting | Robot file | Meaning |
|---|---|---|
| elements | elements | [[x, y, z], ...], where they are on the body, in the order of the values [m] |
| threshold | threshold | below it an element is over something dark |
| rate | update_rate | readings per second |
What the model leaves out:
MQTT_InfraredBackend reads an InfraredMessage with one value per element, in the order of elements:
The board divides each ADC reading by the reading over white paper. Values outside [0, 1] are clamped, and a message with a different number of values than the backend has elements is ignored. Until the first message every element reads 1, white. See bitsim_sensors_mqtt.
An inertial measurement unit, such as an MPU-6050, has a three axis accelerometer and a three axis gyroscope, along the axes of its board.
Values: six, along the axes of the body the IMU is on.
| Index | Value | Unit |
|---|---|---|
| 0, 1, 2 | the specific force: the acceleration minus gravity. At rest it is 9.81 up | m/s² |
| 3, 4, 5 | the angular velocity | rad/s |
acceleration and angular_velocity pick them out of the last read.
CHRONO_IMUBackend takes the motion of its body from Chrono. The IMU sits at \(r\) from the centre of the body, so it accelerates by
\[a_P = a + \alpha \times r + \omega \times (\omega \times r) \]
where \(a\) is the acceleration of the centre of the body and \(\omega\), \(\alpha\) its angular velocity and acceleration. With \(R\) the rotation from the body to the world and \(g\) the gravity of the system, it reads
\[f = R^T (a_P - g) + n_a, \qquad \omega_m = R^T \omega + b_g + n_g \]
where \(b_g\) is a fixed gyroscope bias and \(n_a\), \(n_g\) are normal noise, new for every reading, with standard deviations \(\sigma_a\) and \(\sigma_g\). The noise comes from a generator with a fixed seed, so a simulation repeats.
| Setting | Robot file | Meaning |
|---|---|---|
| position | frame_pos | where it is on the body [m]; its axes are the body's |
| \(b_g\) | gyro_bias | what the gyroscope reads when still [rad/s] |
| \(\sigma_g\) | gyro_noise | [rad/s] |
| \(\sigma_a\) | accel_noise | [m/s²] |
| seed | of the noise generator | |
| rate | update_rate | readings per second |
The robot file has values like an MPU-6050's after its factory calibration: a bias of a few mrad/s, which is a fraction of a degree a second, and a few mrad/s and 0.04 m/s² of noise at 100 readings a second. Integrated, the bias makes a heading drift by \(b_g\,t\), and the noise adds a random walk that grows with \(\sigma_g \sqrt{\Delta t\, t}\); Turning by the gyroscope of an IMU measures the bias and takes it off.
What the model leaves out:
MQTT_IMUBackend reads an IMUMessage:
in m/s² and rad/s, along the axes of the IMU, which the board should line up with the robot's. Many IMUs report in g and deg/s, so the board converts. Until the first message the backend reads zeros. See bitsim_sensors_mqtt.
An encoder on a wheel's motor counts how far the wheel turns: a disc with slots, or magnets, on the shaft, and a sensor that counts them going by. The DC gear motors of the robot have one with 660 counts a turn of the wheel, so it measures the wheel's angle in steps of \(2\pi/660\), about half a degree. On a real robot the encoder is part of the motor and its board, so in bitsim it is part of the motor too: it is not a SensorBase.
Values: DCMotor::encoder_angle, the angle of the wheel as the encoder measures it [rad], counted from where it started. Read it for each wheel:
SIM_DCMotorBackend takes the angle of the wheel from Chrono, the angle of the joint between the wheel and the chassis, and rounds it down to whole counts:
\[\theta_{enc} = \frac{2\pi}{N} \left\lfloor \frac{N \theta}{2\pi} \right\rfloor \]
with \(N\) the counts a turn, encoder_counts in the motors section of the robot file. Its speed controller measures the speed from the same counts.
What the model leaves out: it counts perfectly. A real encoder can miss counts at high speed or pick up noise as extra counts, and a cheap one has slots that are not evenly spaced.
MQTT_DCMotorBackend takes the angle from the reports of the board that drives the motors, DCArduinoBoardImpl:
The board turns its counts into the distance each wheel has rolled [m], and the backend divides by the wheel radius. The encoder angle is the angle the board last reported, counted from its first report; unlike angle(), which the backend smooths and predicts between reports for Chrono, it is not filtered. See A differential drive robot with real motors.
DiffDriveOdometry works out the pose of a differential drive robot from its encoders, by dead reckoning. Between two readings the left and right wheels turn by \(\Delta\theta_L\) and \(\Delta\theta_R\). With wheel radius \(r\) and the wheels \(L\) apart, the robot drives and turns by
\[\Delta s = \frac{r\,(\Delta\theta_L + \Delta\theta_R)}{2}, \qquad \Delta\psi = \frac{r\,(\Delta\theta_R - \Delta\theta_L)}{L} \]
and its pose moves along the heading halfway through the step:
\[x \mathrel{+}= \Delta s \cos\bar\psi, \qquad y \mathrel{+}= \Delta s \sin\bar\psi, \qquad \bar\psi = \psi + \tfrac{1}{2}\Delta\psi \]
The heading comes from the wheels, update(left, right), or from another sensor, update(left, right, heading), such as the gyroscope of the IMU above; then \(\bar\psi\) is the mean of the last two headings. Start it with reset(pose, left, right) from where the robot is placed. distance() gives the length of the path driven.
Odometry adds up small steps, so its errors never go away:
| Error | What it does |
|---|---|
| counting | each reading is up to a count short. That does not add up: the next reading counts from the true angle again |
| slip | a wheel that slips turns without moving the robot as far. Chrono makes the simulated wheels slip as real ones would; on the robot's floor, with friction 0.8 and at 0.3 m/s, they hardly do |
| wheel radius | a radius off by a percent makes every distance off by a percent, whichever the heading comes from |
| axle length | an axle length off by a percent makes every turn off by a percent, so the heading from the wheels drifts: after a full turn by \(2\pi\) times that. It is hard to know better than a percent or two, because a tyre touches the floor over its width |
A heading error is the worst, as every step after it goes a little the wrong way and the position error grows with the distance driven. A gyroscope's heading has none of the wheels' errors, so robots take their distance from the wheels and their heading from a gyroscope. Odometry from the wheel encoders runs both over a lap of 14 m:
| Odometry | Exact geometry | Axle length 2 % off |
|---|---|---|
| heading from the gyroscope | 3.0 cm off | 3.0 cm off |
| heading from the wheels | 0.7 cm off, heading 0.08 deg off | 24 cm off, heading 7.1 deg off |
With exact geometry and wheels that hardly slip, the simulation favours the wheels; with an axle length that is a little off, as on a real robot, the gyroscope wins.
What DiffDriveOdometry leaves out: it gives a pose, not how uncertain the pose is. A filter that combines odometry with other sensors needs that too; see bitsim_sensors_fusion.
DownwardCamera is a camera on a robot that looks straight down at the floor ahead of it. It is simulated only. The floor is a FloorImage: a picture centred on the world origin that covers a given width, its columns along x and its top row the side with the largest y.
Values: an image of image_width × image_height pixels of the rectangle of floor, view_length × view_width metres, centred offset metres ahead of the robot's axle. Its top row is the far edge and its first column the robot's left, as a camera facing forward and tilted down would show them. to_robot turns a pixel into metres ahead of and to the left of the robot.
The model: the pose of the robot gives an affine map from the camera's pixels to the floor's pixels, and the camera samples the picture with it. Floor outside the picture is white. So the camera has no perspective, lens distortion, exposure or motion blur, and it sees only the floor: bodies in the Chrono world do not show in it.
| Setting | Robot file | Meaning |
|---|---|---|
| offset | how far ahead of the axle centre the middle of the view is [m] | |
| view_length, view_width | the floor it sees, along and across the robot [m] | |
| image_width, image_height | the size of its image [pixels] | |
| rate | update_rate | images per second |
It is not a SensorBase: call camera_view for an image. See A line following robot with a Raspberry Pi camera.
MJPEG_HTTPCameraBackend receives the frames of a real camera as an MJPEG stream over HTTP, the multipart/x-mixed-replace response that many cameras and camera servers give, such as the Raspberry Pi server of A line following robot with a Raspberry Pi camera. A thread of its own reads the stream and keeps only the latest frame, so a slow reader never falls behind the camera. If the stream breaks, it opens it again.
| Setting | Config | Meaning |
|---|---|---|
| url | the stream, for example http://raspberrypi.local:8000/odysseus/camera | |
| timeout | the stream is alive while frames arrive at most this far apart [s] | |
| reconnect_delay | how long to wait before opening it again [s] | |
| io_timeout | give up opening it, or reading a frame, after this long [s] |
It reads the stream with OpenCV's FFmpeg backend, and an OpenCV built without FFmpeg gets no frames; can_read_streams tells. Ubuntu's libopencv-dev has FFmpeg.
Each sensor alone has its faults: odometry drifts, the line says nothing about where the robot is along it, and a sonar hears whatever is nearest. Together they can do better. DiffDriveEKF is an extended Kalman filter for the differential drive robot that uses them all. Its state is the centre of the axle, the heading and the bias of the gyroscope, \((x, y, \psi, b)\), with its covariance.
| Sensor | What the filter does with it | Call |
|---|---|---|
| encoders and gyroscope | predict: the distance from the wheels and the turn from the gyroscope less its bias, \(\Delta\psi = (g - b)\,\Delta t\) | predict(distance, gyro_z, dt) |
| infrared elements | correct: where the line is under them, line_position(), should be on the track | update_line(points, sigma) |
| downward camera | correct: where the line crosses bands of its image, line_points(), should be on the track | update_line(points, sigma) |
| ultrasonic sensors | correct: each should read the distance to the nearest wall or box of the map along its beam | update_range(sensor, distance) |
The filter knows the floor and the room from a DiffDriveMap: the track, a RoundedRectangle, and the walls and boxes, as rectangles. A line point at the robot's estimated pose has a signed distance to the track, which the filter takes the sensor to measure as 0. A range is the shortest of rays cast through the map across the beam, as the simulated sensor casts them. A reading whose innovation is too large for its covariance, \(\nu^T S^{-1} \nu\) over 9 per value, is kept out by a gate, and a sonar that hears nothing, or whose map says there is nothing in range, is not used.
The filter is built on ExtendedKalmanFilter, which predicts with a motion model and updates with any number of observation models, each with its own noise and gate; Sensor fusion over MQTT with an extended Kalman filter runs it on readings that come over MQTT. Sensor fusion with an extended Kalman filter drives a lap of the track with odometry and the filter side by side. Off the true position, at most over the lap:
| Run | Odometry | The filter |
|---|---|---|
| as it is | 3.5 cm | 2.6 cm |
| wheel radius taken 3 % too big | 13 cm | 3.1 cm |
| the same, without the sonars | 13 cm | 10 cm |
| the same, with the sonars only | 13 cm | 2.8 cm |
| the gyroscope's bias not measured first | 40 cm | 2.7 cm |
The line fixes the position across the track and the heading, the sonars the position along it, and the filter learns the gyroscope's bias as it drives, 0.0032 rad/s against the true 0.0030.
A real sensor sits on a board, an Arduino or a Raspberry Pi, that publishes each reading as JSON on a topic of its own. Each MQTT backend reads its topic through an MQTT_SensorChannel, so they all behave alike:
In a robot file, give the sensor "backend": "MQTT" and its broker and topic, then connect it:
With a broker on your computer you can stand in for the board:
Every MQTT client after the first in a program takes about 2 s to connect; that is Paho's, not bitsim's. A program with a few sensors spends some seconds starting.
| Piece | What it is |
|---|---|
| SensorManager | keeps a list of sensors; update() reads all the enabled ones |
| OdometryMessage | {"x": ..., "y": ..., "yaw": ...}, a pose estimate from a board, with an optional UTC timestamp |
| CameraMessage | a base64 JPEG image, for a camera that publishes over MQTT |
| EigenVectorMessage | a vector of numbers as [1.0, 2.0, ...] |
To add a kind of sensor, follow the three that are there: