Search code examples
pythonarraysarduinoros

Problem Publishing an Array with Rosserial


I'm using my arduino to publish a simple array. This is the code I'm using:

#include <ros.h>
#include <std_msgs/Int16MultiArray.h>
ros::NodeHandle  nh;
int value[2]={1,6};
std_msgs::Int16MultiArray str_msg;
ros::Publisher chatter("uno", &str_msg);
void setup()
{
nh.initNode();
nh.advertise(chatter);
}
void loop()
{
str_msg.data = value[2];
str_msg.data_length = 2;
chatter.publish( &str_msg );
nh.spinOnce();
delay(1000);
}

This code compiles on the Arduino but returns the following message:

warning: invalid conversion from 'int' to 'std_msgs::Int16MultiArray::_data_type* {aka int*}' [-fpermissive] str_msg.data = value[2];

Also, when I run echo on my Terminal I receive the wrong array. Something like this:

layout: 
dim: []
data_offset: 0
data: [30, 0]

How can I fix this? Thanks a lot!

EDIT: Thanks to the help of Fruchtzwerg I found the mistake. The below code is the answer.

#include <ros.h>
#include <std_msgs/Int16MultiArray.h>
ros::NodeHandle  nh;
int value[2]={1,6};
std_msgs::Int16MultiArray str_msg;
ros::Publisher chatter("uno", &str_msg);
void setup()
{
nh.initNode();
nh.advertise(chatter);
}
void loop()
{
str_msg.data = value;
str_msg.data_length = 2;
chatter.publish( &str_msg );
nh.spinOnce();
delay(1000);
}

Solution

  • You are trying to set the value of str_msg.data but it is an array and no single field. So you need to set an index here also:

    str_msg.data[0] = value[0];
    str_msg.data[1] = value[1];
    

    If you have more fields in future, you can simply use a memcopy here.