Robotics StackExchange | Archived questions

can not getting the data from if condtion

Hello ROS lovers, 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 condtion

if(toggle_msg.data == "M")
{  
nh.loginfo("Recived M if-statment ");  
}

there is no output. kindly help me

Asked by Mubashir alam on 2022-06-24 01:46:55 UTC

Comments

In the future, please format your code with the 101010 button. I did it for you here.

Asked by Mike Scheutzow on 2022-06-24 18:21:32 UTC

It was my first Question. I will careful next time. Thank you

Asked by Mubashir alam on 2022-06-25 00:45:26 UTC

Answers

With a rosserial client, a ros std_msgs/String data field is converted to a simple c char array. So my guess is that for you to use ==, the correct syntax is:

toggle_msg.data[0] == 'M'

The single quotes are important - you are comparing a char, not a string. Also, to avoid a crash, you need to check the string length to make sure it is not 0.

Asked by Mike Scheutzow on 2022-06-25 08:48:41 UTC

Comments