Перейти к основному содержанию
Версия документа: V1.0; дата редакции: 2024-10-12.

Обзор

Camera SDK MRDVS для Linux включает примеры на C/C++, Java (HTTP-сервис), ROS и ROS 2. Примеры показывают базовый рабочий процесс SDK; добавьте логику приложения и обработку ошибок, необходимые для вашего проекта. Сначала завершите настройку среды, выполните установочный скрипт и проверьте каталоги примеров. Затем следуйте разделу компиляции и запуска для нужного языка. В приложении приведены способы установки распространённых зависимостей и тестовых пакетов.

Система и среда

Совместимые системы и версии зависимостей

Поддерживаются следующие системы Linux. Версии программ по умолчанию приведены ниже:

2.2 Проверка версии системы и приложений

2.2.1 Проверка версии системы

Результат:
View system version related icons
Номер версии выпуска операционной системы: 5.15.0
  • Основной номер версии: 5
  • Номер версии: 15 [Нечётные номера соответствуют версиям разработки, чётные — стабильным версиям]
  • Номер редакции: 0 [Количество изменений]
  • Номер редакции этой версии: 97
  • Версия ядра: #107~20.0.4.1; обычно версия системы совпадает с версией ядра

2.2.2 Проверка версии CMake

result:
View Cmake version related icons
Отображается версия CMake 3.16.3

2.2.3 Проверка версии GCC

result:
View Gcc version related icons
Номер версии находится в синем поле в левом нижнем углу. В данном примере версия: 9.4.0

2.2.4 Просмотр версии OpenCV

result:
View Opencv version related icons
В данном примере версия — 3.2.0

2.2.5 Проверка версии PCL

result: В данном примере версия — 1.8.1

2.2.6 Просмотр версии ROS

result:
View ROS version related icons
В данном примере версия — eloquent (версия ROS 2, соответствующая Ubuntu 18.04)
View ROS version related icon 2
В данном примере версия — noetic (версия ROS 1, соответствующая Ubuntu 20)

2.3 Создание базовой среды разработки

Перед установкой необходимо обновить список пакетов:
Результат выглядит следующим образом:
Illustrations related to building a basic development environment

2.3.1 Установка CMake

Installation Cmake related icons

2.3.2 Установка GCC

Install Gcc related icons

2.4 Создание дополнительной среды разработки

2.4.1 Установка OpenCV [для отображения изображений камеры]

Install Opencv [can display camera images] related icons

2.4.2 Установка PCL [для отображения облака точек]

Install Pcl [can display point cloud] related icons

Подготовка примеров кода

3.1 Выполнение установочного скрипта

  1. Распакуйте файл Lanxin-MRDVS и перейдите в папку Lanxin-MRDVS.
Illustrations related to executing the installation script
  1. Щёлкните правой кнопкой мыши и откройте консоль.
  2. Выполните скрипт install.sh.
Illustration related to executing the installation script 2
  1. Перейдите в каталог /opt/ и проверьте успешность установки.
Illustration related to executing the installation script 3
  1. Если папка найдена, установка выполнена успешно.
  2. Если установка не удалась, вручную добавьте её в каталог opt.
  3. Выполните скрипт set_socket_buffer_size.sh.
Illustrations related to executing the installation script 4
  1. На этом установочный скрипт выполнен полностью.

3.2 Обзор примеров кода

Перейдите в каталог Sample. Его содержимое выглядит следующим образом:
Illustrations related to sample code introduction
  • Папка C содержит код на C и C++.
  • Папка Java содержит HTTP-сервер для косвенного вызова SDK.
  • Папка Ros содержит пример ROS.
  • Папка Ros2 содержит пример ROS 2.

3.2.1 Примеры кода C и C++

Перейдите в каталог C. Его содержимое выглядит следующим образом:
Illustrations related to C and C++ sample code
Каталог содержит 9 папок и один файл CMakeLists; в каждой папке находится файл cpp. Основные функции каждого файла cpp следующие:
  • application_obstacle: получение данных потока камеры, включение алгоритма объезда препятствий и вывод результатов алгоритма;
  • application_pallet: получение данных потока камеры, включение алгоритма паллет и вывод результатов алгоритма;
  • arm_local_camera: вызов SDK на камере [ARM] и получение данных потока;
  • frame_callback: получение данных потока камеры с помощью callback-функции;
  • multi_cameras: открытие нескольких камер и получение потоковых данных;
  • single_camera: открытие одной камеры и получение потоковых данных;
  • single_camera2: получение данных кадра через структуру.
Выбирайте разные примеры кода для тестирования и изменения в зависимости от задачи.

3.2.2 Пример кода Java

Перейдите в каталог java. Его содержимое выглядит следующим образом:
Illustrations related to Java sample code
Каталог содержит две папки, файл postman.json и README.
  • Config: папка с конфигурацией сервера;
  • Middleware: серверное промежуточное ПО;
  • LxCamera.postman_collection.json: файл конфигурации Postman;
  • README: руководство по использованию виртуального сервера Java.

3.2.3 Пример кода ROS

Перейдите в каталог ros. Его содержимое выглядит следующим образом:
Illustrations related to ROS sample code
  • lx_camera_node_ws: папка содержит стандартный драйвер ROS;
  • README.EN: на английском языке объясняется, как скомпилировать узел и создать новый узел.

3.2.4 Пример кода ROS 2

Перейдите в каталог ros2. Его содержимое выглядит следующим образом:
ROS2 sample code related images
  • lx_camera_node_ws: папка содержит стандартный драйвер ROS 2;
  • README.EN: на английском языке объясняется, как скомпилировать узел и создать новый узел.

3.2.5 Пример кода ros-v1pro

Перейдите в каталог ros-v1pro. Его содержимое выглядит следующим образом:
Illustrations related to ros-v1pro sample code
  • src: папка содержит стандартный драйвер ROS;
  • README: объясняет, как использовать этот узел;
  • README.pdf: объясняет, как использовать этот узел.

Компиляция и запуск примеров

4.1 Компиляция и запуск примеров C и C++

Перейдите в папку C в каталоге примера:
Illustrations related to compiling and running C and C++ sample code
Откройте терминал в папке C и выполните:
После успешного выполнения перейдите в папку build. Её содержимое должно выглядеть следующим образом:
Illustrations related to compiling and running C and C++ sample code 2
Исполняемый файл находится в каталоге bin. После перехода в каталог bin должно отображаться следующее:
Illustrations related to compiling and running C and C++ sample code 3
Будут скомпилированы все примеры, кроме примера arm. Имя исполняемого файла совпадает с именем папки примера, поэтому его можно запустить напрямую.

4.2 Процесс запуска примера Java

Пример Java отличается от других примеров. Он не содержит исходный код напрямую, а предоставляет HTTP-сервер и пример Postman. Если нужно косвенно управлять камерой через HTTP, выберите пример Java и перейдите в папку java. Её содержимое выглядит следующим образом:
Illustrations related to the java sample running process
Процесс запуска выглядит следующим образом:
  • Перейдите в папку config и измените поля http_sever_host и http_sever_port в файле Configs.json:
  • Перейдите в папку middleware и выполните скрипт start.sh, чтобы включить сервер передачи данных.
Illustrations related to the java sample running process 3
  • Откройте файл LxCamera.postman_collection.json в Postman и отправьте данные на порт примера.

4.3 Компиляция и запуск примера ROS

Перейдите в папку ROS, откройте консоль и выполните:
Illustrations related to compiling and running ROS sample code
Illustrations related to compiling and running ROS sample code 2
Щёлкните правой кнопкой мыши, откройте консоль, перейдите в папку lx_camera_node_ws и выполните:
Illustrations related to compiling and running ROS sample code 3
После успешного выполнения отобразится следующее:
Illustrations related to compiling and running ROS sample code 4
На этом этапе в папке будут скомпилированы и созданы каталоги devel и build:
Illustrations related to compiling and running ROS sample code 5
Выполните следующие команды, чтобы загрузить среду и запустить узел с помощью roslaunch:
Сверху вниз показаны: запуск обычных узлов, запуск двух узлов алгоритма объезда препятствий, запуск узлов алгоритма объезда препятствий и запуск узлов алгоритма паллет. Одновременно можно включить только один узел.

4.4 Компиляция и запуск примера ROS 2

Перейдите в папку ros2. Её содержимое выглядит следующим образом:
Illustrations related to compiling and running ROS2 sample code
Пример узла ROS компилируется с помощью colcon. Сначала установите инструменты компиляции:
Illustrations related to compiling and running ROS2 sample code 2
Затем установите пакет зависимости ros-pcl. Замените foxy на дистрибутив ROS 2, установленный в вашей системе:
После установки перейдите в каталог lx_camera_node_ws и соберите проект:
В зависимости от производительности компьютера компиляция обычно занимает от 30 до 120 секунд. После успешной компиляции отобразится следующее:
Illustrations related to compiling and running ROS2 sample code 3
Некоторые предупреждения вызваны проблемами совместимости версий и не требуют обработки. После завершения компиляции содержимое папки выглядит следующим образом:
Illustrations related to compiling and running ROS2 sample code 4
Выполните следующие команды, чтобы загрузить среду и запустить узел с помощью ros2 launch:
Сверху вниз показаны: запуск обычных узлов, запуск двух узлов алгоритма объезда препятствий, запуск узлов алгоритма объезда препятствий и запуск узлов алгоритма паллет. Одновременно можно включить только один узел.

4.5 Компиляция и запуск примера ros-v1pro

ros-v1pro — специализированный драйвер ROS для камеры V1PRO. В папке ros-v1pro находится файл README.pdf с подробным описанием драйвера. В этом документе приведён только краткий обзор: Перейдите в папку ros-v1pro и скомпилируйте её:
Illustrations related to compiling and running the ros-v1pro sample code 2
Загрузите среду:
Illustrations related to compiling and running the ros-v1pro sample code 3
Наконец, запустите узел:
  • roslaunch lx_camera_ros localization.launch
  • roslaunch lx_camera_ros mapping.launch
  • roslaunch lx_camera_ros sensor_sim.launch
Сверху вниз показаны: запуск узла позиционирования, запуск узла картографирования и запуск узла виртуальных данных. Одновременно можно включить только один узел.

Справочник по примерам кода

В этом разделе весь код и псевдокод разделены на несколько частей. Как правило, всё содержимое одного раздела относится к одному файлу. Если для специальных файлов не приведено подробное описание, в исходных файлах описаны только общие модули. Подробные пояснения приведены в комментариях к коду.

5.1 C и C++

5.1.1 CMakeLists

5.1.2 application_obstacle и application_pallet

5.1.3 arm_local_camera

5.1.4 frame_callback

5.1.5 multi_cameras

5.1.6 single_camera

5.1.7 single_camera2

5.2 Java

Пример Java предоставляет только HTTP-сервер, поэтому здесь описаны интерфейс и формат сообщений. Откройте файл примера в Postman, как показано ниже: Все сообщения отправляются методом POST. Перед отправкой измените IP-адрес на IP-адрес сервера, но не изменяйте URL: он жёстко задан внутри сервера. Формат и содержимое ответа находятся в теле сообщения. В примере доступны следующие интерфейсы:
java related icons 2
  1. DcGetApiVersion: получить номер версии SDK; параметры не требуются.
java related icons 3
  1. DcSetInfoOutput: задать путь для вывода журнала SDK. Параметры:
  • log_path: путь вывода журнала;
  • print_level: уровень вывода журнала;
  • enable_screen_print: выводится ли журнал в консоль.
  1. DcLog: вывести сообщение в журнал SDK. Любое переданное содержимое будет записано в журнал SDK.
  2. DcGetDeviceList: получить список устройств; входные параметры не требуются, вывод имеет формат JSON.
  3. DcOpenDevice: открыть устройство и передать следующие параметры:
java related icons 4
  • open_mode: режим открытия камеры;
  • param: параметры открытия камеры.
  1. DcStartStream: запустить передачу потоковых данных с выбранной камеры. Входные параметры:
java related icons 5
  • handle: дескриптор камеры, возвращаемый функцией DcOpenDevice.
  1. DcSetCmd: отправить команды камере. Передайте следующие параметры:
java related icons 6
  • handle: дескриптор настраиваемой камеры;
  • cmd: номер команды.
  1. DcGetPtrValue: получить данные указателя (изображение, параметры и т. д.). Передайте следующие параметры:
  • handle: дескриптор настраиваемой камеры;
  • cmd: номер команды.
  1. DcSetIntValue: задать параметры камеры типа int. Входные параметры:
java related icons 7
  • handle: дескриптор настраиваемой камеры;
  • cmd: номер команды;
  • value: задаваемое значение.
  1. DcGetIntValue: получить параметр устройства типа int. Входные параметры:
  • handle: дескриптор настраиваемой камеры;
  • cmd: номер команды.
  1. Другие соответствующие инструкции приведены в таблице ниже:

5.3 ROS 1 и ROS 2

В описании ROS рассматриваются не исходный код драйвера, а параметры конфигурации в launch-файле, их настройка, а также отправка и подписка на сообщения. Предоставленный узел ROS уже содержит большинство функций, поэтому напрямую изменять исходный код драйвера не рекомендуется. При особых требованиях сначала изучите поток выполнения в примере C++, а затем изменяйте исходный код драйвера. При запуске драйвера ROS убедитесь, что в системном пути по умолчанию присутствует только одна версия OpenCV и PCL. В противном случае при связывании библиотеки ROS возникнет ошибка, которая может привести к сбою компиляции или аварийному завершению во время выполнения.

5.3.1 Описание launch-файлов ROS 1

5.3.1.1 Все launch-файлы
  1. В папке src/launch находятся следующие файлы:
All launch file related icons
  • localization.launch: файл запуска узлов визуального позиционирования;
  • lx_camera_ros.launch: файл запуска обычных узлов;
  • mapping.launch: файл запуска визуального картографирования;
  • obstacle.launch: файл запуска алгоритма объезда препятствий;
  • obstacleV2.launch: файл запуска алгоритма объезда препятствий V2;
  • pallet.launch: файл запуска алгоритма паллет;
  • sensor_sim.launch: файл запуска для имитации данных позиционирования.
  1. Запускайте разные функции узла с помощью разных launch-файлов. Кроме localization, mapping и sensor, набор параметров во всех узлах одинаков, но их значения различаются. Подробности приведены в следующих разделах. Описание параметров трёх launch-файлов localization, mapping и sensor см. в разделе об узле ros-v1pro.
5.3.1.2 IP камеры, настройка потока и рабочего режима, единица облака точек и т. д.
  • ip: IP-адрес подключаемой камеры. Если задано 0, по умолчанию подключается первая камера;
  • log_path: путь хранения журнала SDK; необходимо указать абсолютный путь;
  • is_xyz: передавать ли данные облака точек;
  • is_depth: передавать ли данные глубины;
  • is_amp: передавать ли данные карты интенсивности;
  • is_rgb: передавать ли данные RGB-изображения;
  • lx_work_mode: рабочий режим;
  • lx_application: включение алгоритма: 0 — выключен, 1 — объезд препятствий, 2 — алгоритм паллет, 3 — позиционирование, 4 — объезд препятствий V2;
  • lx_tof_unit: единица облака точек: 1 — метр, 0 — миллиметр; при просмотре в rviz необходимо изменить значение на 1.
5.3.1.3 Настройка положения камеры
Можно настроить угол поворота и вектор перемещения облака точек.
  • X: смещение камеры по X относительно центра облака точек;
  • Y: смещение камеры по Y относительно центра облака точек;
  • Z: смещение камеры по Z относительно центра облака точек;
  • Yaw: угол поворота облака точек вокруг оси Z;
  • Roll: угол поворота облака точек вокруг оси X;
  • Pitch: угол поворота облака точек вокруг оси Y.
5.3.1.4 Использование конфигурации launch-файла
Можно выбрать, использовать ли конфигурацию параметров камеры из launch-файла.
  • raw_param: 0 — использовать конфигурацию камеры, 1 — использовать конфигурацию launch-файла.
Независимо от того, задан ли этот параметр равным 0 или 1, будут установлены все параметры до него; значения 0 и 1 действуют только для параметров после него.
5.3.1.5 Настройка параметров 2D
  • lx_2d_binning: 0 — 1x1, 1 — 2x2, 2 — 4x4;
  • lx_2d_undistort: устранение искажений 2D, 0 — выключено, 1 — включено;
  • lx_2d_undistort_scale: коэффициент устранения искажений 2D;
  • lx_2d_auto_exposure: автоматическая экспозиция 2D, 0 — выключена, 1 — включена;
  • lx_2d_auto_exposure_value: целевая интенсивность автоматической экспозиции 2D;
  • lx_2d_exposure: значение экспозиции 2D;
  • lx_2d_gain: усиление 2D.
5.3.1.6 Настройка параметров 3D
  • lx_rgb_to_tof: выравнивание RGB;
  • lx_3d_binning: 0 — 1x1, 1 — 2x2, 2 — 4x4;
  • lx_mulit_mode: многокамерный режим для устранения помех между камерами, 0 — выключен, 1 — включён;
  • lx_3d_undistort: устранение искажений 3D, 0 — выключено, 1 — включено;
  • lx_3d_undistort_scale: коэффициент устранения искажений 3D;
  • lx_hdr: HDR, 0 — выключен, 1 — включён;
  • lx_3d_auto_exposure: автоматическая экспозиция 3D, 0 — выключена, 1 — включена;
  • lx_3d_auto_exposure_value: целевая интенсивность автоматической экспозиции 3D;
  • lx_3d_first_exposure: верхняя точка 3D;
  • lx_3d_second_exposure: нижняя точка 3D;
  • lx_3d_gain: усиление 3D.
5.3.1.7 Максимальная и минимальная глубина
  • lx_min_depth: минимальная глубина;
  • lx_max_depth: максимальная глубина.

5.3.2 Описание launch-файлов ROS2

5.3.2.1 Все launch-файлы
В папке src/launch находятся следующие файлы:
All launch file related icons
  • localization.launch.py: файл запуска узла визуального позиционирования
  • lx_camera_ros.launch.py: файл запуска обычного узла
  • mapping.launch.py: файл запуска построения карты визуального позиционирования
  • obstacle.launch.py: файл запуска алгоритма предотвращения столкновений
  • obstacleV2.launch.py: файл запуска алгоритма предотвращения столкновений V2
  • pallet.launch.py: файл запуска алгоритма распознавания палет
  • sensor_sim.launch.py: файл запуска симуляции данных позиционирования
Разные функции узла можно запускать с помощью разных launch-файлов. За исключением localization, mapping и sensor, набор параметров у всех узлов одинаков, но их значения различаются. Подробное описание приведено в следующих разделах. Описание параметров трёх launch-файлов — localization, mapping и sensor — см. в разделе об узле ros-v1pro.
5.3.2.2 IP-адрес камеры, настройка потоков и режима работы, единица измерения облака точек и другие параметры
  • ip: IP-адрес подключаемой камеры. Если указать 0, по умолчанию будет подключена первая камера.
  • log_path: путь хранения журналов SDK; необходимо указать абсолютный путь
  • is_xyz: передавать ли данные облака точек
  • is_depth: передавать ли данные глубины
  • is_amp: передавать ли данные карты интенсивности
  • is_rgb: передавать ли данные изображения RGB
  • lx_work_mode: режим работы
  • lx_application: включить ли алгоритм: 0 — выключено, 1 — алгоритм предотвращения столкновений, 2 — алгоритм распознавания палет, 3 — алгоритм позиционирования, 4 — алгоритм предотвращения столкновений V2
  • lx_tof_unit: единица измерения облака точек: 1 — метр, 0 — миллиметр. При просмотре в rviz необходимо установить значение 1
5.3.2.3 Настройка положения камеры
Можно настроить угол поворота и вектор смещения облака точек.
  • X: смещение камеры по оси X относительно центра облака точек
  • Y: смещение камеры по оси Y относительно центра облака точек
  • Z: смещение камеры по оси Z относительно центра облака точек
  • Yaw: угол поворота облака точек вокруг оси Z
  • Roll: угол поворота облака точек вокруг оси X
  • Pitch: угол поворота облака точек вокруг оси Y
5.3.2.4 Использование конфигурации launch-файла
Можно выбрать, использовать ли конфигурацию параметров камеры из launch-файла.
  • raw_param: 0 — использовать конфигурацию камеры, 1 — использовать конфигурацию launch-файла
Независимо от того, установлено ли для этого параметра значение 0 или 1, будут установлены все параметры, расположенные до него. Значения 0 и 1 применяются только к параметрам, расположенным после него.
5.3.2.5 Настройка параметров 2D
  • lx_2d_binning:0:1x1,1:2x2,2:4x4
  • lx_2d_undistort: коррекция искажений 2D, 0 — выключено, 1 — включено
  • lx_2d_undistort_scale: коэффициент коррекции искажений 2D
  • lx_2d_auto_exposure: автоматическая экспозиция 2D, 0 — выключено, 1 — включено
  • lx_2d_auto_exposure_value: целевая интенсивность автоматической экспозиции 2D
  • lx_2d_exposure: значение экспозиции 2D
  • lx_2d_gain: усиление 2D
5.3.2.6 Настройка параметров 3D
  • lx_rgb_to_tof: выравнивание RGB
  • lx_3d_binning:0:1x1,1:2x2,2:4x4
  • lx_mulit_mode: многокамерный режим для устранения помех между камерами, 0 — выключено, 1 — включено
  • lx_3d_undistort: коррекция искажений 3D, 0 — выключено, 1 — включено
  • lx_3d_undistort_scale: коэффициент коррекции искажений 3D
  • lx_hdr: HDR, 0 — выключено, 1 — включено
  • lx_3d_auto_exposure: автоматическая экспозиция 3D, 0 — выключено, 1 — включено
  • lx_3d_auto_exposure_value: целевая интенсивность автоматической экспозиции 3D
  • lx_3d_first_exposure: высокая экспозиция 3D
  • lx_3d_second_exposure: низкая экспозиция 3D
  • lx_3d_gain: усиление 3D
5.3.2.7 Максимальная и минимальная глубина
  • lx_min_depth: минимальная глубина
  • lx_max_depth: максимальная глубина

5.3.3 Описание уникальных топиков

Поскольку уникальные типы топиков ROS1 и ROS2 одинаковы, далее в качестве примера используется ROS1. В папке src/msg находятся следующие файлы:
Illustrations related to unique theme descriptions
5.3.3.1 FrameRate.msg
Этот узел выводит информацию о частоте кадров. Формат сообщения выглядит следующим образом:
FrameRate.msg related icons
  • header: информация о кадре и временная метка текущих данных
  • depth: частота кадров карты глубины, если карта глубины включена
  • amp: частота кадров карты интенсивности, если карта интенсивности включена
  • rgb: частота кадров RGB, если RGB включён
  • temperature: температура камеры
После запуска узла (за исключением узлов, связанных с визуальным позиционированием) можно подписаться на узел LxCamera_FrameRate и получить соответствующую информацию. Результат выглядит следующим образом:
FrameRate.msg related icons 2
5.3.3.2 Obstacle.msg
Топик obstacle содержит информацию о результатах алгоритма предотвращения столкновений. Формат сообщения obstacle выглядит следующим образом:
Obstacle.msg related icons
  • header: информация о кадре и временная метка текущих данных
  • status: сведения о состоянии, возвращённые алгоритмом предотвращения столкновений
0: обычная работа алгоритма предотвращения столкновений -1: поверхность не задана -2: входные данные не заданы -3: в заданном диапазоне нет облака точек -4: после фильтрации поверхности облако точек пусто -5: после радиальной фильтрации облако точек пусто -6: результат сегментации не получен -99: неопределённая ошибка
  • io_output: информация о предотвращении столкновений, полученная через интерфейс io
0: нормальная работа 1: предупреждение 2: завершение работы
  • box_number: количество препятствий
  • box: информация о препятствиях; массив переменной длины, определяемой параметром box_number
После запуска узла (необходимо включить алгоритм предотвращения столкновений) можно подписаться на узел LxCamera_Obstacel и получить соответствующую информацию. Результат показан ниже (данные на изображении смоделированы):
Obstacle.msg related icons 2
5.3.3.3 Obstacle_box.msg
Топик obstacle_box содержит информацию о препятствиях. Формат сообщения obstacle_box выглядит следующим образом:
Obstacle\_box.msg related icons
  • center: центр масс препятствия в облаке точек
  • rotation: матрица поворота облака точек препятствия
  • translation: вектор смещения облака точек препятствия
  • width: ширина рамки препятствия
  • height: высота рамки препятствия
  • depth: глубина рамки препятствия
После запуска узла (необходимо включить алгоритм предотвращения столкновений) можно подписаться на узел LxCamera_Obstacel и получить соответствующую информацию. Результат показан ниже:
Obstacle\_box.msg related icon 2
5.3.3.4 Result.msg
Возвращаемое значение после отправки командного сообщения в сервис узла сохраняется в Result:
Result.msg related icons
  • ret: возвращаемое значение, полученное при выполнении SDK
  • msg: описание возвращаемого значения, полученного при выполнении SDK
5.3.3.5 Pallet.msg
Топик pallet содержит информацию о результатах алгоритма распознавания палет. Формат сообщения pallet выглядит следующим образом:
Pallet.msg related icons
  • header: информация о кадре и временная метка текущих данных
  • status: сведения о состоянии, возвращённые алгоритмом распознавания палет:
0: распознавание выполнено успешно -1: поверхность не обнаружена -2: ножки палеты не обнаружены -3: расстояние между палетами слишком велико -4: неизвестная ошибка
  • x: расстояние по оси X между палетой и оптическим центром камеры
  • y: расстояние по оси Y между палетой и оптическим центром камеры
  • yaw: угол theta между центром палеты и оптическим центром камеры
После запуска узла (необходимо включить алгоритм распознавания палет) можно подписаться на узел LxCamera_Pallet и получить соответствующую информацию. Результат показан ниже:
Pallet.msg related icons 2

5.3.4 Описание уникальных сервисов

Поскольку уникальные типы сервисов ROS1 и ROS2 одинаковы, далее в качестве примера используется ROS1. В папке src/srv находятся следующие файлы:
Illustrations related to unique service descriptions
Эти сообщения используются для задания или получения значений параметров камеры. Данные над [---] отправляются, а данные под [---] возвращаются.
5.3.4.1 LxBool.srv
LxBool.srv related icons
  • cmd: номер параметра, который требуется получить или установить
  • val: задаваемое значение
  • is_set: нужно ли устанавливать параметр. Если значение true, значение val будет установлено в камере. Если значение false, параметр будет считан из камеры и выведен.
  • val: текущее значение параметра камеры, возвращаемое при чтении или установке
  • result: значение и информация, возвращённые при вызове интерфейса SDK
5.3.4.2 LxCmd.srv
LxCmd.srv related icons
  • cmd: номер параметра, который требуется получить или установить. При значении 0 возвращаются номера всех параметров.
  • result: значение и информация, возвращённые при вызове интерфейса SDK; cmd может иметь несколько возвращаемых значений
5.3.4.3 LxFloat.srv
LxFloat.srv related icons
  • cmd: номер параметра, который требуется получить или установить
  • val: задаваемое значение
  • is_set: нужно ли устанавливать параметр. Если значение true, значение val будет установлено в камере. Если значение false, параметр будет считан из камеры и выведен.
  • max_value: максимальное значение, которое можно установить для этого параметра
  • min_value: минимальное значение, которое можно установить для этого параметра
  • cur_value: текущее значение этого параметра в камере
  • available: поддерживает ли этот параметр установку значения
  • result: значение и информация, возвращённые при вызове интерфейса SDK
5.3.4.4 LxInt.srv
LxInt.srv related icons
  • cmd: номер параметра, который требуется получить или установить
  • val: задаваемое значение
  • is_set: нужно ли устанавливать параметр. Если значение true, значение val будет установлено в камере. Если значение false, параметр будет считан из камеры и выведен.
  • max_value: максимальное значение, которое можно установить для этого параметра
  • min_value: минимальное значение, которое можно установить для этого параметра
  • cur_value: текущее значение этого параметра в камере
  • available: поддерживает ли этот параметр установку значения
  • result: значение и информация, возвращённые при вызове интерфейса SDK
5.3.4.5 LxString.srv
LxString.srv related icons
  • cmd: номер параметра, который требуется получить или установить
  • val: задаваемое значение
  • is_set: нужно ли устанавливать параметр. Если значение true, значение val будет установлено в камере. Если значение false, параметр будет считан из камеры и выведен.
  • val: текущее значение параметра камеры, возвращаемое при чтении или установке
  • result: значение и информация, возвращённые при вызове интерфейса SDK

5.3.5 Описание способов подписки на топики

5.3.5.1 Подписка на данные о частоте кадров и результаты алгоритмов распознавания палет и предотвращения столкновений
Подписка на частоту кадров В каталоге lx_camera_node_ws выполните команду: bash rate.sh
Illustrations related to subscription frame rate, tray algorithm, and obstacle avoidance algorithm output data
После нормального запуска и обновления образа узла lx_camera_node появится следующая информация:
Illustrations related to subscription frame rate, pallet algorithm, and obstacle avoidance algorithm output data 2
Подписка на результаты алгоритма распознавания палет В каталоге lx_camera_node_ws выполните команду: bash pallet.sh
Illustrations related to subscription frame rate, pallet algorithm, and obstacle avoidance algorithm output data 3
После нормального запуска и обновления образа узла lx_camera_node появится следующая информация:
Illustrations related to subscription frame rate, pallet algorithm, and obstacle avoidance algorithm output data 4
Подписка на результаты алгоритма предотвращения столкновений В каталоге lx_camera_node_ws выполните команду: bash obstacle.sh
Illustrations related to subscription frame rate, pallet algorithm, and obstacle avoidance algorithm output data 5
После нормального запуска и обновления образа узла lx_camera_node появится следующая информация:
Illustrations related to subscription frame rate, tray algorithm, and obstacle avoidance algorithm output data 6
5.3.5.2 Подписка на данные изображений (ROS1)
Информацию об изображениях, выводимую узлом, можно просматривать с помощью инструмента изображений, входящего в ROS: Введите в консоли команду: rqt_image_view После выполнения команды появится следующее окно:
Illustrations related to subscribing image data (ROS1)
В красном поле можно выбрать изображения всех узлов. На рисунке показано RGB-изображение камеры MRDVS. Также можно выбрать карту глубины или карту интенсивности, если соответствующий поток включён:
Subscription image data (ROS1) related diagram 2
На рисунке в первом красном поле показана информация RGB, выводимая узлом алгоритма позиционирования, а в остальных трёх — информация об изображениях, выводимая обычными узлами. amp — карта интенсивности, depth — карта глубины, rgb — карта RGB. Выбирайте разные элементы для просмотра разных изображений или используйте rviz для просмотра данных изображений. Введите в консоли команду rviz, после чего появится следующее окно:
Subscription image data (ROS1) related diagram 3
После нажатия кнопки Add в левом нижнем углу появится следующее окно:
Subscription image data (ROS1) related diagram 4
Выберите нужный топик изображения, выберите Image и нажмите OK в правом нижнем углу. Данные изображения появятся в левой части главного интерфейса, как показано ниже:
Subscription image data (ROS1) related diagram 5
5.3.5.3 Подписка на данные изображений (ROS2)
Информацию об изображениях, выводимую узлом, можно просматривать с помощью инструмента изображений, входящего в ROS2. Введите в консоли команду rqt. После выполнения команды появится следующее окно:
Illustrations related to subscribing image data (ROS2)
Выберите первый пункт Image View во втором элементе в нижней части строки меню. После выбора появится следующий интерфейс:
Subscription image data (ROS2) related diagram 2
В красном поле можно выбрать изображения всех узлов. На рисунке показано RGB-изображение камеры MRDVS. Также можно выбрать карту глубины или карту интенсивности, если соответствующий поток включён:
Subscription image data (ROS2) related diagram 3
На рисунке в первом красном поле показана информация RGB, выводимая узлом алгоритма позиционирования, а в остальных трёх — информация об изображениях, выводимая обычными узлами. amp — карта интенсивности, depth — карта глубины, rgb — карта RGB. Выбирайте разные элементы для просмотра разных изображений или используйте rviz2 для просмотра данных изображений. Введите в консоли команду rviz2, после чего появится следующее окно:
Subscription image data (ROS2) related diagram 4
После нажатия кнопки Add в левом нижнем углу появится следующее окно:
Subscription image data (ROS2) related diagram 5
Выберите нужный топик изображения, выберите Image и нажмите OK в правом нижнем углу. Данные изображения появятся в левой части главного интерфейса, как показано ниже:
Subscription image data (ROS2) related diagram 6
В некоторых системах для просмотра изображения необходимо указать [mrdvs] в поле [map], показанном на рисунке выше.
5.3.5.4 Подписка на данные облака точек
Информацию об облаке точек, выводимую узлом, можно просматривать с помощью инструмента облака точек из ROS или ROS2: Команды: rviz【ROS1】, rviz2【ROS2】 После выполнения команды появится следующее окно:
Illustrations related to subscribing to point cloud data
Нажмите кнопку в красном поле ниже, после чего появится следующее окно:
Illustration related to subscribing to point cloud data 2
Выберите вторую вкладку. В ней будет узел lx\_camera\_node, содержащий топик LxCamera\_Cloud. В этом топике находится сообщение PointCloud2. Выберите его и нажмите OK. После этого интерфейс будет выглядеть следующим образом:
Illustrations related to subscribing to point cloud data 3
(интерфейс ROS1)
Illustrations related to subscribing to point cloud data 4
(интерфейс ROS2) На этом этапе облако точек не отображается корректно. Укажите mrdvs в поле карты, выделенном красным и зелёным цветом выше, чтобы увидеть облако точек. Результат выглядит следующим образом:
Illustrations related to subscribing to point cloud data 5
Единицей измерения облака точек по умолчанию в ROS являются метры. Поэтому при просмотре в rviz необходимо установить для lx_tof_unit в launch-файле значение 1 [значение по умолчанию — 1].

5.3.6 Описание способов обмена данными с сервисами

В ROS1 все команды можно дополнять клавишей Tab, а в ROS2 таким образом дополняются только топики; часть с сообщением необходимо вводить вручную. В ROS1 данные можно вводить в формате автодополнения. В ROS2 данные необходимо вводить в формате YAML-файла. После запуска узла откройте терминал в папке lx_camera_node_ws, настройте окружение и выполните команду: source devel/setup.bash.
5.3.6.1 Получение списка номеров всех параметров (Lx_Cmd)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxCmd “cmd: 0”
Get all parameter number list (Lx\_Cmd) related icons
Вы увидите следующий результат:
Get all parameter number list (Lx\_Cmd) related icon 2
ret — номер параметра. В msg указаны тип и описание параметра. Например, параметр 1001 имеет тип int и используется для получения и изменения значения первой экспозиции. ROS2 Enter in the terminal: ros2 service call /LxCamera_LxCmd lx_camera_ros/srv/LxCmd ‘cmd: 0’
Get all parameter number list (Lx\_Cmd) related icon 3
Вы увидите следующий результат:
Get all parameter number list (Lx\_Cmd) related icon 4
Поскольку в ROS2 просматривать сведения о параметрах неудобно, номера, типы и описания всех параметров также приведены в таблице ниже: Some parameters need to stop the flow before they can be set, or there is a sequence of settings. Please contact the technical support staff for specific needs.
5.3.6.2 Get Int parameter (Lx_Int)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxInt “cmd: 1001 val: 0 is_set: false”
Get related icons of Int parameters (Lx\_Int)
You can see the output:
Get the related icon of Int parameter (Lx\_Int) 2
What is in the red box is the return value. What is obtained in the figure is the high integration time. According to the return result, you can see that the maximum value is 3600, the minimum value is 1, the current value is 1010, whether the setting is supported is supported, the interface call return value is 0, and the return value information is success.
ROS2 Enter in the terminal: ros2 service call /LxCamera_LxInt lx_camera_ros/srv/LxInt '{cmd: 1001,val: 0,is_set: false}'
Get the related icon of Int parameter (Lx\_Int) 3
You can see the output:
Get the related icon of Int parameter (Lx\_Int) 4
What is obtained in the figure is the high integration time. According to the returned results, we can see that the maximum value is 3600, the minimum value is 1, the current value is 1010, whether the setting is supported is supported, the return value of the interface call is 0, and the return value information is success.
5.3.6.3 Set Int parameters (Lx_Int)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxInt “cmd: 1001 val: 2000 is_set: true”
Illustrations related to setting Int parameters (Lx\_Int)
You can see the output:
Illustration 2 related to setting Int parameters (Lx\_Int)
What is in the red box is the return value. The high integration time is set in the figure. According to the return result, you can see that the maximum value is 3600, the minimum value is 1, the current value has been modified to 2000, whether the support setting is supported, the interface call return value is 0, and the return value information is success.
ROS2 Enter in the terminal: ros2 service call /LxCamera_LxInt lx_camera_ros/srv/LxInt '{cmd: 1001,val: 3000,is_set: true}'
Illustration 3 related to setting Int parameters (Lx\_Int)
You can see the output:
Illustration 4 related to setting Int parameters (Lx\_Int)
What is obtained in the figure is the high integration time. According to the returned results, we can see that the maximum value is 3600, the minimum value is 1, the current value has been modified to 3000, whether the setting is supported is supported, the interface call return value is 0, and the return value information is success.
5.3.6.4 Get Float parameters (Lx_Float)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxFloat “cmd: 2007 val: 0.0 is_set: false”
Get related icons of Float parameters (Lx\_Float)
You can see the output:
Get the related icon of Float parameter (Lx\_Float) 2
What is in the red box is the return value. What is obtained in the picture is the camera temperature. According to the return result, you can see that the maximum value is 120, the minimum value is -40, the current value is 49.6875, whether the setting is supported is not supported, the interface call return value is 0, and the return value information is success.
ROS2 Enter in the terminal: ros2 service call /LxCamera_LxFloat lx_camera_ros/srv/LxFloat '{cmd: 2007,val: 0,is_set: false}'
Obtain related icons of Float parameters (Lx\_Float) 3
You can see the output:
Get the related icon of Float parameter (Lx\_Float) 4
What is obtained in the picture is the camera temperature. According to the returned results, you can see that the maximum value is 120, the minimum value is -40, the current value is 50.4375, whether the setting is supported is not supported, the return value of the interface call is 0, and the return value information is success.
5.3.6.5 Set Float parameters (Lx_Float)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxFloat “cmd: 2007 val: 5.0 is_set: true”
Illustrations related to setting Float parameters (Lx\_Float)
You can see the output:
Illustration 2 related to setting Float parameters (Lx\_Float)
The red box is the return value. The camera temperature is set in the picture. According to the return result, you can see that the maximum value is 120, the minimum value is -40, the current value is 50.9375, whether the setting is supported is not supported, the interface call return value is -2, the return value information is not supported, the value set here is 5, the current value and the set value are inconsistent because the parameter does not support setting.
ROS2 Enter in the terminal: ros2 service call /LxCamera_LxFloat lx_camera_ros/srv/LxFloat '{cmd: 2007,val: 5.0,is_set: true}'
Illustration 3 related to setting Float parameters (Lx\_Float)
You can see the output:
Illustrations related to setting Float parameters (Lx\_Float) 4
The camera temperature is set in the picture. According to the returned results, you can see that the maximum value is 120, the minimum value is -40, the current value is 51.125, whether the setting is supported is not supported, the return value of the interface call is -2, the return value information is not supported, the value set here is 5, the current value and the set value are inconsistent because the parameter does not support setting.
5.3.6.6 Get Bool parameters (Lx_Bool)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxBool “cmd: 3012 val: false is_set: false”
Get related icons of Bool parameters (Lx\_Bool)
You can see the output:
Get Bool parameter (Lx\_Bool) related icon 2
What is in the red box is the return value. What is obtained in the picture is 2D automatic exposure. According to the return result, we can see that the current value is false, the return value of the interface call is 0, and the return value information is success.
ROS2 Enter in the terminal: ros2 service call /LxCamera_LxBool lx_camera_ros/srv/LxBool '{cmd: 3012,val: false,is_set: false}'
Get Bool parameter (Lx\_Bool) related icon 3
You can see the output:
Get Bool parameter (Lx\_Bool) related icon 4
What is obtained in the figure is 2D automatic exposure. According to the return result, we can see that the current value is false, the return value of the interface call is 0, and the return value information is success.
5.3.6.7 Set Bool parameters (Lx_Bool)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxBool “cmd: 3012 val: true is_set: true”
Illustrations related to setting Bool parameters (Lx\_Bool)
You can see the output:
Illustration 2 related to setting Bool parameters (Lx\_Bool)
What is in the red box is the return value. The 2D automatic exposure is set in the picture. According to the return result, we can see that the current value is true, the return value of the interface call is 0, the return value information is success, and the current value is consistent with the set value.
ROS2 Enter in the terminal: ros2 service call /LxCamera_LxBool lx_camera_ros/srv/LxBool '{cmd: 3012,val: true,is_set: true}'
Illustration 3 related to setting Bool parameters (Lx\_Bool)
You can see the output:
Illustrations related to setting Bool parameters (Lx\_Bool) 4
The setting in the picture is 2D automatic exposure. According to the return result, we can see that the current value is true, the return value of the interface call is 0, the return value information is success, and the current value is consistent with the set value.
5.3.6.8 Get String parameter (Lx_String)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxString “cmd: 4001 val: ” is_set: false”
Get related icons of String parameters (Lx\_String)
You can see the output:
Obtain String parameter (Lx\_String) related icon 2
What is in the red box is the return value. What is obtained in the figure is the device version number. According to the return result, we can see that the current value is V1.1.33_231201, the return value of the interface call is 0, and the return value information is success.
ROS2 Enter in the terminal: ros2 service call /LxCamera_LxString lx_camera_ros/srv/LxString '{cmd: 4001,val: '',is_set: false}'
Obtain String parameter (Lx\_String) related icon 3
You can see the output:
Get the related icon of String parameter (Lx\_String) 4
What is obtained in the figure is the device version number. According to the return result, we can see that the current value is V1.1.33_231201, the return value of the interface call is 0, and the return value information is success.
5.3.6.9 Set String parameters (Lx_String)
ROS1 Enter in the terminal: rosservice call /lx_camera_node/LxCamera_LxString “cmd: 4001 val: ‘put:\“123\”’ is_set: true”
Illustrations related to setting String parameters (Lx\_String)
You can see the output:
Illustration 2 related to setting String parameters (Lx\_String)
The red box is the return value. The device version number is set in the figure. According to the return result, we can see that the current value is V1.1.33_231201, the return value of the interface call is -2, and the return value information is not supported. The current value and the set value are inconsistent because this parameter does not support setting.
ROS2 Enter in the terminal: ros2 service call /LxCamera_LxString lx_camera_ros/srv/LxString '{cmd: 4001,val: "put:\\"123\\"",is_set: true}'
Illustration 3 related to setting String parameters (Lx\_String)
You can see the output:
Illustrations related to setting String parameters (Lx\_String) 4
The device version number is set in the figure. According to the returned result, we can see that the current value is V1.1.33_231201, the return value of the interface call is -2, and the return value information is not supported. The current value is inconsistent with the set value because this parameter does not support setting. When setting a value of String type, escape characters must be added to single quotes and double quotes, except for the initial double quotes in ROS2 and the initial single quotes in ROS1. For example, if you want to input the string [PUT”123”], you must add escape characters to become: [PUT\”123\”].
In the recommended hardware configuration, the analysis is based on CPU core count, CPU usage, and memory size. These are recommended configurations, not minimum requirements. If your hardware is below the recommendation, stable operation may still be possible by reducing stream output, disabling point-cloud computation, or lowering the algorithm load. Running a workload above the available configuration may crash the ROS core or Ubuntu. The second and third sections of this chapter provide detailed usage data. Choose the operating environment and stream configuration that best fits your system. All data here was collected in a VM using an M4 Pro camera. Ubuntu16.04 Ubuntu18.04 Ubuntu20.04 Ubuntu22.04

6.2 CPU details

The CPU details will show the amount of CPU resources occupied by the node under different operating conditions. The test is based on AMD64 [8 cores], 8G memory hardware environment, the test camera is M4 Pro, the test algorithm is tray algorithm, 2D width and height are 1280*960, and 3D width and height are 640*480, 2D anti-distortion is on, 3D anti-distortion is off, and integration 110 - 3000, depth 0 - 8000, ToF frame rate 14, streaming mode, smoothing level 1, noise level 1, time domain level 0, statistics command is TOP. Because the test soft environment is VM virtual machine, it is normal for the data displayed by the physical machine to fluctuate compared with that in the document. For some cameras, such as S2, some algorithms are calculated on the host computer, which results in a large amount of resource usage, which is normal.
1. Some nouns are explained as follows: -Single stream: refers to turning on any stream of RGB, depth, and intensity
  • Dual stream: refers to turning on any two streams of RGB, depth and intensity
-Three streams: refers to RGB, depth, and intensity all three streams are turned on
  • Four streams: means RGB, depth, intensity, and point cloud are all turned on
2. The algorithm has a binding relationship with some streams. The binding relationship is as follows:
  • To enable the pallet algorithm, the depth must be enabled
  • To turn on the obstacle avoidance algorithm, you must turn on depth
  • To turn on the positioning algorithm, you must turn on RGB

The light blue background in the table is the running configuration with point cloud enabled, and the colorless background is the running configuration without point cloud enabled. All the test data below have the algorithm shifted down by default, so for S2 series cameras, all test values ​​may be too small [some algorithms of S2 series cameras are forced to move up]. Ubuntu16.04 Ubuntu18.04 Ubuntu20.04 Ubuntu22.04

6.3 Memory details

The memory details will show the amount of memory resources occupied by the node under different operating conditions. The test is based on AMD64 [8 cores], 8G memory hardware environment, the test camera is M4 Pro, the test algorithm is tray algorithm, 2D width and height are 1280*960, and 3D width and height are 640*480, 2D anti-distortion is on, 3D anti-distortion is off, points 110 - 3000, depth 0 - 8000, ToF frame rate 14, streaming mode, smoothing level 1, noise level 1, time domain level 0, statistics command is TOP. Because the test soft environment is VM virtual machine, it is normal for the data displayed by the physical machine to fluctuate compared with that in the document. For some cameras, such as S2, some algorithms are calculated on the host computer, which results in a large amount of resource usage, which is normal.
1. Some nouns are explained as follows: -Single stream: refers to turning on any stream of RGB, depth, and intensity
  • Dual stream: refers to turning on any two streams of RGB, depth and intensity
-Three streams: refers to RGB, depth, and intensity all three streams are turned on
  • Four streams: means RGB, depth, intensity, and point cloud are all turned on
2. The algorithm has a binding relationship with some streams. The binding relationship is as follows:
  • To enable the pallet algorithm, the depth must be enabled
  • To turn on the obstacle avoidance algorithm, you must turn on depth
  • To turn on the positioning algorithm, you must turn on RGB
  1. The light blue background in the table is the running configuration with point cloud enabled, and the colorless background is the running configuration without point cloud enabled. All the test data below have the algorithm shifted down by default, so for S2 series cameras, all test values ​​may be too small [some algorithms of S2 series cameras are forced to move up].
Ubuntu16.04 Ubuntu18.04 Ubuntu20.04
Ubuntu22.04

Appendix

This appendix provides installation methods for some tools. When using these methods, you need to have at least some basic knowledge of Linux. There is no guarantee that every computer can be successfully installed through the methods shown in the appendix of this document. The environment of each computer is different, and the problems encountered may not be consistent. If you encounter problems not shown in this appendix, please search for solutions yourself.

1. Cmake specified version installation method

Go to https://cmake.org/download/ and download the required CMake version. Extract the downloaded package with tar -zxvf cmake-XXX.tar.gz. Enter the extracted directory, then compile and configure it: ./bootstrap make sudo make install Check the Cmake version to see if the installation is successful: cmake —version

2. Opencv specified version installation method

  1. Download the required version of opencv: Releases-OpenCV
Illustrations related to the installation method of the specified version of Opencv
  1. Environment configuration, execute the following commands in sequence:
sudo apt-get install build-essential sudo apt-getinstallcmake gitlibgtk2.0-devpkg-config libavcodec-dev libavformat-dev libswscale-dev sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev
  1. Create a new opencv folder and extract the downloaded source code into the opencv folder.
  2. Execute the following commands in sequence:
  3.   cd opencv
  4.   mkdir build && cd build
  5.   sudocmake-DCMAKE_BUILD_TYPE=Release-D
  6.   CMAKE_INSTALL_PREFIX=/usr/local ..
  7.   sudo make -j4
  8. sudo make install and wait for the installation to complete

3. Pcl specified version installation method

  1. Check the supported pcl version:
apt-cache madison libpcl-dev
  1. Install the specified pcl version (where 1.10.0 needs to be replaced with the required version number):
sudo apt-get install libpcl-dev=1.10.0

4. Install ROS

Ubuntu16.04
  1. Add the software source and set the secret key:
sudo sh -c ‘echo “deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main” > /etc/apt/sources.list.d/ros-latest.list’ sudoapt-keyadv—keyserver’hkp://keyserver.ubuntu.com:80’—recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654
  1. Add secret key:
curl -sSL ‘http://keyserver.ubuntu.com/pks/lookup?op=get&search=0xC1CF6E31E6BADE8868B172B4F42ED6FBAB17C654’ | sudo apt-key add -
  1. Update source:
sudo apt-get update
  1. Install complete ros:
sudo apt-get install ros-kinetic-desktop-full
  1. Configure environment variables:
echo “source /opt/ros/kinetic/setup.bash” >> ~/.bashrc source ~/.bashrc
  1. Complete ROS-related tools:
sudoaptinstallpython-rosinstallpython-rosinstall-generatorpython-wstool build-essential
  1. Now that the installation of ROS1 is complete, run the example that comes with ROS to check whether the installation is correct:
Open a terminal and enter: roscore Open another terminal and enter: rosrun turtlesim turtlesim_node Open another terminal: rosrun turtlesim turtle_teleop_key In the third terminal, you can control the little turtle through the arrow keys If it can run normally as shown below, it means that ros has been installed correctly: Installation ROS related icons
Ubuntu18.04
  1. Set up the software source:
sudo sh -c ’. /etc/lsb-release && echo “deb http://mirrors.ustc.edu.cn/ros/ubuntu/ `lsb_release -cs` main” > /etc/apt/sources.list.d/ros-latest.list’ 2.Set the public key: sudoapt-keyadv—keyserver’hkp://keyserver.ubuntu.com:80’—recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654
  1. Update software list:
sudo apt update
  1. Install Ubuntu18.04 version of ROS1:
sudo apt install ros-melodic-desktop-full
  1. Set environment variables:
echo “source /opt/ros/melodic/setup.bash” >> ~/.bashrc source ~/.bashrc if it is zsh: echo “source /opt/ros/melodic/setup.bash” >> ~/.zshrc source ~/.zshrc
  1. Complete ROS-related tools:
sudoaptinstallpython-rosdeppython-rosinstallpython-rosinstall-generator python-wstool build-essential
  1. Now that the installation of ROS1 is complete, run the example that comes with ROS to check whether the installation is correct:
Open a terminal and enter: roscore Open another terminal and enter: rosrun turtlesim turtlesim_node Open another terminal: rosrun turtlesim turtle_teleop_key In the third terminal, you can control the little turtle through the arrow keys If it can run normally as shown below, it means that ros has been installed correctly:
Installation ROS related icons 2
Ubuntu20.04
  1. Configure the public key:
sudoapt-keyadv—keyserver’hkp://keyserver.ubuntu.com:80’—recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654
  1. If it shows that it cannot connect to the server or times out, please update the software source list first:
sudo apt-get update sudo apt-get upgrade
  1. After configuring the public key, update the software list again:
sudo apt-get update install ros: sudo apt install ros-noetic-desktop-full
  1. Set environment variables:
echo “source /opt/ros/noetic/setup.bash” >> ~/.bashrc source ~/.bashrc
  1. Install ROS tools:
sudo apt install python3-rosinstall python3-rosinstall-generator python3-wstool build-essential
  1. Now that the installation of ROS1 is complete, run the example that comes with ROS to check whether the installation is correct:
Open a terminal and enter: roscore Open another terminal and enter: rosrun turtlesim turtlesim_node Open another terminal: rosrun turtlesim turtle_teleop_key In the third terminal, you can control the little turtle through the arrow keys If it can run normally as shown below, it means that ros has been installed correctly:
Installation ROS related icons 3
Ubuntu22.04 It is not recommended to install ros1 in Ubuntu22.04. It is not officially supported. If you want to install it, you will encounter a lot of dependency problems.

5. How to create a new test package in Ros

  1. Create a new folder ws, create a new src folder in the ws folder, enter the src folder and execute:
catkin_create_pkg example std_msgs rospy roscpp
  1. This creates a new package named example, which depends on std_msgs rospy roscpp
  2. Then compile this new package: catkin_make This is an empty package, there will not be any executable program, it is just a package
  3. Next, we will demonstrate how to create a package that can output ‘Hellow world’
  4. Based on the package just now, we enter the src folder (src in the package) and create a new main.cpp, as shown below (pay attention to the path):
Illustration of how to create a new test package in Ros
  1. In main.cpp, we enter some codes:
Ros How to Create a New Test Package Related Illustration 2
  1. Then we change the outside CMakeLists.txt and add a line at the bottom: add_executable(example src/main.cpp)
Ros How to Create a New Test Package Related Illustration 3
  1. Then return to the ws directory to compile and execute the command: catkin_make
Ros How to Create a New Test Package Related Illustration 4
  1. Seeing these means the compilation is successful.
  2. Next we configure the environment:
source devel/setup.bash
Ros How to Create a New Test Package Related Illustrations 5
  1. Then execute the program and you can see the output:
rosrun example example
Ros How to Create a New Test Package Related Illustrations 6

6. Install ROS2

Ubuntu16.04
  1. Add secret key:
sudo apt-get update && sudo apt-get install curl curl http://repo.ros2.org/repos.key | sudo apt-key add -
  1. Add permissions:
sudo apt update && sudo apt install curl gnupg2 lsb-release curl-shttps://raw.githubusercontent.com/ros/rosdistro/master/ros.asc|sudo apt-key add -
  1. If an error is reported in this step, use VPN to bypass the wall and then open the browser, enter the URL, and copy the content, then create a new ros.asc and copy the content to the file. After the copy is completed, the following is as follows:
  2. Then re-execute step 3: sudo apt-key add ros.asc
  3. Continue execution:
sudo sh -c ‘echo “deb [arch=amd64] http://packages.ros.org/ros2/ubuntu bionic main” > /etc/apt/sources.list.d/ros2-latest.list’
  1. Install ROS2:
sudo apt update sudo apt install ros-ardent-desktop
  1. Configure environment variables:
source /opt/ros/ardent/setup.bash
  1. Install the function package:
sudo apt-get update sudo apt-get install ros-ardent-ros1-bridge sudo apt-get install ros-ardent-turtlebot2-*
  1. Try running the example program, open a terminal and run:
source ~/.bashrc ros2 run demo_nodes_cpp talker
  1. Open another interrupt to run:
source~/.bashrc ros2 run demo_nodes_cpp talker
  1. The following terminal output proves that the installation is successful:
Ubuntu18.04:
  1. Add software source
sudo apt update && sudo apt install curl gnupg2 lsb-release curl -s https://raw.githubusercontent.com/ros/rosdistro/master/ros.asc sudo apt-key add ros.asc
  1. If this step reports an error as follows:
  2. Use VPN to bypass the wall, then open the browser, enter the URL, and copy the content, then create a new ros.asc and copy the content to the file. After the copy is completed, it is as follows:
  3. Then re-execute step 3: sudo apt-key add ros.asc
  4. Continue execution:
sudo sh -c ‘echo “deb [arch=amd64] http://packages.ros.org/ros2/ubuntu bionic main” > /etc/apt/sources.list.d/ros2-latest.list’
  1. After completion, start downloading ros2, in which the red fonts need to be replaced with different versions (see the table above):
sudo apt update sudo apt install ros-eloquent-desktop
  1. Wait for the installation to complete and continue to install the python library. Execute: sudo apt install -y libpython3-dev python3-pip pip3 install -U argcomplete
Then configure the environment variables: echo “source /opt/ros/eloquent/setup.bash” >> ~/.bashrc source ~/.bashrc
  1. Try running the sample program, open a terminal and run:
source ~/.bashrc ros2 run demo_nodes_cpp talker
  1. Open another interrupt to run:
source ~/.bashrc ros2 run demo_nodes_py listener
  1. The following terminal output proves that the installation is successful:
Ubuntu20.04
  1. Add software source
sudo apt update && sudo apt install curl gnupg2 lsb-release sudo curl -sSL [https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o](https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o) /usr/share/keyrings/ros-archive-keyring.gpg
  1. If you encounter the error “ailed to connect to raw.githubusercontent.com port 443 after 13 ms: connection refused”
Installation ROS2 related icons 6
sudo vi /etc/hosts
  1. Add the following analysis
185.199.108.133raw.githubusercontent.com
  1. The added files are as follows:
Installation ROS2 related icons 7
echo”deb[arch=(source/etc/os-release&&echo$UBUNTU_CODENAME) main” | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null
  1. Continue execution:
sudo sh -c ‘echo “deb [arch=amd64] http://packages.ros.org/ros2/ubuntu bionicmain” > /etc/apt/sources.list.d/ros2-latest.list’
  1. After completion, start downloading ros2:
sudo apt update sudo apt install ros-foxy-desktop
  1. Wait for the installation to complete and continue to install the python library. Execute: sudo apt install -y libpython3-dev python3-pip pip3 install -U argcomplete
  2. Then configure the environment variables:
echo “source /opt/ros/foxy/setup.bash” >> ~/.bashrc source ~/.bashrc
  1. Try running the sample program, open a terminal and run:
source ~/.bashrc ros2 run demo_nodes_cpp talker
  1. Open another interrupt to run:
source ~/.bashrc ros2 run demo_nodes_py listener
  1. The following terminal output proves that the installation is successful:
Ubuntu22.04
  1. Add software source
sudo apt update && sudo apt install curl gnupg lsb-release sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpgecho”deb[arch=(source/etc/os-release&&echo$UBUNTU_CODENAME) main” | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null
  1. If you encounter the error “ailed to connect to raw.githubusercontent.com port 443 after 13 ms: connection refused”
Installation ROS2 related icons 9
sudo vi /etc/hosts adds the following analysis 185.199.108.133raw.githubusercontent.com The added files are as follows:
Installation ROS2 related icons 10
  1. After completion, start downloading ros2: sudo apt update
sudo apt install ros-humble-desktop
  1. Wait for the installation to complete and continue to install the python library. Execute: sudo apt install -y libpython3-dev python3-pip pip3 install -U argcomplete
  2. Then configure the environment variables:
echo “source /opt/ros/humble/setup.bash” >> ~/.bashrc source ~/.bashrc
  1. Try running the sample program, open a terminal and run:
source ~/.bashrc ros2 run demo_nodes_cpp talker
  1. Open another interrupt to run:
source ~/.bashrc ros2 run demo_nodes_py listener
  1. The following terminal output proves that the installation is successful:

7. How to create a new test package in Ros2

  1. Execute the command:
mkdir example_ws && cd example_ws ros2 pkg create —build-type ament_cmake —node-name example_n example_p colcon build source install/setup.bash ros2 run example_p example_n
  1. You can create a new package named example_p and a node named example_n. After running, it will output: hello world example_p package