I actually prefer the BNO055 over other IMU sensors like the MPU6050. I have found that the BNO055 generates more accurate and less noisy data than the MPU6050.
Real-World Applications
This project has a number of real-world applications:
Indoor Delivery Robots
Room Service Robots
Mapping of Underground Mines, Caves, and Hard-to-Reach Environments
Robot Vacuums
Order Fulfillment
Factories
Prerequisites
You have already set up your NVIDIA Jetson Nano (4GB, B01) with ROS. You can also use an Ubuntu-enabled Raspberry Pi that has ROS installed, but the hardware setup will be different.
Make the following connections between the BNO055 and the NVIDIA Jetson Nano:
Connect BNO055 Vin to pin 17 (3.3V) of the Jetson Nano.
Connect BNO055 GND to pin 25 (GND) of the Jetson Nano.
Connect BNO055 SDA to pin 3 (SDA) of the Jetson Nano.
Connect BNO055 SCL to pin 5 (SCL) of the Jetson Nano.
Set Up the Communication Protocol
Our BNO055 will use the I2C serial communication protocol. What this means is that data will be transferred from the IMU to the Jetson Nano one bit at a time.
Turn on your Jetson Nano.
Open a terminal window.
Type the following command to verify that you can see the BNO055.
sudo i2cdetect -r -y 1
Check that the bus of the BNO055 has an address of 0x28.
Install and Build the BNO055 ROS Package
Let’s get all the software set up.
Turn on your Jetson Nano.
Open a new terminal window.
Install the libi2c-dev library.
sudo apt-get update
sudo apt-get install libi2c-dev
Install the BNO055 ROS package.
cd ~/catkin_ws/src
Remove any existing package named ‘ros_imu_bno055’.
The microcontroller we will use is the Nvidia Jetson Nano, but you can also use an Ubuntu-enabled Raspberry Pi.
We will interface Arduino with ROS so we can publish the tick counts for the left wheel and right wheel to ROS topics. The name of this node will be tick_publisher.
Why Publish Wheel Encoder Tick Data
Tick data from wheel encoders helps us determine how much each wheel (both the left and right wheels) has rotated. Since we know the radius of each wheel, we can use the tick data and the wheel radius data to determine the distance traveled by each wheel. Here is the equation for that:
Distance a wheel has traveled = 2 * pi * radius of the wheel * (number of ticks / number of ticks per revolution)
Knowing the distance traveled by each wheel helps us determine where the robot is located in its environment relative to some starting location. This process is known as odometry.
The first time you were exposed to the word “odometry” was likely when you began driving a car. Right behind your steering wheel is typically your odometer. The odometer of your car measures the distance traveled by the vehicle relative to some starting point where the car was first driven. Odometry in robotics works the same way.
A typical odometer on a car’s dashboard
Real-World Applications
You can see that a robotic vacuum cleaner has the same two-wheeled differential drive setup as the robot I’m currently working with in this tutorial.
This project has a number of real-world applications:
Indoor Delivery Robots
Room Service Robots
Mapping of Underground Mines, Caves, and Hard-to-Reach Environments
Although not required at this stage, if you want your robot to perform autonomous navigation, eventually you will want to know how many ticks (i.e. pulses) are generated in one full revolution of your motor. To calculate this value for your motors, follow this tutorial. For the DC motors I’m using, there are 620 ticks per revolution.
You Will Need
Arduino Uno (Elegoo Uno works just fine and is cheaper than the regular Arduino)
Install Arduino on Your Jetson Nano
To get started, turn on your Jetson Nano.
Let’s download the Arduino IDE (you’ll have to download the Arduino IDE directly from the Arduino website if you are using Ubuntu on the Raspberry Pi).
Open a new terminal window, and type the following commands, one right after the other.
Open the IDE and go to File -> Preferences. Make a note of the Sketchbook location. Mine is:
/home/automaticaddison/Arduino
Quit the Arduino IDE.
Open a new terminal window, and go to the sketchbook location you noted above. I’ll type:
cd Arduino
Type the dir command to see the list of folders.
dir
Go to the libraries directory.
cd libraries
rm -rf ros_lib
Within that directory, run the following command to build the Arduino library that will be used by ROS (don’t leave out that period that comes at the end of the command):
rosrun rosserial_arduino make_libraries.py .
Type the dir command to see the list of folders. You should now see the ros_lib library.
dir
Make sure the Arduino IDE is closed. Now open it again.
Blink an LED on the Arduino Using ROS
In this example, Arduino is going to be considered a Subscriber node. It will subscribe to a topic called toggle_led. Publishing a message to that topic causes the LED to turn on. Publishing a message to the topic again causes the LED to turn off.
Go to File -> Examples -> ros_lib and open the Blink sketch.
Before the nh.initNode(); line, add the following code:
nh.getHardware()->setBaud(115200);
Now we need to upload the code to Arduino. Make sure your Arduino is plugged into the USB port on your Jetson Nano (or whatever microcontroller you are using).
Upload the code to your Arduino using the right arrow button in the upper left of your screen. When you upload the code, your Arduino should flicker a little bit.
Note: I created a new Arduino sketch and saved it to /home/automaticaddison/Documents as “blink_ros_arduino_test”. This is not required.
Quit the Arduino IDE.
Open a new terminal window and type:
roscore
In a new terminal window, launch the ROS serial server. This command is explained here on the ROS website. It is necessary to complete the integration between ROS and Arduino:
Now let’s turn on the LED by publishing a single empty message to the /toggle_led topic. Open a new terminal window and type:
rostopic pub toggle_led std_msgs/Empty --once
The LED on the Arduino should turn on.
Now press the Up arrow in the terminal and press ENTER to run this code again. You should see the LED turn off. You might also see a tiny yellow light blinking as well. Just ignore that one…you’re interested in the big yellow light that you’re able to turn off and on by publishing single messages to the /toggle_led topic.
You can see the active topics by typing.
rostopic list
Another good example to check out is a publisher and subscriber. You can see this by going to:
File -> Examples -> ros_lib -> pubsub
This ROS node will blink an LED and publish a “Hello World” message to a topic named chatter.
That’s it! You have now seen how you can integrate Arduino with ROS. To turn off your Arduino, all you need to do is disconnect it after you shut down your Jetson Nano.
Create a Tick Publisher Node
Now we want to write a tick publisher node. This ROS node will publish the accumulated tick count for the left and right motors of the robot at regular intervals.
The Ground pin of the motor connects to GND of the Arduino. I’m using a 400-point solderless breadboard that I bought on Amazon.com to facilitate this connection.
Encoder A (sometimes labeled C1) of the motor connects to pin 2 of the Arduino. Pin 2 of the Arduino will record every time there is a rising digital signal from Encoder A.
Encoder B (sometimes labeled C2) of the motor connects to pin 4 of the Arduino. The signal that is read off pin 4 on the Arduino will determine if the motor is moving forward or in reverse. We’re not going to use this pin in this tutorial, but we will use it in a future tutorial.
The VCC pin of the motor connects to the 5V pin of the Arduino. This pin is responsible for providing power to the encoder.
For the right motor:
The Ground pin of the motor connects to GND of the Arduino.
Encoder A (sometimes labeled C1) of the motor connects to pin 3 of the Arduino. Pin 2 of the Arduino will record every time there is a rising digital signal from Encoder A.
Encoder B (sometimes labeled C2) of the motor connects to pin 11 of the Arduino. The signal that is read off pin 11 on the Arduino will determine if the motor is moving forward or in reverse.
The VCC pin of the motor connects to the 5V pin of the Arduino. This pin is responsible for providing power to the encoder.
Write the Code
Now we’re ready to calculate the accumulated ticks for each wheel.
Open the Arduino IDE, and write the following program. The name of my program is tick_counter.ino.
/*
* Author: Automatic Addison
* Website: https://automaticaddison.com
* Description: Calculate the accumulated ticks for each wheel using the
* built-in encoder (forward = positive; reverse = negative)
*/
// Encoder output to Arduino Interrupt pin. Tracks the tick count.
#define ENC_IN_LEFT_A 2
#define ENC_IN_RIGHT_A 3
// Other encoder output to Arduino to keep track of wheel direction
// Tracks the direction of rotation.
#define ENC_IN_LEFT_B 4
#define ENC_IN_RIGHT_B 11
// True = Forward; False = Reverse
boolean Direction_left = true;
boolean Direction_right = true;
// Minumum and maximum values for 16-bit integers
const int encoder_minimum = -32768;
const int encoder_maximum = 32767;
// Keep track of the number of wheel ticks
volatile int left_wheel_tick_count = 0;
volatile int right_wheel_tick_count = 0;
// One-second interval for measurements
int interval = 1000;
long previousMillis = 0;
long currentMillis = 0;
void setup() {
// Open the serial port at 9600 bps
Serial.begin(9600);
// Set pin states of the encoder
pinMode(ENC_IN_LEFT_A , INPUT_PULLUP);
pinMode(ENC_IN_LEFT_B , INPUT);
pinMode(ENC_IN_RIGHT_A , INPUT_PULLUP);
pinMode(ENC_IN_RIGHT_B , INPUT);
// Every time the pin goes high, this is a tick
attachInterrupt(digitalPinToInterrupt(ENC_IN_LEFT_A), left_wheel_tick, RISING);
attachInterrupt(digitalPinToInterrupt(ENC_IN_RIGHT_A), right_wheel_tick, RISING);
}
void loop() {
// Record the time
currentMillis = millis();
// If one second has passed, print the number of ticks
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
Serial.println("Number of Ticks: ");
Serial.println(right_wheel_tick_count);
Serial.println(left_wheel_tick_count);
Serial.println();
}
}
// Increment the number of ticks
void right_wheel_tick() {
// Read the value for the encoder for the right wheel
int val = digitalRead(ENC_IN_RIGHT_B);
if(val == LOW) {
Direction_right = false; // Reverse
}
else {
Direction_right = true; // Forward
}
if (Direction_right) {
if (right_wheel_tick_count == encoder_maximum) {
right_wheel_tick_count = encoder_minimum;
}
else {
right_wheel_tick_count++;
}
}
else {
if (right_wheel_tick_count == encoder_minimum) {
right_wheel_tick_count = encoder_maximum;
}
else {
right_wheel_tick_count--;
}
}
}
// Increment the number of ticks
void left_wheel_tick() {
// Read the value for the encoder for the left wheel
int val = digitalRead(ENC_IN_LEFT_B);
if(val == LOW) {
Direction_left = true; // Reverse
}
else {
Direction_left = false; // Forward
}
if (Direction_left) {
if (left_wheel_tick_count == encoder_maximum) {
left_wheel_tick_count = encoder_minimum;
}
else {
left_wheel_tick_count++;
}
}
else {
if (left_wheel_tick_count == encoder_minimum) {
left_wheel_tick_count = encoder_maximum;
}
else {
left_wheel_tick_count--;
}
}
}
Upload the program to the Arduino.
If you open the serial monitor, you will see the accumulated tick count. Once the tick count gets outside the range of what a 16-bit integer can handle, it rolls over to either the minimum -32,768 or maximum 32,767 of the range.
Convert the Code to a ROS Node
Now that we see how to print tick counts for the right and left motors, let’s convert the code from the previous section into a ROS node. We want our node to publish tick counts for the right and left wheels of the robot to ROS topics named right_ticks and left_ticks.
Open the Arduino IDE, and write the following program. The name of my program is tick_publisher.ino.
/*
* Author: Automatic Addison
* Website: https://automaticaddison.com
* Description: ROS node that publishes the accumulated ticks for each wheel
* (right_ticks and left_ticks topics) using the built-in encoder
* (forward = positive; reverse = negative)
*/
#include <ros.h>
#include <std_msgs/Int16.h>
// Handles startup and shutdown of ROS
ros::NodeHandle nh;
// Encoder output to Arduino Interrupt pin. Tracks the tick count.
#define ENC_IN_LEFT_A 2
#define ENC_IN_RIGHT_A 3
// Other encoder output to Arduino to keep track of wheel direction
// Tracks the direction of rotation.
#define ENC_IN_LEFT_B 4
#define ENC_IN_RIGHT_B 11
// True = Forward; False = Reverse
boolean Direction_left = true;
boolean Direction_right = true;
// Minumum and maximum values for 16-bit integers
const int encoder_minimum = -32768;
const int encoder_maximum = 32767;
// Keep track of the number of wheel ticks
std_msgs::Int16 right_wheel_tick_count;
ros::Publisher rightPub("right_ticks", &right_wheel_tick_count);
std_msgs::Int16 left_wheel_tick_count;
ros::Publisher leftPub("left_ticks", &left_wheel_tick_count);
// 100ms interval for measurements
const int interval = 100;
long previousMillis = 0;
long currentMillis = 0;
// Increment the number of ticks
void right_wheel_tick() {
// Read the value for the encoder for the right wheel
int val = digitalRead(ENC_IN_RIGHT_B);
if(val == LOW) {
Direction_right = false; // Reverse
}
else {
Direction_right = true; // Forward
}
if (Direction_right) {
if (right_wheel_tick_count.data == encoder_maximum) {
right_wheel_tick_count.data = encoder_minimum;
}
else {
right_wheel_tick_count.data++;
}
}
else {
if (right_wheel_tick_count.data == encoder_minimum) {
right_wheel_tick_count.data = encoder_maximum;
}
else {
right_wheel_tick_count.data--;
}
}
}
// Increment the number of ticks
void left_wheel_tick() {
// Read the value for the encoder for the left wheel
int val = digitalRead(ENC_IN_LEFT_B);
if(val == LOW) {
Direction_left = true; // Reverse
}
else {
Direction_left = false; // Forward
}
if (Direction_left) {
if (left_wheel_tick_count.data == encoder_maximum) {
left_wheel_tick_count.data = encoder_minimum;
}
else {
left_wheel_tick_count.data++;
}
}
else {
if (left_wheel_tick_count.data == encoder_minimum) {
left_wheel_tick_count.data = encoder_maximum;
}
else {
left_wheel_tick_count.data--;
}
}
}
void setup() {
// Set pin states of the encoder
pinMode(ENC_IN_LEFT_A , INPUT_PULLUP);
pinMode(ENC_IN_LEFT_B , INPUT);
pinMode(ENC_IN_RIGHT_A , INPUT_PULLUP);
pinMode(ENC_IN_RIGHT_B , INPUT);
// Every time the pin goes high, this is a tick
attachInterrupt(digitalPinToInterrupt(ENC_IN_LEFT_A), left_wheel_tick, RISING);
attachInterrupt(digitalPinToInterrupt(ENC_IN_RIGHT_A), right_wheel_tick, RISING);
// ROS Setup
nh.getHardware()->setBaud(115200);
nh.initNode();
nh.advertise(rightPub);
nh.advertise(leftPub);
}
void loop() {
// Record the time
currentMillis = millis();
// If 100ms have passed, print the number of ticks
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
rightPub.publish( &right_wheel_tick_count );
leftPub.publish( &left_wheel_tick_count );
nh.spinOnce();
}
}
Upload the code to your Arduino using the right arrow button in the upper left of your screen.
Quit the Arduino IDE.
Run the Tick Publisher
Open a new terminal window and type:
roscore
In a new terminal window, launch the ROS serial server.
This project has a number of real-world applications:
Indoor Delivery Robots
Mapping of Underground Mines, Caves, and Hard-to-Reach Environments
Robot Vacuums
Order Fulfillment
Factories
You can imagine the turtlesim robot is like having an aerial view of a mobile robot moving around on a factory floor. We want to be able to navigate the robot around the floor to do its work, and in order to navigate it, we imagine the factory floor is like an x-y graph (e.g. like the image below from this tutorial). All we would need to do is enter an x-y coordinate, and the robot would move to that goal location (i.e. waypoint).
I’m running my Ubuntu Linux inside a virtual machine on Windows 10. If you have MacOS or Linux, that will work just fine. Just make sure you have ROS installed.
To run the turtlesim simulation, open a terminal window and launch ROS.
roscore
See what nodes are available to run by typing:
rosrun turtlesim <TAB><TAB>
Open another terminal window, and launch the turtlesim_node.
rosrun turtlesim turtlesim_node
Let’s steer the robot.
rosrun rqt_robot_steering rqt_robot_steering
You should see a window pop up.
You’ll note that the default ROS topic is the /cmd_vel topic. This topic is where the rqt_robot_steering node will publish Twist messages. A Twist message in ROS is a special kind of topic that consists of the x, y, and z components of the linear and angular velocity.
Go back to the terminal window, and let’s see what topic the turtlesim node is subscribed to.
rostopic list
The turtlesim node gets its velocity commands from the /turtle1/cmd_vel topic.
List all the active nodes.
rosnode list
Find out what the /turtlesim node is subscribing to.
rosnode info /turtlesim
You can see that the /turtlesim node is subscribing to /turtle1/cmd_vel
Let’s find out more about this topic.
rostopic info /turtle1/cmd_vel
You can see that the type of message that passes through the /turtle1/cmd_vel topic is a Twist message.
Let’s change the topic name of the rqt_steering GUI to /turtle1/cmd_vel.
If you adjust the sliders for the linear and angular velocities, you will see the turtle move accordingly because the GUI is publishing linear and angular velocity values to the /turtle1/cmd_vel topic. The /turtlesim node reads the velocity values on this topic and then moves accordingly.
In a real-world robot, we can see how the rqt_steering node is useful. We can publish velocity commands to the /cmd_vel topic. A motor controller that subscribes to the /cmd_vel topic can convert those velocity commands into motor commands to make the robot drive accordingly.
Create a Package
Now that we’ve gotten reacquainted with turtlesim, let’s see how we get into the purpose of this tutorial: create a ROS node to move the turtlesim robot to a goal location.
Enable C++11 support be removing the hashtag # on line 5 by uncommenting the add_compile_option… line.
Here is how that should look now.
How to Move the Robot to a Desired X Coordinate
Create the ROS Node
Now let’s create a program (i.e. ROS Node) that will take the coordinates of the turtle as input and will output a velocity command as a Twist message. The velocity command will be calculated so as to get the turtlesim robot to move to a goal x coordinate that can be any number from 0 to 11.
In this first node, we will create a ROS node to move the turtlesim robot to a goal x coordinate.
The first thing we need to do is to open a new terminal window.
Move to the src folder of the go_to_goal_turtlesim package.
cd ~/catkin_ws/src/go_to_goal_turtlesim/src
Create a new C++ program called go_to_goal_x.cpp.
gedit go_to_goal_x.cpp
Add the following code to the file, and then click Save.
/// @file go_to_goal_x.cpp
/// @author Addison Sears-Collins
/// @date May 4, 2021
///
/// This program takes the coordinates of the turtlesim robot as input
/// and outputs a velocity command as a Twist message. The velocity command
/// will be calculated so as to get the turtlesim robot to move to a goal
/// x coordinate that can be any number from 0 to 11.
#include <cstdlib> // Use for the absolute value method abs()
#include <iostream> // Enables command line input and output
#include "ros/ros.h" // Necessary header files for ROS
#include "geometry_msgs/Twist.h" // Twist messages (linear & angular velocity)
#include "geometry_msgs/Pose2D.h" // x, y position and theta orientation
#include "turtlesim/Pose.h" // x, y, theta, linear & angular velocity
// Remove the need to use std:: prefix
using namespace std;
// Key variable declarations
geometry_msgs::Twist velCommand; // Linear and angular velocity in m/s
geometry_msgs::Pose2D current; // Current x, y, and theta
geometry_msgs::Pose2D desired; // Desired x, y, and theta
// Goal x-value, which can be any number from 0 to 11 (inclusive)
const double GOAL = 1.3;
// The gain K, which is used to calculate the linear velocity
const double K_l = 1.0;
// The distance threshold in meters that will determine when
// the turtlesim robot successfully reaches the goal.
const double distanceTolerance = 0.1;
// Initialized variables and take care of other setup tasks
void setup() {
// Desired x goal coordinate
desired.x = GOAL;
// Initialize the Twist message.
// Initial linear and angular velocities are 0 m/s and rad/s, respectively.
velCommand.linear.x = 0.0;
velCommand.linear.y = 0.0;
velCommand.linear.z = 0.0;
velCommand.angular.x = 0.0;
velCommand.angular.y = 0.0;
velCommand.angular.z = 0.0;
}
// Get the distance between the current x coordinate and
// the desired x coordinate.
double getDistanceToGoal() {
return desired.x - current.x;
}
// If we haven't yet reached the goal, set the velocity value.
// Otherwise, stop the robot.
void setVelocity() {
if (abs(getDistanceToGoal()) > distanceTolerance) {
// The magnitude of the robot's velocity is directly
// proportional to the distance the robot is from the
// goal.
velCommand.linear.x = K_l * getDistanceToGoal();
}
else {
cout << "Goal has been reached!" << endl << endl;
velCommand.linear.x = 0;
}
}
// This callback function updates the current position and
// orientation of the robot.
void updatePose(const turtlesim::PoseConstPtr ¤tPose) {
current.x = currentPose->x;
current.y = currentPose->y;
current.theta = currentPose->theta;
}
int main(int argc, char **argv) {
setup();
// Initiate ROS
ros::init(argc, argv, "go_to_goal_x");
// Create the main access point to communicate with ROS
ros::NodeHandle node;
// Subscribe to the robot's pose
// Hold no messages in the queue. Automatically throw away
// any messages that are received that are not able to be
// processed quickly enough.
// Every time a new pose is received, update the robot's pose.
ros::Subscriber currentPoseSub =
node.subscribe("turtle1/pose", 0, updatePose);
// Publish velocity commands to a topic.
// Hold no messages in the queue. Automatically throw away
// any messages that are received that are not able to be
// processed quickly enough.
ros::Publisher velocityPub =
node.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 0);
// Specify a frequency that want the while loop below to loop at
// In this case, we want to loop 10 cycles per second
ros::Rate loop_rate(10);
// Keep running the while loop below as long as the ROS Master is active.
while (ros::ok()) {
// Here is where we call the callbacks that need to be called.
ros::spinOnce();
// After we call the callback function to update the robot's pose, we
// set the velocity values for the robot.
setVelocity();
// Publish the velocity command to the ROS topic
velocityPub.publish(velCommand);
// Print the output to the console
cout << "Current x = " << current.x << endl
<< "Desired x = " << desired.x << endl
<< "Distance to Goal = " << getDistanceToGoal() << " m" << endl
<< "Linear Velocity (x) = " << velCommand.linear.x << " m/s" << endl
<< endl;
// Sleep as long as we need to to make sure that we have a frequency of
// 10Hz
loop_rate.sleep();
}
return 0;
}
Now we need to add the C++ program we just wrote to the CMakeLists.txt file so that we can compile the program and launch it using ROS. Each time we write a new C++ ROS node, we have to make sure we add it to the CMakeLists.txt file.
cd ~/catkin_ws/src/go_to_goal_turtlesim
gedit CMakeLists.txt
Go to the bottom of the file.
Add the following lines.
Save the file, and close it.
Go to the root of the workspace.
cd ~/catkin_ws
Compile the code.
catkin_make
Launch the ROS Node
Now let’s launch the ROS node we created in the last section.
Open a new terminal window.
Start ROS.
roscore
Open another terminal window, and launch the turtlesim_node.
rosrun turtlesim turtlesim_node
We can see that the starting pose of the robot is as follows:
x = 5.544445
y = 5.544445
theta = 0.000000
Sorry the font is so small.
Open another terminal window, and launch the go_to_goal_x node.
rosrun go_to_goal_turtlesim go_to_goal_x
How to Move the Robot to a Desired X and Y Coordinate (i.e. Waypoint)
Create the Waypoint Publisher ROS Node
In this section, we’ll write a ROS node that can accept a waypoint (i.e. goal x and y coordinate) from the user. We want to then publish that goal location to a ROS topic named “waypoint”.
We will later write a ROS node that can read the waypoint and navigate the turtlesim robot to that waypoint.
First, move to the src folder of the go_to_goal_turtlesim package.
cd ~/catkin_ws/src/go_to_goal_turtlesim/src
Create a new C++ program called waypoint_publisher.cpp.
gedit waypoint_publisher.cpp
Add the following code to the file, and then click Save.
/// @file waypoint_publisher.cpp
/// @author Addison Sears-Collins
/// @date May 6, 2021
///
/// This program takes the user's desired waypoint (i.e. goal location
/// or x,y coordinate) as input and publishes it to a topic as a
/// geometry_msgs/Pose2D data type.
#include <iostream> // Enables command line input and output
#include "ros/ros.h" // Necessary header files for ROS
#include "geometry_msgs/Pose2D.h" // x, y position and theta orientation
// Remove the need to use std:: prefix
using namespace std;
// Key variable declarations
geometry_msgs::Pose2D waypoint; // Goal location ... x, y, and theta
// Ask user for the desired waypoint...Where do you want the robot to move to?
void set_waypoint() {
cout << "Where do you want the robot to go?" << endl;
cout << "Enter waypoint x: ";
cin >> waypoint.x;
cout << "Enter waypoint y: ";
cin >> waypoint.y;
cout << endl;
}
int main(int argc, char **argv) {
// Initiate ROS
ros::init(argc, argv, "waypoint_publisher");
// Create the main access point to communicate with ROS
ros::NodeHandle node;
// Publish waypoint to a topic.
// Hold no messages in the queue. Automatically throw away
// any messages that are not able to be processed quickly enough.
ros::Publisher waypointPub =
node.advertise<geometry_msgs::Pose2D>("waypoint", 0);
// Keep running the while loop below as long as the ROS Master is active.
while (ros::ok()) {
// Ask the user where he wants the robot to go
set_waypoint();
// Publish the waypoint to the ROS topic
waypointPub.publish(waypoint);
}
return 0;
}
Now we need to add the C++ program we just wrote to the CMakeLists.txt file.
cd ~/catkin_ws/src/go_to_goal_turtlesim
gedit CMakeLists.txt
Go to the bottom of the file.
Add the following lines.
Save the file, and close it.
Go to the root of the workspace.
cd ~/catkin_ws
Compile the code.
catkin_make
Launch the ROS Node
Now let’s launch the ROS node we created in the last section.
Open a new terminal window.
Start ROS.
roscore
Open another terminal window, and launch the waypoint_publisher node.
rosrun go_to_goal_turtlesim waypoint_publisher
Here is what you will see in the terminal.
Open a new terminal, and check out the active topics.
rostopic list
We can see one of the topics is /waypoint.
Let’s see what messages are passing through this topic.
rostopic echo /waypoint
You can see the pose of the robot (i.e. x, y, and theta values) is being published to the topic named /waypoint.
Create a ROS Node to Move the Robot to the Waypoint (i.e. X-Y Coordinate)
Now we need to create a ROS node that subscribes to the /waypoint topic and publishes a velocity command to move the turtle to the user’s desired waypoint (i.e. x-y coordinate).
Open a new terminal window.
Move to the src folder of the go_to_goal_turtlesim package.
cd ~/catkin_ws/src/go_to_goal_turtlesim/src
Create a new C++ program called go_to_goal_x_y.cpp.
gedit go_to_goal_x_y.cpp
Add the following code to the file, and then click Save.
/// @file go_to_goal_x_y.cpp
/// @author Addison Sears-Collins
/// @date May 7, 2021
///
/// This program takes the coordinates of the turtlesim robot and a goal
/// waypoint (published by waypoint_publisher.cpp) as input and outputs
/// a velocity command as a Twist message. The velocity command
/// will be calculated so as to get the turtlesim robot to move to the user's
/// desired goal waypoint (x, y coordinate). The x and y values can be any
/// number from 0 to 11.
#include <cstdlib> // Use for the absolute value method abs()
#include <iostream> // Enables command line input and output
#include "ros/ros.h" // Necessary header files for ROS
#include "geometry_msgs/Twist.h" // Twist messages (linear & angular velocity)
#include "geometry_msgs/Pose2D.h" // x, y position and theta orientation
#include "turtlesim/Pose.h" // x, y, theta, linear & angular velocity
// Remove the need to use std:: prefix
using namespace std;
// Key variable declarations
geometry_msgs::Twist velCommand; // Linear and angular velocity in m/s
geometry_msgs::Pose2D current; // Current x, y, and theta
geometry_msgs::Pose2D waypointGoal; // Waypoint x, y, and theta (the waypoint)
ros::Publisher velocityPub; // Object used for publishing velocity command
const double PI = 3.141592654;
// The gain K, which is used to calculate the linear velocity
const double K_l = 0.5;
// The gain K, which is used to calculate the angular velocity
const double K_a = 0.5;
// The distance threshold in meters that will determine when
// the turtlesim robot successfully reaches the goal.
const double distanceTolerance = 0.1;
// The angle threshold in radians that will determine when
// the turtlesim robot successfully reaches the goal.
const double angleTolerance = 0.1;
// This flag determines when the robot needs to either
// move towards a waypoint or stop.
bool goToWaypoint = false;
// Initialized variables and take care of other setup tasks
void setup() {
// We initialize with the default starting coordinate
// for the turtlesim simulator
waypointGoal.x = 5.544445;
waypointGoal.y = 5.544445;
// Initialize the Twist message.
// Initial linear and angular velocities are 0 m/s and rad/s, respectively.
velCommand.linear.x = 0.0;
velCommand.linear.y = 0.0;
velCommand.linear.z = 0.0;
velCommand.angular.x = 0.0;
velCommand.angular.y = 0.0;
velCommand.angular.z = 0.0;
}
// Get the distance between the current x,y coordinate and
// the desired waypoint x,y coordinate.
double getDistanceToWaypoint() {
return sqrt(pow(waypointGoal.x - current.x, 2) + pow(
waypointGoal.y - current.y, 2));
}
// Get the heading error
// i.e. how many radians does the robot need
// to turn to head towards the waypoint
double getHeadingError() {
double deltaX = waypointGoal.x - current.x;
double deltaY = waypointGoal.y - current.y;
double waypointHeading = atan2(deltaY, deltaX);
double headingError = waypointHeading - current.theta;
// Make sure heading error falls within -PI to PI range
if (headingError > PI) {
headingError = headingError - (2 * PI);
}
if (headingError < -PI) {
headingError = headingError + (2 * PI);
}
return headingError;
}
// If we haven't yet reached the goal, set the velocity value.
// Otherwise, stop the robot.
void setVelocity() {
double distanceToWaypoint = getDistanceToWaypoint();
double headingError = getHeadingError();
// If we are not yet at the waypoint
if (goToWaypoint == true && (abs(distanceToWaypoint) > distanceTolerance)) {
// If the robot's heading is off, fix it.
if (abs(headingError) > angleTolerance) {
velCommand.linear.x = 0.0;
velCommand.angular.z = K_a * headingError;
}
// Just fix the distance gap between current pose and waypoint.
// The magnitude of the robot's velocity is directly
// proportional to the distance the robot is from the
// goal.
else {
velCommand.linear.x = K_l * distanceToWaypoint;
velCommand.angular.z = 0.0;
}
}
else {
cout << "Goal has been reached!" << endl << endl;
velCommand.linear.x = 0.0;
velCommand.angular.z = 0.0;
goToWaypoint == false;
}
}
// This callback function updates the current position and
// orientation of the robot.
void updatePose(const turtlesim::PoseConstPtr ¤tPose) {
current.x = currentPose->x;
current.y = currentPose->y;
current.theta = currentPose->theta;
}
// This callback function updates the desired waypoint when a waypoint
// message is published to the /waypoint topic
void updateWaypoint(const geometry_msgs::Pose2D &waypointPose) {
waypointGoal.x = waypointPose.x;
waypointGoal.y = waypointPose.y;
goToWaypoint = true;
}
int main(int argc, char **argv) {
setup();
// Initiate ROS
ros::init(argc, argv, "go_to_goal_x_y");
// Create the main access point to communicate with ROS
ros::NodeHandle node;
// Subscribe to the robot's pose
// Hold no messages in the queue. Automatically throw away
// any messages that are received that are not able to be
// processed quickly enough.
// Every time a new pose is received, update the robot's pose.
ros::Subscriber currentPoseSub =
node.subscribe("turtle1/pose", 0, updatePose);
// Subscribe to the user's desired waypoint
// Hold no messages in the queue. Automatically throw away
// any messages that are received that are not able to be
// processed quickly enough.
// Every time a new waypoint is received, update the robot's
// desired waypoint.
// The tcpNoDelay is to reduce latency between nodes and to make sure we are
// not missing any critical waypoint messages.
ros::Subscriber waypointPoseSub =
node.subscribe("waypoint", 0, updateWaypoint,
ros::TransportHints().tcpNoDelay());
// Publish velocity commands to a topic.
// Hold no messages in the queue. Automatically throw away
// any messages that are received that are not able to be
// processed quickly enough.
velocityPub =
node.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 0);
// Specify a frequency that want the while loop below to loop at
// In this case, we want to loop 10 cycles per second
ros::Rate loop_rate(10);
// Keep running the while loop below as long as the ROS Master is active.
while (ros::ok()) {
// Here is where we call the callbacks that need to be called.
ros::spinOnce();
// After we call the callback function to update the robot's pose, we
// set the velocity values for the robot.
setVelocity();
// Publish the velocity command to the ROS topic
velocityPub.publish(velCommand);
// Print the output to the console
cout << "Current (x,y) = " << "(" << current.x << "," << current.y << ")"
<< endl
<< "Waypoint (x,y) = " << "(" << waypointGoal.x << ","
<< waypointGoal.y << ")"
<< endl
<< "Distance to Waypoint = " << getDistanceToWaypoint() << " m"
<< endl
<< "Linear Velocity (x) = " << velCommand.linear.x << " m/s"
<< endl << endl;
// Sleep as long as we need to to make sure that we have a frequency of
// 10Hz
loop_rate.sleep();
}
return 0;
}
Now we need to add the C++ program we just wrote to the CMakeLists.txt file.
cd ~/catkin_ws/src/go_to_goal_turtlesim
gedit CMakeLists.txt
Go to the bottom of the file.
Add the following lines.
Save the file, and close it.
Go to the root of the workspace.
cd ~/catkin_ws
Compile the code.
catkin_make
Launch the ROS Node
Now let’s launch the ROS node we created in the last section.
Open a new terminal window.
Start ROS.
roscore
Open another terminal window, and launch the turtlesim_node.
cd ~/catkin_ws/
rosrun turtlesim turtlesim_node
Open another terminal window, and launch the waypoint_publisher node.
rosrun go_to_goal_turtlesim waypoint_publisher
Open another terminal window, and launch the go_to_goal_x_y node.
rosrun go_to_goal_turtlesim go_to_goal_x_y
Now, go back to the terminal window where you launched the waypoint_publisher node.
Enter any waypoint x value from 0 to 11. I will enter 1.2.
Enter any waypoint y value from 0 to 11. I will enter 2.7.
When the turtle gets close enough, you will see a message that says “Goal has been reached!”
Here is what the simulation looks like. You will see the robot moved from (5.544445, 5.544445) to (1.29721, 2.71791)…which is close enough to the waypoint. Once the turtle reached the waypoint, it stopped.
Let’s try another waypoint.
Go back to the terminal window where you launched the waypoint_publisher node.
Enter any waypoint x value from 0 to 11. I will enter 11.
Enter any waypoint y value from 0 to 11. I will enter 11.
Here is the output:
Create a Launch File
So that we don’t have to keep opening up ROS nodes in the future, we will create a launch file to make our life easier.
The first thing we need to do is to open a new terminal window and go to the go_to_goal_turtlesim package.
cd ~/catkin_ws/src/go_to_goal_turtlesim
Create a folder called ‘launch’.
mkdir launch
Create a new launch file inside the launch directory you just made.