mkdir -p ~/catkin_ws/src
cd ~/catkin_ws/src
echo "source /opt/ros/melodic/setup.bash" >> ~/.bashrc
source ~/.bashrc
catkin_init_worksapce
cd ~/catkin_ws
catkin_make
catkin_make install
At this point install Folder
/* 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 */
// 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
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 . */
source ~/catkin_ws/devel/setup.bash
echo $ROS_PACKAGE_PATH
/* result : /home/ubuntu/catkin_ws/src:/opt/ros/melodic/share */
cd ~/catkin_ws/src/
$ 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. */
$ cd ~/catkin_ws/src/learning_topic
/* It contains CMakeLists.txt and package.xml Document and src include Two folders */
$ cd src
$ touch velocity_publisher.cpp
$ gedit velocity_publisher.cpp
// 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(); } */
# 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}
)
$ cd ~/catkin_ws/
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
# 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
# Create another terminal , View the visual calculation diagram
$ rqt_graph
rosnode kill -a
$ 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
$ 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
$ cd ~/catkin_ws
$ catkin_make
# If you can't run find ,python Whether the file modification permission can be executed
rosrun learning_topic velocity_publisher.py
$ 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 */
$ gedit ~/catkin_ws/src/learning_topic/CMakeLists.txt
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber
${catkin_LIBRARIES}
)
$ roscore
$ rosrun turtlesim turtlesim_node
$ rosrun py_learning_topic py_velocity_publisher.py
$ rosrun learning_topic pose_subscriber
$ 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
$ 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()
$ cd ~/catkin_ws
$ catkin_make
# If you can't run find ,python Whether the file modification permission can be executed
rosrun learning_topic velocity_publisher.py
I am a knock 7 year python The