First, follow the creation of the workspace of the previous c++ version
Create a new scripts folder under the function package
content
3. Communicate with C++ (decoupling)
1. Implement the publisher
Then create a new python file
Then copy the following code
#! /usr/bin/env python
"""
需求: 实现基本的话题通信,一方发布数据,一方接收数据,
实现的关键点:
1.发送方
2.接收方
3.数据(此处为普通文本)
PS: 二者需要设置相同的话题
消息发布方:
循环发布信息:HelloWorld 后缀数字编号
实现流程:
1.导包
2.初始化 ROS 节点:命名(唯一)
3.实例化 发布者 对象
4.组织被发布的数据,并编写逻辑发布数据
"""
#1.导包
import rospy
from std_msgs.msg import String
if __name__ == "__main__":
#2.初始化 ROS 节点:命名(唯一)
rospy.init_node("talker_p")
#3.实例化 发布者 对象
pub = rospy.Publisher("chatter",String,queue_size=10)
#4.组织被发布的数据,并编写逻辑发布数据
msg = String() #创建 msg 对象
msg_front = "hello 你好"
count = 0 #计数器
# 设置循环频率
rate = rospy.Rate(1)
while not rospy.is_shutdown():
#拼接字符串
msg.data = msg_front + str(count)
pub.publish(msg)
rate.sleep()
rospy.loginfo("写出的数据:%s",msg.data)
count += 1
Add executable permission
Open in integrated terminal, add executable permission
Then modify the configuration file
ctrl+s after modification
Then compile ctrl shift b
then start the terminal
You can see that there is an error
[rospack] Error package not found
This is because there is no source
You can see that there is an error
SyntaxError:Non ASCII
Solution
Remark
Every time you change, recompile
2. Implement the subscriber
create a new file
Enter the following code
#! /usr/bin/env python
"""
需求: 实现基本的话题通信,一方发布数据,一方接收数据,
实现的关键点:
1.发送方
2.接收方
3.数据(此处为普通文本)
消息订阅方:
订阅话题并打印接收到的消息
实现流程:
1.导包
2.初始化 ROS 节点:命名(唯一)
3.实例化 订阅者 对象
4.处理订阅的消息(回调函数)
5.设置循环调用回调函数
"""
#1.导包
import rospy
from std_msgs.msg import String
def doMsg(msg):
rospy.loginfo("I heard:%s",msg.data)
if __name__ == "__main__":
#2.初始化 ROS 节点:命名(唯一)
rospy.init_node("listener_p")
#3.实例化 订阅者 对象
sub = rospy.Subscriber("chatter",String,doMsg,queue_size=10)
#4.处理订阅的消息(回调函数)
#5.设置循环调用回调函数
rospy.spin()
The reason for this error is because no permissions have been added
Just add permissions
Then
Note that in communication: the subscriber needs to register in the master before receiving data. At this time, it is easy to appear that the first few messages of the publisher have been sent, but the receiver has not received it.
Then look at the calculation graph
3. Communicate with C++ (decoupling)
Files written in different languages in ros can communicate as long as the topic is the same
The topic is changed to fang
Then start the c++ publisher
Then start the python subscriber
Restart the calculation graph
You can see that Ergouzi is associated with listener_p
So you can see that ROS is very powerful