在做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;
}