PCA9685 Driver 0.1.0
API reference
Loading...
Searching...
No Matches
pca9685.hpp
Go to the documentation of this file.
1
15#ifndef PCA9685_HPP
16#define PCA9685_HPP
17
18#include <algorithm>
19#include <array>
20#include <cstddef>
21#include <cstdint>
22#include <span>
23
24#include "pca9685_detail.hpp"
26#include "pca9685_registers.hpp"
27#include "pca9685_types.hpp"
28#include "pca9685_version.h"
29
30namespace pca9685 {
31
32namespace detail {
33
34// Register encoders and decoders: free constexpr functions, emitted once whatever the port type,
35// and proved below with static_assert (KB-CPP20-009, -012).
36
38[[nodiscard]] constexpr std::array<uint8_t, 4> EncodePwm(const Pwm& pwm) noexcept {
39 const auto on = static_cast<uint32_t>(pwm.on_count) & 0x0FFFU;
40 const auto off = static_cast<uint32_t>(pwm.off_count) & 0x0FFFU;
41 const uint32_t on_full = pwm.full_on ? static_cast<uint32_t>(reg::kLedFull) : 0U;
42 const uint32_t off_full = pwm.full_off ? static_cast<uint32_t>(reg::kLedFull) : 0U;
43 return {static_cast<uint8_t>(on & 0xFFU), static_cast<uint8_t>((on >> 8U) | on_full),
44 static_cast<uint8_t>(off & 0xFFU), static_cast<uint8_t>((off >> 8U) | off_full)};
45}
46
52[[nodiscard]] constexpr Result<Pwm> DecodePwm(std::span<const uint8_t, 4> b) noexcept {
53 const auto on_h = static_cast<uint32_t>(b[1]);
54 const auto off_h = static_cast<uint32_t>(b[3]);
55 const auto reserved = static_cast<uint32_t>(reg::kLedHReserved);
56 if (((on_h & reserved) != 0U) || ((off_h & reserved) != 0U)) {
58 }
59 const auto high = static_cast<uint32_t>(reg::kLedCountHigh);
60 const auto full = static_cast<uint32_t>(reg::kLedFull);
61 return Result<Pwm>::Success(Pwm{.on_count = static_cast<uint16_t>(((on_h & high) << 8U) | b[0]),
62 .off_count = static_cast<uint16_t>(((off_h & high) << 8U) | b[2]),
63 .full_on = (on_h & full) != 0U,
64 .full_off = (off_h & full) != 0U});
65}
66
70[[nodiscard]] constexpr uint32_t OffLevelOutne(const Config& c) noexcept {
71 if (!c.invert_outputs) {
72 return reg::kOutneLow;
73 }
75}
76
78[[nodiscard]] constexpr uint8_t Mode2Value(const Config& c) noexcept {
79 uint32_t v = 0U;
80 if (c.invert_outputs) {
81 v |= static_cast<uint32_t>(reg::kMode2Invrt);
82 }
84 v |= static_cast<uint32_t>(reg::kMode2OutDrv);
85 }
86 return reg::Mode2Outne::Insert(static_cast<uint8_t>(v), OffLevelOutne(c));
87}
88
91[[nodiscard]] constexpr uint8_t Mode1Awake(const Config& c) noexcept {
92 return (c.clock == ClockSource::External)
93 ? static_cast<uint8_t>(static_cast<uint32_t>(reg::kMode1Ai) |
94 static_cast<uint32_t>(reg::kMode1ExtClk))
96}
97
101inline constexpr uint8_t kSubAdr1Sentinel = 0x5A;
102static_assert((kSubAdr1Sentinel & 0x01U) == 0U);
103
105[[nodiscard]] constexpr uint8_t With(uint8_t mode1, uint8_t bits) noexcept {
106 return static_cast<uint8_t>(static_cast<uint32_t>(mode1) | static_cast<uint32_t>(bits));
107}
108
110[[nodiscard]] constexpr bool Has(uint8_t value, uint8_t bits) noexcept {
111 return (static_cast<uint32_t>(value) & static_cast<uint32_t>(bits)) != 0U;
112}
113
115[[nodiscard]] constexpr uint16_t ChannelBit(uint32_t channel) noexcept {
116 return static_cast<uint16_t>(uint32_t{1} << (channel & 0x0FU));
117}
118
120[[nodiscard]] constexpr uint16_t ChannelRange(uint32_t first, uint32_t count) noexcept {
121 uint32_t mask = 0U;
122 for (uint32_t i = 0U; i < reg::kChannels; ++i) {
123 if ((i >= first) && (i < (first + count))) {
124 mask |= uint32_t{1} << i;
125 }
126 }
127 return static_cast<uint16_t>(mask);
128}
129
130// The reset configuration encodes to the reset value of MODE2; the encoders round-trip
131// (KB-CPP20-012).
132static_assert(Mode2Value(Config{}) == reg::kMode2Reset);
133static_assert(Mode2Value(DirectLedPreset()) == 0x12U);
134static_assert(EncodePwm(PwmOff())[3] == reg::kLedOffHReset);
135static_assert(DecodePwm(EncodePwm(PwmForDuty(819U, 409U).value)).value ==
136 PwmForDuty(819U, 409U).value);
137static_assert(DecodePwm(EncodePwm(PwmFullOn())).value == PwmFullOn());
138static_assert(DecodePwm(std::array<uint8_t, 4>{0xFFU, 0xFFU, 0xFFU, 0xFFU}).error ==
140static_assert(DecodePwm(std::array<uint8_t, 4>{0U, 0U, 0U, 0U}).ok());
141static_assert((ChannelRange(14U, 4U) == 0xC000U) && (ChannelBit(3U) == 0x0008U));
142
143} // namespace detail
144
151// clang-format off: the hook table below must keep one row per line.
217// clang-format on
218template <I2cPort Port>
219class PCA9685 {
220 static_assert(
221 !detail::DeclaresDelayUs<Port> || detail::HasDelayUs<Port>,
222 "pca9685: the DelayUs hook must be `void DelayUs(uint32_t us) noexcept`, so that no "
223 "wait is truncated");
224 static_assert(!detail::DeclaresGpioSet<Port> || detail::HasGpioSet<Port>,
225 "pca9685: the optional GpioSet hook must be `bool GpioSet(CtrlPin, GpioSignal) "
226 "noexcept`, so that a failed OE write is reported");
227 static_assert(!detail::DeclaresGetLastFailure<Port> || detail::HasGetLastFailure<Port>,
228 "pca9685: the optional GetLastFailure hook must be `bool "
229 "GetLastFailure(I2cFailure& failure) noexcept`");
230 static_assert(!detail::DeclaresLog<Port> || detail::HasLog<Port>,
231 "pca9685: the optional Log hook must be `void Log(LogLevel, const char* message) "
232 "noexcept`");
233
234public:
243 explicit PCA9685(Port& port, uint8_t address = kI2cAddress, const Config& config = {}) noexcept
244 : bus_(port, address), config_(config) {}
245
247 PCA9685(const PCA9685&) = delete;
249 PCA9685& operator=(const PCA9685&) = delete;
250
253
284
287 [[nodiscard]] bool IsInitialized() const noexcept {
288 return initialized_;
289 }
290
306
315 Result<void> ApplyConfig(const Config& config) noexcept;
316
319 [[nodiscard]] const Config& GetConfig() const& noexcept {
320 return config_;
321 }
323 void GetConfig() const&& = delete;
324
326 [[nodiscard]] uint8_t GetAddress() const noexcept {
327 return bus_.GetAddress();
328 }
329
344
348
364 Result<void> SetPwm(uint8_t channel, const Pwm& value, Verify verify = Verify::None) noexcept;
365
374 Result<void> SetDuty(uint8_t channel, uint16_t duty, uint16_t phase = 0U,
375 Verify verify = Verify::None) noexcept;
376
391 Result<uint32_t> SetPulseWidthUs(uint8_t channel, uint32_t width_us,
392 Verify verify = Verify::None) noexcept;
393
400 Result<void> SetFullOn(uint8_t channel, Verify verify = Verify::None) noexcept;
401
411 Result<void> SetChannelOff(uint8_t channel, Verify verify = Verify::None) noexcept;
412
425 Result<void> SetChannels(uint8_t first, std::span<const Pwm> values) noexcept;
426
435 Result<void> SetChannelsOff(uint16_t mask) noexcept;
436
442 Result<void> SetAllOff() noexcept;
443
450 [[nodiscard]] Result<Pwm> GetChannel(uint8_t channel) const noexcept;
451
454 [[nodiscard]] uint16_t GetUncertainChannels() const noexcept {
455 return uncertain_;
456 }
457
467 Result<Pwm> ReadChannel(uint8_t channel) noexcept;
468
475
479
487 Result<void> DisableOutputs() noexcept;
488
495 Result<void> EnableOutputs() noexcept;
496
500
514 Result<void> SetPwmFrequency(uint32_t frequency_hz) noexcept;
515
520 [[nodiscard]] Result<uint8_t> GetPrescale() const noexcept;
521
526 [[nodiscard]] Result<uint32_t> GetPwmFrequencyHz() const noexcept;
527
532 Result<uint8_t> ReadPrescale() noexcept;
533
547 Result<void> Sleep(SleepMode mode = SleepMode::OutputsOff) noexcept;
548
560 Result<void> Wake() noexcept;
561
564 [[nodiscard]] bool MayBeAsleep() const noexcept {
565 return asleep_maybe_;
566 }
567
571
582 Result<uint8_t> ReadRegister(uint8_t address) noexcept;
583
586 [[nodiscard]] uint8_t GetLastMode1() const noexcept {
587 return last_mode1_;
588 }
589
591 [[nodiscard]] uint8_t GetLastMode2() const noexcept {
592 return last_mode2_;
593 }
594
596
597private:
598 Result<void> initialize() noexcept;
599 Error enterSafeState() noexcept;
600 Result<void> configureClock() noexcept;
601 Result<void> checkIdentity() noexcept;
602 Result<void> setOutputEnable(GpioSignal signal) noexcept;
603 Result<void> applyOne(uint8_t channel, const Pwm& value, Verify verify) noexcept;
604 Result<void> switchOff(uint8_t channel, Verify verify) noexcept;
605 Result<void> switchOn(uint8_t channel, const Pwm& value, Verify verify) noexcept;
606 Result<void> writeOffs(uint8_t first, std::span<const Pwm> values) noexcept;
607 Result<void> writeChannels(uint8_t first, std::span<const Pwm> values) noexcept;
608 Result<void> writeAllOff() noexcept;
609 Result<void> writeOff(uint8_t channel) noexcept;
610 void markAllOff() noexcept;
611 Result<void> afterSwitchOff(Result<void> written, uint8_t first, uint8_t count,
612 Verify verify) noexcept;
613 Result<void> readBack(uint8_t first, uint8_t count) noexcept;
614 Result<void> readChannelsInto(uint8_t first, std::span<Pwm> out) noexcept;
615 Result<std::array<uint8_t, 3>> readModeBytes() noexcept;
616 Result<void> checkZeroBurst(std::span<const uint8_t> window) noexcept;
617 [[nodiscard]] bool addressValid() const noexcept;
618 [[nodiscard]] bool looksReset(const std::array<uint8_t, 3>& modes) const noexcept;
619 Result<uint8_t> readModes() noexcept;
620 Result<uint8_t> verifyRunning() noexcept;
621 Result<void> completeWakeCheck() noexcept;
622 Result<void> wakeSequence() noexcept;
623 void awakeConfirmed() noexcept;
624 Result<void> changePrescale(uint8_t prescale) noexcept;
625 Result<uint8_t> readByte(uint8_t reg) noexcept;
626 Error writeByte(uint8_t reg, uint8_t value) noexcept;
627 Result<void> markReset() noexcept;
628 Result<void> fail(Error error, const char* message) noexcept;
629
630 detail::RegisterBus<Port> bus_;
631 Config config_{};
632 std::array<Pwm, kChannelCount> channels_{};
633 uint16_t uncertain_{0};
634 uint8_t mode1_{0};
635 uint8_t mode2_{0};
636 uint8_t prescale_{reg::kPreScaleReset};
637 uint8_t last_mode1_{0};
638 uint8_t last_mode2_{0};
639 bool prescale_known_{false};
640 bool asleep_maybe_{false};
641 bool held_maybe_{false};
642 bool wake_check_pending_{false};
643 bool wake_acked_{false};
644 bool initialized_{false};
645 bool started_once_{false};
646};
647
650} // namespace pca9685
651
652// codeql::misra_deviation_next_line(MD-CPP-009)
653#include "../src/pca9685.ipp" // IWYU pragma: export
654
655#endif // PCA9685_HPP
Driver for one PCA9685 on a platform port.
Definition pca9685.hpp:219
Result< void > DisableOutputs() noexcept
Drive OE high: every output goes to the MODE2.OUTNE level, which the driver makes the level of a chan...
Result< void > SetPwmFrequency(uint32_t frequency_hz) noexcept
Change the PWM frequency of all channels (PRE_SCALE, section 7.3.5).
Result< void > EnsureInitialized() noexcept
Start the chip on the first call. Once it has succeeded, a later call runs the reset check (one 3-byt...
bool MayBeAsleep() const noexcept
Definition pca9685.hpp:564
Result< void > SetAllOff() noexcept
Switch every channel off with one data byte, ALL_LED_OFF_H = 0x10 (figure 24, the orderly shutdown of...
Result< Pwm > ReadChannel(uint8_t channel) noexcept
Read one channel from the chip into the driver's copy: one 3-byte read of MODE1, MODE2 and SUBADR1 (t...
const Config & GetConfig() const &noexcept
Definition pca9685.hpp:319
Result< void > SetChannels(uint8_t first, std::span< const Pwm > values) noexcept
Set values.size() consecutive channels from first in one transfer, so that with OCH = 0 they change t...
Result< void > Deinitialize() noexcept
Switch every channel off and put the chip to sleep, its low-power safe state, and mark the driver uni...
Result< void > SetPwm(uint8_t channel, const Pwm &value, Verify verify=Verify::None) noexcept
Set one channel to a value: one 4-byte write (LEDn_ON_L to LEDn_OFF_H), or for an off value the one b...
Result< uint8_t > GetPrescale() const noexcept
The prescaler the driver last wrote and read back. No I/O.
Result< void > Wake() noexcept
Start the oscillator and the channels again (section 7.3.1.1).
Result< uint32_t > GetPwmFrequencyHz() const noexcept
The PWM frequency of the programmed prescaler, rounded to the nearest hertz. No I/O.
PCA9685(const PCA9685 &)=delete
One driver object per chip.
uint8_t GetLastMode2() const noexcept
Definition pca9685.hpp:591
Result< void > SetChannelsOff(uint16_t mask) noexcept
Switch off every channel in mask (bit n = channel n), one data byte per channel (LEDn_OFF_H = 0x10)....
uint16_t GetUncertainChannels() const noexcept
Definition pca9685.hpp:454
Result< void > SetFullOn(uint8_t channel, Verify verify=Verify::None) noexcept
Switch one channel fully on (LEDn_ON_H bit 4), as SetPwm(channel, PwmFullOn()).
Result< uint8_t > ReadPrescale() noexcept
Read PRE_SCALE into the driver's copy: the reset check, then a 1-byte read.
Result< void > CheckForReset() noexcept
Find out whether the chip reset since the start: one 3-byte read of MODE1, MODE2 and SUBADR1 (about 9...
PCA9685 & operator=(const PCA9685 &)=delete
One driver object per chip.
uint8_t GetAddress() const noexcept
Definition pca9685.hpp:326
Result< uint8_t > ReadRegister(uint8_t address) noexcept
Read one register once: one transfer, no retry, no check (handbook KB-CPP-129).
PCA9685(Port &port, uint8_t address=kI2cAddress, const Config &config={}) noexcept
Bind the driver to a port, a 7-bit I2C address and a configuration. No I/O, no checks: EnsureInitiali...
Definition pca9685.hpp:243
Result< Pwm > GetChannel(uint8_t channel) const noexcept
The value the driver last wrote to or read from a channel. No I/O.
Result< void > SetDuty(uint8_t channel, uint16_t duty, uint16_t phase=0U, Verify verify=Verify::None) noexcept
Set one channel to a duty cycle with a phase delay (PwmForDuty()), as SetPwm().
void GetConfig() const &&=delete
Not on a temporary driver: the reference would dangle (handbook KB-CPP20-044).
Result< std::array< Pwm, kChannelCount > > ReadChannels() noexcept
Read all 16 channels into the driver's copy: the reset check, then one 64-byte read....
bool IsInitialized() const noexcept
Definition pca9685.hpp:287
Result< void > EnableOutputs() noexcept
Drive OE low: the outputs follow their channels again. A switch-on of every channel at once,...
Result< void > SetChannelOff(uint8_t channel, Verify verify=Verify::None) noexcept
Switch one channel off (LEDn_OFF_H bit 4), as SetPwm(channel, PwmOff()). Never refused.
uint8_t GetLastMode1() const noexcept
Definition pca9685.hpp:586
Result< void > ApplyConfig(const Config &config) noexcept
Replace the configuration. When initialised, run the whole start-up of EnsureInitialized() again with...
Result< void > Sleep(SleepMode mode=SleepMode::OutputsOff) noexcept
Stop the oscillator (MODE1.SLEEP = 1): the low-power mode (section 7.3.1).
Result< uint32_t > SetPulseWidthUs(uint8_t channel, uint32_t width_us, Verify verify=Verify::None) noexcept
Set one channel to a pulse of width_us at the start of each period, as SetPwm().
constexpr uint8_t kPreScaleReset
30: about 200 Hz from the 25 MHz oscillator.
Definition pca9685_registers.hpp:101
constexpr uint32_t kOutneHiZ
OUTNE = 10: LEDn = high impedance.
Definition pca9685_registers.hpp:89
constexpr uint8_t kMode1Ai
AI: register auto-increment.
Definition pca9685_registers.hpp:68
constexpr uint8_t kLedOffHReset
LEDn_OFF_H after a reset: full OFF (table 7). The other three bytes reset to 0.
Definition pca9685_registers.hpp:98
constexpr uint8_t kChannels
Number of LED channels.
Definition pca9685_registers.hpp:47
constexpr uint8_t kMode2OutDrv
Definition pca9685_registers.hpp:81
constexpr uint32_t kOutneLow
OUTNE = 00: LEDn = 0.
Definition pca9685_registers.hpp:86
constexpr uint8_t kLedHReserved
Bits 7..5 of the _H bytes: read only, read 0.
Definition pca9685_registers.hpp:92
constexpr uint8_t kLedFull
Bit 4: full ON (ON_H) or full OFF (OFF_H).
Definition pca9685_registers.hpp:93
constexpr uint8_t kMode2Reset
MODE2 after a reset: change on STOP, totem pole, not inverted, LEDn = 0 when OE = 1.
Definition pca9685_registers.hpp:83
constexpr uint8_t kMode2Invrt
INVRT: output logic inverted (OE = 0 only).
Definition pca9685_registers.hpp:79
constexpr uint8_t kMode1ExtClk
EXTCLK: use the EXTCLK pin; sticky.
Definition pca9685_registers.hpp:67
constexpr uint32_t kOutneHigh
OUTNE = 01: LEDn = 1 (totem pole), Hi-Z (open drain).
Definition pca9685_registers.hpp:87
constexpr uint8_t kLedCountHigh
Definition pca9685_registers.hpp:94
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 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
SleepMode
What Sleep() does with the outputs (section 7.3.1.1).
Definition pca9685_types.hpp:222
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 Pwm PwmFullOn() noexcept
Definition pca9685_types.hpp:304
Verify
Whether a call reads back what it wrote (handbook KB-ARCH-041).
Definition pca9685_types.hpp:203
@ External
The EXTCLK pin, DC to 50 MHz; sticky until a power cycle or software reset.
@ TotemPole
Sink 25 mA, source 10 mA. Reset value.
@ None
Write only. Default.
The PCA9685 driver: everything it declares lives here; internals in detail.
Definition pca9685.hpp:30
constexpr uint8_t kI2cAddress
7-bit I2C address with A5 to A0 low, 1000000 (section 7.1.1, figure 4); the pins add 0 to 63.
Definition pca9685_i2c_interface.hpp:52
GpioSignal
Logical level of a control pin; the port maps it to the physical polarity.
Definition pca9685_i2c_interface.hpp:68
Compile-time helpers of the PCA9685 driver: typed integer literals, exact hook matching,...
The I2C port of the PCA9685 driver: the bus requirements, the CRTP base, the I2cPort concept,...
PCA9685 register map: addresses, bit fields and reset values (datasheet section 7....
Public types of the PCA9685 driver: errors, Result<T>, channel values, configuration,...
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
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
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
The value of a call, or why there is none.
Definition pca9685_types.hpp:135
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