hello ros
文章目录
1 创建功能包
cd ~/catkin_ws/src
catkin_create_pkg beginner_tutorials roscpp rospy std_msgs geometry_msgs turtlesim
2 C++
2.1 创建cpp文件
cd ~/catkin_ws/src/beginner_tutorials/src
touch hello.cpp
gedit hello.cpp
#include "ros/ros.h" //包含一个 ros 头文件
#include <string> //包含一个 string 头文件
using namespace std; //使用命名空间 std
int main(int agrc, char **agrv) //主函数
{
ros::init(agrc, agrv, "hello",ros::init_options::AnonymousName); //创建一个节点
ros::NodeHandle n; //创建 ROS 句柄
ros::Rate loop_rate(1); //设置频率
string str; //声明一个字符串变量 str
while(ros::ok()) //当节点关闭时退出循环
{
ROS_INFO("Hello World"); //输出到终端
loop_rate.sleep(); //睡眠
}
}
ros::init():初始化 roscpp 节点。在 node 代码中在调用其它 roscpp 函数前,首先调用 ros::init() 函数。argc 和 argv:解析命令行重映射参数。这里代码中“hello”是节点名,在 ros 系统中,节点名必须唯一;如果重名节点被运行,那之前的节点就会自动关闭。
ros::NodeHandle:创建句柄,后续可以对该句柄进行操作,就相当操作该节点;同时指定命名空间。
ros::ok()接口:返回 false,说明节点已经关闭。
loop_rate.sleep()接口:相当于 delay 函数,让程序暂停一会,让消息的发送频率符合1Hz。
2.2 在 CMakeList 添加语句
打开CMakeLists.txt
~/catkin_ws/src/beginner_tutorials
gedit CMakeLists.txt
添加以下语句
add_executable(hello src/hello.cpp)
target_link_libraries(hello ${catkin_LIBRARIES})
2.3 编译
cd catkin_ws
catkin_make
2.4 运行
roscore
# 新开一个终端,输入
rosrun beginner_tutorials hello
3 python
3.1 创建.py脚本
cd ~/catkin_ws/src/beginner_tutorials/
mkdir scripts && cd scripts
touch hello.py && chmod +x hello.py
gedit hello.py
python脚本以tab缩进分层次,因此不能把tab与空格混用;
最好是把tab设置为4个空格长度;
#!/usr/bin/env python
#! -*- coding: utf-8 -*- #此源程序由 utf-8 编码
import rospy #调用 ROS 的 python 库
rospy.init_node("hello",anonymous=True) #创建一个节点,名称为 hello
rate = rospy.Rate(1) #设定频率为 1Hz
while not rospy.is_shutdown(): #检测程序是否退出
hello_str = "Hello World %s" % rospy.get_time() #hello_str=Hello World+当前时间
rospy.loginfo(hello_str) #输出信息到终端
rate.sleep() #睡眠
第一行:#!/usr/bin/env python
,告诉操作系统应该传递给一个 python 解释器。
#!/usr/bin/python相当于写死了python路径;
#!/usr/bin/env python会去环境设置寻找python目录,推荐这种写法
第二行:# -*- coding: utf-8,防止因代码中出现中文注释而报错 SyntaxError: Non-ASCII character ‘\xe2’ in file。
3.2 编译
cd ~/catkin_ws
catkin_make
3.3 运行
roscore
# 新开一个终端,输入
rosrun beginner_tutorials hello.py