Designing and Programming a DIY Mobile Robot from Scratch
local graph
Chapter 12 — Designing and Programming a DIY Mobile Robot from Scratch
Section titled “Chapter 12 — Designing and Programming a DIY Mobile Robot from Scratch”In previous chapters, we explored how to install and configure ROS 2 packages to implement autonomous navigation, localization, and mapping for a simulated robot. In this chapter, we will focus on building a simple and affordable differential drive robot and equipping it with navigation capabilities.
To follow along with this chapter, you will need some hardware components. However, the programs and configurations provided here can be slightly adapted to work with any DIY mobile platform. The goal of this chapter is to guide you through configuring the complete navigation pipeline—from low-level motor control to localization and path planning.
We will cover the following topics in this chapter:
- Understanding the DIY mobile robot
- Understanding the electronic connection
- Programming and configuring the DIY robot
- Further improvements
Technical requirements
Section titled “Technical requirements”To follow this chapter, you should have the following hardware components:
- Raspberry Pi 3 B: A small single-board computer integrating a standard computer with a series of digital pins that can be used to control electronic components. A microSD used as the main hard drive is still needed.
- Robot frame: The main chassis of the robot, composed of two spots for active motors (the differential drive actuation) and a passive wheel.
- A 2D USB LiDAR: The sensor used to implement the autonomous navigation of the robot. In this chapter, we will use an LD20 LiDAR.
- Two DC TT motors: Direct current (DC) motors are cheap and easy to find in different online shops.
- An L298N controller: This board is used to control the motors.
- A board that converts (steps down) the higher voltage input signal to a lower 5V power that can be used for powering the Raspberry Pi.
- A battery pack: The current source to power the entire system.
The reference materials for this chapter can be found in the Chapter12 folder of the following GitHub repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter12.
Understanding the DIY mobile robot
Section titled “Understanding the DIY mobile robot”The objective of this section is to introduce the basic components that are useful for building a tiny mobile robot. Let’s start by discussing the hardware of the robot, which must be properly connected to ensure the control of the wheels and the sensors. The main brain of the robot is the onboard computer, the Raspberry Pi. The Raspberry Pi [1] is a widely popular board for prototyping and cost-effective system development. Its appeal lies not only in its affordability, compact size, and versatility but also in its general-purpose input/output (GPIO) pins, which enable direct interaction with external devices such as sensors, motors, LEDs, and more.
By leveraging the Raspberry Pi’s built-in GPIO pins, there’s no need for an additional microcontroller (such as an Arduino) to manage the robot’s actuators. Numerous similar robotics platforms have been built using this approach, with many project examples available online, such as PiCar-X [2] – a smart robot car based on Raspberry Pi.
It uses two independently controlled wheels for differential drive motion, or the lidarbot [3], which relies on the same hardware used in this chapter. Depending on your budget, you can choose from various Raspberry Pi models. For example, if you’re on a low budget (20), you can choose the Raspberry Pi Pico (6) for microcontroller projects or the Raspberry Pi Zero 2 W (~35–40) is great for general projects, while the Raspberry Pi 4 (2GB) (80–100) is ideal for AI and robotics, while the Raspberry Pi 5 (4GB/8GB) (120) provides high performance for demanding applications.
In this book, we use the Raspberry Pi 3 B. Although this model is relatively old, it is sufficient to equip the robot with navigation capabilities and is cheaper with respect to the newer models. Here are some features of this board:
- The Raspberry Pi features a Broadcom BCM2837 Quad-Core ARM Cortex-A53 processor running at 1.2 GHz and 1 GB of LPDDR2 SDRAM.
- It includes 802.11n Wi-Fi (2.4 GHz) and Bluetooth 4.1 (BLE) for wireless connectivity.
- A 40-pin GPIO header is available for hardware interfacing.
- Ports include four USB 2.0, full-size HDMI output, and a 3.5 mm audio/composite video jack.
- Storage is provided via a microSD card slot for the operating system and data.
- The recommended power supply is a 5V/2.5A input via micro USB.
Let’s now discuss how to install and configure the Linux environment and ROS 2 for the companion computer.
Installing Linux on the Raspberry Pi
Section titled “Installing Linux on the Raspberry Pi”The Raspberry Pi’s hard drive is a microSD card, so selecting a card with high read/write performance is essential to enhance the Pi’s computational speed. In this example, we use a 64 GB SanDisk Extreme Pro microSDXC card. To set up the Raspberry Pi for the first time, you will need a keyboard and a monitor for the initial configuration, as well as a power supply. The board is powered via a micro-USB cable, so you can use a mobile phone charger or a USB port from a computer. The first step is to install the operating system on the Raspberry Pi’s microSD card. Since we are using ROS 2 Jazzy, Ubuntu 24.04 must be installed on the board. To optimize performance and reduce unnecessary overhead, we will use the server version of Ubuntu, which is designed for server environments.
This version does not include a graphical user interface (GUI), focusing instead on performance and stability for services such as web servers and databases. To install Ubuntu on the Raspberry Pi’s microSD card, use the rpi-imager program. Connect the microSD card to another computer running Ubuntu Linux (you’ll need a microSD card adapter) and install rpi-imager with the following command:
sudo apt-get install rpi-imagerAfter installing rpi-imager, start it with the following command:
rpi-imagerThe main window of the program will now open, as shown in Figure 12.1.

Figure 12.1: The rpi-imager main window
Figure 12.1: The rpi-imager main window
From the main window of rpi-imager, you can choose the target device, that is, the model of the Raspberry Pi you are using, the storage device (the microSD card), and the operating system to install. Here, you can navigate through the following entries:
Other General-Purpose OS -> Ubuntu -> Ubuntu Server 24.04
Before starting the installation process, the program will ask you whether you want to set some advanced options. This step is useful to simplify the usage of the Raspberry Pi after the installation of the system. Here is the setup:
- First, as shown in Figure 12.2, you can set the login data (username and password).
- Then, add a WiFi network for remote access to the board. By default, your PC’s WiFi network (if connected) is already set up. However, you can configure a custom network by following the panel.
- Finally, in the SERVICES tab, you must enable SSH authentication using a username and password.

Figure 12.2: The rpi-imager advanced options
Figure 12.2: The rpi-imager advanced options
After the installation process is completed, insert the SD into the Raspberry Pi, connect the keyboard and the monitor, and finally, start the board with its power supply.
Configuring the Raspberry Pi
Section titled “Configuring the Raspberry Pi”Using the keyboard, you can configure the Raspberry Pi to be an external computer controlling our robot. Let’s start installing ROS 2 on this device. Also, in this case, we don’t need all the packages for the complete installation of ROS 2. For this reason, we can install the base version of ROS 2. The steps for installing ROS are the same as described in Chapter 2. You can also find these steps in [2]. Remember that in the last step, you should install the base version of ROS 2 using the following command:
sudo apt install ros-jazzy-ros-baseYou can source the ROS 2 system before creating a new workspace and compiling it. Remember that you can use the .bashrc file to automatically load the workspace at each boot of the system.
Once ROS 2 is installed and configured, you can start using the Raspberry Pi remotely, even when it is mounted on the mobile robot and not directly connected to a monitor and keyboard.
Using the Raspberry Pi remotely
Section titled “Using the Raspberry Pi remotely”In the final version of our robot, interaction is streamlined through ROS 2, enabling you to visualize its position, view the generated map, or issue position commands. However, there may be instances where you need direct access to the robot’s onboard computer for debugging or manually starting specific programs. Since the computer is physically mounted on the robot, using a keyboard and external screen is impractical. To overcome this, we use the Secure Shell (SSH) protocol—a secure network protocol that allows remote login and command execution over an unsecured network. SSH ensures encryption, data integrity, and authentication, making it a reliable way to manage servers and devices remotely. To connect to the robot’s computer, you need an SSH client, which is available on most Linux and Windows systems. Notice that to establish a connection between your PC and the robot, you need to install two components:
- Client on your PC: This is the software that you will use to interact with the robot.
- Server on the robot: This is the software running on the robot that allows it to accept commands from the client.
To install the client and the server, respectively, use the following commands:
sudo apt-get install openssh-serverSudo apt-get install openssh-clientIf you have the robot’s IP address (e.g., the Raspberry Pi’s IP) and the username of the remote device (in this case, ubuntu), you can connect using the following command:
ssh -l ubuntu <IP_RASPBERRY>After running this command, you will be prompted to enter the password for the remote device. Since SSH password authentication is enabled, entering the correct password will log you into the robot’s computer. However, the simple SSH connection has a problem. If the computer where the connection has been opened loses its connection, all the programs started remotely are interrupted. In addition, you could start the desired programs on the robot before closing the remote connection and wait for it to start operating. For this reason, tmux can be used. tmux is a terminal multiplexer that allows you to manage multiple terminal sessions from a single window, enabling efficient multitasking in a command-line environment. It lets you split your terminal into panes, switch between multiple sessions, and run processes persistently, even after disconnecting from a remote server. You can create a session, detach it to keep processes running in the background, and reattach it later. Basic commands include tmux to start a session and tmux attach to reconnect to an existing session.
You can handle the different panes and sessions using shortcuts. Learning its syntax is not very easy, so we suggest checking a cheat sheet here [4]. However, to start using tmux, you should use the following steps:
- First, log in to your remote server:
ssh user@remote_host
- Install and start
tmux:sudo apt install tmuxtmux new -s my_session - You can work inside
tmuxto run commands or tasks. Later, you can disconnect from the remote server. If you need to log back in to eventually check the output of your programs, you can use the following command:tmux attach -t my_session
tmux is a very interesting tool to handle remote machines without depending on the local connection. Now, the Raspberry Pi is ready to be used as the brain of our robot.
Advanced configuration of the Raspberry Pi
Section titled “Advanced configuration of the Raspberry Pi”The Raspberry Pi is now ready to be used. However, two additional configuration steps could be useful:
- First, an additional WiFi can be configured in case you want to connect to another network. To do this, you can use the
netplanprogram. A proper network configuration file is placed in the/etc/netplandirectory (called50-cloud-init.yaml). Here, you must add the new WiFi network and its password to the list of access points. - Another useful tip is to increase the swap of the board since the 3b model has only 1 GB of RAM. This can be done using the
dphys-swapfileprogram:- Let’s install it with the following command:
sudo apt install dphys-swapfile
- Edit the configuration file:
sudo nano /etc/dphys-swapfile- Search the following line and change it with the desired size:
CONF_SWAPSIZE=100- After this, you can save the file and reboot the board to have the new swap area.
- You can use the following command to be sure that the changes have been applied:
free -h
- Let’s install it with the following command:
We can now move to the rest of the hardware.
Choosing the robot frame
Section titled “Choosing the robot frame”The mobile base platform must have a differential drive actuation. For this reason, any kind of frame considering two wheels placed on the same axes and controlled by two separate motors will be suitable for this task. In our example, we simply rely on a plastic frame with the following data (see Figure 12.3):
- Base length: 22 cm
- Base width: 16 cm
- Wheel separation: 14 cm
- Wheel diameter: 6.5 cm
You can choose any kind of frame based on the shape you prefer. Of course, consider the components that must be placed on it and the presence of two active wheels. Such frames, along with the motors, can be found on webstores such as AliExpress [5] by searching for objects such as “smart robot car” or “wheeled robot frame.” Typically, these frames come equipped with the motors that will be used for the robot actuation, the passive wheel, and the tools needed to assemble it. A power button is also useful to start and stop the robot without disconnecting the power supply.

Figure 12.3: Differential drive robot frame
Figure 12.3: Differential drive robot frame
As for the power supply, any kind of source from 9 to 12 volts can be used. Let’s now discuss the electronics components and the actuators.
Mobile robot electronics and sensors
Section titled “Mobile robot electronics and sensors”As already stated, the Raspberry Pi works as the main brain of the robot, running ROS 2 to handle the system navigation and localization and acting as an interface with the operator. However, there are different devices that are needed to create your mobile robot:
- DC motors: The robot uses two TT DC gearbox motors with a 1:48 gear ratio, powered by 3–6V DC, and controlled by an L298N driver for bidirectional rotation. These basic motors lack features such as encoders or feedback, so odometry will be calculated using a LiDAR sensor, as detailed later in the chapter, in the Odometry calculation section.
- LiDAR sensor: A 2D LiDAR sensor is used to calculate the robot odometry since the motors don’t provide the odometry itself and to implement the localization and mapping functions from the ROS 2 navigation stack. We used an LD20 LiDAR provided by youyeetoo [6]. This is a chip LiDAR with a 360-degree field of view and an update rate of 6 Hz. It can be connected to the onboard computer using the USB port.
- Motor controller: The L298N motor controller is a dual H-bridge driver module used to control the speed and direction of two DC motors or one stepper motor. Acting as an interface between the Raspberry Pi and motors, it allows low-power control signals to manage high-power motor operations. Powered by 5V to 35V, it supports pulse width modulation (PWM) for speed control and digital signals for direction. The module features input pins (IN1–IN4) for direction, enable pins (ENA, ENB) for PWM speed control, output pins (OUT1–OUT4) for motor connections, and power pins for supplying motor and logic power.
- One current stepdown: If your power supply exceeds 5V, a regulator is required to power the Raspberry Pi. In this example, a 12V input source is stepped down to 5V using a DollaTek 2596S regulator. This device includes a USB port for directly powering the Raspberry Pi with a cable.
- Power supply or battery source: A 12-volt power supply can be used for configuration and testing. Once the setup is complete, switch to a battery or power bank for portability.
Let’s see how to connect the single elements in the next section.
Understanding the electronic connection
Section titled “Understanding the electronic connection”To ensure the robot operates correctly, all the components described in the previous section must be properly connected. The most complex part is connecting the Raspberry Pi pinout to the motor controller module, as shown in Figure 12.4. In Figure 12.4, you can see that the Raspberry Pi Model 3B includes several pins designated for similar purposes. First, both boards need to share a common ground. Connect the ground output of the L298N controller to pin 39 on the Raspberry Pi. Next, each motor requires three pin connections:
- Raspberry Pi PWM outputs -> ENA and ENB: These pins are used to enable motor actuation and regulate its velocity. The higher the PWM value, the faster the motor will rotate. In the diagram, we used pins 33 and 32 of the Pi.
- Raspberry Pi GPIO -> IN1 and IN2: These pins are used to regulate the rotation direction of the motor. We used pins 19 and 21 of the Raspberry Pi; setting the value of the GPIOs to
1will disable the motor rotation. Conversely, setting pin 19 to0and 21 to1enables the rotation in a clockwise direction, or counterclockwise if vice versa. - Raspberry Pi GPIO -> IN3 and IN4: These pins are used to control the rotation direction for the other motor. We used pins 24 and 26.

Figure 12.4: Raspberry Pi 3 B and L298N pinout connections
Figure 12.4: Raspberry Pi 3 B and L298N pinout connections
The remaining components can be connected easily. The power pins of L298N should be connected to the motor’s +/- input. The connection direction is not critical—if reversed, the wheels will rotate in the opposite direction. This can be corrected by adjusting the GPIO pin configuration in the control code, as explained in the next section, the Programming and configuring the DIY robot section. The output of the power supply must be connected with the power input of L298N and the 5V current regulator (in the case that you will use it). Of course, in this case, you must pay attention to connect the positive and negative connections correctly. The Raspberry Pi can be powered directly from the power supply or the regulator.
Finally, the LiDAR sensor can be connected to one of the USB ports available on the Raspberry board. The connection schema is shown in Figure 12.5.

Figure 12.5: Mobile robot electronic connections
Figure 12.5: Mobile robot electronic connections
Once the components are correctly connected, you can power the system. To make the operation simpler, consider using a power switch to turn the robot on and off without disconnecting the power cables. When powered on, the L298N controller will illuminate a red LED, indicating the system is functioning properly. We can now discuss how to program the robot, move the actuators, and configure the ROS 2 navigation stack.
Programming and configuring the DIY robot
Section titled “Programming and configuring the DIY robot”We are now ready to program our robot. The first thing to do to enable our robot to successfully navigate the environment autonomously is to allow access to its motors. We will develop a cpp node in the package motor_ctrl. In this node, we will use the pigpio library, which allows the control of the Raspberry Pi without the necessity of superuser privileges. From this code, based on the geometry_msgs::Twist cmd_vel message, eventually generated from the ROS 2 navigation task, the PWM and digital pins of the board can be controlled. After the interface with the motors, we can move on to the configuration of the other software used to enable the autonomous navigation of the mobile base: the odometry calculation and the ROS 2 navigation stack.
Interfacing the robot’s motors
Section titled “Interfacing the robot’s motors”Let’s discuss the motor_ctrl.cpp source:
- We must include the interface library in the
pigpiolibrary. We will start thepigpiodaemon separately, before this node. This interface is used to contact the GPIO daemon:#include <rclcpp/rclcpp.hpp>#include <pigpiod_if2.h>#include "geometry_msgs/msg/twist.hpp" - Two PWM values can be set: the maximum PWM determines the motor’s top speed, while the minimum PWM must be adjusted based on the robot’s weight. Since the motors lack encoders, the minimum value needs to be tested directly on the robot to ensure proper movement:
#define PWM_MAX 40000#define PWM_MIN 8210
- In the constructor of the class, the
pigpiolibrary is initialized. The correct initialization is checked. In this case,pi_is a file descriptor that is initialized with a number higher than 0 if the initialization is completed successfully:class MotorControl : public rclcpp::Node {public:MotorControl() : Node("motor_control_node") {pi_ = pigpio_start(nullptr, nullptr);if (pi_ < 0)rclcpp::shutdown(); - The PWM output is initialized. In particular, pins 12 and 13, used as PWMs, are set to be output, the range maximum is set (considering the maximum value of PWM defined in the code), and finally, their duty cycle is set to
0to stop the motors. Notice that good practice is to set the pin numbers (12and13here) asconstexprvariables within a namespace or static class members for clarity and maintainability. To improve the code readability, in this example, we directly set the pin numbers in the function arguments:set_mode(pi_, 12, PI_OUTPUT);set_mode(pi_, 13, PI_OUTPUT);set_PWM_range(pi_, 12, PWM_MAX);set_PWM_range(pi_, 13, PWM_MAX);set_PWM_dutycycle(pi_, 12, 0);set_PWM_dutycycle(pi_, 13, 0); - Finally, the main loop is started and the subscriber of the
cmd_veltopic is initialized:timer_ = create_wall_timer(std::chrono::milliseconds(100), std::bind(&MotorControl::ctrl_loop, this));cmd_vel_subscription_ = create_subscription<geometry_msgs::msg::Twist>("cmd_vel", 10, std::bind(&MotorControl::cmd_vel_callback, this, std::placeholders::_1)); - In the callback of the velocity command, the velocity data is saved:
void cmd_vel_callback(const geometry_msgs::msg::Twist::SharedPtr msg) {cmd_vel_ = *msg;}
- In the main loop, the first operation is to calculate the velocity associated with the single wheels of the platform based on the dimensions of the same—the wheel distances (0.14 cm) and their diameter (0.325 cm):
void ctrl_loop() {double v_left, v_right;calculate_wheel_velocities(cmd_vel_.linear.x, cmd_vel_.angular.z, 0.325, 0.14, v_left, v_right);
- The desired PWM values to actuate the robot must be calculated. Due to the lack of encoders of the motors, this is only an approximation. The pins associated with the left and right motors and their rotation direction are used to enable the correct rotation direction:
int pwm_m0 = calculate_pwm(v_left, 7, 10, 12, PWM_MIN);int pwm_m1 = calculate_pwm(v_right, 8, 9, 13, PWM_MIN);set_PWM_dutycycle(pi_, 12, pwm_m0);set_PWM_dutycycle(pi_, 13, pwm_m1);}
- The following functions calculate the PWM value based on a desired velocity and set the motor’s direction. The
calculate_pwmfunction maps the absolute velocity to a PWM value within defined limits and determines the motor’s direction usingset_motor_direction. The latter sets GPIO pins to control forward, backward, or stop states based on the velocity’s sign:int calculate_pwm(double velocity, int pin_forward, int pin_backward, int pwm_pin, int pwm_min) {double abs_velocity = std::abs(velocity);int pwm_value = static_cast<int>(map_value(abs_velocity, 0.0, 3.07, pwm_min, PWM_MAX));set_motor_direction(velocity, pin_forward, pin_backward);return pwm_value;}void set_motor_direction(double velocity, int pin_forward, int pin_backward) {if (velocity > 0) {gpio_write(pi_, pin_forward, 1);gpio_write(pi_, pin_backward, 0);} else if (velocity < 0) {gpio_write(pi_, pin_forward, 0);gpio_write(pi_, pin_backward, 1);} else {gpio_write(pi_, pin_forward, 1);gpio_write(pi_, pin_backward, 1);}}
Check the CMakeLists.txt file in the book’s repository to correctly compile this node. Then, you can execute it using the following command. Remember to start the pigpio daemon the first time:
sudo pigpiodros2 run motor_ctrl motor_ctrlYou can control the robot by sending a cmd_vel message using a joypad or the RQT interface, as discussed in previous chapters. By default, other computers on the same network as the Raspberry Pi can communicate directly via topics in ROS 2. If you want to isolate communication, you can use the ROS_DOMAIN_ID environment variable, which specifies a unique domain for each application or robot. If communication is not happening automatically, you can use the ROS_STATIC_PEERS variable to specify a list of fixed peers for direct communication, bypassing the usual discovery process. For example, if the Raspberry Pi has IP 192.168.1.91 and another computer has IP 192.168.1.43, set ROS_STATIC_PEERS to 192.168.1.91 on the Raspberry Pi and to 192.168.1.43 on the other computer. We can put the variable initialization in the .bashrc file to automatically load the configuration when the system starts. For example, the list of variables for the ground computer is the following:
source ~/dev/ros2_ws/install/setup.bashexport ROS_STATIC_PEERS=192.168.1.91export ROS_DOMAIN_ID=13In this way, we can start the motor controller program sending the velocity control data from the ground computer using the operating system user interface. After testing that the motors respond correctly to the velocity command, you can continue the configuration of the robot.
Configuring the LiDAR sensor
Section titled “Configuring the LiDAR sensor”Now, we can start the sensor. For this, we can use the ldlidar_sl_ros2 package (https://github.com/PacktPublishing/Mastering-ROS-2/tree/main/Chapter12/ldlidar_sl_ros2) to interface the LiDAR sensor. After downloading the package, compile the workspace and launch it:
colcon build --symlink-installros2 launch ldlidar_sl_ros2 ld20.launch.pyIn this latter launch file, the only parameter you should adjust is port_name. This parameter specifies the USB port where the LiDAR is connected. By default, it is /dev/ttyUSB0. You can check the correct port by listing the active ports on your Raspberry Pi:
ls /dev | grep ttyThe output of the previous command may list many entries. Focus on those containing “USB” or “ACM” in their names, such as /dev/ttyUSB1 or /dev/ttyACM0. Once the sensor is started, you can check the LiDAR data published on the /scan topic. This data is published in the base_laser frame, so to visualize the scan data correctly in RViz2, ensure you set the fixed frame to base_laser.
Defining the robot model
Section titled “Defining the robot model”Since we are going to use the navigation stack, we need a robot model to describe the connection between the base frame of the robot and the overall shape of the robot. The robot frame and the components are connected as shown in Figure 12.6. Of course, the most important connection is between the lidar_frame and the base_footprint.

Figure 12.6: Mobile platform and its components
Figure 12.6: Mobile platform and its components
As discussed in Chapter 4, tools such as Fusion 360 can be used to have a precise 3D model of your robot. However, an easier and faster solution is to represent the components as basic 3D shapes. To visualize the robot model in RViz2, the launch file contained in the mobile_robot_model can be used:
ros2 launch mobile_robot_model display.launch.pyNow you can open RViz2 adding the robot model displayer. The output is shown in Figure 12.7.

Figure 12.7: Robot model shown in RViz2
Figure 12.7: Robot model shown in RViz2
This model can be used both in the odometry calculation and in the configuration of the Nav2 stack.
Odometry calculation
Section titled “Odometry calculation”As already said, the motors used to build our robot are not equipped with encoder sensors. For this reason, it is not possible to calculate the wheel odometry, which is a rough estimation of the robot’s position within a fixed frame. However, we will use odometry for the map generation and localization. We can directly use the scan data from the LiDAR to estimate the position of the robot. This approach is typically referred to as scan matching: iterative scans are compared with one another to estimate the linear and angular position of the robot. Among the different packages, rf2o_laser_odometry is particularly efficient and lightweight. You can get it from the book’s repository (https://github.com/PacktPublishing/Mastering-ROS-2/tree/main/Chapter12/rf2o_laser_odometry) and compile the workspace. You can use the default launch file contained in the package. From that file, you can set different parameters, including:
- The
scantopic name, which is the topic on which the laser scan data is published base_frame_id, which is the name of the base link used in the odometryodom_frame_id, which is the name of the fixed odometry frame
You can test the odometry calculation by starting the LiDAR sensor, the motor controller, and the rf2o_laser_odometry:
ros2 run motor_ctrl motor_ctrl ros2 launchrf2o_laser_odometry rf2o_laser_odometry.launch.pyros2 launch ldlidar_sl_ros2 ld20.launch.pyYou can test how the quality of the odometry changes the fixed frame of Rviz2 to odom while displaying the transforms (TFs). Can you see how the frame of the robot base is moving with respect to the odometry frame? If the robot frame is correctly shown and it moves coherently with the base of the robot, you can move to the next step, the configuration of the navigation stack for mapping and navigation.
Enabling autonomous navigation
Section titled “Enabling autonomous navigation”We are now ready to enable the autonomous navigation of the robot using the Nav2 stack. For a deep discussion on how to use this framework, we already discussed it in Chapter 8. In this section, we can directly use the default launch file of the navigation and mapping packages.
To recap, we need the following launch file:
- The robot model informs the packages about the TF of the system:
ros2 launch mobile_robot_model load_model.launch.py
- The LiDAR package streams the scan data:
ros2 launch ldlidar_sl_ros2 ld20.launch.py
- The odometry calculation package provides a rough estimation of the robot’s position without the use of the map:
ros2 launch rf2o_laser_odometry rf2o_laser_odometry.launch.py
- We can now start the
slamtoolbox to create the map and, at the same time, adjust the position of the robot inside the map:ros2 launch slam_toolbox online_sync_launch.py - The navigation package generates the
cmd_veldata to actuate the robot:ros2 launch nav2_bringup navigation_launch.py
If everything starts correctly, the mobile base will be displayed on a map that will be updated with the robot’s motion (see Figure 12.8). Remember that you can directly use RViz2 to request the navigation toward a new point, by selecting a 2D Nav goal from the toolbar and selecting a point on the map.

Figure 12.8: Navigation and mapping of the mobile robot
Figure 12.8: Navigation and mapping of the mobile robot
The robot’s motion is neither precise nor smooth, as expected. This is primarily because the motors lack encoders, resulting in open-loop control. The PWM signals used to drive the robot’s base simply assume a desired velocity without feedback. Consequently, the system cannot account for disturbances such as terrain irregularities or other external noise. For this reason, several improvements can be made to the platform, as discussed in the next section.
Future improvements
Section titled “Future improvements”The robot presented in this chapter, along with its software, serves as an example of what can be achieved with simple ROS 2 nodes and low-cost hardware. However, there are several improvements that can be made to enhance the robot’s performance:
- Incorporate wheel odometry for improved localization: A key improvement is using actuators with feedback and precise motion control. To achieve this, DC motors equipped with encoders should be used, allowing the robot to better estimate its position and movement. Additionally, integrating an inertial measurement unit (IMU) can improve accuracy, as wheel odometry can degrade significantly for differential-drive robots when the wheels experience slippage.
- Upgrade to a more powerful motherboard: While the Raspberry Pi 3 B is an affordable and accessible option, its performance is often insufficient for demanding applications. Newer models of the Raspberry Pi, or other compact, GPU-equipped boards such as NVIDIA Jetson devices, can significantly enhance computational capabilities. However, these advanced boards could lack GPIO access. In such cases, microcontrollers paired with ROS 2 packages, such as Micro-ROS [7], can be used to handle GPIO-related tasks.
- Add additional sensors for enhanced perception: Expanding the robot’s sensor suite can improve its understanding of the environment. Depth sensors and vision-based systems, for instance, can provide valuable data to help the robot perceive and navigate its surroundings more effectively.
While these upgrades inevitably increase the cost of the platform, it is still possible to work on software optimization to mitigate hardware limitations and achieve better performance.
Summary
Section titled “Summary”This chapter explored the process of building and programming a mobile robot platform. A mobile robot consists of hardware components that are properly connected to enable motion and control, along with computational units to process and execute tasks. In this example, we used a popular board—the Raspberry Pi—to control the robot’s motors and facilitate intelligent navigation.
The chapter began by detailing how to configure an onboard computer, including the installation of the necessary software to enable remote control of the robot. It then explained the step-by-step process of setting up a mobile platform from scratch. While this chapter focused on a cost-effective mobile platform, additional enhancements were discussed in the final section to illustrate potential improvements to the robot’s design and functionality.
In the next chapter, we will cover a fundamental aspect of software development: testing and continuous integration/continuous deployment (CI/CD). We will explore how to implement these practices using ROS 2.
References
Section titled “References”[1] https://www.raspberrypi.com/
[2] https://docs.sunfounder.com/projects/picar-x/en/latest/
[3] https://github.com/TheNoobInventor/lidarbot
[4] https://tmuxcheatsheet.com/
[5] https://www.aliexpress.com/
[6] https://wiki.youyeetoo.com/en/Lidar/LD20