ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

How to publish a message when the condition is met for the first time in python?

asked 2020-12-11 11:02:22 -0500

rainy719 gravatar image

updated 2020-12-15 19:29:24 -0500

I want a node to subscribe /scan. And when the minimum of the range data is smaller than 0.5, the node publishes "hello" to /comm. Only the condition is met for the first time, the message is published. Then no message will be published.

import rospy from sensor_msgs.msg import LaserScan from std_msgs.msg import String

def callback(data): msg= min(data.ranges) if msg<0.2: rospy.loginfo(str) pub.publish(str) condition= True else: pass

rospy.init_node('detect') sub = rospy.Subscriber('/tb3_1/scan', LaserScan, callback) #We subscribe to the laser's topic pub = rospy.Publisher('/comm', String,queue_size=1)

str="hello"
msg=float ctrl_c=True
condition = False rospy.spin()

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2020-12-11 12:16:22 -0500

tryan gravatar image

The publisher/subscriber tutorial will get you started interacting with ROS topics, and the LaserScan documentation indicates the message structure. The rest is more of a Python question, but here's one way:

condition_met = false  # Set outside scan_callback scope, so it's shared between callbacks

scan_callback(msg):
    if not condition_met:  # Don't need to do anything after condition met
        for value in msg.ranges:
            if value < 0.5:
                condition_met = true
                comm_pub.publish('hello')
                return  # Don't need to check the rest

This isn't a working example, but it should give you an idea. If you're stuck on a specific part, post your code, and I'll be happy to help you figure things out.

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2020-12-11 11:02:22 -0500

Seen: 643 times

Last updated: Dec 15 '20