MycilaJSY 13.0.0
Arduino / ESP32 library for the JSY1031, JSY-MK-163, JSY-MK-193, JSY-MK-194, JSY-MK-227, JSY-MK-229, JSY-MK-333 families single-phase and three-phase AC bidirectional meters from Shenzhen Jiansiyan Technologies Co, Ltd.
Loading...
Searching...
No Matches
MycilaDimmerThyristor.cpp
1// SPDX-License-Identifier: MIT
2/*
3 * Copyright (C) 2023-2025 Mathieu Carbou
4 */
5#include <MycilaDimmerThyristor.h>
6
7// lock
8#include <freertos/FreeRTOS.h>
9
10// gpio
11#include <driver/gpio.h>
12#include <driver/gptimer_types.h>
13#include <esp32-hal-gpio.h>
14#include <hal/gpio_ll.h>
15#include <soc/gpio_struct.h>
16
17// logging
18#include <esp32-hal-log.h>
19
20// timers
21#include "priv/inlined_gptimer.h"
22
23#ifndef GPIO_IS_VALID_OUTPUT_GPIO
24 #define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) ((gpio_num >= 0) && \
25 (((1ULL << (gpio_num)) & SOC_GPIO_VALID_OUTPUT_GPIO_MASK) != 0))
26#endif
27
28#ifndef GPIO_IS_VALID_GPIO
29 #define GPIO_IS_VALID_GPIO(gpio_num) ((gpio_num >= 0) && \
30 (((1ULL << (gpio_num)) & SOC_GPIO_VALID_GPIO_MASK) != 0))
31#endif
32
33// Minimum delay to reach the voltage required for a gate current of 30mA.
34// delay_us = asin((gate_resistor * gate_current) / grid_volt_max) / pi * period_us
35// delay_us = asin((330 * 0.03) / 325) / pi * 10000 = 97us
36#define PHASE_DELAY_MIN_US (90)
37
38#define TAG "Thyristor"
39
40static gptimer_handle_t fire_timer = nullptr;
41
42#ifndef MYCILA_DIMMER_NO_LOCK
43static portMUX_TYPE dimmers_spinlock = portMUX_INITIALIZER_UNLOCKED;
44#endif
45
46Mycila::ThyristorDimmer::RegisteredDimmer* Mycila::ThyristorDimmer::dimmers = nullptr;
47
49 if (_enabled)
50 return true;
51
52 if (!GPIO_IS_VALID_OUTPUT_GPIO(_pin)) {
53 ESP_LOGE(TAG, "Invalid pin: %" PRId8, _pin);
54 return false;
55 }
56
57 ESP_LOGI(TAG, "Enable dimmer on pin %" PRId8, _pin);
58
59 pinMode(_pin, OUTPUT);
60 digitalWrite(_pin, LOW);
61 _registerDimmer(this);
62 _enabled = true;
63
64 // restart with last saved value
65 setDutyCycle(_dutyCycle);
66 return true;
67}
68
70 if (!_enabled)
71 return;
72 _enabled = false;
73 _online = false;
74 ESP_LOGI(TAG, "Disable dimmer on pin %" PRId8, _pin);
75 _apply();
76 _unregisterDimmer(this);
77 digitalWrite(_pin, LOW);
78}
79
80void ARDUINO_ISR_ATTR Mycila::ThyristorDimmer::onZeroCross(int16_t delayUntilZero, void* arg) {
81 // prepare our next alarm for the next dimmer to be fired
82 gptimer_alarm_config_t fire_timer_alarm_cfg = {.alarm_count = UINT16_MAX, .reload_count = 0, .flags = {.auto_reload_on_alarm = false}};
83
84 // immediately reset the firing timer to start counting from this ZC event and avoid it to trigger other alarms
85 if (inlined_gptimer_set_raw_count(fire_timer, 0) != ESP_OK) {
86 // failed to reset the timer: probably not initialized yet: just ignore this ZC event
87 return;
88 }
89
90#ifndef MYCILA_DIMMER_NO_LOCK
91 // lock since we need to iterate over the list of dimmers
92 portENTER_CRITICAL_SAFE(&dimmers_spinlock);
93#endif
94
95 // go through all registered dimmers to prepare the next firing
96 struct RegisteredDimmer* current = dimmers;
97 while (current != nullptr) {
98 if (current->dimmer->_delay) {
99 // if a delay is applied (dimmer is off (UINT16_MAX), or on with a delay > 0), turn off the triac and it will be turned on again later
100 gpio_ll_set_level(&GPIO, current->dimmer->_pin, LOW);
101 // calculate the next firing time:
102 // - If Dimmer is off (UINT16_MAX) => current->alarm_count == UINT16_MAX => dimmer will not be fired
103 // - If Dimmer is on with a delay > 0 => check to be sure it is PHASE_DELAY_MIN_US minimum
104 current->alarm_count = current->dimmer->_delay < PHASE_DELAY_MIN_US ? PHASE_DELAY_MIN_US : current->dimmer->_delay;
105 // keep track the minimum delay at which we have to fire a dimmer
106 if (current->alarm_count < fire_timer_alarm_cfg.alarm_count)
107 fire_timer_alarm_cfg.alarm_count = current->alarm_count;
108 } else {
109 // no delay: dimmer has to be kept on: do nothing
110 gpio_ll_set_level(&GPIO, current->dimmer->_pin, HIGH);
111 // reset the alarm count to indicate that this dimmer was fired
112 current->alarm_count = UINT16_MAX;
113 }
114 current = current->next;
115 }
116
117#ifndef MYCILA_DIMMER_NO_LOCK
118 // unlock the list of dimmers
119 portEXIT_CRITICAL_SAFE(&dimmers_spinlock);
120#endif
121
122 // get the time we spent looping and eventually waiting for the lock
123 uint64_t fire_timer_count_value;
124 if (inlined_gptimer_get_raw_count(fire_timer, &fire_timer_count_value) != ESP_OK) {
125 // failed to get the timer count: just ignore this ZC event
126 return;
127 }
128
129 // check if we had to wait too much time for the lock and we missed the 0V crossing point
130 if (fire_timer_count_value >= delayUntilZero) {
131 fire_timer_count_value -= delayUntilZero;
132
133 // check if we missed the minimum time at which we have to turn the first dimmer on (next alarm)
134 if (fire_timer_count_value <= fire_timer_alarm_cfg.alarm_count) {
135 // directly call the firing ISR to turn on the first dimmer without waiting for an alarm
136 if (inlined_gptimer_set_raw_count(fire_timer, fire_timer_count_value) == ESP_OK) {
137 _fireTimerISR(fire_timer, nullptr, nullptr);
138 }
139 } else {
140 // we are too late: do nothing: this is better to wait for the next ZC event than trying to turn on dimmers too late, which would create flickering
141 }
142
143 } else {
144 // 0V crossing point not yet reached: set the counter to be at the right current position (very large number) before 0: the timer count will then overflow
145 if (inlined_gptimer_set_raw_count(fire_timer, -static_cast<uint64_t>(delayUntilZero) + fire_timer_count_value) == ESP_OK) {
146 // and set an alarm to be woken up at the right time: minimumCount
147 inlined_gptimer_set_alarm_action(fire_timer, &fire_timer_alarm_cfg);
148 }
149 }
150}
151
152// Timer ISR to be called as soon as a dimmer needs to be fired
153bool ARDUINO_ISR_ATTR Mycila::ThyristorDimmer::_fireTimerISR(gptimer_handle_t timer, const gptimer_alarm_event_data_t* event, void* arg) {
154 // prepare our next alarm for the first dimmer to be fired
155 gptimer_alarm_config_t fire_timer_alarm_cfg = {.alarm_count = UINT16_MAX, .reload_count = 0, .flags = {.auto_reload_on_alarm = false}};
156
157 // get the time we spent looping and eventually waiting for the lock
158 uint64_t fire_timer_count_value;
159 if (inlined_gptimer_get_raw_count(fire_timer, &fire_timer_count_value) != ESP_OK) {
160 // failed to get the timer count: just ignore this event
161 return false;
162 }
163
164 do {
165 fire_timer_alarm_cfg.alarm_count = UINT16_MAX;
166
167#ifndef MYCILA_DIMMER_NO_LOCK
168 // lock since we need to iterate over the list of dimmers
169 portENTER_CRITICAL_SAFE(&dimmers_spinlock);
170#endif
171
172 // go through all registered dimmers and check the ones to fire
173 struct RegisteredDimmer* current = dimmers;
174 while (current != nullptr) {
175 if (current->alarm_count != UINT16_MAX) {
176 // this dimmer has not yet been fired (< UINT16_MAX)
177 if (current->alarm_count <= fire_timer_count_value) {
178 // timer alarm has reached this dimmer alarm => time to fire this dimmer
179 gpio_ll_set_level(&GPIO, current->dimmer->_pin, HIGH);
180 // reset the alarm count to indicate that this dimmer has been fired
181 current->alarm_count = UINT16_MAX;
182 } else {
183 // dimmer has to be fired later => keep the minimum time at which we have to fire a dimmer
184 if (current->alarm_count < fire_timer_alarm_cfg.alarm_count)
185 fire_timer_alarm_cfg.alarm_count = current->alarm_count;
186 }
187 }
188 current = current->next;
189 }
190
191#ifndef MYCILA_DIMMER_NO_LOCK
192 // unlock the list of dimmers
193 portEXIT_CRITICAL_SAFE(&dimmers_spinlock);
194#endif
195
196 // refresh the current timer count value to check if we have to fire other dimmers
197 inlined_gptimer_get_raw_count(fire_timer, &fire_timer_count_value);
198 } while (fire_timer_alarm_cfg.alarm_count != UINT16_MAX && fire_timer_alarm_cfg.alarm_count <= fire_timer_count_value);
199
200 // if there are some remaining dimmers to be fired, set an alarm for the next ones
201 if (fire_timer_alarm_cfg.alarm_count != UINT16_MAX)
202 inlined_gptimer_set_alarm_action(fire_timer, &fire_timer_alarm_cfg);
203
204 return false;
205}
206
207// add a dimmer to the list of managed dimmers
208void Mycila::ThyristorDimmer::_registerDimmer(Mycila::ThyristorDimmer* dimmer) {
209 if (dimmers == nullptr) {
210 ESP_LOGI(TAG, "Starting dimmer firing ISR");
211
212 gptimer_config_t timer_config;
213 timer_config.clk_src = GPTIMER_CLK_SRC_DEFAULT;
214 timer_config.direction = GPTIMER_COUNT_UP;
215 timer_config.resolution_hz = 1000000; // 1MHz resolution
216 timer_config.flags.intr_shared = true;
217 timer_config.intr_priority = 0;
218#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
219 timer_config.flags.backup_before_sleep = false;
220#endif
221#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
222 timer_config.flags.allow_pd = false;
223#endif
224
225 ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &fire_timer));
226 gptimer_event_callbacks_t callbacks_config;
227 callbacks_config.on_alarm = _fireTimerISR;
228 ESP_ERROR_CHECK(gptimer_register_event_callbacks(fire_timer, &callbacks_config, nullptr));
229 ESP_ERROR_CHECK(gptimer_enable(fire_timer));
230 ESP_ERROR_CHECK(gptimer_start(fire_timer));
231 }
232
233 ESP_LOGD(TAG, "Register new dimmer %p on pin %d", dimmer, dimmer->getPin());
234
235#ifndef MYCILA_DIMMER_NO_LOCK
236 portENTER_CRITICAL_SAFE(&dimmers_spinlock);
237#endif
238
239 if (dimmers == nullptr) {
240 dimmers = new RegisteredDimmer();
241 dimmers->dimmer = dimmer;
242 } else {
243 struct RegisteredDimmer* additional = new RegisteredDimmer();
244 additional->dimmer = dimmer;
245 additional->next = dimmers;
246 additional->prev = nullptr;
247 dimmers->prev = additional;
248 dimmers = additional;
249 }
250
251#ifndef MYCILA_DIMMER_NO_LOCK
252 portEXIT_CRITICAL_SAFE(&dimmers_spinlock);
253#endif
254}
255
256// remove a dimmer from the list of managed dimmers
257void Mycila::ThyristorDimmer::_unregisterDimmer(Mycila::ThyristorDimmer* dimmer) {
258 ESP_LOGD(TAG, "Unregister dimmer %p on pin %d", dimmer, dimmer->getPin());
259
260#ifndef MYCILA_DIMMER_NO_LOCK
261 portENTER_CRITICAL_SAFE(&dimmers_spinlock);
262#endif
263
264 struct RegisteredDimmer* current = dimmers;
265 while (current != nullptr) {
266 if (current->dimmer == dimmer) {
267 if (current->prev != nullptr) {
268 current->prev->next = current->next;
269 } else {
270 dimmers = current->next;
271 }
272 if (current->next != nullptr) {
273 current->next->prev = current->prev;
274 }
275 delete current;
276 break;
277 }
278 current = current->next;
279 }
280
281#ifndef MYCILA_DIMMER_NO_LOCK
282 portEXIT_CRITICAL_SAFE(&dimmers_spinlock);
283#endif
284
285 if (dimmers == nullptr) {
286 ESP_LOGI(TAG, "Stopping dimmer firing ISR");
287 gptimer_stop(fire_timer); // might be already stopped
288 ESP_ERROR_CHECK(gptimer_disable(fire_timer));
289 ESP_ERROR_CHECK(gptimer_del_timer(fire_timer));
290 fire_timer = nullptr;
291 }
292}
bool setDutyCycle(float dutyCycle)
Set the power duty.
gpio_num_t getPin() const
Get the GPIO pin used for the dimmer.
static void onZeroCross(int16_t delayUntilZero, void *args)
bool begin() override
Enable a dimmer on a specific GPIO pin.
void end() override
Disable the dimmer.