简体   繁体   中英

Rate and sleep function in RCLPY library for ROS2

Recently I started learning ROS2, but I've encountered one issue, I've created a package & defined a node.

#! /usr/bin/env python
import rospy
rospy.init_node("simple_node")
rate = rospy.Rate(2) # We create a Rate object of 2Hz
while not rospy.is_shutdown(): # Endless loop until Ctrl + C
    print("Help me body, you are my only hope")
    rate.sleep()
# We sleep the needed time to maintain the Rate fixed above
# This program creates an endless loop that repeats itself 2 times per second (2Hz) 
# until somebody presses Ctrl + C in the Shell

So, I need to convert above ROS1 code for ROS2, for that I replaced ROSPY library with RCLPY and coded it as below:

import rclpy
def main(args=None):
    rclpy.init()
    myfirstnode = rclpy.create_node('simple_node')
    print("Help me body, you are my only hope")

if __name__ == '__main__':
    main()

Now, I want to implement below-given code snippet using RCLPY but I'm not able to get all the functions required, I've got the RCLPY substitute of rospy.Rate(2) , it is rclpy.create_node('simple_node').create_rate(2) .

while not rospy.is_shutdown():
    print("Help me body, you are my only hope")
    rate.sleep()

Please suggest RCLPY substitutes of the functions rospy.is_shutdown() and rospy.Rate(2).sleep()

You can create a Rate object from your Node:

self._loop_rate = self.create_rate(loop_rate, self.get_clock())

See: https://github.com/ros2/rclpy/blob/master/rclpy/rclpy/node.py

Then within a loop you can call:

self._loop_rate.sleep()

See: https://github.com/ros2/rclpy/blob/master/rclpy/rclpy/timer.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM