What !nh.connected() does (in arduino sketch)
Actually i want my arduino sketch to start when my packages are publishing on topics (basically when ROS MASTER is running).Right now for instance i have a car that is moving before i execute the packages (for example the LIDAR package and more ) .
What while (!nh.connected())
does .Is there anything that could help me with this problem
Asked by Kostas Tzias on 2022-10-05 05:06:00 UTC
Answers
What
while (!nh.connected())
does ...
Let's break it into pieces to understand it better.
nh.connected()
returnstrue
if the node is successfully connected.while
is a loop command and runs as long as the given condition istrue
.
For example, you can assume while(true)
as an infinite loop. Anyway, now, moving back to the original condition, which is while (!nh.connected())
.
- In the beginning, your node may take some time to connect. Therefore,
nh.connected()
will returnfalse
- Next, consider that you do not want to proceed until the node is connected. In other words, you want to wait until the node is connected. Thus you use a
while
loop with the not!
operator innh.connected()
.
In one line, while (!nh.connected())
waits until the node is actually connected. BTW, you should do something like following:
while ( !nh.connected() ){
nh.spinOnce();
}
Asked by ravijoshi on 2022-10-05 05:27:08 UTC
Comments
Hmm .. Is it important to use it in a project ?. I mean is it, a must do , for your project to work better .? Thanks for the explanation !!
Asked by Kostas Tzias on 2022-10-05 05:39:37 UTC
Let me try to give you an example. Consider you have a node publishing (or subscribing to, it does not matter for this example) a topic. If the node is not connected, you should receive an error. Probably the program may crash or throw an exception. Therefore, you should always ensure that node is connected.
On the other hand, based on your original question, it seems your publisher started publishing before your subscriber node subscribed to the publisher. So in this scenario, the subscriber has missed the initial messages. As a workaround, you can manually add a sleep in your publisher node so that the publisher publishes the data after some time. Or, before publishing the data, you can check that your subscriber is connected. Well, there are many ways to deal with it. The simplest solution is to add a sleep in the publisher.
Asked by ravijoshi on 2022-10-05 06:46:27 UTC
Comments