实现发布者
初始化ROS节点
ros::init(argc,argv, 名称)
向ROS Master注册节点信息,包括发布的话题名和话题中消息类型
ros::Publisher publisher = n.advertise<消息类型>(话题名, 消息队列 10);
按照一定频率循环发布消息
xx.publish(消息);
C++代码编辑编辑完成后
配置CMakeLists.txt
add_executable(可执行文件名 src/xxx.cpp) 设置编译的代码和生成可执行文件
target_link_libraries(可执行文件名 ${catkin_LIBRARIES}) 设置链接库
编译
catkin_make
设置环境变量
source devel/setup.bash
运行
roscore
rosrun turtlesim turtlesim_node
rosrun 功能包名 节点名(即上方可执行文件名)
注意:运行前需要先编译、设置环境变量和运行
***直接输入rosrun 功能包名 节点执行名方式
gedit ~/.bashrc
在.bashrc文件的最下方,输入source ~/catkin_ws/devel/setup.bash
重启终端,运行rosrun ...
velocity_publisher.cpp
// 构建发布者,发布话题turtle1/cmd_vel,消息类型为geometry_msgs::Twist
#include
#include
/**
* 初始化ROS节点
* 向ROS Master注册节点信息,包括发布的话题名和话题的消息类型
* 创建消息数据
* 按照一定频率循环发布消息
*/
int main(int argc, char**argv)
{
// ROS初始化节点
ros::init(argc, argv, "velocity_publisher");
// 创建节点句柄
ros::NodeHandle n;
// 创建Publisher,发布topic为/turtle1/cmd_vel,消息类型为geometry_msgs::Twist,队列长度为10
ros::Publisher turtle_vel_pub = n.advertise("/turtle1/cmd_vel", 10);
// 设置循环频率
ros::Rate loop_rate(10);
int count = 0;
while(ros::ok)
{
// 初始化geometry_msgs::Twist类型的消息
geometry_msgs::Twist vel_msg;
// 线速度为0.5
vel_msg.linear.x = 0.5;
// 沿z轴的角速度为0.2
vel_msg.angular.z = 0.2;
// 发布消息
turtle_vel_pub.publish(vel_msg);
ROS_INFO("Publish turtle velocity command[%0.2f m/s, %0.2f rad/s]", vel_msg.linear.x, vel_msg.angular.z);
// 按照循环频率延时
loop_rate.sleep();
}
return 0;
}
注意***:需要检查python文件属性是否是可执行
安装python3
sudo apt-get install python3
通过软连接,将python链接到python3,链接一次即可
sudo ln -s /usr/bin/python3 /usr/bin/python
chmod 更改或分配文件和目录的权限 +为增加权限
定位到workspace/src/功能包/scripts/
chmod +x xxx.py
python脚本上方添加
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
velocity_publisher.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from geometry_msgs.msg import Twist
def velocity_publisher():
print("查看是否启动")
# ROS节点初始化
rospy.init_node('velocity_publisher', anonymous=True)
# 创建Publisher,发布topic /turtle1/cmd_vel,消息类型为geometry_msg::Twist,队列长度为10
turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
# 设置循环的频率
rate = rospy.Rate(10)
while not rospy.is_shutdown(): // ***注意此有()
# 初始化geometry_msgs::Twist类型的消息
vel_msg = Twist()
vel_msg.linear.x = 0.5
vel_msg.angular.z = 0.3
# 发布消息
turtle_vel_pub.publish(vel_msg)
rospy.loginfo("Publisher turtle velocity command [%0.2f m/s, %0.2f rad/s]", vel_msg.linear.x, vel_msg.angular.z)
# 按照循环频率延时
rate.sleep()
if __name__ == '__main__':
try:
velocity_publisher()
except rospy.ROSInterruptException:
print("发布出现问题,中断错误")
初始化ROS节点
创建订阅者,订阅话题,注册回调函数
循环等待回调函数
回调函数在接收到订阅消息后执行
pose_subscriber.cpp
/*
订阅/turtle1/pose话题,消息类型为turtlesim::pose
*/
#include
#include "turtlesim/Pose.h"
// 接收到订阅消息,进入消息回调函数
void poseCallback(const turtlesim::Pose::ConstPtr & msg)
{
// 打印消息
ROS_INFO("Turtle pose: x:%0.6f, y:%0.6f", msg->x, msg->y);
}
int main(int argc, char **argv)
{
// 初始化ROS节点
ros::init(argc, argv, "pose_subscriber");
// 创建节点句柄
ros::NodeHandle n;
// 创建subscriber,订阅topic /turtle1/pose,注册回调函数
ros::Subscriber pose_sub = n.subscribe("/turtle1/pose", 10, poseCallback);
// 循环等待回调函数
ros::spin();
return 0;
}
pose_subscriber.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from turtlesim.msg import Pose
def pose_Callback(msg):
rospy.loginfo("Turtle pose: x: %0.6f, y: %0.6f", msg.x, msg.y)
def pose_subscribe():
# 初始化ROS节点
rospy.init_node('pose_subscriber', anonymous=True)
# 定义发布者
rospy.Subscriber("/turtle1/pose", Pose, pose_Callback)
# 循环等待回调函数
rospy.spin()
if __name__ == '__main__':
pose_subscribe()
步骤:
1、定义msg文件
2、package.xml中添加功能包依赖
3、在CMakeList.txt中添加编译选项
find_package(catkin REQUIRED roscpp rospy std_msgs geometry_msgs message_generation)
add_message_files(FILES Person.msg)
generate_message(DEPENDENCIES std_msgs geometry_msgs)
catkin_package(... CATKIN_DEPENDS message_runtime geometry_msgs roscpp rospy std_msgs)
include_directories(include ${catkin_INCLUDE_DIRS})
在package.xml中添加
catkin
geometry_msgs
roscpp
rospy
std_msgs
message_generation
message_runtime
geometry_msgs
roscpp
rospy
std_msgs
message_generation
message_runtime
geometry_msgs
roscpp
rospy
std_msgs
message_generation
message_runtime 4、编译 catkin_make
5、创建自定义话题发布者、订阅者代码
CMakeList.txt中
add_execte(执行节点名 xxx.cpp)
target_link_liberaries(执行节点名 ${catkin_LIBRARIES})
add_dependencies(执行节点名 ${PROJECT_NAME}_generate_messages_cpp})
6、编译 catkin_make
创建msg文件
touch Person.msg
注意:如果没有引入Person.h头文件,则需要在VSCode的C/C++编辑中,增加xxx/catkin_ws/**
Person_Publisher.cpp
#include
#include "learning_topic/Person.h"
int main(int argc, char**argv)
{
// 初始化节点
ros::init(argc, argv, "person_publisher");
// 创建节点句柄
ros::NodeHandle n;
// 创建发布者,发布topic名为person_info,类型为Person,队列长度为10
ros::Publisher person_info_pub = n.advertise("/person_info", 10);
// 设置循环频率
ros::Rate loop_rate(10);
int count = 0;
while (ros::ok)
{
// 初始化learning_topic::Person类型消息
learning_topic::Person person_msg;
person_msg.name = "Tom";
person_msg.age = 18;
person_msg.sex = learning_topic::Person::male;
// 发布消息
person_info_pub.publish(person_msg);
ROS_INFO("publish Person Info-- name:%s age:%d sex:%d", person_msg.name.c_str(), person_msg.age, person_msg.sex);
// 按照循环频率延时
loop_rate.sleep();
}
return 0;
}
Person_subscriber.cpp
#include
#include "learning_topic/Person.h"
void personInfoCallBack(const learning_topic::Person::ConstPtr& msg)
{
// 接收订阅消息后进入回调函数,打印接收到的消息
ROS_INFO("Subscribe Person Info: name %s age %d sex %d", msg->name.c_str(), msg->age, msg->sex);
}
int main(int argc, char** argv)
{
// 初始化ROS节点
ros::init(argc, argv, "person_subscriber");
// 构建节点句柄
ros::NodeHandle n;
// 构建订阅者,订阅topic为/person_info,消息队列为10
ros::Subscriber person_info_sub = n.subscribe("/person_info", 10, personInfoCallBack);
// 循环等待回调函数
ros::spin();
return 0;
}
python代码
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from learning_topic.msg import Person
def info_publisher():
# 初始化ROS节点
rospy.init_node('person_publisher', anonymous=True)
# 构建Publisher,topic为 /person_info,类型为Person,队列大小为10
person_info_pub = rospy.Publisher("/person_info", Person, queue_size=10)
# 设置循环频率
rate = rospy.Rate(10)
while not rospy.is_shutdown():
# 初始化learning_topic功能包中Person类型消息
person_msg = Person()
person_msg.name = 'Tom'
person_msg.age = 10
person_msg.sex = Person.male
# 发布消息
person_info_pub.publish(person_msg)
rospy.loginfo("Publish person message [%s, %d, %d]", person_msg.name, person_msg.age, person_msg.sex)
# 按照循环频率延时
rate.sleep()
if __name__ == '__main__':
try:
info_publisher()
except rospy.ROSInterruptException:
print("执行错误,中断运行")
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from learning_topic.msg import Person
def personInfoCallBack(msg):
# 收到消息,显示数据
rospy.loginfo("Person subscribe get name:%s age:%d sex:%d]", msg.name, msg.age, msg.sex)
def person_subscribe():
# 初始化节点
rospy.init_node('person_subscriber', anonymous=True)
# 构建订阅者,订阅topic /person_info,消息类型为Person
rospy.Subscriber("/person_info", Person, personInfoCallBack)
# 循环等待回调函数
rospy.spin()
if __name__ == '__main__':
person_subscribe()