Servos on a PCA9685
Drive two servos from a PCA9685 16-channel PWM board over I²C, with the Adafruit library.
Motors · Intermediate
In a real product: Robotic arm (Robotics): One board drives many servo joints over I2C.
Each servo needs its own PWM signal, and an Uno only has six PWM pins. The PCA9685 board makes 16 PWM signals by itself and takes its orders over I²C, so two wires can run up to 16 servos (and boards can be chained for more).
What you'll learn
- Off-loading PWM to a dedicated chip
- The PCA9685's 12-bit counter, its prescaler, and ON/OFF times
- Using the Adafruit PWM Servo Driver library
How it works
SDA and SCL go to A4 and A5; the board answers at address 0x40. VCC powers the chip and V+ powers the servos, through the middle pin of every channel's 3-pin header (GND, V+, signal).
The chip counts 0 to 4095 every PWM period. Each channel turns on at its ON count and off at its OFF count, so the pulse width is set in steps of 1/4096 of the period. setPWMFreq(50) sets the prescaler for 50 Hz (20 ms), what servos expect. writeMicroseconds(channel, us) works out the counts for a pulse width, here 600 to 2400 µs.
Servo 1 is on channel 0 and servo 2 on channel 15. The loop sweeps them in opposite directions.
Try this
- Add more servos on other channels: no extra Uno pins needed.
- Make a robot arm with one servo per joint, moving to stored poses.
- Fade an LED on a channel with
setPWM()instead of a servo.
sketch.ino
// Two servos on a PCA9685 (I2C address 0x40), on channels 0 and 15, sweeping in opposite directions.
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm; // 0x40
const int MIN_US = 600, MAX_US = 2400;
void setup() {
pwm.begin();
pwm.setPWMFreq(50); // servos expect a pulse every 20 ms
delay(10);
}
void loop() {
for (int us = MIN_US; us <= MAX_US; us += 20) {
pwm.writeMicroseconds(0, us);
pwm.writeMicroseconds(15, MIN_US + MAX_US - us);
delay(10);
}
for (int us = MAX_US; us >= MIN_US; us -= 20) {
pwm.writeMicroseconds(0, us);
pwm.writeMicroseconds(15, MIN_US + MAX_US - us);
delay(10);
}
}