#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <stdlib.h>
int main ( int argc , char ** argv ) {
ros::init (argc, argv, "publish_velocity") ;
ros::NodeHandle nh ;
ros::Publisher pub = nh.advertise <geometry_msgs::Twist >(
"turtle1/cmd_vel" , 1000 ) ;
srand(time(0));
ROS_INFO_STREAM( "Sending random velocity : ") ;
ros::Rate rate(2) ;
while (ros::ok()) {
geometry_msgs::Twist msg;
msg.linear.x = double (rand()) / double (RAND_MAX);
msg.angular.z = 2*double ( rand())/double (RAND_MAX)-1;
pub.publish ( msg ) ;
// Send a message to rosout with the details .
ROS_INFO_STREAM( "Sending random velocity command : "
<< " linear=" << msg.linear.x
<< " angular=" << msg.angular.z) ;
// Wait untilit's time for another iterationet.
rate.sleep () ;
}
}
ros::Publisher pub = nh.advertise <geometry_msgs::Twist >(
"turtle1/cmd_vel" , 1000 ) ; 创建一个发布者
发布消息:
pub.publish ( msg ) ;
一.CMakeList.txt 中增加如下:
find_package(catkin REQUIRED COMPONENTS roscpp geometry_msgs)
catkin_package()
include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(pubvel pubvel.cpp)
target_link_libraries(pubvel ${catkin_LIBRARIES})
二.package.xml 配置增加如下:
<build_depend>roscpp</build_depend>
<exec_depend>roscpp</exec_depend>
<build_depend>geometry_msgs</build_depend>
<exec_depend>geometry_msgs</exec_depend>
三。运行程序:
本文介绍了如何使用ROS(Robot Operating System)在C++中创建一个节点,实现在turtlesim环境中向turtle1发送随机速度指令,包括线速度和角速度。通过CMakeLists.txt和package.xml配置,以及运行`rosrun pubvel pubvel`命令进行实战操作。
2978

被折叠的 条评论
为什么被折叠?



