PCA9685 Driver 0.1.0
API reference
Loading...
Searching...
No Matches
Classes | Enumerations | Functions | Variables
Driver types

Errors, results, channel values, configuration and presets. More...

Classes

struct  pca9685::Result< T >
 The value of a call, or why there is none. More...
 
struct  pca9685::Result< void >
 The result of a call that returns no value. More...
 
struct  pca9685::Pwm
 The value of one channel: its four registers, decoded (table 7, figure 9). More...
 
struct  pca9685::Config
 Everything EnsureInitialized() writes to the chip. More...
 
class  pca9685::CheckedConfig
 A configuration proven valid at build time. More...
 

Enumerations

enum class  pca9685::Error : uint8_t {
  pca9685::Error::Ok = 0 , pca9685::Error::NotInitialized = 1 , pca9685::Error::InvalidArgument = 2 , pca9685::Error::Bus = 3 ,
  pca9685::Error::Timeout = 4 , pca9685::Error::DeviceIdMismatch = 5 , pca9685::Error::Crc = 6 , pca9685::Error::Busy = 7 ,
  pca9685::Error::DeviceFault = 8 , pca9685::Error::Unsupported = 9 , pca9685::Error::WriteMismatch = 16 , pca9685::Error::NoDevice = 17 ,
  pca9685::Error::DeviceReset , pca9685::Error::InvalidReply = 19 , pca9685::Error::Asleep = 20 , pca9685::Error::StateUnknown = 21 ,
  pca9685::Error::ExternalClockLatched = 22
}
 Why a call failed. Every call of the driver returns one of these in its Result. More...
 
enum class  pca9685::LogLevel : uint8_t { pca9685::LogLevel::Error = 0 , pca9685::LogLevel::Warning , pca9685::LogLevel::Info , pca9685::LogLevel::Debug }
 Severity passed to the optional Log() hook. More...
 
enum class  pca9685::Verify : uint8_t { pca9685::Verify::None = 0 , pca9685::Verify::ReadBack = 1 }
 Whether a call reads back what it wrote (handbook KB-ARCH-041). More...
 
enum class  pca9685::OutputDrive : uint8_t { pca9685::OutputDrive::OpenDrain = 0 , pca9685::OutputDrive::TotemPole = 1 }
 The output stage of all 16 outputs (MODE2.OUTDRV, table 6). More...
 
enum class  pca9685::ClockSource : uint8_t { pca9685::ClockSource::Internal = 0 , pca9685::ClockSource::External = 1 }
 The clock the PWM counter runs from (MODE1.EXTCLK, table 5). More...
 
enum class  pca9685::SleepMode : uint8_t { pca9685::SleepMode::OutputsOff = 0 , pca9685::SleepMode::HoldOutputs = 1 }
 What Sleep() does with the outputs (section 7.3.1.1). More...
 

Functions

constexpr const char * pca9685::ToString (Error error) noexcept
 The name of an error, for logs.
 
constexpr Pwm pca9685::PwmOff () noexcept
 
constexpr Pwm pca9685::PwmFullOn () noexcept
 
constexpr bool pca9685::IsOff (const Pwm &pwm) noexcept
 Whether a channel value switches the channel off: LEDn_OFF_H[4] set, which takes precedence over everything else (section 7.3.3).
 
constexpr bool pca9685::IsValid (const Pwm &pwm) noexcept
 Whether a channel value can be written: both counts at most 4095 and, unless a full bit is set, different (the registers "should never be programmed with the same values", section 7.3.4).
 
constexpr Result< Pwm > pca9685::PwmForDuty (uint16_t duty, uint16_t phase=0U) noexcept
 The channel value for a duty cycle and a phase delay.
 
constexpr Error pca9685::Validate (const Config &config) noexcept
 Check a configuration without touching the chip.
 
constexpr Result< uint8_t > pca9685::PrescaleFor (uint32_t frequency_hz, uint32_t oscillator_hz) noexcept
 The PRE_SCALE value for a frequency, by equation 1 of section 7.3.5, rounded to nearest.
 
constexpr uint32_t pca9685::FrequencyFor (uint8_t prescale, uint32_t oscillator_hz) noexcept
 The PWM frequency a prescaler gives, rounded to the nearest hertz (equation 1 inverted).
 
constexpr Result< uint16_t > pca9685::CountsForPulseUs (uint32_t width_us, uint8_t prescale, uint32_t oscillator_hz) noexcept
 The counts of a pulse width at a prescaler: one count is (prescale + 1) / oscillator seconds. Uses the chip's programmed prescaler (handbook KB-CPP-128).
 
constexpr uint32_t pca9685::PulseNsForCounts (uint16_t counts, uint8_t prescale, uint32_t oscillator_hz) noexcept
 The pulse width of a number of counts, in nanoseconds, rounded to nearest: what a quantised SetPulseWidthUs() programmed.
 
constexpr Config pca9685::DirectLedPreset () noexcept
 LEDs wired from the supply through a resistor to the outputs (figure 15): open drain, inverted, so that a channel that is off leaves the output high impedance and the LED dark. Mind the reset level: a chip that resets is not inverted and drives every output low, which lights such an LED until EnsureInitialized() runs again (docs/hardware.md).
 
constexpr Config pca9685::ServoPreset () noexcept
 Hobby servos and external N-type drivers (figure 13): totem pole, not inverted, so the reset level, low, is off. 50 Hz, a 20 ms period.
 
void pca9685::ConfigIsInvalid () noexcept
 Reached only when a CheckedConfig is built from an invalid configuration: it is never defined, so the build fails and names it (KB-CPP20-013).
 
constexpr const char * pca9685::GetDriverVersion () noexcept
 
constexpr uint32_t pca9685::GetDriverVersionMajor () noexcept
 
constexpr uint32_t pca9685::GetDriverVersionMinor () noexcept
 
constexpr uint32_t pca9685::GetDriverVersionPatch () noexcept
 

Variables

constexpr uint8_t pca9685::kChannelCount = reg::kChannels
 Number of PWM channels, LED0 to LED15.
 
constexpr uint32_t pca9685::kCountsPerPeriod = 4096U
 Counter steps per PWM period: 4096 (12 bits, section 7.3.3).
 
constexpr uint16_t pca9685::kMaxCount = reg::kMaxCount
 Highest ON or OFF count, 4095.
 
constexpr uint16_t pca9685::kFullDuty = 4096U
 SetDuty() value for a channel that is on for the whole period (full ON).
 
constexpr uint32_t pca9685::kInternalOscillatorHz = 25'000'000U
 Typical frequency of the internal oscillator, in hertz (section 2, table 5).
 
constexpr uint32_t pca9685::kMaxOscillatorHz = 50'000'000U
 Highest EXTCLK frequency, in hertz (table 15, f_EXTCLK).
 
constexpr uint32_t pca9685::kMinOscillatorHz = 1'000'000U
 
constexpr uint32_t pca9685::kMaxPwmFrequencyHz = 10'000U
 
constexpr uint32_t pca9685::kOscillatorStartUs = 500U
 Oscillator start-up after SLEEP is cleared, in microseconds (table 5, note 2: 500 us maximum).
 
constexpr uint8_t pca9685::kMinI2cAddress = 0x40
 Lowest I2C address of a PCA9685: 1 A5 A4 A3 A2 A1 A0 with every pin low (figure 4).
 
constexpr uint8_t pca9685::kMaxI2cAddress = 0x7F
 Highest I2C address of a PCA9685, every address pin high.
 
constexpr uint8_t pca9685::kAllCallAddress = 0x70
 

Detailed Description

Errors, results, channel values, configuration and presets.

Enumeration Type Documentation

◆ ClockSource

enum class pca9685::ClockSource : uint8_t
strong

The clock the PWM counter runs from (MODE1.EXTCLK, table 5).

Enumerator
Internal 

The internal oscillator, 25 MHz typical. Reset value.

External 

The EXTCLK pin, DC to 50 MHz; sticky until a power cycle or software reset.

◆ Error

enum class pca9685::Error : uint8_t
strong

Why a call failed. Every call of the driver returns one of these in its Result.

Values 0 to 9 are the shared base set; chip-specific values start at 16. [[nodiscard]] on the type: a function that returns a bare Error cannot have it ignored either (KB-CPP20-037).

Enumerator
Ok 

The call succeeded.

NotInitialized 

EnsureInitialized() has not succeeded yet, or Deinitialize() ran or a reset was found since.

InvalidArgument 

An argument, the address or a Config field is out of range; nothing was sent (a bank call still sends its switch-offs).

Bus 

A port hook returned false: a NACK of a data byte, a bus error, or a failed output-enable pin write.

Timeout 

Not returned by this driver (no wait polls the chip).

DeviceIdMismatch 

At start-up, a register did not read back what was just written: no PCA9685 answers, or another part does (the chip has no ID register).

Crc 

Not returned by this driver (I2C transfers carry no CRC).

Busy 

Not returned by this driver (the chip has no busy state).

DeviceFault 

Not returned by this driver (the chip reports no faults).

Unsupported 

The port has no output-enable GpioSet() hook, which this call needs.

WriteMismatch 

A register read back differently from what was just written: a write the chip acknowledged but did not keep. Channel calls with Verify::ReadBack; SetPwmFrequency() always (PRE_SCALE ignores a write while awake).

NoDevice 

Nothing acknowledged the address byte: no chip at the address, or it is unpowered. Needs a port with the optional GetLastFailure() hook; without it this is Bus.

DeviceReset 

The chip went through a power-on or software reset since the start, confirmed by two reads: MODE1.AI = 0, or MODE2, EXTCLK, SUBADR1 or PRE_SCALE back at its reset value while the driver's copy differs (sections 7.5, 7.6). The driver drove OE high, wrote ALL_LED_OFF_H and is now uninitialised.

InvalidReply 

A read returned bits the chip cannot send: a read-only bit set, or an inconsistent MODE1/MODE2/SUBADR1 frame. A floating, stuck or shared line, never data.

Asleep 

The registers were written, but the chip is (or may be) asleep, so the outputs do not follow until Wake(); for a switch-off, an output may hold its last level (section 7.3.1, note 4). DisableOutputs() acts at once.

StateUnknown 

The call depends on a value a failed write left unknown (a channel, the prescaler); nothing was sent. Read it back, or write it again.

ExternalClockLatched 

MODE1.EXTCLK is set on the chip but Config asks for the internal oscillator: the bit is sticky until a power cycle or a software reset (table 5).

◆ LogLevel

enum class pca9685::LogLevel : uint8_t
strong

Severity passed to the optional Log() hook.

Enumerator
Error 

A call failed.

Warning 

Something unexpected that the driver recovered from.

Info 

Lifecycle events: initialised, reset found.

Debug 

Detail for bring-up.

◆ OutputDrive

enum class pca9685::OutputDrive : uint8_t
strong

The output stage of all 16 outputs (MODE2.OUTDRV, table 6).

Enumerator
OpenDrain 

Sink only. Needed for LEDs with integrated Zener diodes (section 10, Q5).

TotemPole 

Sink 25 mA, source 10 mA. Reset value.

◆ SleepMode

enum class pca9685::SleepMode : uint8_t
strong

What Sleep() does with the outputs (section 7.3.1.1).

Enumerator
OutputsOff 

Every channel off first (ALL_LED_OFF_H), then sleep: the safe low-power state; Wake() leaves every channel off.

HoldOutputs 

Sleep with the channels as they are; Wake() restarts them (RESTART). While asleep an output may hold its last level.

◆ Verify

enum class pca9685::Verify : uint8_t
strong

Whether a call reads back what it wrote (handbook KB-ARCH-041).

Enumerator
None 

Write only. Default.

ReadBack 

Write, then read MODE1, MODE2, SUBADR1 (the reset check) and the channel back; a difference is Error::WriteMismatch.

Function Documentation

◆ CountsForPulseUs()

constexpr Result< uint16_t > pca9685::CountsForPulseUs ( uint32_t  width_us,
uint8_t  prescale,
uint32_t  oscillator_hz 
)
constexprnoexcept

The counts of a pulse width at a prescaler: one count is (prescale + 1) / oscillator seconds. Uses the chip's programmed prescaler (handbook KB-CPP-128).

Parameters
width_usThe pulse width in microseconds; 0 is off.
prescalePRE_SCALE.
oscillator_hzThe counter clock.
Returns
The counts, rounded to nearest, or InvalidArgument when the width rounds to 0 counts without being 0, or to more than 4095 (it does not fit in one period).

◆ DirectLedPreset()

constexpr Config pca9685::DirectLedPreset ( )
constexprnoexcept

LEDs wired from the supply through a resistor to the outputs (figure 15): open drain, inverted, so that a channel that is off leaves the output high impedance and the LED dark. Mind the reset level: a chip that resets is not inverted and drives every output low, which lights such an LED until EnsureInitialized() runs again (docs/hardware.md).

Returns
The preset.

◆ FrequencyFor()

constexpr uint32_t pca9685::FrequencyFor ( uint8_t  prescale,
uint32_t  oscillator_hz 
)
constexprnoexcept

The PWM frequency a prescaler gives, rounded to the nearest hertz (equation 1 inverted).

Parameters
prescalePRE_SCALE.
oscillator_hzThe counter clock.
Returns
oscillator / (4096 x (prescale + 1)), rounded.

◆ GetDriverVersion()

constexpr const char * pca9685::GetDriverVersion ( )
constexprnoexcept
Returns
The driver version, e.g. "0.1.0", from the generated pca9685_version.h. No I/O.

◆ GetDriverVersionMajor()

constexpr uint32_t pca9685::GetDriverVersionMajor ( )
constexprnoexcept
Returns
The major version. No I/O.

◆ GetDriverVersionMinor()

constexpr uint32_t pca9685::GetDriverVersionMinor ( )
constexprnoexcept
Returns
The minor version. No I/O.

◆ GetDriverVersionPatch()

constexpr uint32_t pca9685::GetDriverVersionPatch ( )
constexprnoexcept
Returns
The patch version. No I/O.

◆ IsOff()

constexpr bool pca9685::IsOff ( const Pwm &  pwm)
constexprnoexcept

Whether a channel value switches the channel off: LEDn_OFF_H[4] set, which takes precedence over everything else (section 7.3.3).

Parameters
pwmThe value.
Returns
true when the channel is off.

◆ IsValid()

constexpr bool pca9685::IsValid ( const Pwm &  pwm)
constexprnoexcept

Whether a channel value can be written: both counts at most 4095 and, unless a full bit is set, different (the registers "should never be programmed with the same values", section 7.3.4).

Parameters
pwmThe value.
Returns
true when valid.

◆ PrescaleFor()

constexpr Result< uint8_t > pca9685::PrescaleFor ( uint32_t  frequency_hz,
uint32_t  oscillator_hz 
)
constexprnoexcept

The PRE_SCALE value for a frequency, by equation 1 of section 7.3.5, rounded to nearest.

Parameters
frequency_hzThe PWM frequency, 1 to kMaxPwmFrequencyHz.
oscillator_hzThe counter clock, kMinOscillatorHz to kMaxOscillatorHz.
Returns
The prescaler, or InvalidArgument when an argument or the result (3 to 255) is out of range: never clamped (handbook KB-CPP-126).

◆ PulseNsForCounts()

constexpr uint32_t pca9685::PulseNsForCounts ( uint16_t  counts,
uint8_t  prescale,
uint32_t  oscillator_hz 
)
constexprnoexcept

The pulse width of a number of counts, in nanoseconds, rounded to nearest: what a quantised SetPulseWidthUs() programmed.

Parameters
counts0 to 4096.
prescalePRE_SCALE.
oscillator_hzThe counter clock, not 0.
Returns
counts x (prescale + 1) / oscillator, in nanoseconds.

◆ PwmForDuty()

constexpr Result< Pwm > pca9685::PwmForDuty ( uint16_t  duty,
uint16_t  phase = 0U 
)
constexprnoexcept

The channel value for a duty cycle and a phase delay.

The output is asserted from count phase for duty counts, wrapping past 4095 into the next period (section 7.3.3, example 2). Staggering the phase of several channels spreads their switching edges and the supply current surges.

Parameters
duty0 (off) to kFullDuty (on for the whole period).
phase0 to 4095, the delay before the output is asserted.
Returns
The value, or InvalidArgument when either argument is out of range.

◆ PwmFullOn()

constexpr Pwm pca9685::PwmFullOn ( )
constexprnoexcept
Returns
A channel value that is on for the whole period: LEDn_ON_H[4] set.

◆ PwmOff()

constexpr Pwm pca9685::PwmOff ( )
constexprnoexcept
Returns
A channel value that is off: LEDn_OFF_H[4] set, the reset value.

◆ ServoPreset()

constexpr Config pca9685::ServoPreset ( )
constexprnoexcept

Hobby servos and external N-type drivers (figure 13): totem pole, not inverted, so the reset level, low, is off. 50 Hz, a 20 ms period.

Returns
The preset.

◆ ToString()

constexpr const char * pca9685::ToString ( Error  error)
constexprnoexcept

The name of an error, for logs.

Parameters
errorThe error.
Returns
A static string such as "Bus"; "Unknown" for a value that is not an enumerator.

◆ Validate()

constexpr Error pca9685::Validate ( const Config &  config)
constexprnoexcept

Check a configuration without touching the chip.

Fails when an enum holds a value that is not an enumerator, the oscillator is outside kMinOscillatorHz to kMaxOscillatorHz, or the frequency is 0, above kMaxPwmFrequencyHz, or needs a prescaler outside 3 to 255 (section 7.3.5).

Parameters
configThe configuration.
Returns
Error::Ok or Error::InvalidArgument.

Variable Documentation

◆ kAllCallAddress

constexpr uint8_t pca9685::kAllCallAddress = 0x70
inlineconstexpr

The LED All Call address at power-up (ALLCALLADR = E0h): every PCA9685 acknowledges it until MODE1.ALLCALL is cleared, so no chip may use it as its own (section 7.1.2).

◆ kMaxPwmFrequencyHz

constexpr uint32_t pca9685::kMaxPwmFrequencyHz = 10'000U
inlineconstexpr

Highest PWM frequency the arithmetic accepts, in hertz; Validate() then checks that the prescaler is in range, which for the internal oscillator caps it at about 1526 Hz.

◆ kMinOscillatorHz

constexpr uint32_t pca9685::kMinOscillatorHz = 1'000'000U
inlineconstexpr

Lowest Config::oscillator_hz the driver accepts, in hertz (EXTCLK runs from DC; below this no PWM frequency of at least 1 Hz exists).