### Install Documentation and License Files Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/CMakeLists.txt Installs documentation, license, and readme files to the share directory of the installation prefix. Also installs a startup script on non-Windows systems. ```cmake install(DIRECTORY cmake/ DESTINATION ${CMAKE_INSTALL_PREFIX}/share/${PROJECT_PKG_NAME}) install(FILES LICENSE.txt README.md DESTINATION ${CMAKE_INSTALL_PREFIX}/share/${PROJECT_PKG_NAME}/) install(DIRECTORY doc DESTINATION ${CMAKE_INSTALL_PREFIX}/share/${PROJECT_PKG_NAME}) IF (WIN32) ELSE() INSTALL(PROGRAMS startup/initenv.sh DESTINATION startup) ENDIF() ``` -------------------------------- ### CYdLidar Class - C++ Example Source: https://context7.com/ydlidar/ydlidar-sdk/llms.txt This example demonstrates how to use the CYdLidar class to initialize, configure, and start scanning with a YDLIDAR sensor. It covers setting serial port, baud rate, lidar type, sample rate, and other essential parameters. The code also includes a loop for processing incoming scan data. ```APIDOC ## CYdLidar Class - C++ Example ### Description This example demonstrates the basic usage of the `CYdLidar` class for initializing, configuring, and acquiring scan data from a YDLIDAR sensor using C++. ### Method C++ Example ### Endpoint N/A (Local SDK usage) ### Parameters N/A (Configuration is done via `setlidaropt` method) ### Request Example ```cpp #include "CYdLidar.h" #include using namespace ydlidar; int main() { // Initialize system signal handling for graceful shutdown ydlidar::os_init(); // Create LiDAR instance CYdLidar laser; // Configure string properties std::string port = "/dev/ttyUSB0"; laser.setlidaropt(LidarPropSerialPort, port.c_str(), port.size()); // Configure integer properties int baudrate = 230400; laser.setlidaropt(LidarPropSerialBaudrate, &baudrate, sizeof(int)); int lidarType = TYPE_TRIANGLE; // or TYPE_TOF for TOF lidars laser.setlidaropt(LidarPropLidarType, &lidarType, sizeof(int)); int deviceType = YDLIDAR_TYPE_SERIAL; laser.setlidaropt(LidarPropDeviceType, &deviceType, sizeof(int)); int sampleRate = 9; // KHz laser.setlidaropt(LidarPropSampleRate, &sampleRate, sizeof(int)); // Configure boolean properties bool autoReconnect = true; laser.setlidaropt(LidarPropAutoReconnect, &autoReconnect, sizeof(bool)); bool singleChannel = false; laser.setlidaropt(LidarPropSingleChannel, &singleChannel, sizeof(bool)); bool intensity = false; laser.setlidaropt(LidarPropIntenstiy, &intensity, sizeof(bool)); // Configure float properties (angles in degrees, range in meters) float maxAngle = 180.0f; laser.setlidaropt(LidarPropMaxAngle, &maxAngle, sizeof(float)); float minAngle = -180.0f; laser.setlidaropt(LidarPropMinAngle, &minAngle, sizeof(float)); float maxRange = 16.0f; laser.setlidaropt(LidarPropMaxRange, &maxRange, sizeof(float)); float minRange = 0.1f; laser.setlidaropt(LidarPropMinRange, &minRange, sizeof(float)); float scanFrequency = 10.0f; // Hz laser.setlidaropt(LidarPropScanFrequency, &scanFrequency, sizeof(float)); // Initialize and start scanning if (!laser.initialize()) { std::cerr << "Failed to initialize: " << laser.DescribeError() << std::endl; return -1; } if (!laser.turnOn()) { std::cerr << "Failed to start: " << laser.DescribeError() << std::endl; return -1; } // Main scanning loop LaserScan scan; while (ydlidar::os_isOk()) { if (laser.doProcessSimple(scan)) { std::cout << "Received " << scan.points.size() << " points at " << scan.scanFreq << " Hz" << std::endl; // Process individual points for (const auto& point : scan.points) { float angle_deg = point.angle * 180.0 / M_PI; float range_m = point.range; float intensity_val = point.intensity; // Use point data... } } } // Cleanup laser.turnOff(); laser.disconnecting(); return 0; } ``` ### Response N/A (This is a client-side SDK example) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Build and Install YDLIDAR SDK (Static Library) Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md Instructions to build and install the YDLIDAR SDK as a static library using CMake and Make. This involves navigating to the build directory, configuring the build, compiling, and installing. ```shell $cd YDLidar-SDK/build $cmake ../ $make $sudo make install ``` -------------------------------- ### ROS Integration Example Source: https://context7.com/ydlidar/ydlidar-sdk/llms.txt This example demonstrates how to convert YDLidar's `LaserScan` data into ROS `sensor_msgs::LaserScan` for seamless integration with ROS. ```APIDOC ## ROS Integration Example ### Description This C++ code snippet shows how to convert the `LaserScan` data obtained from the YDLidar SDK into the ROS `sensor_msgs::LaserScan` message format. This allows you to publish LiDAR data within a ROS ecosystem. ### Method C++ with ROS ### Endpoint N/A (This is a ROS node example) ### Parameters N/A ### Request Body N/A ### Request Example ```cpp #include "CYdLidar.h" #include #include // Convert YDLidar LaserScan to ROS sensor_msgs::LaserScan void publishScan(ros::Publisher& pub, const LaserScan& scan, const std::string& frame_id) { sensor_msgs::LaserScan scan_msg; // Set timestamp from YDLidar nanosecond timestamp scan_msg.header.stamp.sec = scan.stamp / 1000000000ul; scan_msg.header.stamp.nsec = scan.stamp % 1000000000ul; scan_msg.header.frame_id = frame_id; // Set scan parameters from config scan_msg.angle_min = scan.config.min_angle; scan_msg.angle_max = scan.config.max_angle; scan_msg.angle_increment = scan.config.angle_increment; scan_msg.scan_time = scan.config.scan_time; scan_msg.time_increment = scan.config.time_increment; scan_msg.range_min = scan.config.min_range; scan_msg.range_max = scan.config.max_range; // Calculate array size int size = (scan.config.max_angle - scan.config.min_angle) / scan.config.angle_increment + 1; scan_msg.ranges.resize(size, std::numeric_limits::infinity()); scan_msg.intensities.resize(size, 0); // Fill in range and intensity data for (size_t i = 0; i < scan.points.size(); i++) { int index = std::ceil((scan.points[i].angle - scan.config.min_angle) / scan.config.angle_increment); if (index >= 0 && index < size) { scan_msg.ranges[index] = scan.points[i].range; scan_msg.intensities[index] = scan.points[i].intensity; } } pub.publish(scan_msg); } int main(int argc, char** argv) { ros::init(argc, argv, "ydlidar_node"); ros::NodeHandle nh; ros::Publisher scan_pub = nh.advertise("/scan", 10); ydlidar::os_init(); CYdLidar laser; // Configure LiDAR (use ROS parameters in real implementation) std::string port = "/dev/ttyUSB0"; laser.setlidaropt(LidarPropSerialPort, port.c_str(), port.size()); // ... additional configuration ... if (laser.initialize() && laser.turnOn()) { LaserScan scan; ros::Rate rate(20); while (ros::ok() && ydlidar::os_isOk()) { if (laser.doProcessSimple(scan)) { publishScan(scan_pub, scan, "laser_frame"); } ros::spinOnce(); rate.sleep(); } laser.turnOff(); } laser.disconnecting(); return 0; } ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Install YDLidar-SDK Python API Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/howto/how_to_build_and_install.md Installs the Python API for the YDLidar SDK using pip or by building and installing from the source code. ```shell cd YDLidar-SDK pip install . python setup.py build python setup.py install ``` -------------------------------- ### Build YDLIDAR SDK Source with Examples Disabled Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md Command to build the YDLIDAR SDK from source while disabling the generation of example executables. This is useful for reducing build time or if examples are not needed. ```shell $cmake -DBUILD_EXAMPLES=OFF ../ && make ``` -------------------------------- ### POST /lidar/initialize Source: https://context7.com/ydlidar/ydlidar-sdk/llms.txt Initializes the LiDAR sensor and starts the scanning process. ```APIDOC ## POST /lidar/initialize ### Description Initializes the hardware connection and starts the motor/laser scanning process. ### Method POST ### Endpoint /lidar/initialize ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **status** (boolean) - Returns true if initialization and start were successful. #### Response Example { "status": true } ``` -------------------------------- ### Install CMake and Dependencies on Ubuntu Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/howto/how_to_build_and_install.md Installs CMake, pkg-config, and optionally Python and SWIG for using the Python API on Ubuntu systems using apt. ```shell sudo apt install cmake pkg-config sudo apt-get install python swig sudo apt-get install python-pip ``` -------------------------------- ### Method 1: Link against installed YDLidar SDK Source: https://context7.com/ydlidar/ydlidar-sdk/llms.txt This method demonstrates how to link your CMake project against an already installed YDLidar SDK. ```APIDOC ## Link against installed YDLidar SDK ### Description This CMake configuration finds the installed YDLidar SDK, includes its headers, and links your executable against its libraries. ### Method CMake build system ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```cmake cmake_minimum_required(VERSION 2.8) project(my_lidar_project) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") # Find installed YDLidar SDK find_package(ydlidar_sdk REQUIRED) # Include directories include_directories(${YDLIDAR_SDK_INCLUDE_DIRS}) # Link directories link_directories(${YDLIDAR_SDK_LIBRARY_DIRS}) # Create executable add_executable(my_lidar_app main.cpp) # Link to SDK target_link_libraries(my_lidar_app ${YDLIDAR_SDK_LIBRARIES}) ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Install YDLIDAR SDK Package Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/CMakeLists.txt Configures the installation of the YDLIDAR SDK, including headers, generated headers, and libraries. It sets up the package name, version, and destination directories. ```cmake string(TOUPPER ${PROJECT_NAME} PROJECT_PKG_NAME) install_package( PKG_NAME ${PROJECT_PKG_NAME} LIB_NAME ${PROJECT_NAME} VERSION ${YDLIDAR_SDK_VERSION} INSTALL_HEADERS ${SDK_HEADERS} INSTALL_GENERATED_HEADERS ${GENERATED_HEADERS} DESTINATION ${CMAKE_INSTALL_PREFIX}/include INCLUDE_DIRS ${SDK_INCS} LINK_LIBS ${SDK_LIBS} ) ``` -------------------------------- ### Initialize YDLIDAR SDK and Device Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_c++.md Initializes the system signal handler, creates a CYdLidar instance, and performs the initial device connection and setup. ```c++ #include "CYdLidar.h" ydlidar::os_init(); CYdLidar laser; bool ret = laser.initialize(); ``` -------------------------------- ### Implement LiDAR Data Acquisition in C++ Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_c++.md A complete C++ example demonstrating how to configure LiDAR properties, initialize the device, and enter a loop to process incoming scan data. ```cpp #include "CYdLidar.h" #include using namespace std; using namespace ydlidar; #if defined(_MSC_VER) #pragma comment(lib, "ydlidar_sdk.lib") #endif int main(int argc, char *argv[]) { ydlidar::os_init(); CYdLidar laser; std::map ports = ydlidar::lidarPortList(); std::string port = "/dev/ydlidar"; if(!ports.empty()) { port = ports.begin()->second; } laser.setlidaropt(LidarPropSerialPort, port.c_str(), port.size()); std::string ignore_array; ignore_array.clear(); laser.setlidaropt(LidarPropIgnoreArray, ignore_array.c_str(), ignore_array.size()); int optval = 230400; laser.setlidaropt(LidarPropSerialBaudrate, &optval, sizeof(int)); optval = TYPE_TRIANGLE; laser.setlidaropt(LidarPropLidarType, &optval, sizeof(int)); optval = YDLIDAR_TYPE_SERIAL; laser.setlidaropt(LidarPropDeviceType, &optval, sizeof(int)); optval = 9; laser.setlidaropt(LidarPropSampleRate, &optval, sizeof(int)); optval = 4; laser.setlidaropt(LidarPropAbnormalCheckCount, &optval, sizeof(int)); bool b_optvalue = false; laser.setlidaropt(LidarPropFixedResolution, &b_optvalue, sizeof(bool)); laser.setlidaropt(LidarPropReversion, &b_optvalue, sizeof(bool)); laser.setlidaropt(LidarPropInverted, &b_optvalue, sizeof(bool)); b_optvalue = true; laser.setlidaropt(LidarPropAutoReconnect, &b_optvalue, sizeof(bool)); b_optvalue = false; laser.setlidaropt(LidarPropSingleChannel, &b_optvalue, sizeof(bool)); laser.setlidaropt(LidarPropIntenstiy, &b_optvalue, sizeof(bool)); laser.setlidaropt(LidarPropSupportMotorDtrCtrl, &b_optvalue, sizeof(bool)); laser.setlidaropt(LidarPropSupportHeartBeat, &b_optvalue, sizeof(bool)); float f_optvalue = 180.0f; laser.setlidaropt(LidarPropMaxAngle, &f_optvalue, sizeof(float)); f_optvalue = -180.0f; laser.setlidaropt(LidarPropMinAngle, &f_optvalue, sizeof(float)); f_optvalue = 16.f; laser.setlidaropt(LidarPropMaxRange, &f_optvalue, sizeof(float)); f_optvalue = 0.1f; laser.setlidaropt(LidarPropMinRange, &f_optvalue, sizeof(float)); f_optvalue = 10.f; laser.setlidaropt(LidarPropScanFrequency, &f_optvalue, sizeof(float)); bool ret = laser.initialize(); if (ret) { ret = laser.turnOn(); } else { fprintf(stderr, "%s\n", laser.DescribeError()); fflush(stderr); } while (ret && ydlidar::os_isOk()) { LaserScan scan; if (laser.doProcessSimple(scan)) { fprintf(stdout, "Scan received[%llu]: %u ranges is [%f]Hz\n", scan.stamp, (unsigned int)scan.points.size(), 1.0 / scan.config.scan_time); fflush(stdout); } else { fprintf(stderr, "Failed to get Lidar Data\n"); fflush(stderr); } } laser.turnOff(); laser.disconnecting(); return 0; } ``` -------------------------------- ### Initialize and Start Lidar Scanning Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_network_adapter_tutorial_c++.md Initializes the Lidar device and starts its scanning routine on a separate thread. Includes error handling for initialization failures and starts the motor. Returns false if initialization or turning on fails. ```c++ bool ret = laser.initialize(); if (ret) { ret = laser.turnOn(); } else { fprintf(stderr, "%s\n", laser.DescribeError()); fflush(stderr); } ``` -------------------------------- ### Configure and Initialize LiDAR Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_network_adapter_tutorial_c++.md This documentation outlines how to set LiDAR properties such as network configuration, range, and frequency, and how to start the scanning process. ```APIDOC ## [METHOD] setlidaropt ### Description Configures specific properties for the LiDAR device, such as communication type, network settings, and operational ranges. ### Method C++ SDK Method Call ### Parameters #### Properties - **LidarPropSerialPort** (string) - Required - The IP address of the LiDAR (for TCP). - **LidarPropSerialBaudrate** (int) - Required - The network port of the LiDAR. - **LidarPropDeviceType** (int) - Required - The device type (e.g., YDLIDAR_TYPE_TCP). - **LidarPropMaxRange** (float) - Optional - Maximum detection range in meters. - **LidarPropScanFrequency** (float) - Optional - Scanning frequency in Hz. ### Request Example laser.setlidaropt(LidarPropSerialPort, "192.168.31.200", size); laser.setlidaropt(LidarPropDeviceType, &YDLIDAR_TYPE_TCP, sizeof(int)); ### Response #### Success Response - **ret** (bool) - Returns true if initialization and connection are successful. #### Response Example if (laser.initialize()) { laser.turnOn(); } ``` -------------------------------- ### Build YDLIDAR SDK Source as Shared Library with Examples Disabled Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md Command to build the YDLIDAR SDK from source as a shared library and disable example executables. This combines two common build configurations. ```shell $cmake -DBUILD_EXAMPLES=OFF -DBUILD_SHARED_LIBS=ON ../ && make ``` -------------------------------- ### Initialize and Configure YDLIDAR Device in C++ Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_network_adapter_tutorial_c++.md This snippet shows how to instantiate a CYdLidar object, configure various properties such as port, baudrate, device type, and scan parameters, and start the data acquisition loop. ```cpp #include "CYdLidar.h" #include using namespace std; using namespace ydlidar; #if defined(_MSC_VER) #pragma comment(lib, "ydlidar_sdk.lib") #endif int main(int argc, char *argv[]) { ydlidar::os_init(); CYdLidar laser; std::string port = "192.168.31.200"; laser.setlidaropt(LidarPropSerialPort, port.c_str(), port.size()); int optval = 8000; laser.setlidaropt(LidarPropSerialBaudrate, &optval, sizeof(int)); optval = YDLIDAR_TYPE_TCP; laser.setlidaropt(LidarPropDeviceType, &optval, sizeof(int)); bool ret = laser.initialize(); if (ret) { ret = laser.turnOn(); } while (ret && ydlidar::os_isOk()) { LaserScan scan; if (laser.doProcessSimple(scan)) { fprintf(stdout, "Scan received: %u points\n", (unsigned int)scan.points.size()); } } laser.turnOff(); laser.disconnecting(); return 0; } ``` -------------------------------- ### Install CMake using vcpkg on Windows Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/howto/how_to_build_and_install.md Installs CMake using the vcpkg package manager for both 32-bit and 64-bit Windows projects. It also integrates vcpkg with the build environment. ```shell .\vcpkg install cmake .\vcpkg integrate install .\vcpkg install cmake:x64-windows .\vcpkg integrate install ``` -------------------------------- ### Build YDLidar-SDK on Linux Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/howto/how_to_build_and_install.md Clones the YDLidar-SDK repository, creates a build directory, configures the project with CMake, compiles the SDK, and installs it. ```shell git clone https://github.com/YDLIDAR/YDLidar-SDK.git cd YDLidar-SDK mkdir build cd build cmake .. make sudo make install ``` -------------------------------- ### Start Lidar Motor (C++) Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md Initiates the operation of the Lidar's motor. Returns RESULT_OK on success. ```C++ result_t startMotor(); ``` -------------------------------- ### SDK Initialization and Control Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md Functions for initializing, starting, stopping, and uninitializing the YDLIDAR SDK and device. ```APIDOC ## initialize ### Description Initializes the SDK and the LiDAR device. ### Method bool ### Endpoint N/A (C++ function) ### Parameters None ### Request Example ```cpp CYdLidar laser; if (laser.initialize()) { // Initialization successful } ``` ### Response #### Success Response (true) - SDK and device initialized successfully. #### Response Example ```json { "success": true } ``` ## turnOn ### Description Starts the device scanning routine on a separate thread and enables the motor. ### Method bool ### Endpoint N/A (C++ function) ### Parameters None ### Request Example ```cpp CYdLidar laser; if (laser.turnOn()) { // Scanning started successfully } ``` ### Response #### Success Response (true) - Scanning started successfully. #### Response Example ```json { "success": true } ``` ## turnOff ### Description Stops the device scanning thread and disables the motor. ### Method bool ### Endpoint N/A (C++ function) ### Parameters None ### Request Example ```cpp CYdLidar laser; if (laser.turnOff()) { // Scanning stopped successfully } ``` ### Response #### Success Response (true) - Scanning stopped successfully. #### Response Example ```json { "success": true } ``` ## disconnecting ### Description Uninitializes the SDK and disconnects the LiDAR device. ### Method void ### Endpoint N/A (C++ function) ### Parameters None ### Request Example ```cpp CYdLidar laser; laser.disconnecting(); ``` ### Response None ``` -------------------------------- ### Method 2: Include SDK as subdirectory Source: https://context7.com/ydlidar/ydlidar-sdk/llms.txt This method shows how to include the YDLidar SDK source directly into your project as a subdirectory, which avoids the need for separate installation. ```APIDOC ## Include SDK as subdirectory ### Description This CMake configuration includes the YDLidar SDK source code as a subdirectory of your project. This approach is useful when you don't want to install the SDK system-wide. ### Method CMake build system ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```cmake cmake_minimum_required(VERSION 2.8) project(my_lidar_project) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") # Include YDLidar SDK directories include_directories( ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/YDLidar-SDK ${CMAKE_SOURCE_DIR}/YDLidar-SDK/src ${CMAKE_CURRENT_BINARY_DIR}/YDLidar-SDK ) # Add SDK as subdirectory add_subdirectory(YDLidar-SDK) # Create executable add_executable(my_lidar_app main.cpp) # Link to SDK target_link_libraries(my_lidar_app ydlidar_sdk) ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Initialize System Signal Handling Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_c.md Initializes system signal handling, specifically installing a SIGINT handler for Ctrl+C interruption. This ensures graceful shutdown. ```c os_init(); ``` -------------------------------- ### Manage YDLidar Lifecycle in C++ Source: https://context7.com/ydlidar/ydlidar-sdk/llms.txt This snippet demonstrates the full lifecycle of a YDLidar device using the C++ SDK. It covers configuring device options, initializing the connection, starting the scanning thread, performing data acquisition, and safely shutting down the device. ```cpp #include "CYdLidar.h" #include int main() { ydlidar::os_init(); CYdLidar laser; std::string port = "/dev/ttyUSB0"; laser.setlidaropt(LidarPropSerialPort, port.c_str(), port.size()); int baudrate = 230400; laser.setlidaropt(LidarPropSerialBaudrate, &baudrate, sizeof(int)); int lidarType = TYPE_TRIANGLE; laser.setlidaropt(LidarPropLidarType, &lidarType, sizeof(int)); int deviceType = YDLIDAR_TYPE_SERIAL; laser.setlidaropt(LidarPropDeviceType, &deviceType, sizeof(int)); bool ret = laser.initialize(); if (!ret) { std::cerr << "Initialization failed: " << laser.DescribeError() << std::endl; return -1; } ret = laser.turnOn(); if (!ret) { std::cerr << "Failed to start scanning: " << laser.DescribeError() << std::endl; laser.disconnecting(); return -1; } LaserScan scan; for (int i = 0; i < 100 && ydlidar::os_isOk(); i++) { if (laser.doProcessSimple(scan)) { std::cout << "Scan " << i << ": " << scan.points.size() << " points" << std::endl; } } laser.turnOff(); laser.disconnecting(); return 0; } ``` -------------------------------- ### Triangle LiDAR Initialization and Scanning Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md This C++ code snippet shows how to initialize the YDLIDAR SDK, configure various parameters for a Triangle LiDAR, start the scanning process, and continuously process incoming scan data. ```APIDOC ## Triangle LiDAR Initialization and Scanning ### Description This example demonstrates the initialization and usage of the YDLIDAR SDK with a Triangle LiDAR sensor. It covers setting up serial port, baud rate, LiDAR type, and other essential configurations. The code then starts the LiDAR scanning, processes scan data in a loop, and handles potential errors. ### Method This is a C++ code example demonstrating SDK usage, not a direct API endpoint. ### Endpoint N/A (SDK Usage Example) ### Parameters This section details the configuration parameters set for the LiDAR sensor using `setlidaropt`: #### String Properties - **LidarPropSerialPort** (string) - Required - The serial port the LiDAR is connected to (e.g., \"/dev/ydlidar\"). - **LidarPropIgnoreArray** (string) - Optional - A string to ignore specific data points. #### Integer Properties - **LidarPropSerialBaudrate** (int) - Required - The baud rate for serial communication (e.g., 230400). - **LidarPropLidarType** (int) - Required - Specifies the LiDAR type, set to `TYPE_TRIANGLE` for Triangle LiDAR. - **LidarPropDeviceType** (int) - Required - Specifies the device type, set to `YDLIDAR_TYPE_SERIAL` for serial devices. - **LidarPropSampleRate** (int) - Optional - The sample rate for the LiDAR (e.g., 9). - **LidarPropAbnormalCheckCount** (int) - Optional - The number of abnormal checks before reporting an error (e.g., 4). #### Boolean Properties - **LidarPropFixedResolution** (bool) - Optional - Whether to use fixed angle resolution (false). - **LidarPropReversion** (bool) - Optional - Whether to reverse the scan direction (false). - **LidarPropInverted** (bool) - Optional - Whether to invert the scan (false). - **LidarPropAutoReconnect** (bool) - Optional - Whether to enable automatic reconnection (true). - **LidarPropSingleChannel** (bool) - Optional - Whether to use one-way communication (false). - **LidarPropIntenstiy** (bool) - Optional - Whether to enable intensity data (false). - **LidarPropSupportMotorDtrCtrl** (bool) - Optional - Whether to support motor DTR control (false). #### Float Properties - **LidarPropMaxAngle** (float) - Optional - The maximum scan angle in degrees (e.g., 180.0f). - **LidarPropMinAngle** (float) - Optional - The minimum scan angle in degrees (e.g., -180.0f). - **LidarPropMaxRange** (float) - Optional - The maximum detection range in meters (e.g., 16.f). - **LidarPropMinRange** (float) - Optional - The minimum detection range in meters (e.g., 0.1f). - **LidarPropScanFrequency** (float) - Optional - The desired scan frequency in Hz (e.g., 10.f). ### Request Example ```cpp #include "CYdLidar.h" #include #include #include #include using namespace std; using namespace ydlidar; #if defined(_MSC_VER) #pragma comment(lib, "ydlidar_sdk.lib") #endif int main(int argc, char *argv[]) { // init system signal ydlidar::os_init(); CYdLidar laser; // Configure LiDAR properties... std::string port = "/dev/ydlidar"; laser.setlidaropt(LidarPropSerialPort, port.c_str(), port.size()); int optval = 230400; laser.setlidaropt(LidarPropSerialBaudrate, &optval, sizeof(int)); optval = TYPE_TRIANGLE; laser.setlidaropt(LidarPropLidarType, &optval, sizeof(int)); // ... other setlidaropt calls ... // Initialize and start scanning bool ret = laser.initialize(); if (ret) { ret = laser.turnOn(); } else { fprintf(stderr, "%s\n", laser.DescribeError()); fflush(stderr); } // Process scan data while (ret && ydlidar::os_isOk()) { LaserScan scan; if (laser.doProcessSimple(scan)) { fprintf(stdout, "Scan received[%llu]: %u ranges is [%f]Hz\n", scan.stamp, (unsigned int)scan.points.size(), 1.0 / scan.config.scan_time); fflush(stdout); } else { fprintf(stderr, "Failed to get Lidar Data\n"); fflush(stderr); } } // Stop and disconnect laser.turnOff(); laser.disconnecting(); return 0; } ``` ### Response #### Success Response (200) This example does not directly return HTTP responses. Instead, it processes scan data and prints information to standard output. - **scan.stamp** (unsigned long long) - Timestamp of the scan. - **scan.points.size()** (unsigned int) - Number of data points in the scan. - **1.0 / scan.config.scan_time** (float) - Scan frequency in Hz. #### Response Example ``` Scan received[1678886400]: 1024 ranges is [10.000000]Hz ``` #### Error Handling - If `laser.initialize()` fails, an error message is printed to stderr using `laser.DescribeError()`. - If `laser.doProcessSimple(scan)` fails, "Failed to get Lidar Data" is printed to stderr. ``` -------------------------------- ### Explanation: Turning On the LiDAR Device Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_python.md This snippet attempts to turn on the LiDAR device and start its scanning routine, which runs in a separate thread. It returns false if the lidar stalls or experiences power supply issues. ```python if ret: ret = laser.turnOn(); ``` -------------------------------- ### Define Build Options Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/CMakeLists.txt Defines boolean options that control which parts of the SDK are built. Users can enable or disable building shared libraries, examples, C# bindings, and tests. ```cmake option( BUILD_SHARED_LIBS "Build shared libraries." OFF) option( BUILD_EXAMPLES "Build Example." ON) option( BUILD_CSHARP "Build CSharp." OFF) option( BUILD_TEST "Build Test." OFF) ``` -------------------------------- ### Start Lidar Scan (C++) Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md Initiates the Lidar scanning process. Can optionally force a restart and has a timeout parameter. This function should be called before attempting to grab scan data. Returns RESULT_OK on success. ```C++ virtual result_t startScan(bool force = false, uint32_t timeout = DEFAULT_TIMEOUT); ``` -------------------------------- ### Create beginner_tutorials Directories Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_python.md This snippet demonstrates how to create the necessary directory structure for the lidar tutorial project using shell commands. ```shell mkdir beginner_tutorials cd beginner_tutorials ``` -------------------------------- ### Initialize YDLIDAR SDK and System Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_network_adapter_tutorial_c++.md Includes necessary headers, initializes the SDK's system signals for Ctrl-C handling, and creates a handle for the Lidar device. ```c++ #include "CYdLidar.h" // ... ydlidar::os_init(); CYdLidar laser; ``` -------------------------------- ### Build Project from Command Line Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_network_adapter_tutorial_c++.md Standard sequence of commands to create a build directory, run CMake configuration, and compile the project using make. ```bash mkdir build cd build cmake .. make j4 ``` -------------------------------- ### YDLIDAR SDK Initialization and Configuration Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_c.md This snippet covers the essential steps for initializing the YDLIDAR SDK, including system initialization, lidar creation, port detection, and setting various configuration parameters (serial port, baud rate, lidar type, sample rate, boolean properties, and float properties). ```APIDOC ## YDLIDAR SDK Initialization and Configuration ### Description This section details the process of initializing the YDLIDAR SDK and configuring the lidar device. It includes steps for system initialization, creating a lidar handle, discovering available serial ports, and setting various properties such as serial port, baud rate, lidar type, sample rate, and other boolean and float parameters. ### Method C++ SDK functions ### Endpoint N/A (Local SDK operations) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```c++ #include "ydlidar_sdk.h" os_init(); YDLidar *laser = lidarCreate(); // string prop char port[50] = "/dev/ydlidar"; LidarPort ports; int size = lidarPortList(&ports); int i = 0; for(i =0; i < size; i++) { printf("port: %s\n", ports.port[i].data); /// last port strcpy(port, ports.port[i].data); } setlidaropt(laser, LidarPropSerialPort, port, sizeof(port)); strcpy(port, ""); setlidaropt(laser, LidarPropIgnoreArray,port, sizeof(port)); // int prop int i_optvalue = 512000; setlidaropt(laser, LidarPropSerialBaudrate, &i_optvalue, sizeof(int)); i_optvalue = TYPE_TOF; setlidaropt(laser, LidarPropLidarType, &i_optvalue, sizeof(int)); i_optvalue = YDLIDAR_TYPE_SERIAL; setlidaropt(laser, LidarPropDeviceType, &i_optvalue, sizeof(int)); i_optvalue = 20; setlidaropt(laser, LidarPropSampleRate, &i_optvalue, sizeof(int)); // bool prop bool b_optval = true; setlidaropt(laser, LidarPropAutoReconnect, &b_optval, sizeof(bool)); b_optval = false; setlidaropt(laser, LidarPropSingleChannel, &b_optval, sizeof(bool)); setlidaropt(laser, LidarPropIntenstiy, &b_optval, sizeof(bool)); setlidaropt(laser, LidarPropInverted, &b_optval, sizeof(bool)); setlidaropt(laser, LidarPropReversion, &b_optval, sizeof(bool)); setlidaropt(laser, LidarPropSupportMotorDtrCtrl, &b_optval, sizeof(bool)); setlidaropt(laser, LidarPropFixedResolution, &b_optval, sizeof(bool)); // float prop float f_optval = 10.f; setlidaropt(laser, LidarPropScanFrequency, &f_optval, sizeof(float)); f_optval = 180.0f; setlidaropt(laser, LidarPropMaxAngle, &f_optval, sizeof(float)); f_optval = -180.0f; setlidaropt(laser, LidarPropMinAngle, &f_optval, sizeof(float)); f_optval = 64.f; setlidaropt(laser, LidarPropMaxRange, &f_optval, sizeof(float)); f_optval = 0.05f; setlidaropt(laser, LidarPropMinRange, &f_optval, sizeof(float)); bool ret = initialize(laser); ``` ### Response #### Success Response (200) N/A (This is an initialization and configuration step, not a direct API call with a response) #### Response Example N/A ``` -------------------------------- ### Install Python Scripts with CMake Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/csharp/examples/CMakeLists.txt This CMake script locates all Python files (*.py) in the current source directory and installs them to the 'bin' destination. It sets specific file permissions for the installed executables, ensuring owner and group execute permissions, along with read permissions for others. ```cmake set(curdir ${CMAKE_CURRENT_SOURCE_DIR}) FILE(GLOB APP_LIST "${curdir}/*.py") foreach(child ${APP_LIST}) install(FILES ${child} DESTINATION bin PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) endforeach() ``` -------------------------------- ### Explanation: Initializing the SDK and LiDAR Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_python.md This code attempts to initialize the YDLIDAR SDK and the connected LiDAR device. It returns false if initialization fails due to issues like incorrect port, permissions, baud rate, or lidar type. ```c++ // initialize SDK and LiDAR ret = laser.initialize(); ``` -------------------------------- ### Start Scanning and Process Data Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_c++.md Starts the device scanning routine and enters a loop to process incoming LaserScan data until the system is shut down or interrupted. ```c++ if (laser.turnOn()) { while (ydlidar::os_isOk()) { LaserScan scan; if (laser.doProcessSimple(scan)) { printf("Scan received: %u points\n", (unsigned int)scan.points.size()); } } } ``` -------------------------------- ### Initialize and Configure YDLIDAR in C Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/tutorials/writing_lidar_tutorial_c.md This code demonstrates the lifecycle of a YDLIDAR device, including port discovery, setting various configuration properties (string, integer, boolean, and float), and entering a processing loop to capture scan data. It requires the ydlidar_sdk library and handles both Windows and POSIX environments. ```c #include #include #include #ifdef WIN32 #include #else #include #endif #include "ydlidar_sdk.h" #if defined(_MSC_VER) #pragma comment(lib, "ydlidar_sdk.lib") #endif int main(int argc, const char *argv[]) { os_init(); YDLidar *laser = lidarCreate(); char port[50] = "/dev/ydlidar"; LidarPort ports; int size = lidarPortList(&ports); for(int i = 0; i < size; i++) { printf("port: %s\n", ports.port[i].data); strcpy(port, ports.port[i].data); } setlidaropt(laser, LidarPropSerialPort, port, sizeof(port)); int i_optvalue = 512000; setlidaropt(laser, LidarPropSerialBaudrate, &i_optvalue, sizeof(int)); bool b_optval = true; setlidaropt(laser, LidarPropAutoReconnect, &b_optval, sizeof(bool)); bool ret = initialize(laser); if(ret) { ret = turnOn(laser); } LaserFan scan; LaserFanInit(&scan); while (ret && os_isOk()) { if(doProcessSimple(laser, &scan)) { fprintf(stdout, "Scan received[%llu]: %u ranges\n", scan.stamp, (unsigned int)scan.npoints); } } LaserFanDestroy(&scan); turnOff(laser); disconnecting(laser); lidarDestroy(&laser); return 0; } ``` -------------------------------- ### Get Lidar Status and Information (C++) Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md Provides functions to check the connection status, scanning status, and retrieve the SDK version. It also includes a function to get the device's health status and detailed information, with configurable timeouts for these operations. ```C++ virtual const char *DescribeError(bool isTCP = true); virtual std::string getSDKVersion(); virtual bool isscanning() const; virtual bool isconnected() const; virtual result_t getHealth(device_health &health, uint32_t timeout = DEFAULT_TIMEOUT); virtual result_t getDeviceInfo(device_info &info, uint32_t timeout = DEFAULT_TIMEOUT); ``` -------------------------------- ### SDK Initialization and Device Control (C) Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md Functions for initializing the YDLIDAR SDK and controlling the lidar device's operation. `initialize` prepares the SDK for use, and `turnOn` starts the lidar's scanning routine on a separate thread. `doProcessSimple` is mentioned as a prerequisite for obtaining scan data after `turnOn` is successful. ```C /** * Initialize the SDK. * @return true if successfully initialized, otherwise false. */ bool initialize(YDLidar *lidar); /** * Start the device scanning routine which runs on a separate thread. * @return true if successfully started, otherwise false. */ bool turnOn(YDLidar *lidar); /** * @brief Get the LiDAR Scan Data. turnOn is successful before doProcessSimple scan data. * @param[in] lidar LiDAR instance * @param[out] outscan LiDAR Scan Data * @return true if successfully started, otherwise false. */ ``` -------------------------------- ### Initialize and Scan with YDLIDAR SDK in Python Source: https://github.com/ydlidar/ydlidar-sdk/blob/master/doc/YDLIDAR_SDK_API_for_Developers.md This Python script demonstrates how to initialize the YDLIDAR device, configure its parameters (serial port, baud rate, lidar type, etc.), and continuously process scan data. It includes error handling for initialization and data processing, and a loop to fetch scan data at a specified frequency. ```Python import os import ydlidar import time if __name__ == "__main__": ydlidar.os_init(); laser = ydlidar.CYdLidar(); laser.setlidaropt(ydlidar.LidarPropSerialPort, "/dev/ydlidar"); laser.setlidaropt(ydlidar.LidarPropSerialBaudrate, 230400); laser.setlidaropt(ydlidar.LidarPropLidarType, ydlidar.TYPE_TRIANGLE); laser.setlidaropt(ydlidar.LidarPropDeviceType, ydlidar.YDLIDAR_TYPE_SERIAL); laser.setlidaropt(ydlidar.LidarPropScanFrequency, 10.0); laser.setlidaropt(ydlidar.LidarPropSampleRate, 9); laser.setlidaropt(ydlidar.LidarPropSingleChannel, False); ret = laser.initialize(); if ret: ret = laser.turnOn(); scan = ydlidar.LaserScan(); while ret and ydlidar.os_isOk() : r = laser.doProcessSimple(scan); if r: print("Scan received[",scan.stamp,"]:",scan.points.size(),"ranges is [",1.0/scan.config.scan_time,"]Hz"); else : print("Failed to get Lidar Data") time.sleep(0.05); laser.turnOff(); laser.disconnecting(); ```