Этот учебник является частью: Управление 16 или 32 сервомоторами с помощью PCA9685
Эта подборка обучающих видеороликов поможет вам управлять 32 и более сервомоторами с помощью Arduino UNO, Nano, Mini или ESP32. Все коды прилагаются.
Управление 16 сервомоторами с помощью модуля PCA9685 и скетча Arduino V2 #1: По одному
В этом учебном пособии мы научимся управлять до 16 сервомоторами с помощью модуля PCA9685 и Arduino. PCA9685 — это 16-канальный, 12-разрядный PWM контроллер, который позволяет точно управлять сервомоторами. Следуя этому руководству, вы сможете индивидуально управлять каждым сервомотором и устанавливать их на определенные углы, достигая различных роботизированных движений.
Сначала мы обсудим аппаратные компоненты, которые вам понадобятся для этого проекта, затем перейдем к подробным инструкциям по проводке. После этого мы шаг за шагом рассмотрим код, выделяя ключевые идентификаторы и их роли в управлении серво-моторами. Для более ясного понимания вы можете обратиться к сопроводительному видео (в видео на 00:00).
Аппаратное обеспечение объяснено
Основным компонентом в этом проекте является модуль PCA9685, который отвечает за генерацию PWM-сигналов для управления сервоприводами. Каждый сервопривод подключен к одному из 16 каналов на PCA9685, что позволяет осуществлять независимое управление. Модуль общается с Arduino, используя протокол I2C, который требует всего лишь двух проводов: SDA и SCL.
В дополнение к PCA9685 вам понадобится плата Arduino, 16 сервомоторов и внешний источник питания. Внешний источник питания имеет решающее значение, поскольку сама плата Arduino может не обеспечить достаточный ток для одновременной работы всех сервомоторов. Каждый сервомотор обычно работает на 5В, поэтому убедитесь, что ваш источник питания соответствует этому требованию.
Технические характеристики
| Производитель | NXP Семикондукторы |
|---|---|
| Номер детали | PCA9685 |
| Логическое/ входное и выходное напряжение | 2.3 - 5.5 В |
| Напряжение питания | 5 В |
| Ток на выходе (на канал) | 25 мА |
| Руководство по частоте ШИМ | 60 Гц |
| Входные логические пороги | 0.3VCC (низкий) / 0.7VCC (высокий) |
| Напряжение / RDS(включено)/ насыщение | - |
| Термические ограничения | - |
| Упаковка | TSSOP-28 / VQFN-28 |
| Заметки / варианты | - |
- Подключите внешний блок питания 5V для сервоприводов.
- Используйте I2C для связи, подключая SDA к A4 и SCL к A5 на Arduino.
- Убедитесь, что все земли общие между Arduino и PCA9685.
- Настройте ширину импульса в зависимости от используемых сервоприводов.
- Обеспечьте правильное охлаждение для PCA9685, если вы одновременно питаете множество сервоприводов.
Инструкции по подключению
Чтобы подключить модуль PCA9685 к Arduino и сервомоторам, начните с подключения внешнего блока питания 5V к контакту V+ модуля PCA9685. Подключите минус блока питания к контактам земли модуля PCA9685, а также к земле Arduino.
Затем подключите контакты SDA и SCL от PCA9685 к соответствующим контактам на Arduino (SDA к A4 и SCL к A5). Каждый сервомотор будет иметь три провода: землю (обычно черный или коричневый), VCC (как правило, красный) и сигнал (часто желтый или белый). Подключите провод земли каждого сервомотора к клемме земли PCA9685, провод VCC к клемме V+, а провод сигнала к соответствующим каналам (0-15) на PCA9685. Убедитесь, что провод сигнала подключен в правильном порядке для каждого сервомотора.
Примеры кода и пошаговое сопровождение
Теперь мы пройдемся по коду, который управляет сервомоторами, по одному. Код начинается с импорта необходимых библиотек для I2C-коммуникации и модуля PCA9685. Ниже приведен фрагмент, инициализирующий объект PCA9685:
#include
#include
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(); // Initialize PCA9685 В функции настройки мы инициализируем последовательный монитор и устанавливаем PWM частоту для сервоприводов:
void setup() {
Serial.begin(9600); // Start serial communication
pwm.begin(); // Initialize PCA9685
pwm.setPWMFreq(60); // Set frequency to 60 Hz for servos
}Главный цикл содержит два вложенных цикла: внешний цикл проходит через каждый из 16 сервоприводов, в то время как внутренний цикл постепенно изменяет угол от 0 до 180 градусов.
void loop() {
for(int i=0; i<16; i++) {
for(int angle = 0; angle<181; angle += 10) {
delay(50); // Wait for servo to move
pwm.setPWM(i, 0, angleToPulse(angle)); // Set servo position
}
}
delay(1000); // Wait before repeating
}Эта структура позволяет каждому сервоприводу перемещаться в заданный угол с шагом 10 градусов, обеспечивая плавные переходы. ФункцияangleToPulse(int ang)преобразует значения углов в ширину импульсов, подходящую для сервоприводов:
int angleToPulse(int ang) {
int pulse = map(ang, 0, 180, SERVOMIN, SERVOMAX); // Map angle to pulse width
return pulse; // Return pulse width
}Эта функция необходима для преобразования желаемого угла в PWM сигнал, который может понять PCA9685 и передать сервоприводам. Для получения дополнительной информации помните, что полный код загружен ниже статьи.
Демонстрация / Чего ожидать
Как только все провода подключены правильно и код загружен, вы должны увидеть, как каждый сервопривод перемещается на свои углы один за другим. Если у вас возникли какие-либо проблемы, еще раз проверьте свои соединения и убедитесь, что у вас есть стабильный источник питания для сервоприводов. Если сервоприводы не отвечают как ожидалось, проверьте сигналы PWM, отправляемые через PCA9685.
Временные метки видео
- 00:00 Подробности о модуле с чипом PCA9685
- 06:14 Добавление библиотеки, необходимой для PCA9685
- 07:14 Загрузка примерного кода
- 07:35 Объяснение кода
- 11:31 Упрощенный код Arduino для PCA9685
- 12:00 Нахождение минимального и максимального значения для вашего сервопривода
- 18:27 Соответствие угла импульса ширине импульса
- 20:05 Создание отдельного метода для отображения
- 20:55 Использование цикла for для тестирования всех углов для отображения
Этот учебник является частью: Управление 16 или 32 сервомоторами с помощью PCA9685
- Код Arduino и видео для сервоконтроллера PCA9685 на 16 каналов с разрешением 12 бит V1
- Управление 16 серводвигателями с помощью модуля PCA9685 и скетча Arduino V2: Управление отдельным сервоприводом
- Controlling 16 Servo Motors Using a PCA9685 Module and Arduino V2 Sketch #3: All Servos Together
- Управление 32 сервомотором с использованием модуля PCA9685 и скетча Arduino V3 #1: Все сервы вместе
- Управление 32 сервомоторами с помощью модуля PCA9685 и ESP32 V4
- Управление 32 сервомоторами по Wi-Fi с использованием ESP32 и PCA9685 через настольный или мобильный телефон V5
/*
* Original source: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
* PCA9685 Video V2, Arduino Code-1
* This is the Arduino code PAC6985 16 channel servo controller
* watch the video for details (V1) and demo http://youtu.be/y8X9X10Tn1k
* This code is #1 for V2 Video Watch the video :https://youtu.be/bal2STaoQ1M
get this code and wiring from https://robojax.com/RTJ243
* I have got 3 codes as follow:
#1-Arduino Code to run one by one all servos from 0 to 180°
#2-Arduino Code to control specific servos with specific angle
#3-Arduino Code to run 2 or all servos at together
* Written/updated by Ahmad Shamshiri for Robojax Video channel www.Robojax.com
* Date: Dec 16, 2017, in Ajax, Ontario, Canada
* Watch 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 Servo https://youtu.be/y8X9X10Tn1k
* Disclaimer: this code is "AS IS" and for educational purpose only.
* this code has been downloaded from https://robojax.com
or make donation using PayPal http://robojax.com/L/?id=64
* * This code is "AS IS" without warranty or liability. Free to be used as long as you keep this note intact.*
* This code has been download from Robojax.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/***************************************************
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, thats 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!
// Watch video V1 to understand the two lines below: http://youtu.be/y8X9X10Tn1k
#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() {
//watch video for details: https://youtu.be/bal2STaoQ1M
for(int i=0; i<16; i++)
{
for( int angle =0; angle<181; angle +=10){
delay(50);
pwm.setPWM(i, 0, angleToPulse(angle) );
// see YouTube video for details (robojax)
}
}
// robojax PCA9865 16 channel Servo control
delay(1000);// wait for 1 second
}
/*
/* angleToPulse(int ang)
* @brief gets angle in degree and returns the pulse width
* @param "ang" is integer representing angle from 0 to 180
* @return returns integer pulse width
* Usage to use 65 degree: angleToPulse(65);
* Written by Ahmad Shamshiri on Sep 17, 2019.
* in Ajax, Ontario, Canada
* www.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 sourse: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
* PCA9685 Video V2, Arduino Code-2
* This is the Arduino code PAC6985 16 channel servo controller
* watch the video for details (V1) and demo http://youtu.be/y8X9X10Tn1k
* This code is #2 for V2 Video Watch the video :https://youtu.be/bal2STaoQ1M
get codes and wring from https://robojax.com/RTJ243
* I have got 3 codes as follow:
#1-Arduino Code to run one by one all servos from 0 to 180°
#2-Arduino Code to control specific servos with specific angle
#3-Arduino Code to run 2 or all servos at together
*
* Written/updated by Ahmad Shamshiri for Robojax Video channel www.Robojax.com
* Date: Dec 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 purpose only.
* this code has been downloaded from https://robojax.com
* Watch 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 Servo https://youtu.be/y8X9X10Tn1k
* Get this code and other Arduino codes from Robojax.com
Learn Arduino step by step in structured course with all material, wiring diagram and library
all in once place. Purchase My course on Udemy.com http://robojax.com/L/?id=62
****************************
Get early access to my videos via Patreon and have your name mentioned at end of very
videos I publish on YouTube here: http://robojax.com/L/?id=63 (watch until end of this video to list of my Patrons)
****************************
or make donation using PayPal http://robojax.com/L/?id=64
* * This code is "AS IS" without warranty or liability. Free to be used as long as you keep this note intact.*
* This code has been download from Robojax.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#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!
// Watch video V1 to understand the two lines below: http://youtu.be/y8X9X10Tn1k
#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() {
//watch video for details: https://youtu.be/bal2STaoQ1M
for(int i=0; i<16; i++)
{
for( int angle =0; angle<181; angle +=10){
delay(50);
pwm.setPWM(5, 0, angleToPulse(angle) );
pwm.setPWM(8, 0, angleToPulse(angle) );
pwm.setPWM(15, 0, angleToPulse(angle) );
}
}
// robojax PCA9865 16 channel Servo control
delay(1000);
}
/*
* angleToPulse(int ang)
* gets angle in degree and returns the pulse width
* also prints the value on seial 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;
}
Ресурсы и ссылки
Ресурсов пока нет.
Файлы📁
Нет доступных файлов.