I have a node running on pc which published [std_msgs/String] in string It published M, R, S, I have the following Arduino code.
#include <ros.h>
#include <std_msgs/Empty.h>
#include <std_msgs/String.h>
ros::NodeHandle nh;
void messageCb( const std_msgs::String & toggle_msg)
{
nh.loginfo("recived new message ");
nh.loginfo(toggle_msg.data);
if(toggle_msg.data == "M")
{
nh.loginfo("Recived M if-statment ");
}
else if(toggle_msg.data == "R")
{
nh.loginfo("Recived R if-statment ");
}
else if(toggle_msg.data == "S")
{
nh.loginfo("Recived S if-statment ");
}
}
ros::Subscriber<std_msgs::String> sub("talker_vision", &messageCb );
void setup()
{
pinMode(13, OUTPUT);
nh.initNode();
nh.subscribe(sub);
}
void loop()
{
nh.spinOnce();
delay(1);
}
I received M , R , S from nh.loginfo(toggle_msg.data);
but when I applied If condition
if(toggle_msg.data == "M")
{
nh.loginfo("Recived M if-statment ");
}
there is no output.
The problem you are facing is that you are comparing two strings here which are defined as char*
, not the Arduino classic String
type is used. You can see the type of the string inside the message which was generated for example here.
Comparing
const char* str1 = "abc";
const char* str2 = "abc";
bool equal = str1 == str2;
will be always false since you are comparing memory positions and not the string itself.
So you have two options:
Create two Arduino string objects and compare them
String arduinoString1 = String(str1);
String arduinoString2 = String(str2);
bool equal = arduinoString1 == arduinoString2;
Or even better is to use the standard string comparision strcmp
(documentation) function as described here for example:
bool equal = strcmp(str1, str2) == 0;