supla-device
Loading...
Searching...
No Matches
PCA9685.h
1// SPDX-FileCopyrightText: AC SOFTWARE SP. Z O.O.
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6/*
7Version: 25.11.24
8Dependency: https://github.com/RobTillaart/PCA9685_RT
9Use library manager to install it
10*/
11
12#include <PCA9685.h>
13
14#include <supla/io.h>
15#include <supla/mutex.h>
16#include <supla/log_wrapper.h>
17
18namespace Supla {
19namespace Io {
20
21class PCA9685 : public Supla::Io::Base {
22 public:
23 explicit PCA9685(uint8_t address = 0x40,
24 Supla::Mutex *mutex = nullptr,
25 TwoWire *wire = &Wire)
26 : Supla::Io::Base(), pca_(address, wire), mutex_(mutex) {
27 if (!pca_.begin()) {
28 SUPLA_LOG_ERROR("Unable to find PCA9685 at address 0x%x", address);
29 } else {
30 SUPLA_LOG_DEBUG("PCA9685 is connected at address: 0x%x, "
31 "with PWM freq: %d Hz", address, pca_.getFrequency());
32 }
33 }
34
35 void customPinMode(int channelNumber, uint8_t pin, uint8_t mode) override {
36 }
37 void customDigitalWrite(int channelNumber, uint8_t pin,
38 uint8_t val) override {
39 if (mutex_) mutex_->lock();
40 if (pca_.isConnected()) {
41 pca_.write1(pin, val);
42 }
43 if (mutex_) mutex_->unlock();
44 }
45 int customDigitalRead(int channelNumber, uint8_t pin) override {
46 uint8_t val = 0;
47 if (mutex_) mutex_->lock();
48 if (pca_.isConnected()) {
49 val = pca_.read1(pin);
50 }
51 if (mutex_) mutex_->unlock();
52 return (val == 1) ? 1 : 0;
53 }
54 unsigned int customPulseIn(int channelNumber, uint8_t pin, uint8_t value,
55 uint64_t timeoutMicro) override {
56 return 0;
57 }
58 void customAnalogWrite(int channelNumber, uint8_t pin, int val) override {
59 if (mutex_) mutex_->lock();
60 if (pca_.isConnected()) {
61 val = map(val, 0, 1023, 0, 4095);
62 pca_.setPWM(pin, val);
63 }
64 if (mutex_) mutex_->unlock();
65 }
66
67 int customAnalogRead(int channelNumber, uint8_t pin) override {
68 return 0;
69 }
70
71 // Default frequency: 200 Hz
72 void setPWMFrequency(uint16_t frequency) {
73 if (mutex_) mutex_->lock();
74 if (pca_.isConnected()) {
75 pca_.setFrequency(frequency);
76 SUPLA_LOG_DEBUG("[PCA9685] set PWM frequency: %d Hz",
77 pca_.getFrequency());
78 }
79 if (mutex_) mutex_->unlock();
80 }
81
82 protected:
83 ::PCA9685 pca_;
84 Supla::Mutex *mutex_ = nullptr;
85};
86
87}; // namespace Io
88}; // namespace Supla
Definition io.h:23
Definition PCA9685.h:21
Definition mutex.h:9