当前位置:网站首页>2021-07-18 ROS notes - basics and communication
2021-07-18 ROS notes - basics and communication
2022-06-11 01:48:00 【Captain xiaoyifeng】
my ROS yes noetic edition , Language is Python,Ubuntu yes 20.04
Here are some of the pits we have encountered , And some experience
About Linux Simple use
create a file
This is more convenient
>>1.py
echo "int a">>1.py
You can also use vim etc.
Create folder
mkdir <name>
Move
mv [option] <source> <target>
among [option] -f It's compulsory
-i I will ask you if you want to
Delete
rm [option] <name>
among [option] -f It's compulsory
-i I will ask you if you want to
-r Is to recursively delete all sub files
Copy
cp <source> <target>
Line break
\
About configuring the environment
Create Feature Pack
Because the structure of the function pack is relatively fixed , So it is troublesome to build , You need to call system commands directly
cd ~/catkin_ws/src
catkin_create_pkg <name> [depend1] [depend2] [depend3]
Compile workspace and set environment variables
cd ~/catkin_ws
catkin_make
. ./devel/setup.bash or source ./devel/setup.bash
Be careful : The environment variables here are only valid on the current terminal , If you want the environment variable to be valid on all terminals
echo "source /WORKSPACE/devel/setup.bash">>~/.bashrc
WORKSPACE Represents the workspace path
Little knowledge : stay linux in ,~ Express home,/ Represents the root directory
View the working position
echo $ROS_PACKAGE_PATH
Little knowledge :$ Variables are usually represented in programs
About Python Script
There are some python Script without suffix .py Of , And some are with , When you use it, you should see clearly Otherwise, it will report a mistake
Change the default Python edition
ROS Related libraries are installed in by default Python3 below , and Ubuntu The default open version is python2, The following modifications are required
echo alias python=python3 >> ~/.bashrc
And execute immediately
. ~/.bashrc
among alias Is an equivalent command
.bashrc Is the hidden file of the system , Custom commands for users , For all command line windows
About where the code in the package is and roscp Instructions for use
Written in the package directory scripts Folder customization file Can be run directly like this
rosrun beginner_tutorials talker.py
The files included in the package are, for example /opt/ros/noetic/share/rospy_tutorials/005_add_two_ints in
It cannot be run directly like this
rosrun beginner_tutorials add_two_ints_server.py( wrong )
It needs to be copied out
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 You can recursively traverse all the files under a folder
roscd Can directly cd Into a bag , No absolute directory is required
Use custom messages
CMakeList This command is written at the beginning
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation
)
Then write
add_service_files(
FILES
AddTwoInts.srv
)
add_message_files(
FILES
Num.msg
)
generate_messages(
DEPENDENCIES
std_msgs
)
catkin_package(
…
CATKIN_DEPENDS message_runtime …
…)
etc.
xml Remove the comments below the file
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
After finishing the corresponding work ,python The script can be quoted as follows
from std_msgs.msg import String
from beginner_tutorials.msg import Num
The above sentence is the basic message in the standard message function package String, Contains only one member , namely data, Used to store string information
The following sentence is in the custom package beginner_tutorials Of msg In a folder Num.msg file
Write the inside
int64 num
Introduction to communication mechanism
There are mainly [gugugu]
Use 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()# Feeling %s And the back of the % Can be replaced by +
rospy.loginfo(hello_str)# Print it to the screen
pub.publish(hello_str)
rate.sleep()#delay
# Prevent intermediate exit to enhance robustness
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
Use subsriber
import rospy
from std_msgs.msg import String
def callback(data):
rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)# Print to screen
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)
# The same topic “chatter” Next
rospy.Subscriber("chatter", String, callback)# register callback As a callback function
# spin() simply keeps python from exiting until this node is stopped
# Prevent the program from exiting in the middle Robustness enhancement
rospy.spin()
if __name__ == '__main__':
listener()
Use 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()
Another way of writing
#!/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()
Use 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):
# Don't have to initial initialization because service It doesn't have to be a node It is initiated at any time
# 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():# Output usage
return "%s [x y]"%sys.argv[0] #argv[0] For file name
if __name__ == "__main__":
argv = rospy.myargv()
if len(argv) == 1:# No input
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)))
Another way of writing
#!/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)))
finish writing sth. py Configuration after file
Add permissions to make it executable
chmod +x scripts/add_two_ints_server.py
Explanation of this command , See https://blog.csdn.net/u012106306/article/details/80436911
And then in CMakeList Add to file
catkin_install_python(PROGRAMS scripts/add_two_ints_server.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
Make sure you install the correct script and use the correct interpreter
rosbag Recording and playback of communication
rostopic list -v
Show the theme in use
cd ~/bagfiles
rosbag record -a
a Express all
rosbag record /topic_name1 /topic_name2 /topic_name3
Interested in topic Record ,topic Is a slash plus topic name
rosbag record -O filename.bag /topic_name1
Specify a filename
边栏推荐
- [ROS] review of 2021 ROS Summer School
- C语言 深度探究具有不定参数的函数
- threejs:如何获得几何体的boundingBox?
- Once you know these treasure websites, you can't live without them!!!
- 1.6 Px4 initialization calibration
- Leetcode 1814 count nice pairs in an array (recommended by map)
- 2021-3-1MATLAB写cnn的mnist数据库训练
- SAS principal component analysis (finding correlation matrix, eigenvalue, unit eigenvector, principal component expression, contribution rate and cumulative contribution rate, and data interpretation)
- detectron2训练自己的数据集和转coco格式
- Kubernetes binary installation (v1.20.15) (VII) plug a work node
猜你喜欢

Brief description of custom annotations
![[leetcode] reverse linked list II](/img/03/5e4921a8fe50b3489b4b99310d1afb.jpg)
[leetcode] reverse linked list II

Function of barcode fixed assets management system, barcode management of fixed assets

threejs:两点坐标绘制贝赛尔曲线遇到的坑

關於概率統計中的排列組合

The problem of slow response of cs-3120 actuator during use

Loki 学习总结(1)—— Loki 中小项目日志系统的不二之选

Multi interest recall model practice | acquisition technology

PX4从放弃到精通(二十四):自定义机型

Detectron2 trains its own dataset and converts it to coco format
随机推荐
1.6、 PX4初始化校准
What if ROS lacks a package
Matlab array other common operation notes
2022.6.6-----leetcode.732
On permutation and combination in probability and statistics
[ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design
Detailed explanation of classic papers on OCR character recognition
Uninstall mavros
Kubernetes binary installation (v1.20.15) (VII) plug a work node
[mavros] mavros startup Guide
[geometric vision] 4.2 piecewise linear transformation
Leetcode 665 non decreasing array (greedy)
1.7、PX4遥控器校准
[ROS introduction] cmakelist Txt and packages XML interpretation
关于CS-3120舵机使用过程中感觉反应慢的问题
Linux安装mysql数据库详解
1.2、ROS+PX4预备基础知识
Summary of SAS final review knowledge points (notes on Application of multivariate statistics experiment)
1.5、PX4载具选择
1.3 ROS 无人机简介