-
先上圖片:
- 編碼
$cd ~/catkin_ws/
$catkin_create_pkg beginner_tutorials std_msgs rospy roscpp
$cd beginner_tutorials
$mkdir src
$cd src
創(chuàng)建 talker.cpp / listenner.cpp兩個源碼文件
//talker.cpp
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
int main(int argc,char **argv)
{
//名稱talker必須唯五
ros::init(argc,argv,"talker1");
ros::NodeHandle n;
ros::Publisher chatter_pub=n.advertise<std_msgs::String>("message1",1000);
ros::Rate loop_rate(10); //loop_rate 發(fā)送數(shù)據(jù)頻率10Hz
int count=0;
while(ros::ok())
{
std_msgs::String msg;
std::stringstream ss;
ss<< "helo world" <<count;
msg.data=ss.str();
ROS_INFO("%s",msg.data.c_str());
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
//listenner.cpp
#include "ros/ros.h"
#include "std_msgs/String.h"
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("I heard:[%s]",msg->data.c_str());
}
int main(int argc,char **argv)
{
//名稱初始化時要求唯一
ros::init(argc,argv,"listenner1");
ros::NodeHandle n;
//這里訂閱的chatter必須與發(fā)布者一致
ros::Subscriber sub=n.subscribe("message1",1000,chatterCallback);
//spin()是節(jié)點讀取數(shù)據(jù)的消息響應循環(huán)
ros::spin();
return 0;
}
目錄下的CMakelists.txt尾部追加信息
include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
add_dependencies(talker rospubsub_demo_generate_messages_cpp)
add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})
add_dependencies(listener rospubsub_demo_generate_messages_cpp)
- 運行
$source ~/catkin_ws/devel/setup.bash
運行tmux開三個窗口后分別運行下面的程序
$roscore
$rosrun beginner_tutorials talker
$rosrun beginner_tutorials listenner
- 通過rqt_graph看節(jié)點狀態(tài)
$rosrun rqt_graph rqt_graph