Квадрокоптер на ардуино своими руками пошаговая инструкция

Здравствуйте, наши уважаемые читатели. В этой статье мы поговорим про то, как собрать квадрокоптер на Ардуино. Это не самая простая, хотя и очень увлекательная задача, результатом решения которой станет появление небольшого беспилотника, спроектированного, собранного, и настроенного собственными руками. Сразу оговоримся, что речь идет о максимально дешевом дроне из наиболее доступных по цене комплектующих.

Необходимые детали и узлы

Прежде чем приступить к сборке квадрокоптера своими руками, необходимо обзавестись всеми необходимыми деталями. Мозгом нашей самоделки станет полетный контроллер Arduino Uno. Его возможностей более чем достаточно для того, чтобы управлять беспилотником.

Помимо микроконтроллера, нам понадобятся:

  • Аккумулятор (лучше несколько) на 3.7В
  • Плата MPU-6050 (на ней установлены гироскоп и акселерометр)
  • Транзистор ULN2003A
  • Коллекторные двигатели с полым ротором 0820
  • Провода

Необходимо сделать несколько замечаний. Так как мы собираем дешевый самодельный дрон, то наш выбор пал на коллекторные движки с полым ротором (так называемые coreless motors). Они далеко не так надежны, как бесколлекторные двигатели, но зато гораздо дешевле стоят. Кроме того, можно обойтись без дополнительных контроллеров скорости.

Зато невозможно обойтись без гироскопа и акселерометра. Гироскоп необходим для того, чтобы квадрокоптер мог удерживать заданное направление движения, тогда как акселерометр используется для измерения ускорения. Без этих устройств управлять коптером было бы гораздо сложнее (если вообще возможно), так как именно они предоставляют данные для сигнала, регулирующего скорость вращения винтов.

Мы не указали в списке необходимых деталей раму. Ее можно приобрести, а можно распечатать на 3D принтере каркас, лучи и крепления для двигателей. Второй вариант нам кажется более предпочтительным, тем более, что в интернете можно без труда найти проекты квадрокоптера.

Распечатанная на принтере рама окажется не только легкой, но и прочной. Но если доступа к 3D принтеру нет, раму можно заказать.

Пошаговая инструкция по сборке

Как напечатать раму и крепеж

3D принтеры можно найти во многих университетах, лабораториях, коворкингах. Зачастую доступ к ним бесплатный. Модели для печати можно создать самостоятельно, используя для этого, например, Solidworks. А можно воспользоваться уже готовыми решениями, при необходимости изменив параметры.

Как настроить акселерометр гироскопа

Для настройки акселерометра-гироскопа (I2C)мы рекомендуем использовать следующую библиотеку. Ни в коем случае не подключайте плату к напряжению 5В, иначе вы моментально ее испортите.

Вкратце расскажем, чем интересна плата I2C с датчиками. Она заметно отличается от обычной платы акселерометра с тремя аналоговыми выходами для осей X, Y, Z. I2C представляет собой интерфейсную шину, обеспечивающую передачу значительных объемов данных через логические цифровые импульсы.

Аналоговых выходов на плате не много, и в этом большой плюс I2C, ведь в противном случае нам бы пришлось использовать все порты на Arduino, чтобы получить данные от гироскопа и акселерометра.

Схема подключения к Arduino

Прежде чем плата I2C сможет обмениваться данными с Arduino, ее необходимо подключить к контроллеру.

Схема следующая:

  • VDD -3.3v
  • GND — GND
  • INT- digital 2
  • SCL — A5
  • SDA — A4
  • VIO – GND

Еще раз обращаем внимание на то, что для питания необходимо использовать необходимо именно 3.3В. Подключение платы к 5В скорее всего приведет к ее поломке (спасти может только регулятор напряжения, но он далеко не всегда присутствует на плате).

Если на плате присутствует контакт AD0, он подключается к земле (GND).

В библиотеке, на которую мы дали ссылку выше, используются перечисленные каналы.

Скетч для Arduino

Преимуществом выбранного для сборки дрона микроконтроллера является относительная простота работы с ним. Вам не придется читать специальные книги, документы и техническую документацию. Достаточно знать основы программирования Arduino, которые, как вы сейчас убедитесь, не так сложны.

Подсоединив плату MPU-6050 к контроллеру, включите его и перейдите по ссылке.

Нас интересует скетч I2C scanner code, вернее, его код.

Скопируйте программный код, вставьте в пустой скетч, после чего запустите его. Убедитесь, что подключение установлено к 9600 (для этого запустите Arduino IDE через Tools-Serial Monitor). Должно появиться устройство I2C с адресом 0х68 либо 0х69. Запишите или запомните адрес. Если же адрес не присвоился, скорее всего проблема в подключении к электронике Arduino.

Затем нам понадобится скетч, умеющий обрабатывать данные гироскопа и акселерометра. В интернете есть множество вариантов, и найти подходящий не проблема. Скорее всего, он будет в заархивированном виде. Разархивируйте скачанный архив, отройте Arduino IDE и добавьте библиотеку (sketch-import library-add library). Нам понадобятся папки MPU6050 и I2Cdev.

Открываем MPU6050_DMP6 и внимательно просматриваем код. Никаких сложных действий производить не придется, но если был присвоен адрес 0х60, то необходимо расскоментировать строку в верхней части (ее можно найти за #includes) и написать верный адрес. Изначально таv указан 0х68.

Загружаем программу, открываем окно монитора через 115200 и просто следуем инструкции. Через несколько мгновений вы получите данные с гироскопа/акселерометра. Затем следует провести калибровку датчиков.

Установите плату на ровную поверхность и запустите скетч MPU6050_calibration.ino (легко ищется в интернете). Просмотрите код, по умолчанию в нем указан адрес 0х68. После запуска программы у вас появится информация по отклонениям (offset). Запишите ее, она нам понадобится в скетче MPU6050_DMP6.

Все, вы получили функционирующие гироскоп и акселерометр.

Программа для Arduino

По ссылке вы сможете скачать программу для Arduino, с помощью которой коптер будет стабилизирован в полете и сможет зависнуть над землей. В дополнение к программе обязательно скачайте библиотеку с Arduino PID по ссылке.

Программа поможет вам управлять дроном. Алгоритм, используемый для стабилизации, основан на двух PID-контроллерах. Один предназначен для крена, другой – для тангажа.

Разница в скоростях вращения пары винтов 1 и 2 равна разнице в скоростях пары винтов 3 и 4. Тоже самое справедливо и для пар 1, 3 и 2, 4. PID-регулятор производит изменение разницы в скорости, после чего крен и тангаж становятся равными нулю.

Обратите внимание на цифровые пины Arduino для моторов и не забудьте изменить скетч.

Подключение к контроллеру

Для того, чтобы управлять коптером, нам необходимо получить контроль над моторами, подключив их к Arduino. Контроллер дает на выходе лишь небольшое напряжение и силу тока, поэтому подключение двигателей напрямую лишено смысла. Вместо этого можно поставить несколько транзисторов, позволяющих увеличить напряжение.

Для составления схемы нам необходимы:

  • Arduino
  • Двигатели
  • Транзисторы

Все это собирается на монтажной плате и соединяется коннекторами.

На первом этапе следует подсоединить 4 ШИМ выхода (обозначены ~) к транзистору. Затем подсоедините коннекторы к движкам, подключенным к питанию. В нашем случае мы используем аккумулятор на 5В, но подойдет и аккумулятор на 3-5В.

Транзисторы должны быть заземлены, а земля на плате Arduino должна быть подключена к земле аккумулятора. Двигатели должны вращаться в правильном направлении, то есть работать на подъем коптера, а не на его крен.

Переключив контакт двигателя с напряжения 5В на транзистор, вы увидите, что ротор изменит направление вращения. Единожды совершив настройку, больше возвращаться к изменению направления вращения ротора не придется. Теперь нас интересует скорость.

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

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

Как еще можно модернизировать квадрик

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

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

Выбор платы Arduino Uno обусловлен тем, что с нее можно довольно легко снять чип и поставить его на ProtoBoard. Это позволяет уменьшить вес дрона на 30 грамм, но придется включить в схему дополнительные конденсаторы. Подойдет и плата Arduino Pro Mini.

Что касается программы Arduino, то ее можно сравнительно легко изменить и дополнить новыми функциями. Главное, что с ее помощью дрон способен в автоматическом режиме стабилизовать свое положение.

На квадрокоптер могут быть установлены дополнительные модули, например, плата приемника, что позволит организовать дистанционное управление дроном.

На этом мы завершаем статью о создании беспилотника на Arduino. Подписывайтесь на наши обзоры и делитесь полезными материалами в социальных сетях. До новых встреч.

Загрузка…

Introduction: How to Build a Rc Drone and the Transmitter Using Arduino

Making a drone these is a simple task these days,but it will cost you much.So i’m gonna tell you how to build a drone using arduino with low cost.Also i’m gonna tell you how to build the transmitter of drone too.so this drone is fully homemade.You don’t need to buy any flight controller boards or transmitters.

Supplies

We need thes items to make the drone,

  • For the drone-
    1. Frame– The “backbone” of the quadcopter. The frame is what keeps all the parts of the helicopter together. It has to be sturdy, but on the other hand, it also has to be light so that the motors and the batteries don’t struggle to keep it in the air.
    2. Motors– The thrust that allows the Quadcopter to get airborne is provided by Brushless DC motors and each of them is separately controlled by an electronic speed controller or ESC.
    3. ESCs – Electronic Speed Controller is like a nerve that delivers the movement information from the brain (flight controller) to the arm or leg muscles (motors). It regulates how much power the motors get, which determines the speed and direction changes of the quad.
    4. Propellers – Depending on the type of a quad, you can use 9 to 10 or 11-inch props (for stable, aerial photography flights), or 5-inch racing props for less thrust but more speed.
    5. Battery – Depending on your setup maximum voltage level, you can choose from 2S, 3S, 4S, or even 5S batteries. But, the standard for a quad that is planned to be used for aerial filming (just an example), you will need a 11.4 V 3S battery. You could go with the 22.8 V 4S if you are building a racing quad and you want the motors to spin a lot faster.
    6. Arduino board(Nano)
    7. IMU(MPU 6050) – A board that is basically (depending on your choice) a sum of various sensors that help your quad know where it is and how to level itself.
  • For the transmitter-
    1. NRF24L01 Transceiver Module
    2. NRF24L01 + PA + LNA
    3. Potentiometer
    4. Servo Motor
    5. Toggle Switch
    6. Joystick
    7. Arduino Pro Mini

Step 1: SCHEMATICS

This is the main blueprint of your operation.

How to connect the ESCs:

  • Signal Pin ESC 1 – D3
  • Signal Pin ESC 3 – D9
  • Signal Pin ESC 2 – D10
  • Signal Pin ESC 4 – D11

How to connect the Bluetooth module:

  • Tx – Rx
  • Rx – Tx

How to connect the MPU-6050:

  • SDA – A4
  • SCL – A5

How to connect the LED indicator:

  • LED Anode Leg – D8

How to connect the receiver:

  • Throttle – 2Elerons – D4
  • Ailerons – D5
  • Rudder – D6
  • AUX 1 – D7 You need the MPU-6050, the Bluetooth module, the receiver, and the ESCs, to be grounded. And, to do that, you need to connect the all GND pins to the Arduino GND Pin.

Step 2: SOLDER EVERYTHING TOGETHER

  • The first thing you need to do is to take the female headers and solder them to the prototype board. This will house your Arduino board.
  • Solder them right in the center so that there’s room for the rest of the headers for the MPU, Bluetooth module, Receiver, and the ESCs, and leave some space for some additional sensors you may decide to add in the future.
  • The next step is soldering the Receiver and ESCs male headers right from the Arduino female headers. How many male ESC header rows you will have, depends on how many motors your drone will have. In our case, we are building a quadcopter, meaning there will be 4 rotors, and an ESC for each. That further means 4 rows with each having 3 male headers. The first header in the first row, will be used for the Signal PID, the second for the 5V (though, this depends on your ESCs having a 5V pin or not, if not, you will leave these headers empty), and the third header will be for the GND.

    When the ESCs soldering part is over, you can move on to the Receiver headers soldering part. In most cases, a quad has 4 channels. These are Throttle, Pitch, Yaw, and Roll. The remaining free channel (the fifth one), is used for Flight mode changes (the Auxillary channel). This means that you will need to solder male Headers in 5 rows. And, each but one will have one header, while just one of those rows needs 3 headers in a row.

  • all the grounds were connected with the Arduino grounds. That includes all ESC grounds, Receiver ground (Throttle signal header completely on the right), and the Bluetooth module and MPU grounds .
  • Then, you need to follow the schematics and the connections we explained above. For example, the MPU ( SDA – A4, and SCL – A5), and for Bluetooth (TX – TX and RX – RX) of Arduino. After that, just follow the connections as we wrote them: Signal pins of ESC1, ESC2… to D3, D10… of Arduino. Then the Receiver signal pins Pitch – D2, Roll – D4… and so on. Furthermore, you need to connect the Long Lead of the LED (positive Terminal) to the Arduino D8 Pin, as well as add the 330-ohm resistor in between the Ground of Arduino and the LED Short lead (negative terminal). The last thing to do is to provide a 5V power source connection. And, for that, you need to parallel connect the Black wire (ground of the battery) to the ground of all your components, and the Red wire to Arduino, MPU, and Bluetooth Module, 5V pins. Now, the MPU 6050 needs to be soldered to male headers to the ones you plan on using. After that, turn the board 180 degrees and connect all your components to the respective headers on the prototype board.
  • Power it up and your Arduino is ready for adding codes through a computer!

Step 3: HOW TO PROGRAM YOUR ARDUINO FLIGHT CONTROLLER

  1. First, you need to download the MultiWii 2.4. Then extract it.
  2. Enter the MultiWii folder, and look for MultiWii icon and run it
  3. Use the Arduino IDE to find the “Arduino File” or Multiwii file with “.ino”. Any “CPP file” or “H file” are the support files for our Multiwii Code so don’t open those. Just use the Multiwii.ino file.
  4. When you open the file, you will find many tabs Alarms.cpp, Alarms.h, EEPROM.cpp, EEPROM.h and many more. Find the “config.h”
  5. Scroll down till you find ‘The type of multi-copter” and then by deleting the “//” you mark is as defined and running. Quad X because we are assuming that you are using the “X” rotor configuration on your quad.
  6. Now scroll down and look for “Combined IMU Boards” and activate the type of the Gyro+Acc Board you are uusing. In our case, we used the GY-521 so we activated that option.
  7. If you decide to add other sensors such as a barometer or an Ultrasonic sensor, all you have to do is to “activate” them here and they will be running.
  8. Next is the “Buzzer pin”,There, you need to activate the Flight indicator options (the first 3 ones)
  9. Unplug the Arduino board from the Flight controller and then connect it to your computer using USB. Once out of the FC and connected to your computer, you will find TOOLS and select the type of your Arduino board (in our case Arduino Nano).
  10. Now find “Serial Port” and activate the COM Port the Arduino Nano is connected to (our case, COM3).Finally, click on the arrow and upload the code, and wait for the code to be transferred.
  11. When the upload is finished, unhook the Arduino from USB, insert it back to its place in the FC board, and connect a 5V battery so that the entire FC is powered up, and then wait till the LED on the Arduino is red. That means it has finished booting and that you can connect it to your computer again.Now, find the Multiwii 2.4folder, then the MultiwiiConfig, and locate the folder that is compatible with your OS. In our case, it is the “application.windows64”.
  12. Now start the MultiwiiConf applicationAnd, that’s it! You will immediately notice how you move the FC, the values for the Accelerometer and Gyroscope data on the screen.The orientation of your FC is shown at the bottom.In this interface, you can change the PID values and fine-tune your quad to match your personal preferences. And, you can also assign the flight modes to certain Auxillary switch positions in this interface. All you have to do now is find a place for your Arduino FC on the frame and it is ready to hit the skies.

Step 4: Frame

  • Now you have to do is to set all parts to the frame.you can buy a frame or you can make one at home.

Step 5: Assembling the Motors and Speed Controllers

  • First you need to do is drill the holes in the frame for the motors, according to the distance between the screws holes on the motors. It would be good to make another hole that will allow the clip and shaft of the motor to move freely.
  • It is recommended to connect the speed controllers on the bottom side of the frame due to several reasons which involve the functionality of the drone. These reasons, among others, include that it will “unload” the upper side of the drone where other components should be added.

Step 6: Adding the Flight Controller and the Battery

  • Now assemble our home made flight controller(arduino receiver) to the center of the drone frame.
  • It is recommended to put a small piece of sponge on the underside of the flight controller because it absorbs and reduces the vibrations from the motors. Thus, your drone will be more stable while flying, and stability is key to fly a drone.
  • Now add the lipo battery to the bottom of the frame and make sure that the drone is balanced to the center.
  • now your drone is ready to take off

Step 7: Making the Transmitter

  • The radio communication of this controller is based on the NRF24L01 transceiver module which if used with an amplified antenna it can have a stable range of up to 700 meters in open space. It features 14 channels, 6 of which are analog inputs and 8 digital inputs.
  • It has two joysticks, two potentiometers, two toggle switches, six buttons and additionally an internal measuring unit consisting of an accelerometer and a gyroscope which can be also used for controlling things with just moving around or tilting the controller.

Step 8: Circuit Diagram

  • The brain of this RC controller is an Arduino Pro Mini which is powered using 2 LiPo batteries producing around 7.4 volts. We can connect them directly to the RAW pin of the Pro Mini which has a voltage regulator that reduced the voltage to 5V. Note that there are two versions of the Arduino Pro Mini, like the one I have that operates at 5V and the other operates at 3.3V.
  • On the other hand, the NRF24L01 module strictly needs 3.3V and it’s recommended to come from a dedicated source. Therefore we need to use a 3.3V voltage regulator which is connected to the batteries and convert the 7.4V to 3.3V. Also we need to use a decoupling capacitor right next to the module in order to keep the voltage more stable, thus the radio communication will be more stable as well. The NRF24L01 module communicates with the Arduino using SPI protocol, while the MPU6050 accelerometer and gyro module uses the I2C protocol.
  • You have to solder all parts together according to the diagram.you can design and print a circuit which makes easier.

Step 9: Coding the Transmitter

  • For programming a Pro Mini board we need an USB to serial UART interface which can be hooked up to the programing header located on the top side of our controller.
  • Then in the Arduino IDE tools menu we need to select the Arduino Pro or Pro Mini board, select the proper version of the processor, select the port and select the programming method to “USBasp”.
  • Here’s the complete Arduino code for this DIY Arduino RC Transmitter
  • Upload it to the arduino pro mini.

Step 10: Coding the Receiver

  • Here is a simple receiver code where we will receive the data and simply print it on the serial monitor so that we know that the communication works properly. Again we need to include the RF24 library and define the objects and the structure the same way as in the transmitter code. In the setup section when defining the radio communication we need to use the same settings as the transmitter and set the module as receiver using the radio.startListening() function.
  • Upload it to the receiver

Step 11: Taking Off the Drone

  • Firstly, position your drone on the ground and prepare it for operation. Grab your flight controller and then start your first flight carefully and safely.
  • However, it is highly recommended to throttle up the drone slowly. Moreover, for the first time, make sure to fly it at a lower altitude.
  • I hope that this article will help you to build your homemade drone.
  • Don’t forget to like this and leave a comment.

Introduction: Arduino Nano Quadcopter

(At the moment the project is being edited as the previous model had a couple of flaws)

This is Arduino based and 3D printed nano quadcopter which flies on DC brushed motors. The name nano comes from the fact that the project is based on Arduino nano, which I think is one of the most successful dev boards ever made. This project isn’t just another Hey — look what a cool thing I made, it is instead aimed at analysing and understanding the design decisions which need to be made when designing a quadcopter, thus it will be a bit lengthy. However if you want to understand quadcopters from the bottom up — stay with me!

When I initially started working on the project (a shame to say — years ago…) I went along with Bluetooth 2.0 module as this was popular back then, however years passed by and many more Arduino modules got developed. Recently, I noticed that a couple more different nano modules such as BLE-Nano and RF-Nano (nRF24L01) are cheaply available on Aliexpress so I decided to revive this project and finally complete it. I will use BLE-Nano as the connections worked out very well and I will also want to control it using my smartphone.

One more bit, I specifically chose SMD parts available at JLCPCB Basic library and provided both Schematics and the PCB files available at EasyEDA for both, Nano Quadcopter and later improved nRF52840 Quadcopter. Some through-hole connectors and other quadcopter related essentials will still have to be sourced separately, otherwise one can preorder an already assembled PCB or order parts separately and solder them by hand.

P.S. The robot is dedicated for M.O.N.T.E. (Mobile Omnidirectional Neutralization and Termination Eradicator) killer robot from The Big Bang Theory :D

Step 1: Frame & Plastic

Material Choice

When designing the frame there are a couple of considerations to make. The frame must be:

  • Light — obviously the lighter it is, the easier it will be to lift it up!
  • Sturdy — quadcopter tend to fall a lot and if it doesn’t break after every fall — is it a huge plus.
  • Resistive to vibrations — otherwise it might be unstable as the motors do vibrate a lot. This also helps to reduce accelerometer picked up noise.

In the past I saw quadcopters which frame was made from plastic, carbon fibre, some sort of metal, PCB or a combination of these. Because I wanted to learn about 3D printing too, I decided to design my own frame and then print it using ABS plastic, however PLA should also be good. I didn’t do a PCB only based quadcopter as that would increase the overall price of the PCB printing plus if one part broke… the whole quadcopter would have to be thrown away.

3D Design

Using 3D printer allowed me to design the quadcopter in any shape and form I wanted. The weight of the frame that I designed was around 10 — 15 g however it will vary slightly depending on the printer settings and the plastic used to print it. For the design I used a free web design tool TinkerCAD, which is super easy to use and I encourage using it for beginners or for smaller projects. For more professional designs you could also use AutoCAD (Paid) or Blender (Free), the latter being open source and free to use is a huge advantage in my perspective, however the learning curve is way more gradual when compared to TinkerCAD.

I added the design files here so that you could go and print it right away yourself. However if you want to look into the design from all angles then visit Thingiverse. Likewise, you can visit TinkerCAD to modify my previous design the way you like it.

For a single quadcopter you only need to print Quadcopter_bottom_3.stl. Other parts are optional as they do not add any value and are there more for the looks. Also note that the screws were printed very poorly and thus I could not fit them through the designated holes. I redesigned the bottom part so that you could stick in the top part and then could simply use some plastic ties, wire or even electrical wire if you intended to use it — note though that each part adds unnecessary weight.

Step 2: Electronics Components

While researching some things I noticed some very similar or otherwise very interesting projects such as this one based on MultiWii project, Crazyflie 1.0 and Cracyflie 2.X or another hobby project. These are given here as a reference if you wanted to find other components which could be used for your projects or if you get stuck somewhere. When deciding each part for my quadcopter I will include its weight, if it is larger than 1g. Otherwise I will simply omit it as it’s very insignificant.

Microcontroller & Connectability

When I started this project initially I used a clone of Arduino Nano, which doesn’t include any communication module, thus I wanted to use HC-06 Bluetooth 2.0 slave module. However these days way better alternatives include such as:

  • Bluno Nano, which has. built in CC2540 BLE chip. The cost is around £27.
  • BLE-Nano, which is a Chinese clone of Bluno Nano. On Aliexpress it’s available for ~£4 including delivery!
  • RF-Nano, which is available for ~£4 on Aliexpress including delivery.
  • Nano 33 BLE, which runs a lot faster than than the above processor nRF52840. The cost is around £17.
  • Nano 33 BLE Sense, which is very similar to the Arduino Nano 33 BLE but it additionally includes some more sensors such as accelerometer and gyro, thus wouldn’t need to add externally. The cost is around £27.

I thought that Beetle BLE was another interesting choice, however they only have 2xPWM output, thus controlling 4 motors isn’t possible without extra circuitry, thus not worth the pain in this project. I went along with BLE-Nano for their low price and connectability to a smart phone using BLE. On top of that, these chips no longer have the CH340 chip which was typically inside the clone boards and was used as both USB-to-Serial converter and 5V to 3.3V LDO voltage regulator, which could supply up to 25mA of current without dropping the voltage. This means there is no need to install the CH340 drivers and the used new LDO SP6205 can now supply up 500mA. They also finally use micro-USB rather than the old fashioned Mini-USB (about time!).The weight of each chip varies barely. Also note, that RF-Nano utilises pins 9, 10, 11, 12 and 13 for talking to the RF module, thus utilising these pins for PWM is not possible — you will have to find a workaround such as using an external PWM chip or using Software based PWM.

If you do not care about the money, I would recommend going with their the Nano 33 BLE or the Nano 33 BLE Sense (you will have to modify my code a bit..), but I wanted this to be as cheap as possible. Plus if I ever wanted I can simply replace the Nano to a different one without needing to remodel the PCB — that’s the beauty of using Nanos for Quadcopters!

I think if not choosing Nanos other great choices for microcontrollers (and I think in the future I will redesign the schematics and PCBs to work with these) would include:

  • Particle Xenon — based on nRF52840 with built-in BLE this is a great dev board which costs around £11.Sadly it’s being discontinued and I think you should buy a couple of them as they’re great.
  • Adafruit Feather nRF52840 Express — this and Particle Xenon are rather interchangeable. Although the connection pin number vary, they will behave pretty much the same.. The price however closer to £22.
  • ESP32 — This is another great chip and it has many modules, most popular ones being Lolin32 variants. It has built in BLE, Bluetooth and WiFi thus making this a great choice.
  • ESP8266 — This chip does not support BLuetooth in any way, however it does support WiFi. It probably can be described as a younger brother os ESP32…

The good thing about the above modules is that they are slightly wider and due to this our IMU can be easily fitted underneath thus saving a lot of space. Not only that but they already pack a battery connector (would need to find out the connector current rating though), battery charger, voltage level detector and many more. On top of that they can alternatively be programmed using Microcpython (ESP), Circuitpython (nRF52840) and others, thus I think they might be a great choice for the future. Not only that but the BLE built inside most of these support something called HID mode, which would allow to connect them straight to pretty much all gaming controllers for phones or PS4 thus removing the need of the phone altogether. I think they are great choices of chips.

Total weight ~5g

Motors

I got two sets of motors, one being from Micro Motor Warehouse (later called MMW motors) and another was a replacement for Hubsan X4 (later called Hubsan motors) from Ebay. Both them were 8.5mm x 20mm in size also known as configuration 8520. The MMW set was not cheap (~£25), however the motors are supposed to be a lot faster and have more thrust than the Hubsan ones. The weight of my quadcopter is a bit larger, thus I may need fast motors to lift up the weight, however I will test both motors to see if Hubsan is sufficient as their price is only around ~£4 per set. If faster motors are required, there is an option from the same place as MMW — these, however note that thrust is the same thus you won’t really see much difference. Another way is getting from TinyWhoop shop, however the motors are smaller. When buying motor sets the most important things (from most to less important) which you need to take a look are:

  • Type — there are brushed DC and brushless AC motors. Nano quadcopters are usually based on brushed DC motors as they’re smaller and easier to control without the need of extra AC controllers. However they have a lot less thrust and cannot be used for larger quadcopters.
  • Can diameter — the 3D design was made for motors with 8.5mm diameter. The design would have to be altered for a different diameter.
  • Max Static Thrust or simply Thrust — defines how much weight can the motors keep in the air or basically — how heavy your quadcopter can be. Propeller type have to be defined and often thrust vs current curve (often called performance curve) is supplied e.g. for Hubsan you can find one online. To compare, the MMW motors have 40g while Hubson have 34g of thrust per motor.
  • Weight — the weight of a motor, which will be added to the total weight of the quadcopter. Both MMW and Hubson motors weight around 5g per motor.
  • Load current — defines what current is being drawn by a motor when a specified voltage applied using specified propellers. Note that without the propellers attached this current would drop to really small values, thus when testing for brownout voltage (more of that later) always put on the propellers. To compare, MMW motors draw 2.75A while Hubsan 1.85A of current per motor.
  • Recommended propeller size — years ago I didn’t care about this but then I noticed that the quadcopter doesn’t get lifted anyhow and realised that the propellers I used were simply too small! Both motors should aim for 55mm propellers.
  • Lifetime rating — this defines how long should the motors run without failing. MMW specify this to be 5-6h, I am not sure about the Hubsan ones though. Thus always a good idea to buy two sets of motors.
  • Speed — fast speed will give you faster flights, however with increased currents, thus need better batteries. Plus they’re likely more difficult to control due to their speed… Thus I wouldn’t care about this one for as long as the motors are designed for quadcopters.
  • The plug type — this is to simply know which female type connectors to buy to match these. MMW motors use JST-PH 2.0 2-pin connectors and I would recommend you sticking to these. More about them later.

Total weight for all motors ~20g

Inertial Measurement Unit (IMU)

Essentially IMU is used to calculate the angle between the quadcopters each axis and the ground. Normally IMU used inside quadcopters must have at least two elements — an accelerometer and a gyroscope. Not going too much into the details on how IMUs are made it is worth noting that:

  • Accelerometer (later called accel) measures acceleration (duhh!). It has 3-axis sensor and thus can measure the acceleration component in 3 perpendicular axises. Earths gravity is actually an acceleration component pointing to the centre of the Earth and thus it can be measured too. By applying some basic maths we can calculate where with respect to the current quadcopters rotation the gravity vector is pointing to. However accels not only pick up the gravity but any other acceleration too, such as quadcopter accelerating up, down, to the sides. Not only that but the vibrations caused by the motors are essentially accelerations too! This type of introduced motor noise is often reduced by damping the sensor e.g. adding polystyrene in between the accel and the quadcopter itself. Overall, this sensor alone doesn’t cannot be trusted well enough.
  • Gyroscope (later called gyro) measures rate of rotation (wait whut?). It has 3-axis sensor and thus can measure the change or rate of rotation in 3 different axis. Mechanical gyros measure the actual angle, however chip based solution instead rely on other techniques thus allowing to minimise the sensors size and also add the third axis (along the surface of earth) which otherwise couldn’t be measured. The drawback is that to evaluate the angle one must integrate the sensor value over time. This gives a very smooth output value, however if such sensor is used alone, the angle value is going to drift over time. This happens in two ways:
    • Sensor bias or simply offset — gyros are not made perfect, thus every gyro that comes out of the manufacturing process will add some offset to their actual measurement value. This offset can be eliminated by calibrating the gyros, which is done by placing them motionless and then taking a sample of let’s say 100 measurement and averaging them. Later this offset value can be subtracted from the actual measurement thus improving the result.
    • Continuous vs discrete world dilemma — we live in continuous world, while the microcontrollers do not. When sensor performs measurement it samples them at a specified sampling rate e.g. 80Hz. If the some change occurs very rapidly in between the two sample measurements the measurement will not pick that change up. This problem is reduced by increasing the sampling rate, however over longer periods of times the drift will still become apparent.

This is why IMUs come equipped not with one but two sensors — some clever algorithms are being performed to merge the sensor values together to acquire a smooth and reliable angle values over even very long periods of time.

Another important factor is placement of the IMU sensor within the quadcopter surface. This is no simple maths but its analysis you can find here. In short though, accelerometer sensor must be place as close to the centre of mass as possible as otherwise due to centripetal acceleration the rotation of the quadcopter will be measured as acceleration even though the quadcopter will actually not be moving at all! Either this or additional maths would have to be used to remove this component from the final result. I will try to keep the accelerometer as close to the mass of centre as possible, however I believe that in out case this will not add that much of extra inaccuracies as the quadcopter by nature will try to keep it’s rotation angle in alignment with the Earths surface while not in motion — otherwise it would fall. Well, unless you’re performing some tricks I guess! Otherwise can always place it on the second layer of the PCB aka The Upside Down!

For the project I used a very popular and cheap MPU6050 IMU, which includes a 3-axis Gyroscope and a 3-axis Accelerometer. One might be interested. in using MPU9250, which additionally includes a 3-axis magnetometer (measures the magnetic field), however indoors these do not very well due to existing magnetic interference from the electrical wiring and construction, plus the running motors will induce extra magnetic field, thus I wonder if it worked. Anyway, within the circuit and PCB I added the MPU9250 board, which is backwards compatible with the MPU6050, thus any of these IMUs could be used.

Total weight ~2g

Batteries

Choosing adequate batteries is very important as wrong batteries will not allow the motors to draw enough current to light up the quadcopter and on top of that there will be huge voltage drops, which will keep interfering with the electronics. There are a few important points to note when buying them:

  • Type — there are many battery types such as li-po, li-on and even these come in shades. Rather recently Graphene based batteries became available, which can withstand higher currents and have higher capacity density. Of course the downside is the price!
  • Capacity (measured in mAh or Wh) — will determine how much energy is stored inside the battery. The larger the capacity, the longer the quadcopter will run on a single charge. This will be proportional to the size and weight of the battery and will also determine how much current can be drawn from and into the battery.
  • Max allowed discharge (burst) and average discharge (constant) rate (C) — the first determines peak currents e.g. when quadcopter starts accelerating, while the latter determines normal operation current e.g. quadcopter is kept constant in the air. There is often a rule of thumb that multiplication of capacity and the discharge rate will give the current that the batteries can supply. To be on the safe side also need to add 20% of safety margin — we do not want the batteries to explode do we? Thus for example, if you had a battery with 200 mAh and 20 C of average/constant discharge, then 200mAh * 25C * 80% = 4A. Thus on average such a battery can supply 4A without issues. However, this is just a rule of thumb, when very high currents are involved, we want the discharge rate to be way higher, independently to the battery capacity. For example, I Previously tried Turnigy nano-tech 650mAh 1S 15c (thus according to our calculations 7.8A of current) with absolutely no luck. They only managed to fully power a single motor, which meant that the discharge rate was simply too small.
  • Weight (g) — larger capacity batteries weight more, thus need to find some which provide enough flying time but still provide good flying performance.

Let’s calculate which batteries to choose and how long the batteries will last. In our case the motors draw hundreds of times less current than the electronics, thus when calculating the required discharge rate we only need to care about the motor currents. Total max load current = 2.75A * 4 = 11A. Good battery capacity should range from 150-350mAh and I chose a battery somewhere in the middle — 260mAh (how? intuition..). To simplify calculations I will use 0.26Ah. This means I need 11A / 0.26Ah = 42.3C of max discharge rate. From this follows that on a single charge they should last at least for 0.26Ah * 60min / 11A = 1.4 min. Doesn’t seem a lot at all does it? I tested when I attached the quadcopter with the threads to the ground and it seems like the numbers are reasonable, I really couldn’t hold the quadcopter in the air even 2min, however this assumes that the quadcopter is attached to the ground and thus not only has to win over the its own weight but also resist the threads. Real world numbers should be reading at least 3min of flight. I suggest buying batteries such as Turnigy nano-tech 300mah 1S 45~90C (9g) or even Turnigy Graphene 600mAh 1S 65C (15g) which seem to be very promising as their discharge rate really high, but I have’t tested them. If you have extra cash, buy both Graphene and normal batteries the normal ones as the graphene are lighter when compared to alternative batteries with the same capacity and provide a lot higher discharge rates (at least on the paper). I didn’t try them myself but would be really interesting to see how they compare in reality as I think the battery I got with 35C discharge rate is a bit smallish as well. When choosing the battery and propellers also take a look at this video, where various battery and propeller tests are being performed! I will get back to this video when choosing the propellers..

Total weight ~12g

Connectors

The most used connectors for quadcopter are called JST. They’re confusing because there are many types and everyone mixes them and sometimes advertises one as another, but the most popular connectors overall seem to be:

  • JST PH 2.0 2-Pin, which PCB female connector are through-hole, and JST PH 2.0 2-Pin SMT RA (Right Angle), which are surface mounted (SMD). The first also come in a 90 degrees rotate form. These are the most popular ones by far IMO and I found them being used for both batteries and motors. The MMW motors come equipped with JST-PH 2.0 2-pin male connectors. Not only that but if you notice Wemos Lolin32, all particle boards and all battery supported Adafruit boards come equipped with the SMD variant of this. We will use there for motors and will also add one for battery. Both are available on Farnell, ebay or Aliexpress. Make sure you buy the correct connectors as shown in the images as they’re all called very similarly and some providers even name them the same…
  • JST Micro-T MX 2.0 2-Pin, which PCB female connector comes in SMD package only (Haven’t seen other). This is second most common battery connector, however I haven’t seen them being used for motors before. The good thing about them is that even though the solder mask is slightly different, they can still be soldered on the same mask as JST PH 2-Pin SMT RA.
  • JST connectors like these. They are annoying as no name is usually provided thus have to always inspect the images. Good thing is that their spacing is 0.1 inch (2.54cm), which is the same as that of breadboards, thus they’re perfect when testing as can be plugged straight into the power line! On top of that, two 0.1 inch spacing holes can be added to the PCB to allow connecting these without buying any special connectors. They do slip out easier than other connectors, thus they’re better for testing as they can be pulled out in case something goes wrong. The downside is that by accident you might plug the connector incorrectly the other way around… Thus please don’t drink before plugging it in as you might fry the chips which were not protected by the special circuitry.
  • BT 2.0 2-Pin — these are used on large quadcopter due to their lower resistance and thus ability to carry larger currents. We do not need those.

Some batteries might even come with double connectors. For my quadcopter design I didn’t want to go nuts and use different connector for everything. For the motors I used JST PH2.0 2-Pin through hole. Battery on the other hand could come with various connectors and that’s harder to maintain. I used to cut the existing connectors and solder the preferred ones, but that’s a bit annoying too. Therefore I will add two 0.1 inch holes to support JST connector, which will be best for testing, and then JST PH 2.0 2-Pin — the same on as for motors as I already another one of those connectors available. Of course it would be nice to be able to support all connectors, thus I will add the connector parts in the Optional Schematic fie if you decide to use different batteries.

Note that connectors will have to support large currents of up to 10A, thus always good to check if they’re capable for that. Other considerations when designing the PCB will be making thicker tracks for motors with no jumper wires/vias to not affect the performance.

Propellers

The propellers are differentiated by their:

  • Length — which is measured as the radius multiplied by 2.
  • Number of the leaves — this usually is 2, but others exist with 3 and more.
  • Shape of the propeller —
  • Angle of the twist — the steeper the angle, the more thrust the propeller can provide.

The recommended propellers for MMW were 55mm ones, such as for Hubsan quadcopter. I struggled a lot with which correct propellers to get as the quadcopter didn’t want to lift so I also ordered Walkera LadyBird props, which are also 55mm. I checked this the previously mentioned video to find out that they actually give more thrust than the Hubsan and depending on the battery it can be somewhere around 3g per propeller thus in total giving additionally 12g of thrust! There are, however even better propellers such as KingKong ones, however I didn’t want to use larger propellers because they provide a lot more thrust, thus being able to lift the quadcopter easier, however will draw more current, thus might overheat the motors, thus I wasn’t sure…

Total weight 1g

N-MOSFETs (JLCPCB Assembled)

We need 4xMOSFET transistors also known as switches. They will be used together with PWM to supply the current to the motors in peaks. Choosing them might be tricky and there are a couple of important points when when choosing one for out application:

  • Maximum drain current it can supply (Id max), which in this case should be around 3A to support the motor which can draw around 2.75A.
  • The Vgs threshold voltage, which has to be low, maybe somewhere around 1V as li-po batteries voltage might drop to 3.4V at some point. If too large threshold is chosen Arduino won’t be able to turn the MOSFETs on enough to supply the required amount of current. It is always best to also check the drain current (Id) dependency on the threshold voltage (Vgs threshold) as each transistor will have a different response.
  • Drain to sink resistance when MOSFET is fully turned on (Rds (on)). This is provided under certain gate to sink bias Vgs. Normally expect this to be around 0.032Ohm, however the smaller the better. If you choose some MOSFET with Rds (on) equal to 0.3Ohm or so, due to motors running at 3A the voltage drop over the MOSFET will be 0.9V, thus motors will not get sufficient voltage drop over them.

Note that MOSFETs always include a freewheel (also called flyback) diode in the package, it is needed there to work and if some schematic will not be including them, they probably still exist but are simply not shown. Also these diodes protect the MOSFET from the surge currents coming from the motor coil, which will protect the MOSFET from frying, so double plus.

On the initial board that I made I ordered SQ2310ES from Farnell as it has Vgs threshold voltage of 0.6V and could supply 6A! This might be a little over the board but hey — if I wanted I could power any possible brushed motor with them without any concerns! I also made a table with other good MOSFETs and their important characteristics. Some of these were picked from the similar quadcopters and some came from the same family of chips or I stumbled upon them on Aliexpress or JLCPCB. All these are 3-pin SOT-23 packaged, thus compatible with the later provided PCB:

  • Name // Max Ids (A) // Vgs thr (min-max) (V) // Rds(on) (Vgs = 3V, T = 25C) (mOhm)
  • SI2302DS // 2.2 — 2.8 // 0.65 — ??? // 80
  • SI2300DS // 2.5 — 3.0 // 0.6 — 1.5 // 60
  • PMV31XN // 3.75 — 5.9 // ??? — 1.8 // 35
  • CJ2302 // 2.1 // 0.65-1.2 // 40
  • CJ2304 // 3.3 // 1-2.2 // 400???
  • AO3400A // 5.9 // 0.65 — 1.45 // 22
  • IRLML2502 // 3.4 — 4.2 // 0.6 — 1.2 // 35
  • SI2314 // 5 // 0.6 — 1.1 // 50
  • SI2312CDS // 4 — 5 // 0.45 — 1 // 28
  • SQ2310ES // 3.5 — 6 // 0.4 — 1 // 32
  • IRLML0030TRPbF // 4.3-5.3 // 1.3-2.3 // 150

Note that all of them had Vgs threshold very small and can supply enough current to power Hubsan motors. However to run the faster motors I would only recommend the ones that can provide currents of over 3A and has smallest Rds(on) as then less voltage drop will be over the MOSFET itself rather than the motor. JLCPCB basic library had AO3400A available thus I went with it. At the time of writing most popular MOSFETs on Aliexpress out of the suggested ones were SI2300DS, SI2314, IRLML2502 and AO3400A.

If through-hole components used you could use these:

  • Name // Max Ids (A) // Vgs thr (min-max) (V) // Rds(on) (Vgs = 3V, T = 25C) (mOhm)
  • NDP6020 // 35 // 0.4 — 1 // 22
  • IRF3706 // 54 — 77 // 0.6 — 2.0 // 10
  • IRF3708 // 52 — 62 // 0.6 — 2.0 // 12
  • IRLB3034 // 195 // 1 — 2.5 // ???
  • IRLZ44 // 36 — 50 // 1 — 2 // ???
  • IRL540N // 26 — 36 // 1 — 2 // ???

All these come in TO-220 package, thus it will be easy to solder them and they will withstand large amounts of currents. I would recommend the ones that have the lowest Rds(on) as then they will dissipate less power and the motors will be able to run at higher speeds.

P-MOSFET (JLCPCB Assembled)

Because the used batteries can deliver tremendous amounts of currents we do not want to risk connecting the circuit the wrong way around, which does happen by accident, thus it’s important to design some kind of reverse battery protection system. This can actually be done very easily using a single P-MOSFET transistor as discussed in here. There are two ways to approach this though:

  • Install such a P-MOSFET which can supply currents of over 12A. NDP6020P would fit for the purpose with its very good Vgs but if you notice it is a TO-220 package through-hole component.
  • Only protect the expensive electronics such as Nano, IMU and pixels. In this case we can use pretty much any P-MOSFET available as it would only need to supply up to 300mA of current at max.

For now I though we could at least protect the main electronics, which will make life a bit easier. To achieve that we could separate the battery into two supplies, one unprotected, which will be used to run the motors, and the other protected, which will be used to power the rest of the electronics. N-MOSFETs and the used Zener diodes will probably die (Direct path for the electricity to flow through the diode and the zener diode) if you connect the battery the other way around but the other electronics and motors will live. I would also probably recommend installing a battery connector, which permits connection one way only…

If we go along with this design, some of good choices of P-MOSFETs would include AO3401A, SI2301CDS, SI2301DS, CJ2301 or IRLML6401 and many others as it needs to provide up to 300mA of current at max with optional components added. The AO3401A and SI2301DS were available at JLCPCB basic library thus I picked randomly between the two. What you can also do is check the N-MOSFETs list I suggested and find their P-MOSFET alternatives (most N-Type will be even numbered e.g. 2300 and P-Type alternative will be odd numbered, thus 2301) as all of them will have low Vgs threshold.

Through-hole alternative could be NDP6020P

Resistors (JLCPCB Assembled)

Resistors regulate how much current can flow between two points in the circuit. The current flowing through them also gives a voltage drop proportional to the current flowing through them. There is a number of resistors we will need to use for this project for various reasons:

  • 4x10kOhm pull-down resistors going from each MOSFETs gate to ground. To understand why we need these you need to know a little bit of a theory. A MOSFET has 3 pins named Drain, Source and Gate. N-type MOSFET is said to be switched on when high enough (at least higher than the Vgs threshold voltage) voltage is applied to the Gate. When the MOSFET is switched on, current flows from the Drain to Source and while there is some resistance in series between the two, it will be low for as long as the applied Gate voltage is a lot large than the Vgs threshold. Now the reason why the MOSFET gets switched on when the Gate voltage is applied in fact because Gate is not connected to the other two channels in any way — it is actually a capacitor! The other side of this capacitor is essentially an area between the Drain and Source (yep, that’s why MOSFET is being drawn like this with the gate disconnected and large square area between drain and source). When Gate voltage is applied the other side of the capacitor plate attracts negative electrons and when a large enough amount is attracted a channel is created between drain and source allowing the current to flow. Getting back to the pull-down resistors — without them we would have two problems 1) when turning the transistors off due to gate being a capacitor it tends to store charge, thus if we turn the N-type MOSFET on by connecting high Gate voltage and then disconnect the power — the MOSFET will stay on for a very long time. Of course when we set Arduino pins to LOW, it will create a path for the current to flow, however to achieve the best possible result is to add an additional 10kOhm resistor going to ground thus providing an extra path for discharging the gate capacitor and consequently turning the transistor off. 2) Before Arduino sets each output pin to LOW the gate will have a floating point, meaning the voltage is unknown. It may as well be that the motors will turn on for just a brief moment! Thus providing a pull-down resistor will guarantee that each MOSFET is turned off at the start. To read more about this and see some interesting graphs see this article.
  • 4x100Ohm resistors connecting from the output of Arduino PWM pin to the gate of each MOSFET. If we did not include these resistors, the current rushed into the Gate of the MOSFET when output pin state is HIGH would be very large and would thus turn the MOSFET instantaneously on. This would create a very large inrush current due to the nature of the motors inductor, which would drop the battery voltage significantly enough to even reset the Arduino or the electronics. We need to lower this inrush current by lowering the current flowing into the MOSFET Gate, thus a very small 100Ohm resistor is added which will charge the Gate capacitor.
  • A combination of 33kOhm and 100kOhm will form a potential divider pair used to measure the battery voltage. Li-Po batteries do not like dropping below 3.2V nor do they like being charged over 4.2V. Every time they go over the limit there is a risk damaging them or even causing fire! Thus we need to know when to turn the quadcopter off before the voltage reaches critical levels. For this to work though we will need to utilise the chip built-in internal 1.1V reference. For this to work correctly we need to make sure we do not apply more than 1.1V to the analog pin (as 1.1V will measure 1023 or simply put 100%), which is being used to measure the battery voltage. I chose such resistor values so that when fully charged battery to 4.2V is measured it would give 33k / (33k + 100k) * 4.2 = 1.04V. This is perfect, because the internal reference actually varies from chip-to-chip and can be in the range 1 — 1.2V. The chosen value would allow the quadcopter to work with any nano board no matter the reference variations while also providing the highest available resolution of close to 10bit. Also note that these resistor values are meant to be high in order to not waste the energy, however in our application this isn’t much of a concern knowing that motors draw thousands of times more current.

Capacitors (JLCPCB Assembled)

Capacitors (later called caps) in quadcopters are used to filter out the unwanted high frequency voltage spikes on the power supply, which would otherwise make Arduino and other chips unhappy. The voltage spikes are mainly caused by the motors, which on top of causing noise due to brushes also take in a lot of current (12A in total!). Thus if care is not taken, voltage would fluctuate significantly, sometimes in the order of hundreds of millivolts. This can affect video quality (if video transmission is used), communication between the base and the quadcopter (noise in the transmission signal), the MCU (the chips could constantly get reset) and the IMU readings (noise on the ADC inside the IMU for example).

Note that caps come in different types based on the dielectric material with most popular being ceramic, electrolytic and tantalum ones. I strongly recommend watching this and this videos to see what a significant change can be achieved with the right placement of the caps. There is also this article which I recommend on checking out. From this post, we will need to sort out the voltage spike issue in two ways:

  1. Reduce the noise at the source of disturbance, thus the motors
  2. Remove the voltage spikes from power supply close to the chips and other sensitive parts e.g. reset pin (regarding the latter on Arduino, reset pin seems to have auto-reset mechanism performed through another capacitor, thus to not mess with that I will avoid adding this capacitor for now)

On top of that, we need to choose low ESR (Equivalent Series Resistance) caps for the design as motors run on high PWM frequencies and capacitors will act as a very low value resistor for these type of spikes and effectively short them to ground. Note though that all capacitors have built-in parasitics such as resistance and conductance in series with the capacitance. Therefore in high frequencies even though the capacitance resistance (to be more precise — impedance) is low, due to the other parasitic components the resistance can never never go below a certain point and sometimes even starts rising with the increasing frequency — pretty crazy.

Some articles recommend using ceramic caps whenever possible as they don’t have polarity and have less parasitics, thus will have better efficiency and will also filter out the ripple better. However they usually come in lower values thus sometimes a tantalum cap could be used in parallel with a ceramic one. Electrolytic caps are used as a last resort. Also note that you cannot just blindly go for one type of capacitors all the time — the right choice will depend on the application e.g. in music industry different types of caps are preferred, ones which may have less noise and ESR might not be such a huge concern.

Caps have to be placed physically as close to the target area as possible to be effective. In this project will need to add caps to these areas:

  • 1 x 100nF ceramic cap between VCC of IMU and GND. Note though that in our case MPU6050 module already has these built in as shown in the documentation. However an additional cap isn’t going to hurt much.
  • 1 x 22uF and 1 x 100nF ceramic caps in parallel between 5V of Arduino and GND. From the BLE-Nano schematics we can see that 5V and 3.3V rails only have 0.1uF caps (located at the output of the two different voltage regulators) and no large caps. We will not use 3.3V rail at all, thus this one line is fine, however we would still need one caps between 5V and GND to provide stable voltage.
  • 100-300uF tantalum cap in between the battery pins. JLCPCB largest available cap is 100uF Tantalum one, thus I will add that, however its price is rather large… On top of that I added holes for another through-hole cap if needed in the future.
  • 1 x 100nF ceramic cap between analog input measuring the battery voltage and GND to give more stable battery readings.
  • 4 x 22uF ceramic caps in between each positive motor pin and GND (or motor controllers for brushless motors).
  • 4 x 10nF ceramic caps in between motor connectors to remove the brush noise as explained here. They’re using 100nF caps, however larger caps will impose extra load and might increase the noise, thus 10nF is safer. Note though that the cap is meant to go right in between the motor pins, however this is not possible for the motors we got, thus placing right next to the motor connectors will have to be sufficient. From this link, you can see that without this cap a motor can cause power supply ripple of over 3V, while adding one it reduced to 0.5V!
  • (for now no) 2 x 100nF ceramic cap between each Arduino RST (reset) pin and GND in case these will not be included in the used MCU.

Note that all caps have to be installed as close as possible to the desired places. They cannot simply be be all put somewhere in the corner as in many cases the chip might not be stable or might not work at all.

Total weight 1g

Diodes (JLCPCB Assembled)

We will need to incorporate a freewheel (flyback) Schottky diodes in between the motor legs to provide with the current path when switching the motors off, this is also called snubber diode configuration. Check this video if you do not know the difference between each diode type, but main difference from normal diodes is high switching frequency capability (which we will need if we want to drive motors at high higher frequency) and lower power dissipation due to lower voltage barrier.

Each of the motors have built-in coils, which induced electric field spins the motor. However the coils store energy, which opposes the current flow. When the current is switched off using the transistors, the opposing current needs a path to flow, otherwise huge voltage spikes will occur due to these high currents. You can read some more here. Normally a simple and for high frequency applications a Schottky diode is placed to provide this path and all of the quadcopter implementations I saw do specifically that. However there seem to exist better implementations in a form of the zener snubber, which would lower down the currents even quicker than a simple snubber diode configuration. You can read about it here, but for now this needs to be experimented on first to see if it was to give any better performance.

Choosing the right diode is a bit tricky and there are many discussions like this online. It’s best note down these characteristics from the datasheet:

  • Average forward current — in theory, the opposing current in the motor coil will be the same size as the current flowing in the motors (2.75A in our case) when the motor is on and when the motor is switched off that current will try to find a new path to flow — through the diode. Therefore the diode should be able to withstand 2.75A, however the averaged current will be lower as the current will quickly degrade. However this number will increase with increasing driving frequency as the current will have less time to degrade, therefore it’s best when the diode average forward current is high enough to support full motor needs. You can usually always choose such a diode, which average current will be the same as of the motor, which will prevent from any kinds of risks just to be on a safe side.
  • Maximum repetitive peak reverse voltage — when the opposing current flows it will create a spike in voltage as the resistance of the motor is very small. This peak will be several times higher than the voltage used to drive the motor. In our case it’s not a huge problem as most of the diodes can handle the rating easily.

I would recommend using SS family Schottky diodes SS12-SS16 (riskier side), SS22-SS210 (adequate) or SS32-SS3200 (safe side), SS52-SS5200 (an overkill safe). Note that these more or less follow the format of naming SSXY, where number X refers to the maximum average forward current, and number Y multiplied by 10 is the maximum DC blocking voltage. Though if there are more than 2 numbers this no longer applies.. From these SS14, SS210, SS34, SS54 were available at JLCPCB, thus I just used SS34 as it was on the safe side without change in packaging size or price. There are some others available e.g.1N5819 (riskier side), 1N5820-1N5822 (safe side) which are available at both SMD and through-hole packaging.

Charger

You might already have a good chargers, however in case you don’t you can always get something like this. It uses JST type connectors, thus you will have to get the connectors mentioned before. Alternatively you could get a TP4056 chip based module and solder the connectors yourself. They even come with a USB-C connector nowadays! This might also come in handy in later projects as the chip can become part of the whole PCB in that case. Note that other popular chips are TP4054 and TP4057.

I really wanted to design an on-board charger using TP4057, so that the battery could be changed through the Arduino USB, however sadly Nano design is not very friendly with that.. As I mentioned before though Particle Xenon, Feather nRF52840 Express and ESP series modules already include battery chargers, thus they could be a better choice for this. The first two additionally include battery level measurement circuit which saves a bit of space too.

Step 3: Optional Components

Note that you do not have to solder the following components for the quadcopter to function properly. These can be added though if you wanted to add some extra functionality such as being able to turn the quadcopter off using a slider switch or adding some Neopixel LEDs. The circuit schematic and the PCB was designed in such a way what would not prevent the quadcopter from functioning if these components were not installed, thus you can always leave the components unsoldered.

Neopixels (Optional Soldering)

I thought it would be cool to fly this quadcopter during the night from time to time (or just make it look cooler), thus I also added a couple of Neopixels. These are tiny RGB (Red/Green/Blue) LED pixels with integrated PWM controller (thus can adjust the brightness) inside of them. The beauty is that they only need one or two pins connected to Arduino, depending on the used chip type, to control pretty much any shade and brightness of any number of pixels connected in series. The other advantage is after setting the desired combination of colours Arduino does not need to interact with them any longer, thus processing power can be used for something e.g. controlling the quadcopter. I thought a nice way would be to have 4 Neopixels in total — two at the bottom and two at the top, one on each direction. In the dark this would allow to always know where the quadcopter is facing, which would ease the control.

Many variants are available and rather largish table with their specifications can be found here and a video about which ones are best is here. For this project I would recommend WS2812B (RGB) or SK6812 (RGB + White) and size of 5050 (5cm x 5cm) LEDs. Size 3535 (3.5cm x 3.5cm) is also available, but is more difficult to solder (thus more easy to damage them while soldering) and is more difficult to find when buying. Note though that there are two types of this size, one with pins on the outside (Mini-HS) and one with the pins on the bottom (Mini). I do not recommend the latter if soldering by hand. The LEDs require one pin from Arduino to control all of them. From the datasheet it would need one external 100nF decoupling cap for each of the Neopixels. Remember from the Capacitors section that these are used to remove the power supply ripple. In this case I believe they are here due to pixels using a rather significant amount of current themselves — each pixel can draw up to 60mA of current when Red, Green and Blue LEDs are turned on at maximum brightness. In addition to that, from the suggested guidelines we also need to place a resistor of value 300 to 500 Ohm in between Arduino and the input of the first neopixel, it has to be placed close to the Neopixel. Finally, a large decoupling cap is placed next to the power supply, but we already included one and discussed before.

On Aliexpress these neopixels can be purchased for example from here or here or many other places.

Power Software Control (nRF52840 Only)

One problem with the pixels mentioned above is rather large quiescent (turned off) current of 1mA. This is fine without power switch, however otherwise when the power is off, we need a way of turning these off. This can be done through adding another P-MOSFET, which by default would be off but could be turned on using code through one of Arduino pins. This is easily achieved using pull-up configuration where gate is connected to source through lets say 10k Ohm resistor and is also connected to the Arduino through let’s say 100 Ohms resistor (reduce surge-in currents). We could either use another P-MOSFET (one is used as reverse voltage protection) or use a chip with dual one P-MOSFETs such as APM4953. I will still use two chips instead as then there are more option to choose from. On top of that I will basically create two separate power sources, one powering the motors and the nRF52840 dev board and another programmable powering the rest of the sensors and the LEDs.

Altitude Sensor (Optional Soldering)

When only using IMU to control the quadcopter two tricky problems appear:

  • Being able to hover at a constant altitude. Usually the control of the Z axis (vertical) is done by increasing or decreasing the desired speed of all the motors, thus effectively adding offset. However due to the drained batteries throughout the flight even though the desired speed might not change, the voltage on the battery will drop, which will drop the speed.
  • Automatic taking off and landing without the user interaction. This is useful both controlling the quadcopter as usual and when performing emergency landing in case of dying batteries. After the quadcopter reaches the land this can also be used to turn the motors completely off.

Both of these problems can be easily sorted using a so called altitude sensor. This, depending on the quadcopter size and type, will be of different type:

  • Barometer — pressure changes with changing altitude and through certain formulas the change in altitude can be easily calculated. However barometer are best used for drones which are used outside due to not being super accurate. On top of that pressure changes in time (weather), but this change is rather gradual, thus doesn’t impose much issues unless long flights are used.
  • Ultrasound sensor — these are by far the most popular. in Arduino community, thus probably everyone already knows them very well. They utilise ultrasound waves together with TOF (Time-of-Flight) algorithm to effectively measure how long did the sound travel from the sensor to the object and after being reflected came back. I do not like these as they’re bulky, suffer a lot from noise and thus have a lot of false positives, cannot measure longer distances than around 1m accurately and on top of that, the measurement accuracy is dependent on humidity in the air.
  • Laser sensor — I believe this is by far the best sensor to use for indoor quadcopter. It is also based on TOF algorithm, however instead of sound it uses light, which speed in the air is rather constant. A very cheap sensor that I already had is VL53L0X, which modules on Aliexpress can be bought for under £1 and they are also available on Adafruit. They’re small, light, measure the distance with great accuracy, do not suffer from the side reflexions and can measure range for up to 1m. It also states that 2m range can be measured when LONG_RANGE mode is enabled, but it works best in the dark. One disadvantage is that they cannot tell the difference between 0 and 5cm, thus when this distance was reached we could program to land the quadcopter down. Another similar sensor is VL6180X, but it’s used more for short distances of 0 — 20cm and it also supports gesture detection. This sensor would be more useful for landing/lifting operation. If we combined both would be amazing but even having one of them would allow us. to add some nice functionality.

Of course I chose the latter variant. Both chips use I2C communication and thus we we do not need to use more pins than already are being used as MPU6050 also uses I2C. I used the VL53L0X as I already had one. Just one thing to note, we will need a decoupling capacitor to keep the voltage more stable next to the sensor.

Power Switch (Not added to schematic by default)

Sometimes it is nice to have a way of turning the chip through some sort of a slider switch or a button. The first is easier to implement as usually it doesn’t even require any extra components. Note though that these switches do not have a very large contact rating current. For example switch MSS3-Q-T/R only supports up to 25mA, while our circuit might consume more even without turning on the motors!

To go around this problem we could design a very similar circuit as the one which this product is based on here. Schematic is added as an image there. The only difference is that we wouldn’t need the extra part of controlling the turn on using an external BJT, thus that part can be removed. I redesigned the circuit slightly and added it to a separate project if someone wanted this functionality replace the existing circuit.

Better Noise Filtering (Not added to schematic by default)

I thought of a couple of different ideas on how voltage ripple current could be filtered in case I experienced a lot of noise even with the added caps:

LC Filter

an idea of also adding an LC filter as shown in the 3rd page of the Crazyflie 2.1 schematics (Note down the sentence Filter the power supply 73kHz.) as this should remove the power supply ripple even more, however, I’ve seen videos where it disproves this and some low ESR caps seemed to work better than this, thus for now I left it on a separate project.

«Capacitance Multiplier»

This circuit is actually an active low-pass filter, however it’s being implemented in a very neat way. The circuit behaviour is very nicely explained in this video. It is a way of «increasing» the capacitance of the existing cap by hundreds of times by adding a single resistor and a BJT, Darlington Pair or a N-MOSFET. Of course the capacitance isn’t increasing, we would simply be decreasing the current flowing into the capacitor. I haven’t seen anyone using this circuit in quadcopter design, thus I don’t know how well it would behave but I think it’s worth a thought when needing to provide a very stable supply voltage for powering the IMU without adding any huge caps. On top of that, the resistor could be replaced by an inductor (look above at LC filter) and thus this might be a very neat circuit indeed!

Step 4: Weight and Price Calculations

Price

Probably many of you would like to know the price of the thingy. Well, lets just calculate that using some rough calculations as the price will depend on the supplier:
Expensive motors:

£4 (BLE-Nano) + £3 (MPU6050) + £20 (Motors) + £3 (Motor Battery) + £2 (Propellers) + £2 (MOSFETs) + £2 (The rest of electronics + plastic) + £1 (Connectors) + £3 (Charger) = £40

Cheap Hubsan X4 Motors:

£40 — £15 = £25

I would say this is a rather good price as the competing products cost several times more!

Expensive motors

For our quadcopter to fly nicely there is a rule of thumb that 50 % of the max thrust of motors should be equal to the weight of the quadcopter itself. Thus meaning that the quadcopter will be in the constant height when giving 50% of its full power. The motors that I bought have 40g per motor of thrust. In total that adds up to 160g. 50% of that is 80g. Now lets add up all of the electronics + the frame:

15g (frame) + 8g (PCB) + 20g (motors) + 12g (battery) + 5g (microcontroller) + 2g (MPU) + 5g (extra) = 67g

We managed to easily fit within the 80g boundaries, thus the quadcopter should be able to fly happily.

Cheap motors

Provided thrust from motors is 34g per motor, thus 136g in total. 50% of that is 68g. Total component weight will be more or less the same, maybe can add a smaller battery and that should still be able to fit within the 50% thrust boundary. It might not fly as good as with faster motors, but oh well, you are using at least 4 times cheaper motors!

Step 5: Wiring the System Together

When designing the PCB care must be taken as this will directly affect the performance of the circuit. Each module and chip has to be connected to the correct input of nano.

Motors controlling PWM

Motor controlling MOSFETs will be controlled using PWM signal. There are available 6 pins with hardware built-in PWM on nano pins 3, 5, 6, 9, 10, 11. We will only need 4 pins for the project, however in fact — for easiest development there are only 4 «correct» pins to go for. You see, PWM uses dedicated Timers to set the PWM frequency and nano has 3 such Timers, which use slightly different default (however possible to modify) frequencies. I strongly recommend taking a look at Timer PWM Cheatsheet as my next presumptions will be based on it. Right so Timer 0 (Default 976Hz) is used for pins 5 and 6, Timer 1 (Default 490Hz) for pins 9 and 10 and Timer 2 (Default 490Hz) for pins 3 and 11. To get best performance PWM frequencies for all motors have to be the same as the thrust is frequency dependent as can be seen on this video. Because Timer 0 is also used for functions delay and millis(), we wouldn’t want to change its frequency as it would affect the two functions. We would have to adapt the code, possibly even change the used libraries, which rely on these two functions. Thus this gives us two options:

  1. Using pins 3, 5, 6 and 11, keeping the Timer 0 default frequency of 976Hz but then upscaling Timer 2 to provide us with frequency of 980Hz.
  2. Using pins 3, 9, 10 and 11 and either keeping the default frequency of 490Hz or upscaling both Timer 1 and 2 to 3921Hz.

I don’t know what’s the best choice here, and from some of the sources it seems that the actual value isn’t really that important, however higher frequency will give smoother response and less noise as discussed in the forums. Therefore I will choose the option two and will also upscale the frequency to 3921Hz. Another good forum which discusses how timers affect and how can they be modified to produce different PWM frequency.

Note though that it is also possible to use software based PWM also known as Bit Banging (can read more of this here), however it’s more complicated managing the code as care must be taken not to affect timings — I would strongly discourage from this if possible. However also note that if you want to use RF-Nano chip, from the schematics we can see that pins 9, 10, 11, 12 and 13 are already utilised for talking to nRF24L01 chip, thus the only possibility of using it in this project is by either using an external PWM chip or using Bit Banging.

IMU

The used IMU MPU6050 communicates using I2C and to keep the libraries happy I decided to stick with the default pins A4 (SDA) and A5 (SCL). I will connect the interrupt pin in case I will need it in the future. Nano supports interrupts on pins 2 and 3 only as can be seen here. Therefore I will use pin 2 for it as pin 3 is PWM and it could be used for something else e.g. flashing an LED! I found another project which uses identical configurations here.

Powering Arduino

From the BLE-Nano Schematics we can see that the best place to connect the batteries is straight into the 5V pin. We cannot connect it to Vin as it’s expecting voltages larger than 5V as otherwise the voltage drop due to the voltage regulator would be horrible and we also cannot connect it to 3.3V, because Arduino itself is being powered from the 5V line rather than the 3.3V line, thus then Arduino wouldn’t get powered at all.

Even though the chip powering Arduino Nano (ATmega328) can work off voltages in the range 1.8 — 5.5V, there are certain protections built-in to prevent it from running at too low voltages. The lower acceptable voltage before the chip stops working is called brownout voltage. On Arduino this is set to 2.7V. In our project the voltages might drop for short periods of times (milliseconds) close to this point, which might cause the Nano to restart. To prevent this from happening I might need to set the brownout voltage to be 1.8V and this can be done as explained in this comment.

Battery Level Detector

As previously said we will build a potential divider to measure the battery voltage. The input from the potential divider will go into analog pin A0 and in the software we will set INTERNAL voltage reference.

Neopixels (Optional)

The input to the first Neopixel will connect to Arduino pin number 5, however it could as well be connected to any other unused pin.

Step 6: Circuit Schematic

I am adding here the legacy «schematics» for the old setup I made years back, however if you compare them to the new circuitry you will see where the errors were made (whoops). My latest Nano Quadcopter design is available at EasyEDA so that you could either use it as it is or change the design and/or the PCB in any way you like. I also added explanation to each modules for easy understanding. Note that if you do not understand something you can always reference the Electronics Components or Wiring the System Together steps as I made sure to provide enough information to explain each part of the circuitry.

On top of Nano Quadcopter I also added the schematics for nRF52840 Quadcopter, which will work with dev boards Particle Xenon or Adafruit Feather nRF52840 Express. It was easier to design for these boards as it already includes a lot of modules such as enable pin for adding power switch, battery level detector and a battery charging circuitry with a battery connector of course. On top of that the modules are faster, almost all of the pins support PWM and can be programmed using Circuitpython or Micropython!

Step 7: PCB and Soldering

I recommend ordering the PCB from JLCPCB, which can be done straight off the EasyEDA. The price is only $2 for 10 PCBs, which is really insignificant. Right now I live in Spain and the delivery here costs around $10, thus not a bad deal, even though I will probably only need one PCB… On top of that you could also select an option for the SMD components to be pre-soldered for you for a little bit of extra cost. I selected such components choices which were available at the JLCPCB Assembled Basic SMT Type library, to keep this as an option. The only SMD part which was from the extended library was the LED WS2812B, however not having one will not stop the quadcopter from flying! You can also order them cheaply from the Aliexpress.

Component Size

The PCB that I designed now will use SMD components of size 806. These settings are good enough to be able to solder the PCB by hand. However you’re welcome to redesign the PCB to your likings. I might even provide a PCB for through-hole components, however fitting everything becomes a lot more complicated.

Track Design

Because very large currents will be used to run motors, the tracks for running the motors have to be designed with care:

  • None of the power wires should have vias, this is in order to reduce the wire resistance and thus voltage drop over the wire.
  • The thickness of the wire has to be around 50 mil, however it will depend on which copper layer thickness you choose. You can simply use online track width calculator to decide this.

It is a lot easier to solder all the components on an already prepared PCB. Sadly, getting an access to a machine to make one is not always possible. We had one at the University, thus I designed a PCB using Target 3001! Software. To open the *.T3001 file you will have to download Target 3001 software, which is sadly, only Windows compatible. I might export the project to Eagle later. Adding Target3001, .xps, .tif and .src (export to Eagle) for those who intend to make a PCB at home.

Ground Separation

Note that it might be a good idea to separate the ground used by the motors and the other sensors as the noise caused by the motors would then not affect the sensors as discussed here. This however isn’t very easy to do using the easyEDA PCB editor as I tried and got clearance errors. Thus for now I kept this just as an idea in my head for the future if the quadcopter fails to fly…

The printed and soldered result looks as in the provided image. I added red circles showing the soldered transistors, yellow circles showing the JST connectors for the motors, green circle marking the battery connectors, supplying power to the motor ONLY, and blue circle marking the battery connectors, supplying the power to the rest of the electronics (Arduino, MPU6050, etc.). As you can see, there is some fixes made next to both of the power connectors. You don’t need to do that as the PCB was updated after making the first working model. Basically, the problem was that at first the PCB only had a single power supply. During the testing it appeared that the Bluetooth module kept constantly disconnecting from the phone as the battery voltage was dropping to low levels (< 3V). Not only that but Arduino also had issues with that, which were fixed by lowering brownout voltage. You can do that easily yourself as it only required modifying a single file in the Arduino IDE, however it is more of a hack as the higher the frequency, the higher voltage is needed. In the end, something else might break in the future or you might loose all available power, etc. Anyway, implementing two-battery system worked nicely, especially that the battery, powering electronics weight only around 3g.

When soldering on the motor connectors, make sure that they are soldered the correct way! On each side one of the connector is facing one way and another another way. You have to ensure that pin 1 is always connected the same side. I think it’s best to first place all of the connectors, then recheck them 3 times and only then solder.

Note that I market the battery connector with a plus to make sure you do not connect it the wrong way. I might add a battery protection actually… Need to take a look into it!

Future Considerations

In the future I might get rid off the 3D printed parts completely and will store all of the components on he PCB itself. This will lower the weight dramatically, however it might increase turbulence and vibrations, thus care will have to be taken to avoid these problems by lets say setting the PCB thickness to the largest available. Not only that but will need to think of a way to attach the motors so that they stay securely on the PCB.

Step 8: Software

Long time ago I wrote a library and an example program using mbed for a quadcopter which you can find in here. At the time though I didn’t fully understand how PID worked when applied on Quadcopter theory. To develop the Software now I took a look at existing projects such as

Setup

Because I do not hate myself, I decided to program the Quadcopter using Visual Studio Code editor with the installed PlatformIO plugin. To install the setup I simply followed this guide.

Reading Battery Voltage

To perform analog measurement by default Arduino uses its power supply as a voltage reference. If we did not change this setup when reading the battery voltage it would always be the same as our power supply will get lower with the discharging battery. To solve this we need to use interval voltage reference. As discussed before on Atmega328 this is equal to ±1.1V. The code for reading actual battery value and printing it into Serial port would become:

// Compensation factor, which is inverse of VBAT = (150k / (150k + 150k))
#define VBAT_DIVIDER_COMP ((33.0 + 100.0) / 33.0) 
// Interval voltage reference of 1.1V in mV
#define BATTERY_VOLTAGE_REFERENCE_VALUE 1100 
// 10-bit resolution gives 1023 steps
#define RESOLUTION_STEPS 1023
// Combine together from a formula
#define REAL_BATTERY_MV_PER_LSB (VBAT_DIVIDER_COMP * BATTERY_VOLTAGE_REFERENCE_VALUE / RESOLUTION_STEPS)

#define BATTERY_PIN A0

void setup () {
    // Set internal 1.1V voltage reference
    analogReference(INTERNAL); 
    Serial.begin(115200);
}
void loop () {
    Serial.println(analogRead(BATTERY_PIN) * REAL_BATTERY_MV_PER_LSB);
}

MPU6050

MPU6050 library is available by Jeff Rowberg 2012. The provided example code MPU6050_DMP6 is used as the main code for the project.

Stabilising Motors

In the control systems a PID controller is a very popular way to stabilise the system. In here we will want to stabilise the pitch and roll of MPU6050. I used library PID_v1 for this purpose. In the code given below I will setup both motors and PID controller. I will then add a function to stabilise the motors depending on the required speed.

#define FL_MOTOR 3
#define FR_MOTOR 9
#define BR_MOTOR 10
#define BL_MOTOR 11
//---------------------------------PID------------------------------------
//Define Variables we'll be connecting to
double rollSetpoint, rollInput, rollOutput;
double pitchSetpoint, pitchInput, pitchOutput; 

//Define the aggressive and conservative Tuning Parameters<br>double consKp = 1, consKi = 0.05, consKd = 0.25;
PID pitchPID(&rollInput, &rollOutput, &rollSetpoint, consKp, consKi, consKd, DIRECT);
PID rollPID(&pitchInput, &pitchOutput, &pitchSetpoint, consKp, consKi, consKd, DIRECT);

void setup() {
//------------------------------PID----------------------------------
  pitchInput = 0.0;
  rollInput = 0.0;  
  pitchSetpoint = 0.0;
  rollSetpoint = 0.0;
  //turn the PID on
  pitchPID.SetMode(AUTOMATIC);
  rollPID.SetMode(AUTOMATIC);
  pitchPID.SetOutputLimits(-20, 20);
  rollPID.SetOutputLimits(-20, 20);
  //-------------------------------------------------------------------
  for (int i = 0; i < 4; i++) {
    targetSpeed[i] = 0;
  } 

  pinMode(FL_MOTOR, OUTPUT);
  pinMode(FR_MOTOR, OUTPUT);
  pinMode(BR_MOTOR, OUTPUT);
  pinMode(BL_MOTOR, OUTPUT);

void loop() {
  pitchPID.Compute();
  rollPID.Compute();
  int actSpeed[4];
  stabilise (targetSpeed, actSpeed, rollOutput, pitchOutput);
  //    targetSpeed = actSpeed; // should this be here or not
}
void stabilise (int* currSpeed, int* actSpeed, float rollDiff, float pitchDiff) {
  //actual Speed is calculated as follows +- half rollDiff +- half pitchDiff
  actSpeed[0] = (int) currSpeed[0] + (rollDiff / 2) - (pitchDiff / 2);
  actSpeed[1] = (int) currSpeed[1] + (rollDiff / 2) + (pitchDiff / 2);
  actSpeed[2] = (int) currSpeed[2] - (rollDiff / 2) + (pitchDiff / 2);
  actSpeed[3] = (int) currSpeed[3] - (rollDiff / 2) - (pitchDiff / 2);
  for (int i = 0; i < 4; i ++) {
    if (actSpeed[i] < 0) actSpeed[i] = 0;  
  }
}
void runIndividual (int* actSpeed) {
  analogWrite(FL_MOTOR, actSpeed[0]);
  analogWrite(FR_MOTOR, actSpeed[1]);
  analogWrite(BR_MOTOR, actSpeed[2]);
  analogWrite(BL_MOTOR, actSpeed[3]);
}

BLE Connectivity

BLE (Bluetooth Low Energy) is a completely different communication protocol from the old Bluetooth 2.0. Instead of drawing a lot of power to maintain the connectivity to a host device it instead sends bursts of pulses. Each burst might reach levels of 20-40mA, however they will be very short and will be send only a couple of times per second. On average the energy consumption gets close to sub-mA level!

Communication from the quadcopter to the phone will be done through the BLE-Nano built-in BLE module. The nano connects to the BLE chip using the built in Serial on pins TX and RX. Of course this slightly makes it more difficult if you want to talk to the PC instead, however I will rarely need a connection to the PC anyway. An example on how to receive an integer through BLE UART service and echo it back is given below:

void setup() {
    mySerial.begin(115200);
}
void loop () {
    if (mySerial.available()) {
        int reading = mySerial.parseInt();

        //flushing anything that wasn't read
        while (mySerial.available()) {
            mySerial.read();
        }

        // Echo the integer back
        Serial.println(reading);
    }
}

Adding Bits Together

As for the whole code, I am always working on it, so I decided not to add it ALL here. You can find the latest version of code in GitHub. I will notify in this Instructable when the code is finished. At the moment I need to setup correct PID constants etc…

Neopixels (Optional)

A couple of libraries are available:

  • Adafruit
  • WS2812B
  • FastLED — it was designed to control different types of RGB LED strip, thus if in the future different one was used this library would allow changing everything very easily. The downside is increased memory use.

Здравствуйте, хаброжители!
В этой серии статей мы с вами приоткроем крышку квадрокоптера чуть больше, чем этого требует хобби, а также напишем, настроим и запустим в воздух собственную программу для полетного контроллера, которым будет являться обычная плата Arduino Mega 2560.

У нас впереди:

  1. Базовые понятия (для начинающих коптероводов).
  2. PID-регуляторы с интерактивной web-демонстрацией работы на виртуальном квадрокоптере.
  3. Собственно программа для Arduino и настроечная программа на Qt.
  4. Опасные тесты квадрокоптера на веревке. Первые полёты.
  5. Крушение и потеря в поле. Автоматический поиск с воздуха средствами Qt и OpenCV.
  6. Окончательные успешные тесты. Подведение итогов. Куда дальше?

Материал объемный, но постараюсь уложиться в 2-3 статьи.
Сегодня нас ожидает: спойлер с видео, как наш квадрокоптер полетел; базовые понятия; PID-регуляторы и практика подбора их коэффициентов.

Зачем все это?

Академический интерес, который, кстати, преследует не только меня (1, 2, 3). Ну и, конечно же, для души. Я получил огромное удовольствие во время работы и ощутил настоящее непередаваемое счастье, когда «ЭТО» полетело с моей программой :-)

Для кого?

Данный материал может быть интересен в том числе и людям, которые далеки, или пока только собираются заняться мультироторными системами. Сейчас поговорим про назначение основных узлов квадрокоптера, про то, как они взаимодействуют между собой, про основные понятия и про принципы полёта. Конечно, все знания, которые нам потребуются, можно найти в сети, но нельзя же заставлять выискивать их на просторах необъятного интернета.

Без ущерба для понимания в базовых понятиях смело пропускайте все, что вам известно, до следующего незнакомого термина, выделенного жирным, или до непонятной иллюстрации.

НЕТ №1!

Не беритесь писать собственную программу для полетного контроллера, пока не попробуете готовые решения, которых сейчас достаточно много (Ardupilot, MegapirateNG, MiltiWii, AeroQuad и т.п.). Во-первых, это опасно! Чтобы управлять квадрокоптером без GPS и барометра нужна практика, а тем более, когда он глючит, переворачивается, летит не совсем туда, куда надо — а этого почти не избежать во время первых тестов. Во-вторых, вам будет во много раз легче программировать понимая, что нужно программировать и как оно должно работать в итоге. Поверьте: математика полета — лишь малая часть кода программы.

НЕТ №2!

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

Базовые понятия

Квадрокоптеры бывают разные, но всех их объединяют четыре несущих винта:

Не смотря на кажущуюся симметрию, пилоту очень важно различать, где у квадрокоптера перед (показан стрелкой). Здесь, как у радиоуправляемых моделей автомобилей: при команде «вперед» квадрокоптер летит не туда, куда смотрит пилот, а туда, куда направлен воображаемый нос квадрокоптера. Это таит в себе опасность: новичкам бывает трудно вернуть к себе подхваченный ветром аппарат, развернутый как-нибудь боком (мы, конечно, не говорим про полеты по камере от первого лица и про «умные» режимы полета с использованием компаса и GPS.) Решению этой проблемы частично могут помочь передние винты или лучи другого цвета, какой-нибудь шарик спереди или разноцветные светодиоды. Но все это оказывается бесполезным, когда пепелац стремительно превращается в точку над горизонтом.

Мы будем летать на раме квадрокоптера формы «X», потому что она мне больше нравится внешне. У каждой конструкции свои плюсы и свое предназначение. Кроме квадрокоптеров есть и другие мультикоптеры. Даже если не считать экзотические варианты, все равно их видов — целая куча!

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

Углы тангажа, крена и рыскания (pitch, roll, yaw) — углы, которыми принято определять и задавать ориентацию квадрокоптера в пространстве.

Иногда слово «угол» опускают и просто говорят: тангаж, крен, рыскание. Но согласно Википедии это не совсем точно. Полет квадрокоптера в необходимом направлении достигается изменением этих трех углов. Например, чтобы полететь вперед квадрокоптер должен наклониться за счет того, что задние моторы закрутятся чуть сильнее передних:

Газ квадрокоптера — среднее арифметическое между скоростями вращения всех моторов. Чем больше газ, тем больше суммарная тяга моторов, тем сильнее они тащат квадрокоптер вверх (НЕ ВПЕРЕД!!! «Тапок в пол» здесь означает наискорейший подъем). Обычно измеряется в процентах: 0% — моторы остановлены, 100% — вращаются с максимальной скоростью. Газ висения — минимальный уровень газа, который необходим, чтобы квадрокоптер не терял высоту.

Газ, тангаж, крен, рыскание — если вы можете управлять этими четырьмя параметрами, значит вы можете управлять квадрокоптером. Их еще иногда называют каналами управления. Если вы приобрели двухканальный пульт, с квадрокоптером вам не совладать. Трехканальный скорее подойдет для маленьких вертолетов: без управления креном летать можно, но на квадрокоптере — не удобно. Если вы хотите менять режимы полета, придется раскошелиться на пятиканальный пульт. Хотите управлять наклоном и поворотом камеры на борту — еще плюс два канала, хотя профессионалы используют для этого отдельный пульт.

Режимов полета существует много. Используется и GPS, и барометр, и дальномер. Но мы хотим реализовать базовый — режим стабилизации (stab, stabilize, летать в «стабе»), в котором квадрокоптер держит те углы, которые ему задаются с пульта не зависимо от внешних факторов. В этом режиме при отсутствии ветра квадрокоптер может висеть почти на месте. Ветер же придется компенсировать пилоту.

Направление вращения винтов выбирается не случайно. Если бы все моторы вращались в одну сторону, квадрокоптер вращался бы в противоположную из-за создаваемых моментов. Поэтому одна пара противостоящих моторов всегда вращается в одну сторону, а другая пара — в другую. Эффект возникновения моментов вращения используется, чтобы изменять угол рыскания: одна пара моторов начинает вращаться чуть быстрее другой, и вот уже квадрокоптер медленно поворачивается к нам лицом (ужас какой):

  • LFW — left front clockwise rotation (левый передний, вращение по часовой стрелке)
  • RFC — right front counter clockwise rotation (правый передний, вращение против часовой стрелке)
  • LBC — left back counter clockwise rotation (левый задний, вращение против часовой стрелке)
  • RBW — right back clockwise rotation (правый задний, вращение по часовой стрелке)

Скоростью вращения моторов управляет полетный контроллер (контроллер, мозги). Обычно это небольшая плата или коробочка с множеством входов и выходов. Существует огромное количество различных контроллеров с разным набором возможностей, разными прошивками, разными задачами. Вот лишь некоторые:

Обобщенной задачей полетного контроллера является несколько десятков раз в секунду выполнять цикл управления в который входит: считывание показаний датчиков, считывание каналов управления, обработка информации и выдача управляющих сигналов моторам, чтобы выполнять команды пилота. Именно это мы и собираемся запрограммировать.

Различных видов датчиков, которые можно задействовать, очень много. Мы будем использовать ставшие уже почти обязательными во всех квадрокоптерах трехосевой гироскоп и трехосевой акселерометр. Акселлерометр измеряет ускорение, гироскоп измеряет угловую скорость. Благодаря им полетный контроллер узнает текущие углы тангажа, крена и рыскания. Эти датчики бывают встроенными в полетный контроллер, а бывают внешними. Процесс вычисления трех углов по показаниям датчиков — тема для отдельной статьи. Но нам этого здесь знать не надо: за нас все сделает MPU-6050. Это небольшая плата, проводящая необходимые вычисления и фильтрации у себя внутри и выдающая по протоколу i2c уже почти готовые углы. Нам останется их считать, обработать с остальными данными и выдать управляющие сигналы моторам.

Моторы на мультикоптерах потребляют большие токи, поэтому полетный контроллер управляет ими не напрямую, а через специальные аппаратные драйвера, называемые регуляторами скорости (ESC, ре́гуль, е́ска). Эти регуляторы питаются от основного бортового аккумулятора, управляющий сигнал получают от контроллера, а на выходе у них стоит по три провода (A, B, C), которые непосредственно идут к моторам (каждому мотору — свой регуль!)

«Протокол» общения между регулятором и мотором нам не так важен, как «протокол» общения между полетным контроллером и регулятором, ведь нам предстоит из контроллера программно управлять регулятором. Бывают регуляторы, управляемые по i2c, но наиболее распространенные управляются сигналом прямоугольной формы с минимумом 0 вольт и максимумом 3-5 вольт (его называют ШИМ или PWM, а некоторые утверждают, что правильнее — PPM. Подробнее, например, здесь).

«Протокол» — это громко сказано: чтобы дать команду мотору вращаться с максимальной скоростью контроллер должен отправлять импульсы длительностью 2 миллисекунды, перемежающиеся логическим нулем длительностью 10 — 20 миллисекунд. Длительности импульса в 1 миллисекунду соответствует остановка мотора, 1.1 мс — 10% от максимальной скорости, 1.2 мс — 20% и т.п. Практически длительность нуля не играет никакой роли, важна только длительность самого импульса.

При всей кажущейся простоте, здесь кроется засада: полетные контроллеры бывают разные с разными настройками, регуляторы бывают разные, и минимум (1 мс) и максимум (2 мс) — не универсальны. В зависимости от множества факторов диапазон 1-2 мс может на деле оказаться 1.1 — 1.9 мс. Для того, чтобы регулятор и контроллер говорили абсолютно на одном языке существует процедура калибровки регуляторов. В ходе этой процедуры диапазоны регуляторов изменяются и становятся равными диапазону контроллера. Процедура зашита в программу каждого регулятора и включает в себя несколько простых шагов (шаги могут отличаться в зависимости от производителя — читайте инструкции!):

  • Отключить питание регулятора.
  • Снять с мотора пропеллер.
  • Подать на вход регулятора сигнал, соответствующий максимальной скорости вращения.
  • Подать на регулятор питание. Мотор при этом должен сохранять неподвижность без посторонней помощи.
  • Сделать паузу 1-2 секунды, дождаться характерного писка.
  • Подать на вход регулятора сигнал, соответствующий минимальной скорости вращения.
  • Сделать паузу 1-2 секунды, дождаться характерного писка.
  • Отключить питание регулятора.

После этого в регулятор будут занесены соответствующие границы интервала. При попытке взлететь с некалиброванными регуляторами последствия могут оказаться неожиданными: от внезапного рывка квадрокоптера в ближайшее дерево до полной неподвижности моторов при любом значении газа.

PWM с точно таким же принципом использует и бортовой приемник. Это небольшое устройство, получающая сигналы радиоуправления с земли и передающая их в полетный контроллер. Чаще всего в полетном контроллере для каждого канала управления (газ, тангаж, крен и т.п.) имеется свой вход на который поступает PWM. Логика взаимодействия проста: команда, например, «70% газ» непрерывно идет с земли на приемник, где преобразуется в PWM и по отдельному проводу поступает в полетный контроллер. Аналогично с тангажем, креном, рысканием.

Раз между приемником и контроллером свои товарищеские PWM отношения, то их тоже придется калибровать: пульты с приемниками бывают разные со своими диапазонами работы. Контроллер должен уметь подстраиваться. Процедуру калибровки радио, в отличие от калибровки регуляторов нам придется создавать самим как часть полетный программы. Общий план калибровки такой:

  • Снять пропеллеры с моторов на всякий случай.
  • Каким-либо образом перевести контроллер в режим калибровки радио.
  • Контроллер запускает калибровку радио на несколько десятков секунд.
  • За отведенное время двигаем всеми стиками пульта во все стороны до упоров.
  • Контроллер запоминает максимумы и минимумы для всех каналов управления во внутреннюю память на века.

Итак: во время калибровки радио полетный контроллер запоминает диапазоны приемника по всем каналам управления; во время калибровки регуляторов диапазон полетного контроллера заносится во все регуляторы.

Помимо программы для полетного контроллера необходима еще одна программа: интерфейс настройки полетного контроллера. Чаще всего им является программа для PC, которая соединяется с полетным контроллером по USB и позволяет пользователю настраивать и проверять полетную программу, например: запускать калибровку радио, настраивать параметры стабилизации, проверять работу датчиков, задавать маршрут полета на карте, определять поведение мультикоптера при потере сигнала и многое другое. Мы свой интерфейс настройки будем писать на C++ и Qt в виде консольной утилиты. Вот она, если заглянуть в будущее:

Никто не застрахован от случайностей. Даже десятидюймовые пластиковые винты на маленьких моторах могут оставить кровавые синяки на коже, которые будут болеть еще неделю (проверено лично). Элементарно сделать себе новый макияж и прическу, если зацепить стик газа на пульте, пока несешь включенный квадрокоптер. Поэтому полетный контроллер должен обеспечивать хоть какую-то безопасность: механизм armed/disarmed. Состояние квадрокоптера «disarmed» означает, что моторы отключены и даже команда полного газа с пульта не имеет никакого эффекта, хотя питание подано. Состояние «armed» квадрокоптера означает, что команды с пульта выполняются полетным контроллером. В этом состоянии квадрокоптеры взлетают, летают и садятся. Квадрокоптер включается и должен сразу попасть в состояние disarmed на тот случай, если невнимальельный пилот включает его, когда стик газа на пульте находится не в нуле. Чтобы перевести коптер в состояние «armed» пилоту необхоимо сделать какой-то заранее оговоренный жест стиками пульта. Часто этим жестом является удержание левого стика в правом нижнем углу (газ = 0%, рыскание = 100%) втечении пары секунд. После этого полетный контроллер делает хотя бы минимальную самопроверку и при ее успешном прохождении «армится» (к полету готов!) Другим жестом (газ = 0%, рыскание = 0%) квадрокоптер «дизармится«. Еще одна хорошая мера безопасности — автодизарм, если газ был на нуле втечении 2-3 секунд.

О моторах, аккумуляторах, регуляторах, пропеллерах

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

И все же для общего понимания полезно знать основные моменты.

Аккумуляторы

Среди любителей и профессионалов многороторных систем наиболее распространены литий-полимерные аккумуляторы, как основные источники питания бортовой электроники и моторов. Их различают по емкости, напряжению и максимальной токоотдаче. Емкость, как обычно, измеряется в ампер-часах или миллиампер-часах. Напряжение измеряется в количестве «банок» аккумулятора. Одна «банка» — в среднем 3.7 вольт. Полностью заряженая «банка» — 4.2 вольта. Наиболее распространеты аккумуляторы с количеством банок от трех до шести. Максимальная токоотдача измеряется в амперах, а маркируется, например вот так: 25C. C — емкость аккумулятора, 25 — множитель. Если емкость равна 5 амперам, то такой аккумулятор может отдавать 25 * 5 = 125 ампер. Конечно же параметр токоотдачи лучше брать с запасом, но, в основном, чем он больше, тем дороже аккумулятор. Пример маркировки: 25C 3S 4500mah.

Каждая банка является отдельным аккумулятором. Все они спаяны последовательно. Для того чтобы равномерно заряжать все банки предусматривается баллансировочный разъем с доступом к каждой банке отдельно, и использутся специальные зарядные устройства.

Моторы, пропеллеры, регуляторы

Основной параметр бесколлекторного мотора — его kv. Это количество оборотов в минуту на каждый вольт поданного напряжения. Наиболее распространены моторы с kv от 300 до 1100. Kv ближе к 1000 обычно выбирают для малых квадрокоптеров (1-2 килограмма плюс 500 граммов полезной нагрузки) и ставят на них пластиковые пропеллеры до 12 дюймов в диаметре. На больших мультикоптерах (для поднятия хорошей и тяжелой фото-видео техники) или на долголетах (для рекордов по времени полета) обычно стоят моторы с низким kv (300-500) и огромными карбоновыми пропеллерами (15 — 20 дюймов в диаметре). Kv — не единственный важный параметр мотора: часто можно встретить целые таблицы зависимости мощности мотора и тяги от подаваемого напряжения и типа установленного пропеллера. Кроме того, каждый мотор рассчитан на свой диапазон напряжений (количество банок аккумулятора) и на свой максимальный ток. Если производитель пишет 3-4S, не стоит использовать его с 5S аккумуляторами. Это же касается и регуляторов.

Если мотор рассчитан на ток до 30А, то регулятор стоит рассчитывать на ток до 30 + 10А, чтобы не допускать перегревов. Некачественные или неподходящие регуляторы могут вызвать так называемые «срывы синхронизации» и остановку мотора в полете, и вы узнаете еще один мультироторный термин: «поймал планету.» Еще один важный момент — толщина и качество проводов. Неправильно рассчитанное сечение провода или плохой коннектор могут привести к пожару в воздухе.

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

Математика стабилизации, ПИД-регуляторы (PID)

Если вы решили заняться мультикоптерами, то рано или поздно вам придется столкнуться с настройкой ПИД-регулятора, поскольку этот математический аппарат применяется почти во всех задачах стабилизации: стабилизация углов квадрокоптера в воздухе, полет и удержание позиции по GPS, удержание высоты по барометру, бесколлекторные механизмы стабилизации видеокамеры в полете (подвес камеры).

Вы приобретаете двухосевой подвес для камеры, ставите туда, например, GoPro, включаете и вместо стабилизации получаете конвульсии, вибрации и дергания, хотя все датчики откалиброваны и механические проблемы устранены. Причина — неверные параметры ПИД-регуляторов.

Вы собираете мультикоптер, калибруете датчики, регуляторы, радио, все проверяете, пытаетесь взлететь, а он такой унылый в воздухе, что его даже легким ветерком переворачивает. Или наоборот: он такой резкий, что внезапно срывается с места и крутит тройное сальто без разрешения. Причина все та же: параметры ПИД-регуляторов.

Для многих устройств использующих ПИД-регуляторы существуют инструкции по настройке, а то и несколько в добавок к многочисленным видеонструкциям от самих пользователей. Но чтобы легче ориентироваться в этом многообразии полезно понимать, как же внутри устроены эти регуляторы. Кроме того, мы же собираемся писать собственную систему стабилизации квадрокоптера! Предлагаю вместе со мной самим заново «изобрести» и «на пальцах» понять формулу ПИД-регулятора. Для тех, кому больше нравится сухой математический язык, я рекомендую Википедию, английскую статью, т.к. в русской пока не так подробно изложен материал.

Будем рассматривать квадрокоптер в двумерном пространстве, где у него есть только один угол — угол крена, и два мотора: левый и правый.

В полетный контроллер непрерывно поступают команды с земли: «крен 30 градусов», «крен -10 градусов», «крен 0 градусов (держать горизонт)»; его задача — как можно быстрее и точнее их выполнять с помощью моторов с учетом: ветра, неравномерного распределения веса квадрокоптера, неравномерного износа моторов, инерции квадрокоптера и т.п. Таким образом, полетный контроллер должен непрерывно решать задачу, какую скорость вращения подавать на каждый мотор с учетом текущего значения угла крена и требуемого. Непрерывно — это, конечно, громко сказано. Все зависит от вычислительных возможностей конкретного железа. На Adruino вполне можно одну итерацию цикла обработки и управления уместить в 10 миллисекунд. Это значит, что раз в 10 миллисекунд будут считываться показания углов квадрокоптера, и на их основе будут отправляться управляющие сигналы к моторам. Эти 10 миллисекунд называют периодом регулирования. Понятно, что чем он меньше, тем чаще и точнее происходит регулирование.

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


где — реакция квадрокоптера (усилие), которое создает момент вращения за счет того, что левый мотор вращается на быстрее, чем газ, а правый — на столько же медленнее. может принимать и отрицательные значения, тогда правый мотор закрутится быстрее. Если мы научимся вычислять эту величину на каждой итерации цикла обработки, значит мы сможем управлять квадрокоптером. Понятно, что как минимум должно зависеть от текущего угла крена () и желаемого угла крена (), который поступает с пульта управления.

Представим ситуацию: поступает команда «держать горизонт» ( = 0), а квадрокоптер имеет крен влево:

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

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

Здесь P — коэффициент пропорциональности. Чем он больше, тем сильнее будет реакция, тем резче квадрокоптер будет реагировать на отклонение от требуемого угла крена. Эта интуитивно понятная и простая формула описывает работу пропорционального регулятора. Суть элементарна: чем сильнее квадрокоптер отклонился от требуемого положения, тем сильнее надо пытаться его вернуть. К сожалению, эту формулу придется усложнить. Главная причина — перерегулирование.

За несколько десятков миллисекунд (несколько итераций цикла обработки) под воздействием пропорционального регулятора квадрокоптер вернется в требуемое (в данном случае горизонтальное) положение. Все это время ошибка и усилие будут иметь один и тот же знак, хоть и становиться все меньше по модулю. Набрав какую-то скорость поворота (угловую скорость) квадрокоптер просто перевалится на другой бок, ведь никто его не остановит в требуемом положении. Все равно что пружина, которая всегда стремится вернуться в начальное положение, но если ее оттянуть и отпустить — будет колебаться, пока трение не возьмет верх. Конечно, на квадрокоптер тоже будет действовать трение, но практика показывает, что его не достаточно.

По этой причине в пропорциональный регулятор нужно добавить еще одно слагаемое, которое будет тормозить вращение квадрокоптера и препятствовать перерегулированию (переваливанию в противоположную сторону) — своего рода имитация трения в вязкой среде: чем быстрее поворачивается квадрокоптер, тем сильнее надо пытаться его остановить, конечно, в разумных пределах. Скорость вращения (скорость изменения ошибки ) обозначим как , тогда:

где D — настраиваемый коэффициент: чем он больше, тем сильнее останавливающее усилие. Из школьного курса физики всплывают смутные воспоминания, что скорость изменения любой величины — производная этой величины по времени:

.

И вот пропорциональный регулятор превращается в пропорционально-дифференциальный (пропорциональное слагаемое и дифференциальное):

.

Ошибку вычислить легко, ведь на каждой итерации мы знаем и ; P и D — настраиваемые перед запуском параметры. Для вычисления производной (скорости изменения ) необходимо хранить предыдущее значение, знать текущее значение и знать время, которое прошло между измерениями (период регулирования). И вот она — физика шестого класса школы (скорость = расстояние / время):

.

— период регулирования; — значение ошибки с предыдущей итерации цикла регуляции. Кстати, эта формула — простейший способ численного дифференцирования, и он нам здесь вполне подойдет.

Теперь у нас есть пропорционально-дифференциальный регулятор в плоском «бикоптере», но осталась еще одна проблема. Пусть левый край будет весить чуть больше правого, или, что то же самое, левый мотор работает чуть хуже правого. Квадрокоптер чуть наклонен влево и не поворачивается обратно: дифференциальное слагаемое равно нулю, а пропорциональное слагаемое хоть и принимает положительное значение, но его не хватает, чтобы вернуть квадрокоптер в горизонтальное положение, ведь левый край весит чуть больше правого. Как следствие — квадрокоптер будет все время тянуть влево.

Необходим механизм, который бы отслеживал такие отклонения и исправлял их. Характерной особенностью таких ошибок является то, что они прявляют себя со временем. На помощь приходит интегральное слагаемое. Оно хранит сумму всех ошибкок по всем итерациям цикла обработки. Как же это поможет? Если пропорционального слагаемого не достаточно, чтобы исправить маленькую ошибку, но она все равно есть — постепенно, со временем, набирает силы интегральное слагаемое, увеличивая реакцию и квадрокоптер принимает требуемый угол крена.

Тут есть нюанс. Предположим равна 1 градусу, цикл регулирования — 0.1с. Тогда за одну секунду сумма ошибок примет значение 10 градусов. А если цикл обработки — 0.01с, то сумма наберет аж 100 градусов. Чтобы за одно и тоже время интегральное слагаемое набирало одно и тоже значение при разных периодах регулирования, полученную сумму будем умножать на сам период регулирования. Легко посчитать, что в обоих случаях из примера получается сумма в 1 градус. Вот оно — интегральное слагаемое (пока без настраиваемого коэффициента):

.

Эта формула — не что иное, как численный интеграл по времени функции в интервале от нуля до текущего момента. Именно поэтому слагаемое называется интегральным:

,

где T — текущий момент времени.
Пришло время записать окончательную формулу пропорционально-интергрально-дифференциального регулятора:

,

где — один из настраиваемых параметров, которых теперь трое: . Эта формула удобна в применении из программного кода, а вот формула, которая приводится в учебниках:

.

Существует несколько ее вариаций, например, можно ограничить модуль интегрального слагаемого, чтобы он не превысил определенный допустимый порог (мы так и будем делать).

Практика

Ну а теперь пришло время для практики подбора коэффициентов. Читателям предлагается JavaScript-страничка с виртуальным квадрокоптером, который он уже видел на картинках:

подбор параметров PID-регулятора для квадрокоптера

(JSFiddle). При первом запуске сразу видно перерегулирование — колебания вокруг требуемого положения. Когда колебания останавливаются, можно наблюдать эффект, что пропорциональный коэффициент не справляется с ошибкой из-за «несимметричного» квадрокоптера (задается галочкой «Asymmetry»). Для настройки доступны параметры P, I, D. Теперь вы знаете что с ними делать. «Скролом» под квадрокоптером можно управлять требуемым значением крена. «Interval (ms):» — интервал регулирования. Уменьшать его — «читерство», но посмотреть как он влияет на качество стабилизации — очень полезно.

Для любителей «чистой» математики можно предложить

настроить абстрактный ПИД-регулятор

Введенные параметры автоматически не применяются: нужно жмакать «Apply». Пара небольших советов: если вам кажется, что квадрокоптер слишком медленно реагирует на управление — можно увеличить P, но слишком большое значение P может привести к перерегулированию. С перерегулированием поможет справиться параметр D, но слишком большие значения приведут к частым колебаниям, или опять к перерегулированию. Параметр I, обычно, в 10 — 100 раз меньше, чем параметр P т.к. его сила в накоплении во времени, а не в быстром реагировании.

Ручная настройка ПИД-параметров требует практики. Существуют аналитические методы их вычисления, но они требуют хорошей подготовки и точного знания многих параметров конкретной настраиваемой системы. Как среднее между ручным подбором и аналитическим вычислением есть широкий ряд эмпирических методов, предложенных различными исследователями.

В нашем 2D квадрокоптере меняется только один угол — угол крена. В настроящем 3D квадрокоптере потребуется три независимых ПИД-регулятора для каждого из углов, а управление конкретным мотором будет представлять сумму усилий по всем регуляторам.

Заключение первой части

В этой статье мы познакомились с базовыми понятиями: квадрокоптер и принцип полета, тангаж, крен, рыскание, газ, газ висения, режим полета stabilize, полетный контроллер, гироскоп, акселерометр, регулятор скорости, ШИМ, калибровка регуляторов, калибровка радио, бортовой приемник, интерфейс настройки полетного контроллера, состояния armed/disarmed, автодизарм.

После этого мы заново изобрели формулу ПИД-регулятора немного каснувшись численного дифференцирования и интегрирования, и на своей шкуре испытали, как настраивать параметры P, I, D на

виртуальном квадрокоптере

.

Теперь, если вы владеете световым мечем-программированием, вы можете приступать к своей программе стабилизации квадрокоптера, или, еще лучше, присоединиться со свежими идеями к существующими open source проектам. Ну а я

через неделю-другую

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

В заключении этой части я просто обязан упомянуть человека, который помогал мне в выборе комплектующих и настройке самого сложного (первого!) квадрокоптера на прошивке MegapirateNG и терпеливо отвечал на сотни вопросов по этим самым базовым понятиям: SovGVD, спасибо тебе! :-)

В награду тем, кто смог промотать всю эту простыню, выкладываю обещанное маленькое видео, как наш квадрокоптер с нашими «изобретенными» ПИД-регуляторами, на нашей программе для Arduino Mega 2560 летает:

Конечно, ему не хватает GPS, как в коммерческих и массовых продуктах, немного не хватает устойчивости, но зато — НАШ, и мы знаем его вдоль и поперек до последнего множителя при интегральном коэффициенте! И это действительно круто, что сегодня нам доступны такие технологии.

Разве не в прекрасное время мы живем?!

Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.

В какое время мы живем?

Проголосовали 1774 пользователя.

Воздержались 249 пользователей.

Понравилась статья? Поделить с друзьями:
  • Квадрокоптер е58 инструкция на русском
  • Квадрокоптер дискавери mobicaro инструкция на русском языке
  • Квадрокоптер властелин небес ящер вн3466 инструкция по применению
  • Квадрокоптер властелин небес инструкция по эксплуатации на русском
  • Квадрокоптер аирбласт инструкция на русском