<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jiayi Hoffman on Medium]]></title>
        <description><![CDATA[Stories by Jiayi Hoffman on Medium]]></description>
        <link>https://medium.com/@jiayi.hoffman?source=rss-7f2725a555fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LrYJ4g-_ENWNDsHE8GxHig.png</url>
            <title>Stories by Jiayi Hoffman on Medium</title>
            <link>https://medium.com/@jiayi.hoffman?source=rss-7f2725a555fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:10:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jiayi.hoffman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Upgrade LEGO Technic 42203 into a Motorized Truck]]></title>
            <link>https://medium.com/@jiayi.hoffman/upgrade-lego-technic-42203-into-a-motorized-truck-10eba244b52a?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/10eba244b52a</guid>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[robotics-technology]]></category>
            <category><![CDATA[lego]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 18:54:27 GMT</pubDate>
            <atom:updated>2026-03-06T15:37:42.449Z</atom:updated>
            <content:encoded><![CDATA[<p>Want to give your LEGO Technic 42203 a fun makeover? How about turning it into a motorized construction truck that you can remotely control using a gamepad!</p><h3><strong>Introduction</strong></h3><p>LEGO Technic 42203 is a charming construction truck with a flatbed that can carry a large load. It features doors that open to reveal the cabin&#39;s cozy interior. It’s a great choice for building a robot car. The flatbed is perfect for holding computer gear, and the flat top can be used as a lidar sensor mount. Plus, the cabin has plenty of space for a camera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJuFPew_dhoDIz0e3W3Xbw.png" /></figure><h3><strong>What makes a Motorized Car</strong></h3><p>To make a motorized car move, we need both a steering system and a drive system. The driving and steering gears I have are from the LEGO Technic 42160 Audi RS Q e-tron. They’re much bigger and more complex than the cute little construction truck!</p><p>Here is the top-down, under-the-hood view of the simple construction truck:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqIFKJTgeHUH5XDFjUZ8cQ.jpeg" /></figure><p>Here are the guts of the Audi rally car. I placed the truck’s tires next to the monster Audi rally car’s tires. How much smaller the truck’s tires are! I’ll design a new driving and steering system for the truck, reuse the motors and hub from the LEGO Audi, and keep the truck’s form factor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3TT0jv6DfLT33yRpzueTQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-khWyIEzdF-fFRKiJmP2TQ.jpeg" /></figure><h4><strong>Gear Rack with a Double Bevel Gear for Steering</strong></h4><p>After some research, I developed this steering system for the truck. It uses a 1x7 Gear Rack with a 12-tooth Double Bevel Gear. The Gear Rack has axle holes and pin holes that can be attached to connectors to form joints for movement. The Double Bevel Gear’s axle connects to the motor. Here’s a closer look at how the connectors and pins work together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzlRobHuEqyTKVp4Slgxdw.jpeg" /></figure><p>Bevel Gears are conical gears with angled, rounded teeth designed to transfer torque at 90-degree angles.</p><p>The beige-colored axles are commonly used as the motor output. They have segments shaped like “+” to lock the axle to the motor and the gearwheel, while the smooth segment allows the axle to spin in the separator with minimal friction.</p><p>Here’s a snapshot of how it looks when it’s set up on the truck. I used the same-length front beam to keep the dimensions and shape consistent, so the upgraded truck frame can still fit under the same truck head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pCwmzu4ymCIpT2fgYYLYA.jpeg" /></figure><h4><strong>Differential Gear for Propulsion</strong></h4><p>A differential is a gear mechanism that allows the left and right wheels to rotate at different speeds while still being powered by the same motor.</p><p>This is very important when a vehicle turns because the outside wheel travels a longer distance than the inside wheel. Therefore, the outside wheel must spin faster than the inside wheel. Without a differential, the wheels fight each other, and turning becomes jerky.</p><p>My LEGO Technic Differential Gear has:</p><ul><li>A round housing with five small 12-tooth Bevel Gears inside and a 28-tooth bright yellow Bevel Gear on the outside as the “lid”</li><li>One input gear in the center, which is a 14-tooth bright yellow Bevel Gear that transfers motion at a 90-degree angle</li><li>Two axle outputs for the wheels</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyeuH3F35s5eawFzLEFF-Q.jpeg" /></figure><p>In my truck, the motor sits a bit higher than the Differential’s input. To transfer the rotation downward, I vertically aligned two Spur Gears on the motor’s output shaft. A Spur Gear is a flat gear with straight teeth.</p><h4><strong>Putting All Together</strong></h4><p>Here’s the base frame for the upgraded truck! I removed the original gear set that lifts and lowers the cargo bed and used the space for the two motors and the Differential Gear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kie_lUiDIqdaIapQjtJBVg.jpeg" /></figure><p>Here is the truck’s original base frame for reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_LkqjsFBHrI-aaacjfhew.jpeg" /></figure><h3><strong>Show Time</strong></h3><p>Here is how the upgraded truck looks. You won’t notice much difference at first glance, except for the power supply in the trunk. Keeping the same look is my goal. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbRgNYmfWGJkbgr5rt-rlA.jpeg" /></figure><p>Enjoy a quick demo of the construction truck driving autonomously using a <a href="https://github.com/jiayihoffman/lego_audi_etron/blob/main/scripts/demo_drive.py">ROS2 script</a>!</p><p>For information on how to control a LEGO motorized car using a gamepad or autonomously, please check out my earlier post on <a href="https://medium.com/@jiayi.hoffman/ros2-control-of-the-lego-audi-164b4b0b9235">ROS2 Control of the LEGO Audi e-tron</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgXDgUqN7Z0k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgXDgUqN7Z0k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgXDgUqN7Z0k%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/26130496f45613f5cc1b485d11b3b993/href">https://medium.com/media/26130496f45613f5cc1b485d11b3b993/href</a></iframe><p>Cheers!</p><h3>Related Articles</h3><ul><li><a href="https://medium.com/@jiayi.hoffman/ros2-control-of-the-lego-audi-164b4b0b9235"><strong>ROS2 Control of the LEGO Audi</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c"><strong>ROS 2 Control, Robot Control the Right Way</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10eba244b52a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROS2 Control of the LEGO Audi]]></title>
            <link>https://medium.com/@jiayi.hoffman/ros2-control-of-the-lego-audi-164b4b0b9235?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/164b4b0b9235</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[lego]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[ros2]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 23:24:48 GMT</pubDate>
            <atom:updated>2026-03-06T15:38:52.595Z</atom:updated>
            <content:encoded><![CDATA[<p>My journey of building a LEGO mobile robot using ROS2 and ros2_control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yoa3CsNazXKQkrhivuZ_ww.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>After building a <a href="https://medium.com/@jiayi.hoffman/robot-auto-mapping-using-nav2-slam-toolbox-40b575433fb0">differential robot</a> using mechanical parts from <a href="https://osepp.com/mechanical-parts">OSEPP</a>, I am looking to build a more durable mobile robot with stronger motors and a more attractive look.</p><p>I started with RC cars. However, to modify an RC car for ROS2 Control, I would have to discard many of its original RC parts, which is not very economical. Besides, the modified RC car does not look good.</p><p>I grew up as a LEGO fan and am now an AFOL (Adult Fan of LEGO). LEGO is the ultimate building block. I can take the blocks and build anything I want. Thanks to LEGO® Technic™, which releases model rally cars with real motors and hubs.</p><h4><strong>LEGO® Technic™ 42160</strong></h4><p>The <a href="https://www.lego.com/en-us/product/audi-rs-q-e-tron-42160">LEGO Audi RS Q e-tron (Technic™ 42160)</a> is a model of the 2022 Audi RS Q e-tron Dakar rally car. It features many realistic details, including individual suspension on each of the car’s 4 wheels and wheel elements that reflect the full-sized Audi’s wheel design.</p><p>Like a real-world rally car, the LEGO Audi e-tron has front-wheel steering and all-wheel drive. The model car is powered by three <a href="https://www.lego.com/en-us/product/technic-large-motor-88013">Technic™ motors</a>, connected to the ports of the <a href="https://www.lego.com/en-us/product/technic-hub-88012">Technic™ Hub</a>.</p><p>The LEGO Audi e-tron can be controlled via LEGO’s Control+ iOS and Android apps, but I want to control it with ROS2 and ros2_control so it can integrate with the larger ecosystem and do more than just drive. :)</p><h3><strong>ROS2 Controlled LEGO Car</strong></h3><h4><strong>What and Why ROS2 Control</strong></h4><p>ros2_control is a robot control framework in ROS 2 that provides a hardware abstraction layer for controlling robot actuators, sensors, and hardware interfaces in a modular and efficient way.</p><p>ros2_control enhances performance and offers real-time capabilities by avoiding multiple processes that collaborate via messages and topics. Besides, it promotes standardization and modular robot control. It supports various hardware interfaces through a hardware abstraction layer and enables a seamless transition between simulation and different hardware implementations with minimal code changes.</p><p>Developers can reuse existing controllers instead of writing their own from scratch. In fact, much of the robot control logic has already been developed by others, so the pre-built ROS2 controllers can be utilized as is in most use cases.</p><p><strong>ROS2 Controllers for Wheeled Mobile Robots</strong></p><p>For wheeled mobile robots, ros2_control framework offers the following types of controllers.</p><ul><li><em>Differential Drive Controller:</em> Controller for mobile robots with a differential drive, which has two wheels, each of which is driven independently.</li><li><em>Steering Controllers</em>: <strong>Bicycle</strong> — with the front wheel(s) steerable and the traction wheel(s) at the rear. <strong>Tricycle</strong> — with a steerable front wheel and two independent traction wheels at the rear. <strong>Ackermann</strong>— with two independent steering wheels at the front and two independent traction wheels at the rear.</li><li><em>Mecanum Drive Controllers</em>: Controller for a mobile robot with four mecanum wheels, allowing the robot to move sideways, spin, and drive in any direction by controlling each wheel independently.</li></ul><p>For more information about the ROS2 Steering Controller, please see the documentation on <a href="https://control.ros.org/humble/doc/ros2_controllers/doc/mobile_robot_kinematics.html">control.ros.org</a> and <a href="https://control.ros.org/humble/doc/ros2_controllers/steering_controllers_library/doc/userdoc.html#steering-controllers-library-userdoc">steering_controllers</a>. The second article provides detailed information on the controller’s command and state interfaces, parameters, and subscribed and published topics.</p><p><strong>Bicycle Steering Controllers for LEGO Audi e-tron</strong></p><p>This LEGO Audi e-tron is a car-like robot. It has steerable front wheels and all-wheel drive. The two front wheels work together to steer the car, and all wheels provide the same traction and forward and backward motion to propel it.</p><p>This resembles the Bicycle Steering model. Therefore, the <em>bicycle steering controller </em>is used for this LEGO car, utilizing two joints, <em>virtual_rear_wheel_joint</em> and <em>virtual_front_wheel_joint</em>, to control its movement.</p><h4><strong>Architecture</strong></h4><p>Here is the architecture diagram for a ROS2-controlled LEGO car, where the Controller Manager connects the controllers and the hardware abstraction of the ros2_control framework. On the one hand, the Controller Manager manages controllers (e.g., loading, activating, deactivating, and unloading them). On the other hand, it accesses the hardware components via the Resource Manager.</p><p>The control loop is managed by the Controller Manager’s <em>update</em> method. It reads data from the hardware components, updates the outputs of all active controllers, and writes the results back to the components.</p><p>The Resource Manager loads the hardware component, manages its lifecycle, and exposes its command and state interfaces. During control loop execution, the Resource Manager’s <em>read</em> and <em>write</em> methods communicate with the hardware component.</p><p>To support the LEGO car, we need to implement the LEGO hardware component, which is the driver program for the physical LEGO car. The remaining components in the diagram are provided by the ros2_control framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzh0DBUr1RklxHa1RkMgDg.png" /></figure><h4><strong>ros2_control LEGO Hardware Component</strong></h4><p>There are three basic types of hardware components:</p><ul><li><strong>Actuator</strong>: Simple 1-DOF (Degrees of Freedom) robotic hardware, such as motors and valves. An actuator implementation is related to only one joint.</li><li><strong>System</strong>: Multi-DOF robotic hardware such as industrial robots. This component has reading and writing capabilities and can have multiple joints.</li><li><strong>Sensor</strong>: Robotic hardware used for sensing its environment.</li></ul><p>I use the <em>System</em> type for the LEGO hardware component because it has 2-DOF and uses two joints, <em>virtual_rear_wheel_joint</em> and <em>virtual_front_wheel_joint</em>, for steering and traction.</p><p><strong>Hardware Description in URDF</strong></p><p>The ros2_control framework uses the <em>&lt;ros2_control&gt;</em> tag in the robot’s URDF file to describe the components and the hardware setup. Here is my <em>ros2_control.xacro</em>:</p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;robot xmlns:xacro=&quot;http://www.ros.org/wiki/xacro&quot;&gt;<br>  &lt;xacro:macro name=&quot;carlikebot_ros2_control&quot; params=&quot;name prefix&quot;&gt;<br><br>    &lt;ros2_control name=&quot;${name}&quot; type=&quot;system&quot;&gt;<br>      &lt;hardware&gt;<br>        &lt;plugin&gt;audi_etron/CarlikeBotSystemHardware&lt;/plugin&gt;<br>        &lt;!-- LEGO Motor Control Parameters --&gt;<br>        &lt;!-- Maximum power for traction motors (0-100), default 80  --&gt;<br>        &lt;param name=&quot;max_traction_power&quot;&gt;90.0&lt;/param&gt;<br>        &lt;!-- Maximum power for traction motors (0-100), default 50  --&gt;<br>        &lt;param name=&quot;max_steering_power&quot;&gt;50.0&lt;/param&gt;<br>        &lt;!-- Maximum velocity command for scaling (rad/s) --&gt;<br>        &lt;param name=&quot;max_traction_velocity&quot;&gt;25.0&lt;/param&gt;<br>        &lt;!-- Maximum steering position for scaling (rad), default 0.4 (~22.9 degrees)<br>             Must match URDF joint limits. Turning radius at max ~0.57m (wheelbase 0.24m) --&gt;<br>        &lt;param name=&quot;max_steering_position&quot;&gt;0.4&lt;/param&gt;<br>        &lt;param name=&quot;steering_deadzone&quot;&gt;0.05&lt;/param&gt;<br>        &lt;!-- Hub name pattern to search for during BLE scan, default &quot;Technic&quot; --&gt;<br>        &lt;param name=&quot;hub_name&quot;&gt;Technic&lt;/param&gt;<br>      &lt;/hardware&gt;<br>      &lt;joint name=&quot;${prefix}virtual_front_wheel_joint&quot;&gt;<br>        &lt;command_interface name=&quot;position&quot;/&gt;<br>        &lt;state_interface name=&quot;position&quot;/&gt;<br>      &lt;/joint&gt;<br>      &lt;joint name=&quot;${prefix}virtual_rear_wheel_joint&quot;&gt;<br>        &lt;command_interface name=&quot;velocity&quot;/&gt;<br>        &lt;state_interface name=&quot;velocity&quot;/&gt;<br>        &lt;state_interface name=&quot;position&quot;/&gt;<br>      &lt;/joint&gt;<br>    &lt;/ros2_control&gt;<br><br>  &lt;/xacro:macro&gt;<br>&lt;/robot&gt;</pre><p>Among the LEGO Motor Control parameters, the <em>max_steering_power</em> limits the power sent to the steering motor. It defaults to 50% for the following reasons:</p><ol><li>Steering requires smooth, precise control, and lower power reduces jerky movements.</li><li>Lower steering power provides mechanical protection because steering components are typically more delicate; limiting power reduces stress.</li><li>Steering only turns the front wheels, which requires less torque than driving the car.</li></ol><p><strong>Hardware Component Class</strong></p><p>The hardware component is a ROS2 package written in C++ with <em>ament_cmake</em> as the build type. A helpful command for creating the package is “<em>ros2 pkg create</em>”. After creating the package, add &lt;robot_hardware_interface_name&gt;.hpp and &lt;robot_hardware_interface_name&gt;.cpp for the hardware component implementation. Mine is <em>carlikebocarlikebot_system.hpp</em> and <em>carlikebot_system.cpp</em>.</p><p>The hardware_interface class must implement LifecycleNodeInterface’s <em>on_configure</em>, <em>on_cleanup</em>, <em>on_shutdown</em>, <em>on_activate</em>, <em>on_deactivate</em>, <em>on_error</em> methods; and overriding SystemInterface’s <em>on_init</em>, <em>export_state_interfaces</em>, <em>export_command_interfaces</em>, <em>read</em>, <em>write</em>.</p><p>For my LEGO <em>CarlikeBotSystemHardware</em> class, the LEGO motor’s control parameters are initialized in the <em>on_init</em> method. The <em>on_activate</em> method connects to the LEGO Technic Hub, and the <em>on_deactivate</em> method disconnects.</p><p>Code snippet from <em>carlikebot_system.cpp</em>:</p><pre>hardware_interface::CallbackReturn CarlikeBotSystemHardware::on_activate(<br>  const rclcpp_lifecycle::State &amp; /*previous_state*/)<br>{<br>  RCLCPP_INFO(get_logger(), &quot;Activating hardware...&quot;);<br><br>  // Connect to LEGO Technic Hub<br>  RCLCPP_INFO(get_logger(), &quot;Connecting to LEGO Technic Hub...&quot;);<br>  if (!lego_motor_controller_-&gt;connect(hub_name_)) {<br>    RCLCPP_ERROR(get_logger(), &quot;Failed to connect to LEGO Technic Hub&quot;);<br>    return hardware_interface::CallbackReturn::ERROR;<br>  }<br><br>  for (auto &amp; joint : hw_interfaces_)<br>  {<br>    joint.second.state.position = 0.0;<br><br>    if (joint.first == &quot;traction&quot;)<br>    {<br>      joint.second.state.velocity = 0.0;<br>      joint.second.command.velocity = 0.0;<br>    }<br><br>    else if (joint.first == &quot;steering&quot;)<br>    {<br>      joint.second.command.position = 0.0;<br>    }<br>  }<br><br>  // Ensure all motors are stopped initially<br>  lego_motor_controller_-&gt;stop_all_motors();<br><br>  RCLCPP_INFO(get_logger(), &quot;Successfully activated!&quot;);<br><br>  return hardware_interface::CallbackReturn::SUCCESS;<br>}</pre><p>The class’s <em>write</em> method converts the traction velocity into <em>traction_power</em> and the steering position into <em>steering_power</em>, enabling forward/backward motion and steering.</p><pre>hardware_interface::return_type audi_etron::CarlikeBotSystemHardware::write(<br>  const rclcpp::Time &amp; /*time*/, const rclcpp::Duration &amp; /*period*/)<br>{<br>  // Check if motor controller is connected<br>  if (!lego_motor_controller_ || !lego_motor_controller_-&gt;is_connected()) {<br>    RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 1000, &quot;LEGO motor controller not connected&quot;);<br>    return hardware_interface::return_type::OK;<br>  }<br><br>  // Convert traction velocity command to motor power (needed to determine direction for steering)<br>  double traction_velocity = hw_interfaces_[&quot;traction&quot;].command.velocity;<br><br>  // Convert steering position command to motor power<br>  double steering_command = hw_interfaces_[&quot;steering&quot;].command.position;<br>  <br>  // Apply deadzone: if command is within deadzone threshold, force to zero to actively center steering<br>  if (std::abs(steering_command) &lt; steering_deadzone_) {<br>    steering_command = 0.0;<br>  }<br>  <br>  // Scale steering position (-max_steering_position to max_steering_position) to power (-max_steering_power to max_steering_power)<br>  double steering_power_raw = 0.0;<br>  if (max_steering_position_ &gt; 0.0) {<br>    steering_power_raw = (steering_command / max_steering_position_) * max_steering_power_;<br>  }<br>  // Clamp to valid range<br>  steering_power_raw = std::max(-max_steering_power_, std::min(max_steering_power_, steering_power_raw));<br>  int8_t steering_power = static_cast&lt;int8_t&gt;(std::round(steering_power_raw));<br>  <br>  // Negate steering only when moving backward or stationary (forward motion doesn&#39;t need negation)<br>  // When velocity &gt; 0 (forward): negate (to fix opposite direction)<br>  // When velocity &lt;= 0 (backward/stationary): don&#39;t negate (steering is already correct)<br>  int8_t steering_power_to_send = (traction_velocity &gt; 0.0) ? -steering_power : steering_power;<br>  <br>  // Send steering command to PORT_D<br>  lego_motor_controller_-&gt;set_motor_power(LegoPort::PORT_D, steering_power_to_send);<br>  // Scale velocity (-max_traction_velocity to max_traction_velocity) to power (-max_traction_power to max_traction_power)<br>  double traction_power_raw = 0.0;<br>  if (max_traction_velocity_ &gt; 0.0) {<br>    traction_power_raw = (traction_velocity / max_traction_velocity_) * max_traction_power_;<br>  }<br>  // Clamp to valid range<br>  traction_power_raw = std::max(-max_traction_power_, std::min(max_traction_power_, traction_power_raw));<br>  int8_t traction_power = static_cast&lt;int8_t&gt;(std::round(traction_power_raw));<br><br>  // Send traction commands to PORT_A and PORT_B (both wheels)<br>  lego_motor_controller_-&gt;set_motor_power(LegoPort::PORT_A, traction_power);<br>  lego_motor_controller_-&gt;set_motor_power(LegoPort::PORT_B, traction_power);<br><br><br>  return hardware_interface::return_type::OK;<br>}</pre><p>I have a separate <em>LegoMotorController</em> class that handles all communication with the <a href="https://www.lego.com/en-us/product/technic-hub-88012">Technic™ Hub</a> via the SimpleBLE library. The main methods in <em>LegoMotorController</em> are <em>set_motor_power</em>, <em>connect</em>, <em>disconnect</em>, and <em>stop_all_motors</em>. SimpleBLE is a cross-platform library for Bluetooth Low Energy (BLE) with C++ and other language support.</p><p>For more information about creating a new ros2_control hardware component, please see the documentation on <a href="https://control.ros.org/humble/doc/ros2_control/hardware_interface/doc/writing_new_hardware_component.html">control.ros.org</a>.</p><p>The source code repository for this LEGO car’s ros2_control hardware component is at <a href="https://github.com/jiayihoffman/lego_audi_etron">https://github.com/jiayihoffman/lego_audi_etron</a>.</p><p><strong>Build the project</strong></p><p>When running ROS2 robots, I prefer using a ROS2 Docker container because it provides a complete ROS2 environment with all dependencies and can run on any environment. I have a Dockerfile prepared for this project, located in the project’s <a href="https://github.com/jiayihoffman/lego_audi_etron/tree/main/docker"><em>docker</em></a> folder.</p><p>To build the Docker image:</p><pre>docker build -t lego_audi_etron -f &quot;./docker/Dockerfile&quot; .</pre><h4><strong>Let the Robot March</strong></h4><p><strong>Start the robot on the Raspberry Pi</strong></p><p>To start the robot, I start the “lego_audi_etron” Docker container. The container’s launch file loads and initializes the ROS2 hardware and the controllers.</p><p>I turn on the LEGO car’s Hub immediately after starting the Docker container. This is because the ROS2 control manager needs to connect to the Hub upon activation.</p><pre>docker run -it --rm \<br>    --network=host \<br>    --privileged \<br>    -v /var/run/dbus:/var/run/dbus \<br>    &quot;lego_audi_etron&quot;</pre><p>Explaining the “<em>docker run”</em> command:</p><ul><li><em>— privileged</em>: Required to bypass AppArmor restrictions and access D-Bus/Bluetooth hardware</li><li><em>-v /var/run/dbus:/var/run/dbus</em>: Mounts the host’s D-Bus socket so SimpleBLE can communicate with BlueZ</li></ul><p>SimpleBLE uses D-Bus to communicate with the BlueZ daemon for Bluetooth Low Energy operations</p><p>In the command line, when I see the following messages, it means the ROS2 control manager is able to activate the LEGO car via the ROS2 control hardware interface:</p><pre>[ros2_control_node-1] [INFO] [1768345118.037541315] [controller_manager.resource_manager.hardware_component.system.CarlikeBot]: Connecting to LEGO Technic Hub…<br>[ros2_control_node-1] [INFO] [1768345121.052584207] [controller_manager.resource_manager.hardware_component.system.CarlikeBot]: Found Technic Hub: Technic Hub (Address: )<br>[ros2_control_node-1] [INFO] [1768345121.052596873] [controller_manager.resource_manager.hardware_component.system.CarlikeBot]: Connecting to hub…<br>[ros2_control_node-1] [INFO] [1768345123.247685785] [controller_manager.resource_manager.hardware_component.system.CarlikeBot]: Successfully connected to LEGO Technic Hub!<br>[ros2_control_node-1] [INFO] [1768345123.498398953] [controller_manager.resource_manager.hardware_component.system.CarlikeBot]: Successfully activated!</pre><p>I then wait for the messages of the <em>bicycle_steering_controller</em> and <em>joint_state_broadcaster</em> being loaded and configured:</p><pre>[ros2_control_node-1] [INFO] [1768345123.647514626] [controller_manager]: Loading controller &#39;bicycle_steering_controller&#39;<br>[spawner-3] [INFO] [1768345123.792577584] [spawner_bicycle_steering_controller]: Loaded bicycle_steering_controller<br>[ros2_control_node-1] [INFO] [1768345123.794617367] [controller_manager]: Configuring controller &#39;bicycle_steering_controller&#39;<br>[ros2_control_node-1] [INFO] [1768345123.794807106] [bicycle_steering_controller]: bicycle odometry configure successful<br>[ros2_control_node-1] [INFO] [1768345123.803230163] [bicycle_steering_controller]: configure successful<br>[spawner-3] [INFO] [1768345124.718624417] [spawner_bicycle_steering_controller]: Configured and activated bicycle_steering_controller<br>[ros2_control_node-1] [INFO] [1768345125.248599089] [controller_manager]: Loading controller &#39;joint_state_broadcaster&#39;<br>[spawner-4] [INFO] [1768345125.515453413] [spawner_joint_state_broadcaster]: Loaded joint_state_broadcaster<br>[ros2_control_node-1] [INFO] [1768345125.516909386] [controller_manager]: Configuring controller &#39;joint_state_broadcaster&#39;<br>[ros2_control_node-1] [INFO] [1768345125.517096273] [joint_state_broadcaster]: &#39;joints&#39; or &#39;interfaces&#39; parameter is empty. All available state interfaces will be published<br>[spawner-4] [INFO] [1768345126.473333746] [spawner_joint_state_broadcaster]: Configured and activated joint_state_broadcaster</pre><p>At this point, the ros2_control robot has started successfully.</p><p><strong>Start the ROS2 Joystick</strong></p><p>To use a joystick (gamepad) to control the LEGO car, I use the ROS2 <em>teleop_twist_joy</em> package. Each gamepad has an enable button. Press it while twisting the joystick to control the robot. On the PS5, it is the “PS” button.</p><p>One important thing to note is that the <em>ROS_DOMAIN_ID</em> environment variable must be the same on the dev machine running the “teleop_twist_joy” and in the Docker container running the robot. This environment variable controls who can access the robot’s published data and which ROS2 applications can interact with one another. If your robot cannot see the commands published by the joystick, please check that the <em>ROS_DOMAIN_ID</em> is set correctly.</p><p>To start the ROS2 <em>teleop_twist_joy</em>:</p><pre>ros2 launch teleop_twist_joy teleop-launch.py joy_config:=&#39;ps3&#39; publish_stamped_twist:=true</pre><p>Here is a demo of the car driving autonomously using a <a href="https://github.com/jiayihoffman/lego_audi_etron/blob/main/scripts/demo_drive.py">ROS2 script</a>, and we visualize it in RViz.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSI8qrDnAVWQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSI8qrDnAVWQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSI8qrDnAVWQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/28f79a133317b9ce97902766b29f22e7/href">https://medium.com/media/28f79a133317b9ce97902766b29f22e7/href</a></iframe><p>Enjoy!</p><p>The source code repository for this LEGO car’s ros2_control hardware component: <a href="https://github.com/jiayihoffman/lego_audi_etron">https://github.com/jiayihoffman/lego_audi_etron</a>.</p><h3><strong>Related Articles</strong></h3><ul><li><a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c"><strong>ROS 2 Control, Robot Control the Right Way</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/upgrade-lego-technic-42203-into-a-motorized-truck-10eba244b52a"><strong>Upgrade LEGO Technic 42203 into a Motorized Truck</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564"><strong>PRLidar in ROS 2 Docker on Raspberry Pi</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/robot-auto-mapping-using-nav2-slam-toolbox-40b575433fb0"><strong>Robot Auto Mapping using Nav2 SLAM Toolbox</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=164b4b0b9235" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Control Security Robots over the Internet]]></title>
            <link>https://medium.com/@jiayi.hoffman/control-security-robots-over-the-internet-f14451b06543?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f14451b06543</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[smart-home-security]]></category>
            <category><![CDATA[security-camera]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robots]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 16:54:17 GMT</pubDate>
            <atom:updated>2026-02-16T03:45:16.747Z</atom:updated>
            <content:encoded><![CDATA[<h3>Remotely Control Security Robots over the Internet</h3><p>In robotics, the Robot Operating System (ROS) offers software libraries and tools that help developers connect motors, sensors, and other software, speeding up the development of advanced robots.</p><p>However, ROS nodes in robots communicate with each other via TCP/UDP sockets, which are not accessible outside the robot’s LAN. Rosbridge WebSocket is a communication interface that enables non-ROS applications, such as web or mobile apps, to interact with a ROS system over a WebSocket connection through standard HTTP.</p><p>To use the robot as a security robot, I need to be able to interact with it over the internet while I’m away. How can I do that securely?</p><p>In my previous post, <a href="https://medium.com/@jiayi.hoffman/live-video-streaming-of-security-robots-28ffaeceaed4">Live Video Streaming of Security Robots</a>, I explained how to stream video from the robot over the internet securely. In this article, I will discuss how to securely control the robot over the internet.</p><h3><strong>Architecture</strong></h3><p>There are three components involved in the project. In the following sections, we will provide a detailed explanation of what they are and why they are needed:</p><p>1. The <strong>robot</strong>, where the ROS framework and ROS bridge operate.</p><p>2. The <strong>cloud server</strong>, which acts as an SSH Tunnel to relay WebSocket messages from the mobile app to the robot.</p><p>3. The <strong>mobile app</strong>, such as <a href="https://medium.com/@jiayi.hoffman/droid-vision-with-built-in-joystick-and-keypad-f9652926e9a8">Droid Vision with built-in Joystick and Keypad</a>, connects to the cloud server “wss://cloud-server-domain.com/rosbridge/” and sends ROS commands in JSON format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWlIY2Pw4BikYKJ633HH0Q.png" /></figure><h4>The Robot</h4><p>Robot Operating System (ROS) runs entirely on the robot</p><ol><li>The robot exposes ROS2 topics, such as /cmd_vel, /odom, and sensor topics, on the robot’s LAN. For details on running ROS2 on a physical robot, please see my article <a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c">ROS 2 Control, Robot Control the Right Way</a>.</li></ol><pre>ros2 launch my_bot robot.launch.py</pre><p>2. The robot launches the ROS bridge server to accept ROS commands via HTTP requests</p><pre>ros2 launch rosbridge_server rosbridge_websocket_launch.xml</pre><p>At this point, if I expose the robot’s IP address, I can control it from the iOS app through the websocket URL “ws://robot-ip-address:9090”. However, I am not comfortable making my robot’s IP address public.</p><p>After exploring various options, I chose the “Reverse SSH Tunnel” method. It is similar to a Cloudflare tunnel but is self-hosted on a cloud compute instance. Since I already use a cloud instance as the media relay server for video streaming (<a href="https://medium.com/@jiayi.hoffman/live-video-streaming-of-security-robots-28ffaeceaed4">Live Video Streaming of Security Robots</a>), this approach fits well with my robot’s deployment architecture.</p><p>Here is the command I run on the robot to create a reverse SSH tunnel that opens an outbound WebSocket connection to the cloud server.</p><pre>ssh -N -R 10000:localhost:9090 user@cloud-server-ip</pre><p>Explanation of the argument “-R 10000:localhost:9090”:</p><ul><li>“-R” is reverse port forwarding. This means we open port 10000 on the cloud server and forward all traffic to port 9090 on the robot.</li><li>“localhost” refers to the robot where this “ssh” command runs.</li><li>The rosbridge only listens locally on port 9090 on the robot. It is not accessible from the outside.</li></ul><p>The SSH tunnel disappears if the robot reboots or the network drops. Therefore, I have a “stream_control.py” program that dynamically opens and closes the tunnel based on whether the user goes live on the robot.</p><h4><strong>Cloud Server</strong></h4><p>The cloud server here functions solely as a relay and is not a ROS node. For simplicity, there is no ROS component on the cloud server.</p><p>Once the Reverse SSH Tunnel is established on the robot, any traffic on the cloud server’s port 10000 is automatically forwarded to the robot’s rosbridge.</p><p>However, there are two issues:</p><ol><li>The WebSocket traffic isn’t encrypted</li><li>The firewall rule for the cloud instance includes ingress on port 10000.</li></ol><p>To improve security, I will use Nginx to terminate the TLS WebSocket connection and upgrade/forward the WebSocket frames to the rosbridge tunnel at port 10000.</p><p>Here is the corresponding Nginx configuration:</p><pre>server {<br>    listen 443 ssl;<br>    server_name cloud-server-domain.com;<br><br>    # SSL cert paths<br>    ssl_certificate ...<br>    ssl_certificate_key ...<br><br>    location /rosbridge/ {<br>        proxy_pass http://127.0.0.1:10000/;<br><br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &quot;upgrade&quot;;<br><br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br><br>        # prevents 101 switching errors<br>        proxy_read_timeout 3600;<br>        proxy_send_timeout 3600;<br>    }<br>}</pre><p>This simple configuration encrypts WebSocket traffic over the internet, with only the standard HTTPS port open on the cloud server. Messages to the URL “/cloud-server-domain.com/rosbridge” are forwarded to port 10000, which automatically tunnels to the robot’s ROS Bridge at port 9090.</p><h4><strong>Droid Vision iOS app</strong></h4><p>Now, the iOS app can connect to “wss://cloud-server-domain.com/rosbridge” to send commands to the ROS topic “/cmd_vel”, which the robot uses to control its driving speed and direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzu1w72tpPrZNSNzwlgDBQ.png" /></figure><h3><strong>Conclusion</strong></h3><p>This approach is highly secure because:</p><ul><li>The robot is never exposed to the internet.</li><li>SSH encryption secures the tunnel and WebSocket connection.</li><li>Only HTTPS port 443 is open on the cloud server.</li><li>The cloud relay can restrict what the user can do to the robot.</li></ul><p>Here is a quick summary of what each component does:</p><h4><strong>Robot</strong></h4><ul><li>Runs ROS2</li><li>Runs rosbridge on port 9090 locally</li><li>Opens an SSH reverse tunnel between the robot and the remote cloud server.</li></ul><h4><strong>Cloud Server</strong></h4><ul><li>The cloud server functions solely as a pass-through, not as a ROS node. It relays messages to the robot via the SSH tunnel.</li><li>It provides a secure WebSocket connection for the mobile app.</li></ul><h4><strong>iOS app</strong></h4><ul><li>Sends ROS commands to the robot by invoking the secure cloud server URL.</li></ul><p>Cheers!</p><h3>Related Articles</h3><ul><li><a href="https://medium.com/@jiayi.hoffman/live-video-streaming-of-security-robots-28ffaeceaed4">Live Video Streaming of Security Robots</a></li><li><a href="https://medium.com/@jiayi.hoffman/droid-vision-with-built-in-joystick-and-keypad-f9652926e9a8">Droid Vision with built-in Joystick and Keypad</a></li><li><a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c">ROS 2 Control, Robot Control the Right Way</a></li><li><a href="https://medium.com/@jiayi.hoffman/droid-vision-19dd9b2108ef">Droid Vision app</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f14451b06543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock Analyzer AI Agent]]></title>
            <link>https://medium.com/@jiayi.hoffman/stock-analyzer-ai-agent-74d7559ada58?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/74d7559ada58</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[stock-market-tips]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 21:02:04 GMT</pubDate>
            <atom:updated>2025-11-07T06:11:35.285Z</atom:updated>
            <content:encoded><![CDATA[<p>I enjoy trading stocks for long-term investing because it requires knowledge, analytical skills, and a long-term perspective. Over time, I have developed technical skills in analyzing stock charts to identify patterns, resistance and support levels, and to gauge whether the stock is becoming bearish or bullish. I also enjoy reading news and listening to tech podcasts to stay up-to-date on upcoming trends.</p><p>In addition to personal interests, in the era of AGI, wealth is predominantly generated through equity market investments.</p><h3><strong>A Stock AI Agent</strong></h3><p>That said, I don’t always have time to watch live stock charts. That makes me want to create a stock app where AI agents analyze the charts and relate them to market sentiment to give trading insights.</p><p>Additionally, in many ways, trading stocks is more of a psychological game than a numbers game. Therefore, using AI agents to recommend stock actions can be helpful during major pullbacks when everyone is scared, as well as at market peaks when everyone is greedy. AI has a much calmer mind than we humans. :)</p><p>I have a few stocks to start with, but I’d love to add more to the list as the AI agent researches and recommends new stocks in sectors that interest me.</p><h4><strong>Agent-based Architecture</strong></h4><p>Here’s a brief overview of the architecture. The benefit of agent-based design is that:</p><ol><li>It is modular, flexible, and with expert stock analyst intelligence.</li><li>This design supports the “in the loop” evaluation, enabling the Orchestrator agent to oversee and critique the output of other agents, promoting reflection—a key aspect of the agentic reasoning pattern that helps improve performance.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*XKRJeJTjXaDHLdhg39IL0Q.png" /></figure><p>Here are the responsibilities of each agent:</p><ul><li>The Orchestrator Agent initiates the flow (e.g., on schedule or event).</li><li>It instructs the Technical Analysis Agent and Sentiment Agent to analyze the stocks.</li><li>The Technical Agent contacts the Market Data Agent for stock data, and the Sentiment Agent uses the News Agent to fetch news data for the stocks.</li><li>The Orchestrator Agent combines all signals and makes a recommendation.</li><li>All insights are logged by the Logging Agent.</li></ul><p>The word “agent” is a general term here. It can refer to a large language model (LLM) or an entity that performs specific tasks. For example:</p><ul><li>The “Technical Analysis Agent” is a large language model. It calculates various technical indicators for stocks and uses reasoning to provide a technical assessment.</li><li>Conversely, the “Market Data Agent” retrieves stock data from the stock exchange.</li></ul><h4><strong>Technologies</strong></h4><p>I use ChatGPT-5 as the large language model (LLM) and LangGraph as the agent framework. The AI agent app is built with Python and Angular. The web user interface is developed entirely through Cursor, an AI-assisted coding tool.</p><p>The agent functions as a REST service with endpoints for on-demand stock analysis requests. It also runs the “watchlist” job in the background to automatically generate insightful alerts for the user.</p><h4><strong>The Stock Analyzer AI Agent</strong></h4><p>Here is the Stock Analyzer, the AI agent that offers professional stock technical insights and market sentiment analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txvQ7NIKnYYVWjgoKarawA.png" /></figure><p>In addition to “Quick Insights,” the user can also chat with the agent about specific stock topics. Unlike a generic chatbot, the agent has access to the stock’s charts and the latest news, so it can provide the user with solid data points for quick decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4GSFB7lSV3djizN8t3gLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvWg_BnDKXKyJ465USHERw.png" /></figure><h4><strong>Testimony</strong></h4><p><strong>Palantir (PLTR)</strong></p><p>Two days before Palantir’s earnings report, the Stock Analyzer recommended holding the position and not trimming it. It also noted that news headlines reinforced the technical outlook and supported a bullish run. After the earnings report, PLTR stock surged by 22%, from $154 to $188.</p><p>Then, on Friday, August 08, the Analyzer recommended that I trim slightly and take some profits because the stock was strongly overbought. One week later, the stock dropped 6% to $177. Ten days later, on August 19, PLTR sits at $157, 16% down from the price point where the Stock Analyzer recommended trimming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZBtb11_FZk9Mm1oPbM11A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOQzxpexc1yE66XuziB9CA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t37i7eG2MJbRQIRwv_wXqg.png" /></figure><p><strong>Oklo Inc. (OKLO)</strong></p><p>On September 25, the Stock Analyzer Agent recommended that I trim my OKLO position modestly at $131, as the OKLO chart indicates a loss of momentum and signals a potential distribution following the big run.</p><p>This proved to be a very helpful tip. The OKLO stock fell more than $21, closing at $110 over the next two trading days. Additionally, CNBC later reported that “<a href="https://www.cnbc.com/2025/09/25/oklo-nuclear-shares-fall-ai-data-center.html">Oklo has also seen a cluster of insider selling over the past few days</a>&quot;, which matches my AI agent’s speculation based on the chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpZegkPCEuDgO6EKVywczA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m11Ny-lHdRXYy4P7fWhz-Q.png" /></figure><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74d7559ada58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live Video Streaming of Security Robots]]></title>
            <link>https://medium.com/@jiayi.hoffman/live-video-streaming-of-security-robots-28ffaeceaed4?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/28ffaeceaed4</guid>
            <category><![CDATA[robots]]></category>
            <category><![CDATA[security-camera]]></category>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[home-security-cameras]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 17:20:06 GMT</pubDate>
            <atom:updated>2026-02-20T18:07:16.702Z</atom:updated>
            <content:encoded><![CDATA[<p>In one of my early posts, <a href="https://medium.com/@jiayi.hoffman/droid-vision-19dd9b2108ef">Droid Vision</a>, I showed how to set up a streaming server on a mobile robot using GStreamer and visualize the robot’s surroundings from my mobile device. This works well if I’m using the robot at home to record videos of pets and flowers. Both the phone and the robot are on the same network, allowing the phone to access the robot’s IP address directly.</p><p>However, to use the robot as a security camera, I am away from home, and the robot’s IP address is not visible from the phone. How can I monitor my home in real-time while I&#39;m away? Exposing the robot’s IP address poses a significant security risk and is not an option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTA9yMn3edEYHuWnO7YsfQ.jpeg" /></figure><h3><strong>Relay the Video using a Public Media Server</strong></h3><p>The solution is to use a public server to relay the video: the video stream from the robot is sent to a cloud server, which then re-publishes the stream to the mobile device. This way, the robot can stay within the private network with all the safety and security, while its video is accessible from a public media server protected by credentials and a firewall.</p><p>All video data sent to the server is in memory and passes through. Nothing is stored unless the recording is requested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*K1AWaXcWP2oOrSyFqlI2fg.png" /></figure><h4><strong>MediaMTX Media Server</strong></h4><p>A standard relay option is using an RTMP media server. RTMP is a protocol designed for streaming audio, video, and data over the internet, especially with low latency. It allows live video and audio from a source (such as a camera) to be sent to a platform (such as YouTube Live or Twitch) for viewers to watch in real time.</p><p>The RTMP media server I use is <a href="https://github.com/bluenviron/mediamtx">MediaMTX</a>, an open-source solution that supports live streaming via RTSP, HLS, and WebRTC. Therefore, the Droid Vision app can continue using RTSP, and I just need to change the RTSP URL to the public media server: “rtsp://PUBLIC_CLOUD_SERVER:8554/live/stream”.</p><p>MediaMTX is easy to run. I can run it as a Docker container or download and run its binaries. The binary download page is on <a href="https://github.com/bluenviron/mediamtx/releases">GitHub</a>.</p><p>Here’s the output from MediaMTX. I used the MediaMTX Docker container. When the robot publishes the video to the MediaMTX server, the message “[conn &lt;robot ip&gt;:34668] is publishing to path ‘live/stream’” is printed to the screen. When the Droid Vision app contacts the media server for the video stream, the message “[session &lt;session id&gt;] is reading from path ‘live/stream’” is displayed.</p><pre>% docker run --rm -it --network=host bluenviron/mediamtx:latest<br><br>025/07/07 21:02:36 INF MediaMTX v1.13.0<br>2025/07/07 21:02:36 INF configuration loaded from /mediamtx.yml<br>2025/07/07 21:02:36 INF [RTSP] listener opened on :8554 (TCP), :8000 (UDP/RTP), :8001 (UDP/RTCP)<br>2025/07/07 21:02:36 INF [RTMP] listener opened on :1935<br>2025/07/07 21:02:36 INF [HLS] listener opened on :8888<br>2025/07/07 21:02:36 INF [WebRTC] listener opened on :8889 (HTTP), :8189 (ICE/UDP)<br>2025/07/07 21:02:36 INF [SRT] listener opened on :8890 (UDP)<br>2025/07/07 21:03:01 INF [RTMP] [conn &lt;robot ip&gt;:34668] opened<br>2025/07/07 21:03:03 INF [RTMP] [conn &lt;robot ip&gt;:34668] is publishing to path &#39;live/stream&#39;, 1 track (H264)<br>2025/07/07 21:03:10 INF [RTSP] [conn &lt;mobile device ip&gt;:62634] opened<br>2025/07/07 21:03:10 INF [RTSP] [session c7b3d9d8] created by &lt;mobile device ip&gt;:62634<br>2025/07/07 21:03:11 INF [RTSP] [session c7b3d9d8] is reading from path &#39;live/stream&#39;, with UDP, 1 track (H264)</pre><h4><strong>Video Stream pushes to the Media Server</strong></h4><p>Here is the GStreamer pipeline for the robot to publish the video stream to the media server. Please replace PUBLIC_CLOUD_SERVER with your server’s IP address in the cloud.</p><pre>gst-launch-1.0 libcamerasrc ! \<br>  video/x-raw,format=YUY2,width=640,height=480,framerate=30/1 ! \<br>  videoconvert ! \<br>  queue ! \<br>  x264enc tune=zerolatency speed-preset=ultrafast bitrate=1500 ! \<br>  queue ! \<br>  flvmux streamable=true name=mux ! \<br>  queue ! \<br>  rtmpsink location=&quot;rtmp://PUBLIC_CLOUD_SERVER/live/stream&quot;</pre><p>Here is the corresponding Python code “push_rtmp.py” for the robot. Either method can publish the video stream to the RTMP server.</p><pre>import gi<br><br>gi.require_version(&#39;Gst&#39;, &#39;1.0&#39;)<br>from gi.repository import Gst, GLib<br><br>class RTMPPush:<br>    def __init__(self):<br>        Gst.init(None)<br><br>        self.rtmp_url = &quot;rtmp://PUBLIC_CLOUD_SERVER/live/stream&quot;<br><br>        self.pipeline = Gst.parse_launch(<br>            f&quot;&quot;&quot;<br>            libcamerasrc !<br>            video/x-raw,format=YUY2,width=640,height=480,key-int-max=30,framerate=30/1 !<br>            videoconvert !<br>            queue !<br>            x264enc tune=zerolatency speed-preset=ultrafast bitrate=1500 !<br>            queue !<br>            flvmux streamable=true name=mux !<br>            queue !<br>            rtmpsink location={self.rtmp_url}<br>            &quot;&quot;&quot;<br>        )<br>    def run(self):<br>        self.pipeline.set_state(Gst.State.PLAYING)<br>        loop = GLib.MainLoop()<br>        loop.run()<br><br>if __name__ == &quot;__main__&quot;:<br>    pusher = RTMPPush()<br>    pusher.run()</pre><p>RTMP is very efficient, and MediaMTX is just a relay. Additionally, the receiving pipeline on the Droid Vision app uses UDP, which is extremely fast. So, there’s no noticeable delay when using the MediaMTX server to route the video stream.</p><h4><strong>Video Stream fetched for the Droid Vision app</strong></h4><p>As mentioned earlier, we will continue to use RTSP to stream video to the mobile app. Therefore, the Droid Vision app only needs a URL update. The new URL is now: `rtsp://PUBLIC_CLOUD_SERVER:8554/live/stream`.</p><h4><strong>Protect MediaMTX with Credentials</strong></h4><p>By default, MediaMTX has no authentication — anyone who knows its RTSP/RTMP/HLS URL can push or pull. So it’s essential to protect it, especially when it runs in the public cloud.</p><p>MediaMTX has built-in user/password auth for:</p><ul><li>Publishers</li><li>Readers/viewers</li></ul><p>I configured users and passwords in the “mediamtx.yml” file. The credential applies to all paths.</p><pre># mediamtx.yml<br>paths:<br>  all_others:<br>    # protect push<br>    publishUser: mypublisher<br>    publishPass: secret123<br><br>    # protect pull<br>    readUser: myviewer<br>    readPass: view456</pre><p>To run the Docker container with the updated yaml file, I mount the local “mediamtx.yml” into the container:</p><pre>% docker run --rm -it --network=host \<br>    -v /path/to/local/config/mediamtx.yml:/mediamtx.yml \<br>    bluenviron/mediamtx:latest</pre><p>When publishing or reading the stream, I include the credentials in the URL. For example, on the robot, I change the rtmp_url of the RTMPPush class to:</p><pre>MEDIA_SERVER = os.getenv(&quot;MEDIA_SERVER&quot;)<br>MEDIA_PUBLISH_USER = os.getenv(&quot;MEDIA_PUBLISH_USER&quot;)<br>MEDIA_PUBLISH_PASS = os.getenv(&quot;MEDIA_PUBLISH_PASS&quot;)<br><br>self.rtmp_url = f&quot;rtmp://{MEDIA_SERVER}/live/stream?user={MEDIA_PUBLISH_USER}&amp;pass={MEDIA_PUBLISH_PASS}&quot;</pre><p>The Droid Vision app has been updated so users can configure the “Use Media Server” option with the media server’s username and password as separate fields. The app automatically inserts these credentials into the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SVrrWuwANvnFF4z4JzImQ.png" /></figure><p>This method of protection is straightforward but not ideal for large-scale or highly secure applications because it uses hardcoded credentials. Therefore, MediaMTX offers alternative methods that utilize external authentication. For more information, please see the MediaMTX <a href="https://github.com/bluenviron/mediamtx">product site</a>.</p><h3><strong>On-Demand Video Streaming</strong></h3><p>With a security camera, another critical feature is on-demand video streaming. Instead of streaming video continuously, the robot streams only when it detects something or when the user requests.</p><h4><strong>Media Control Server (Polling)</strong></h4><p>A quick solution is for the robot to run a small control client that periodically polls the cloud server for the streaming state, as requested by the mobile app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*yOfhJRdJoOOPV_5BxjWBsQ.png" /></figure><h4><strong>MQTT Broker (Messaging)</strong></h4><p>The second approach involves using Message Queuing Telemetry Transport (MQTT) for push notifications: set up a public cloud MQTT broker. The robot subscribes to a specific MQTT topic, while the mobile app publishes “start” or “stop” messages to that topic.</p><p>Compared to the previous solution, this method eliminates polling, allowing the robot to react instantly. It also scales well to many cameras. MQTT is widely used for smart cameras, doorbells, drones, and other devices, which is why I chose this approach for my security robot.</p><p><strong>Media Bridge Server</strong></p><p>To use messaging in the mobile app, I need to make some deployment adjustments: instead of sending start/stop commands directly from the mobile app, which would require embedding the MQTT Swift client library, I use a cloud-based bridge server. The bridge server is an HTTP server that posts start/stop messages to the MQTT broker.</p><p>This setup keeps the Droid Vision app simple — it can use HTTP requests to start and stop the robot’s streaming through the bridge server rather than sending direct messages by embedding the MQTT client library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*9yah3ZkB8Zsz71N_2te6-g.png" /></figure><p><strong>1. Install and Config the Mosquitto MQTT Broker on the Cloud Server</strong></p><p>Update packages, install, and configure Mosquitto MQTT broker:</p><pre>sudo apt update<br>sudo apt install mosquitto mosquitto-clients -y<br><br># Enable and start Mosquitto service<br>sudo systemctl enable mosquitto<br>sudo systemctl start mosquitto<br><br># add password auth<br>sudo mosquitto_passwd -c /etc/mosquitto/passwd mymqttuser<br># Enter password when prompted</pre><p>Create Mosquitto config “/etc/mosquitto/conf.d/default.conf” as the “root” user:</p><pre>allow_anonymous false<br>password_file /etc/mosquitto/passwd<br>listener 1883 0.0.0.0</pre><p>Restart Mosquitto for the config changes:</p><pre>sudo systemctl restart mosquitto</pre><p><strong>2. FastAPI Media Bridge on the Cloud Server</strong></p><p>Install FastAPI and MQTT client:</p><pre># Create virtual environment:<br>python3 -m venv venv<br>source venv/bin/activate<br><br># Install FastAPI and MQTT client<br>pip install fastapi uvicorn paho-mqtt</pre><p>Python code `bridge.py` for the media bridge server. The APIs use the “x_api_key” header for the Authentication.</p><pre>import os<br>from typing import Optional<br><br>from fastapi import FastAPI, HTTPException<br>from paho.mqtt import publish<br>import uvicorn<br><br>app = FastAPI()<br><br>MQTT_BROKER = os.getenv(&quot;MQTT_BROKER&quot;, &quot;localhost&quot;)<br>MQTT_PORT = int(os.getenv(&quot;MQTT_PORT&quot;, &quot;1883&quot;))<br>MQTT_USER = os.getenv(&quot;MQTT_USER&quot;)<br>MQTT_PASS = os.getenv(&quot;MQTT_PASS&quot;)<br>API_KEY = os.getenv(&quot;API_KEY&quot;)<br><br><br>def _publish(command: str, robot_name: str) -&gt; None:<br>    auth: Optional[dict] = None<br>    if MQTT_USER and MQTT_PASS:<br>        auth = {&quot;username&quot;: MQTT_USER, &quot;password&quot;: MQTT_PASS}<br><br>    # Use robot-specific topic: robots/{robot_name}/stream<br>    topic = f&quot;robots/{robot_name}/stream&quot;<br><br>    try:<br>        publish.single(<br>            topic,<br>            command,<br>            hostname=MQTT_BROKER,<br>            port=MQTT_PORT,<br>            auth=auth,<br>        )<br>    except Exception as exc:  # noqa: BLE001<br>        raise HTTPException(status_code=502, detail=f&quot;Failed to publish MQTT message: {exc}&quot;) from exc<br><br>def verify_api_key(x_api_key: Optional[str] = Header(None, alias=&quot;X-API-Key&quot;)) -&gt; None:<br>    &quot;&quot;&quot;Verify API key authentication.&quot;&quot;&quot;<br>    if not API_KEY:<br>        # If no API key is configured, skip authentication<br>        return<br>    <br>    if not x_api_key or x_api_key != API_KEY:<br>        raise HTTPException(<br>            status_code=401, <br>            detail=&quot;Invalid or missing API key. Include X-API-Key header.&quot;<br>        )<br><br>@app.get(&quot;/&quot;)<br>def index():<br>    return {&quot;msg&quot;: &quot;Media bridge service running!&quot;}<br><br><br>@app.post(&quot;/robots/{robot_name}/stream/start&quot;)<br>def start(robot_name: str, _: None = Depends(verify_api_key)):<br>    _publish(&quot;start&quot;, robot_name)<br>    return {&quot;msg&quot;: f&quot;Published start for robot: {robot_name}&quot;}<br><br><br>@app.post(&quot;/robots/{robot_name}/stream/stop&quot;)<br>def stop(robot_name: str, _: None = Depends(verify_api_key)):<br>    _publish(&quot;stop&quot;, robot_name)<br>    return {&quot;msg&quot;: f&quot;Published stop for robot: {robot_name}&quot;}</pre><p>Start FastAPI media bridge server in the Python virtual environment:</p><pre>uvicorn bridge:app --host 0.0.0.0 --port 8000 --reload</pre><p>For security reasons, the Media bridge must have SSL enabled. I prefer to use Nginx and generate the SSL certificate with Certbot. Nginx acts as a reverse proxy, forwarding stream commands to the FastAPI application. This way, the FastAPI port 8000 remains hidden behind the firewall, and the cloud instance exposes only the default HTTP ports, 443 and 80.</p><p><strong>3. Streaming Control on the Robot</strong></p><p>The Robot connects to the MQTT broker, waits for messages, and starts or stops GStreamer accordingly.</p><p>To begin, I install the “MQTT client” Python library on the robot.</p><pre># Create virtual environment:<br>python3 -m venv venv --system-site-packages<br>source venv/bin/activate<br><br># install MQTT client<br>pip install paho-mqtt</pre><p>Then I create “stream_control.py” that waits for messages from the “robot/stream” topic. If the message is “start”, it starts the video streaming on the robot and publishes it to the media server. If the message is “stop”, the robot stops streaming the video.</p><pre>import os<br>import shlex<br>import subprocess<br><br>import paho.mqtt.client as mqtt<br><br>MQTT_BROKER = os.getenv(&quot;MQTT_BROKER&quot;)<br>MQTT_PORT = int(os.getenv(&quot;MQTT_PORT&quot;, &quot;1883&quot;))<br>MQTT_USER = os.getenv(&quot;MQTT_USER&quot;)<br>MQTT_PASS = os.getenv(&quot;MQTT_PASS&quot;)<br>ROBOT_NAME = os.getenv(&quot;ROBOT_NAME&quot;, &quot;Robot1&quot;)<br><br># Construct robot-specific topic: robots/{robot_name}/stream<br># Note: MQTT topics can contain spaces, so we use the robot name directly<br>MQTT_TOPIC = f&quot;robots/{ROBOT_NAME}/stream&quot;<br><br>MEDIA_SERVER = os.getenv(&quot;MEDIA_SERVER&quot;)<br>MEDIA_PUBLISH_USER = os.getenv(&quot;MEDIA_PUBLISH_USER&quot;)<br>MEDIA_PUBLISH_PASS = os.getenv(&quot;MEDIA_PUBLISH_PASS&quot;)<br><br>RTMP_URL = f&quot;rtmp://{MEDIA_SERVER}/live/stream?user={MEDIA_PUBLISH_USER}&amp;pass={MEDIA_PUBLISH_PASS}&quot;<br><br>GST_PIPELINE = f&quot;&quot;&quot;<br>libcamerasrc ! \<br>  video/x-raw,format=YUY2,width=640,height=480,framerate=30/1 ! \<br>  videoconvert ! \<br>  queue ! \<br>  x264enc tune=zerolatency speed-preset=ultrafast bitrate=1500 ! \<br>  queue ! \<br>  flvmux streamable=true name=mux ! \<br>  queue ! \<br>  rtmpsink location=&quot;{RTMP_URL}&quot;<br>&quot;&quot;&quot;<br><br>gst_process = None<br><br>def on_connect(client, userdata, flags, rc):<br>    print(f&quot;Connected with result code {rc}&quot;)<br>    print(f&quot;Subscribing to topic: {MQTT_TOPIC}&quot;)<br>    client.subscribe(MQTT_TOPIC)<br><br>def on_message(client, userdata, msg):<br>    global gst_process<br>    payload = msg.payload.decode()<br>    print(f&quot;Received: {payload}&quot;)<br><br>    if payload == &quot;start&quot;:<br>        if gst_process is None:<br>            print(&quot;Starting GStreamer...&quot;)<br>            gst_process = subprocess.Popen(<br>                shlex.split(f&quot;gst-launch-1.0 {GST_PIPELINE}&quot;),<br>                stdout=subprocess.PIPE,<br>                stderr=subprocess.PIPE<br>            )<br>        else:<br>            print(&quot;Stream already running.&quot;)<br><br>    elif payload == &quot;stop&quot;:<br>        if gst_process is not None:<br>            print(&quot;Stopping GStreamer...&quot;)<br>            gst_process.terminate()<br>            gst_process = None<br>        else:<br>            print(&quot;No stream to stop.&quot;)<br><br>client = mqtt.Client()<br>if MQTT_USER:<br>    client.username_pw_set(username=MQTT_USER, password=MQTT_PASS)<br>client.on_connect = on_connect<br>client.on_message = on_message<br><br>client.connect(MQTT_BROKER, MQTT_PORT, 60)<br>client.loop_forever()</pre><p>Finally, let’s start the robot’s stream control in the Python virtual environment.</p><pre>python stream_control.py</pre><p><strong>4. Start or Stop Streaming using the Droid Vision App</strong></p><p>Last but not least, in the Droid Vision app, I configure the media server API key and tap “Go Live View” to start the streaming request on the robot. Closing the streaming view stops the video streaming from the robot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guyhfG3_nkQnBQu56CYNCw.png" /></figure><h3>All in One Picture</h3><p>Putting video relay and on-demand streaming together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd26WlspiGhoOS_4-8WRyg.png" /></figure><p>Cheers!</p><h3>Related Articles</h3><ul><li><a href="https://medium.com/@jiayi.hoffman/diy-security-camera-using-an-ai-vision-model-a832452863fd">DIY security camera using an AI vision model</a></li><li><a href="https://medium.com/@jiayi.hoffman/droid-vision-19dd9b2108ef">Droid Vision</a> app</li><li><a href="https://medium.com/@jiayi.hoffman/control-security-robots-over-the-internet-f14451b06543">Remotely Control Security Robots over the Internet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28ffaeceaed4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Robot Auto Mapping using Nav2 SLAM Toolbox]]></title>
            <link>https://medium.com/@jiayi.hoffman/robot-auto-mapping-using-nav2-slam-toolbox-40b575433fb0?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/40b575433fb0</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[slam]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[ros2]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Wed, 28 May 2025 15:47:34 GMT</pubDate>
            <atom:updated>2026-02-13T19:16:45.903Z</atom:updated>
            <content:encoded><![CDATA[<p>I am always curious about how the Roomba vacuum automatically creates a map of the floor by driving around. In this blog, I will explain how to create a floor map using a mobile robot with the Nav2 SLAM Toolbox.</p><h3><strong>Get to Know the SLAM Toolbox</strong></h3><p>The Nav2 (Navigation 2) stack is a modular system that enables autonomous navigation for mobile robots in the ROS framework. The <strong>SLAM Toolbox</strong>, which stands for Simultaneous Localization and Mapping, plays a crucial role in the navigation stack and is part of ROS Navigation 2.</p><p>The SLAM Toolbox is a 2D mapping and localization system based on LiDAR data and odometry. It is the first two steps of the Nav2 pipeline, which are:</p><ol><li><strong>Mapping</strong>: generating and publishing the map of the environment</li><li><strong>Localization</strong>: using the saved map to localize the robot in the known environment</li><li><strong>Planning</strong>: computing the path from the current pose to the goal</li><li><strong>Control</strong>: following the path using velocity commands</li><li><strong>Recovery</strong>: handling failure conditions, such as scenarios where the robot gets stuck</li></ol><h4><strong>Mapping</strong></h4><p>The SLAM Toolbox enables the robot to generate a map of an unknown environment while tracking its position on that map in real time. SLAM Toolbox builds a 2D occupancy grid map using the robot’s laser scans and motion data.</p><p>Here is the kitchen map created by my robot, R4, as it circled the kitchen using the <a href="https://medium.com/@jiayi.hoffman/droid-vision-with-built-in-joystick-and-keypad-f9652926e9a8">Droid Vision</a> app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h56UTaWvhD_l5BFu_3KleQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5HTosrSPC9A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5HTosrSPC9A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5HTosrSPC9A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/86f907c9f253ebc6c31beafcf0c7ec0a/href">https://medium.com/media/86f907c9f253ebc6c31beafcf0c7ec0a/href</a></iframe><p>The tool that displays the map is RViz, which is a 3D visualization tool within the ROS 2 framework. RViz enables users to view and interact with a robot’s state, sensor data, and environment in a 3D space. It provides a window into the robot’s world, illustrating what the robot “sees” and how it is positioned.</p><p>The generated map can be saved in RViz using the “SlamToolboxPlugin” panel. This panel contains the “save” and “serialization” options, where the “serialization” format is intended for use by the SLAM Toolbox itself, while the “save” format allows the map to be utilized by other Nav2 localization tools, such as Adaptive Monte Carlo Localization (AMCL).</p><p>Mapping is the first step of the navigation pipeline, and SLAM Toolbox plays a crucial role in map generation.</p><h4><strong>Localization</strong></h4><p>The SLAM Toolbox is also a localization system that identifies the robot’s position and orientation (pose) within its perceived world.</p><p>To explain the concept of “Localization” in ROS, we must discuss the ROS Frame and Transform.</p><p><strong>Frame</strong></p><ul><li>A <strong>frame</strong> refers to a 3D coordinate system used to define the spatial location and orientation of an entity (like a robot, sensor, or object) in space.</li><li>The <strong>odom frame</strong> is the starting point of the robot’s trajectory. As the robot moves, its pose changes in the odom frame based on odometry data.</li><li>The <strong>base_link frame </strong>is a fixed frame attached to the robot’s chassis or main body. It serves as a reference point for other robot frames, such as wheels and lidar sensors.</li></ul><p>The ROS coordinate frame follows the Right-Hand Rule, where X goes forward from the robot’s center, Y goes to the left, and Z rises upward, perpendicular to the floor.</p><p>Here are the frames of my mobile robot, as seen in RViz, with red representing the X-axis, green representing the Y-axis, and blue representing the Z-axis. Every joint defined in the robot’s URDF has a frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BAgOMugwpFXnhdwxvCQCQ.png" /></figure><p><strong>Transform Chain</strong></p><p>What is Transform in ROS?</p><ul><li><strong>Transform(TF)</strong> represents the position and orientation of a coordinate frame relative to another. It’s a fundamental concept in ROS that describes how objects and coordinate systems are positioned in 3D space, enabling systems to understand the relative positions of various components and their interactions.</li></ul><p>A typical Transform chain for mobile robots looks like this:</p><pre>map → odom → base_link → laser_frame</pre><p>Each transform has a purpose:</p><ul><li>The<strong> odom → base_link</strong> comes from the <a href="https://medium.com/@jiayi.hoffman/enhance-dc-motors-with-motor-encoders-4682c329ad8c">wheel encoder</a> or other local sensors. It tracks how far the robot has moved from its starting point. It is fast to compute, continuous, but it accumulates drift over time. To correct for odometry drift, a higher-level system like SLAM Toolbox computes the robot’s true global pose and broadcasts.</li><li>The<strong> map → odom</strong> comes from the SLAM Toolbox and provides global correction to the drifting odometry. The SLAM Toolbox estimates the robot’s pose in the global map frame based on <a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564">laser scans</a> and odometry data. It uses this information to compute a correction transform and broadcasts it as the map → odom transform. This allows the robot’s current global position to be determined as base_link in the map frame.</li></ul><p>The “map → odom” transform is essential for:</p><ol><li>RViz visualization: the robot appears in the correct position on the map.</li><li>Path planning: the global planners can compute paths from the robot’s actual location.</li><li>Localization: the robot can recognize when it returns to a previously visited location, known as loop closure.</li></ol><p>In summary, the SLAM Toolbox broadcasts the map → odom transform to anchor the robot’s local odometry in the global map frame. This corrects for drift and ensures accurate global navigation. Without this transform, Nav2 cannot correctly localize the robot or plan valid paths.</p><p>With the SLAM Toolbox for mapping and localization, the navigation server performs the remaining steps of planning, control, and recovery in the navigation pipeline.</p><h3><strong>Meet Robot R4</strong></h3><p>This is my Differential Mobile Robot featuring two independently driven wheels and two caster wheels for balance. The Differential Bot moves forward or backward by rotating both wheels in the same direction, and it can rotate in place by spinning the wheels in opposite directions.</p><p>At the top of the robot is the RPLidar, which generates the scan data. I have a blog ‘<a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564">RPLidar in ROS 2 Docker on Raspberry Pi</a>’ that details how to configure and run the Lidar nodes on a real robot. Please check that out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdnR1HcMQxiqNGLAq2OY5Q.jpeg" /></figure><h3><strong>Robot Mapping</strong></h3><p>To run the robot that generates maps, we need a ROS environment that includes the robot module, the RPLidar driver, the navigation stack, the rosbridge suite, and many other dependencies. The most straightforward approach is to use a Docker container. Docker simplifies deployment and makes the environment portable, consistent, and shareable.</p><h4><strong>A Docker Container</strong></h4><p>A Docker container is created from a Docker image, which serves as a template defining its structure and dependencies. Docker is widely used in enterprise software’s microservice architecture, but is relatively new in robotic applications. I have a blog, <a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564">RPLidar in ROS 2 Docker on Raspberry Pi</a>, which explains in detail how to use a Docker container in a robot.</p><p>The Dockerfile I prepared for my robot can be downloaded from <a href="https://github.com/jiayihoffman/jiayihoffman.github.io/blob/main/code">here</a>: Dockerfile and requirements.txt. The Docker image created from the Dockerfile includes all the necessary ROS 2 modules, Python libraries, and source code repositories. Access to the private Git repository is granted using an SSL key.</p><p>We can build the Docker image and start the Docker container using the following commands. Building the Docker image compiles the source code and sets up the bot environment. You only need to build the image once and can reuse it to start the Docker container whenever needed.</p><pre># build the docker image &quot;my_bot_image&quot;<br>docker build -t my_bot_image .<br><br># start the docker container from the image<br>docker run -it --network=host --ipc=host -v /dev:/dev \<br>    --device-cgroup-rule=&#39;c 188:* rmw&#39; \<br>    --device-cgroup-rule=&#39;c 166:* rmw&#39; \<br>    my_bot_image</pre><h4><strong>Commands to Run the Robot Mapping</strong></h4><p>I launch the robot, the PRLidar, and the SLAM toolbox in the Raspberry Pi’s Docker container.</p><p>Additionally, I start the “rosbridge_server” because I use the Droid Vision app to view and control my robot remotely from my phone. Please see the article ‘<a href="https://medium.com/@jiayi.hoffman/droid-vision-with-built-in-joystick-and-keypad-f9652926e9a8">Droid Vision with built-in Joystick and Keypad</a>’ for more information. If you prefer the traditional ROS teleop_twist_keyboard or teleop_twist_joy for remote control, feel free to use those and skip launching the rosbridge_server.</p><pre># 1. Start the robot itself<br>ros2 launch my_bot robot.launch.py<br><br># 2. Start the robot&#39;s LiDAR scan<br>ros2 launch rplidar_ros rplidar_c1_launch.py serial_port:=/dev/ttyUSB0 frame_id:=laser_frame<br><br># 3. Start the slam toolbox to create the map <br>ros2 launch slam_toolbox online_async_launch.py use_sim_time:=false<br><br># 4. Start the rosbridge_server for the Droid Vision Teleop<br>ros2 launch rosbridge_server rosbridge_websocket_launch.xml</pre><p>On the Linux development machine, I launch RViz to visualize the robot in its world.</p><pre># 1. Launch RViz<br>rviz2 -d ~/dev/dev_ws/src/my_bot/config/view_bot_map.rviz</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5HTosrSPC9A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5HTosrSPC9A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5HTosrSPC9A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/86f907c9f253ebc6c31beafcf0c7ec0a/href">https://medium.com/media/86f907c9f253ebc6c31beafcf0c7ec0a/href</a></iframe><p>Cheers! :D</p><p><strong>Part One: </strong><a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c"><strong>ROS 2 Control, Robot Control the Right Way</strong></a></p><p><strong>Part Two: </strong><a href="https://medium.com/@jiayi.hoffman/enhance-dc-motors-with-motor-encoders-4682c329ad8c"><strong>Enhancing DC Motors with Motor Encoders</strong></a></p><p><strong>Part Three: </strong><a href="https://medium.com/@jiayi.hoffman/simplify-robot-cars-using-tb6612-motor-shield-c99fea70071b"><strong>Simplify Robot Cars using TB6612 Motor Shield</strong></a></p><h3>Related Articles</h3><ul><li><a href="https://medium.com/@jiayi.hoffman/droid-vision-with-built-in-joystick-and-keypad-f9652926e9a8"><strong>Droid Vision with built-in Joystick and Keypad</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564"><strong>PRLidar in ROS 2 Docker on Raspberry Pi</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/ros2-control-of-the-lego-audi-164b4b0b9235"><strong>ROS2 Control of the LEGO Audi</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40b575433fb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Droid Vision with built-in Joystick and Keypad]]></title>
            <link>https://medium.com/@jiayi.hoffman/droid-vision-with-built-in-joystick-and-keypad-f9652926e9a8?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9652926e9a8</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[teleoperation]]></category>
            <category><![CDATA[rosbridge]]></category>
            <category><![CDATA[ros2]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Tue, 27 May 2025 00:53:19 GMT</pubDate>
            <atom:updated>2025-11-24T22:38:30.607Z</atom:updated>
            <content:encoded><![CDATA[<p>Chasing my cat and watching him run around through the lens of a mobile robot is quite fun. However, there is one drawback: it is inconvenient to hold the iPhone in one hand and the remote control in the other. What if I could integrate the remote control into the Droid Vision app, allowing me to see and control the robot using just one device, with everything consolidated in the app!</p><p>This leads to Droid Vision 2.1, free from the <a href="https://apps.apple.com/us/app/droid-vision/id6737351549">App Store</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLCufwPer-VU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FLCufwPer-VU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLCufwPer-VU%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4f1b2b8e0d3c97c67d81ed144d3dac3/href">https://medium.com/media/c4f1b2b8e0d3c97c67d81ed144d3dac3/href</a></iframe><h3><strong>ROS and Rosbridge WebSocket</strong></h3><p>To control the robot using the Droid Vision app, I utilized Rosbridge WebSocket.</p><p>In robotics, the Robot Operating System (ROS) is the standard choice for developing robot applications. It provides software libraries and tools that enable developers to connect motors, sensors, and software seamlessly, thereby accelerating the process of creating advanced robots.</p><p>Rosbridge WebSocket is a communication interface that allows non-ROS applications, such as web or mobile apps, to interact with a ROS system using JSON messages over a WebSocket connection. It is part of the rosbridge_suite and enables bidirectional communication between ROS nodes and external applications without requiring them to be ROS-native.</p><p>This is particularly beneficial for applications that need real-time interaction with a ROS system while avoiding the complexity of ROS 2 DDS networking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*mGf3XeoDceE91icjWC1lwQ.png" /></figure><h3><strong>ROS 2 Docker Container</strong></h3><p>To run ROS on a Raspberry Pi, I recommend using the ROS 2 Docker container. It simplifies dependency management, making the environment portable, consistent, and shareable.</p><p>Docker is widely used in enterprise software’s microservice architecture, where each service functions as a lightweight Docker container that can be independently deployed and upgraded. A Docker container is created from a Docker image, which serves as a template defining its structure and dependencies.</p><p>The concept of using Docker for robotic applications is relatively new. I have a detailed article about it, which is <a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564?source=your_stories_page--------------------------------------------">RPLidar in ROS 2 Docker on Raspberry Pi</a>.</p><p>The Dockerfile that I prepared for my robot can be downloaded from <a href="https://github.com/jiayihoffman/jiayihoffman.github.io/blob/main/code">here</a>: Dockerfile and requirements.txt. The Docker image created from the Dockerfile includes all the necessary ROS2 modules, Python libraries, and source code repositories. Access to the private Git repository is granted using an SSL key.</p><p>We can build the Docker image and start the Docker container using the following commands. Building the Docker image compiles the source code and creates the bot environment. You only need to build the image once and can reuse it to start the Docker container whenever needed.</p><pre># build the docker image &quot;my_bot_image&quot;<br>docker build -t my_bot_image .<br><br># start the docker container from the image<br>docker run -it --network=host --ipc=host -v /dev:/dev \<br>    --device-cgroup-rule=&#39;c 188:* rmw&#39; \<br>    --device-cgroup-rule=&#39;c 166:* rmw&#39; \<br>    my_bot_image<br><br># start the robot and rosbridge_server in the docker container<br>ros@raspi:ros2 launch my_bot robot.launch.py<br>ros@raspi:ros2 launch rosbridge_server rosbridge_websocket_launch.xml</pre><p>With that, the Rosbridge WebSocket is open on the Raspberry Pi and can be accessed from the Droid Vision app.</p><h3><strong>Droid Vision App</strong></h3><p>Using the joystick or keypad on the Droid Vision is straightforward. We just enable the “ROS2 Teleop” in the robot’s settings, and tap the “gamepad” icon once we are live viewing the robot.</p><h4><strong>Joystick Control</strong></h4><p>The “Joystick” is the default option for controlling the robot since it is easier to use than the “Keypad”.</p><p>The value of “ROS2 Topic” depends on your robot, but “/cmd_vel” is the default ROS topic for the robot’s velocity messages. My <a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c">ROS 2 Control, Robot Control the Right Way</a> blog shows how to configure the “controller_manager” in the robot’s launch file to use “cmd_vel” as the velocity command topic.</p><h4>Keypad Control</h4><p>If using the “Keypad”, we tap the key for the robot to go in the corresponding direction. To continuously send the same velocity messages, we press down the key, which sends the same message every 0.3 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2V7PuLaPudwUbpZz2cX3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_qno7JS2JZgFvgTKch-CA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0tiU2ptBrM5p_TeDNcYbg.png" /></figure><h3><strong>Meet Robot R4</strong></h3><p>This is a Differential Mobile Robot featuring two independently driven wheels and two caster wheels for balance. The Differential Bot moves forward or backward by spinning both wheels in the same direction, and it rotates in place by spinning the wheels in opposite directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdnR1HcMQxiqNGLAq2OY5Q.jpeg" /></figure><p>Here is my robot circling the kitchen. I was controlling the robot using Droid Vision’s joystick and viewing the kitchen from the robot’s onboard camera through the Droid Vision app. The robot has a pair of sports tires, and the ground is textured tile, so the ride is a little bumpy. :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLCufwPer-VU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FLCufwPer-VU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLCufwPer-VU%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4f1b2b8e0d3c97c67d81ed144d3dac3/href">https://medium.com/media/c4f1b2b8e0d3c97c67d81ed144d3dac3/href</a></iframe><h3>Related Articles</h3><ul><li><a href="https://medium.com/@jiayi.hoffman/robot-auto-mapping-using-nav2-slam-toolbox-40b575433fb0"><strong>Robot Auto Mapping using Nav2 SLAM Toolbox</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564"><strong>PRLidar in ROS 2 Docker on Raspberry Pi</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c"><strong>ROS 2 Control, Robot Control the Right Way</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/droid-vision-19dd9b2108ef"><strong>Droid Vision App</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9652926e9a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Robot Cars using TB6612 Motor Shield]]></title>
            <link>https://medium.com/@jiayi.hoffman/simplify-robot-cars-using-tb6612-motor-shield-c99fea70071b?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99fea70071b</guid>
            <category><![CDATA[shield]]></category>
            <category><![CDATA[motor]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ros2]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 05:12:55 GMT</pubDate>
            <atom:updated>2025-05-28T15:52:04.339Z</atom:updated>
            <content:encoded><![CDATA[<p>Recall from my blog <a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c">ROS 2 Control, Robot Control the Right Way</a>, that my robot uses an Arduino microcontroller. The Arduino cannot directly drive the motors because they require much more current than the Arduino can supply. Additionally, when the motors are turned off, they produce high voltages that could damage the microcontroller pins. Therefore, the Arduino employs a DC motor driver to control the motors’ speed and direction.</p><h3><strong>Motor Driver</strong></h3><p>I select motor drivers based on the motor&#39;s <a href="https://osepp.com/downloads/pdf/DC-Motor-Spec.pdf">specifications</a>, particularly its rated voltage and current. Additionally, I also consider the motor driver’s size and mounting methods. If I build a tiny robot, I must use a tiny motor driver.</p><p>To control the motor’s direction, we commonly use a design called an “H-Bridge”, which consists of four switches (typically transistors) arranged in an “H” pattern, with the motor connected between the center points of the left and right legs. By turning on specific pairs of switches, current flows through the motor in one direction or the other, allowing it to spin forward or backward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ij-X7SH-XQkc_XVRB_RGKQ.png" /></figure><p>To control motor speed, we use PWM (Pulse Width Modulation) on the motor driver’s PWM input pin. PWM works by rapidly switching the motor’s power on and off and adjusting the duty cycle — the percentage of time the signal is HIGH versus LOW. A higher duty cycle (e.g., 80%) means the motor receives more power and spins faster, while a lower duty cycle (e.g., 30%) slows it down. In Arduino, this is done using the analogWrite function, where the value ranges from 0 (off) to 255 (full speed).</p><p>Examples of H-Bridge Motor Drivers. All of them have two channels for controlling two DC motors.</p><ul><li>L298N: supports motor voltage 5V — 35V and continuous current up to 2A.</li><li>TB6612FNG: a tiny module. It supports motor voltage 4.5V — 13.5V and continuous current up to 1.2A.</li><li>MX1508: an ideal choice for tiny motors. It supports motor voltage 2V — 10V and continuous current up to 1.5A.</li></ul><h4><strong>L298N Dual H-Bridge</strong></h4><p>The L298N is a popular dual H-bridge motor driver that can control the speed and direction of two DC motors. It operates at voltages up to 35V and can handle up to 2A per channel, making it suitable for small to medium-sized motor control applications. It is very affordable, widely available, and easy to use.</p><p>The L298N uses bipolar junction transistors (BJTs) in its H-bridge design, which are less efficient than MOSFETs, resulting in more heat and significant voltage drop. Typically, a single bipolar transistor experiences a drop of approximately 0.7 volts. When two transistors are employed simultaneously in an H-Bridge configuration, the total drop is estimated to be around 1.4 volts. Consequently, if a 9-volt supply is applied to the H-Bridge, the motor will actually receive only 7.6 volts.</p><p>Another problem I face when using the L298N is that it is bulky and requires messy wiring to connect the necessary L298N pins to the Arduino. Here are the pins that must be connected:</p><ul><li>EnableA, EnableB (connect to Arduino’s PWM pins to control the motor’s speed)</li><li>IN1, IN2, IN3, IN4 (control the motor direction)</li><li>5V logic voltage, GND</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3_JR8X6jhXyMGBOmmcoHg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rgaCbDLI7_krkzUNc5H0Q.jpeg" /></figure><h4><strong>TB6612FNG Dual H-Bridge</strong></h4><p>The voltage drop, heat generation, and bulky size led me to explore other Dural H-Bridge motor drivers.</p><p>TB6612FNG features a newer, more efficient design, utilizing MOSFETs for switching, which results in a lower voltage drop and higher efficiency. Overall, TB6612FNG is smaller, cooler, and more efficient, making it a better choice for most projects unless higher voltage tolerance is needed from L298N.</p><p>Regarding the wiring, TB6612FNG uses the same pins as L298N and can serve as a drop-in replacement for L298N.</p><p>Here are L298N and TB6612FNG side by side; TB6612FNG is less than one-fifth the size of L298N.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAUxqkTKrs2bmt4fMiDDhQ.jpeg" /></figure><h3><strong>Motor Shield</strong></h3><p>An Arduino Motor Shield is an add-on board (or “shield”) that plugs directly onto an Arduino to make it easy to control DC motors, stepper motors, and servos. It contains motor driver chips, such as the L298N or TB6612FNG, that handle the high current and voltage required by motors, which the Arduino alone cannot supply.</p><p>The shield simplifies wiring and programming by using a standard pin layout, and many shields come with Arduino libraries to make coding easier.</p><h4><strong>Meet the OSEPP TB6612 Motor Shield</strong></h4><p>The OSEPP TB6612 Motor Shield uses two TB6612FNG dual H-bridge driver chips, allowing independent control of up to four DC motors (M1–M4). All pins from the shield are already connected to the Arduino once the shield is stacked onto the Arduino board, removing eight wires from the configuration.</p><p>Here are the pictures of the updated wiring. I replaced the L298N motor driver with the TB6612 motor shield. Once I connect the motors to the motor shield using the wire clips, I don’t need any additional wires to control the motor. The four wires on the motor shield are for the motor encoders, not for the motors themselves.</p><p>The motor shield has convenient “V” and “G” rails to provide the 5V Logic Voltage and GND for the encoders and sensors. However, they are NOT directly connected to Arduino’s 5V/GND rails, so be careful when using them. More details will be discussed in the next section on how to use them correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xe_qoRwn4URBiMef44CQZw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WfZVARaxT2p6C3RwnomwA.jpeg" /></figure><h4><strong>Troubleshooting Lessons, Common Pitfalls</strong></h4><p>Once the wires are cleaned up, the next step is to update the code to make it work again. I struggled with that for a couple of days, and here are some crucial details I learned about using the TB6612 Motor Shield.</p><p><strong>Dedicated Arduino Digital Pins</strong></p><p>Unlike a standalone motor driver, the OSEPP TB6612 motor shield has a <a href="https://osepp.com/downloads/pdf/tb6612.pdf">Driver Schematic</a>, which indicates that each H-bridge connects to dedicated Arduino digital pins for direction and PWM control, with motor power supplied through a VIN terminal and routed internally to the driver chips’ VM pins. This means I need to update the Arduino sketch to use those specific pins for motor direction and PWM control.</p><p>The STBY (standby) pins are internally connected to 5V, keeping both motor drivers active by default. This design integrates neatly with Arduino UNO headers, requiring no external wiring for basic motor control.</p><p>Each type of shield has its schematic. Grok or ChatGPT are currently not aware of it and hallucinate heavily. For example, they believe the reason the code is not working with the TB6612 motor shield is that the STBY pin is not set to HIGH and insist I run a jumper wire to connect pin 10 to 5V since pin 10 is usually the STBY pin. :D</p><p><strong>PWM with One DIRECTION Input</strong></p><p>From the OSEPP example code, I learned that I only use one pin to control the direction, unlike L298N or TB6612FNG, which use two input pins for the direction. Therefore, to stop the motor, I must set PWM to 0 rather than setting the input pins to LOW.</p><p>Here is the Arduino sketch I created to test the DC motor with the OSEPP TB6612 Motor Shield:</p><pre>// Motor M1 (Motor A)<br>int enA = 11;    // PWM speed control<br>int dirA = 8;    // DIRECTION control<br><br>// Motor M2 (Motor B)<br>int enB = 3;     // PWM speed control<br>int dirB = 12;   // DIRECTION control<br><br>void setup()<br>{<br>  // Set all the motor control pins to outputs<br>  pinMode(enA, OUTPUT);<br>  pinMode(enB, OUTPUT);<br>  pinMode(dirA, OUTPUT);<br>  pinMode(dirB, OUTPUT);<br><br>  Serial.begin(9600);<br>}<br><br>// Run the motors in both directions at a fixed speed<br>void loop()<br>{<br>  // Run Motor M1 and M2 forward<br>  Serial.println(&quot;Forward&quot;);<br>  digitalWrite(dirA, HIGH);<br>  analogWrite(enA, 150); // speed 0–255<br><br>  digitalWrite(dirB, HIGH);<br>  analogWrite(enB, 150); // speed 0–255<br>  delay(2000);<br><br>  // Reverse the motor directions<br>  Serial.println(&quot;Reverse&quot;);<br>  digitalWrite(dirA, LOW);<br>  digitalWrite(dirB, LOW);<br>  delay(2000);<br><br>  // Stop the motor<br>  Serial.println(&quot;Stop motors&quot;);<br>  analogWrite(enA, 0);<br>  analogWrite(enB, 0);<br>  delay(1000);<br>}</pre><p><strong>0 Volts at M1, M2?</strong></p><p>OSEPP TB6612 Motor Shield has a toggle switch. Even if the shield’s VIN terminal is connected to a battery and the shield is powered, the motors are NOT powered until the shield’s switch is turned on. I was stuck on this and could not figure out why the motor did not spin until I noticed the switch on the shield.</p><p><strong>The Power Puzzle: VIN, VM, and the “V” and “G” Rails</strong></p><p>The motor shield includes logic rails labeled “V” and GND rails labeled “G” for powering encoders or sensors and exposes signal pins alongside them for convenient 3-pin connections. However, the pins on those rails are not directly connected to Arduino’s 5V/GND rails. They are only powered when the shield’s VIN terminal is connected to the battery and the motor shield switch is turned on. Otherwise, the encoder signal lines become “floating” and produce oscillating HIGH/LOWs.</p><p>The alternative is to use Arduino 5V and GND for a clean and stable reference voltage, which is what I ended up choosing in my setup.</p><h4><strong>Update to the ROS Arduino Bridge Sketch</strong></h4><p>I updated the <a href="https://github.com/jiayihoffman/ros_arduino_bridge/tree/MS_TB6612">ros_arduino_bridge</a> repository to support the TB6612 motor shield and modified the encoder_driver to use analog pins A2-A5 for encoder readings. This repository serves as the hardware interface for the ros2_control of my robot car.</p><p>Cheers!</p><p><strong>Part One: </strong><a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c"><strong>ROS 2 Control, Robot Control the Right Way</strong></a></p><p><strong>Part Two: </strong><a href="https://medium.com/@jiayi.hoffman/enhance-dc-motors-with-motor-encoders-4682c329ad8c"><strong>Enhancing DC Motors with Motor Encoders</strong></a></p><p><strong>Part Four: </strong><a href="https://medium.com/@jiayi.hoffman/robot-auto-mapping-using-nav2-slam-toolbox-40b575433fb0?source=your_stories_page--------------------------------------------"><strong>Robot Auto Mapping using Nav2 SLAM Toolbox</strong></a></p><h3>Related Articles</h3><ul><li><a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564"><strong>PRLidar in ROS 2 Docker on Raspberry Pi</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99fea70071b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing DC Motors with Motor Encoders]]></title>
            <link>https://medium.com/@jiayi.hoffman/enhance-dc-motors-with-motor-encoders-4682c329ad8c?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4682c329ad8c</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[dc-motor]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 04:04:05 GMT</pubDate>
            <atom:updated>2025-05-28T15:50:35.355Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ROS (Robot Operating System) ecosystem, a motor encoder plays a crucial role in enabling feedback control and odometry estimation for mobile robots. In this article, I will show you how to enhance standard DC motors using motor encoders.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNX-1zldg81s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNX-1zldg81s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNX-1zldg81s%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f635339b2768c80c4dec270d6784d19/href">https://medium.com/media/7f635339b2768c80c4dec270d6784d19/href</a></iframe><h3><strong>What is a Motor Encoder</strong></h3><p>A motor encoder is a sensor attached to a motor shaft that measures the rotation of the shaft. It converts mechanical motion into digital signals that a controller can interpret to manage the motor’s speed.</p><p>Recall from part one of the blog, <a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c?source=your_stories_page--------------------------------------------"><strong>ROS 2 Control, Robot Control the Right Way</strong></a>, that I briefly discussed using motor encoders and ros2_control for a closed-loop robot system. In the following component diagram, the motor encoder contributes to the elements circled in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEsO0ZophKktG3GeWDVNQA.png" /></figure><h4><strong>The Purpose of Motor Encoder in ROS</strong></h4><p><strong>Odometry</strong></p><p>In robotics, odometry (or odom for short) refers to the method of estimating a robot’s position and orientation over time based on sensor data from wheel encoders. In ROS, odometry is published as messages on the /odom topic. Specifically, encoders track how far each wheel has turned, and the ROS nodes utilize this data to estimate:</p><ul><li>Distance traveled</li><li>Robot’s pose (position and orientation)</li><li>Velocity</li></ul><p><strong>Feedback for Motor Control</strong></p><p>The “diff_drive_controller” in ros2_control relies on encoder feedback for:</p><ul><li>Position control: Moving to a desired position.</li><li>Velocity control: Maintaining a target speed.</li></ul><p>The encoder data is part of the closed-loop system that adjusts motor commands in real-time.</p><p><strong>Joint State Publishing</strong></p><p>The readings from the encoders assist in reporting the position, angle, and velocity of the left and right wheel joints through the /joint_states topic, allowing users to visualize the robot in tools like RViz. This is how my robot appears in RViz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_SDvW3oXe59uY-ZO9FNsg.png" /></figure><h3><strong>Upgrade DC Motors using Motor Encoders</strong></h3><p>I have several <a href="https://osepp.com/accessories/motors/143-ls-00041-high-torque-electric-motor-6v">OSEPP DC motors</a> that I used for different DIY robotics projects. These motors are high-quality, made from durable materials, and they provide high torque and a long motor shaft. They work well with the mechanical components of my robot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZ_F2lwBsUz4Ii4SQpfVuA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2LXKwFeey0EVKxbV97WOg.jpeg" /></figure><p>I considered using a new pair of DC motors with built-in encoders to simplify the setup. However, the ones I found on Amazon do not have a long enough motor shaft to work with my robotic parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQQPQJT9_avQHSkte5ZHNA.jpeg" /></figure><p>After careful consideration, I chose to reuse my existing DC motors and enhance them with the <a href="https://osepp.com/accessories/motors/114-motor-encoder">OSEPP Motor Encoder</a>. This motor encoder comes with a datasheet and detailed <a href="https://osepp.com/downloads/pdf/Encoder%20Assembly.pdf">assembly instructions</a>. Furthermore, I appreciate the build quality of OSEPP products.</p><h4><strong>Quadrature Encoders</strong></h4><p>The OSEPP motor encoder is a quadrature encoder, a type of rotary encoder. It provides two output signals, Channel A and Channel B, that are 90° out of phase. This allows the system to determine:</p><ol><li>Speed (the rate at which the motor is rotating).</li><li>Direction (If A leads B → clockwise. If B leads A → counterclockwise).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*ahICmMQ5SYHpsM0wWJQbVQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*by5U4zVwGBXU2dqLupy8Mg.jpeg" /></figure><h4><strong>Test the Encoder Installation</strong></h4><p>After following the assembly instructions, I installed the encoder mount next to the motor’s magnet. I wired the encoders to the Arduino, and now it’s time to test the encoders’ readings.</p><p>I used the following Arduino program to check the readings:</p><pre>#define ENCA A4 // Pin 2, A4<br>#define ENCB A5 // Pin 3, A5<br><br>void setup() {<br>  Serial.begin(9600);<br>  pinMode(ENCA,INPUT);<br>  pinMode(ENCB,INPUT);<br>}<br><br>void loop() {<br>  int a = digitalRead(ENCA);<br>  int b = digitalRead(ENCB);<br>  Serial.print(a*5); <br>  Serial.print(&quot; &quot;);<br>  Serial.print(b*5);<br>  Serial.println();<br>}</pre><p>If everything is installed and wired correctly, we should see “Value A” and “Value B” interlacing in the Serial Plotter when I manually rotate the wheel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGck2oVlLOxgFq5NQFSpXQ.png" /></figure><p>If the plot appears as a flat line or shows only one value oscillating while rotating the wheel, the issue may be related to the wire connection or the positioning of the encoder.</p><p>In my case, the problem was that the encoder mount was too far from the magnet. Additionally, the two channels were angled relative to the magnet. The A3144 sensor’s Channels A and B must be close to and parallel to the magnet’s side to detect the magnetic field while the motor shaft spins. Here is a picture of a properly installed motor encoder mount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6BrKfgKslE38oS4KButZg.jpeg" /></figure><h4><strong>Encoder Count Per Revolution</strong></h4><p>To use the encoder in ROS2 Control, an important parameter is enc_counts_per_rev, which refers to the encoder counts generated for one full revolution of the wheel or motor shaft.</p><p>This parameter is defined in “ros2_control.xacro” and is used in the “read” and “write” functions of the hardware interface “DiffDriveArduinoHardware” to calculate the velocity command sent to the motor, as well as to compute the robot’s current pose and velocity.</p><p>Here is the “ros2_control.xacro”:</p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;robot xmlns:xacro=&quot;http://www.ros.org/wiki/xacro&quot;&gt;<br>    &lt;ros2_control name=&quot;RealRobot&quot; type=&quot;system&quot;&gt;<br>        &lt;hardware&gt;<br>            &lt;plugin&gt;diffdrive_arduino/DiffDriveArduinoHardware&lt;/plugin&gt;<br>   ...<br>            &lt;param name=&quot;enc_counts_per_rev&quot;&gt;2000&lt;/param&gt;<br>        &lt;/hardware&gt;</pre><p><strong>Compute the enc_counts_per_rev</strong></p><p>To determine the enc_counts_per_rev, I wrote an Arduino program that outputs the count after I manually rotate the motor shaft for one full revolution. I perform this rotation several times and calculate the average count, which gives me the enc_counts_per_rev of the motor.</p><pre>#define ENC_A 2  // Encoder Channel A (Digital Pin 2)<br>#define ENC_B 3  // Encoder Channel B (Digital Pin 3)<br><br>volatile int pulseCount = 0;<br>bool counting = false;<br><br>void encoderISR() {<br>    if (counting) {<br>        pulseCount++;  // Increment count on each rising edge<br>    }<br>}<br><br>void setup() {<br>    Serial.begin(9600);<br>    pinMode(ENC_A, INPUT_PULLUP);<br>    pinMode(ENC_B, INPUT_PULLUP);<br>    <br>    // Attach interrupt for counting pulses<br>    attachInterrupt(digitalPinToInterrupt(ENC_A), encoderISR, RISING);<br>    <br>    Serial.println(&quot;Rotate the motor one full revolution and press ENTER.&quot;);<br>}<br><br>void loop() {<br>    if (Serial.available()) {<br>        Serial.read();  // Clear serial buffer<br>        <br>        pulseCount = 0;  // Reset pulse count<br>        counting = true;<br>        Serial.println(&quot;Start rotating the motor one full revolution...&quot;);<br>        <br>        delay(5000);  // Wait 5 seconds for manual rotation<br>        <br>        counting = false;<br>        Serial.print(&quot;Total pulses counted: &quot;);<br>        Serial.println(pulseCount);<br>        <br>        Serial.print(&quot;Estimated CPR: &quot;);<br>        Serial.println(pulseCount * 4);  // Multiply by 4 for quadrature encoders<br>        Serial.println(&quot;Press ENTER and rotate again.&quot;);<br>    }<br>}</pre><h3><strong>Let robot dance in RViz</strong></h3><p>As mentioned earlier, one application of motor encoders is to help users visualize the robot using tools like RViz. Therefore, I created this robot dance clip. Cheers! :D</p><pre>```<br># start the robot on Raspberry Pi<br>ros2 launch my_bot robot.launch.py<br><br># view the robot in rviz on the linux dev machine<br>rviz2 -d ~/dev/dev_ws/src/my_bot/config/view_bot.rviz<br>```</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNX-1zldg81s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNX-1zldg81s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNX-1zldg81s%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f635339b2768c80c4dec270d6784d19/href">https://medium.com/media/7f635339b2768c80c4dec270d6784d19/href</a></iframe><p><strong>Part One: </strong><a href="https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c?source=your_stories_page--------------------------------------------"><strong>ROS 2 Control, Robot Control the Right Way</strong></a></p><p><strong>Part Three: </strong><a href="https://medium.com/@jiayi.hoffman/simplify-robot-cars-using-tb6612-motor-shield-c99fea70071b"><strong>Simplify Robot Cars using TB6612 Motor Shield</strong></a></p><p><strong>Part Four: </strong><a href="https://medium.com/@jiayi.hoffman/robot-auto-mapping-using-nav2-slam-toolbox-40b575433fb0?source=your_stories_page--------------------------------------------"><strong>Robot Auto Mapping using Nav2 SLAM Toolbox</strong></a></p><h3>Related Articles</h3><ul><li><a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564?source=your_stories_page--------------------------------------------"><strong>PRLidar in ROS 2 Docker on Raspberry Pi</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4682c329ad8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROS 2 Control, Robot Control the Right Way]]></title>
            <link>https://medium.com/@jiayi.hoffman/ros-2-control-robot-control-the-right-way-d0e72e7f1b6c?source=rss-7f2725a555fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0e72e7f1b6c</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[mobile-robot]]></category>
            <category><![CDATA[gamepad]]></category>
            <dc:creator><![CDATA[Jiayi Hoffman]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 20:12:18 GMT</pubDate>
            <atom:updated>2026-02-13T19:17:37.581Z</atom:updated>
            <content:encoded><![CDATA[<p>My journey of building a mobile robot using ROS2 and ros2_control.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7GwNFUnjZKw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7GwNFUnjZKw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7GwNFUnjZKw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/011ea22f1c92099afabd67af19d9509a/href">https://medium.com/media/011ea22f1c92099afabd67af19d9509a/href</a></iframe><h3><strong>First Attempt — Raspberry Pi GPIO</strong></h3><p>When I began building mobile robots with ROS, I was unaware of ros2_control. I used ROS nodes to communicate directly with the Raspberry Pi’s GPIO pins, controlling the sensors and motors. A ROS node is a program that runs on ROS and interacts with other nodes. Nodes are the basic building blocks of ROS and are used to perform computations and control systems.</p><h4><strong>ROS Node Graph</strong></h4><p>In the initial version of the robot, my PS5 gamepad utilizes the joystick’s “joy_node” to publish velocity and direction messages to the “/cmd_vel” topic. My “motor_gpio_node” consumes these messages and directs the GPIO pin’s Pulse Width Modulation (PWM) signals to the wheel motor.</p><p>Here is the “Node Graph” introspection from ROS RQT. RQT is a collection of plugins that offers a graphical user interface for ROS, enabling developers to visualize and interact with the robot’s internals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQKYWkJuNa9EzttFm-CSbQ.png" /></figure><h4><strong>Direct RPI.GPIO Communication</strong></h4><p>Watching the robot come to life and respond to my gamepad’s joystick was quite enjoyable. Here is the “motor_gpio_node” code written in Python:</p><pre>class MotorSubscriber(Node):<br><br>    def listener_callback(self, msg):<br>        # extract linear and angular velocities from Twist message<br>        linear_vel = msg.linear.x<br>        angular_vel = msg.angular.z<br><br>        # 1. set motor direction on digital pins<br>        GPIO.output(RIGHT_MOTOR_1, linear_vel &gt; 0)<br>        GPIO.output(RIGHT_MOTOR_2, linear_vel &lt; 0)<br>        GPIO.output(LEFT_MOTOR_1, linear_vel &gt; 0)<br>        GPIO.output(LEFT_MOTOR_2, linear_vel &lt; 0)<br>    <br>        # 2. set speed using PWM. The angular velocity will &quot;weigh&quot; the motors speed.<br>        # map from the cmd_vel linear range to the motor&#39;s PWM range<br>        motor_speed = self.map(abs(linear_vel), LINEAR_X_MIN, LINEAR_X_MAX, PWM_MIN, PWM_MAX)<br>        right_pwm = self.compute_pwm(motor_speed, angular_vel)<br>        left_pwm = self.compute_pwm(motor_speed, angular_vel)<br>        <br>        self.pwm_right.ChangeDutyCycle(right_pwm)<br>        self.pwm_left.ChangeDutyCycle(left_pwm)</pre><p>After the excitement faded, I felt I was overloading the Raspberry Pi. The Pi should concentrate on robot control and high-level processing while delegating hardware communication to another device. This is where Arduino comes into the picture.</p><h3><strong>Second Attempt — Raspberry Pi with Arduino</strong></h3><p>Arduino is a microcontroller optimized for low-level tasks, such as precise PWM motor control, reading motor encoder outputs, retrieving sensor data, and managing real-time tasks without the overhead of an operating system. In contrast, Raspberry Pi is a single-board computer that can run AI models and execute path-planning algorithms.</p><p>I integrated Arduino into my robot design and rewired the motors, LED light, and PIR sensor. Here is its current appearance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pze1B0v6X64j4v5sQYiJfQ.jpeg" /></figure><h4><strong>Coding for the Arduino Board</strong></h4><p>Writing code for Arduino differs significantly from high-level programming languages due to its emphasis on hardware interaction, real-time processing, and resource limitations. Here’s what makes it unique:</p><p>1. Arduino executes bare-metal code without an operating system. Arduino code interacts directly with hardware through digital and analog pins.</p><p>2. Code is written in the Arduino IDE and saved as Sketches. Each Sketch contains two primary functions; everything operates sequentially within the loop() function.</p><pre>void setup() { <br>    // Runs once at startup<br>}<br><br>void loop() { <br>    // Runs repeatedly<br>}</pre><p>Due to its unique interaction style, Arduino can execute tasks with precision and in real-time.</p><h4><strong>Serial Port Communication</strong></h4><p>Raspberry Pi communicates with Arduino using either a Serial port or I2C. The serial port is simpler and has default support. I2C allows for multiple boards but requires slightly more complex wiring. A serial connection can be established through UART or USB. For quick prototyping, I used Serial over USB. After connecting the Raspberry Pi to Arduino, I could find the serial port on the Pi using this command:</p><pre>$ ls -l /dev/serial/by-id<br>lrwxrwxrwx 1 root root 13 Feb 20 17:05 usb-Arduino__www.arduino.cc__0043_956353339303515160E1-if00 -&gt; ../../ttyACM1</pre><p>I tested the serial communication on the Raspberry Pi using the Python utility called “mini-term,” as shown below.</p><pre>$ python3 -m serial.tools.miniterm -e /dev/ttyACM1 57600<br>--- Miniterm on /dev/ttyACM1  57600,8,N,1 ---<br>--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---<br>r<br>OK</pre><ul><li>“/dev/ttyACM1” is the serial port identified from the above “by-id” command,</li><li>“57600” is the “baudrate”, declared in the Arduino sketch setup function.</li><li>The output from the miniterm depends on the Arduino code in the loop function.</li></ul><p>The baud rate is the communication speed between two devices over a serial port, representing the number of bits transmitted per second (bps). The default setting is 9600. The output of the mini-term depends on what is loaded onto the Arduino board.</p><h4><strong>Firmata</strong></h4><p>At this stage, my robot is quite simple. The control node calculates the PWM value and sends it to the Arduino to control the direction and velocity of the wheels. Therefore, I can use the standard Firmata instead of writing my own delegate code for Arduino. Firmata comes with the Arduino IDE and can be accessed through File -&gt; Examples -&gt; Firmata -&gt; StandardFirmata. Once the Firmata sketch is uploaded to the Arduino board, the Arduino side is ready to receive commands from the Raspberry Pi.</p><p>Here’s what to configure on the Raspberry Pi:</p><ol><li>Install pyFirmata — `pip3 install pyfirmata`</li><li>Grant the robot user permission to read and write the serial port — `sudo adduser $USER dialout`</li><li>Update the ROS node to use pyFirmata</li></ol><pre>import pyfirmata<br><br>board = pyfirmata.Arduino(&#39;/dev/ttyACM1&#39;)<br><br>board.digital[RIGHT_MOTOR_1].write(0)<br>board.digital[RIGHT_MOTOR_2].write(0)<br>...</pre><p>Firmata works well for a simple robot, but I must explore more sophisticated options as my robot advances.</p><h3><strong>Third Attempt — ros2_control</strong></h3><p>The mobile robot I want to build will drive itself using a map, localization, and navigation. A motor encoder is needed to tell its velocity and position, and the robot will efficiently control the motor using the PID algorithm. Therefore, a simple open-loop and pass-through control is not enough. I need a feedback loop and real-time, low-latency execution using ros2_control.</p><h4><strong>What is ros2_control</strong></h4><p>ros2_control is a robot control framework in ROS 2 that provides a hardware abstraction layer for controlling robot actuators, sensors, and hardware interfaces in a modular and efficient way.</p><p>The primary benefit of ros2_control is that it enhances performance and offers real-time capabilities. The ros2_control conducts a direct, low-latency interface with the hardware by reducing ROS message overhead when communicating with actuators and sensors. The ROS 2 controllers operate within a single process rather than multiple processes collaborating through messages and topics.</p><p>In addition to performance and efficiency advantages, ros2_control also promotes standardization and modular robot control. It supports various hardware interfaces through the hardware abstraction layer and enables a seamless transition between simulated and different hardware implementations with little code change. Developers can reuse existing controllers instead of writing their own from scratch. In fact, much of the robot control logic has already been developed by others, so the <a href="https://control.ros.org/humble/doc/ros2_controllers/doc/controllers_index.html">pre-built ROS2 controllers</a> can be utilized as is in most use cases.</p><p>For reference, ros2_controll supports various types of control for the <a href="https://control.ros.org/humble/doc/ros2_controllers/doc/mobile_robot_kinematics.html">wheeled mobile robot</a>.</p><h4><strong>Update My Code to Use ros2_control</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFwpjs6F7GRSNZYu2ABCRQ.png" /></figure><p>To incorporate ros2_control into my robot, here are the changes I made:</p><ol><li>Update the robot launch file to use standard ROS2 controllers.</li><li>Add two new configuration files.</li><li>Add the hardware plugin that communicates with the Arduino for the state and command of the motors.</li><li>Create an Arduino sketch that provides encoder readings, open-loop and closed-loop control.</li><li>Remove my RO2 node “motor_gpio_node”</li></ol><p>Here are more details about each change. The hardware plugin and Arduino sketch (items #3 and #4) are downloaded from the robotics community.</p><p><strong>ROS 2 Launch File</strong></p><p>This is the robot’s launch file that uses the standard ros2_controllers. They are controllers for the <a href="https://control.ros.org/humble/doc/ros2_controllers/diff_drive_controller/doc/userdoc.html">Differential Drive</a> and the <a href="https://control.ros.org/humble/doc/ros2_controllers/joint_state_broadcaster/doc/userdoc.html">Joint State Broadcaster</a>.</p><pre>def generate_launch_description():<br>...<br>    control_node = Node(<br>        package=&quot;controller_manager&quot;,<br>        executable=&quot;ros2_control_node&quot;,<br>        parameters=[robot_controllers],<br>        output=&quot;both&quot;,<br>        remappings=[<br>            (&quot;~/robot_description&quot;, &quot;/robot_description&quot;),<br>            (&quot;/diffbot_base_controller/cmd_vel&quot;, &quot;/cmd_vel&quot;),<br>        ],<br>    )<br><br>    robot_state_pub_node = Node(<br>        package=&quot;robot_state_publisher&quot;,<br>        executable=&quot;robot_state_publisher&quot;,<br>        output=&quot;both&quot;,<br>        parameters=[robot_description],<br>    )    <br><br>    joint_state_broadcaster_spawner = Node(<br>        package=&quot;controller_manager&quot;,<br>        executable=&quot;spawner&quot;,<br>        arguments=[&quot;joint_state_broadcaster&quot;, &quot;--controller-manager&quot;, &quot;/controller_manager&quot;],<br>    )<br><br>    robot_controller_spawner = Node(<br>        package=&quot;controller_manager&quot;,<br>        executable=&quot;spawner&quot;,<br>        arguments=[&quot;diffbot_base_controller&quot;, &quot;--controller-manager&quot;, &quot;/controller_manager&quot;],<br>    )<br><br>    # Delay start of joint_state_broadcaster after `robot_controller`<br>    delay_joint_state_broadcaster_after_robot_controller_spawner = RegisterEventHandler(<br>        event_handler=OnProcessExit(<br>            target_action=robot_controller_spawner,<br>            on_exit=[joint_state_broadcaster_spawner],<br>        )<br>    )<br><br>    nodes = [<br>        control_node,<br>        robot_state_pub_node,<br>        robot_controller_spawner,<br>        delay_joint_state_broadcaster_after_robot_controller_spawner,<br>    ]<br><br>    return LaunchDescription(declared_arguments + nodes)</pre><p><strong>New Configuration Files:</strong></p><p>The “ros2_control.xacro” describes the hardware plugin.</p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;robot xmlns:xacro=&quot;http://www.ros.org/wiki/xacro&quot;&gt;<br>    &lt;ros2_control name=&quot;RealRobot&quot; type=&quot;system&quot;&gt;<br>        &lt;hardware&gt;<br>            &lt;plugin&gt;diffdrive_arduino/DiffDriveArduinoHardware&lt;/plugin&gt;<br>            &lt;param name=&quot;left_wheel_name&quot;&gt;left_wheel_joint&lt;/param&gt;<br>            &lt;param name=&quot;right_wheel_name&quot;&gt;right_wheel_joint&lt;/param&gt;<br>            &lt;param name=&quot;loop_rate&quot;&gt;30&lt;/param&gt;<br>            &lt;param name=&quot;device&quot;&gt;/dev/ttyACM1&lt;/param&gt;<br>            &lt;param name=&quot;baud_rate&quot;&gt;57600&lt;/param&gt;<br>            &lt;param name=&quot;timeout_ms&quot;&gt;1000&lt;/param&gt;<br>            &lt;param name=&quot;enc_counts_per_rev&quot;&gt;2000&lt;/param&gt;<br>        &lt;/hardware&gt;<br>        &lt;joint name=&quot;left_wheel_joint&quot;&gt;<br>            &lt;command_interface name=&quot;velocity&quot;&gt;<br>                &lt;param name=&quot;min&quot;&gt;-10&lt;/param&gt;<br>                &lt;param name=&quot;max&quot;&gt;10&lt;/param&gt;<br>            &lt;/command_interface&gt;<br>            &lt;state_interface name=&quot;position&quot;/&gt;<br>            &lt;state_interface name=&quot;velocity&quot;/&gt;<br>        &lt;/joint&gt;<br>        &lt;joint name=&quot;right_wheel_joint&quot;&gt;<br>            &lt;command_interface name=&quot;velocity&quot;&gt;<br>                &lt;param name=&quot;min&quot;&gt;-10&lt;/param&gt;<br>                &lt;param name=&quot;max&quot;&gt;10&lt;/param&gt;<br>            &lt;/command_interface&gt;<br>            &lt;state_interface name=&quot;position&quot;/&gt;<br>            &lt;state_interface name=&quot;velocity&quot;/&gt;<br>        &lt;/joint&gt;<br>    &lt;/ros2_control&gt;<br>&lt;/robot&gt;</pre><p>The “diffbot_controllers.yaml” file is used to tweak the controller behaviors.</p><pre>controller_manager:<br>  ros__parameters:<br>    update_rate: 10  # Hz<br><br>    joint_state_broadcaster:<br>      type: joint_state_broadcaster/JointStateBroadcaster<br><br>    diffbot_base_controller:<br>      type: diff_drive_controller/DiffDriveController<br><br>diffbot_base_controller:<br>  ros__parameters:<br>    publish_rate: 50.0<br><br>    base_frame_id: base_link<br><br>    left_wheel_names: [&quot;left_wheel_joint&quot;]<br>    right_wheel_names: [&quot;right_wheel_joint&quot;]<br>    wheel_separation: 0.14<br>    wheel_radius: 0.03<br>    ...</pre><p><strong>Hardware Plugin and Arduino sketch</strong></p><p>The hardware plugin “diffdrive_arduino/DiffDriveArduinoHardware” I used was originally developed by the robotics community. I made some adjustments for my motors and easier wiring. I cloned the <a href="https://github.com/jiayihoffman/diffdrive_arduino/tree/humble">git repository</a> and built it using “colcon” in my ROS 2 workspace.</p><p>The Arduino sketch works with the hardware plugin and can be downloaded <a href="https://github.com/jiayihoffman/ros_arduino_bridge/tree/main">here</a>.</p><h3><strong>Let the Robot Dance</strong></h3><p>I want to see how well the robot reacts to the joystick’s twists and turns, so I created this robot dance clip. Cheers! :D</p><pre># start the robot on Raspberry Pi<br>ros2 launch my_bot robot.launch.py<br><br># start the joystick teleop on the linux dev machine<br>ros2 launch teleop_twist_joy teleop-launch.py joy_config:=&#39;ps3&#39;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7GwNFUnjZKw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7GwNFUnjZKw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7GwNFUnjZKw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/011ea22f1c92099afabd67af19d9509a/href">https://medium.com/media/011ea22f1c92099afabd67af19d9509a/href</a></iframe><p><strong>Part Two: </strong><a href="https://medium.com/@jiayi.hoffman/enhance-dc-motors-with-motor-encoders-4682c329ad8c?source=your_stories_page--------------------------------------------"><strong>Enhancing DC Motors with Motor Encoders</strong></a></p><p><strong>Part Three: </strong><a href="https://medium.com/@jiayi.hoffman/simplify-robot-cars-using-tb6612-motor-shield-c99fea70071b"><strong>Simplify Robot Cars using TB6612 Motor Shield</strong></a></p><p><strong>Part Four: </strong><a href="https://medium.com/@jiayi.hoffman/robot-auto-mapping-using-nav2-slam-toolbox-40b575433fb0?source=your_stories_page--------------------------------------------"><strong>Robot Auto Mapping using Nav2 SLAM Toolbox</strong></a></p><h3>Related Articles</h3><ul><li><a href="https://medium.com/@jiayi.hoffman/prlidar-in-ros-2-docker-on-raspberry-pi-06086e968564"><strong>PRLidar in ROS 2 Docker on Raspberry Pi</strong></a></li><li><a href="https://medium.com/@jiayi.hoffman/ros2-control-of-the-lego-audi-164b4b0b9235"><strong>ROS2 Control of the LEGO Audi</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0e72e7f1b6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>