一、工作空间创建
1.创建工作空间
ll@ll-ThinkPad-P15-Gen-1:~$ mkdir myRosWorkSpace
ll@ll-ThinkPad-P15-Gen-1:~$ cd myRosWorkSpace
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace$ mkdir src
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace$ cd src
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace/src$ catkin_init_workspace
核心命令:catkin_init_workspace,在src文件夹下
2.编译工作空间
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace/src$ cd ../
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace$ catkin_make
#创建install目录,可选作
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace$ catkin_make install
核心命令:catkin_make,在工作空间目录下
二、包创建
1.创建包
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace/src$ catkin_create_pkg myCmdVel std_msgs roscpp rospy geometry_msgs
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace/src$ cd ../
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace$ catkin_make
2.配置source
ll@ll-ThinkPad-P15-Gen-1:~$ sudo vim .bashrc
在末尾加入
source /home/ll/myRosWorkSpace/devel/setup.bash
3.在包目录下的src目录里加入代码
用vscode 打开包目录,并插入代码
#include<ros/ros.h>
#include<geometry_msgs/Twist.h>
#include<iostream>
int main(int argc,char **argv){
//初始化ros
ros::init(argc,argv,"myCmdVelNode");
//初始化node
ros::NodeHandle node;
//初始化publisher
ros::Publisher publisher=node.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel",100);
//初始化频率
ros::Rate rate(5);
double linear_x=0;
double angular_z=0;
std::cout<<"input linear_x>";
std::cin>>linear_x;
std::cout<<"input angular_z>";
std::cin>>angular_z;
while (ros::ok()&&linear_x!=0&&angular_z!=0)
{
/* code */
//设置信息
geometry_msgs::Twist twist;
twist.linear.x=linear_x;
twist.angular.z=angular_z;
//发布信息
publisher.publish(twist);
//ROS_INFO("")
rate.sleep();
}
return 0;
}
4.修改编译设置
打开包目录下src文件里的CMakeLists.txt文件,在155行左右的位置加入如下代码:
add_executable(main src/main.cpp)
target_link_libraries(main ${catkin_LIBRARIES})
保证make时能编译自定义cpp文件
5.编译cpp
切换到工作空间目录,输入catkin_make指令即可
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace$ catkin_make
三、执行该节点
ll@ll-ThinkPad-P15-Gen-1:~/myRosWorkSpace$ rosrun myCmdVel main
rosrun <包名> <节点名>