NAME

RPi::PWM::PCA9685 - Interface to the NXP PCA9685 16-channel, 12-bit PWM/servo controller over the I2C bus

Coverage Status

SYNOPSIS

use RPi::PWM::PCA9685;

# LEDs / general PWM

my $pca = RPi::PWM::PCA9685->new(freq => 1000);

$pca->duty(0, 2048);        # channel 0 at 50%
$pca->duty_pct(1, 12.5);    # channel 1 at 12.5%
$pca->full_on(2);           # channel 2 hard on, no PWM

$pca->all_off;

# Powering an LED, two ways (see DRIVING LEDS)

# Sourced from the pin:  pin -> resistor -> LED -> GND (totem-pole default)
$pca->duty_pct(0, 75);

# Sunk from a higher rail: V+ -> LED -> resistor -> pin (eg. 5V LED, 3.3V chip)
$pca->sink_mode;            # Open-drain + inverted logic
$pca->duty_pct(0, 75);

# Servos (the whole chip must run at 50 Hz)

my $servo = RPi::PWM::PCA9685->new(freq => 50);

$servo->servo_us(0, 1500);  # centre
$servo->servo_us(0, 2000);  # one end
$servo->servo_us(0, 0);     # stop the pulses; servo goes limp

DESCRIPTION

Interface to the NXP PCA9685 16-channel, 12-bit PWM controller over the I2C bus. This is the chip found on virtually every "16-channel servo driver" or "16-channel PWM/LED driver" breakout board.

Each of the 16 channels has 4096 duty cycle steps, and the chip generates all PWM in hardware, so the Pi spends zero CPU keeping the signals alive. All 16 channels share a single PWM frequency (24-1526 Hz); duty cycle and phase are per-channel.

This distribution is pure Perl. The I2C transport is provided by RPi::I2C, which carries the compiled layer and talks to the chip through the kernel's /dev/i2c-N interface. Channel updates go out as a single atomic I2C transaction, so an output never glitches through a half-written state.

The chip powers up asleep with its oscillator stopped; new() wakes it and enables register auto-increment automatically.

METHODS

new

Instantiates a new RPi::PWM::PCA9685 object, opens the I2C bus, verifies the chip responds, and wakes it up.

Parameters:

All parameters are sent in within a single hash, and all are optional.

device => $str

Optional, String: The I2C bus device. Defaults to /dev/i2c-1.

addr => $int

Optional, Integer: The 7-bit I2C address of the chip, as set by its A5-A0 address pins. Defaults to 0x40 (all address pins low). See "I2C ADDRESSING".

freq => $num

Optional, Number: The PWM frequency in Hz for all 16 channels, between 24-1526. Use 50 for servos, 1000 is a good choice for LEDs. If not supplied, the chip keeps its current prescaler (200 Hz from power-on).

osc => $num

Optional, Number: The true speed in Hz of the chip's internal oscillator, if you've measured it. See "osc_freq".

invert => $bool

Optional, Bool: Invert the output logic of all channels. See "invert".

drive => $str

Optional, String: The output drive type, 'totem' (the default) or 'open_drain'. Totem-pole drives each pin both high and low, and suits LEDs powered from the chip's own pins and servo signal lines. Open-drain only sinks (an off pin floats), which is what you want when sinking current from a supply above the chip's VDD - see "sink_mode" and "DRIVING LEDS". The setting is reapplied across "reset".

Returns: The RPi::PWM::PCA9685 object. Croaks if the bus can't be opened or the chip doesn't respond.

freq

Sets and/or gets the PWM frequency shared by all 16 channels.

Changing frequency briefly stops the chip's oscillator (the prescaler is only writable during sleep), so all outputs pause for about a millisecond. Set it once, up front.

Parameters:

$freq

Optional, Number: The desired frequency in Hz, clamped by the chip to 24-1526.

Returns: The actual frequency in Hz. The prescaler is an 8-bit divider, so what you get is quantised; ask for 1000 and you'll receive 1017.25.

duty

Sets a channel's duty cycle.

Parameters:

$channel

Mandatory, Integer: The channel, 0-15, or 16 for all channels at once.

$duty

Mandatory, Integer: 0-4095. 0 is hard off and 4095 is hard on (these use the chip's full-off/full-on flags); anything between is $duty/4096 of each PWM cycle.

Returns: 0 upon success.

duty_pct

Same as "duty", but takes a percentage.

Parameters:

$channel

Mandatory, Integer: The channel, 0-15, or 16 for all.

$pct

Mandatory, Number: Duty cycle as a percentage, 0-100. Decimals are fine.

Returns: 0 upon success.

servo_us

Sets a channel's pulse width in microseconds - the native language of hobby servos. The chip should be running at 50 Hz (freq => 50 in new()).

Parameters:

$channel

Mandatory, Integer: The channel, 0-15, or 16 for all.

$us

Mandatory, Number: The pulse width in microseconds. Nominal servo range is 1000-2000 with 1500 as centre; many servos accept 500-2500 for their full mechanical throw. Sneak up on the limits - a servo buzzing at an end stop is cooking itself. 0 stops the pulses entirely, releasing the servo. Croaks if the pulse would be wider than the PWM period.

Returns: 0 upon success.

pwm

Raw access to a channel's ON and OFF tick registers, for phase control.

Within each 4096-tick PWM cycle, the output switches high when the counter hits $on, and low when it hits $off. Duty is the distance between them; giving each channel a different $on staggers the switching edges so heavy loads don't all slam the supply at the same instant.

Parameters:

$channel

Mandatory, Integer: The channel, 0-15, or 16 for all.

$on

Mandatory, Integer: Tick the output goes high, 0-4095. Setting bit 12 (0x1000) forces the channel full on.

$off

Mandatory, Integer: Tick the output goes low, 0-4095. Setting bit 12 (0x1000) forces the channel full off, which wins over everything else.

Returns: 0 upon success.

pwm_read

Reads back a channel's ON and OFF tick registers.

Parameters:

$channel

Mandatory, Integer: The channel, 0-15.

Returns: A two element list, ($on, $off).

full_on

Puts a channel hard on - solid high, no PWM.

Parameters:

$channel

Mandatory, Integer: The channel, 0-15, or 16 for all.

Returns: 0 upon success.

full_off

Puts a channel hard off. For a servo, this stops its pulses (releasing it).

Parameters:

$channel

Mandatory, Integer: The channel, 0-15, or 16 for all.

Returns: 0 upon success.

all_off

Puts every channel hard off in a single call.

Takes no parameters. Returns: 0 upon success.

invert

Inverts the output logic of all 16 channels.

Useful when LEDs are wired to be current-sunk (V+ -> LED -> resistor -> pin), where the LED is lit while the pin is low. Inverting makes duty cycle mean brightness again. For the full sink-wiring setup, see "sink_mode".

Parameters:

$invert

Optional, Bool: True to invert, false for normal logic. Defaults to 1.

Returns: 0 upon success.

sink_mode

Configures the chip for current-sinking LED wiring in one call: it switches the outputs to open-drain and inverts the output logic. Equivalent to new(drive => 'open_drain') followed by invert(1).

Use this when LEDs (or other loads) are wired V+ -> load -> resistor -> pin and powered from a supply above the chip's VDD - for example a 3.3 V chip sinking 5 V LEDs. Open-drain lets an off pin float to the external rail (within the pins' 5.5 V tolerance) instead of driving it down to VDD, and the inversion keeps higher duty meaning brighter. See "DRIVING LEDS".

The open-drain setting is remembered and reapplied across "reset".

Takes no parameters. Returns: 0 upon success.

osc_freq

Sets and/or gets the oscillator frequency the prescaler and pulse width math assumes. Defaults to the nominal 25000000 (25 MHz).

The chip's internal oscillator is only accurate to a few percent, which skews both the PWM frequency and servo pulse widths. If you've measured your board's true speed (scope an output, or trim until a known pulse width measures correctly), set it here - subsequent "freq" and "servo_us" calls self-correct. This only changes the math on the Pi; nothing is written to the chip.

Parameters:

$hz

Optional, Number: The true oscillator speed in Hz.

Returns: The currently assumed oscillator speed in Hz.

sleep

Puts the chip into low-power sleep - the oscillator stops and all outputs freeze. Register contents survive.

Takes no parameters. Returns: 0 upon success.

wake

Wakes the chip from sleep, and restarts any PWM that was running when it went down.

Takes no parameters. Returns: 0 upon success.

reset

Software-resets the chip to its power-on defaults, then re-initialises it (auto-increment on, awake).

WARNING: this is the I2C "general call" reset - it resets every PCA9685 on the bus, not just this one.

Takes no parameters. Returns: 0 upon success.

register

Reads or writes any register on the chip directly, for anything this API doesn't wrap. See the datasheet, or the TECHNICAL INFORMATION section below for the register map.

Parameters:

$reg

Mandatory, Integer: The register address, 0-255.

$value

Optional, Integer: A byte to write, 0-255. If omitted, the register is read instead.

Returns: The byte read, or the byte written.

close

Closes the I2C connection and invalidates the object. Called automatically on DESTROY. The chip's outputs keep running - call "all_off" first if you want everything off.

Takes no parameters. Returns: 0.

TECHNICAL INFORMATION

DEVICE SPECIFICS

- 16 outputs, 12-bit (4096 step) duty resolution each
- One shared PWM frequency, 24-1526 Hz
- Internal 25 MHz oscillator; no crystal required
- Powers up asleep; new() handles the wake-up
- Runs at 2.3-5.5V; the Pi's 3.3v is fine
- Each output sinks up to 25 mA, sources up to 10 mA
- The OE pin (active low) is a hardware master output-enable

Wiring to the Pi: VCC to 3.3v, SDA to GPIO 2 (pin 3), SCL to GPIO 3 (pin 5), GND to ground. If the board has a V+ LED/servo supply input, feed it from an external 5v supply, not the Pi. Verify the chip answers with i2cdetect -y 1 - you'll see the chip at 0x40 and its all-call alias at 0x70.

PWM OPERATION

A free running counter ticks 0-4095 repeatedly; one lap is one PWM cycle. Each channel holds two numbers: the output goes high when the counter hits ON, low when it hits OFF. Duty cycle is (OFF - ON) / 4096, and where the pulse sits within the cycle (the phase) is up to you via "pwm".

The PWM frequency for all channels is set by an 8-bit prescaler dividing the oscillator:

freq     = 25MHz / (4096 * (prescale + 1))
prescale = round(25MHz / (4096 * freq)) - 1

Because the prescaler is quantised, the actual frequency usually differs from the request - "freq" returns what you really got.

DRIVING LEDS

There are two ways to wire an LED to a channel, and they want different output drive types.

Sourcing - the pin supplies the current:

pin -> resistor -> LED anode -> LED cathode -> GND

The pin drives high to light the LED. This needs totem-pole outputs (the default), and is limited to the ~10 mA a pin can source. Good for indicator LEDs powered from the chip itself.

Sinking - an external supply drives the LED, the pin is the return:

V+ -> LED anode -> LED cathode -> resistor -> pin

The pin sinks up to 25 mA to light the LED, so it handles brighter LEDs, and crucially the LED can run from a rail higher than the chip's VDD. The outputs are 5.5 V tolerant regardless of VDD, so a chip powered at the Pi's 3.3 V can sink LEDs from a 5 V rail (up to 5.5 V) directly.

This must use open-drain outputs. In totem-pole an off pin is driven to VDD, which a higher V+ would back-feed through the LED into the chip's supply; open-drain lets the off pin float to V+ instead. Sinking also inverts the logic sense (the pin is low to light the LED), so the PWM values want inverting to make duty mean brightness.

"sink_mode" sets both at once:

my $pca = RPi::PWM::PCA9685->new(freq => 1000);
$pca->sink_mode;              # Open-drain + inverted, for V+ -> LED -> pin
$pca->duty_pct(0, 75);        # 75% brightness

Requirements for the sinking setup:

- Keep V+ at or below 5.5 V (the pins' absolute tolerance)
- Tie the V+ supply's ground to the chip's VSS (shared return)
- Size the resistor for <= 25 mA per channel, and mind the package total
  across all lit channels

For loads beyond 25 mA or above 5.5 V, drive an external transistor from the pin instead. Open-drain plus "invert" also suits an external N-type driver; totem-pole plus non-inverted suits a P-type - see the datasheet's section 7.7.

SERVO OPERATION

Servos ignore duty cycle; they read the width of the pulse arriving each 20 ms (50 Hz) frame. Roughly 1000 us is one end of travel, 1500 us centre, 2000 us the other end. At 50 Hz, one counter tick is ~4.9 us of pulse width, about 200 positions across a standard servo's range.

Real-world limits vary per servo, and the chip's oscillator tolerance skews pulse widths a percent or three - calibrate with "osc_freq" if you need repeatable angles.

REGISTER MAP

0x00        MODE1        Power/clock/addressing switches
0x01        MODE2        Output pin behaviour (invert, drive type)
0x02-0x05   SUBADR/ALLCALL Alternate I2C addresses
0x06-0x45   LEDn ON/OFF  4 bytes per channel, starting at 0x06 + 4 * ch
0xFA-0xFD   ALL_LED      Write every channel at once
0xFE        PRE_SCALE    PWM frequency divider (writable only in sleep)
0xFF        TESTMODE     Leave it alone

ON THE WIRE

This is what the registers above look like on the bus as the data is clocked in. Time flows left to right, one box per byte, bits go out MSB-first, and every 9th clock is an ACK slot:

S = START    Sr = Repeated START    P = STOP
A = ACK (receiver pulls SDA low)    N = NACK (master, "no more bytes")

Every transaction opens the same way: SDA falls while SCL is still high (that's the START), then the master (the Pi) clocks out the chip address. SDA may only change while SCL is low; the chip samples each bit while SCL is high. Here's the first byte of every write this module does - address 0x40 shifted left plus the R/W bit, i.e. 0x80:

      Idle  START   1     0     0     0     0     0     0     0    ACK
SDA   ------\_____/-----\_______________________________________________
SCL   -----------\_/--\__/--\__/--\__/--\__/--\__/--\__/--\__/--\__/--\_

On the ACK clock the master releases SDA and the chip holds it low (the line doesn't visibly move here since bit 0 was already 0 - only the driver changes). SCL just keeps running, and the next byte follows the same 8-bits-plus-ACK shape until the STOP.

A plain register write - the byte after the address is always the register number, which is how the wire indexes into the register map. This is the frame "wake" sends at the end of a bare new(), identical to $pca->register(0x00, 0x21):

+---+-----------+---+-----------+---+-----------+---+---+
| S | 1000000 0 | A | 0000 0000 | A | 0010 0001 | A | P |
+---+-----------+---+-----------+---+-----------+---+---+
      Chip addr       Register        New value
      0x40 + W=0      0x00 (MODE1)    0x21 (AI|ALLCALL)

A channel update: $servo->servo_us(0, 1500) at 50 Hz works out to 307 ticks, so it becomes pwm(0, 0, 307) - four bytes at LED0_ON_L in a single transaction. Because new() set MODE1's auto-increment bit, the chip bumps its register pointer after each data byte:

+---+------+---+------+---+------+---+------+---+------+---+------+---+---+
| S | 0x80 | A | 0x06 | A | 0x00 | A | 0x00 | A | 0x33 | A | 0x01 | A | P |
+---+------+---+------+---+------+---+------+---+------+---+------+---+---+
     addr+W     Reg        Lands in   Lands in   Lands in   Lands in
                pointer    0x06       0x07       0x08       0x09
                           LED0_ON_L  LED0_ON_H  LED0_OFF_L LED0_OFF_H

The outputs don't take the new values byte-by-byte - they latch at the STOP, which is what makes channel updates atomic. The 12-bit OFF value of 307 (0x133) is split across the L/H register pair; the top three bits of the H byte are don't-cares:

LED0_OFF_L (0x08) = 0x33               LED0_OFF_H (0x09) = 0x01
+---+---+---+---+---+---+---+---+      +---+---+---+---+---+---+---+---+
| 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 |      | - | - | - | F | 0 | 0 | 0 | 1 |
+---+---+---+---+---+---+---+---+      +---+---+---+---+---+---+---+---+
           OFF[7:0]                                  ^    OFF[11:8]
                                                     |
                                        The 0x1000 "full off" flag
                                        (clear in this frame)

Reading a register back is a write of just the register pointer, then a repeated START with the R bit set. Direction flips mid-transaction: during the data byte the chip drives SDA and the master only supplies clocks. $pca->register(0xFE) after freq => 50:

+---+------+---+------+---+----+------+---+------+---+---+
| S | 0x80 | A | 0xFE | A | Sr | 0x81 | A | 0x79 | N | P |
+---+------+---+------+---+----+------+---+------+---+---+
     addr+W     PRE_SCALE       addr+R     Chip      Master NACKs the
                pointer         (R bit=1)  drives    last byte, then STOPs

"pwm_read" is the same shape with four data bytes - the master ACKs the first three and NACKs the fourth.

The general call reset is the shortest frame the module ever produces: "reset" sends the SWRST magic byte to 7-bit address 0x00, and every PCA9685 on the bus ACKs it and resets:

+---+-----------+---+-----------+---+---+
| S | 0000000 0 | A | 0000 0110 | A | P |
+---+-----------+---+-----------+---+---+
     General call     SWRST magic
     addr 0x00        0x06

That's every wire shape the module generates: single-byte write, auto-increment block write, pointer-then-read, and the general call.

I2C ADDRESSING

The chip's 7-bit address is a fixed high bit followed by the six hardware address pins, A5 down to A0:

1  A5 A4 A3 A2 A1 A0         The 7-bit address
|  32 16  8  4  2  1         Each pin's weight when strapped high
|
Fixed - the 0x40 every address starts from

Each address pin must be tied to a rail - GND for low, VCC for high. The chip has no internal pull resistors on these pins, so one left floating reads an undefined level, and the chip can answer at an address you didn't intend - or not at all. Breakout boards typically strap all six low and provide solder pads to bridge individual pins high.

All pins grounded gives the default 0x40, which is what new() assumes when no addr is passed. Pulling a few pins high simply adds their weights:

A5 A4 A3 A2 A1 A0      Address
-----------------      -------
 L  L  L  L  L  L       0x40      The default - all pins to GND
 L  L  L  L  L  H       0x41
 L  L  L  L  H  L       0x42
 L  L  L  H  L  H       0x45
 H  L  L  L  L  L       0x60
 H  H  L  H  L  H       0x75

Match the straps with the addr param:

my $pca = RPi::PWM::PCA9685->new(addr => 0x45);

Two straps to avoid: 110000 (0x70) collides with the all-call address every PCA9685 answers by default (see "MULTIPLE DEVICES"), and the 111xxx combinations land in I2C-reserved space (0x78-0x7F) that new() refuses. The strapped value is what leads every transaction on the bus, shifted left with the R/W bit appended - see "ON THE WIRE".

MULTIPLE DEVICES

The chip's 7-bit address is 0x40 plus whatever is strapped on its six address pins, so up to 62 chips can share the bus. Since all 16 channels of one chip share a frequency, running servos (50 Hz) alongside flicker-free LEDs (1 kHz) means using two chips:

my $leds   = RPi::PWM::PCA9685->new(addr => 0x40, freq => 1000);
my $servos = RPi::PWM::PCA9685->new(addr => 0x41, freq => 50);

Note that every PCA9685 also answers the all-call address 0x70 by default, and "reset" resets all of them at once.

DATASHEET

The NXP PCA9685 datasheet (Rev. 4) is distributed with this software as docs/datasheet/PCA9685.pdf. It covers the register map, the PWM timing, and the I2C framing this module drives.

SEE ALSO

RPi::I2C, which provides the I2C transport for this distribution.

AUTHOR

Steve Bertrand, <steveb at cpan.org>

LICENSE AND COPYRIGHT

Copyright 2026 Steve Bertrand.

This program is free software; you can redistribute it and/or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at:

http://www.perlfoundation.org/artistic_license_2_0