|
21 | 21 | #include "AppConfig.h"
|
22 | 22 | #include "LogUtils.h"
|
23 | 23 |
|
| 24 | +#include <drivers/pwm.h> |
24 | 25 | #include <zephyr.h>
|
25 | 26 |
|
26 | 27 | LightingManager LightingManager::sLight;
|
27 | 28 |
|
28 |
| -int LightingManager::Init(const char * gpioDeviceName, gpio_pin_t gpioPin) |
| 29 | +int LightingManager::Init(const char * pwmDeviceName, uint32_t pwmChannel) |
29 | 30 | {
|
30 | 31 | // We use a gpioPin instead of a LEDWidget here because we want to use PWM
|
31 | 32 | // and other features instead of just on/off.
|
32 | 33 |
|
33 | 34 | mState = kState_On;
|
34 |
| - mGPIOPin = gpioPin; |
35 |
| - mGPIODevice = const_cast<device *>(device_get_binding(gpioDeviceName)); |
| 35 | + mLevel = kMaxLevel; |
| 36 | + mPwmDevice = device_get_binding(pwmDeviceName); |
| 37 | + mPwmChannel = pwmChannel; |
36 | 38 |
|
37 |
| - if (!mGPIODevice) |
| 39 | + if (!mPwmDevice) |
38 | 40 | {
|
39 |
| - LOG_ERR("Cannot find GPIO port %s", LOG_STRDUP(gpioDeviceName)); |
| 41 | + LOG_ERR("Cannot find PWM device %s", LOG_STRDUP(pwmDeviceName)); |
40 | 42 | return -ENODEV;
|
41 | 43 | }
|
42 | 44 |
|
43 |
| - int res = gpio_pin_configure(mGPIODevice, mGPIOPin, GPIO_OUTPUT); |
44 |
| - if (res != 0) |
45 |
| - { |
46 |
| - LOG_ERR("Cannot configure GPIO pin"); |
47 |
| - return res; |
48 |
| - } |
49 |
| - |
50 | 45 | Set(false);
|
51 | 46 | return 0;
|
52 | 47 | }
|
@@ -74,7 +69,7 @@ bool LightingManager::InitiateAction(Action_t aAction, int32_t aActor, uint8_t s
|
74 | 69 | action_initiated = true;
|
75 | 70 | new_state = kState_Off;
|
76 | 71 | }
|
77 |
| - else if (aAction == LEVEL_ACTION) |
| 72 | + else if (aAction == LEVEL_ACTION && *value != mLevel) |
78 | 73 | {
|
79 | 74 | action_initiated = true;
|
80 | 75 | if (*value == 0)
|
@@ -114,20 +109,20 @@ bool LightingManager::InitiateAction(Action_t aAction, int32_t aActor, uint8_t s
|
114 | 109 |
|
115 | 110 | void LightingManager::SetLevel(uint8_t aLevel)
|
116 | 111 | {
|
117 |
| - LOG_INF("LEVEL %u", aLevel); |
118 |
| - // TODO: use the level for PWM |
| 112 | + LOG_INF("Setting brightness level to %u", aLevel); |
| 113 | + mLevel = aLevel; |
| 114 | + UpdateLight(); |
119 | 115 | }
|
120 | 116 |
|
121 | 117 | void LightingManager::Set(bool aOn)
|
122 | 118 | {
|
123 |
| - if (aOn) |
124 |
| - { |
125 |
| - mState = kState_On; |
126 |
| - gpio_pin_set_raw(mGPIODevice, mGPIOPin, 0); |
127 |
| - } |
128 |
| - else |
129 |
| - { |
130 |
| - mState = kState_Off; |
131 |
| - gpio_pin_set_raw(mGPIODevice, mGPIOPin, 1); |
132 |
| - } |
| 119 | + mState = aOn ? kState_On : kState_Off; |
| 120 | + UpdateLight(); |
| 121 | +} |
| 122 | + |
| 123 | +void LightingManager::UpdateLight() |
| 124 | +{ |
| 125 | + constexpr uint32_t kPwmWidthUs = 1000u; |
| 126 | + const uint8_t level = mState == kState_On ? mLevel : 0; |
| 127 | + pwm_pin_set_usec(mPwmDevice, mPwmChannel, kPwmWidthUs, kPwmWidthUs * level / kMaxLevel, 0); |
133 | 128 | }
|
0 commit comments