Ask Your Question
0

can not getting the data from if condtion

asked 2022-06-24 01:59:52 -0500

Mubashir alam gravatar image

updated 2022-06-24 18:20:59 -0500

Mike Scheutzow gravatar image

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

edit retag flag offensive close merge delete

Comments

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

Mike Scheutzow gravatar image Mike Scheutzow  ( 2022-06-24 18:21:32 -0500 )edit

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

Mubashir alam gravatar image Mubashir alam  ( 2022-06-25 00:45:26 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-06-25 08:48:41 -0500

Mike Scheutzow gravatar image

updated 2022-06-25 08:51:11 -0500

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2022-06-24 01:46:55 -0500

Seen: 17 times

Last updated: Jun 25