当前位置:网站首页>2021-07-18 ROS笔记-基础和通讯
2021-07-18 ROS笔记-基础和通讯
2022-06-11 00:29:00 【萧易风船长】
我的ROS是noetic版,语言是Python,Ubuntu是20.04
下面说一些遇到过的坑,以及一些经验
关于Linux的简单使用
创建文件
这样比较方便
>>1.py
echo "int a">>1.py
还可以用vim等
创建文件夹
mkdir <name>
移动
mv [option] <source> <target>
其中[option] -f 是强制
-i 是会问你要不要
删除
rm [option] <name>
其中[option] -f 是强制
-i 是会问你要不要
-r 是递归删除所有子文件
拷贝
cp <source> <target>
换行
\
关于配置环境
创建功能包
因为功能包的结构比较固定,所以建起来麻烦,需要直接调用系统命令
cd ~/catkin_ws/src
catkin_create_pkg <name> [depend1] [depend2] [depend3]
编译工作空间和设置环境变量
cd ~/catkin_ws
catkin_make
. ./devel/setup.bash或source ./devel/setup.bash
注意:这里的环境变量只在当前终端有效,如果希望环境变量在所有终端有效
echo "source /WORKSPACE/devel/setup.bash">>~/.bashrc
WORKSPACE表示工作空间路径
小知识:在linux里,~表示home,/表示根目录
查看工作位置
echo $ROS_PACKAGE_PATH
小知识:$通常在程序里表示变量
关于Python脚本
有些python脚本是不带后缀.py的,而有些是带的,用的时候要看清楚 不然会报错
修改默认Python版本
ROS相关库默认安装在Python3下面,而Ubuntu默认打开的版本是python2,需要如下修改
echo alias python=python3 >> ~/.bashrc
并立即执行
. ~/.bashrc
其中alias是表示等价命令
.bashrc是系统的隐藏文件,用于用户的自定义命令,对所有的命令行窗口都会生效
关于包里的代码在哪和roscp使用的说明
写在包目录下的scripts文件夹的自定义文件 可以直接被这样运行
rosrun beginner_tutorials talker.py
而包自带的文件在比如/opt/ros/noetic/share/rospy_tutorials/005_add_two_ints里
不可以被直接这样运行
rosrun beginner_tutorials add_two_ints_server.py(错)
需要拷出来
roscd beginner_tutorials/
roscp rospy_tutorials add_two_ints_server scripts/add_two_ints_server.py
roscp rospy_tutorials add_two_ints_client scripts/add_two_ints_client.py
roscp可以递归遍历一个文件夹下面所有文件
roscd可以直接cd到一个包里,不需要绝对目录
使用自定义消息
CMakeList里这个命令写在最前面
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation
)
然后要写
add_service_files(
FILES
AddTwoInts.srv
)
add_message_files(
FILES
Num.msg
)
generate_messages(
DEPENDENCIES
std_msgs
)
catkin_package(
…
CATKIN_DEPENDS message_runtime …
…)
等
xml文件里下面的去除注释
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
在做完相应工作后,python脚本里如下引用即可
from std_msgs.msg import String
from beginner_tutorials.msg import Num
上面那句是标准消息功能包里的基础消息 String,只包含一个成员,即data,用于存字符串的信息
下面那句是在自定义包beginner_tutorials的msg文件夹里的Num.msg文件
里面写了
int64 num
通信机制介绍
主要有[gugugu]
使用publisher
import rospy
from std_msgs.msg import String
def talker():
pub = rospy.Publisher('chatter', String, queue_size=10)
rospy.init_node('talker', anonymous=True)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
hello_str = "hello world %s" % rospy.get_time()#感觉%s和后面的% 可以被替代为+
rospy.loginfo(hello_str)#打印到屏幕上
pub.publish(hello_str)
rate.sleep()#delay
#防止中间退出增强鲁棒性
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
使用 subsriber
import rospy
from std_msgs.msg import String
def callback(data):
rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)#打印到屏幕
def listener():
# In ROS, nodes are uniquely named. If two nodes with the same
# name are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'listener' node so that multiple listeners can
# run simultaneously.
rospy.init_node('listener', anonymous=True)
# 同一个topic “chatter”下
rospy.Subscriber("chatter", String, callback)#注册callback作为回调函数
# spin() simply keeps python from exiting until this node is stopped
# 防止程序中间退出 增强鲁棒性
rospy.spin()
if __name__ == '__main__':
listener()
使用server
#!/usr/bin/env python3
## Simple demo of a rospy service that add two integers
NAME = 'add_two_ints_server'
# import the AddTwoInts service
from rospy_tutorials.srv import *
import rospy
def add_two_ints(req):
print("Returning [%s + %s = %s]" % (req.a, req.b, (req.a + req.b)))
return AddTwoIntsResponse(req.a + req.b)
def add_two_ints_server():
rospy.init_node(NAME)
s = rospy.Service('add_two_ints', AddTwoInts, add_two_ints)
# spin() keeps Python from exiting until node is shutdown
rospy.spin()
if __name__ == "__main__":
add_two_ints_server()
另一种写法
#!/usr/bin/env python
from __future__ import print_function
from beginner_tutorials.srv import AddTwoInts,AddTwoIntsResponse
import rospy
def handle_add_two_ints(req):
print("Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b)))
return AddTwoIntsResponse(req.a + req.b)
def add_two_ints_server():
rospy.init_node('add_two_ints_server')
s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
print("Ready to add two ints.")
rospy.spin()
if __name__ == "__main__":
add_two_ints_server()
使用client
#!/usr/bin/env python3
## Simple demo of a rospy service client that calls a service to add
## two integers.
import sys
import os
import rospy
# imports the AddTwoInts service
from rospy_tutorials.srv import *
## add two numbers using the add_two_ints service
## @param x int: first number to add
## @param y int: second number to add
def add_two_ints_client(x, y):
# 可以不用initial初始化 因为service不一定要是节点 是随时发起的
# NOTE: you don't have to call rospy.init_node() to make calls against
# a service. This is because service clients do not have to be
# nodes.
# block until the add_two_ints service is available
# you can optionally specify a timeout
rospy.wait_for_service('add_two_ints')
try:
# create a handle to the add_two_ints service
add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
print("Requesting %s+%s"%(x, y))
# simplified style
resp1 = add_two_ints(x, y)
# formal style
resp2 = add_two_ints.call(AddTwoIntsRequest(x, y))
if not resp1.sum == (x + y):
raise Exception("test failure, returned sum was %s"%resp1.sum)
if not resp2.sum == (x + y):
raise Exception("test failure, returned sum was %s"%resp2.sum)
return resp1.sum
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
def usage():#输出用法
return "%s [x y]"%sys.argv[0] #argv[0]表示文件名
if __name__ == "__main__":
argv = rospy.myargv()
if len(argv) == 1:#无输入
import random
x = random.randint(-50000, 50000)
y = random.randint(-50000, 50000)
elif len(argv) == 3:
try:
x = int(argv[1])
y = int(argv[2])
except:
print(usage())
sys.exit(1)
else:
print(usage())
sys.exit(1)
print("%s + %s = %s"%(x, y, add_two_ints_client(x, y)))
另一种写法
#!/usr/bin/env python
from __future__ import print_function
import sys
import rospy
from beginner_tutorials.srv import *
def add_two_ints_client(x, y):
rospy.wait_for_service('add_two_ints')
try:
add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
resp1 = add_two_ints(x, y)
return resp1.sum
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
def usage():
return "%s [x y]"%sys.argv[0]
if __name__ == "__main__":
if len(sys.argv) == 3:
x = int(sys.argv[1])
y = int(sys.argv[2])
else:
print(usage())
sys.exit(1)
print("Requesting %s+%s"%(x, y))
print("%s + %s = %s"%(x, y, add_two_ints_client(x, y)))
写完py文件后的配置
添加权限使其被标记为可执行
chmod +x scripts/add_two_ints_server.py
对于这个命令的解释,详见https://blog.csdn.net/u012106306/article/details/80436911
然后在CMakeList文件里添加
catkin_install_python(PROGRAMS scripts/add_two_ints_server.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
确保安装正确脚本和使用正确的解释器
rosbag 对通信的记录和回放
rostopic list -v
显示正在使用的主题
cd ~/bagfiles
rosbag record -a
a表示all
rosbag record /topic_name1 /topic_name2 /topic_name3
对感兴趣的topic记录,topic的表示是斜杠加topic名
rosbag record -O filename.bag /topic_name1
指定文件名
边栏推荐
- SAS factor analysis (proc factor process, factor rotation and regression method for factor score function)
- 【ROS】ROSmsg cakin_ Make compilation error
- How to download web photos
- ROS参数服务器
- Project_ Visual analysis of epidemic data based on Web Crawler
- PX4装机教程(六)垂起固定翼(倾转)
- How about compound interest insurance and financial products? Can I buy it?
- Uninstall mavros
- Implementing MySQL fuzzy search with node and express
- CSRF attack
猜你喜欢

Px4 installation tutorial (VI) vertical fixed wing (tilting)

How to use user-defined annotation for parameter verification
![[VBA Script] extract the information and pending status of all annotations in the word document](/img/dc/0db51d092cde019cef4113796e4882.png)
[VBA Script] extract the information and pending status of all annotations in the word document

中间件_Redis_06_Redis的事务

对象存储 S3 在分布式文件系统中的应用

2.1 ros+px4 simulation - Fixed Point flight control

项目_基于网络爬虫的疫情数据可视化分析

OCR文字识别经典论文详解

Once you know these treasure websites, you can't live without them!!!

Daily problem essay | 21.11.29: use resttemplate to call external put request, and prompt '400 bad request'
随机推荐
Merge sort and cardinality sort
How much is the bonus of China Patent Award, with a subsidy of 1million yuan
There is a problem with numpy after CONDA installs pytoch
[ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design
中间件_Redis_06_Redis的事务
Bad RequestThis combination of host and port requires TLS.
部分 力扣 LeetCode 中的SQL刷题整理
Hooks' design philosophy
Clean up the broken artifacts data (.lastUpdated files) and reload the project. Problem resolution
SAS聚类分析(系统聚类cluster,动态聚类fastclus,变量聚类varclus)
函数的节流和防抖
Leetcode string problem
Digital IC Design self-study ing
云呐|PDA无线固定资产盘点管理系统
SAS discriminant analysis (Bayes criterion and proc discrim process)
IRS application release 15: application security self test guide
项目_基于网络爬虫的疫情数据可视化分析
How about compound interest insurance and financial products? Can I buy it?
CSRF攻击
Project_ Visual analysis of epidemic data based on Web Crawler