如何用ROS创建一个HelloWorld工程

C++

# 创建工作去
mkdir -p demo01_ws/src
cd demo01_ws/
catkin_make

# 导入功能包,roscpp是C++库,rospy是python库,std_msgs是标准消息库
cd src/
catkin_create_pkg helloworld roscpp rospy std_msgs

# 编写cpp文件
vim helloworld/src/helloworld_c.cpp

内容如下:

#include "ros/ros.h"

int main(int argc, char *argv[]) {
    ros::init(argc, argv, "hello_shit");
    ROS_INFO("hello world!");
    return 0;
}

编写配置文件vim helloworld/CMakeLists.txt

# 去掉以下两处注释
# 此处功能为将${PROJECT_NAME}_node映射为src/helloworld_c.cpp
add_executable(${PROJECT_NAME}_node src/helloworld_c.cpp)

# 此处功能为设置${PROJECT_NAME}_node的链接库
target_link_libraries(${PROJECT_NAME}_node
  ${catkin_LIBRARIES}
)

最后在demo01_ws目录编译

catkin_make

编译成功后执行,在一个新终端执行roscore,在原来目录下执行

source ./devel/setup.bash
rosrun helloworld helloworld_node

Python

cd demo01_ws/src/helloworld
mkdir scripts
cd scripts
vim helloworld_p.py

内容如下

#! /usr/bin/env python

import rospy

if __name__ == "__main__":
    rospy.init_node("hello_p");
    rospy.loginfo("hello world! by python");

添加可执行权限

chmod +x helloworld_p.py

修改CMakeLists.txt

# 修改以下内容
catkin_install_python(PROGRAMS
  scripts/helloworld_p.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

最后在demo01_ws目录编译

catkin_make

编译成功后执行,在一个新终端执行roscore,在原来目录下执行

source ./devel/setup.bash
rosrun helloworld helloworld_p.py