容易出错的地方
链接catkin的库
target_link_libraries(main ${catkin_LIBRARIES})
使用自定义头文件,前面加包名
#include "package_name/xxx.h"
CMakeLists.txt
如果有自定义类,需要包含头文件和链接库
// 头文件位置
include_libraries(include)
// 添加库文件
add_libraries(Student STATIC src/Student.cpp)
// 链接
target_link_libraries(main Student)
std_msgs的数据类型
#include <std_msgs/Float64.h>
float64 data
#include <std_msgs/Float64MultiArray.h>
float64[] data // 这种可变数组就相当于vector
代码示例
发布者 talker
int main(int argc, char** argv)
{
ros::init(argc, argv, "talker"); // 节点名
ros::NodeHandle n; // 句柄
ros::Publisher pub = n.advertise<std_msgs::Float64>("chatting", 10);
// 往chatting话题上发消息,数据类型是std_msgs::Float64
std_msgs::Float64 input;
input.data = 0.0;
ros::Rate loop_rate(1); // 1s发一次
while(ros::ok())
{
input.data += 0.1;
pub.publish(input);
loop_rate.sleep();
}
}
不同数据类型std_msgs::Float64MultiArray
int main(int argc, char** argv)
{
ros::init(argc, argv, "talker");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<std_msgs::Float64MultiArray>("chatting", 10);
ros::Rate loop_rate(1);
double arr[3] = {14, 15, 16};
std::vector<double> vi(arr, arr+3); // float64就是double
std_msgs::Float64MultiArray input_float;
input_float.data = vi;
while(ros::ok())
{
for (auto& i : input_float.data)
std::cout << i << " ";
std::cout << std::endl;
pub.publish(input_float);
loop_rate.sleep();
}
}
订阅者 listener
void chatting_cb(const std_msgs::Float64::ConstPtr& message)
{
ROS_INFO("I receive the number: %f", message->data);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Subscribe sub = n.subscribe("chatting", 1, chatting_cb);
ros::spin(); // 阻塞
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.2)
project(learning_communication)
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
)
catkin_package()
include_directories(
include
${catkin_INCLUDE_DIRS}
)
add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
Python
发布者
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import String
from test_msgs.msg import Position
def talker():
rospy.init_node('py_talker', anonymous=True)
Pos_pub = rospy.Publisher('/test/Position', Position, queue_size=10)
rate = rospy.Rate(10)
pos = Position()
pos.x = 10
pos.y = 20
while not rospy.is_shutdown():
pos.x += 1
pos.y += 2
rospy.loginfo(pos)
Pos_pub.publish(pos)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:pass
订阅者
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from test_msgs.msg import Position
def callback(msg):
rospy.loginfo('Receive: %f, %f', msg.x, msg.y)
def listener():
rospy.init_node('py_listener', anonymous=True)
rospy.Subscriber('/test/Position', Position, callback)
rospy.spin()
if __name__ == '__main__':
try:
listener()
except rospy.ROSInitException:pass