程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Ros- create a new workspace, function pack, use c++, python language to write publish and Subscribe Communication

編輯:Python

List of articles

  • 1、 Create workspaces and feature packs
    • 1.1 working space
      • 1.1.1 Introduction to the workspace
      • 1.1.2 Create a workspace
      • 1.1.3 Compile workspace
    • 1.2 Function pack
      • 1.2.1 Introduction to function pack
      • 1.2.1 Creation of function package
      • 1.2.2 Compilation of function package
      • 1.2.3 The meaning of the files in the function pack
      • 1.2.4 Set the environment variable
  • 2、 Publisher Publisher The implementation of the
    • 2.1 Implemented topic model
    • 2.2 Create feature packs and write code
    • 2.3 Modify the file and compile
    • 2.4 Run the feature pack and view the nodes
    • 2.5 utilize python Script run
  • 3、 subscriber Subscriber The implementation of the
    • 3.1 Implementation model
    • 3.2 Create subscriber code c++
    • 3.3 utilize python Script implementation
      • Welcome to pay attention to wechat work number , Push articles more timely .

1、 Create workspaces and feature packs

1.1 working space

1.1.1 Introduction to the workspace

  • A workspace is a folder where files related to engineering development are stored . It includes
    • src: Code space ( Used to store the source code of the function package )
    • build: Compilation space ( Compile process file , Usually binary files )
    • devel: Development space
    • install: Installation space

1.1.2 Create a workspace

  • 1、 Create a file directory to store files . among catkin_ws Is the name of the workspace , You can change , But there must be... Under the workspace src, Can't change .
mkdir -p ~/catkin_ws/src
  • 2、 open src Catalog .
cd ~/catkin_ws/src
  • 3、 Only after the environment variables are configured can catkin_init_worksapce, You can enter catkin_init_worksapce Try . If you are prompted that you cannot install catkin Add environment variables .
echo "source /opt/ros/melodic/setup.bash" >> ~/.bashrc
source ~/.bashrc
  • 4、 The final will be SRC The directory becomes a spatial attribute .
catkin_init_worksapce

1.1.3 Compile workspace

  • 1、 Go back to the workspace root directory , Direct basis SRC The directory makelists File compilation empty workspace
cd ~/catkin_ws
catkin_make
  • 2、 At this point, a build,devel Folder .install Folders need a separate command to generate .
catkin_make install
 At this point install Folder

1.2 Function pack

1.2.1 Introduction to function pack

  • After the workspace is created, you can create a function package , There can be multiple function packs in a workspace, most of which are placed in src in . When too many function packages are designed, multiple workspaces can be divided according to types .

1.2.1 Creation of function package

  • catkin_create_pkg command
/* catkin_create_pkg The command will ask you to enter package_name, If necessary, you can add some dependencies later Other packages for :catkin_create_pkg <package_name> [depend1] [depend2] [depend3] */
// go back to src Under the table of contents , Create a demo Function pack , rely on std_msgs rospy roscpp These function packages .
cd ~/catkin_ws/src
catkin_create_pkg demo std_msgs rospy roscpp
/* Create demo Folder , And generate folders and files in it . std_msgs yes ros Some standard software packages , Such as int、bool rospy You can call python The interface of , Conduct python To write roscpp You can call c++ The interface of , Conduct c++ To write */

1.2.2 Compilation of function package

  • The compilation of function packages is the same as that of workspaces .
// Go back to the workspace root directory , Direct basis SRC The directory makelists File compilation empty workspace , Including the function package under the space .
cd ~/catkin_ws
catkin_make

1.2.3 The meaning of the files in the function pack

  • include It's for storage. c++ The header file
  • src Is to store source code files
  • CMakeLists.txt It is the rule of function package compilation , utilize CMAKE grammar , Compile dependent function packages 、 Generate executable files .
  • package.xml yes html Information about language compilation and feature packs , name 、 Version number 、 Description information 、 Maintainer information 、lincense( Open source license )、 Dependent information ( It can be modified later )

1.2.4 Set the environment variable

  • 1、 First look at the environment variables
echo $ROS_PACKAGE_PATH
/* result : /opt/ros/melodic/share There is no search path for the new workspace , If not, you cannot complete the newly created function package , Can't use roscd Wait for the order . */
  • 2、 Add workspace path
source ~/catkin_ws/devel/setup.bash
  • 3、 Detecting environment variables
echo $ROS_PACKAGE_PATH
/* result : /home/ubuntu/catkin_ws/src:/opt/ros/melodic/share */

2、 Publisher Publisher The implementation of the

2.1 Implemented topic model

  • There are two main nodes , One is a turtle simulator 、 One needs to be implemented Publisher The node of , Release a topic to control the movement of the simulator turtle through the program .
  • Publisher Publish a Message The message type is geometry_msgs::Twist These include linear velocity and angular velocity , adopt turtle1/cmd_vel topic of conversation , Then turtle subscribed to this topic , Further control the position of the turtle in the simulator .

2.2 Create feature packs and write code

  • 1、 Enter the workspace src in .
cd ~/catkin_ws/src/
  • 2、 Create Feature Pack
$ catkin_create_pkg learning_topic roscpp rospy std_msgs geometry_msgs turtlesim
/* result : rospy std_msgs geometry_msgs turtlesim Created file learning_topic/package.xml Created file learning_topic/CMakeLists.txt Created folder learning_topic/include/learning_topic Created folder learning_topic/src Successfully created files in /home/ubuntu/catkin_ws/src/learning_topic. # Please adjust the values in package.xml. */
  • 3、 Enter the newly created function pack .
$ cd ~/catkin_ws/src/learning_topic
/* It contains CMakeLists.txt and package.xml Document and src include Two folders */
  • 4、 Open the src establish cpp File programming .
$ cd src
$ touch velocity_publisher.cpp
$ gedit velocity_publisher.cpp
  • 5、 Content :
// The header file 
#include <ros/ros.h>// relevant ros in API The file of , Function definition 
#include <geometry_msgs/Twist.h>// A library of linear and angular velocities 
// The main function 
int main(int argc,char **argv)
{

// Complete node initialization .velocity_publisher Is the node name 
ros::init(argc,argv,"velocity_publisher");
// New node handle , management API Related resources .
ros::NodeHandle n;
// establish publisher, Define a publisher , Node handle advertise< The type of message published >(“ The topic name of the release purpose ”, Equivalent to cache , If it cannot be sent out for queue storage , If the sending speed is slow , Clear the old data , Keep the latest data )
//advertise Will return a ros::Publisher Type value , Use the return value to control the publishing of messages , Refuse to publish when the published message type is wrong 
ros::Publisher turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel",10);
// Set the cycle frequency 10hz
ros::Rate loop_rate(10);
// Cycle through 
while(ros::ok)
{

// Set the initialization and content of the published message type 
geometry_msgs::Twist vel_msg;
vel_msg.linear.x = 0.5;
vel_msg.angular.z = 0.2;
// Release the news 
turtle_vel_pub.publish(vel_msg);
// Print 
ROS_INFO("Publisher turtle velocity command[%0.2f m/s,%0.2f rad/s]",vel_msg.linear.x,vel_msg.angular.z);
// The delay is carried out according to the set frequency .
loop_rate.sleep();
}
return 0;
}
/* Release a summary of the news : 1、 initialization ros node ros::init(argc,argv," The name of the node "); 2、 Create node handle ros::NodeHandle n; 3、 establish publisher It includes the type, purpose, topic and storage size of the published message ros::Publisher advertise The return value of = n.advertise< Message type >(" Purpose topic ", Queue storage size ); 4、 Create the content of the message type Message type initialization and assignment 5、 Publish at a certain frequency ros::Rate loop_rate(10); while(ros::ok) { advertise The return value of .publish(vel_msg); loop_rate.sleep(); } */

2.3 Modify the file and compile

  • 1、 modify package.xml.
    • Because the creation dependency is increased when creating the function package , This will automatically generate , If the dependency is not adjusted during creation or other dependencies need to be added for later programming, it can be modified .
  • 2、 modify CMakeLists.txt. Add the following code
# take velocity_publisher.cpp Translate it into velocity_publisher Executable file
add_executable(velocity_publisher src/velocity_publisher.cpp)
# Executables and ROS Link to the library of
target_link_libraries(velocity_publisher
${catkin_LIBRARIES}
)
  • 3、 Go back to the workspace and compile
$ cd ~/catkin_ws/

2.4 Run the feature pack and view the nodes

  • 1、 Modify environment variables . For the... Under the user directory .bashrc File modification .
gedit ~/.bashrc
# Add a path after opening 
# The first one should be added during installation 
# The second item should be added in the creation workspace . If both exist, there is no need to add .
source /opt/ros/melodic/setup.bash
source /home/ubuntu/catkin_ws/devel/setup.bash
# If you only need to add environment variables temporarily, you can use source command , Valid only at the current terminal 
# source /home/ubuntu/catkin_ws/devel/setup.bash
  • 2、 function ros System , And required nodes
# Create a terminal to run ros System 
$ roscore
# Then create a simulation node for the terminal running turtle 
$ rosrun turtlesim turtlesim_node
# Create a terminal to run the just written velocity_publisher node 
$ rosrun learning_topic velocity_publisher
  • 3、 The phenomenon , The turtle moves according to the instructions sent .
  • 4、 View node communication status .
# Create another terminal , View the visual calculation diagram 
$ rqt_graph
  • 5、 End out rosout Nodes outside ,
rosnode kill -a

2.5 utilize python Script run

  • 1、 Open the function package to create and store python Folders and files , And modify file permissions
$ roscd learning_topic/
$ mkdir scripts
$ cd scripts
$ touch velocity_publisher.py
# Remember to modify the file permissions after creation , Otherwise, it is impossible to compile , Node package not found 
chmod +x velocity_publisher.py
  • 2、 Programming .
$ gedit velocity_publisher.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Make sure the script acts as Python Script execution code and format utf-8
import rospy# utilize python Modules that must be imported 
from geometry_msgs.msg import Twist# Modules of message types that need to be utilized 
# Define a function 
def velocity_publisher():
# Initialize node ,velocity_publisher As the node name ,anonymous = True Will cause random numbers to be added to the end of the name ( Time stamp ), To ensure that the node has a unique name 
rospy.init_node('velocity_publisher', anonymous=True)
# /turtle1/cmd_vel It is the topic that the node message type is published to .Twist The message type published by this node .queue_size When the subscriber does not receive the message fast enough , Limit the number of messages queued 
turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
# Rate cycling . Its parameters are 10, That means you want it to cycle every second 10 Time ( As long as our processing time does not exceed one tenth of a second )!
rate = rospy.Rate(10)
while not rospy.is_shutdown():# see is_shutdown() To check whether the program should exit ( For example, there are Ctrl+C Or others )
# Initialize the message type variable and assign a value 
vel_msg = Twist()
vel_msg.linear.x = 0.5
vel_msg.angular.z = 0.2
# It publishes a message type variable to the target topic . 
turtle_vel_pub.publish(vel_msg)
# loginfo To print messages to the screen ; Write the message to the log file of the node ; write in rosout
rospy.loginfo("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]", vel_msg.linear.x, vel_msg.angular.z)
# The part of the loop also calls rate.sleep(), It can use just the right amount of sleep time to maintain the desired rate during the cycle . 
rate.sleep()
if __name__ == '__main__':
try:
# Call function 
velocity_publisher()
except rospy.ROSInterruptException:
pass
  • 4、 Recompile the workspace , about python No need
$ cd ~/catkin_ws
$ catkin_make
  • 5 Its operation and c++ It's basically the same , Finally, when you need to call learning_topic Of velocity_publisher.py.
# If you can't run find ,python Whether the file modification permission can be executed 
rosrun learning_topic velocity_publisher.py
  • 6、 When put python Node names in do not add time stamps , and c++ The same name , When both need to run, they find that they will squeeze each other out

3、 subscriber Subscriber The implementation of the

3.1 Implementation model

  • Published by turtle Simulator , Subscribers are subscribers that need to be implemented , adopt /turtle1/pose The node of receives the message sent by the turtle simulator turtlesim::Pose Message type content of .

3.2 Create subscriber code c++

  • 1、 Open the function pack file, create a file and edit
$ cd ~/catkin_ws/src/learning_topic/src
$ touch pose_subscriber.cpp
$ gedit pose_subscriber.cpp

// The header file 
#include <ros/ros.h>
#include "turtlesim/Pose.h"
void PoseCallback(const turtlesim::Pose::ConstPtr& msg)
{

// The callback function should not take too long .
ROS_INFO("Turtle pose:x:%0.6f,y:%0.6f",msg->x,msg->y);
}
// The main function 
int main(int argc,char **argv)
{

// Initialize node 
ros::init(argc,argv,"posr_subscriber");
// Create handle 
ros::NodeHandle n;
// establish subscribe Subscriber type for , Callback function PoseCallback Is called when the subscribed topic is published 
ros::Subscriber pose_sub = n.subscribe("/turtle1/pose",10,PoseCallback);
// Loop waiting for , Keep checking the queue , Call the above calling function if there is data .
ros::spin();
// In principle, the return value... Will not be executed 
return 0;
}
/* subscriber : 1、 Initialize node ros::init 2、 Create handle ros::NodeHandle 3、 Write callback function PoseCallback(const turtlesim::Pose::ConstPtr& msg) 4、 Create subscribers , And ros::spin(); Call the callback function when there is subscription information */
  • 2 Modify the configuration file
$ gedit ~/catkin_ws/src/learning_topic/CMakeLists.txt
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber
${catkin_LIBRARIES}
)
  • 3 Run to check the phenomenon
$ roscore
$ rosrun turtlesim turtlesim_node
$ rosrun py_learning_topic py_velocity_publisher.py
$ rosrun learning_topic pose_subscriber

3.3 utilize python Script implementation

  • 1、 Open and store python Folders and files , And modify file permissions
$ roscd learning_topic/
$ cd scripts
$ touch pose_subscriber.py
# Remember to modify the file permissions after creation , Otherwise, it is impossible to compile , Node package not found 
chmod +x pose_subscriber.py
  • 2、 Programming .
$ gedit pose_subscriber.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from turtlesim.msg import Pose
def poseCallback(msg):
rospy.loginfo("Turtle pose: x:%0.6f, y:%0.6f", msg.x, msg.y)
def pose_subscriber():
# ROS Node initialization 
rospy.init_node('pose_subscriber', anonymous=True)
# Create a Subscriber, The subscription is called /turtle1/pose Of topic, Register callback function poseCallback
rospy.Subscriber("/turtle1/pose", Pose, poseCallback)
# Loop waiting for callback function 
rospy.spin()
if __name__ == '__main__':
pose_subscriber()
  • 4、 Recompile the workspace , about python No need
$ cd ~/catkin_ws
$ catkin_make
  • 5 Its operation and c++ It's basically the same , Finally, when you need to call learning_topic Of pose_subscriber.py.
# If you can't run find ,python Whether the file modification permission can be executed 
rosrun learning_topic velocity_publisher.py
  • 6、 When put python Node names in do not add time stamps , and c++ The same name , When both need to run, they find that they will squeeze each other out

Welcome to pay attention to wechat work number , Push articles more timely .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved