Compare commits
15
Commits
27af674d19
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9bbded33b2 | ||
|
|
51fd157ed2 | ||
|
|
862ed13e09 | ||
|
|
a4f27bf433 | ||
|
|
a83e6c0dc5 | ||
|
|
42e1d12ec4 | ||
|
|
5dfc8b9033 | ||
|
|
f02dc77b28 | ||
|
|
dbe7fce7ce | ||
|
|
0e9f663a8d | ||
|
|
f18ee9ba77 | ||
|
|
88907c3705 | ||
|
|
46762415d2 | ||
|
|
a14888aab0 | ||
|
|
54841bfd79 |
No files matched your search
+6
-1
@@ -1 +1,6 @@
|
||||
idf_component_register(SRCS "zh_ac_dimmer.c" INCLUDE_DIRS "include" REQUIRES driver esp_timer)
|
||||
if(${IDF_VERSION_MAJOR} STREQUAL 6)
|
||||
set(requires esp_driver_gpio esp_driver_gptimer esp_timer)
|
||||
else()
|
||||
set(requires driver esp_timer)
|
||||
endif()
|
||||
idf_component_register(SRCS "zh_ac_dimmer.c" INCLUDE_DIRS "include" REQUIRES ${requires})
|
||||
@@ -1,30 +1,28 @@
|
||||
# ESP32 ESP-IDF component for AC dimmer 115V/400Hz
|
||||
# ESP32 ESP-IDF component for AC dimmer (phase-angle control)
|
||||
|
||||
## Tested on
|
||||
## Features
|
||||
|
||||
1. [ESP32 ESP-IDF v5.5.3](https://docs.espressif.com/projects/esp-idf/en/v5.5.3/esp32/index.html)
|
||||
|
||||
## SAST Tools
|
||||
|
||||
[PVS-Studio](https://pvs-studio.com/pvs-studio/?utm_source=website&utm_medium=github&utm_campaign=open_source) - static analyzer for C, C++, C#, and Java code.
|
||||
1. Zero-crossing detection via GPIO interrupt on both edges with edge polarity determined from the current GPIO level and duplicate/glitch edge rejection.
|
||||
2. Spurious-interrupt filtering based on half-cycle range derived from the mains frequency limits (30 to 500 Hz).
|
||||
3. Low-pass filtered zero-crossing half-period measurement adapts the firing delay to the actual mains frequency.
|
||||
4. TRIAC gate control through ESP-IDF gptimer with 1 MHz resolution and configurable dimming level from 0 to 100 percent.
|
||||
5. Firing delay clamped to a guard band of at least 5 microseconds before the end of the half-cycle.
|
||||
6. Automatic runtime calibration of the hardware base offset using exponential moving average of the zero-crossing pulse width.
|
||||
7. Handle-based API with init, deinit, start, stop, set and get functions.
|
||||
8. Memory managed through ESP-IDF heap_caps functions with full cleanup on initialization failure.
|
||||
|
||||
## Attention
|
||||
|
||||
1. Supports frequency 400Hz only.
|
||||
2. For correct operation, please enable the following settings in the menuconfig:
|
||||
|
||||
```text
|
||||
GPIO_CTRL_FUNC_IN_IRAM
|
||||
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM
|
||||
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
|
||||
CONFIG_GPTIMER_ISR_CACHE_SAFE
|
||||
```
|
||||
1. Only one dimmer instance per zero-crossing GPIO pin. Initializing a second instance on the same pin replaces the ISR handler of the first one.
|
||||
2. Not thread-safe. Volatile fields prevent compiler optimizations but do not provide mutual exclusion between tasks.
|
||||
3. Calibration assumes a symmetric zero-crossing optocoupler pulse. Asymmetric pulses introduce a systematic offset error.
|
||||
4. Supported mains frequency range is limited by the compile-time constants 30 to 500 Hz. Out-of-range intervals reset the timing and calibration state.
|
||||
|
||||
## Using
|
||||
|
||||
In an existing project, run the following command to install the components:
|
||||
In an existing project, run the following command to install the component:
|
||||
|
||||
```text
|
||||
```bash
|
||||
cd ../your_project/components
|
||||
git clone https://github.com/aZholtikov/zh_ac_dimmer
|
||||
```
|
||||
@@ -37,33 +35,149 @@ In the application, add the component:
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Example: Initialize and Control Dimming Level
|
||||
|
||||
```c
|
||||
#include "zh_ac_dimmer.h"
|
||||
|
||||
zh_ac_dimmer_handle_t *ac_dimmer_handle = NULL;
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
esp_log_level_set("zh_ac_dimmer", ESP_LOG_ERROR);
|
||||
zh_ac_dimmer_init_config_t config = ZH_AC_DIMMER_INIT_CONFIG_DEFAULT();
|
||||
config.zero_cross_gpio = GPIO_NUM_16;
|
||||
config.triac_gpio = GPIO_NUM_17;
|
||||
zh_ac_dimmer_init(&config);
|
||||
zh_ac_dimmer_start();
|
||||
esp_err_t ret = zh_ac_dimmer_init(&config, &ac_dimmer_handle);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Dimmer initialization error: %s\n", esp_err_to_name(ret));
|
||||
return;
|
||||
}
|
||||
ret = zh_ac_dimmer_start(&ac_dimmer_handle);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Dimmer start error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
uint8_t val1 = 50;
|
||||
ret = zh_ac_dimmer_set(&ac_dimmer_handle, val1);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Dimmer set error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
uint8_t value = 0;
|
||||
ret = zh_ac_dimmer_get(&ac_dimmer_handle, &value);
|
||||
if (ret == ESP_OK)
|
||||
{
|
||||
printf("Dimmer value: %u\n", value);
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Dimmer get error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
vTaskDelay(5000 / portTICK_PERIOD_MS);
|
||||
ret = zh_ac_dimmer_stop(&ac_dimmer_handle);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Dimmer stop error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
zh_ac_dimmer_deinit(&ac_dimmer_handle);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Fade In Fade Out Example
|
||||
|
||||
```c
|
||||
#include "zh_ac_dimmer.h"
|
||||
|
||||
zh_ac_dimmer_handle_t *ac_dimmer_handle = NULL;
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
esp_log_level_set("zh_ac_dimmer", ESP_LOG_ERROR);
|
||||
zh_ac_dimmer_init_config_t config = ZH_AC_DIMMER_INIT_CONFIG_DEFAULT();
|
||||
config.zero_cross_gpio = GPIO_NUM_16;
|
||||
config.triac_gpio = GPIO_NUM_17;
|
||||
esp_err_t ret = zh_ac_dimmer_init(&config, &ac_dimmer_handle);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Dimmer initialization error: %s\n", esp_err_to_name(ret));
|
||||
return;
|
||||
}
|
||||
ret = zh_ac_dimmer_start(&ac_dimmer_handle);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Dimmer start error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
uint8_t value = 0;
|
||||
for (uint8_t i = 0; i <= 100; ++i)
|
||||
{
|
||||
zh_ac_dimmer_set(i);
|
||||
zh_ac_dimmer_get(&value);
|
||||
printf("Dimmer value: %d.\n", value);
|
||||
zh_ac_dimmer_set(&ac_dimmer_handle, i);
|
||||
zh_ac_dimmer_get(&ac_dimmer_handle, &value);
|
||||
printf("Dimmer value: %u\n", value);
|
||||
vTaskDelay(100 / portTICK_PERIOD_MS);
|
||||
}
|
||||
for (uint8_t i = 100; i > 0; --i)
|
||||
{
|
||||
zh_ac_dimmer_set(i);
|
||||
zh_ac_dimmer_get(&value);
|
||||
printf("Dimmer value: %d.\n", value);
|
||||
zh_ac_dimmer_set(&ac_dimmer_handle, i);
|
||||
zh_ac_dimmer_get(&ac_dimmer_handle, &value);
|
||||
printf("Dimmer value: %u\n", value);
|
||||
vTaskDelay(100 / portTICK_PERIOD_MS);
|
||||
}
|
||||
zh_ac_dimmer_stop();
|
||||
zh_ac_dimmer_deinit();
|
||||
zh_ac_dimmer_stop(&ac_dimmer_handle);
|
||||
zh_ac_dimmer_deinit(&ac_dimmer_handle);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Error Handling Example
|
||||
|
||||
```c
|
||||
#include "zh_ac_dimmer.h"
|
||||
|
||||
zh_ac_dimmer_handle_t *ac_dimmer_handle = NULL;
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
esp_log_level_set("zh_ac_dimmer", ESP_LOG_ERROR);
|
||||
zh_ac_dimmer_init_config_t config = ZH_AC_DIMMER_INIT_CONFIG_DEFAULT();
|
||||
config.zero_cross_gpio = GPIO_NUM_16;
|
||||
config.triac_gpio = GPIO_NUM_16;
|
||||
esp_err_t ret = zh_ac_dimmer_init(&config, &ac_dimmer_handle);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Expected init error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
config.triac_gpio = GPIO_NUM_17;
|
||||
ret = zh_ac_dimmer_init(&config, &ac_dimmer_handle);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Dimmer initialization error: %s\n", esp_err_to_name(ret));
|
||||
return;
|
||||
}
|
||||
ret = zh_ac_dimmer_init(&config, &ac_dimmer_handle);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Expected double init error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
zh_ac_dimmer_start(&ac_dimmer_handle);
|
||||
ret = zh_ac_dimmer_set(&ac_dimmer_handle, 101);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Expected set range error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
ret = zh_ac_dimmer_set(&ac_dimmer_handle, 75);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
printf("Dimmer set error: %s\n", esp_err_to_name(ret));
|
||||
}
|
||||
uint8_t value = 0;
|
||||
zh_ac_dimmer_get(&ac_dimmer_handle, &value);
|
||||
printf("Dimmer value: %u\n", value);
|
||||
zh_ac_dimmer_stop(&ac_dimmer_handle);
|
||||
zh_ac_dimmer_deinit(&ac_dimmer_handle);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,8 @@
|
||||
description: ESP32 ESP-IDF component for AC dimmer
|
||||
url: https://github.com/aZholtikov/zh_ac_dimmer
|
||||
version: "3.1.0"
|
||||
license: "Apache-2.0"
|
||||
maintainers:
|
||||
- "Alexey Zholtikov <alexey.zholtikov@yandex.ru>"
|
||||
dependencies:
|
||||
idf: ">=5.0"
|
||||
+108
-29
@@ -1,9 +1,33 @@
|
||||
/**
|
||||
* @file zh_ac_dimmer.h
|
||||
*
|
||||
* @brief Header file for AC dimmer driver based on zero-crossing detection and TRIAC control.
|
||||
*
|
||||
* This module provides an interface for controlling AC power via phase-angle
|
||||
* dimming using ESP-IDF gptimer and GPIO peripherals. It detects the AC
|
||||
* mains zero-crossing point, measures the zero-crossing period, and fires the
|
||||
* TRIAC with a programmable delay to regulate the average power delivered to
|
||||
* the load.
|
||||
*
|
||||
* Key features:
|
||||
* - Zero-crossing detection via GPIO interrupt with period measurement
|
||||
* - TRIAC gate control through ESP-IDF gptimer
|
||||
* - Configurable dimming level (0–100 %)
|
||||
* - Automatic runtime calibration of the hardware base offset
|
||||
* - Start/stop/set/get API
|
||||
*
|
||||
* @note The supported mains frequency range is defined by
|
||||
* `ZH_AC_DIMMER_FREQ_MIN_HZ` and `ZH_AC_DIMMER_FREQ_MAX_HZ`. The measured
|
||||
* zero-crossing period is filtered and used to calculate the firing delay.
|
||||
* @warning This module interacts with mains voltage. Incorrect wiring or
|
||||
* insufficient isolation can cause electric shock or hardware damage.
|
||||
* Ensure proper opto-isolation and safety compliance before deployment.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "stdint.h"
|
||||
#include "esp_heap_caps.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "driver/gptimer.h"
|
||||
@@ -11,9 +35,9 @@
|
||||
#include "esp_log.h"
|
||||
#include "driver/gpio.h"
|
||||
|
||||
/**
|
||||
* @brief AC dimmer initial default values.
|
||||
*/
|
||||
#define ZH_AC_DIMMER_FREQ_MIN_HZ 30
|
||||
#define ZH_AC_DIMMER_FREQ_MAX_HZ 500
|
||||
|
||||
#define ZH_AC_DIMMER_INIT_CONFIG_DEFAULT() \
|
||||
{ \
|
||||
.zero_cross_gpio = GPIO_NUM_MAX, \
|
||||
@@ -25,65 +49,120 @@ extern "C"
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Structure for initial initialization of AC dimmer.
|
||||
* @brief Opaque handle representing an AC dimmer instance.
|
||||
*
|
||||
* Internal fields are defined in `zh_ac_dimmer.c` and must not be
|
||||
* accessed directly by user code.
|
||||
*/
|
||||
typedef struct _zh_ac_dimmer_handle_t zh_ac_dimmer_handle_t;
|
||||
|
||||
/**
|
||||
* @brief Configuration structure for AC dimmer initialization.
|
||||
*
|
||||
* Specifies the GPIO pins used for zero-crossing detection and TRIAC
|
||||
* gate control. Both pins must be valid and different from each other.
|
||||
*
|
||||
* @note The firing-delay offset is calibrated automatically at runtime and
|
||||
* is not part of the configuration.
|
||||
*/
|
||||
typedef struct
|
||||
{
|
||||
uint8_t zero_cross_gpio; /*!< Zero cross GPIO. */
|
||||
uint8_t triac_gpio; /*!< Triac GPIO. */
|
||||
gpio_num_t zero_cross_gpio; /*!< GPIO pin for zero-crossing detection input */
|
||||
gpio_num_t triac_gpio; /*!< GPIO pin for TRIAC gate control output */
|
||||
} zh_ac_dimmer_init_config_t;
|
||||
|
||||
/**
|
||||
* @brief Initialize AC dimmer.
|
||||
* @brief Initialize the AC dimmer driver.
|
||||
*
|
||||
* @param[in] config Pointer to AC dimmer initialized configuration structure. Can point to a temporary variable.
|
||||
* Allocates memory for the dimmer handle, validates the configuration,
|
||||
* initializes GPIO pins (TRIAC as output, zero-crossing as input with
|
||||
* both-edge interrupt), installs the ISR service, and creates the gptimer.
|
||||
*
|
||||
* @note Before initialize the AC dimmer recommend initialize zh_ac_dimmer_init_config_t structure with default values.
|
||||
* @param[in] config Pointer to the initialization configuration structure (may point to a
|
||||
* temporary variable, not stored internally)
|
||||
* @param[out] handle Pointer to receive the created dimmer handle (must not be NULL and must point to NULL)
|
||||
*
|
||||
* @code zh_ac_dimmer_init_config_t config = ZH_AC_DIMMER_INIT_CONFIG_DEFAULT @endcode
|
||||
* @return ESP_OK on success
|
||||
* @return ESP_ERR_INVALID_ARG if config or handle is NULL
|
||||
* @return ESP_ERR_INVALID_STATE if the handle pointer already points to an initialized instance
|
||||
* @return ESP_ERR_NO_MEM if memory allocation failed
|
||||
* @return ESP_FAIL if configuration validation, GPIO, ISR service, or timer initialization failed
|
||||
*
|
||||
* @return ESP_OK if success or an error code otherwise.
|
||||
* @note The driver supports only one instance per zero-crossing GPIO pin. Initializing a
|
||||
* second instance on the same pin replaces the ISR handler of the first one, so each
|
||||
* pin must be claimed by a single dimmer instance.
|
||||
*/
|
||||
esp_err_t zh_ac_dimmer_init(const zh_ac_dimmer_init_config_t *config);
|
||||
esp_err_t zh_ac_dimmer_init(const zh_ac_dimmer_init_config_t *config, zh_ac_dimmer_handle_t **handle);
|
||||
|
||||
/**
|
||||
* @brief Deinitialize AC dimmer.
|
||||
* @brief Deinitialize the AC dimmer driver.
|
||||
*
|
||||
* @return ESP_OK if success or an error code otherwise.
|
||||
* Disables TRIAC firing, removes the GPIO ISR handler, resets the GPIO
|
||||
* pins, stops, disables and deletes the gptimer, frees the dimmer handle
|
||||
* and sets the output handle to NULL. Cleanup steps are executed
|
||||
* unconditionally and their failures are only logged.
|
||||
*
|
||||
* @param[in,out] handle Pointer to the dimmer handle, set to NULL on return (must not be NULL)
|
||||
*
|
||||
* @return ESP_OK on success
|
||||
* @return ESP_ERR_INVALID_ARG if handle or *handle is NULL
|
||||
*
|
||||
* @warning After calling this function, the handle is invalid and must not
|
||||
* be used. Call `zh_ac_dimmer_init()` again to reinitialize.
|
||||
*/
|
||||
esp_err_t zh_ac_dimmer_deinit(void);
|
||||
esp_err_t zh_ac_dimmer_deinit(zh_ac_dimmer_handle_t **handle);
|
||||
|
||||
/**
|
||||
* @brief Start AC dimmer.
|
||||
* @brief Start the AC dimmer.
|
||||
*
|
||||
* @return ESP_OK if success or an error code otherwise.
|
||||
* Enables the dimmer so that zero-crossing events trigger TRIAC firing
|
||||
* according to the current dimming value.
|
||||
*
|
||||
* @param[in] handle Pointer to the dimmer handle (must not be NULL)
|
||||
*
|
||||
* @return ESP_OK on success
|
||||
* @return ESP_ERR_INVALID_ARG if handle or *handle is NULL
|
||||
*/
|
||||
esp_err_t zh_ac_dimmer_start(void);
|
||||
esp_err_t zh_ac_dimmer_start(zh_ac_dimmer_handle_t **handle);
|
||||
|
||||
/**
|
||||
* @brief Stop AC dimmer.
|
||||
* @brief Stop the AC dimmer.
|
||||
*
|
||||
* @return ESP_OK if success or an error code otherwise.
|
||||
* Disables TRIAC firing on zero-crossing events. The dimmer can be
|
||||
* restarted with `zh_ac_dimmer_start()`. The TRIAC gate stays in the
|
||||
* state left by the last half-cycle until the next zero-crossing event.
|
||||
*
|
||||
* @param[in] handle Pointer to the dimmer handle (must not be NULL)
|
||||
*
|
||||
* @return ESP_OK on success
|
||||
* @return ESP_ERR_INVALID_ARG if handle or *handle is NULL
|
||||
*/
|
||||
esp_err_t zh_ac_dimmer_stop(void);
|
||||
esp_err_t zh_ac_dimmer_stop(zh_ac_dimmer_handle_t **handle);
|
||||
|
||||
/**
|
||||
* @brief Set AC dimmer dimming value.
|
||||
* @brief Set the AC dimmer brightness level.
|
||||
*
|
||||
* @param[in] value Dimming value (0 to 100).
|
||||
* Sets the dimming percentage that will be applied on the next
|
||||
* zero-crossing event.
|
||||
*
|
||||
* @return ESP_OK if success or an error code otherwise.
|
||||
* @param[in] handle Pointer to the dimmer handle (must not be NULL)
|
||||
* @param[in] value Dimming level in percent, where 0 keeps the load off and 100 fires the TRIAC immediately (must be <= 100)
|
||||
*
|
||||
* @return ESP_OK on success
|
||||
* @return ESP_ERR_INVALID_ARG if handle, *handle, or value is invalid
|
||||
*/
|
||||
esp_err_t zh_ac_dimmer_set(uint8_t value);
|
||||
esp_err_t zh_ac_dimmer_set(zh_ac_dimmer_handle_t **handle, uint8_t value);
|
||||
|
||||
/**
|
||||
* @brief Get AC dimmer dimming value.
|
||||
* @brief Get the current AC dimmer brightness level.
|
||||
*
|
||||
* @param[out] value Pointer to dimming value.
|
||||
* @param[in] handle Pointer to the dimmer handle (must not be NULL)
|
||||
* @param[out] value Pointer to receive the current dimming level in percent (must not be NULL)
|
||||
*
|
||||
* @return ESP_OK if success or an error code otherwise.
|
||||
* @return ESP_OK on success
|
||||
* @return ESP_ERR_INVALID_ARG if handle, *handle, or value is NULL
|
||||
*/
|
||||
esp_err_t zh_ac_dimmer_get(uint8_t *value);
|
||||
esp_err_t zh_ac_dimmer_get(zh_ac_dimmer_handle_t **handle, uint8_t *value);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
2.0.1
|
||||
3.1.0
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
# Описание компонента zh_ac_dimmer
|
||||
|
||||
## Общие сведения
|
||||
|
||||
**zh_ac_dimmer** — это драйвер для ESP-IDF, реализующий фазовое управление мощностью
|
||||
переменного тока (AC dimming) через детектирование перехода через ноль и управление
|
||||
затвором тиристора (TRIAC). Компонент определяет момент перехода сетевого напряжения
|
||||
через ноль, измеряет период полуволны и зажигает TRIAC с программируемой задержкой,
|
||||
регулируя среднюю мощность, подаваемую на нагрузку.
|
||||
|
||||
Компонент предоставляет полный набор функций для инициализации, запуска, остановки
|
||||
и управления уровнем затемнения (0–100 %), а также автоматическую калибровку
|
||||
аппаратного смещения в режиме реального времени.
|
||||
|
||||
### Основные возможности
|
||||
|
||||
1. **Детектирование перехода через ноль** — через GPIO-прерывание с измерением периода.
|
||||
2. **Управление TRIAC** — через ESP-IDF gptimer с программируемой задержкой.
|
||||
3. **Уровень затемнения 0–100 %** — плавная регулировка мощности нагрузки.
|
||||
4. **Автоматическая калибровка** — аппаратное смещение калибруется во время работы.
|
||||
5. **Фильтрация периодов** — низкочастотный фильтр для стабильного измерения частоты сети.
|
||||
6. **Защитный зазор (guard band)** — гарантированное отключение TRIAC до конца полуволны.
|
||||
7. **Валидация частоты** — отбрасывание помех и некорректных импульсов.
|
||||
8. **Старт/стоп API** — простое управление состоянием dimmer.
|
||||
|
||||
---
|
||||
|
||||
## Внутреннее устройство
|
||||
|
||||
### Структура `zh_ac_dimmer_handle_t`
|
||||
|
||||
Внутренняя структура хранит все состояние экземпляра dimmer: GPIO-пины, таймер,
|
||||
состояние синхронизации и текущий уровень затемнения.
|
||||
|
||||
| Поле | Тип | Описание |
|
||||
| ------ | ----- | ---------- |
|
||||
| `zero_cross_gpio` | `gpio_num_t` | GPIO-пин для детектирования перехода через ноль |
|
||||
| `triac_gpio` | `gpio_num_t` | GPIO-пин для управления затвором TRIAC (выход) |
|
||||
| `dimmer_timer_handle` | `gptimer_handle_t` | Экземпляр gptimer для задержки зажигания TRIAC |
|
||||
| `prev_zero_crossing_us` | `uint64_t` | Метка времени предыдущего фронтa (мкс) |
|
||||
| `pulse_start_us` | `uint64_t` | Метка времени текущего фронтa для измерения ширины импульса (мкс) |
|
||||
| `period_us` | `uint32_t` | Отфильтрованный период полуволны в мкс (0 до первого измерения) |
|
||||
| `base_offset_us` | `volatile uint32_t` | Автоматически откалиброванное опережение ISR относительно нуля (мкс) |
|
||||
| `auto_base_samples` | `volatile uint32_t` | Количество образцов, использованных для калибровки |
|
||||
| `dimmer_value` | `volatile uint8_t` | Текущий уровень затемнения, 0 (выкл) .. 100 (полная мощность) |
|
||||
| `is_dimmer_work` | `volatile bool` | Флаг активной работы dimmer |
|
||||
| `last_edge_was_rising` | `bool` | Флаг полярности последнего фронта для отбрасывания дубликатов |
|
||||
|
||||
### Управление памятью
|
||||
|
||||
Память выделяется через `heap_caps_calloc()` в функции `zh_ac_dimmer_init()`
|
||||
с флагом `MALLOC_CAP_8BIT`. Освобождение происходит в `zh_ac_dimmer_deinit()`
|
||||
через `heap_caps_free()`. При неудачной инициализации освобождённая память
|
||||
очищается через цепочку cleanup в макросе `ZH_ERROR_CHECK`.
|
||||
|
||||
### Структура `zh_ac_dimmer_init_config_t`
|
||||
|
||||
Конфигурационная структура, передаваемая пользователем при инициализации.
|
||||
|
||||
| Поле | Тип | Описание |
|
||||
|------|-----|----------|
|
||||
| `zero_cross_gpio` | `gpio_num_t` | GPIO-пин для детектирования перехода через ноль |
|
||||
| `triac_gpio` | `gpio_num_t` | GPIO-пин для управления затвором TRIAC |
|
||||
|
||||
---
|
||||
|
||||
## API (интерфейс)
|
||||
|
||||
### Инициализация и освобождение
|
||||
|
||||
| Функция | Описание |
|
||||
|---------|----------|
|
||||
| `zh_ac_dimmer_init()` | Инициализирует драйвер: выделяет память, настраивает GPIO, устанавливает ISR-обработчик, создаёт gptimer |
|
||||
| `zh_ac_dimmer_deinit()` | Полностью деинициализирует драйвер: удаляет ISR, сбрасывает GPIO, удаляет таймер, освобождает память |
|
||||
|
||||
### Управление состоянием
|
||||
|
||||
| Функция | Описание |
|
||||
|---------|----------|
|
||||
| `zh_ac_dimmer_start()` | Включает dimmer — переходы через ноль начинают запускать TRIAC |
|
||||
| `zh_ac_dimmer_stop()` | Останавливает dimmer — TRIAC не зажигается до следующего перехода через ноль |
|
||||
|
||||
### Установка и получение уровня
|
||||
|
||||
| Функция | Описание |
|
||||
|---------|----------|
|
||||
| `zh_ac_dimmer_set()` | Устанавливает уровень затемнения (0–100 %), применяется на следующем полупериоде |
|
||||
| `zh_ac_dimmer_get()` | Возвращает текущий установленный уровень затемнения |
|
||||
|
||||
---
|
||||
|
||||
## Потокобезопасность
|
||||
|
||||
Компонент **не является потокобезопасным**. Все поля структуры `zh_ac_dimmer_handle_t`,
|
||||
изменяемые как из основного потока, так и из ISR (`dimmer_value`, `is_dimmer_work`,
|
||||
`base_offset_us`, `auto_base_samples`), помечены как `volatile` для предотвращения
|
||||
оптимизаций компилятора. Синхронизация между потоками не предусмотрена — пользователь
|
||||
должен обеспечивать взаимное исключение на уровне приложения, если dimmer используется
|
||||
из нескольких задач FreeRTOS.
|
||||
|
||||
---
|
||||
|
||||
## Алгоритмы
|
||||
|
||||
### Калибровка аппаратного смещения
|
||||
|
||||
При детектировании спадающего фронта импульса перехода через ноль вычисляется ширина
|
||||
импульса (`pulse_width`), которая делится пополам для получения опережения:
|
||||
|
||||
```
|
||||
measured_adv = pulse_width / 2
|
||||
```
|
||||
|
||||
Первое измерение устанавливает `base_offset_us` напрямую. Последующие значения
|
||||
сглаживаются экспоненциальным скользящим средним (EMA) с коэффициентом 15/16:
|
||||
|
||||
```
|
||||
base_offset_us = (base_offset_us * 15 + measured_adv) / 16
|
||||
```
|
||||
|
||||
Валидация импульса: ширина должна быть в диапазоне `[4 мкс, period_us / 4]`.
|
||||
Если `period_us` ещё не измерен, используется верхний предел 2000 мкс.
|
||||
|
||||
### Фильтрация периода полуволны
|
||||
|
||||
Первый принятый фронт устанавливает `period_us` напрямую. Последующие значения
|
||||
сглаживаются EMA с коэффициентом 7/8:
|
||||
|
||||
```
|
||||
period_us = (period_us * 7 + delta_us) / 8
|
||||
```
|
||||
|
||||
Если интервал между фронтами выходит за пределы `[period_min_us, period_max_us]`,
|
||||
состояние сбрасывается: `period_us = 0`, `auto_base_samples = 0`, TRIAC сбрасывается.
|
||||
|
||||
Границы периода рассчитываются из настраиваемой частоты сети:
|
||||
|
||||
```
|
||||
period_min_us = 1 000 000 / (2 * ZH_AC_DIMMER_FREQ_MAX_HZ)
|
||||
period_max_us = 1 000 000 / (2 * ZH_AC_DIMMER_FREQ_MIN_HZ)
|
||||
```
|
||||
|
||||
### Расчёт задержки зажигания TRIAC
|
||||
|
||||
Для каждого принятого фронтa вычисляется задержка до зажигания TRIAC:
|
||||
|
||||
1. Вычисляется целевая задержка на основе уровня затемнения:
|
||||
|
||||
```
|
||||
t_fire = period * (100 - dimmer_value) / 100
|
||||
```
|
||||
|
||||
2. Добавляется откалиброванное смещение:
|
||||
|
||||
```
|
||||
delay_us = t_fire + base_offset_us
|
||||
```
|
||||
|
||||
Если `base_offset_us >= period`, смещение ограничивается значением `period`.
|
||||
3. Если `delay_us <= 0`, TRIAC зажигается немедленно.
|
||||
4. Вычисляется защитный зазор: `guard_us = max(period / 20, 5 мкс)`.
|
||||
5. Если `delay_us > period - guard_us`, задержка урезается до `period - guard_us`.
|
||||
6. Таймер запускается с вычисленной задержкой.
|
||||
|
||||
### Обработка ISR перехода через ноль
|
||||
|
||||
ISR обрабатывает оба фронта сигнала:
|
||||
|
||||
1. **Спадающий фронт** (GPIO = 0, предыдущий фронт был возрастающий):
|
||||
- Измеряется ширина импульса.
|
||||
- Калибруется `base_offset_us` через EMA.
|
||||
- Действий с TRIAC не выполняется.
|
||||
|
||||
2. **Возрастающий фронт** (GPIO = 1):
|
||||
- Сохраняется метка времени `pulse_start_us`.
|
||||
- Если это первый фронт — только запоминается время, TRIAC сбрасывается.
|
||||
- Интервал сравнивается с допустимыми границами:
|
||||
- Если интервал слишком короткий — фронт отбрасывается как помеха.
|
||||
- Если интервал слишком длинный — состояние сбрасывается.
|
||||
- Обновляется отфильтрованный период `period_us`.
|
||||
- Если dimmer не работает или уровень = 0 — таймер останавливается.
|
||||
- Иначе — вычисляется задержка и запускается таймер для зажигания TRIAC.
|
||||
|
||||
---
|
||||
|
||||
## Примеры использования
|
||||
|
||||
### Базовый пример инициализации и управления
|
||||
|
||||
```c
|
||||
#include "zh_ac_dimmer.h"
|
||||
|
||||
zh_ac_dimmer_handle_t *dimmer = NULL;
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
// Настройка уровня логирования
|
||||
esp_log_level_set("zh_ac_dimmer", ESP_LOG_ERROR);
|
||||
|
||||
// Конфигурация пинов
|
||||
zh_ac_dimmer_init_config_t config = ZH_AC_DIMMER_INIT_CONFIG_DEFAULT();
|
||||
config.zero_cross_gpio = GPIO_NUM_16;
|
||||
config.triac_gpio = GPIO_NUM_17;
|
||||
|
||||
// Инициализация и запуск
|
||||
zh_ac_dimmer_init(&config, &dimmer);
|
||||
zh_ac_dimmer_start(&dimmer);
|
||||
|
||||
// Установка уровня затемнения 50 %
|
||||
zh_ac_dimmer_set(&dimmer, 50);
|
||||
|
||||
// Чтение текущего уровня
|
||||
uint8_t level = 0;
|
||||
zh_ac_dimmer_get(&dimmer, &level);
|
||||
|
||||
// Остановка и деинициализация
|
||||
zh_ac_dimmer_stop(&dimmer);
|
||||
zh_ac_dimmer_deinit(&dimmer);
|
||||
}
|
||||
```
|
||||
|
||||
### Динамическое изменение яркости
|
||||
|
||||
```c
|
||||
#include "zh_ac_dimmer.h"
|
||||
|
||||
zh_ac_dimmer_handle_t *dimmer = NULL;
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
esp_log_level_set("zh_ac_dimmer", ESP_LOG_ERROR);
|
||||
|
||||
zh_ac_dimmer_init_config_t config = ZH_AC_DIMMER_INIT_CONFIG_DEFAULT();
|
||||
config.zero_cross_gpio = GPIO_NUM_16;
|
||||
config.triac_gpio = GPIO_NUM_17;
|
||||
|
||||
zh_ac_dimmer_init(&config, &dimmer);
|
||||
zh_ac_dimmer_start(&dimmer);
|
||||
|
||||
// Плавное нарастание яркости от 0 до 100 %
|
||||
for (uint8_t i = 0; i <= 100; ++i)
|
||||
{
|
||||
zh_ac_dimmer_set(&dimmer, i);
|
||||
vTaskDelay(100 / portTICK_PERIOD_MS);
|
||||
}
|
||||
|
||||
// Плавное затухание от 100 до 0 %
|
||||
for (uint8_t i = 100; i > 0; --i)
|
||||
{
|
||||
zh_ac_dimmer_set(&dimmer, i);
|
||||
vTaskDelay(100 / portTICK_PERIOD_MS);
|
||||
}
|
||||
|
||||
zh_ac_dimmer_stop(&dimmer);
|
||||
zh_ac_dimmer_deinit(&dimmer);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Логирование
|
||||
|
||||
Компонент использует ESP-IDF логирование с тегом `"zh_ac_dimmer"`.
|
||||
|
||||
```c
|
||||
esp_log_level_set("zh_ac_dimmer", ESP_LOG_ERROR);
|
||||
```
|
||||
|
||||
Доступные уровни: `ESP_LOG_ERROR`, `ESP_LOG_WARN`, `ESP_LOG_INFO`, `ESP_LOG_DEBUG`.
|
||||
Настройка `ESP_LOG_ERROR` оставляет только сообщения об ошибках. Уровень `ESP_LOG_INFO`
|
||||
добавляет сообщения об успешной инициализации, запуске и остановке.
|
||||
|
||||
---
|
||||
|
||||
## Ошибки
|
||||
|
||||
| Код | Описание |
|
||||
| ----- | ---------- |
|
||||
| `ESP_OK` | Успешное выполнение |
|
||||
| `ESP_ERR_INVALID_ARG` | Неверный аргумент: NULL-указатель, некорректный GPIO, одинаковые пины, значение > 100 |
|
||||
| `ESP_ERR_INVALID_STATE` | Драйвер уже инициализирован (handle указывает на существующий экземпляр) |
|
||||
| `ESP_ERR_NO_MEM` | Не удалось выделить память для handle |
|
||||
| `ESP_FAIL` | Не удалось настроить GPIO, установить ISR-обработчик или создать таймер |
|
||||
|
||||
---
|
||||
|
||||
## Ограничения
|
||||
|
||||
1. **Один экземпляр на GPIO-пин** — инициализация второго dimmer на том же
|
||||
zero-cross GPIO заменяет ISR-обработчик первого экземпляра. Каждый пин должен
|
||||
принадлежать одному экземпляру.
|
||||
2. **Не потокобезопасный** — нет внутренней синхронизации между задачами.
|
||||
`volatile` защищает только от оптимизаций компилятора, но не от гонки данных.
|
||||
3. **Диапазон частот сети** — определяется макросами `ZH_AC_DIMMER_FREQ_MIN_HZ`
|
||||
(по умолчанию 30 Гц) и `ZH_AC_DIMMER_FREQ_MAX_HZ` (по умолчанию 500 Гц).
|
||||
Выход за эти границы приводит к сбросу состояния.
|
||||
4. **Симметричный оптоизолятор** — калибровка смещения предполагает симметричный
|
||||
импульс перехода через ноль (`base_offset = pulse_width / 2`). Асимметрия
|
||||
внесёт систематическую погрешность.
|
||||
5. **Защитный зазор** — минимальная задержка перед концом полуволны ограничена
|
||||
`max(period / 20, 5 мкс)`, что может не обеспечить достаточного времени
|
||||
для полного затухания TRIAC на очень низких частотах.
|
||||
|
||||
---
|
||||
|
||||
## Требования для сборки
|
||||
|
||||
- ESP-IDF (фреймворк для ESP32)
|
||||
- FreeRTOS (входит в состав ESP-IDF)
|
||||
- Драйверы `driver/gpio` и `driver/gptimer` (входят в состав ESP-IDF)
|
||||
|
||||
Компонент размещается в директории `components/` проекта ESP-IDF.
|
||||
|
||||
---
|
||||
|
||||
## Установка
|
||||
|
||||
```bash
|
||||
cd ваш_проект/components
|
||||
git clone https://github.com/aZholtikov/zh_ac_dimmer
|
||||
```
|
||||
|
||||
```c
|
||||
#include "zh_ac_dimmer.h"
|
||||
```
|
||||
+281
-99
@@ -13,100 +13,208 @@ static const char *TAG = "zh_ac_dimmer";
|
||||
return err; \
|
||||
}
|
||||
|
||||
static gptimer_handle_t _dimmer_timer = NULL;
|
||||
static gptimer_alarm_config_t _alarm_config = {0};
|
||||
#define ZH_ERROR_CHECK_CONT(cond, cleanup, msg, ...) \
|
||||
if (!(cond)) \
|
||||
{ \
|
||||
ZH_LOGE(msg, ESP_FAIL, ##__VA_ARGS__); \
|
||||
cleanup; \
|
||||
}
|
||||
|
||||
static zh_ac_dimmer_init_config_t _init_config = {0};
|
||||
static volatile uint64_t _prev_us = 0;
|
||||
static volatile uint8_t _dimmer_value = 0;
|
||||
static volatile bool _is_dimmer_work = false;
|
||||
static bool _is_initialized = false;
|
||||
/**
|
||||
* @brief Internal handle for AC dimmer instance.
|
||||
*
|
||||
* Stores GPIO pin assignments, gptimer handle, zero-crossing timing state,
|
||||
* auto-calibrated base offset, current dimming level, and running state.
|
||||
*/
|
||||
struct _zh_ac_dimmer_handle_t
|
||||
{
|
||||
gpio_num_t zero_cross_gpio; /*!< GPIO pin for zero-crossing detection input */
|
||||
gpio_num_t triac_gpio; /*!< GPIO pin for TRIAC gate control output */
|
||||
gptimer_handle_t dimmer_timer_handle; /*!< gptimer instance used for TRIAC firing delay */
|
||||
uint64_t prev_zero_crossing_us; /*!< Timestamp of the previous rising edge (us) */
|
||||
uint64_t pulse_start_us; /*!< Timestamp of the current rising edge, used to measure pulse width (us) */
|
||||
uint32_t period_us; /*!< Filtered zero-crossing half-period in microseconds (0 until measured) */
|
||||
volatile uint32_t base_offset_us; /*!< Auto-calibrated advance of the zero-cross ISR relative to T0 (us) */
|
||||
volatile uint32_t auto_base_samples; /*!< Number of valid pulse-width measurements used for calibration */
|
||||
volatile uint8_t dimmer_value; /*!< Current dimming level, 0 off .. 100 full */
|
||||
volatile bool is_dimmer_work; /*!< Set when the dimmer is actively running */
|
||||
bool last_edge_was_rising; /*!< Tracks edge polarity to reject duplicate/glitch edges */
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Validate the AC dimmer initialization configuration.
|
||||
*
|
||||
* Checks that both GPIO pins are valid (less than `GPIO_NUM_MAX`) and are not
|
||||
* the same pin.
|
||||
*
|
||||
* @param config Pointer to the initialization configuration structure
|
||||
*
|
||||
* @return ESP_OK if the configuration is valid
|
||||
* @return ESP_ERR_INVALID_ARG if any GPIO pin is invalid, or both pins are the same
|
||||
*/
|
||||
static esp_err_t _zh_ac_dimmer_validate_config(const zh_ac_dimmer_init_config_t *config);
|
||||
static esp_err_t _zh_ac_dimmer_gpio_init(const zh_ac_dimmer_init_config_t *config);
|
||||
static esp_err_t _zh_ac_dimmer_timer_init(void);
|
||||
|
||||
/**
|
||||
* @brief Initialize GPIO pins for TRIAC control and zero-crossing detection.
|
||||
*
|
||||
* Configures the TRIAC GPIO as an output (pulled low) and the zero-crossing
|
||||
* GPIO as an input with pull-down and both-edge interrupt. Installs the
|
||||
* ESP-IDF ISR service (if not already installed) and registers the ISR
|
||||
* handler for the zero-crossing pin.
|
||||
*
|
||||
* @param config Pointer to the initialization configuration structure
|
||||
* @param handle Pointer to the dimmer handle to store GPIO pin numbers
|
||||
*
|
||||
* @return ESP_OK on success
|
||||
* @return ESP_FAIL if GPIO configuration, ISR service installation, or ISR
|
||||
* handler registration failed
|
||||
*
|
||||
* @note `ESP_ERR_INVALID_STATE` from `gpio_install_isr_service()` is treated
|
||||
* as success because the ISR service may have been installed previously.
|
||||
*/
|
||||
static esp_err_t _zh_ac_dimmer_gpio_init(const zh_ac_dimmer_init_config_t *config, zh_ac_dimmer_handle_t *handle);
|
||||
|
||||
/**
|
||||
* @brief Initialize the gptimer used for TRIAC firing delay.
|
||||
*
|
||||
* Creates a new gptimer with a 1 MHz resolution (1 us steps), registers the
|
||||
* alarm callback that fires the TRIAC, and enables the timer.
|
||||
* The timer is enabled but not started. It is stopped, reset and armed from
|
||||
* the rising-edge branch of the zero-crossing ISR, then started when a delay
|
||||
* is required.
|
||||
*
|
||||
* @param handle Pointer to the dimmer handle (timer handle stored here)
|
||||
*
|
||||
* @return ESP_OK on success
|
||||
* @return ESP_FAIL if timer creation, callback registration, or enable failed
|
||||
*/
|
||||
static esp_err_t _zh_ac_dimmer_timer_init(zh_ac_dimmer_handle_t *handle);
|
||||
|
||||
/**
|
||||
* @brief ISR handler for zero-crossing detection.
|
||||
*
|
||||
* Executed on both edges of the zero-crossing signal. The edge polarity is
|
||||
* determined from the current GPIO level:
|
||||
*
|
||||
* - On a falling edge (falling edge follows a rising edge of the same pulse),
|
||||
* the width of the zero-crossing pulse is measured and fed into the
|
||||
* auto-calibration EMA for `base_offset_us`. The value represents the
|
||||
* advance of the rising edge relative to the physical mains zero crossing
|
||||
* and is computed as `pulse_width / 2` (valid for a symmetric AC-input
|
||||
* optocoupler). No TRIAC action is taken on falling edges.
|
||||
*
|
||||
* - On a rising edge, the interval since the previous rising edge is compared
|
||||
* against the half-cycle range derived from `ZH_AC_DIMMER_FREQ_MIN_HZ` and
|
||||
* `ZH_AC_DIMMER_FREQ_MAX_HZ`:
|
||||
*
|
||||
* - An interval shorter than the minimum is treated as spurious and ignored.
|
||||
* - An interval longer than the maximum resets the timing state: the period
|
||||
* filter and the calibration sample counter are cleared, the TRIAC gate is
|
||||
* set low, and only the timestamp is kept.
|
||||
* - The first rising edge only stores its timestamp and sets the TRIAC gate low.
|
||||
*
|
||||
* Each accepted rising edge updates the low-pass filtered half-period and
|
||||
* resets the TRIAC gate low, then behaves according to the running state and
|
||||
* the dimming level:
|
||||
*
|
||||
* - When not running or at dimming = 0: the timer is stopped and reset, and
|
||||
* the gate stays low.
|
||||
* - When the computed delay is not positive: the TRIAC fires immediately
|
||||
* (gate set high).
|
||||
* - Otherwise: the gptimer alarm fires after a delay calculated from the
|
||||
* filtered period, the dimming value and the auto-calibrated base offset,
|
||||
* clamped to leave a guard band (period / 20, at least 5 us) before the
|
||||
* end of the half-cycle. The delay decreases as the dimming value
|
||||
* increases, so the TRIAC fires earlier and the load receives more power.
|
||||
*
|
||||
* @param arg Pointer to the dimmer handle (passed from GPIO ISR)
|
||||
*/
|
||||
static void _zh_ac_dimmer_isr_handler(void *arg);
|
||||
|
||||
/**
|
||||
* @brief gptimer alarm callback that fires the TRIAC.
|
||||
*
|
||||
* Stops the timer and clears its count, then sets the TRIAC gate high to
|
||||
* trigger conduction, but only while the dimmer is running and the dimming
|
||||
* level is above zero. Otherwise the gate is left unchanged until the next
|
||||
* zero-crossing event.
|
||||
*
|
||||
* @param timer Handle to the gptimer that triggered the alarm
|
||||
* @param edata Event data (unused)
|
||||
* @param user_ctx Pointer to the dimmer handle
|
||||
*
|
||||
* @return false to indicate that no higher-priority task needs to be woken
|
||||
*/
|
||||
static bool _zh_ac_dimmer_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx);
|
||||
|
||||
esp_err_t zh_ac_dimmer_init(const zh_ac_dimmer_init_config_t *config) // -V2008
|
||||
esp_err_t zh_ac_dimmer_init(const zh_ac_dimmer_init_config_t *config, zh_ac_dimmer_handle_t **handle)
|
||||
{
|
||||
ZH_LOGI("AC dimmer initialization started.");
|
||||
ZH_ERROR_CHECK(config != NULL, ESP_ERR_INVALID_ARG, NULL, "AC dimmer initialization failed. Invalid argument.");
|
||||
ZH_ERROR_CHECK(_is_initialized == false, ESP_ERR_INVALID_STATE, NULL, "AC dimmer initialization failed. AC dimmer is already initialized.");
|
||||
esp_err_t err = _zh_ac_dimmer_validate_config(config);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "AC dimmer initialization failed. Initial configuration check failed.");
|
||||
err = _zh_ac_dimmer_gpio_init(config);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "AC dimmer initialization failed. GPIO initialization failed.");
|
||||
err = _zh_ac_dimmer_timer_init();
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, err = gpio_isr_handler_remove((gpio_num_t)config->zero_cross_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Remove GPIO isr handler failed."); err = gpio_reset_pin((gpio_num_t)config->triac_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Reset GPIO failed."); err = gpio_reset_pin((gpio_num_t)config->zero_cross_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Reset GPIO failed."), "AC dimmer initialization failed. Timer initialization failed.");
|
||||
_init_config = *config;
|
||||
_is_initialized = true;
|
||||
ZH_ERROR_CHECK(config != NULL && handle != NULL, ESP_ERR_INVALID_ARG, NULL, "AC dimmer initialization failed. Invalid argument.");
|
||||
ZH_ERROR_CHECK(*handle == NULL, ESP_ERR_INVALID_STATE, NULL, "AC dimmer initialization failed. AC dimmer is already initialized.");
|
||||
*handle = heap_caps_calloc(1, sizeof(zh_ac_dimmer_handle_t), MALLOC_CAP_8BIT);
|
||||
ZH_ERROR_CHECK(*handle != NULL, ESP_ERR_NO_MEM, NULL, "AC dimmer initialization failed. Failed to allocate handle.");
|
||||
ZH_ERROR_CHECK(_zh_ac_dimmer_validate_config(config) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "AC dimmer initialization failed. Initial configuration check failed.");
|
||||
ZH_ERROR_CHECK(_zh_ac_dimmer_gpio_init(config, *handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "AC dimmer initialization failed. GPIO initialization failed.");
|
||||
ZH_ERROR_CHECK(_zh_ac_dimmer_timer_init(*handle) == ESP_OK, ESP_FAIL,
|
||||
{ZH_ERROR_CHECK_CONT(gpio_isr_handler_remove(config->zero_cross_gpio) == ESP_OK, NULL, "Remove GPIO isr handler failed.")};
|
||||
{ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->triac_gpio) == ESP_OK, NULL, "Reset GPIO failed.")};
|
||||
{ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->zero_cross_gpio) == ESP_OK, NULL, "Reset GPIO failed.")};
|
||||
heap_caps_free(*handle); *handle = NULL, "AC dimmer initialization failed. Timer initialization failed.");
|
||||
ZH_LOGI("AC dimmer initialization completed successfully.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t zh_ac_dimmer_deinit(void) // -V2008
|
||||
esp_err_t zh_ac_dimmer_deinit(zh_ac_dimmer_handle_t **handle)
|
||||
{
|
||||
ZH_LOGI("AC dimmer deinitialization started.");
|
||||
ZH_ERROR_CHECK(_is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "AC dimmer deinitialization failed. AC dimmer is not initialized.");
|
||||
esp_err_t err = gptimer_stop(_dimmer_timer);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "AC dimmer deinitialization failed. Timer stop fail.");
|
||||
err = gptimer_disable(_dimmer_timer);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "AC dimmer deinitialization failed. Timer disable fail.");
|
||||
err = gptimer_del_timer(_dimmer_timer);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "AC dimmer deinitialization failed. Timer delete fail.");
|
||||
err = gpio_isr_handler_remove((gpio_num_t)_init_config.zero_cross_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "AC dimmer deinitialization failed. Remove GPIO isr handler failed.");
|
||||
err = gpio_reset_pin((gpio_num_t)_init_config.triac_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "AC dimmer deinitialization failed. Reset GPIO failed.")
|
||||
err = gpio_reset_pin((gpio_num_t)_init_config.zero_cross_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "AC dimmer deinitialization failed. Reset GPIO failed.")
|
||||
_is_dimmer_work = false;
|
||||
_is_initialized = false;
|
||||
_dimmer_timer = NULL;
|
||||
_dimmer_value = 0;
|
||||
_prev_us = 0;
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "AC dimmer deinitialization failed. Invalid argument.");
|
||||
(*handle)->is_dimmer_work = false;
|
||||
ZH_ERROR_CHECK_CONT(gpio_isr_handler_remove((*handle)->zero_cross_gpio) == ESP_OK, NULL, "AC dimmer deinitialization failed. Remove GPIO isr handler failed.");
|
||||
ZH_ERROR_CHECK_CONT(gpio_reset_pin((*handle)->triac_gpio) == ESP_OK, NULL, "AC dimmer deinitialization failed. Reset GPIO failed.");
|
||||
ZH_ERROR_CHECK_CONT(gpio_reset_pin((*handle)->zero_cross_gpio) == ESP_OK, NULL, "AC dimmer deinitialization failed. Reset GPIO failed.");
|
||||
ZH_ERROR_CHECK_CONT(gptimer_stop((*handle)->dimmer_timer_handle) == ESP_OK, NULL, "AC dimmer deinitialization failed. Timer stop fail.");
|
||||
ZH_ERROR_CHECK_CONT(gptimer_disable((*handle)->dimmer_timer_handle) == ESP_OK, NULL, "AC dimmer deinitialization failed. Timer disable fail.");
|
||||
ZH_ERROR_CHECK_CONT(gptimer_del_timer((*handle)->dimmer_timer_handle) == ESP_OK, NULL, "AC dimmer deinitialization failed. Timer delete fail.");
|
||||
heap_caps_free(*handle);
|
||||
*handle = NULL;
|
||||
ZH_LOGI("AC dimmer deinitialization completed successfully.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t zh_ac_dimmer_start(void)
|
||||
esp_err_t zh_ac_dimmer_start(zh_ac_dimmer_handle_t **handle)
|
||||
{
|
||||
ZH_LOGI("AC dimmer start begin.");
|
||||
ZH_ERROR_CHECK(_is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "AC dimmer start failed. AC dimmer is not initialized.");
|
||||
_is_dimmer_work = true;
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "AC dimmer start failed. Invalid argument.");
|
||||
(*handle)->is_dimmer_work = true;
|
||||
ZH_LOGI("AC dimmer start completed successfully.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t zh_ac_dimmer_stop(void)
|
||||
esp_err_t zh_ac_dimmer_stop(zh_ac_dimmer_handle_t **handle)
|
||||
{
|
||||
ZH_LOGI("AC dimmer stop begin.");
|
||||
ZH_ERROR_CHECK(_is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "AC dimmer stop failed. AC dimmer is not initialized.");
|
||||
_is_dimmer_work = false;
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "AC dimmer stop failed. Invalid argument.");
|
||||
(*handle)->is_dimmer_work = false;
|
||||
ZH_LOGI("AC dimmer stop completed successfully.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t zh_ac_dimmer_set(uint8_t value)
|
||||
esp_err_t zh_ac_dimmer_set(zh_ac_dimmer_handle_t **handle, uint8_t value)
|
||||
{
|
||||
ZH_LOGI("AC dimmer setup begin.");
|
||||
ZH_ERROR_CHECK(_is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "AC dimmer setup failed. AC dimmer is not initialized.");
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "AC dimmer setup failed. Invalid argument.");
|
||||
ZH_ERROR_CHECK(value <= 100, ESP_ERR_INVALID_ARG, NULL, "AC dimmer setup failed. Dimming value invalid.");
|
||||
_dimmer_value = value;
|
||||
(*handle)->dimmer_value = value;
|
||||
ZH_LOGI("AC dimmer setup completed successfully.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t zh_ac_dimmer_get(uint8_t *value)
|
||||
esp_err_t zh_ac_dimmer_get(zh_ac_dimmer_handle_t **handle, uint8_t *value)
|
||||
{
|
||||
ZH_LOGI("AC dimmer getting status begin.");
|
||||
ZH_ERROR_CHECK(value != NULL, ESP_ERR_INVALID_ARG, NULL, "AC dimmer getting status failed. Invalid argument.");
|
||||
ZH_ERROR_CHECK(_is_initialized == true, ESP_ERR_INVALID_STATE, NULL, "AC dimmer getting status failed. AC dimmer is not initialized.");
|
||||
*value = _dimmer_value;
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL && value != NULL, ESP_ERR_INVALID_ARG, NULL, "AC dimmer getting status failed. Invalid argument.");
|
||||
*value = (*handle)->dimmer_value;
|
||||
ZH_LOGI("AC dimmer getting status completed successfully.");
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -119,7 +227,7 @@ static esp_err_t _zh_ac_dimmer_validate_config(const zh_ac_dimmer_init_config_t
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t _zh_ac_dimmer_gpio_init(const zh_ac_dimmer_init_config_t *config) // -V2008
|
||||
static esp_err_t _zh_ac_dimmer_gpio_init(const zh_ac_dimmer_init_config_t *config, zh_ac_dimmer_handle_t *handle)
|
||||
{
|
||||
gpio_config_t triac_gpio_config = {
|
||||
.intr_type = GPIO_INTR_DISABLE,
|
||||
@@ -128,83 +236,157 @@ static esp_err_t _zh_ac_dimmer_gpio_init(const zh_ac_dimmer_init_config_t *confi
|
||||
.pull_down_en = GPIO_PULLDOWN_DISABLE,
|
||||
.pull_up_en = GPIO_PULLUP_DISABLE,
|
||||
};
|
||||
esp_err_t err = gpio_config(&triac_gpio_config);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Triac GPIO configuration failed.");
|
||||
err = gpio_set_level((gpio_num_t)config->triac_gpio, 0);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Triac GPIO set failed.");
|
||||
ZH_ERROR_CHECK(gpio_config(&triac_gpio_config) == ESP_OK, ESP_FAIL, NULL, "Triac GPIO configuration failed.");
|
||||
ZH_ERROR_CHECK(gpio_set_level(config->triac_gpio, 0) == ESP_OK, ESP_FAIL, NULL, "Triac GPIO set failed.");
|
||||
gpio_config_t zero_cross_gpio_config = {
|
||||
.intr_type = GPIO_INTR_POSEDGE,
|
||||
.intr_type = GPIO_INTR_ANYEDGE,
|
||||
.mode = GPIO_MODE_INPUT,
|
||||
.pin_bit_mask = (1ULL << config->zero_cross_gpio),
|
||||
.pull_down_en = GPIO_PULLDOWN_ENABLE,
|
||||
.pull_up_en = GPIO_PULLUP_DISABLE,
|
||||
};
|
||||
err = gpio_config(&zero_cross_gpio_config);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, err = gpio_reset_pin((gpio_num_t)config->triac_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Reset GPIO failed."), "Zero cross GPIO configuration failed.");
|
||||
err = gpio_install_isr_service(ESP_INTR_FLAG_LOWMED);
|
||||
ZH_ERROR_CHECK(err == ESP_OK || err == ESP_ERR_INVALID_STATE, err, err = gpio_reset_pin((gpio_num_t)config->triac_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Reset GPIO failed."); err = gpio_reset_pin((gpio_num_t)config->zero_cross_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Reset GPIO failed."), "Failed install isr service.")
|
||||
err = gpio_isr_handler_add((gpio_num_t)config->zero_cross_gpio, _zh_ac_dimmer_isr_handler, NULL);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, err = gpio_reset_pin((gpio_num_t)config->triac_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Reset GPIO failed."); err = gpio_reset_pin((gpio_num_t)config->zero_cross_gpio);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Reset GPIO failed."), "Failed add isr handler.");
|
||||
ZH_ERROR_CHECK(gpio_config(&zero_cross_gpio_config) == ESP_OK, ESP_FAIL,
|
||||
{ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->triac_gpio) == ESP_OK, NULL, "Reset GPIO failed.")}, "Zero cross GPIO configuration failed.");
|
||||
esp_err_t err = gpio_install_isr_service(ESP_INTR_FLAG_LOWMED);
|
||||
ZH_ERROR_CHECK(err == ESP_OK || err == ESP_ERR_INVALID_STATE, ESP_FAIL,
|
||||
{ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->triac_gpio) == ESP_OK, NULL, "Reset GPIO failed.")};
|
||||
{ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->zero_cross_gpio) == ESP_OK, NULL, "Reset GPIO failed.")}, "Failed install isr service.")
|
||||
handle->triac_gpio = config->triac_gpio;
|
||||
handle->zero_cross_gpio = config->zero_cross_gpio;
|
||||
ZH_ERROR_CHECK(gpio_isr_handler_add(config->zero_cross_gpio, _zh_ac_dimmer_isr_handler, handle) == ESP_OK, ESP_FAIL,
|
||||
{ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->triac_gpio) == ESP_OK, NULL, "Reset GPIO failed.")};
|
||||
{ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->zero_cross_gpio) == ESP_OK, NULL, "Reset GPIO failed.")}, "Failed add isr handler.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t _zh_ac_dimmer_timer_init(void)
|
||||
static esp_err_t _zh_ac_dimmer_timer_init(zh_ac_dimmer_handle_t *handle)
|
||||
{
|
||||
gptimer_config_t timer_config = {
|
||||
.clk_src = GPTIMER_CLK_SRC_DEFAULT,
|
||||
.direction = GPTIMER_COUNT_UP,
|
||||
.resolution_hz = 1 * 1000 * 1000,
|
||||
.resolution_hz = 1000000,
|
||||
};
|
||||
esp_err_t err = gptimer_new_timer(&timer_config, &_dimmer_timer);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Failed create dimmer timer.");
|
||||
ZH_ERROR_CHECK(gptimer_new_timer(&timer_config, &handle->dimmer_timer_handle) == ESP_OK, ESP_FAIL, NULL, "Failed create dimmer timer.");
|
||||
gptimer_event_callbacks_t cbs = {
|
||||
.on_alarm = _zh_ac_dimmer_timer_on_alarm_cb,
|
||||
};
|
||||
err = gptimer_register_event_callbacks(_dimmer_timer, &cbs, NULL);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, err = gptimer_del_timer(_dimmer_timer);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Timer delete fail."), "Failed register dimmer timer event callbacks.");
|
||||
err = gptimer_enable(_dimmer_timer);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, err = gptimer_del_timer(_dimmer_timer);
|
||||
ZH_ERROR_CHECK(err == ESP_OK, err, NULL, "Timer delete fail."), "Failed enable dimmer timer.");
|
||||
ZH_ERROR_CHECK(gptimer_register_event_callbacks(handle->dimmer_timer_handle, &cbs, handle) == ESP_OK, ESP_FAIL,
|
||||
{ZH_ERROR_CHECK_CONT(gptimer_del_timer(handle->dimmer_timer_handle) == ESP_OK, NULL, "Timer delete fail.")}, "Failed register dimmer timer event callbacks.");
|
||||
ZH_ERROR_CHECK(gptimer_enable(handle->dimmer_timer_handle) == ESP_OK, ESP_FAIL,
|
||||
{ZH_ERROR_CHECK_CONT(gptimer_del_timer(handle->dimmer_timer_handle) == ESP_OK, NULL, "Timer delete fail.")}, "Failed enable dimmer timer.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void IRAM_ATTR _zh_ac_dimmer_isr_handler(void *arg)
|
||||
static void _zh_ac_dimmer_isr_handler(void *arg)
|
||||
{
|
||||
uint64_t _current_us = esp_timer_get_time();
|
||||
if (_current_us - _prev_us <= (1250 * 0.9)) // 90% of zero crossing period (1250 µs) at 400 Hz.
|
||||
zh_ac_dimmer_handle_t *handle = (zh_ac_dimmer_handle_t *)arg;
|
||||
uint64_t now_us = esp_timer_get_time();
|
||||
if (gpio_get_level(handle->zero_cross_gpio) == 0)
|
||||
{
|
||||
if (handle->last_edge_was_rising == true)
|
||||
{
|
||||
uint64_t pulse_width = now_us - handle->pulse_start_us;
|
||||
const uint64_t pulse_min_us = 4;
|
||||
const uint64_t pulse_max_us = (handle->period_us > 0) ? (handle->period_us / 4) : 2000;
|
||||
if (pulse_width >= pulse_min_us && pulse_width <= pulse_max_us)
|
||||
{
|
||||
uint32_t measured_adv = (uint32_t)(pulse_width / 2);
|
||||
if (handle->auto_base_samples == 0)
|
||||
{
|
||||
handle->base_offset_us = measured_adv;
|
||||
}
|
||||
else
|
||||
{
|
||||
handle->base_offset_us = (handle->base_offset_us * 15 + measured_adv) / 16;
|
||||
}
|
||||
if (handle->auto_base_samples < UINT32_MAX)
|
||||
{
|
||||
++handle->auto_base_samples;
|
||||
}
|
||||
}
|
||||
}
|
||||
handle->last_edge_was_rising = false;
|
||||
return;
|
||||
}
|
||||
handle->last_edge_was_rising = true;
|
||||
handle->pulse_start_us = now_us;
|
||||
if (handle->prev_zero_crossing_us == 0)
|
||||
{
|
||||
handle->prev_zero_crossing_us = now_us;
|
||||
gpio_set_level(handle->triac_gpio, 0);
|
||||
return;
|
||||
}
|
||||
uint64_t delta_us = now_us - handle->prev_zero_crossing_us;
|
||||
const uint64_t period_min_us = 1000000 / (2 * ZH_AC_DIMMER_FREQ_MAX_HZ);
|
||||
const uint64_t period_max_us = 1000000 / (2 * ZH_AC_DIMMER_FREQ_MIN_HZ);
|
||||
if (delta_us < period_min_us)
|
||||
{
|
||||
return;
|
||||
}
|
||||
gpio_set_level((gpio_num_t)_init_config.triac_gpio, 0);
|
||||
_prev_us = _current_us;
|
||||
if (_is_dimmer_work == false)
|
||||
if (delta_us > period_max_us)
|
||||
{
|
||||
handle->prev_zero_crossing_us = now_us;
|
||||
handle->period_us = 0;
|
||||
handle->auto_base_samples = 0;
|
||||
gpio_set_level(handle->triac_gpio, 0);
|
||||
return;
|
||||
}
|
||||
if (_dimmer_value != 0)
|
||||
if (handle->period_us == 0)
|
||||
{
|
||||
if (_dimmer_value == 100)
|
||||
handle->period_us = (uint32_t)delta_us;
|
||||
}
|
||||
else
|
||||
{
|
||||
gpio_set_level((gpio_num_t)_init_config.triac_gpio, 1);
|
||||
handle->period_us = (handle->period_us * 7 + (uint32_t)delta_us) / 8;
|
||||
}
|
||||
handle->prev_zero_crossing_us = now_us;
|
||||
gpio_set_level(handle->triac_gpio, 0);
|
||||
if (handle->is_dimmer_work == false || handle->dimmer_value == 0)
|
||||
{
|
||||
gptimer_stop(handle->dimmer_timer_handle);
|
||||
gptimer_set_raw_count(handle->dimmer_timer_handle, 0);
|
||||
return;
|
||||
}
|
||||
_alarm_config.alarm_count = (uint64_t)((((1250 - 330) / 100) * (100 - _dimmer_value)) + 330); // 330 is 50% of zero crossing time (by logic analyser).
|
||||
_alarm_config.flags.auto_reload_on_alarm = false;
|
||||
gptimer_set_alarm_action(_dimmer_timer, &_alarm_config);
|
||||
gptimer_start(_dimmer_timer);
|
||||
uint32_t period = handle->period_us;
|
||||
uint32_t base = handle->base_offset_us;
|
||||
if (base >= period)
|
||||
{
|
||||
base = period;
|
||||
}
|
||||
int32_t t_fire = (int32_t)(((uint64_t)period * (100 - handle->dimmer_value)) / 100);
|
||||
int32_t delay_us = t_fire + (int32_t)base;
|
||||
if (delay_us <= 0)
|
||||
{
|
||||
gpio_set_level(handle->triac_gpio, 1);
|
||||
return;
|
||||
}
|
||||
int32_t guard_us = (int32_t)(period / 20);
|
||||
if (guard_us < 5)
|
||||
{
|
||||
guard_us = 5;
|
||||
}
|
||||
if (delay_us > (int32_t)period - guard_us)
|
||||
{
|
||||
delay_us = (int32_t)period - guard_us;
|
||||
}
|
||||
gptimer_stop(handle->dimmer_timer_handle);
|
||||
gptimer_set_raw_count(handle->dimmer_timer_handle, 0);
|
||||
gptimer_alarm_config_t alarm_config = {0};
|
||||
alarm_config.alarm_count = (uint32_t)delay_us;
|
||||
alarm_config.flags.auto_reload_on_alarm = false;
|
||||
gptimer_set_alarm_action(handle->dimmer_timer_handle, &alarm_config);
|
||||
gptimer_start(handle->dimmer_timer_handle);
|
||||
}
|
||||
|
||||
static bool IRAM_ATTR _zh_ac_dimmer_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
|
||||
static bool _zh_ac_dimmer_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
|
||||
{
|
||||
gpio_set_level((gpio_num_t)_init_config.triac_gpio, 1);
|
||||
gptimer_stop(_dimmer_timer);
|
||||
gptimer_set_raw_count(_dimmer_timer, 0);
|
||||
(void)edata;
|
||||
zh_ac_dimmer_handle_t *handle = (zh_ac_dimmer_handle_t *)user_ctx;
|
||||
gptimer_stop(timer);
|
||||
gptimer_set_raw_count(timer, 0);
|
||||
if (handle->is_dimmer_work && handle->dimmer_value > 0)
|
||||
{
|
||||
gpio_set_level(handle->triac_gpio, 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
Reference in new issue
Block a user