Implement Publisher 1. code part (1) python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 import rospyfrom geometry_msgs.msg import Twistdef velocity_publisher (): rospy.init_node('velocity_publisher' , anonymous=True ) turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel' , Twist, queue_size=10 ) rate = rospy.Rate(10 ) while not rospy.is_shutdown(): vel_msg = Twist() vel_msg.linear.x = 0.5 vel_msg.angular.z = 0.2 turtle_vel_pub.publish(vel_msg) rospy.loginfo("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]" , vel_msg.linear.x, vel_msg.angular.z) rate.sleep() if __name__ == '__main__' : try : velocity_publisher() except rospy.ROSInterruptException: pass
(2) C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 #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 ) ; int count = 0 ; while (ros::ok ()) { geometry_msgs::Twist vel_msg; vel_msg.linear.x = 0.5 ; vel_msg.angular.z = 0.2 ; turtle_vel_pub.publish (vel_msg); ROS_INFO ("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]" , vel_msg.linear.x, vel_msg.angular.z); loop_rate.sleep (); } return 0 ; }
2. set up env (1) python
create a folder under your <package>
named scripts, it is because distinguish between python and c++
go to the terminal
1 rosrun turtlesim turtlesim_node
1 rosrun learning_topic velocity_publisher.py
we can see the turtle move
(2) C++
put the c code in the <package>/src
folder
go to the CMakeLists.txt
file, add these two command here
1 2 add_executable(velocity_publisher src/velocity_publisher.cpp) target_link_libraries(velocity_publisher ${catkin_LIBRARIES})
go to the workspace root folder and open terminal here
compile the c++ file
if can see 0%
to 100%
means success
then go to the terminal
1 rosrun turtlesim turtlesim_node
1 rosrun learning_topic velocity_publisher