ROS发布、订阅Float64MultiArray数组类消息(C++)

在做webots仿真六轮车时,想通过rosbag记录一下仿真运行时的电机转速,之前ROS也用得少,没发过数组类型的消息,写程序的时候发现有一些小地方需要注意,就在这儿记录一下。

Float64MultiArray在这里插入图片描述

从官方给的资料看,float64,或者说是c++里的double型,对应的数组类型,可以在http://wiki.ros.org/msg里查阅到,是std::vector。并且webots里电机的响应数据也是float64。。

另外,"std_msgs/Float64MultiArray.h",已经包含了<vector>,可以使用push_back函数往数组中直接添加数据。

知道了两边数据的格式,就可以把这一段程序写进去了。

publisher

//ros端需要的头文件
#include <std_msgs/Float64.h>
#include <std_msgs/Float64MultiArray.h>
#include "ros/ros.h"

//webots端需要的头文件
#include <webots_ros/set_float.h>
#include <webots_ros/get_float.h>



int main(int argc, char **argv) {
ros::init(argc, argv, "ros_test", ros::init_options::AnonymousName);
n = new ros::NodeHandle;
ros::Publisher six_wheel_speed_pub = n->advertise<std_msgs::Float64MultiArray>("wheel_speed_publisher", 1000);//发布话题wheel_speed_publisher
ros::Rate loop_rate(10);

while (ros::ok()) {
std_msgs::Float64MultiArray msg;

/*webots相关代码,不需要可以删除
for (int i = 0; i < NMOTORS; ++i) {
    ros::ServiceClient get_velocity_client;
    webots_ros::get_float get_velocity_srv;

    get_velocity_client = n->serviceClient<webots_ros::get_float>(std::string("ros_test/") + std::string(motorNames[i]) +
                                                                 std::string("/get_velocity"));

   get_velocity_srv.request.ask = true;
    if (get_velocity_client.call(get_velocity_srv) && get_velocity_srv.response.value != 0){
      speed_response[i] = get_velocity_srv.response.value;
      ROS_INFO("Velocity of %s is %f.", motorNames[i], get_velocity_srv.response.value);
   }
    else
     ROS_ERROR("Failed to call service get_velocity on motor %s.", motorNames[i]);
    }
*/
msg.data.push_back(speed_response[0]);
msg.data.push_back(speed_response[1]);
msg.data.push_back(speed_response[2]);
msg.data.push_back(speed_response[3]);
msg.data.push_back(speed_response[4]);
msg.data.push_back(speed_response[5]);

six_wheel_speed_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;

subscriber

#include "ros/ros.h"
#include "std_msgs/Float64MultiArray.h" //#include "std_msgs/String.h"

void wheel_speed_publisherCallback(const std_msgs::Float64MultiArray::ConstPtr& msg) 
{
//你的回调函数
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "listener");

  ros::NodeHandle n;

  ros::Subscriber sub = n.subscribe("wheel_speed_publisher", 1000, wheel_speed_publisherCallback);

  ros::spin();

  return 0;
}
  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值