1. 創建文件夾
在catkin_ws/src 下創建project文件夾
$ cd catkin_ws/src
$ catkin_create_pkg my_first_pkg roscpp rospy std_msgs
之後在/src會生成一個文件夾my_first_pkg,內部有一個src文件夾和一個CMakeLists.txt和package.xml文件
2. 在/src/my_first_pkg/src下創建一個cpp文件,這裏叫my_odom.cpp
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
int main(int argc, char** argv){
ros::init(argc, argv, "odometry_publisher");
ros::NodeHandle n;
ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>("myodom", 50);
tf::TransformBroadcaster odom_broadcaster;
double x = 0.0;
double y = 0.0;
double th = 0.0;
double vx = 0.1;
double vy = -0.1;
double vth = 0.1;
ros::Time current_time, last_time;
current_time = ros::Time::now();
last_time = ros::Time::now();
ros::Rate r(1.0);
while(n.ok()){
ros::spinOnce(); // check for incoming messages
current_time = ros::Time::now();
//compute odometry in a typical way given the velocities of the robot
double dt = (current_time - last_time).toSec();
double delta_x = (vx * cos(th) - vy * sin(th)) * dt;
double delta_y = (vx * sin(th) + vy * cos(th)) * dt;
double delta_th = vth * dt;
x += delta_x;
y += delta_y;
th += delta_th;
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th);
//first, we'll publish the transform over tf
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time;
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_footprint"//"base_link";
odom_trans.transform.translation.x = x;
odom_trans.transform.translation.y = y;
odom_trans.transform.translation.z = 0.0;
odom_trans.transform.rotation = odom_quat;
//send the transform
odom_broadcaster.sendTransform(odom_trans);
//next, we'll publish the odometry message over ROS
nav_msgs::Odometry odom;
odom.header.stamp = current_time;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = vth;
//publish the message
odom_pub.publish(odom);
last_time = current_time;
r.sleep();
}
}
3. 修改CMakeLists.txt和package.xml中的內容,添加編譯依賴文件(其中roscpp rospy std_msgs之前創建文件夾時自動添加了),添加編譯目標
CMakeLists.txt 中添加
//編譯依賴文件
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
tf
nav_msgs
)
// 編譯目標
add_executable(my_odom src/my_odom.cpp)
target_link_libraries(my_odom ${catkin_LIBRARIES})
package.xml 中添加
<build_depend>tf</build_depend>
<build_depend>nav_msgs</build_depend>
<build_export_depend>tf</build_export_depend>
<build_export_depend>nav_msgs</build_export_depend>
<exec_depend>tf</exec_depend>
<exec_depend>nav_msgs</exec_depend>
4. catkin_make 編譯即可
$ cd ~/catkin_ws/
catkin_ws$ catkin_make