博客參考:https://www.jianshu.com/p/5509c8ba522b?utm_campaignnode
利用Turtlesim,編寫簡單的消息發佈器和訂閱器bash
1. Twist消息,它的Topic是/cmd_vel,base controler訂閱Twist消息來控制電機, 在終端中執行如下指令查看Twist消息的具體內容oop
rosmsg show geometry_msgs/Twist
2. 編寫一個控制turtlesim的發佈器測試
2.1 Roboware 建立turtlesim package, then add Src Folder including source file talker.cpp對象
#include <ros/ros.h> #include <std_msgs/String.h> #include <geometry_msgs/Twist.h> int main(int argc, char** argv) { ros::init(argc, argv,"talker"); ros::NodeHandle n; ros::Publisher pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 1000); ros::Rate loop_rate(10); while(ros::ok()) { geometry_msgs::Twist msg; msg.linear.x = 1; msg.angular.z = 1; pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } return 0; }
源代碼內重要的部分blog
1. 定義一個publisher類的對象,其中advertise內的參數爲(話題,發佈的緩衝區大小)get
ros::Publisher chatter_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 1000);
2 geometry_msgs::Twist msgcmd
//定義一個twist類消息對象 msg.linear.x = 1; // 設置線速度爲1m/s,正爲前進,負爲後退 msg.angular.z = 1; // 設置角速度爲1rad/s,正爲左轉,負爲右轉
3 pub.publish(msg)博客
經過剛纔建立的publisher對象發佈剛纔建立的twist類對象, 這樣執行完上面的代碼,咱們就能夠將複製好linear和angular參數的twist對象廣播出去,廣播的topic是/turtle1/cmd_vel,也就是turtlesim會自動訂閱的topic.it
運行
1. 運行roscore
2. 運行turtlesim仿真器
rosrun turtlesim turtlesim_node
3. 運行編譯的消息發佈結點
source devel/setup.bash rosrun turrlesim talker
測試效果以下