### Control Robot Position with MoveToPos API in C++ Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface This C++ example shows how to control the robot's position using the `MoveToPos` API. It subscribes to odometry data to determine the current position and orientation, calculates a target position one meter forward in the robot's base frame, and then commands the robot to move to that target. Dependencies include the Unitree SDK, Eigen for matrix operations, and C++ standard library components. ```cpp /** * @file move_to_pos_test.cpp * @brief Use the api named MoveToPos to control the pos of robot * @date 2025-07-10 */ #include #include #include #include //The topic of odom #define TOPIC_ODOM_STATE "rt/lf/odommodestate" using namespace std; using namespace unitree::common; using namespace unitree::robot; //Forced close progress void MySigintHandler(int sig) { exit(0); } class MoveToPosTest{ public: MoveToPosTest(){ sport_client_.SetTimeout(1.0f); sport_client_.Init(); } ~MoveToPosTest(){} void Init(){ odommodestate_subscriber_.reset(new ChannelSubscriber(TOPIC_ODOM_STATE)); odommodestate_subscriber_->InitChannel(std::bind(&MoveToPosTest::OdomModeStateMessageHandler, this, std::placeholders::_1), 1); } void OdomModeStateMessageHandler(const void *message){ unitree_go::msg::dds_::SportModeState_ sport_mode_state = *(unitree_go::msg::dds_::SportModeState_*)message; Eigen::Matrix cur_pose; yaw_ = sport_mode_state.imu_state().rpy()[2]; cur_pose[0] = sport_mode_state.position()[0]; cur_pose[1] = sport_mode_state.position()[1]; cur_pose[2] = 0.0; if(this->have_odom_data_ == false){ this->have_odom_data_ = true; Eigen::Matrix target_in_base; //Move one meter along the robot's direction target_in_base << 1.0, 0.0, 0.0; Eigen::Matrix qua; Eigen::Matrix r; float c_yaw = cos(yaw_); float s_yaw = sin(yaw_); r << c_yaw,-s_yaw,0, s_yaw,c_yaw,0, 0,0,1; target_pos_ = cur_pose + r * target_in_base; std::cout << "[Target Pos] is : " << target_pos_.transpose() << std::endl; std::cout << "[Target Yaw] is : " << yaw_ << std::endl; } } void run(){ sport_client_.MoveToPos(target_pos_[0],target_pos_[1],yaw_); } private: ChannelSubscriberPtr odommodestate_subscriber_; bool have_odom_data_ = false; bool have_send_ = false; Eigen::Matrix target_pos_; float yaw_; unitree::robot::b2::SportClient sport_client_; }; int main(){ signal(SIGINT, MySigintHandler); unitree::robot::ChannelFactory::Instance()->Init(0); MoveToPosTest move_to_pos_test_; move_to_pos_test_.Init(); while(true){ move_to_pos_test_.run(); sleep(1.0); } return 0; } ``` -------------------------------- ### Control Robot Velocity with Move API in C++ Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface This C++ example demonstrates how to control the robot's velocity using the `Move` API of the SportClient. It initializes the client, sets the robot to a balanced standing state, enables classic walk mode, and then applies a linear velocity. Dependencies include the Unitree SDK for B2 sport client andunistd.h for sleep functionality. ```cpp /** * @file move_test.cpp * @brief Use the api named Move to control the vel of robot * @date 2025-07-10 */ #include #include //Forced close progress void MySigintHandler(int sig) { exit(0); } int main() { signal(SIGINT, MySigintHandler); //Init channel unitree::robot::ChannelFactory::Instance()->Init(0); //Create SportClient unitree::robot::b2::SportClient sport_client; //Set time-out period for request sport_client.SetTimeout(10.0f); //Init SportClient sport_client.Init(); //Use api to balance stand sport_client.BalanceStand(); //Use api to ClassicWlak Mode sport_client.ClassicWalk(true); sleep(3); //Use api to move sport_client.Move(0.3, 0., 0.); sleep(3); //Stop move sport_client.StopMove(); return 0; } ``` -------------------------------- ### PathPoint Structure Definition Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Defines the structure of a PathPoint, which contains information about a specific point along a tracked path. This includes the time from the start, x and y coordinates, yaw angle, and corresponding velocities (vx, vy, vyaw). ```cpp typedef struct { float tFromStart; // Time at which the path point is located float x; //x position float y; //y position float yaw; // Yaw angle float vx; //x speed float vy; //y speed float vyaw; // Yaw speed } PathPoint; ``` -------------------------------- ### TrajectoryFollow Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Commands the robot to follow a predefined motion trajectory. The trajectory consists of up to 30 PathPoint objects. ```APIDOC ## POST /api/walk/trajectory ### Description Command the robot to follow a specified motion trajectory. ### Method POST ### Endpoint /api/walk/trajectory ### Parameters #### Request Body - **path** (array) - Required - An array of PathPoint objects defining the trajectory. Maximum 30 points. - **PathPoint** (object) - Represents a point in the trajectory. - **x** (float) - X-coordinate. - **y** (float) - Y-coordinate. - **yaw** (float) - Yaw angle. - **duration** (float) - Time duration to reach this point. ### Request Example ```json { "path": [ { "x": 1.0, "y": 0.0, "yaw": 0.0, "duration": 2.0 }, { "x": 2.0, "y": 1.0, "yaw": 0.5, "duration": 4.0 } ] } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ``` -------------------------------- ### ClassicWalk Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Enables or disables the classic gait mode. High or low speed levels can be set. ```APIDOC ## POST /api/walk/classic ### Description Enable or disable the classic gait mode. ### Method POST ### Endpoint /api/walk/classic ### Parameters #### Request Body - **flag** (boolean) - Required - Set to true to enable classic walk, false to disable. ### Request Example ```json { "flag": true } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ### Remarks High or low speed levels can be set separately. ``` -------------------------------- ### FreeWalk Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Activates the free gait mode for the robot. High or low speed levels can be set. ```APIDOC ## POST /api/walk/free ### Description Activate the free gait mode. ### Method POST ### Endpoint /api/walk/free ### Parameters None ### Request Example ```json { "action": "start" } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ### Remarks High or low speed levels can be set separately. ``` -------------------------------- ### Ai Sport State Types Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Details on the data structures and types used to represent the robot's sport state, IMU data, and path points. ```APIDOC ## Ai Sport State Types ### Description Provides a detailed breakdown of the data structures and their fields used for reporting the robot's sport state and associated information. ### SportModeState_ - **stamp** (TimeSpec) - Timestamp of the state data. - **errorCode** (uint32_t) - Error code indicating the status of the sport mode. - **imuState** (IMU) - Structure containing IMU (Inertial Measurement Unit) data. - **mode** (Uint8_t) - The current sports mode of the robot. - 0: idle, default stand - 1: balanceStand - 3: locomotion - 5: lieDown - 6: jointLock - 7: damping - 8: recoveryStand - 9: FreeWalk - 18: ClassicWalk - 19: FastWalk - 20: Euler - **progress** (float) - Action execution status (0.0 for false, 1.0 for true). - **footRaiseHeight** (float) - The height the foot is raised. - **position** (std::array) - The 3D position of the robot (x, y, z). - **bodyHeight** (float) - The height of the robot's body. - **velocity** (std::array) - The 3D velocity of the robot (vx, vy, vz). - **yawSpeed** (float) - The rotational speed around the yaw axis. - **rangeObstacle** (std::array) - Distances to obstacles in different directions. - **pathPoints** (std::array) - An array of path points the robot is currently tracking. ### IMU - **quaternion** (std::array) - Orientation represented as a quaternion (w, x, y, z). - **gyroscope** (std::array) - Angular velocity in radians per second (x, y, z). - **accelerometer** (std::array) - Acceleration in m/s^2 (x, y, z). - **rpy** (std::array) - Roll, Pitch, Yaw angles in radians. - **temperature** (int8_t) - Temperature sensor reading. ### PathPoint - **tFromStart** (float) - Time at which the path point is located from the start. - **x** (float) - X coordinate of the path point. - **y** (float) - Y coordinate of the path point. - **yaw** (float) - Yaw angle at the path point. - **vx** (float) - Velocity along the x-axis. - **vy** (float) - Velocity along the y-axis. - **vyaw** (float) - Yaw angular velocity. ``` -------------------------------- ### C++: Control B2 Robot Motion with SportClient Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Demonstrates how to use the SportClient class in the SDK to send motion commands to the B2 robot, such as balancing, standing, and crouching. It requires the SDK's sport_client library and handles signal interruption for graceful exit. The output is robot motion executed on the B2. ```cpp /** * @file sport_client_test.cpp * @brief Use the class named SportClient to request sport mode * @date 2025-07-10 */ #include #include //Forced close progress void MySigintHandler(int sig) { exit(0); } int main() { signal(SIGINT, MySigintHandler); //Init channel unitree::robot::ChannelFactory::Instance()->Init(0); //Create SportClient unitree::robot::b2::SportClient sport_client; //Set time-out period for request sport_client.SetTimeout(10.0f); //Init SportClient sport_client.Init(); //Use api to balance stand sport_client.BalanceStand(); sleep(3); //Use api to sit down sport_client.StandDown(); sleep(3); return 0; } ``` -------------------------------- ### FastWalk Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Enables or disables the running gait mode. High or low speed levels can be set. ```APIDOC ## POST /api/walk/fast ### Description Enable or disable the running gait mode. ### Method POST ### Endpoint /api/walk/fast ### Parameters #### Request Body - **flag** (boolean) - Required - Set to true to enable fast walk, false to disable. ### Request Example ```json { "flag": true } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ### Remarks High or low speed levels can be set separately. ``` -------------------------------- ### SUBSCRIBE /rt/sportmodestate Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Subscribe to the 'rt/sportmodestate' topic to receive real-time motion data from the robot. This includes position, speed, attitude, and IMU status. The topic is published at a high frequency (500Hz). ```APIDOC ## SUBSCRIBE /rt/sportmodestate ### Description Subscribes to the topic "rt/sportmodestate" to obtain the robot's motion states, including position, speed, and attitude. ### Method SUBSCRIBE ### Endpoint rt/sportmodestate ### Parameters #### Topic Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **state** (unitree_go::msg::dds_::SportModeState_) - A structure containing the robot's current motion state. #### Response Example ```json { "stamp": {"sec": 1678886400, "nanosec": 123456789}, "errorCode": 0, "imu_state": { "quaternion": [0.0, 0.0, 0.0, 1.0], "gyroscope": [0.0, 0.0, 0.0], "accelerometer": [0.0, 0.0, 9.81], "rpy": [0.0, 0.0, 0.0], "temperature": 25 }, "mode": 1, "progress": 0.0, "footRaiseHeight": 0.0, "position": [0.0, 0.0, 0.0], "bodyHeight": 0.5, "velocity": [0.0, 0.0, 0.0], "yawSpeed": 0.0, "rangeObstacle": [1.0, 1.0, 1.0, 1.0], "pathPoints": [ { "tFromStart": 0.0, "x": 0.0, "y": 0.0, "yaw": 0.0, "vx": 0.0, "vy": 0.0, "vyaw": 0.0 } ] } ``` ### Error Handling None specified for subscription. ``` -------------------------------- ### Subscribe to Robot Sport Mode State (C++) Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface This C++ code snippet demonstrates how to subscribe to the 'rt/sportmodestate' topic to receive real-time motion state data from the robot. It includes a callback function to process incoming messages and print position and IMU quaternion data. Dependencies include the unitree/idl/go2/SportModeState_.hpp and unitree/robot/channel/channel_subscriber.hpp headers. ```cpp #include #include //high frequency (500Hz) #define TOPIC_HIGHSTATE "rt/sportmodestate" //low frequency (500Hz) //#define TOPIC_HIGHSTATE "rt/lf/sportmodestate" using namespace unitree::robot; //Callback function void SportModeStateHandler(const void* message) { unitree_go::msg::dds_::SportModeState_ state = *(unitree_go::msg::dds_::SportModeState_*)message; std::cout<<"position: " <Init(0); //Create a subscriber to get sport mode state ChannelSubscriber sport_mode_state_sub_(TOPIC_HIGHSTATE); //Init channel sport_mode_state_sub_.InitChannel(SportModeStateHandler); while(1) { usleep(20000); } return 0; } ``` -------------------------------- ### VisionWalk Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Enables or disables visual walk functionality. When enabled, the robot uses visual input for walking. ```APIDOC ## POST /api/walk/vision ### Description Enable or disable visual walk mode. ### Method POST ### Endpoint /api/walk/vision ### Parameters #### Request Body - **flag** (boolean) - Required - Set to true to enable visual walk, false to disable. ### Request Example ```json { "flag": true } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ``` -------------------------------- ### Euler Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Sets the robot's orientation using Euler angles (roll, pitch, yaw). It is recommended to call BalanceStand before calling Euler. ```APIDOC ## POST /api/pose/euler ### Description Set the robot's orientation using Euler angles. ### Method POST ### Endpoint /api/pose/euler ### Parameters #### Request Body - **roll** (float) - Required - Roll angle in radians, range [-0.6~0.6]. - **pitch** (float) - Required - Pitch angle in radians, range [-0.6~0.6]. - **yaw** (float) - Required - Yaw angle in radians, range [-0.6~0.6]. ### Request Example ```json { "roll": 0.1, "pitch": -0.2, "yaw": 0.3 } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ### Remarks It is recommended to call BalanceStand before calling Euler. ``` -------------------------------- ### MoveToPos Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Commands the robot to move to a specified position (x, y) and yaw angle in the odometer coordinate system. The robot will continue stepping even if the current speed is 0 after initiating continuous walk. ```APIDOC ## POST /api/move/position ### Description Move the robot to a specified position and yaw angle. ### Method POST ### Endpoint /api/move/position ### Parameters #### Request Body - **x** (float) - Required - The target X-coordinate. - **y** (float) - Required - The target Y-coordinate. - **yaw** (float) - Required - The target yaw angle. ### Request Example ```json { "x": 1.0, "y": 0.5, "yaw": 0.1 } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ``` -------------------------------- ### Ai Sport State Data Structure Overview Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface This section outlines the various data fields available within the Ai sport state, including timestamps, error codes, IMU status, sport modes, action progress, and physical attributes like position and velocity. It details the methods for accessing these states and provides a reference for different sport modes. ```cpp TimeSpec stamp(); uint32_t errorCode(); // Error IMU imuState();// IMU status Uint8_t mode();// Sports mode /* Sports mode 0. idle, default stand 1. balanceStand 3. locomotion 5. lieDown 6. jointLock 7. damping 8. recoveryStand 9. FreeWalk 18.ClassicWalk 19.FastWalk 20.Euler */ float progress(); // Action execution status: 0. dance false; 1. dance true float footRaiseHeight();// Leg lift height std::array position();// 3D position float bodyHeight();// Body height std::array velocity();// Three-dimensional velocity float yawSpeed();// Yaw speed std::array rangeObstacle();// Obstacle distance std::array pathPoints();// The current tracked path point ``` -------------------------------- ### HandStand Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Activates or deactivates the handstand function. This is a dangerous function and requires a 3-meter radius clear of people and obstacles. ```APIDOC ## POST /api/action/handstand ### Description Enable or disable the handstand function. ### Method POST ### Endpoint /api/action/handstand ### Parameters #### Request Body - **flag** (boolean) - Required - Set to true to enable handstand, false to disable. ### Request Example ```json { "flag": true } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ### Remarks Ensure a 3-meter radius is clear of people and obstacles before enabling. Unitree Technology is not responsible for damages caused by misoperation. ``` -------------------------------- ### AutoRecoverySet Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Enables or disables the automatic recovery function. When enabled, the robot attempts to recover its balance and defaults to free gait upon success. Ensure a 3-meter radius is clear during recovery. ```APIDOC ## POST /api/recovery/auto ### Description Enable or disable the automatic recovery function. ### Method POST ### Endpoint /api/recovery/auto ### Parameters #### Request Body - **flag** (boolean) - Required - Set to true to enable automatic recovery, false to disable. ### Request Example ```json { "flag": true } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ### Remarks Ensure a 3-meter radius is clear of people and obstacles when the robot is recovering. ``` -------------------------------- ### IMU Data Acquisition Methods Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface This snippet details the methods used to retrieve Inertial Measurement Unit (IMU) data, including orientation as a quaternion, angular velocity, acceleration, and Roll-Pitch-Yaw (RPY) angles. It also includes a method for obtaining the IMU temperature. ```cpp std::array quaternion(); // Quaternion (w, x, y, z) std::array gyroscope(); // Angular velocity (unit: rad/s) std::array accelerometer(); // Acceleration m/(s2) std::array rpy(); // Unit: rad int8_Temperature ();// temperature ``` -------------------------------- ### SwitchMoveMode Source: https://support.unitree.com/home/en/B2_developer/AI%20Motion%20Interface Switches the robot's movement response mode. Continuous response mode ensures the robot always responds to the latest command, while disabling it makes the robot stop after one second without new commands. ```APIDOC ## POST /api/move/mode/switch ### Description Switch the robot's movement response mode between continuous and default. ### Method POST ### Endpoint /api/move/mode/switch ### Parameters #### Request Body - **flag** (boolean) - Required - Set to true to enable continuous response mode, false to disable. ### Request Example ```json { "flag": true } ``` ### Response #### Success Response (200) - **status** (int32_t) - 0 if successful, otherwise an error code. #### Response Example ```json { "status": 0 } ``` ### Remarks Continuous response mode is disabled by default. Use with caution. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.