how to access the msg in the subscriber callback in ros2 rclpy
Hello,
I am trying to run the following ros2 node. however, it seems that I cannot access the msg inside the callback function.
import rclpy
from rclpy.node import Node
import time
from std_msgs.msg import String
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.subscription = self.create_subscription(
String,
'topic',
self.listener_callback,
10)
self.subscription # prevent unused variable warning
self.topub = 0
def listener_callback(self, msg):
self.topub = msg.data
def printmsg (self):
while True:
self.get_logger().info('I heard: "%s"' % self.topub)
time.sleep(0.5)
def main(args=None):
rclpy.init(args=args)
minimal_subscriber = MinimalSubscriber()
minimal_subscriber.printmsg()
rclpy.spin(minimal_subscriber)
if __name__ == '__main__':
main()
if anyone has a clue, please help.
Thank you
Have you tried
ros2 topic echo
to verify if publication is working as you expect?when would
printmsg(..)
return?Yes, the topic is published
actually I want to have acess to the msg subscribed within a loop.