Этот учебник является частью: Сервомоторы
Здесь перечислены все видеоролики, связанные с сервомоторами. Ссылки на другие видео находятся ниже этой статьи.
Код Arduino и видео для сервоконтроллера PCA9685 на 16 каналов с разрешением 12 бит V1
В этом руководстве мы рассмотрим, как использовать 16-канальный 12-разрядный контроллер сервоприводов PCA9685 от NXP Semiconductor. Этот модуль позволяет управлять до 16 сервоприводами или точно регулировать яркость группы светодиодов с помощью широтно-импульсной модуляции (ШИМ). К концу этого руководства у вас будет рабочая настройка, которая сможет управлять несколькими сервоприводами как индивидуально, так и одновременно.

Чтобы более подробно разъяснить содержание учебного пособия, я рекомендую вам посмотреть прилагаемое видео (в видео на 00:00) для визуальной демонстрации процесса настройки и кодирования.
Аппаратное обеспечение объяснено
Модуль PCA9685 представляет собой компактную плату, которая может управлять несколькими сервоприводами через коммуникацию I2C. Он имеет 16 каналов, что позволяет подключать до 16 сервоприводов, каждый из которых имеет свой собственный управляющий сигнал. Модуль работает от источника питания 5 В и предназначен для обработки PWM-сигналов, которые необходимы для точного управления положением сервоприводов.
Плата включает в себя специальные выводы для питания (VCC), земли (GND) и связи (SDA и SCL). Вывод SDA используется для передачи данных, в то время как вывод SCL является тактовым сигналом, оба из которых подключаются к аналоговым выводам Arduino A4 и A5 соответственно. Эта схема обеспечивает надежную связь между Arduino и модулем PCA9685.
Технические характеристики
| Производитель | NXP Семикондорторы |
|---|---|
| Номер детали | PCA9685 |
| Логическое/входное напряжение | 3.3 В до 5.5 В |
| Напряжение питания | 2.3 В до 5.5 В |
| Выходной ток (на канал) | 25 мА макс |
| Пиковый ток (на канал) | 100 мА макс |
| Руководство по частоте ШИМ | 24 Гц до 1,6 кГц |
| Входные логические пороги | 0.3 В (низкое) / 0.7 В (высокое) |
| Падение напряжения / RДС(включено)/ насыщение | 0,5 В макс |
| Термальные ограничения | -40 °C до 125 °C |
| Упаковка | HTSSOP-28 |
| Заметки / варианты | 16-канальный PWM контроллер |
- Обеспечьте источник питания 5В с достаточным током (рекомендуется 1А).
- Не подключайте серво напрямую к Arduino, чтобы избежать повреждений.
- Используйте правильные выводы I2C: SDA к A4 и SCL к A5.
- Настройте значения ширины импульса в соответствии с вашими конкретными сервомотором.
- Проверьте проводку на правильную полярность: GND, VCC и сигнал.
- Учтите теплоотвод для высокотоковых приложений.
Инструкции по подключению

Чтобы подключить PCA9685 к вашему Arduino, начните с подключения питания и заземления. Подключите вывод VCC на PCA9685 к выходу 5V на Arduino. Затем подключите вывод GND на PCA9685 к GND на Arduino. Далее подключите вывод SDA на PCA9685 к выводу A4 на Arduino, а вывод SCL к выводу A5.
Для сервоприводов подключите сигнальный провод к соответствующему каналу на PCA9685 (например, CH0 для первого сервопривода), провод питания к отдельному источнику питания (поскольку сервоприводы могут требовать больше тока, чем может предоставить Arduino), а провод заземления к общему заземлению, используемому с PCA9685. Убедитесь, что сигнальный, питающий и заземляющий провода правильно выровнены, чтобы избежать повреждения ваших компонентов.
Примеры кода и пошаговое руководство
В разделе настройки кода мы инициализируем модуль PCA9685 сpwm.begin()и установите частоту ШИМ сpwm.setPWMFreq(60);Это устанавливает частоту связи для сервоприводов.
void setup() {
Serial.begin(9600);
Serial.println("16 channel Servo test!");
pwm.begin();
pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates
}В пределах цикла мы управляем сервоприводами, устанавливая значения ШИМ, соответствующие желаемым углам. ФункцияangleToPulse(int ang)преобразует угол в соответствующую ширину импульса, что важно для точного позиционирования сервопривода.
void loop() {
for( int angle =0; angle<181; angle +=20){
delay(500);
pwm.setPWM(0, 0, angleToPulse(angle) );
}
}Наконец, функцияangleToPulse(int ang)преобразует угол в ширину импульса, используя заданные минимальные и максимальные длины импульсов. Это позволяет вам легко контролировать положение сервопривода в зависимости от угла, который вы хотите достичь.
int angleToPulse(int ang){
int pulse = map(ang,0, 180, SERVOMIN,SERVOMAX);
Serial.print("Angle: ");Serial.print(ang);
Serial.print(" pulse: ");Serial.println(pulse);
return pulse;
}Демонстрация / Что ожидать
После того как все провода подключены правильно и код загружен, вы должны увидеть, как сервопривод перемещается под заданными углами с шагом 20 градусов. Если сервопривод не ведет себя так, как ожидалось, проверьте проводку на предмет правильных соединений и убедитесь, что источник питанияAdequate (в видео на 12:30).
Временные метки видео
- 00:00- Введение в PCA9685
- 02:30- Инструкции по проводке
- 05:00- Обзор кода
- 10:15- Демонстрация управления сервоприводом
- 12:30- Устранение распространенных проблем
Этот учебник является частью: Сервомоторы
- Controlling a Servo with Push Buttons Using Arduino
- Control a Servo Motor with a Push Button: Move Servo and Return SPB-1
- Control a Servo Motor with a Push Button: Move Servo in One Direction SPB-2
- Controlling a Servo Motor with a Push Button: Move Servo While Button Is Pressed (SPB-3)
- Controlling a Servo with a Potentiometer Using Arduino
- Controlling a Servo with Potentiometer and LCD1602 using Arduino
- Управление сервомоторами с помощью инфракрасного пульта на Arduino
- Управление сервомотором Arduino с помощью потенциометра
- Управление положением сервопривода с помощью жестов рук для Arduino
- Controlling Two or More Servos with Potentiometers Using an Arduino
- How to Control a 360° Servo with Three Push-Button Switches
- How to Use Continuous 360° Servo with Arduino
- Build an Arduino Servo Toggle Switch with a Push Button
/*
* Original source: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
* This is the Arduino code for the PCA9685 16-channel servo controller.
* Watch the video for details and demo: http://youtu.be/y8X9X10Tn1k
* get code and wiring diagram from http://robojax.com/RTJ27
* Watch the video for this code:
*
* Related Videos:
V5 video of PCA9685 32 Servo with ESP32 with WiFi: https://youtu.be/bvqfv-FrrLM
V4 video of PCA9685 32 Servo with ESP32 (no WiFi): https://youtu.be/JFdXB8Za5Os
V3 video of PCA9685: how to control 32 servo motors: https://youtu.be/6P21wG7N6t4
V2 Video of PCA9685: 3 different ways to control servo motors: https://youtu.be/bal2STaoQ1M
V1 Video introduction to PCA9685 to control 16 servos: https://youtu.be/y8X9X10Tn1k
* Written by Ahmad Shamshiri for Robojax Video channel: www.Robojax.com
* Date: December 16, 2017, in Ajax, Ontario, Canada
* Permission granted to share this code, given that this
* note is kept with the code.
* Disclaimer: This code is "AS IS" and for educational purposes only.
* This code has been downloaded from https://robojax.com
*
*/
/***************************************************
This is an example for our Adafruit 16-channel PWM & Servo driver.
Servo test - this will drive 16 servos, one after the other.
Pick one up today in the Adafruit shop!
------> http://www.adafruit.com/products/815
These displays use I2C to communicate; 2 pins are required to
interface. For Arduino UNOs, that's SCL -> Analog 5, SDA -> Analog 4.
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution.
****************************************************/
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
// you can also call it with a different address you want
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);
// Depending on your servo make, the pulse width min and max may vary; you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos you
// have!
#define SERVOMIN 125 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX 575 // this is the 'maximum' pulse length count (out of 4096)
// our servo # counter
uint8_t servonum = 0;
void setup() {
Serial.begin(9600);
Serial.println("16 channel Servo test!");
pwm.begin();
pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates
//yield();
}
// the code inside loop() has been updated by Robojax
void loop() {
for( int angle =0; angle<181; angle +=20){
delay(500);
pwm.setPWM(0, 0, angleToPulse(angle) );
}
delay(1000);
}
/*
* angleToPulse(int ang)
* gets angle in degrees and returns the pulse width.
* Also prints the value on the serial monitor.
* Written by Ahmad Shamshiri for Robojax, Robojax.com
*/
int angleToPulse(int ang){
int pulse = map(ang,0, 180, SERVOMIN,SERVOMAX);// map angle of 0 to 180 to Servo min and Servo max
Serial.print("Angle: ");Serial.print(ang);
Serial.print(" pulse: ");Serial.println(pulse);
return pulse;
}
/*
* Original source: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
* This is the Arduino code for the PCA9685 16-channel servo controller.
we have simple code with mapping PWM for simplicity explained in the video at 18:27
* Watch the video for details and demo: http://youtu.be/y8X9X10Tn1k
get this code and wiring from for this video: http://robojax.com/RJT27
* Written by Ahmad Nejrabi for Robojax Video channel: www.Robojax.com
* Date: December 15, 2017, in Ajax, Ontario, Canada
* Permission granted to share this code, given that this
* note is kept with the code.
* Disclaimer: This code is "AS IS" and for educational purposes only.
*
*/
/***************************************************
This is an example for our Adafruit 16-channel PWM & Servo driver.
Servo test - this will drive 16 servos, one after the other.
Pick one up today in the Adafruit shop!
------> http://www.adafruit.com/products/815
These displays use I2C to communicate; 2 pins are required to
interface. For Arduino UNOs, that's SCL -> Analog 5, SDA -> Analog 4.
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
// you can also call it with a different address you want
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);
// Depending on your servo make, the pulse width min and max may vary; you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos you
// have!
#define SERVOMIN 125 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX 575 // this is the 'maximum' pulse length count (out of 4096)
// our servo # counter
uint8_t servonum = 0;
void setup() {
Serial.begin(9600);
Serial.println("16 channel Servo test!");
pwm.begin();
pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates
//yield();
}
// the code inside loop() has been updated by Robojax
void loop() {
pwm.setPWM(0, 0, 125 );
delay(500);
pwm.setPWM(0, 0, 255 );
delay(500);
pwm.setPWM(0, 0, 450 );
delay(500);
pwm.setPWM(0, 0, 575 );
delay(500);
}
Вещи, которые могут вам понадобиться
-
АмазонкаКупите PCA9685 на Amazonamzn.to
-
eBayКупите PCA9685 на eBayebay.us
-
АлиЭкспрессКупите PCA9685 на AliExpresss.click.aliexpress.com
-
БанггудПриобретите PCA9685 на Bangoodbanggood.com
Ресурсы и ссылки
Ресурсов пока нет.
Файлы📁
Библиотеки Arduino (zip)
-
Adafruit-PWM-Сервопривод-Менеджер-Библиотека-мастер
Adafruit-PWM-Servo-Driver-Library-master.zip0.02 MB