DIY Raspberry Pi Drone : Mechanics – Part 1

Awesome, where do i start?

Typical consumer drones (like DJI Mavic) are not open source and it’s impossible or at least inconvenient to control them via code. Their frames usually don’t support installation of additional components like onboard computer — these drones are meant to be used as they are.

To use clover software, you need a drone with a Raspberry Pi 3 or 4 on board — anything with a PX4-compatible flight controller will do.

Calibrating the esc

The last stage is to calibrate the Electronic speed controllers (ESC). Out of the box these small devices are generally pretty similar but inevitably need calibration as well. They basically control the speed at which each of the propellers spin, so all need to be perfectly synced so all props give the same amount of lift.

Don’t kill the lipo

One of the biggest issues with drones is power and this comes in the form of lithium-ion polymer (LiPo) batteries. They’re small, relatively lightweight and pack a punch when it comes to supplying enough power to the small motors to create lift.

Смотрите про коптеры:  10 лучших дронов с камерой с АлиЭкспресс – рейтинг 2023

Unfortunately, this power is relatively short-lived and even with the small drone that we’ve built, you really can’t expect more than five minutes of actual flight time per charge.

Once the juice runs low the drone is prone to either dropping out of the sky or in the worse case scenario flying off.

But a crashing drone is the least of your worries, when it comes to LiPo batteries it’s easy to forget that they’re extremely volatile, and if used incorrectly can explode or catch fire. The big problem with LiPos is that it’s extremely easy to abuse the small cells without realising it and we need to do everything we can to limit the possibilities of any damage to the cells or the drone itself.

Part of the beauty of building a Linux-based drone is that you can program in failsafes through the APM Planner 2.0 software. The two main settings that we’ll need to cover are ‘Throttle Failsafe’ and ‘Battery Failsafe’. We also need to do a little more hardware calibration, this time for the power module.

This module is the extremely expensive and seemingly redundant circuit that sits between the PXFmini and battery and is what enables you to gauge the voltage of your battery and avoid over discharging.

Hardware:

  • DJI F450 ARF (Almost Ready to Fly) Kit
  • 3300mAh 3S 35C LiPo battery with T-Connectors
  • EV-Peak – AP606 – 50W DC LiPo battery charger/discharger (most LiPo battery chargers will work)
  • RadioLink AT9 2.4GHz 9CH Transmitter w/ R9D 9CH Receiver
  • Xiaomi Yi Action Camera with microSD card
  • FeiYu Tech Mini 3D 3-Axis Brushless Gimbal
  • Raspberry Pi (Model A ), microSD card
  • Raspberry Pi camera module
  • Any USB Wi-Fi dongle with support for 802.11a/n/ac (5GHz band)—D-Link DWA-160 was used in this project
  • Spare micro USB cable
  • Various male and female T-Connectors
  • RadioLink AT9 2.4GHz 9CH Transmitter w/ R9D 9CH Receiver
  • Suction car window mount for a phone
  • 4 x M3 bolts and 8 x M3 nuts
  • Android Phone

Mavproxy

MAVProxy уже установлен в образе Navio. Его также можно

и на ПК (Windows, Linux, MacOS) для дальнейшего общения с автопилотом в консольном режиме.

Убедившись, что Ardupilot работает, запустим на Raspberry скрипт MAVProxy такой командой:

mavproxy.py --master=udp:127.0.0.1:14550

Параметр

–master=udp:127.0.0.1:14550

задает для скрипта источник данных. Это локальный UDP-порт, который был прописан в файле конфигурации Ardupilot. После запуска команды, MAVProxy соединиться с этим портом и выведет на экран сообщения автопилота, примерно как у меня:

pi@navio:~ $ mavproxy.py --master=udp:127.0.0.1:14550
Connect udp:127.0.0.1:14550 source_system=255
Failed to load module: No module named adsb. Use 'set moddebug 3' in the MAVProxy console to enable traceback
Log Directory:
Telemetry log: mav.tlog
Waiting for heartbeat from 127.0.0.1:14550 MAV> online system 1
STABILIZE> Mode STABILIZE
fence breach
GPS lock at 0 meters
APM: APM:Copter V3.5.5 (88a1ecdd)
APM: Frame: UNKNOWN
APM: PreArm: RC Roll not configured
APM: PreArm: Compass not calibrated
APM: PreArm: 3D Accel calibration needed
APM: PreArm: check firmware or FRAME_CLASS
APM: PreArm: Throttle below Failsafe

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

arm throttle
takeoff 20

Не откалиброванный автопилот не полетит, а покажет сообщения с причинами, почему он этого сделать не сможет.

Tools:

  • Soldering iron
  • Solder
  • Allen key
  • Hot glue gun
  • Hot glue sticks

Before starting this project it is imperative to understand the purpose of each part of the quadcopter. Below is a list of each part on the quadcopter you will build, its purpose, and the specific part used in this How-To.

      • Purpose: The frame provides a convenient way to mount motors and electronics
      • Parts used in this project: DJI Flame Wheel 450 (F450) frame (included in the ARF Kit)
  • Brushless motors and propellers:
  • Electric Speed Controllers (ESC):
      • Purpose: ESCs power the brushless motors and provide a PWM interface that allows the flight controller to control the speed (and thrust) of each motor
      • Parts used in this project: DJI E305 960KV motors (included in the ARF Kit)
      • Purpose: As the name suggests, the flight controller controls how the quadcopter is flown. A flight is a small computer that has an Inertial Measurement Unit or IMU (which includes a gyroscope and accelerometer) to keep the quadcopter stable; the flight controller also has a barometer, GPS, magnetometer to allow the flight controller to know at what altitude it is at, where on the earth it is, and what direction it is facing, respectively.
      • Parts used in this project: NAZA-M Lite with GPS kit (included in the ARF Kit)
  • Voltage regulator, flight controller status LED/USB Interface:
      • Purpose: The voltage regulator provides a steady 5V to the flight controller. The status LED relays info about the state of the quadcopter to the pilot during flight. Indicators include low battery and a GPS lock. The USB interface also allows the flight controller to be configured from a PC (we will use this in part #2).
      • Parts used in this project: The voltage regulator and status LED used are included with the NAZA-M Lite
      • Purpose: A LiPo battery charger safely charges a LiPo battery. It is important to use a LiPo battery charger and not a battery charger designed for other battery chemistries (NiCd, NiMH).
  • Part used in this project: EV-Peak – AP606 – 50W DC Charger/Discharger
      • Purpose: The transmitter accepts the pilot’s commands via multiple joysticks and switches and relays them wirelessly to a receiver on the quadcopter. The receiver decodes the pilot’s commands and forwards them to the flight controller.
      • Parts used in this project: RadioLink AT9 2.4GHz 9CH Transmitter w/ R9D 9CH Receiver
      • Purpose: The camera and gimbal transforms a quadcopter into an aerial photography platform capable of capturing professional quality footage. The camera is attached to a gimbal, which essentially performs the opposite movements of the quadcopter—making sure the camera is always level with the horizon.
      • Parts used in this project: Xiaomi Yi Action Camera, FeiYu Tech Mini-3D Gimbal
  • RPi, RPi Camera, WiFi dongle:
      • Purpose: While the gimbal-mounted camera can record video at a stunning 2K resolution, even the best camera gear is useless if your desired subject is not in the frame. A Raspberry Pi camera is connected to a Raspberry Pi Model A with a 5GHz WiFi dongle. This allows the Raspberry Pi to broadcast a live stream of the forward-facing Raspberry Pi camera to any device connected over WiFi.
      • Parts used in this project: Raspberry Pi Model A , Raspberry Pi Camera Module, D-Link DWA-160.
  • Android phone, phone mount:
    • Purpose: The phone hosts a Wi-Fi hotspot that the Raspberry Pi connects to and provides a convenient screen to view the live stream from the drone. The phone mount is a helpful way to attach the phone to the transmitter.
    • Parts used in this project:  LG Nexus 5 (any Android Phone with support for mobile hotspot will work). Any phone mount that has a suction cup on one end and a magnetic phone mount on the other

What if i’m not ready to mess with the real drone yet?

If you don’t have a drone yet, you can still learn how to code them using the simulator. You can download clover OVF VM image, run it with Virtualbox or VMware Player and test your code in a virtual environment.

More in-depth documentation on simulation is available in the PX4 docs for developers. The simulation is extremely useful during the drone development, allowing to create elaborated CI pipelines for the onboard software.

What you need

Before we get started you’ll need to make sure  you have your drone built, and that you’re using the PXFmini and Raspberry Pi Zero as the heart and brains respectively. You’ll also need to have connected a PPM compatible RC unit and receiver to the PXFMini.

In order to connect the drone to your Linux system you’ll also need a wireless connection, as the PXFMini doesn’t have a network socket, and you can’t create the connection required through USB.

The wireless dongle we’ll be using will create a 5GHz connection, so you’ll need to make sure that your computer’s Wi-Fi is compatible. The dongle used is the Edimax EW-7811UAC (opens in new tab) (Make sure you buy this version rather than the USC).

In the first part of this feature we’ll take a look at how to connect using Linux and go on to open the APM software which will enable us to start calibrating the drone so that level flight is possible. Once that’s out of the way we’ll make a huge leap in the functionality of the drone by fitting a GPS module – this part is surprisingly easy.

Why should i, really?

  • Many of you have quadcopters, but is it really cool to pilot them with a remote control? Especially when there’s a way to make the drone bring you beer, chase your friends, perform aerobatics… completely on its own! Here are some examples of what an autonomous drone can do:

Видео через интернет

image

Для ретрансляции видео установим на сервер VLC плеер:

sudo apt-get install vlc

После установки, запустим его как ретранслятор c UDP порта 5001 в RTSP канал

SERVER_IP:8554/live

cvlc -vvv udp://@:5001 --sout '#rtp{sdp=rtsp://:8554/live}' :demux=h264

На борту запустим видеотрансляцию с камеры на сервер по UDP (вместо

SERVER_IP

адрес сервера):

gst-launch-1.0 rpicamsrc bitrate=1000000 ! video/x-h264,width=640,height=480,framerate=25/1 ! h264parse ! udpsink host=SERVER_IP port=5001


Адрес потока теперь можно использовать как источник видео в настройках GCS или открыть в любом плеере, поддерживающим этот протокол.

Теперь можно спланировать маршрут полета и запустить дрон через интернет, предварительно его включив, например, с помощью помощника по телефону.

Очевидно, что из-за относительно большого времени путешествия видео и телеметрии по сети, такой способ вряд ли подойдет для FPV-полетов в ручном режиме между препятствиями.

Темы для последующих публикаций:

Продолжение следует…

Видеотрансляция

Проверим как работает видеотрансляция в сети WiFi. Такой командой можно запустить видео в TCP-порт на Raspberry с использованием родной утилиты raspivid для камеры Raspicam:

raspivid -t 0 -hf -fps 25 -w 640 -h 480 -o - | gst-launch-1.0 fdsrc ! h264parse ! rtph264pay config-interval=1 pt=96 ! gdppay ! tcpserversink host=0.0.0.0 port=5001

А вот такой командой делается тоже самое, только с использованием ранее скомпилированной обертки rpi-camsrc для gstreamer:

gst-launch-1.0 rpicamsrc sensor-mode=4 ! h264parse ! rtph264pay config-interval=1 pt=96 ! gdppay ! tcpserversink host=0.0.0.0 port=5001


В обоих случаях, трансляция в формате h264 доступна по IP-адресу Raspberry на порту 5001.

Посмотреть ее можно запустив на своем ПК такую команду (должен быть установлен gstreamer), вместо RPI_ADDRESS указываем адрес Raspberry в сети:

gst-launch-1.0 -v tcpclientsrc host=RPI_ADDRESS port=5001 ! gdpdepay ! rtph264depay ! avdec_h264 ! videoconvert ! autovideosink sync=false

В результате должно открыться окошко с видео.

Практически в любую GCS встроен видеоплеер, который может показывать RTSP-видеопоток. Чтобы сделать из Raspberry RTSP-сервер можно использовать консольный плеер VLC. Установка:

sudo apt-get install vlc


Видеотрансляция запускается так:

raspivid -o - -t 0 -n -w 320 -h 240 -fps 25 | cvlc -vvv stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/live}' :demux=h264

Видео доступно по адресу (вместо

RPI_ADDRESS

, адрес Raspberry):

rtsp://RPI_ADDRESS:8554/live

Настройка GCS:

Адрес потока можно использовать для подключения нескольких плееров на разных устройствах, но, так как видеозахват и трансляция для Raspberry весьма трудоемкий процесс, то для нескольких потребителей видео лучше использовать внешний сервер (описание ниже).

Калибровка датчиков и настройка параметров автопилота

Калибровку автопилота можно сделать почти в любой GCS. В документации Ardupilot она

во всех подробностях. Прежде всего устанавливаем тип рамы. У меня стандартная 4-х моторная компоновка, поэтому это

Quad X

Первый полет лучше все же сделать в ручном режиме. Подключаем и калибруем радиоуправление (приемник и передатчик).

Осталось откалибровать акселерометр и компас.

Для того, чтобы Ardupilot видел и учитывал данные с внешних датчиков, установим необходимые параметры:

Для PX4Flow (калибровка самого датчика и обновление прошивки)

FLOW_ENABLE = 1 (Enabled)FLOW_ADDR = 0 (0 = вариант для стандартного адреса 0х42)

Для лазерного высотомера VL53L0X (инструкция)

RNGFND_TYPE = 16 (VL53L0X)RNGFND_ORIENT = 25 (ориентация дальномера вниз)RNGFND_ADDR = 41 (I2C-адрес в десятичном виде). Адрес датчика по-умолчанию 0x29, что в десятичном виде = 41.RNGFND_SCALING = 1RNGFND_MIN_CM = 5RNGFND_MAX_CM = 120RNGFND_GNDCLEAR = 15 (расстояние от датчика до поверхности, когда дрон стоит на земле)

Для IRLock (подробная инструкция, wiki IR-Lock)

PLND_ENABLED = 1PLND_TYPE = 2PLND_BUS = 1

Для сонара переднего обзора (инструкция)

Настройка и запуск ardupilot


Релизы новых версий Ardupilot немного запаздывают в сборке от Emlid. Если необходимый функционал доступен в самой последней версии, то установить ее из исходников можно

Разработчики Navio добавили в свою сборку простую и удобную утилиту Emlid tool для проверки датчиков и настройки Ardupilot. Сначала проверим, видит ли Raspberry контроллер Navio:

emlidtool info

Если в ответ на эту команду выдает что-то вроде:

Vendor: Emlid Limited
Product: Navio 2
Issue: Emlid 2023-06-05 831f3b08594f2da17dccae980a2e3659115ef71f
Kernel: 4.14.34-emlid-v7
RCIO firmware: 0xcaec2284

значит видит. Проверим состояние датчиков (покажет список и состояние):

emlidtool test

и драйвера ШИМ-контроллера в ядре Linux:

cat /sys/kernel/rcio/status/alive

0 = не работает, 1 = работает.

Прошивка ШИМ-контроллера обновляется так:

sudo emlidtool rcio update

Теперь настроим Ardupilot:

sudo emlidtool ardupilot

В терминале откроется текстовый GUI с пошаговыми менюшками. Выбираем copter последней версии, тип

arducopter

, автозапуск при включении (

On boot: enable

), старт после настройки (

Ardupilot: start

Выходим через пункт меню Quit.

Проверим запустился ли Ardupilot:

sudo systemctl status arducopter

Обратите внимание, файл запуска в systemd называется

arducopter

, так как настроен был вариант

copter

Теперь нужно настроить Ardupilot так, чтобы он отправлял нам телеметрию. Для этого отредактируем файл конфигурации:

sudo nano /etc/default/arducopter 

В нем должны быть такие строки:

TELEM1="-A udp:127.0.0.1:14550"
ARDUPILOT_OPTS="$TELEM1"

Сохраняем файл (

Ctrl X

, затем

Y

) и перезапускаем Ardupilot:

sudo systemctl daemon-reload
sudo systemctl restart arducopter


Проверить состояние процесса Ardupilot можно такой командой:

sudo systemctl status arducopter

С такими настройками Ardupilot будет транслировать телеметрию (пакеты

) в локальный UDP-порт 14550. Далее, скрипт

(описание ниже) будет забирать оттуда телеметрию и передавать в GCS или скрипт, а также отправлять в обратном направлении пакеты с командами.

Вместо локального адреса и порта можно записать IP-адрес ПК или планшета в локальной сети и пакеты будут транслироваться сразу туда.

Однако, такой подход оправдан, если данные телеметрии больше нигде не используются и у устройства с GCS статический IP адрес. Иначе каждый раз в настройках Ardupilot придется прописывать новый. Чтобы общаться с автопилотом по TCP могли одновременно несколько GCS с динамическими адресами и еще какие-нибудь скрипты на самом бортовом компьютере, удобнее использовать MAVProxy.

Этот скрипт (написан на Python) может получать пакеты MAVLink на локальный UDP-адрес и ретранслировать их на несколько локальных или удаленных IP-адресов как по UDP, так и по TCP. Пакеты передаются в обоих направлениях Ardupilot ⇔ GCS. Кроме того, MAVProxy представляет из себя полноценную GCS, но с текстовым интерфейсом.

Обновление дистрибутива и установка необходимых пакетов

Открываем SSH-клиент и соединяемся с Raspberry (локальный IP-адрес navio вместо

RASPBERRY_IP_ADDRESS

ssh pi@RASPBERRY_IP_ADDRESS


Стандартный пароль:

raspberry

. В первую очередь необходимо расширить файловую систему ОС на весь объем SD-карты:

sudo raspi-config --expand-rootfs

и перегрузиться:

sudo reboot

После перезагрузки, соединяемся еще раз и обновляем дистрибутив:

sudo apt-get update && sudo apt-get dist-upgrade -y


Устанавливаем дополнительные пакеты:

sudo apt-get install autoconf automake libtool pkg-config libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libraspberrypi-dev gstreamer1.0-tools gstreamer1.0-plugins-good gstreamer1.0-plugins-bad

и компилируем обертку

для

и родной камеры Raspicam:

По для управления дроном на пк и планшетах


Для управления БПЛА используются специальные программы GCS (Ground Control Station). Далее по тексту я буду использовать эту аббревиатуру. Мне по душе пришлась

, мультиплатформенная (Windows, Linux, MacOS, iOS, Android) GCS с открытым исходным кодом, которая стала частью проекта

. Но есть и альтернативы, бесплатные и коммерческие:

(DroidPlanner) для Android,

(iOS),

(iOS). А также консольная

Телеметрия через интернет

Чтобы GCS могла подключиться через интернет к дрону с динамическим IP-адресом, необходим промежуточный сервер со статическим IP, на котором будет запущен скрипт MAVProxy. Для этих целей я воспользовался арендой облачного сервера у одного из известных провайдеров.

Для MAVProxy подойдет самая минимальная конфигурация, но так как у меня этот же сервер будет заниматься ретрансляцией видео, то я выбрал вариант с чуть большей памятью (одно ядро и 1Гб памяти, Ubuntu 18.04). Для минимальной задержки в прохождении данных между бортом и GCS, сервер должен располагаться в максимальной географической близости к дрону и GCS.

Устанавливаем MAVProxy на сервер. Сначала зависимости:

sudo apt-get install python-dev python-opencv python-wxgtk3.0 python-pip python-matplotlib python-pygame python-lxml python-yaml

а потом и сам скрипт через PIP:

sudo pip install MAVProxy

пропишем путь:

Установка образа ос на sd-карту

Для нормальной работы автопилота крайне рекомендуется использовать “быстрые” SD-карты (класс 10). Медленные карты памяти не успевают сохранять логи автопилота даже на небольшой частоте, в результате чего они получаются кривыми или вообще не пишутся. Свидетельством этого может быть ошибка “

No IO heartbeat

Установка связи с дроном в локальной сети

Остановим скрипт (

Ctrl C

) и снова запустим его в таком виде:

mavproxy.py --master=udp:127.0.0.1:14550 --out=tcpin:0.0.0.0:5762

С дополнительным параметром

–out=tcpin:0.0.0.0:5762

MAVProxy будет слушать порт 5762 на входящие TCP соединения от GCS. Как только GCS соединиться, пакеты с данными начнут перемещаться между дроном и GCS. Попробуем подключиться с ПК:

Если подключение удалось, то GCS покажет кучу сообщений с требованием откалибровать датчики и загрузит бортовые параметры с их текущими значениями:

Оцените статью
Радиокоптер.ру
Добавить комментарий