yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
MicroROS V2 Robot Car📖
01.Introduction
  • 0.Unboxing Video
  • 1. Readme Learning Route
  • 2. Must Read Before Use
  • 3. Introduction to MicroROS V2 Control Board
  • 4. Introduction to LiDAR
  • 5. Introduction to ESP32 Camera Module
  • 6. FAQ
  • 7. About Charging
02.Assembly course
  • Assembly Video
03.Preparation
  • 1. Quickly Start
  • 2. Write Firmware
  • 3. Install VM and Start System
  • 4. Configure VM and Connect Robot
  • 5. Connect to MicroROS Agent
  • 6. Change Ubuntu System Language to English
04.Quick start control course
  • 1. VM Keyboard Remote Control
  • 2. VM Handle Remote Control
  • 3. USB Handle Control
05.Robot control course
  • 1. Robot Information Release
  • 2. Robot Keyboard Control
  • 3. Robot Handle Control
  • 4. Robot State Estimation
  • 5. Linear Speed Calibration
  • 6. Angular Velocity Calibration
  • 7. Robot URDF Model
06.Lidar course
  • 1. Precautions for LiDAR Mapping and Navigation
  • 2. Lidar Avoid
  • 3. Lidar Following
  • 4. Lidar Guard
  • 5. Lidar Patrol
  • 6. Gmapping Mapping
  • 7. Cartographer Mapping
  • 8. Cartographer Quickly Repositioning Navigation
  • 9. Slam Toolx Mapping
  • 10. Navigation2 Single Point Navigation
  • 11. Navigation2 Multi Point Navigation
  • 12. Ros Robot App Mapping And Navigation
07.Road network planning
  • 1. Introduction to Road Network Planning and Quick Start
  • 2. Build a Pose Map
  • 3. Road Network Annotation
  • 4. Planning and Navigation Between Road Networks
  • 5. Road Network Navigation in Any Pose
  • 6. Path Replanning
08.Vision basic course
OpenCV Image Processing
  • 1. Introduction to OpenCV Source CV
  • 2. Open Source CV Geometric Transformation
  • 3. Open Source CV Image Processing and Drawing Text Line Segments
  • 4. Open Source CV Image Beautification
09.Visual General Course (For Standard&Superior version)
1. ESP32 Visual Recognition Module Configuration
  • 1. Serial Port Configuration WiFi Instructions
  • 2. Use ESP32 Camera Module in Robot Car
  • 3. Servo PTZ Calibration
2. OpenCV Visual Recognition
  • 1. Human Pose Estimation
  • 2. Object Detection
  • 3. AR Vision
  • 4. QR Code
  • 5. Color Recognition
  • 6. Facial Recognition
  • 7. AprilTag Machine Code Recognition
3. Mediapipe Visual Recognition
  • 1. Hand Detection
  • 2. Pose Detection
  • 3. Holistic Detection
  • 4. Facial Detection
  • 5. Facial Recognition
  • 6. Facial Special Effects
  • 7. 3D Object Recognition
  • 8. Brush
  • 9. Gesture Recognition
  • 10. Palm Target Localization
  • 11. Fingertip Trajectory Recognition
4. Yolov11&26 Visual Recognition
  • 1. YOLO Environment Setup
  • 2. CLI Usage
  • 3. Object Detection
  • 4. Instance Segmentation
  • 5. Pose Estimation
  • 6. Image Classification
  • 7. Oriented Bounding Boxes Object Detection
  • 8. Model Prediction
10.Visual Advanced Course (Just for Standard version)
1. Visual Control
  • 1. QR Code Recognition Control Action
  • 2. AprilTag Control Car Action Group
  • 3. Gesture Control Car Action Group
  • 4. Visual Line Tracking
2. Visual Tracking
  • 1. Color Tracking
  • 2. Facial Tracking
  • 3. QR Code Tracking
  • 4. Object Recognition And Tracking
  • 5. Mediapipe Palm Tracking
  • 6. Mediapipe Gesture Tracking
  • 7. Mediapipe Human Pose Tracking
  • 8. KCF Object Tracking
  • 9. AprilTag Machine Code Tracking
3. Visual Following
  • 1. Color Follow
  • 2. Face Follow
  • 3. QR Code Follow
  • 4. Mediapipe Palm Follow
  • 5. Mediapipe Gesture Follow
  • 6. Mediapipe Human Posture Follow
  • 7. AprilTag Machine Code Follow
  • 8. Object Follow
11.Visual Advanced Course (Just for Superior version)
1. Visual Control
  • 1. QR Code Recognition Control Action
  • 2. AprilTag Control Car Action Group
  • 3. Gesture Control Car Action Group
  • 4. Visual Line Tracking
2. Visual Tracking
  • 1. Color Tracking
  • 2. Facial Tracking
  • 3. QR Code Tracking
  • 4. YOLO Object Recognition and Tracking
  • 5. Mediapipe Palm Tracking
  • 6. Mediapipe Gesture Tracking
  • 7. Mediapipe Human Pose Tracking
  • 8. KCF Object Tracking
  • 9. AprilTag Machine Code Tracking
3. Visual Follow
  • 1. Color Follow
  • 2. Face Follow
  • 3. QR Code Follow
  • 4. Mediapipe Palm Follow
  • 5. Mediapipe Gesture Follow
  • 6. Mediapipe Human Pose Follow
  • 7. AprilTag Machine Code Follow
  • 8. Object Follow
12.AI Large Model Basic and Applications Course
1. AI Large Model Preparation
  • 1.AI Large Model Preparation
2. AI Large Model Basic Course
  • 1. AI Large Model Types and Principles
  • 2. RAG Retrieval Augmented and Training Samples
  • 3. Embodied Intelligent System Architecture
  • 4. Embodied Intelligence Core Source Code
3. AI Large Model Development
  • 1. Register Model Service Account
  • 2. Configure API KEY
  • 3. Dify Introduction
  • 4. Dify Basic Features
  • 5. RAG Knowledge Base Deployment
  • 6. AI Application Development Chatbot
  • 7. RAG Knowledge Base and Chatbot
  • 8. AI Agent Workflow
4. AI Large Model (Text Version)
  • 1. Semantic Understanding and Instruction Following
  • 2. Multimodal Visual Understanding
  • 3. Multimodal Visual Understanding + Basic Control
  • 4. Multimodal Visual Understanding + Object Following
  • 5. Multimodal Visual Understanding + Visual Line Following
  • 6. Multimodal Visual Understanding + SLAM Navigation
  • 7. Multimodal Visual Understanding + SLAM Navigation + Visual Line Following
  • 8. Multimodal Visual Understanding + SLAM Navigation + Object Following
  • 9. Intent Inference + Multimodal Visual Understanding + SLAM Navigation
13.Openclaw Basics Course
  • 1. Openclaw Introduction
  • 2. Openclaw Core Concepts
  • 3. Openclaw Api-Key Configuration
  • 4. Openclaw Switching Models
  • 5. Openclaw System Prompt
  • 6. Openclaw Common CLI Command
14. Openclaw Interaction Course
  • 1. Openclaw Webchat Interaction
  • 2. Openclaw Tui Interaction
  • 3. Openclaw Whatsapp Interaction
15.Openclaw Development Course
  • 1. Openclaw Robot Mcp Service Integration
  • 2. Robot CLI Command Tools
  • 3. Robot-Control Plugin Tools
  • 4. Openclaw Skills Development
  • 5. Openclaw Scheduled Tasks
  • 6. Openclaw Multi Agent System
  • 7. Openclaw Proactive Interaction
  • 8. Openclaw Vector Memory
16.Openclaw Embodied Intelligence Course
  • 1. OpenClaw Natural Interaction + Basic Control
  • 2. OpenClaw Natural Interaction + Slam Navigation
  • 3. OpenClaw Natural Interaction + Multimodal Visual Understand
  • 4. OpenClaw Natural Interaction + Multimodal Visual Understand + Slam Navigation + Visual Follow
  • 5. OpenClaw Natural Interaction + Multimodal Visual Understand + Slam Navigation + Visual Track
17.Multi-machine Course
  • 1. Multi Machine Handle Control
  • 2. Multi Machine Keyboard Control
  • 3. Multi Machine Navigation
18.MicroROS-V2 Control Board Development Environment
  • 1. Set Up the ESP32-IDF Development Environment
  • 2. ESP32-IDF Configuration Tool
  • 3. ESP Flash Tool Flashing Firmware
  • 4. Install ESP32 Microros Components
  • 5. Install And Start Microros Agent
19.MicroROS-V2 Control Board ESP32 Basic Course
  • 1. Led Light Up
  • 2. Button Function
  • 3. Drive Buzzer
  • 4. Oled
  • 5. Usb Host Function
  • 6. Serial Communication
  • 7. Battery Voltage Detection
  • 8. Drive Pwm Servo
  • 9. Drive Motors
  • 10. Read Motor Encoder Data
  • 11. Pid Motor Speed Control
  • 12. Robot Kinematics Analysis Theory
  • 13. Read Imu Data
  • 14. Read Lidar Data
  • 15. Flash Data Storage
  • 16. Custom Partition Table
  • 17. Bluetooth Communication
  • 18. Wifi Connection
  • 19. ESP32 Visual Recognition Module
20.MicroROS-V2 Control Board Micro_ros Basic Course
  • 1. Publish Topics
  • 2. Subscribe To Topics
  • 3. Multi Topic Subscription And Publishing
  • 4. Subscribe To Buzzer Topic
  • 5. Subscribe To Pwm Servo Topic
  • 6. Subscribe To Speed Control Topic
  • 7. Publish Odometry Topic
  • 8. Publish Imu Data Topic
  • 9. Publish Lidar Data Topic
21. Linux System Course
  • 1.Introduction to Linux system
  • 2.Ubuntu file system
  • 3.Ubuntu common commands
  • 4.Ubuntu common editors
  • 5.Ubuntu software operation commands
  • 6.Virtual machine installation
  • 7.SSH remote control
  • 8.VNC remote control
  • 9.Transfer files remotely
  • 10.Driver library and communication
  • 11.Static IP and hotspot mode
  • 12.Bind device ID
  • 13.Capacity expansion and resource allocation
  • 14.Update system software sources
  • 15.Set root user password
  • 16.sudo free password
  • 17.Connect to WiFi network
  • 18.View system version
  • 19.Customized service management
  • 20.Back up system image
22.Docker Course
  • 1.Docker overview and docker installation
  • 2.Common commands for docker image containers
  • 3.Docker images deeply understand and publish images
23.ROS Basic Course
  • 1.Introduction to ROS2
  • 2.ROS2 install Humble
  • 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
  • Mapping_APP(iOS_Android)
  • Code
  • Software_Tools
  • VM_System_File
  • 3D_Model_File
  • ESP32_Firmware
  • Dify LLM Base
  • Instruction_Manual
  • VMware
Download ZIP

Welcome to MicroROS V2 Robot Car repository

1. Color Tracking

Color Tracking (PTZ)

1. Experiment Objective

The PTZ pan-tilt tracks an object of a specified color, keeping the target at the center of the frame.

2. Experiment Principle

1. Key Terms

TermDescription
Visual TrackingDetects and continuously locks onto a target through a vision algorithm; only the pan-tilt follows, the car does not move
PTZ Pan-Tilt-ZoomA two-degree-of-freedom servo pan-tilt; s1 rotates horizontally and s2 tilts, controlled via the /cmd_ptz_angle topic (geometry_msgs/Vector3)
HSV Color SpaceDescribes colors with the three dimensions Hue, Saturation, and Value; better suited than RGB for color threshold filtering and target segmentation
PD ControlProportional-derivative control; computes the pan-tilt angle step from the target offset (P term) and the offset change rate (D term), with no integral term to avoid overshoot
DeadbandWhen the target offset is within the deadband pixel range, the pan-tilt does not move, avoiding continuous jitter caused by tiny errors

2. Technical Architecture

The color tracking node color_tracker_ptz_node subscribes to the raw image topic /camera/image_raw of the ESP32 camera, segments the target color region with HSV thresholding, computes the pan-tilt angle step with a PD controller, and publishes geometry_msgs/msg/Vector3 to /cmd_ptz_angle to control the pan-tilt servos to track the target.

Detection pipeline: image conversion → HSV conversion → inRange binarization → morphological closing → findContours largest contour extraction → minEnclosingCircle target center → EMA low-pass filter → PD pan-tilt control (fixed 25 Hz).

3. Core Topics Quick Reference

Firmware Uplink (Sensor Data)

TopicMessage TypeQoSDescription
/camera/image_rawsensor_msgs/msg/Imagebest_effortRaw image from the ESP32 camera

Firmware Downlink (Control Commands)

TopicMessage TypeQoSFieldRangeDirection
/cmd_ptz_anglegeometry_msgs/msg/Vector3best_effort + keep_last(1)x[-90, 90]°s1 horizontal servo angle
   y[-90, 20]°s2 tilt servo angle

ROS2 Internal Topics

TopicMessage TypeQoSSourceDescription
/color_tracker_ptz/debug_imagesensor_msgs/msg/Imagereliablecolor_tracker_ptz_nodeDebug image (published when publish_debug_image=true)

3. Experiment Steps

1. Hardware Preparation

HardwareRequirement
PTZ version✅ Supported
No-PTZ version❌
Required peripheralsESP32 camera (pan-tilt) + PTZ servo

2. Start Agent + Camera + Joint Model (Terminal 1)

ros2 launch microros_v2_bringup car_base.launch.py

image-20260728161615714

3. Start Color Tracking (Terminal 2)

xxxxxxxxxx
ros2 launch microros_v2_ptz_visual_control_pkg color_tracker_ptz.launch.py

image-20260728190612932

4. Operation Instructions

Workflow

After startup, the node receives camera frames at the image frame rate and executes the following steps on every processing cycle:

1. Image decoding and preprocessing

The node subscribes to the raw image topic /camera/image_raw (QoS: BEST_EFFORT, KEEP_LAST, depth=1), converts it to a BGR frame with CvBridge.imgmsg_to_cv2(..., desired_encoding="bgr8"), scales it to image_width×image_height (320×240 by default), and then enters the processing pipeline.

2. HSV color detection

The BGR frame is converted to the HSV color space and binarized with cv.inRange using the six-parameter threshold Hmin/Smin/Vmin ~ Hmax/Smax/Vmax, producing a mask of the target color region. A rectangular kernel (morph_kernel_size, 5×5 by default) then performs a morphological closing (MORPH_CLOSE) to fill holes and gaps, and the result is threshold-binarized again to generate the final mask.

3. Target extraction and filtering

cv.findContours (RETR_EXTERNAL) finds external contours in the mask; the contour with the largest cv.contourArea is taken as the candidate target. Its cv.minAreaRect rotated rectangle is computed, then cv.minEnclosingCircle obtains the minimum enclosing circle (center cx/cy and radius). The target is marked valid only when the radius is ≥ min_target_radius (8 px) and the area is ≥ min_target_area (100 px²).

4. Target center low-pass filter

The valid target center is passed through a first-order low-pass filter: filtered = (1-α) × old + α × new, with α = target_smooth_alpha (0.6). The first detected target uses the raw value directly; later frames transition smoothly, reducing center jitter from OpenCV detection noise.

5. PD pan-tilt control (fixed 25 Hz)

A fixed-rate control timer (ptz_control_rate = 25 Hz), independent of image processing, runs the PD control and outputs only in the tracking state:

  • Compute the pixel error: error = target_center - image_center
  • Deadband check: if |error| < deadband (20 px), zero the error
  • Normalize: normalized_error = error / half_image_size
  • PD output: raw_step = (kp × normalized_error + kd × d(normalized_error)/dt) × max_ptz_step
  • Step limiting: clamp raw_step to [-max_ptz_step, +max_ptz_step] (±1.2°)
  • Step smoothing: step = (1-α) × last_step + α × raw_step (α = ptz_step_smooth_alpha = 0.35)
  • Angle smoothing: angle = (1-α) × current_angle + α × desired_angle (α = ptz_smooth_alpha = 0.85)
  • Publish geometry_msgs/Vector3 to /cmd_ptz_angle after angle limiting (x = horizontal, y = tilt)

6. Color sampling (ROI box selection)

Press r to enter ROI sampling mode (state init) and drag the mouse to box-select the target color region. On mouse release, the node computes the min/max values of each HSV channel inside the box and adds an expansion margin (h_expand=5, s_expand=20, v_expand=20). The sampled result is written to both the ROS parameters and the persistent file color_hsv.txt, then the node switches to recognition mode.

Interaction

KeyFunctionDescription
SpaceTracking/recognition switchToggles between "recognition mode" (detects only, does not control the pan-tilt) and "tracking mode" (detects + controls the pan-tilt)
r / RROI color samplingEnters sampling mode; drag the mouse to box-select the target color region and extract the HSV threshold automatically
i / IRecognition modeOnly detects the target and overlays it on the frame, without publishing pan-tilt control commands
q / Q / ESCExitForce-exits the node process with os._exit(0)

Mouse operation: In ROI sampling mode, hold the left button and drag to box-select the target color region (at least 3×3 pixels); on release, the HSV threshold is sampled automatically and saved persistently.

On-screen overlay: The debug window overlays the current mode, frame rate, pan-tilt angle, PD parameters, HSV threshold range, target state (raw/filtered/lost), and key hints in real time.

Safety and Edge Cases

  • No valid HSV threshold: At startup, if there is no HSV config file and auto_start_tracking=false, the node enters the init state automatically and waits for the user to press r to box-select and sample a color
  • HSV file exists: At startup, the HSV threshold is loaded automatically from color_hsv.txt; if auto_start_tracking=true as well, the node enters tracking mode directly
  • Target lost handling: When no valid target is detected for more than lost_timeout (1.0 s), the target is marked lost, the PD control state resets (error/step history cleared), and the pan-tilt stops (stays at its last position); if lost_target_stop=true (default), the filtered target state is also cleared
  • Pan-tilt angle limiting: The horizontal angle is clamped to [ptz_x_min, ptz_x_max] (-90°~90°) and the tilt angle to [ptz_y_min, ptz_y_max] (-90°~20°); out-of-range values are truncated automatically
  • Single-step limiting: The raw PD step is clamped to [-max_ptz_step, +max_ptz_step] (±1.2°) to prevent large abrupt changes
  • Deadband protection: When the target offset is within the deadband range, the normalized error and step are forced to zero, producing no control output
  • Runtime parameter validation: When parameters are modified via ros2 param set /color_tracker_ptz_node <parameter> <value> (or rqt), full range validation is performed (HSV channels [0,179]/[0,255], alpha [0.01,1.0], angle min<max, etc.); illegal values are rejected. Changes to topic parameters such as image_topic/ptz_topic/window_name are rejected with a prompt to restart the node
  • Exit strategy: Press q/ESC to exit directly with os._exit(0), without relying on rclpy.shutdown, to avoid OpenCV/ROS2 hanging during cleanup

5. How to Stop

Press Ctrl+C to stop Terminal 2 → Terminal 1 in order.

4. Experiment Observations

  • No HSV threshold and no box selection: Enters the init state; the frame prompts the user to press r to box-select the target color region, and the pan-tilt does not move
  • After box-selecting a color (recognition mode): The frame shows the target detection result in real time (green rotated rectangle + purple enclosing circle + red center point), overlays the HSV threshold and state, but does not publish pan-tilt control commands
  • Target detected + tracking mode: The pan-tilt follows the target smoothly with PD control; a yellow crosshair is drawn at the frame center, the filtered target center is a solid yellow circle, and the actual pan-tilt angle and PD parameters are overlaid in real time
  • Target within the deadband: The pixel error is smaller than the deadband (20 px), the step is forced to zero, and the pan-tilt outputs nothing, avoiding micro-jitter
  • Target briefly lost (<1 s): The filtered position of the last valid target is retained (the target center is not cleared), preserving tracking continuity; the pan-tilt has brief inertia
  • Target lost by timeout (>1 s): The PD state resets, the filtered target is cleared, and the pan-tilt stays at its position before the loss, waiting for the target to reappear
  • Press r to re-sample: Enters ROI box-selection mode with a green drag rectangle on the frame; on release, the HSV range is extracted automatically (with expansion margin) and persisted to color_hsv.txt, then switches to recognition mode

5. Program Analysis

Source code paths:

  • Launch: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/launch/color_tracker_ptz.launch.py
  • Node: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/microros_v2_ptz_visual_control_pkg/color_tracker_ptz_node.py

1. Launch Parameters

Parameter definition files:

  • Launch: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/launch/color_tracker_ptz.launch.py
  • YAML: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/config/color_tracker_ptz.yaml
ParameterTypeDefault ValueDescription
image_topicstring/camera/image_rawInput raw image topic
ptz_topicstring/cmd_ptz_anglePan-tilt Vector3 control topic
hsv_filestringconfig/color_hsv.txtHSV threshold file path
display_debug_windowbooltrueShow the OpenCV debug window
auto_start_trackingboolfalseStart tracking immediately after launch when HSV is available
enable_rqt_dynamic_parametersbooltrueEnable runtime dynamic tuning via rqt/ros2 param
config_filestringconfig/color_tracker_ptz.yamlYAML config file path
pd_kpfloat0.7PD proportional gain
pd_kdfloat0.25PD derivative gain
ptz_control_ratefloat25.0 HzPan-tilt control publishing rate (YAML override)
deadband_xfloat20.0 pxHorizontal deadband pixel range
deadband_yfloat20.0 pxVertical deadband pixel range
target_smooth_alphafloat0.6Target center low-pass filter coefficient (YAML override)
ptz_smooth_alphafloat0.85Pan-tilt angle low-pass filter coefficient (YAML override)
max_ptz_stepfloat1.2°Maximum single pan-tilt angle step
ptz_step_smooth_alphafloat0.35Step EMA smoothing coefficient
lost_timeoutfloat1.0 sTarget lost timeout
Hmin / Hmaxint0 / 9HSV hue lower/upper bound [0, 179]
Smin / Smaxint85 / 253HSV saturation lower/upper bound [0, 255]
Vmin / Vmaxint126 / 253HSV value lower/upper bound [0, 255]
min_target_radiusfloat8.0 pxMinimum valid target radius (YAML override)
min_target_areafloat100.0 px²Minimum valid target area (YAML override)
ptz_init_x / ptz_init_yfloat0.0° / -45.0°Initial pan-tilt horizontal/tilt angle (YAML overrides ptz_init_y)
ptz_x_min / ptz_x_maxfloat-90.0° / 90.0°Horizontal angle range
ptz_y_min / ptz_y_maxfloat-90.0° / 20.0°Tilt angle range

2. Core Node Analysis

ColorTrackerPtzNode inherits from rclpy.node.Node and is the core implementation of color tracking. The constructor and the PD control callback are shown below.

Constructor __init__

The constructor declares the ROS2 parameters, creates the publishers and subscribers, initializes the tracking state, and sets up the fixed-rate control timer:

​x
class ColorTrackerPtzNode(Node):
    """ROS2 color tracker PTZ node."""
​
    def __init__(self) -> None:
        super().__init__("color_tracker_ptz_node")
​
        self.cv_bridge = CvBridge()
        self.target_state_lock = threading.Lock()
​
        self._declare_ros_parameters()
        self._load_ros_parameters()
​
        # Create publishers: pan-tilt angle command / debug image
        self.ptz_angle_publisher = self.create_publisher(Vector3, self.ptz_topic, 10)
        self.debug_image_publisher = self.create_publisher(Image, self.debug_image_topic, 10)
​
        # Create subscriber: input image (default raw image topic)
        subscribed_image_message_type = Image
        self.image_subscriber = self.create_subscription(
            subscribed_image_message_type,
            self.image_topic,
            self.image_callback,
            QoSProfile(history=QoSHistoryPolicy.KEEP_LAST, depth=1,
                       reliability=QoSReliabilityPolicy.BEST_EFFORT,
                       durability=QoSDurabilityPolicy.VOLATILE),
        )
​
        # Tracking state initialization
        self.tracking_state = "identify"
​
        # Load the HSV threshold (prefer loading from the file)
        self.hsv_threshold_range = self._get_hsv_range_from_parameters()
        saved_hsv = read_hsv_threshold_file(self.hsv_file)
        if saved_hsv is not None:
            self.hsv_threshold_range = saved_hsv
            self._apply_hsv_range_to_ros_parameters(saved_hsv)
            self.get_logger().info(f"Loaded HSV from file: {self.hsv_file}, "
                                   f"hsv={saved_hsv}")
​
        # Initial pan-tilt angles
        self.current_ptz_horizontal_angle = float(self.ptz_init_x)
        self.current_ptz_vertical_angle = float(self.ptz_init_y)
​
        # PD control state initialization
        self.previous_error_x = 0.0
        self.previous_error_y = 0.0
        self.previous_control_time = 0.0
        self.last_step_x = 0.0
        self.last_step_y = 0.0
​
        # Target detection state
        self.raw_target_circle = (0, 0, 0)
        self.filtered_target_center_x = None
        self.filtered_target_center_y = None
​
        # Create the fixed-rate pan-tilt control timer (25 Hz by default)
        self._recreate_ptz_control_timer(False)
​
        # Create the OpenCV debug window
        if self.display_debug_window:
            cv.namedWindow(self.window_name, cv.WINDOW_NORMAL)
            cv.resizeWindow(self.window_name, self.window_width, self.window_height)
            cv.setMouseCallback(self.window_name, self._on_mouse_event)
​
        # Register the runtime dynamic tuning callback
        self.parameter_callback_handle = self.add_on_set_parameters_callback(
            self._handle_runtime_parameter_update
        )

Pan-tilt control callback _control_timer_callback

Triggered at a fixed rate (25 Hz); runs the PD pan-tilt control only in the tracking state:

xxxxxxxxxx
def _control_timer_callback(self) -> None:
    """Run fixed-rate PTZ control."""
    if self.tracking_state != "tracking":
        return
​
    with self.target_state_lock:
        target_is_valid = self.target_is_valid
        target_age = time.perf_counter() - self.last_valid_target_time_seconds
        filtered_x = self.filtered_target_center_x
        filtered_y = self.filtered_target_center_y
        filtered_r = self.filtered_target_radius
​
    if (not target_is_valid or filtered_x is None
            or filtered_y is None or filtered_r is None
            or target_age > self.lost_timeout):
        self._handle_lost_target()
        return
​
    self._track_target_with_smooth_ptz(
        (int(filtered_x), int(filtered_y), int(filtered_r))
    )

PD tracking method _track_target_with_smooth_ptz

Implements the complete PD control chain: pixel error computation → deadband handling → normalization → PD step → step smoothing → angle smoothing → clamped publish:

xxxxxxxxxx
def _track_target_with_smooth_ptz(self, target_circle: TargetCircleInPixels) -> None:
    target_center_x, target_center_y, _ = target_circle
    image_cx = self.image_width * 0.5
    image_cy = self.image_height * 0.5
​
    # Compute the pixel error, zeroed inside the deadband
    err_x = float(target_center_x - image_cx)
    err_y = float(target_center_y - image_cy)
    if abs(err_x) < self.deadband_x:
        err_x = 0.0
    if abs(err_y) < self.deadband_y:
        err_y = 0.0
​
    # Time delta (for the derivative term)
    now = time.perf_counter()
    dt = max(now - self.previous_control_time, 1.0e-3)
​
    # Normalized error + derivative
    norm_x = err_x / image_cx
    norm_y = err_y / image_cy
    dx = (norm_x - self.previous_error_x) / dt
    dy = (norm_y - self.previous_error_y) / dt
​
    # PD computation + step limiting
    raw_x = (self.pd_kp * norm_x + self.pd_kd * dx) * self.max_ptz_step
    raw_y = (self.pd_kp * norm_y + self.pd_kd * dy) * self.max_ptz_step
    raw_x = clamp_numeric_value(raw_x, -self.max_ptz_step, self.max_ptz_step)
    raw_y = clamp_numeric_value(raw_y, -self.max_ptz_step, self.max_ptz_step)
​
    # Step EMA smoothing
    alpha = self.ptz_step_smooth_alpha
    step_x = (1.0 - alpha) * self.last_step_x + alpha * raw_x
    step_y = (1.0 - alpha) * self.last_step_y + alpha * raw_y
​
    # Save the control history
    self.previous_error_x = norm_x
    self.previous_error_y = norm_y
    self.previous_control_time = now
    self.last_step_x = step_x
    self.last_step_y = step_y
​
    # Compute the desired angle (with direction reversal)
    desired_h = (self.current_ptz_horizontal_angle - step_x
                 if self.ptz_x_reverse else self.current_ptz_horizontal_angle + step_x)
    desired_v = (self.current_ptz_vertical_angle + step_y
                 if self.ptz_y_reverse else self.current_ptz_vertical_angle - step_y)
    desired_h = clamp_numeric_value(desired_h, self.ptz_x_min, self.ptz_x_max)
    desired_v = clamp_numeric_value(desired_v, self.ptz_y_min, self.ptz_y_max)
​
    # Angle EMA smoothing
    ptz_alpha = self.ptz_smooth_alpha
    self.current_ptz_horizontal_angle = (
        (1.0 - ptz_alpha) * self.current_ptz_horizontal_angle + ptz_alpha * desired_h
    )
    self.current_ptz_vertical_angle = (
        (1.0 - ptz_alpha) * self.current_ptz_vertical_angle + ptz_alpha * desired_v
    )
​
    # Clamp again and publish
    self.current_ptz_horizontal_angle = clamp_numeric_value(
        self.current_ptz_horizontal_angle, self.ptz_x_min, self.ptz_x_max)
    self.current_ptz_vertical_angle = clamp_numeric_value(
        self.current_ptz_vertical_angle, self.ptz_y_min, self.ptz_y_max)
    self._publish_ptz_angle(self.current_ptz_horizontal_angle,
                            self.current_ptz_vertical_angle)

6. Frequently Asked Questions

ProblemCauseSolution
Pan-tilt jitterspd_kp too large or target_smooth_alpha too smallReduce pd_kp (e.g., 0.3), increase target_smooth_alpha (e.g., 0.5)
Target lostMoving too fast for the pan-tilt response, or the HSV threshold mismatchesSlow down the target; press r to box-select and re-sample the color
Target not detectedHSV threshold inaccurate or large lighting changesPress r and re-box-select the target color region under the current lighting
Cannot enter tracking modeNo HSV sampling performed or auto_start_tracking=falsePress r to box-select, then press Space to enter tracking mode
Pan-tilt does not return to center after startupThe initial angle is set by ptz_init_x/ptz_init_yAdjust the initial angle in the YAML or launch parameters
Visual Line Tracking
Facial Tracking

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/中文