A simulated ultrasonic sensor with the backend swapped: the readings come from a sensor on a board that publishes them over MQTT, read by MQTT_UltrasonicBackend. The program reads the sensor the same way.
What you need
- bitsim built with MQTT; see Installing bitsim;
- an MQTT broker on localhost:1883, such as Mosquitto;
- something that publishes readings on the topic ultrasound: a board with an HC-SR04, or feed.py in this example's directory, which needs Python and paho-mqtt.
The messages
Each reading is a JSON object with the distance, its unit and when it was measured:
{"distance": 0.42, "unit": "cm", "timestamp": "2026-11-19 10:00:00.000000+00:00"}
feed.py publishes one every 2 s, with the distance growing by 0.01 each time. The example prints the distance the sensor returns, and what the last message said.
Running the example
mosquitto # the broker, if none is running
./mqtt_ultrasonic_sensor
python feed.py # in another terminal
The robot of the line following examples reads its sonar through the same backend when its robot file says "backend": "MQTT"; see bitsim::sensors.
The code
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_MQTT
#include <chrono>
#include <iostream>
#include <memory>
#include <thread>
{
{
ultrasound_subscriber.connect();
auto sensor_backend =
std::make_shared<sensors::backends::MQTT_UltrasonicBackend>(ultrasound_subscriber);
sensor_backend->set_max_distance(5.0);
sensor_backend->set_sensor_units("m");
sensor.init();
while (true)
{
auto values = sensor.read_values();
std::cout << "Measured distance: " << values[0] << " in: " << sensor.sensor_units()
<< std::endl;
const auto &read_message = sensor_backend->last_value_read();
std::cout << "Distance received: " << read_message.distance << std::endl;
std::cout << "Units received: " << read_message.unit_str << std::endl;
std::cout << "Generated at: " << read_message.source_timestamp << std::endl;
std::this_thread::sleep_for(std::chrono::microseconds(200));
}
}
}
{
return 0;
}
#endif
Definition mqtt_subscriber.h:24
Class for modelling ultrasonic sensors.
Definition ultrasonic_sensor.h:21
int main()
Definition discounted_returns.cpp:19
Definition dc_motor_backend_base.h:9
Definition pytorch_linear_regression.cpp:17
void run_mqtt()
Definition mqtt_ultrasonic_sensor.cpp:18