ros publish message learning (Gu Yueju ROS Introduction 21 Lectures Tenth Lectures Publisher's Programming Implementation)

Create a workspace: mkdir -p ~/catkin_ws1/src

Compile workspace: catkin_make

Initialize the workspace: catkin_init_workspace

Execute the source command: source devel/setup.bash

For convenience, add it to the .bashrc file so that you don't need to execute the source command every time.

New package function package: catkin_create_pkg learning_topic roscpp rospy std_msgs gemotry_msgs turtlesim

Create a new cpp file and copy the following code into the file: vim velocity_publisher.cpp

#include<ros/ros.h>
#include<geometry_msgs/Twist.h>

int main(int argc,char**argv)
{
    ros::init(argc,argv,"velocity_publisher");
    ros::NodeHandle n;
    ros::Publisher turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel",10);
    ros::Rate loop_rate(10);
    while(ros::ok())
    {
        geometry_msgs::Twist vel_msgs;
	vel_msgs.linear.x=0.5;
        vel_msgs.angular.z=0.2;
        
        turtle_vel_pub.publish(vel_msgs);
        ROS_INFO("Publish turtle velocity command[%0.2f m/s,%0.2f rad/s]",vel_msgs.linear.x,vel_msgs.angular.z);
        loop_rate.sleep();	
    }
    return 0;
}

Use vim editor, press i to edit, press esc+: wq to save and exit.

Add the following two lines in CMakelists.txt:

add_executable(velocity_publisher src/velocity_publisher.cpp)
target_link_libraries(velocity_publisher ${catkin_LIBRARIES})
如下图:

At this point, the program is
fine , and then compile; catkin_make

Then, execute the program:

roscore

rosrun turtlesim turtlesim_node

rosrun learning_topic velocity_publisher

 

Yes, it works perfectly!

 

Guess you like

Origin blog.csdn.net/qqliuzhitong/article/details/112618021