之前草草的“过了”下ros的基本操作,没有好好实践,这次重新记录下自己的实践主要步骤,方便下次再切换工作时快速捡起来:
此贴仅供个人参考~ 更多 直接移步 ros doc 官网
。。。。。。
工作空间: ~/catkin_ws/
代码一般放在: ~/catkin_ws/ src/
在~/catkin_ws/ src/
下面快速创建个功能包: (命令 + 包名 + 依赖包名 )
$catkin_create_pkg test_pkg_retro std_msgs rospy roscpp
$cd ../ (到工作空间 ~/catkin_ws/下 )
$ catkin_make
$ source ./devel/setup.bash
$ rospack list 可以看到 这个 包了
$ roscd test_pkg_retro
$ mkdir scripts
在scripts下书写代码(节点这些)
快速写一个发布节点,
topic 叫:'chatting_topic'
node 名字叫:talker_node (实际启动后会随机添加后缀名,这是 ros里避免重名的操作)
#! /usr/bin/python
from numpy import rate
import rospy
from std_msgs.msg import String
def talker():
pub = rospy.Publisher('chatting_topic',String, queue_size=10)
rospy.init_node('talker_node', anonymous=True)
rate = rospy.Rate(10) # 10 hz
while not rospy.is_shutdown():
hi_str = "hi this is a new publisher...%s " % rospy.get_time()
rospy.loginfo('publish a new msg! %s' % hi_str)
pub.publish(hi_str)
rate.sleep()
if __name__ == "__main__":
try:
talker()
except rospy.ROSInterruptException:
pass
运行节点:
$ chmod +x talker.py # 这个很重要,必须确保 talker.py具有可执行权限
$rosrun test_pkg_retro talker.py
下面快速写一个 订阅(subscrpber):
在运行发布者之后,可通过
$ rostopic echo /chatting_topic
查看topic 发布的消息
#!/usr/bin/python
import rospy
from std_msgs.msg import String
def callback_func(data):
# data.data
# data is the variable passed in
# .data means the datatype is String
# rosmsg show std_msgs/String
# String class include one element data
rospy.loginfo('I received the msg: %s' % data.data)
def listener_node():
rospy.init_node('listener_node',anonymous=True)
rate = rospy.Rate(10)
rospy.Subscriber("chatting_topic", String, callback_func)
# this is similar to rospy.spin
#while not rospy.is_shutdown():
# rate.sleep()
rospy.spin()
if __name__ == "__main__":
try:
listener_node()
except rospy.ROSInterruptException:
pass
修改包内的CMakeLists.txt
将新写的 talker 与listener 脚本名称更新上去
catkin_install_python(PROGRAMS
scripts/talker.py
scripts/listener.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
重新构建一次 ,切换到工作空间目录 ~/catkin_ws/
$catkin_make
$ source ./devel/setup.bash
运行订阅者
$ rosrun test_pkg_retro listener.py
如果此时关掉发布者节点,订阅者不再接收到消息,但此时通过
$rostopic pub /chatting_topic std_msgs/String "nihao"
来发布一条消息到 /chatting_topic 主题上来,订阅者则可以收到。
发布者与订阅者快速回顾完毕!
-----------------------------------------------
--------- 新增msg的定义与使用 ----------------
在test_pkg_retro下新建 msg 文件夹并创建HelloMsg.msg空文件
写入内容:
String Name
int32 Age
float32 score
需要修改包中设置:
1)package.xml
对以下两行内容去掉注释:
<build_depend>message_generation</build_depend> <exec_depend>message_runtime</exec_depend>
2)去掉注释的行,并加入“message_generation” 找到对应包
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs message_generation )
3)catkin 编译的依赖:
catkin_package( ... CATKIN_DEPENDS message_runtime ... (手动加入) ...)
4)增加文件
add_message_files( FILES HelloMsg.msg )
5)取消注释:
generate_messages( DEPENDENCIES std_msgs )
在使用时:py脚本中:
from test_pkg_retro.msg import HelloMsg
# 建立一个消息类型(HelloMsg)的对象
# 参数顺序与 HelloMsg.msg中的顺序相同
data_transition = HelloMsg('cc',22,23.2)