Cerca codice

Controlla 16 Motori Servo utilizzando un modulo PCA9685 e sketch Arduino V2 #1: Uno per uno

Controlla 16 Motori Servo utilizzando un modulo PCA9685 e sketch Arduino V2 #1: Uno per uno

In questo tutorial, impareremo come controllare fino a 16 servomotori utilizzando un modulo PCA9685 e un Arduino. Il PCA9685 è un controller PWM a 16 canali e 12 bit che consente un controllo preciso dei servomotori. Seguendo questa guida, sarai in grado di controllare individualmente ciascun servomotore e impostarli su angoli specifici, ottenendo una varietà di movimenti robotici.

Inizieremo discutendo dei componenti hardware necessari per questo progetto, seguiti da istruzioni dettagliate per il cablaggio. Dopodiché, passeremo al codice passo dopo passo, evidenziando gli identificatori chiave e il loro ruolo nel controllo dei servomotori. Per una comprensione più chiara, potresti voler fare riferimento al video di accompagnamento (nel video a :00).

Hardware Spiegato

Il componente principale di questo progetto è il modulo PCA9685, che è responsabile della generazione di segnali PWM per controllare i servomotori. Ogni servomotore è collegato a uno dei 16 canali del PCA9685, consentendo un controllo indipendente. Il modulo comunica con l'Arduino utilizzando il protocollo I2C, richiedendo solo due fili: SDA e SCL.

Oltre al PCA9685, avrai bisogno di una scheda Arduino, 16 servomotori e un'alimentazione esterna. L'alimentazione esterna è fondamentale perché l'Arduino da solo potrebbe non fornire sufficiente corrente per alimentare tutti i servomotori simultaneamente. Ogni servomotore normalmente opera a 5V, quindi assicurati che la tua alimentazione soddisfi questo requisito.

Dettagli della scheda tecnica

ProduttoreNXP Semiconductors
Numero partePCA9685
Tensione di logica/IO2,3 - 5,5 V
Tensione di alimentazione5 V
Corrente di uscita (per canale)25 mA
Linee guida sulla frequenza PWM60 Hz
Soglie logiche di ingresso0.3VCC (basso) / 0.7VCC (alto)
Caduta di tensione / RDS(on)/ saturazione-
Limiti termici-
PacchettoTSSOP-28 / VQFN-28
Note / varianti-
  • Collegare un alimentatore esterno da 5V per i servomotori.
  • Utilizza I2C per la comunicazione, collegando SDA a A4 e SCL a A5 sull'Arduino.
  • Assicurati che tutti i terreni siano comuni tra l'Arduino e il PCA9685.
  • Regolare le larghezze degli impulsi in base ai servomotori specifici utilizzati.
  • Mantieni un adeguato raffreddamento per il PCA9685 se alimenti molti servomotori contemporaneamente.

Istruzioni di cablaggio

Per collegare il modulo PCA9685 all'Arduino e ai servo motori, inizia collegando l'alimentazione esterna a 5V al terminale V+ del PCA9685. Collega il polo negativo dell'alimentatore al terminale di massa del PCA9685 e anche a quello di massa dell'Arduino.

Successivamente, collega i pin SDA e SCL del PCA9685 ai pin corrispondenti dell'Arduino (SDA ad A4 e SCL ad A5). Ogni servomotore avrà tre fili: massa (di solito nero o marrone), VCC (tipicamente rosso) e segnale (spesso giallo o bianco). Collega il filo di massa di ogni servomotore al terminale di massa del PCA9685, il filo VCC al terminale V+, e il filo di segnale ai canali rispettivi (0-15) sul PCA9685. Assicurati di collegare il filo di segnale nell'ordine corretto per ogni servomotore.

Esempi di codice e guida passo-passo

Procederemo ora a esaminare il codice che controlla i servomotori uno alla volta. Il codice inizia importando le librerie necessarie per la comunicazione I2C e il modulo PCA9685. L'estratto seguente inizializza l'oggetto PCA9685:

#include 
#include 

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(); // Initialize PCA9685

Nella funzione di configurazione, inizializziamo il monitor seriale e impostiamo la frequenza PWM per i servomotori:

void setup() {
  Serial.begin(9600); // Start serial communication
  pwm.begin(); // Initialize PCA9685
  pwm.setPWMFreq(60); // Set frequency to 60 Hz for servos
}

Il ciclo principale contiene due cicli annidati: il ciclo esterno itera attraverso ciascuno dei 16 servocomandi, mentre il ciclo interno cambia gradualmente l'angolo da 0 a 180 gradi.

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
}

Questa struttura consente a ciascun servomotore di muoversi verso l'angolo designato in incrementi di 10 gradi, garantendo transizioni fluide. La funzioneangleToPulse(int ang)converte i valori degli angoli in larghezze d'impulso appropriate per i servomotori:

int angleToPulse(int ang) {
   int pulse = map(ang, 0, 180, SERVOMIN, SERVOMAX); // Map angle to pulse width
   return pulse; // Return pulse width
}

Questa funzione è essenziale per tradurre l'angolo desiderato in un segnale PWM che il PCA9685 può comprendere e trasmettere ai servomotori. Per ulteriori dettagli, ricorda che il codice completo si carica sotto l'articolo.

Dimostrazione / Cosa Aspettarsi

Una volta che tutto è cablato correttamente e il codice è caricato, dovresti vedere ogni servo muoversi nei rispettivi angoli uno dopo l'altro. Se riscontri problemi, controlla di nuovo le tue connessioni e assicurati di avere un'alimentazione stabile per i servomotori. Se i servomotori non rispondono come previsto, verifica i segnali PWM inviati tramite il PCA9685.

Timestamp video

  • 00:00 Dettagli del modulo con chip PCA9685
  • 06:14 Aggiunta della libreria necessaria per il PCA9685
  • 07:14 Caricamento del codice di esempio
  • 07:35 Codice spiegato
  • 11:31 Codice Arduino semplificato per PCA9685
  • 12:00 Trovare il valore minimo e massimo per il tuo servo
  • 18:27 Mappatura dell'angolo di impulso alla lunghezza dell'impulso
  • 20:05 Creazione di un metodo separato per la mappatura
  • 20:55 Utilizzando un ciclo for per testare tutti gli angoli per la mappatura
267-PCA9685 Video V2, Arduino Code-1 to run servo one by one all servos from 0 to 180°
Lingua: C++
/*
 * 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;
}
268-PCA9685 Video V2, Arduino Code-2 to control specific servos with specific angles (one or more servos)
Lingua: C++
/*
 * 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;
}

Risorse e riferimenti

Nessuna risorsa ancora.

File📁

Nessun file disponibile.