yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
RDK S600 Developer Kit📖
1.RDK S600 board introduction
  • 1.1 RDK S600 board introduction
  • 1.2 System Flashing
  • 1.3 Hardware Interface Description
  • 1.4 Accessory Installation
  • 1.5 Camera Expansion Board
  • 1.6 MCU Interface Expansion Board
  • 1.7 Precautions for Using the 15.6-inch Screen
  • 1.8 System Boot Modes
2.RDK S600 basic course
  • 2.1 Network Configuration
  • 2.2 Remote Login
  • 2.3 System Update
  • 2.4 Boot Auto-Start Configuration
  • 2.5 RDK Exclusive Command Usage
  • 2.6 Linux Command Usage
  • 2.7 Examples of GPIO Read and Write Operations
  • 2.8 Using the USB Camera
  • 2.9 Solid-state mounting
  • 2.10 SSD expansionnew
  • 2.11 Using the IMX219 Cameranew
  • 2.12 Using the GS130W Stereo Cameranew
3.TogetheROS.Bot Vision Applications
  • 1. About TogetheROS. Bot
  • 2. System Installation
  • 3. Object Detection(YOLO)
  • 4. Image Classification(mobilenetv2)
  • 5. Image Segmentation(mobilenet_unet)
  • 6. Perception Algorithm(BEV)
  • 7. Human Detection and Tracking (Ultralytics YOLO Pose)
4. Offline AI Large Model Development
Offline large model (Text Interaction)
  • 1. AI large model environment deployment
  • 2. Install large model dialogue platform
  • 3. Meta AI Llama 3.2 model
  • 4. Alibaba Cloud Qwen3 model
  • 5. Microsoft Phi-4 mini model
  • 6. DeepSeek - DeepSeek-R1 model
  • 7. Alibaba Cloud Qwen2.5vl Visual Multimodal Large Model
  • 8. Google Gemma3 Visual Multimodal Large Model
  • 9. Lava Visual Multimodal Large Model
  • 10. MiniCPM-V Visual Multimodal Large Model
  • 11. Multimodal visual understand application
  • 12. Multimodal text image application
  • 13. Multimodal visual localization application
  • 14. Multimodal table scanning application
  • 15. Multimodal Autonomous Agent Applications
Offline large model (Voice Interaction)
  • 0. Voice Interaction Hardware Connection (Must Read)
  • 1. Offline speech-to-text (ASR)
  • 2. Offline Text-to-Speech (TTS)
  • 3. AI large model voice interaction
  • 4. Multimodal visual understanding voice interaction
  • 5. Multimodal Text-to-Image application
  • 6. Multimodal video analytics application
  • 7. Multimodal visual localization application
  • 8. Multimodal table scanning application
  • 9. Multimodal autonomous agent application
  • 10. AI Large Model Offline Voice Assistant
5. Online AI Large Model Development
Online large model (Text Interaction)
  • 1.OpenRouter large model API aggregation platform
  • 2.Multimodal visual understand application
  • 3.Multimodal visual localization application
  • 4.Multimodal table scanning application
  • 5.Multimodal autonomous proxy application
Online large model (Voice Interaction)
  • 0.Voice interaction hardware connection (ReadMe)
  • 1.Online speech to text (ASR)
  • 2.Online text to speech (TTS)
  • 3.AI large model voice interaction
  • 4.Multimodal visual understand speech interaction
  • 5.Multimodal visual localization application
  • 6.Multimodal table scanning application
  • 7.Multimodal autonomous proxy application
  • 8.AI large model online voice assistant
6.YOLO26 tutorials
  • 01.YOLO26 environment
  • 02.CLI use
  • 03.Object detection
  • 04.Instance segmentation
  • 05.Pose estimation
  • 06.Image classification
  • 07.Oriented object detection
  • 08.Model conversion
  • 09.Dataset annotation
  • 10.Model training - conversion
  • 11.Model prediction
7.OpenClaw Advanced Development
  • 1. OpenClaw Deployment
  • 2. OpenClaw and WhatsApp Plugin Application
  • 3. OpenClaw TUI Interaction
  • 4. OpenClaw WebChat Interaction
  • 5. OpenClaw Gate Gateway Operation Manual
  • 6. OpenClaw Plugin Function Introduction
  • 7. OpenClaw Tools Introduction
  • 8. OpenClaw ClawHub Introduction (skill Installation)
  • 9.OpenClaw Application - File Management
  • 10.OpenClaw Application - Browser Control
  • 11.OpenClaw Application - Camera
  • 12.OpenClaw Application - Script Execution
  • 13.OpenClaw Application - AI Programming (Peripheral & GPIO Control)
  • 14. OpenClaw Application - Dedicated AI Assistant
  • 15. OpenClaw Configure Web Search Capability
8.ROS2 basic course
  • 1.Introduction to ROS2
  • 2.ROS2 install Jazzy
  • 3.ROS2 development environment
  • 4.ROS2 workspace
  • 5.ROS2 function package
  • 6.ROS2 node
  • 7.ROS2 topic communication
  • 8.ROS2 service communication
  • 9.ROS2 action communication
  • 10.ROS2 custom interface message
  • 11.ROS2 parameter service case
  • 12.ROS2 meta-function package
  • 13.ROS2 distributed communication
  • 14.ROS2 DDS
  • 15.ROS2 time related API
  • 16.ROS2 common command tools
  • 17.ROS2 rviz2 use
  • 18.ROS2 rqt toolbox
  • 19.ROS2 Launch startup file configuration
  • 20.ROS2 recording and playback tool
  • 21.ROS2 URDF model
  • 22.ROS2 Gazebo simulation platform
  • 23.ROS2 TF2 coordinate transformation
Download
  • System_File
  • Code
  • 3D_Model_File
  • Tools_Software
Download ZIP

Welcome to RDK S600 Developer Kit repository

15.ROS2 time related API

15. ROS2 Time-related API

Note: The accompanying reference video uses the ROS Humble version, for reference only

1. Time-related API Overview

The time-related APIs in ROS2 include Rate, Time, Duration, and operations between Time and Duration. Let's explain them one by one.

  • First, create a package to store related program files:

ros2 pkg create learning_time --build-type ament_python --dependencies rclpy

 

2. create_rate

ROS2 also provides the create_rate function, which is a tool for controlling loop execution frequency. Its core function is to allow a piece of code to execute periodically at a fixed frequency. Rate ensures loop execution frequency stability by controlling the loop's "sleep time". Important: Rate generally cannot be used directly in the main thread, as it will permanently block callback events. It is usually only used in programs with multi-threaded callbacks or in sub-threads.

Working principle:

  1. Record the start time of each loop iteration;

  2. Execute the code within the loop;

  3. Calculate the difference between the actual time consumed by the current loop and the "target interval time";

  4. Automatically sleep for the corresponding difference time, ensuring that the interval from the start of one loop to the start of the next loop strictly equals the "target interval" (e.g., 100 milliseconds).

Although both Rate and Timer can achieve periodic execution, they are suitable for different scenarios:

FeatureRateTimer
ImplementationBased on active sleep within the loop (blocks current thread)Based on callback function (non-blocking, triggered by ROS 2 event loop)
Applicable ScenariosSuitable for loops that need to execute at fixed frequency in the same thread (e.g., main control logic)Suitable for periodic tasks that need asynchronous execution (does not block main thread)
FlexibilityCan directly control flow within the loop (e.g., break to exit)Needs to control callback execution through flags or other means

 

  • Below is the basic usage of Rate, implementing a loop that executes twice per second:

    • Create a file rate_demo.py in the package:

​x
import rclpy
from rclpy.node import Node
import threading

class RateExampleNode(Node):
    def __init__(self):
        super().__init__("rate_example_node")
        self.get_logger().info("Rate example node started")

    def run_loop(self):
        # Use node's create_rate() to create a 2Hz Rate
        rate = self.create_rate(2)

        count = 0
        try:
            while rclpy.ok():
                self.get_logger().info(f"Loop executed {count} times")
                count += 1
                rate.sleep()  # Sleep until next cycle (0.5 seconds)
        except KeyboardInterrupt:
            self.get_logger().info("Loop interrupted")

def main(args=None):
    rclpy.init(args=args)
    node = RateExampleNode()

    # Create thread to run loop (avoid blocking main thread)
    loop_thread = threading.Thread(target=node.run_loop)
    loop_thread.start()

    # Main thread executes spin, maintaining ROS 2 node operation
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        loop_thread.join()  # Wait for thread to finish
        node.destroy_node()
        rclpy.shutdown()

if __name__ == "__main__":
    main()

 

  • Configure the corresponding setup.py file. Add to console_scripts:

xxxxxxxxxx
'rate_demo=learning_time.rate_demo:main'

image-20250905155834618

 

  • Build the package:

xxxxxxxxxx
colcon build --packages-select learning_time

image-20250905155916058

 

  • Refresh workspace environment and run node:

xxxxxxxxxx
 source ./install/setup.bash
xxxxxxxxxx
ros2 run learning_time rate_demo

image-20250905155949678

 

3. Timer Application

  • Timer is used to create a timer that triggers periodically to execute some periodic tasks

  • Example: Create two timers. One executes once per second to print the execution count, and another executes once every 0.5 seconds to print the current time.

  • Create a new program file Timer_demo.py:

xxxxxxxxxx
import rclpy
from rclpy.node import Node

class TimerDemoNode(Node):
    def __init__(self):
        super().__init__('timer_demo_node')

        # Counter for demonstrating timer execution count
        self.counter = 0

        # Create timer: Execute callback function once per second
        self.timer = self.create_timer(1.0, self.timer_callback)

        # Create a faster timer: Execute once every 0.5 seconds
        self.fast_timer = self.create_timer(0.5, self.fast_timer_callback)

        self.get_logger().info("Timer node started")

    def timer_callback(self):
        """1-second timer callback function"""
        self.counter += 1
        current_time = self.get_clock().now()

        # Print current time and counter value
        self.get_logger().info(
            f"[1-second timer] Execution {self.counter}, current time: {current_time.seconds_nanoseconds()}"
        )

    def fast_timer_callback(self):
        """0.5-second timer callback function"""
        # Print current timestamp (nanoseconds)
        self.get_logger().info(
            f"[0.5-second timer] Current timestamp: {self.get_clock().now().nanoseconds}"
        )

def main(args=None):
    # Initialize ROS 2
    rclpy.init(args=args)

    # Create node
    node = TimerDemoNode()

    # Run node
    rclpy.spin(node)

    # Shutdown ROS 2
    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()

  • Configure the corresponding setup.py file. Add to console_scripts:

xxxxxxxxxx
'Timer_demo=learning_time.Timer_demo:main'

image-20250905160115901

 

  • Build the package:

xxxxxxxxxx
colcon build --packages-select learning_time

image-20250905155916058

 

  • Refresh workspace environment and run node:

xxxxxxxxxx
source ./install/setup.bash
xxxxxxxxxx
ros2 run learning_time Timer_demo

image-20250905160239330

  • As you can see, the timer triggers according to the set timing. Each callback function prints corresponding log information.

 

4. get_clock - Get Current Time

  • The get_clock function can be used to get the clock object, and then the current time can be obtained through the () method.

  • Create a new program file get_clock_demo.py and fill in the following example program:

xxxxxxxxxx
import rclpy
from rclpy.node import Node
from rclpy.time import Time

class TimeExampleNode(Node):
    def __init__(self):
        super().__init__("time_example_node")

        # Get the node's clock object (uses system clock by default)
        self.clock = self.get_clock()

        # Get current time (returns Time object)
        current_time = self.clock.now()
        self.get_logger().info(f"Current time: {current_time}")

def main(args=None):
    rclpy.init(args=args)
    node = TimeExampleNode()
    rclpy.spin_once(node)  # Run node once
    node.destroy_node()
    rclpy.shutdown()

if __name__ == "__main__":
    main()
  • Configure the corresponding setup.py file. Add to console_scripts:

xxxxxxxxxx
'get_clock_demo=learning_time.get_clock_demo:main'

image-20250905160541502

 

  • Build the package:

xxxxxxxxxx
colcon build --packages-select learning_time

image-20250905155916058

  • Refresh workspace environment and run node:

xxxxxxxxxx
 source ./install/setup.bash
xxxxxxxxxx
ros2 run learning_time get_clock_demo

image-20250905160631573

 

5. Time and Duration

  • The Time class in ROS is used to represent a specific point in time (e.g., "2023-10-01 12:00:00"). It is usually used to mark the moment when an event occurs.

  • The Duration class represents the interval between two points in time (e.g., "5 seconds"). It is used to calculate time differences or delays.

  • Example: Time and Duration application

  • Create a new program file TimeDuration_demo.py:

xxxxxxxxxx
import rclpy
from rclpy.time import Time
from rclpy.duration import Duration

def main():
    rclpy.init()
    node = rclpy.create_node("time_opt_node")

    # How to use Time class: Create 'point in time, moment'
    time1 = Time(seconds=10)
    time2 = Time(seconds=4)
    # How to use Duration class: Create 'duration, time period'
    duration1 = Duration(seconds=3)
    duration2 = Duration(seconds=5)

    # Time points can be compared
    node.get_logger().info("time1 >= time2 ? %d" % (time1 >= time2))
    node.get_logger().info("time1 < time2 ? %d" % (time1 < time2))

    # Time periods and time points can do math operations
    t3 = time1 + duration1
    t4 = time1 - time2
    t5 = time1 - duration1

    node.get_logger().info("t3 = %d" % t3.nanoseconds)
    node.get_logger().info("t4 = %d" % t4.nanoseconds)
    node.get_logger().info("t5 = %d" % t5.nanoseconds)

    # Time periods can be compared
    node.get_logger().info("-" * 80)
    node.get_logger().info("duration1 >= duration2 ? %d" % (duration1 >= duration2))
    node.get_logger().info("duration1 < duration2 ? %d" % (duration1 < duration2))

    rclpy.shutdown()

if __name__ == "__main__":
    main()
  • Configure the corresponding setup.py file. Add to console_scripts:

xxxxxxxxxx
'TimeDuration_demo=learning_time.TimeDuration_demo:main'

image-20250905160751388

 

  • Build the package:

xxxxxxxxxx
colcon build --packages-select learning_time

image-20250905155916058

 

  • Refresh workspace environment and run node:

xxxxxxxxxx
 source ./install/setup.bash
xxxxxxxxxx
ros2 run learning_time TimeDuration_demo

image-20250905160840013

  • This example demonstrates that time points and time periods can perform mathematical operations, allowing us to flexibly query and manipulate data with different timestamps.

ROS2 DDS
ROS2 common command tools

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文