PCA9685 Driver 0.1.0
API reference
Loading...
Searching...
No Matches
pca9685_types.hpp
Go to the documentation of this file.
1
15#ifndef PCA9685_TYPES_HPP
16#define PCA9685_TYPES_HPP
17
18#include <cstdint>
19
20#include "pca9685_detail.hpp"
21#include "pca9685_registers.hpp"
22#include "pca9685_version.h"
23
25namespace pca9685 {
26
39enum class [[nodiscard]] Error : uint8_t {
40 // Base set: the same names and values in every driver of the org (standards/driver.md).
41 Ok = 0,
42 NotInitialized = 1,
44 InvalidArgument = 2,
46 Bus = 3,
48 Timeout = 4,
51 Crc = 6,
52 Busy = 7,
53 DeviceFault = 8,
54 Unsupported = 9,
55 // Chip-specific values start at 16; each one is returned by some call (tests/test_errors.cpp).
56 WriteMismatch = 16,
59 NoDevice = 17,
63 18,
67 InvalidReply = 19,
70 Asleep = 20,
73 StateUnknown = 21,
78};
79
85constexpr const char* ToString(Error error) noexcept {
86 switch (error) {
87 case Error::Ok:
88 return "Ok";
90 return "NotInitialized";
92 return "InvalidArgument";
93 case Error::Bus:
94 return "Bus";
95 case Error::Timeout:
96 return "Timeout";
98 return "DeviceIdMismatch";
99 case Error::Crc:
100 return "Crc";
101 case Error::Busy:
102 return "Busy";
104 return "DeviceFault";
106 return "Unsupported";
108 return "WriteMismatch";
109 case Error::NoDevice:
110 return "NoDevice";
112 return "DeviceReset";
114 return "InvalidReply";
115 case Error::Asleep:
116 return "Asleep";
118 return "StateUnknown";
120 return "ExternalClockLatched";
121 default:
122 break; // a value made by static_cast from an integer that is not an enumerator
123 }
124 return "Unknown";
125}
126
134template <typename T>
135struct [[nodiscard]] Result {
136 T value{};
137 Error error{Error::Ok};
138
140 [[nodiscard]] constexpr bool ok() const noexcept {
141 return error == Error::Ok;
142 }
144 constexpr explicit operator bool() const noexcept {
145 return ok();
146 }
147
153 static constexpr Result Success(T v) noexcept {
154 return {v, Error::Ok};
155 }
161 static constexpr Result Failure(Error e) noexcept {
162 return {T{}, e};
163 }
164};
165
167template <>
168struct [[nodiscard]] Result<void> {
169 Error error{Error::Ok};
170
172 [[nodiscard]] constexpr bool ok() const noexcept {
173 return error == Error::Ok;
174 }
176 constexpr explicit operator bool() const noexcept {
177 return ok();
178 }
179
181 static constexpr Result Success() noexcept {
182 return {Error::Ok};
183 }
189 static constexpr Result Failure(Error e) noexcept {
190 return {e};
191 }
192};
193
195enum class LogLevel : uint8_t {
196 Error = 0,
197 Warning,
198 Info,
199 Debug,
200};
201
203enum class Verify : uint8_t {
204 None = 0,
205 ReadBack = 1,
207};
208
210enum class OutputDrive : uint8_t {
211 OpenDrain = 0,
212 TotemPole = 1,
213};
214
216enum class ClockSource : uint8_t {
217 Internal = 0,
218 External = 1,
219};
220
222enum class SleepMode : uint8_t {
223 OutputsOff = 0,
225 HoldOutputs = 1,
227};
228
229namespace detail {
231template <>
232struct EnumLast<Verify> {
233 static constexpr Verify kValue = Verify::ReadBack;
234};
236template <>
237struct EnumLast<OutputDrive> {
238 static constexpr OutputDrive kValue = OutputDrive::TotemPole;
239};
241template <>
242struct EnumLast<ClockSource> {
243 static constexpr ClockSource kValue = ClockSource::External;
244};
246template <>
247struct EnumLast<SleepMode> {
248 static constexpr SleepMode kValue = SleepMode::HoldOutputs;
249};
250} // namespace detail
251
253inline constexpr uint8_t kChannelCount = reg::kChannels;
255inline constexpr uint32_t kCountsPerPeriod = 4096U;
257inline constexpr uint16_t kMaxCount = reg::kMaxCount;
259inline constexpr uint16_t kFullDuty = 4096U;
261inline constexpr uint32_t kInternalOscillatorHz = 25'000'000U;
263inline constexpr uint32_t kMaxOscillatorHz = 50'000'000U;
266inline constexpr uint32_t kMinOscillatorHz = 1'000'000U;
269inline constexpr uint32_t kMaxPwmFrequencyHz = 10'000U;
271inline constexpr uint32_t kOscillatorStartUs = 500U;
273inline constexpr uint8_t kMinI2cAddress = 0x40;
275inline constexpr uint8_t kMaxI2cAddress = 0x7F;
278inline constexpr uint8_t kAllCallAddress = 0x70;
279
287struct Pwm {
288 uint16_t on_count{0};
289 uint16_t off_count{0};
291 bool full_on{false};
292 bool full_off{true};
293
295 friend constexpr bool operator==(const Pwm& lhs, const Pwm& rhs) noexcept = default;
296};
297
299constexpr Pwm PwmOff() noexcept {
300 return Pwm{};
301}
302
304constexpr Pwm PwmFullOn() noexcept {
305 return Pwm{.on_count = 0U, .off_count = 0U, .full_on = true, .full_off = false};
306}
307
314constexpr bool IsOff(const Pwm& pwm) noexcept {
315 return pwm.full_off;
316}
317
325constexpr bool IsValid(const Pwm& pwm) noexcept {
326 if ((pwm.on_count > kMaxCount) || (pwm.off_count > kMaxCount)) {
327 return false;
328 }
329 return pwm.full_on || pwm.full_off || (pwm.on_count != pwm.off_count);
330}
331
343constexpr Result<Pwm> PwmForDuty(uint16_t duty, uint16_t phase = 0U) noexcept {
344 if ((duty > kFullDuty) || (phase > kMaxCount)) {
346 }
347 if (duty == 0U) {
349 }
350 if (duty == kFullDuty) {
352 }
353 const uint32_t off = (static_cast<uint32_t>(phase) + static_cast<uint32_t>(duty)) & 0x0FFFU;
354 return Result<Pwm>::Success(Pwm{.on_count = phase,
355 .off_count = static_cast<uint16_t>(off),
356 .full_on = false,
357 .full_off = false});
358}
359
387
398constexpr Error Validate(const Config& config) noexcept;
399
407constexpr Result<uint8_t> PrescaleFor(uint32_t frequency_hz, uint32_t oscillator_hz) noexcept {
408 if ((frequency_hz == 0U) || (frequency_hz > kMaxPwmFrequencyHz) ||
409 (oscillator_hz < kMinOscillatorHz) || (oscillator_hz > kMaxOscillatorHz)) {
411 }
412 // round(osc / (4096 f)) as (osc + 2048 f) / (4096 f): at most 70.5e6, inside uint32_t.
413 const uint32_t divisor = kCountsPerPeriod * frequency_hz;
414 const uint32_t rounded = (oscillator_hz + (divisor / 2U)) / divisor;
415 if ((rounded < (uint32_t{reg::kPreScaleMin} + 1U)) || (rounded > 256U)) {
417 }
418 return Result<uint8_t>::Success(static_cast<uint8_t>(rounded - 1U));
419}
420
427constexpr uint32_t FrequencyFor(uint8_t prescale, uint32_t oscillator_hz) noexcept {
428 const uint32_t divisor = kCountsPerPeriod * (static_cast<uint32_t>(prescale) + 1U);
429 return (oscillator_hz + (divisor / 2U)) / divisor;
430}
431
441constexpr Result<uint16_t> CountsForPulseUs(uint32_t width_us, uint8_t prescale,
442 uint32_t oscillator_hz) noexcept {
443 using detail::operator""_u16;
444 if (width_us == 0U) {
445 return Result<uint16_t>::Success(0_u16);
446 }
447 const uint64_t per_count = 1'000'000ULL * (static_cast<uint64_t>(prescale) + 1ULL);
448 const uint64_t counts =
449 ((static_cast<uint64_t>(width_us) * oscillator_hz) + (per_count / 2ULL)) / per_count;
450 if ((counts == 0ULL) || (counts > kMaxCount)) {
452 }
453 return Result<uint16_t>::Success(static_cast<uint16_t>(counts));
454}
455
464constexpr uint32_t PulseNsForCounts(uint16_t counts, uint8_t prescale,
465 uint32_t oscillator_hz) noexcept {
466 const uint64_t ticks = static_cast<uint64_t>(counts) * (static_cast<uint64_t>(prescale) + 1ULL);
467 const uint64_t osc = (oscillator_hz == 0U) ? 1ULL : static_cast<uint64_t>(oscillator_hz);
468 return static_cast<uint32_t>(((ticks * 1'000'000'000ULL) + (osc / 2ULL)) / osc);
469}
470
471constexpr Error Validate(const Config& config) noexcept {
472 if (!detail::IsEnumerator(config.clock) || !detail::IsEnumerator(config.output_drive)) {
474 }
475 return PrescaleFor(config.pwm_frequency_hz, config.oscillator_hz).error;
476}
477
485constexpr Config DirectLedPreset() noexcept {
486 Config c{};
488 c.invert_outputs = true;
489 c.pwm_frequency_hz = 1000U;
490 return c;
491}
492
498constexpr Config ServoPreset() noexcept {
499 Config c{};
500 c.pwm_frequency_hz = 50U;
501 return c;
502}
503
504// The arithmetic and the presets, proved at build time (KB-CPP20-012).
505static_assert(Validate(Config{}) == Error::Ok);
506static_assert(Validate(DirectLedPreset()) == Error::Ok);
507static_assert(Validate(ServoPreset()) == Error::Ok);
508// Equation 2: 200 Hz from 25 MHz is 0x1E, the reset value of PRE_SCALE.
509static_assert(PrescaleFor(200U, kInternalOscillatorHz).value == reg::kPreScaleReset);
510// 1526 Hz is PRE_SCALE 3 and PRE_SCALE 255 gives 24 Hz (section 7.3.5); 1800 Hz and 23 Hz do not
511// fit.
512static_assert(PrescaleFor(1526U, kInternalOscillatorHz).value == 3U);
513static_assert(FrequencyFor(0xFFU, kInternalOscillatorHz) == 24U);
514static_assert(PrescaleFor(24U, kInternalOscillatorHz).value == 253U);
515static_assert(!PrescaleFor(1800U, kInternalOscillatorHz).ok());
516static_assert(!PrescaleFor(23U, kInternalOscillatorHz).ok());
517static_assert(!PrescaleFor(0U, kInternalOscillatorHz).ok());
519// 50 Hz: PRE_SCALE 121; 1.5 ms is 307 counts of 4.88 us.
520static_assert(PrescaleFor(50U, kInternalOscillatorHz).value == 121U);
521static_assert(CountsForPulseUs(1500U, 121U, kInternalOscillatorHz).value == 307U);
522static_assert(PulseNsForCounts(307U, 121U, kInternalOscillatorHz) == 1'498'160U);
523static_assert(!CountsForPulseUs(30'000U, 121U, kInternalOscillatorHz).ok());
524// Example 1 of section 7.3.3: a 10 % delay (409) and a 20 % duty (819) end at count 1228.
525static_assert(PwmForDuty(819U, 409U).value.off_count == 1228U);
526// Example 2: a 90 % delay (3685) and a 90 % duty (3686) wrap to 3275.
527static_assert(PwmForDuty(3686U, 3685U).value.off_count == 3275U);
528static_assert(IsOff(PwmForDuty(0U).value) && PwmForDuty(kFullDuty).value.full_on);
529static_assert(!PwmForDuty(kFullDuty + 1U).ok() && !PwmForDuty(1U, 4096U).ok());
530static_assert(IsValid(Pwm{}) && IsValid(PwmFullOn()) && !IsValid(Pwm{.full_off = false}) &&
531 !IsValid(Pwm{.on_count = 4096U}));
532
537void ConfigIsInvalid() noexcept;
538
547public:
552 consteval explicit CheckedConfig(const Config& config) noexcept : config_(config) {
553 if (Validate(config) != Error::Ok) {
555 }
556 }
558 [[nodiscard]] constexpr const Config& Get() const& noexcept {
559 return config_;
560 }
562 void Get() const&& = delete;
563
564private:
565 Config config_;
566};
567
569constexpr const char* GetDriverVersion() noexcept {
570 return PCA9685_VERSION_STRING;
571}
573constexpr uint32_t GetDriverVersionMajor() noexcept {
574 return PCA9685_VERSION_MAJOR;
575}
577constexpr uint32_t GetDriverVersionMinor() noexcept {
578 return PCA9685_VERSION_MINOR;
579}
581constexpr uint32_t GetDriverVersionPatch() noexcept {
582 return PCA9685_VERSION_PATCH;
583}
584
587} // namespace pca9685
588
589#endif // PCA9685_TYPES_HPP
A configuration proven valid at build time.
Definition pca9685_types.hpp:546
constexpr const Config & Get() const &noexcept
Definition pca9685_types.hpp:558
consteval CheckedConfig(const Config &config) noexcept
Check config at build time.
Definition pca9685_types.hpp:552
void Get() const &&=delete
Not on a temporary: the reference would dangle (KB-CPP20-044).
constexpr uint8_t kPreScaleReset
30: about 200 Hz from the 25 MHz oscillator.
Definition pca9685_registers.hpp:101
constexpr uint8_t kChannels
Number of LED channels.
Definition pca9685_registers.hpp:47
constexpr uint16_t kMaxCount
Highest LEDn_ON and LEDn_OFF count: the 12-bit counter runs 0 to 4095 (section 7.3....
Definition pca9685_registers.hpp:96
constexpr uint8_t kPreScaleMin
The hardware forces at least 3 (1526 Hz).
Definition pca9685_registers.hpp:102
constexpr uint32_t FrequencyFor(uint8_t prescale, uint32_t oscillator_hz) noexcept
The PWM frequency a prescaler gives, rounded to the nearest hertz (equation 1 inverted).
Definition pca9685_types.hpp:427
constexpr Config DirectLedPreset() noexcept
LEDs wired from the supply through a resistor to the outputs (figure 15): open drain,...
Definition pca9685_types.hpp:485
constexpr uint32_t GetDriverVersionMinor() noexcept
Definition pca9685_types.hpp:577
constexpr Error Validate(const Config &config) noexcept
Check a configuration without touching the chip.
Definition pca9685_types.hpp:471
constexpr uint32_t GetDriverVersionPatch() noexcept
Definition pca9685_types.hpp:581
constexpr Result< uint8_t > 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.
Definition pca9685_types.hpp:407
constexpr uint32_t 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 SetPulseW...
Definition pca9685_types.hpp:464
constexpr bool IsOff(const Pwm &pwm) noexcept
Whether a channel value switches the channel off: LEDn_OFF_H[4] set, which takes precedence over ever...
Definition pca9685_types.hpp:314
constexpr Config ServoPreset() noexcept
Hobby servos and external N-type drivers (figure 13): totem pole, not inverted, so the reset level,...
Definition pca9685_types.hpp:498
constexpr uint8_t kChannelCount
Number of PWM channels, LED0 to LED15.
Definition pca9685_types.hpp:253
LogLevel
Severity passed to the optional Log() hook.
Definition pca9685_types.hpp:195
constexpr const char * ToString(Error error) noexcept
The name of an error, for logs.
Definition pca9685_types.hpp:85
constexpr uint8_t kMinI2cAddress
Lowest I2C address of a PCA9685: 1 A5 A4 A3 A2 A1 A0 with every pin low (figure 4).
Definition pca9685_types.hpp:273
constexpr Result< Pwm > PwmForDuty(uint16_t duty, uint16_t phase=0U) noexcept
The channel value for a duty cycle and a phase delay.
Definition pca9685_types.hpp:343
constexpr uint8_t kMaxI2cAddress
Highest I2C address of a PCA9685, every address pin high.
Definition pca9685_types.hpp:275
constexpr uint32_t kMaxOscillatorHz
Highest EXTCLK frequency, in hertz (table 15, f_EXTCLK).
Definition pca9685_types.hpp:263
constexpr Result< uint16_t > 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....
Definition pca9685_types.hpp:441
ClockSource
The clock the PWM counter runs from (MODE1.EXTCLK, table 5).
Definition pca9685_types.hpp:216
constexpr uint16_t kFullDuty
SetDuty() value for a channel that is on for the whole period (full ON).
Definition pca9685_types.hpp:259
constexpr uint32_t kOscillatorStartUs
Oscillator start-up after SLEEP is cleared, in microseconds (table 5, note 2: 500 us maximum).
Definition pca9685_types.hpp:271
SleepMode
What Sleep() does with the outputs (section 7.3.1.1).
Definition pca9685_types.hpp:222
OutputDrive
The output stage of all 16 outputs (MODE2.OUTDRV, table 6).
Definition pca9685_types.hpp:210
void ConfigIsInvalid() noexcept
Reached only when a CheckedConfig is built from an invalid configuration: it is never defined,...
constexpr const char * GetDriverVersion() noexcept
Definition pca9685_types.hpp:569
constexpr uint32_t GetDriverVersionMajor() noexcept
Definition pca9685_types.hpp:573
constexpr Pwm PwmOff() noexcept
Definition pca9685_types.hpp:299
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition pca9685_types.hpp:39
constexpr uint32_t kMaxPwmFrequencyHz
Definition pca9685_types.hpp:269
constexpr uint32_t kInternalOscillatorHz
Typical frequency of the internal oscillator, in hertz (section 2, table 5).
Definition pca9685_types.hpp:261
constexpr uint32_t kMinOscillatorHz
Definition pca9685_types.hpp:266
constexpr Pwm PwmFullOn() noexcept
Definition pca9685_types.hpp:304
constexpr uint16_t kMaxCount
Highest ON or OFF count, 4095.
Definition pca9685_types.hpp:257
constexpr bool IsValid(const Pwm &pwm) noexcept
Whether a channel value can be written: both counts at most 4095 and, unless a full bit is set,...
Definition pca9685_types.hpp:325
Verify
Whether a call reads back what it wrote (handbook KB-ARCH-041).
Definition pca9685_types.hpp:203
constexpr uint8_t kAllCallAddress
Definition pca9685_types.hpp:278
constexpr uint32_t kCountsPerPeriod
Counter steps per PWM period: 4096 (12 bits, section 7.3.3).
Definition pca9685_types.hpp:255
@ Warning
Something unexpected that the driver recovered from.
@ Info
Lifecycle events: initialised, reset found.
@ Debug
Detail for bring-up.
@ 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.
@ OpenDrain
Sink only. Needed for LEDs with integrated Zener diodes (section 10, Q5).
@ TotemPole
Sink 25 mA, source 10 mA. Reset value.
@ Crc
Not returned by this driver (I2C transfers carry no CRC).
@ DeviceFault
Not returned by this driver (the chip reports no faults).
@ Ok
The call succeeded.
@ Unsupported
The port has no output-enable GpioSet() hook, which this call needs.
@ Timeout
Not returned by this driver (no wait polls the chip).
@ Busy
Not returned by this driver (the chip has no busy state).
@ None
Write only. Default.
The PCA9685 driver: everything it declares lives here; internals in detail.
Definition pca9685.hpp:30
Compile-time helpers of the PCA9685 driver: typed integer literals, exact hook matching,...
PCA9685 register map: addresses, bit fields and reset values (datasheet section 7....
Everything EnsureInitialized() writes to the chip.
Definition pca9685_types.hpp:377
bool invert_outputs
MODE2.INVRT. Reset value: not inverted.
Definition pca9685_types.hpp:385
uint32_t pwm_frequency_hz
Definition pca9685_types.hpp:378
uint32_t oscillator_hz
Definition pca9685_types.hpp:380
OutputDrive output_drive
MODE2.OUTDRV. Reset value: totem pole.
Definition pca9685_types.hpp:384
ClockSource clock
MODE1.EXTCLK. Reset value: internal.
Definition pca9685_types.hpp:383
The value of one channel: its four registers, decoded (table 7, figure 9).
Definition pca9685_types.hpp:287
bool full_on
LEDn_ON_H[4].
Definition pca9685_types.hpp:291
uint16_t off_count
Definition pca9685_types.hpp:289
friend constexpr bool operator==(const Pwm &lhs, const Pwm &rhs) noexcept=default
Exact comparison of every field (integral members only, KB-CPP20-033).
bool full_off
LEDn_OFF_H[4]. Reset value: set.
Definition pca9685_types.hpp:292
uint16_t on_count
LEDn_ON[11:0], 0 to 4095.
Definition pca9685_types.hpp:288
static constexpr Result Success() noexcept
Definition pca9685_types.hpp:181
static constexpr Result Failure(Error e) noexcept
A failed result.
Definition pca9685_types.hpp:189
constexpr bool ok() const noexcept
Definition pca9685_types.hpp:172
The value of a call, or why there is none.
Definition pca9685_types.hpp:135
constexpr bool ok() const noexcept
Definition pca9685_types.hpp:140
static constexpr Result Success(T v) noexcept
A successful result.
Definition pca9685_types.hpp:153
static constexpr Result Failure(Error e) noexcept
A failed result.
Definition pca9685_types.hpp:161