Compare commits
4
Commits
780ffbbad0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb87e98189 | ||
|
|
d9872c8e94 | ||
|
|
b28ff61343 | ||
|
|
7f9f1b7f6f |
No files matched your search
@@ -192,12 +192,12 @@ void zh_encoder_event_handler(void *arg, esp_event_base_t event_base, int32_t ev
|
||||
if (event_id == ZH_BUTTON_EVENT)
|
||||
{
|
||||
zh_encoder_button_event_on_isr_t *button_event = (zh_encoder_button_event_on_isr_t *)event_data;
|
||||
printf("Encoder %d button %s\n", button_event->encoder_number, button_event->button_status ? "released" : "pressed");
|
||||
printf("Encoder %d button %s\n", button_event->encoder_number, button_event->button_status == ZH_ENCODER_BUTTON_STATUS_RELEASED ? "released" : "pressed");
|
||||
}
|
||||
else if (event_id == ZH_ENCODER_EVENT)
|
||||
{
|
||||
zh_encoder_event_on_isr_t *encoder_event = (zh_encoder_event_on_isr_t *)event_data;
|
||||
printf("Encoder %d position %0.3f %s\n", encoder_event->encoder_number, encoder_event->encoder_position, encoder_event->encoder_status ? "increased" : "reduced");
|
||||
printf("Encoder %d position %0.3f %s\n", encoder_event->encoder_number, encoder_event->encoder_position, encoder_event->encoder_status == ZH_ENCODER_STATUS_INCREASED ? "increased" : "reduced");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
description: ESP32 ESP-IDF component for rotary encoder
|
||||
url: https://github.com/aZholtikov/zh_encoder
|
||||
version: "3.1.0"
|
||||
version: "3.2.0"
|
||||
license: "Apache-2.0"
|
||||
maintainers:
|
||||
- "Alexey Zholtikov <alexey.zholtikov@yandex.ru>"
|
||||
|
||||
+22
-2
@@ -20,6 +20,8 @@
|
||||
*
|
||||
* @note All public functions require a valid handle pointer obtained through zh_encoder_init().
|
||||
* @note Rotation and button events are posted from task context (shared processing task and timer callback).
|
||||
* @note Button state semantics: with pull-up enabled (default), the pressed level is read as 0
|
||||
* (ZH_ENCODER_BUTTON_STATUS_PRESSED) and the released level as 1 (ZH_ENCODER_BUTTON_STATUS_RELEASED).
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
@@ -121,6 +123,15 @@ extern "C"
|
||||
|
||||
ESP_EVENT_DECLARE_BASE(ZH_ENCODER);
|
||||
|
||||
/**
|
||||
* @brief Encoder rotation direction reported in rotation events.
|
||||
*/
|
||||
typedef enum
|
||||
{
|
||||
ZH_ENCODER_STATUS_DECREASED, /*!< Encoder position decreased */
|
||||
ZH_ENCODER_STATUS_INCREASED /*!< Encoder position increased */
|
||||
} zh_encoder_status_t;
|
||||
|
||||
/**
|
||||
* @brief Event data structure for encoder rotation events.
|
||||
*
|
||||
@@ -132,9 +143,18 @@ extern "C"
|
||||
{
|
||||
float encoder_position; /*!< Encoder current position */
|
||||
uint8_t encoder_number; /*!< Encoder unique number */
|
||||
bool encoder_status; /*!< true if position increased, false if reduced */
|
||||
zh_encoder_status_t encoder_status; /*!< Rotation direction */
|
||||
} zh_encoder_event_on_isr_t;
|
||||
|
||||
/**
|
||||
* @brief Encoder push-button state reported in button events.
|
||||
*/
|
||||
typedef enum
|
||||
{
|
||||
ZH_ENCODER_BUTTON_STATUS_PRESSED, /*!< Button is pressed */
|
||||
ZH_ENCODER_BUTTON_STATUS_RELEASED /*!< Button is released */
|
||||
} zh_encoder_button_status_t;
|
||||
|
||||
/**
|
||||
* @brief Event data structure for encoder button events.
|
||||
*
|
||||
@@ -146,7 +166,7 @@ extern "C"
|
||||
typedef struct
|
||||
{
|
||||
uint8_t encoder_number; /*!< Encoder unique number */
|
||||
bool button_status; /*!< Encoder button status */
|
||||
zh_encoder_button_status_t button_status; /*!< Debounced button state */
|
||||
} zh_encoder_button_event_on_isr_t;
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
3.1.0
|
||||
3.2.0
|
||||
+19
-17
@@ -23,7 +23,7 @@
|
||||
Внутренняя структура энкодера (opaque-хэндл, доступен только через API компонента):
|
||||
|
||||
| Поле | Тип | Описание |
|
||||
| ------ | ----- | ---------- |
|
||||
| ----------------------- | ----------------------- | ----------------------------------------------------------------------- |
|
||||
| `s_gpio_status` | `bool` | Текущее состояние кнопки (обновляется только колбэком таймера дребезга) |
|
||||
| `encoder_number` | `uint8_t` | Уникальный номер энкодера, передаётся в событиях |
|
||||
| `s_gpio_number` | `gpio_num_t` | GPIO кнопки (`GPIO_NUM_MAX`, если кнопка отключена) |
|
||||
@@ -45,7 +45,7 @@
|
||||
Передаётся из ISR точки наблюдения PCNT в общую задачу обработки:
|
||||
|
||||
| Поле | Тип | Описание |
|
||||
|------|-----|----------|
|
||||
| -------- | ----------------------- | ---------------------------------------------------------- |
|
||||
| `count` | `int32_t` | Знаковое значение счётчика PCNT, прочитанное перед сбросом |
|
||||
| `handle` | `zh_encoder_handle_t *` | Указатель на хэндл энкодера-источника |
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
### Общие (статические) ресурсы
|
||||
|
||||
| Ресурс | Тип | Описание |
|
||||
| -------- | ----- | ---------- |
|
||||
| --------------- | -------------------- | ----------------------------------------------------------------- |
|
||||
| `zh_encoder` | `TaskHandle_t` | Дескриптор общей задачи обработки, создаётся для первого энкодера |
|
||||
| `_queue_handle` | `QueueHandle_t` | Общая очередь сообщений от ISR PCNT к задаче обработки |
|
||||
| `_spinlock` | `portMUX_TYPE` | Спинлок для защиты общих данных энкодеров |
|
||||
@@ -76,7 +76,7 @@
|
||||
### Инициализация и освобождение
|
||||
|
||||
| Функция | Описание |
|
||||
| --------- | ---------- |
|
||||
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `zh_encoder_init()` | Создаёт энкодер по конфигурации: проверяет параметры, регистрирует номер в векторе, при необходимости создаёт общую очередь и задачу, инициализирует PCNT и GPIO кнопки. Позиция устанавливается в середину диапазона. Требует, чтобы входной `*handle` был равен `NULL`. |
|
||||
| `zh_encoder_deinit()` | Останавливает PCNT, удаляет каналы и единицу, снимает обработчик GPIO прерываний и таймер кнопки, удаляет номер из вектора. При удалении последнего энкодера удаляет общую задачу, очередь и вектор. Устанавливает входной указатель в `NULL`. |
|
||||
| `zh_encoder_reinit()` | Меняет диапазон (`min`, `max`) и шаг (`step`) без перераспределения ресурсов, сбрасывает позицию в середину нового диапазона и обнуляет счётчик PCNT. |
|
||||
@@ -84,7 +84,7 @@
|
||||
### Управление позицией
|
||||
|
||||
| Функция | Описание |
|
||||
|---------|----------|
|
||||
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| `zh_encoder_set()` | Устанавливает позицию в заданное значение (в пределах настроенного диапазона), обнуляет аккумулятор и счётчик PCNT. |
|
||||
| `zh_encoder_get()` | Читает текущую позицию энкодера. |
|
||||
| `zh_encoder_reset()` | Сбрасывает позицию в середину диапазона `(min + max) / 2` и обнуляет счётчик PCNT. |
|
||||
@@ -92,20 +92,22 @@
|
||||
### Статистика
|
||||
|
||||
| Функция | Описание |
|
||||
|---------|----------|
|
||||
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `zh_encoder_get_stats()` | Возвращает read-only указатель на глобальную структуру статистики `zh_encoder_stats_t`. Указатель действителен до вызова `zh_encoder_reset_stats()`. |
|
||||
| `zh_encoder_reset_stats()` | Обнуляет все счётчики статистики. |
|
||||
|
||||
### Типы и события
|
||||
|
||||
| Элемент | Описание |
|
||||
| --------- | ---------- |
|
||||
| `zh_encoder_init_config_t` | Конфигурация инициализации: GPIO, диапазон, шаг, параметры задачи и уникальный номер. Значения по умолчанию задаёт `ZH_ENCODER_INIT_CONFIG_DEFAULT()`. |
|
||||
| `zh_encoder_stats_t` | Статистика: `event_post_error`, `queue_overflow_error`, `min_stack_size`. |
|
||||
| `zh_encoder_event_on_isr_t` | Данные события поворота: позиция, номер энкодера, направление (`true` — увеличение). |
|
||||
| `zh_encoder_button_event_on_isr_t` | Данные события кнопки: номер энкодера, состояние. |
|
||||
| `zh_encoder_event_id_t` | Идентификаторы событий: `ZH_BUTTON_EVENT`, `ZH_ENCODER_EVENT`. |
|
||||
| `ZH_ENCODER` | База событий `esp_event`, в которую компонент постит все сообщения. |
|
||||
| Тип | Конструктор значений | Значения |
|
||||
| ---------------------------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `zh_encoder_init_config_t` | `ZH_ENCODER_INIT_CONFIG_DEFAULT()` | Конфигурация инициализации: GPIO, диапазон, шаг, параметры задачи и уникальный номер |
|
||||
| `zh_encoder_stats_t` | — | Статистика: `event_post_error`, `queue_overflow_error`, `min_stack_size` |
|
||||
| `zh_encoder_event_id_t` | — | Идентификаторы событий: `ZH_BUTTON_EVENT`, `ZH_ENCODER_EVENT` |
|
||||
| `zh_encoder_status_t` | — | Направление поворота: `ZH_ENCODER_STATUS_DECREASED`, `ZH_ENCODER_STATUS_INCREASED` |
|
||||
| `zh_encoder_button_status_t` | — | Состояние кнопки: `ZH_ENCODER_BUTTON_STATUS_PRESSED` (уровень 0), `ZH_ENCODER_BUTTON_STATUS_RELEASED` (уровень 1) |
|
||||
| `zh_encoder_event_on_isr_t` | — | Данные события поворота: позиция, номер энкодера, направление (`zh_encoder_status_t`) |
|
||||
| `zh_encoder_button_event_on_isr_t` | — | Данные события кнопки: номер энкодера, состояние (`zh_encoder_button_status_t`) |
|
||||
| `ZH_ENCODER` | `ESP_EVENT_DEFINE_BASE` | База событий `esp_event`, в которую компонент постит все сообщения |
|
||||
|
||||
## Потокобезопасность
|
||||
|
||||
@@ -161,11 +163,11 @@ void zh_encoder_event_handler(void *arg, esp_event_base_t event_base, int32_t ev
|
||||
if (event_id == ZH_ENCODER_EVENT) {
|
||||
zh_encoder_event_on_isr_t *rot = (zh_encoder_event_on_isr_t *)event_data;
|
||||
printf("Encoder %d: position %0.3f (%s)\n", rot->encoder_number,
|
||||
rot->encoder_position, rot->encoder_status ? "up" : "down");
|
||||
rot->encoder_position, rot->encoder_status == ZH_ENCODER_STATUS_INCREASED ? "up" : "down");
|
||||
} else if (event_id == ZH_BUTTON_EVENT) {
|
||||
zh_encoder_button_event_on_isr_t *btn = (zh_encoder_button_event_on_isr_t *)event_data;
|
||||
printf("Encoder %d: button %s\n", btn->encoder_number,
|
||||
btn->button_status ? "released" : "pressed");
|
||||
btn->button_status == ZH_ENCODER_BUTTON_STATUS_RELEASED ? "released" : "pressed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,7 +262,7 @@ esp_log_level_set("zh_encoder", ESP_LOG_ERROR);
|
||||
## Ошибки
|
||||
|
||||
| Код | Описание |
|
||||
| ----- | ---------- |
|
||||
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ESP_OK` | Операция выполнена успешно |
|
||||
| `ESP_ERR_INVALID_ARG` | NULL-аргументы, неверные параметры конфигурации (диапазон, шаг, номер, GPIO), дублирование номера энкодера, позиция вне диапазона |
|
||||
| `ESP_ERR_INVALID_STATE` | Энкодер по входному хэндлу уже инициализирован (`*handle != NULL`) |
|
||||
|
||||
+69
-25
@@ -13,6 +13,14 @@
|
||||
return err; \
|
||||
}
|
||||
|
||||
#define ZH_ERROR_CHECK_VOID(cond, cleanup, msg, ...) \
|
||||
if (!(cond)) \
|
||||
{ \
|
||||
ZH_LOGE(msg, ESP_FAIL, ##__VA_ARGS__); \
|
||||
cleanup; \
|
||||
return; \
|
||||
}
|
||||
|
||||
#define ZH_ERROR_CHECK_CONT(cond, cleanup, msg, ...) \
|
||||
if (!(cond)) \
|
||||
{ \
|
||||
@@ -47,6 +55,7 @@ struct _zh_encoder_handle_t
|
||||
pcnt_channel_handle_t pcnt_channel_a_handle; /*!< PCNT channel A handle */
|
||||
pcnt_channel_handle_t pcnt_channel_b_handle; /*!< PCNT channel B handle */
|
||||
TimerHandle_t button_timer; /*!< One-shot debounce timer for the button */
|
||||
portMUX_TYPE lock; /*!< Spinlock protecting fields accessed from ISR and task context */
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -67,7 +76,6 @@ typedef struct
|
||||
|
||||
TaskHandle_t zh_encoder = NULL;
|
||||
static QueueHandle_t _queue_handle = NULL;
|
||||
static portMUX_TYPE _spinlock = portMUX_INITIALIZER_UNLOCKED;
|
||||
|
||||
static zh_encoder_stats_t _stats = {0};
|
||||
static zh_vector_t *_vector = NULL;
|
||||
@@ -146,6 +154,15 @@ static esp_err_t _zh_encoder_resources_init(const zh_encoder_init_config_t *conf
|
||||
*/
|
||||
static esp_err_t _zh_encoder_task_init(const zh_encoder_init_config_t *config);
|
||||
|
||||
/**
|
||||
* @brief Roll back shared resources (queue, task) if the failed init was
|
||||
* the first (and only) device.
|
||||
*
|
||||
* Must be called BEFORE zh_vector_delete_back(&_vector) — otherwise the
|
||||
* vector size will no longer reflect "first device".
|
||||
*/
|
||||
static void _zh_encoder_rollback_task_and_resources(void);
|
||||
|
||||
/**
|
||||
* @brief PCNT watch-point interrupt handler.
|
||||
*
|
||||
@@ -218,12 +235,14 @@ esp_err_t zh_encoder_init(const zh_encoder_init_config_t *config, zh_encoder_han
|
||||
ZH_ERROR_CHECK(zh_vector_init(&_vector, sizeof(uint8_t)) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. Failed to create vector.");
|
||||
}
|
||||
ZH_ERROR_CHECK(zh_vector_push_back(&_vector, &config->encoder_number) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. Failed to add vector data.");
|
||||
ZH_ERROR_CHECK(_zh_encoder_resources_init(config) == ESP_OK, ESP_FAIL, zh_vector_delete_back(&_vector); heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. Resources initialization failed.");
|
||||
ZH_ERROR_CHECK(_zh_encoder_task_init(config) == ESP_OK, ESP_FAIL,
|
||||
zh_vector_delete_back(&_vector);
|
||||
ZH_ERROR_CHECK(_zh_encoder_resources_init(config) == ESP_OK, ESP_FAIL,
|
||||
{ZH_ERROR_CHECK_CONT(zh_vector_delete_back(&_vector) == ESP_OK, NULL, "Failed delete vector data.")};
|
||||
heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. Resources initialization failed.");
|
||||
ZH_ERROR_CHECK(_zh_encoder_task_init(config) == ESP_OK, ESP_FAIL, _zh_encoder_rollback_task_and_resources();
|
||||
{ZH_ERROR_CHECK_CONT(zh_vector_delete_back(&_vector) == ESP_OK, NULL, "Failed delete vector data.")};
|
||||
heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. Processing task initialization failed.");
|
||||
ZH_ERROR_CHECK(_zh_encoder_pcnt_init(config, *handle) == ESP_OK, ESP_FAIL,
|
||||
zh_vector_delete_back(&_vector);
|
||||
ZH_ERROR_CHECK(_zh_encoder_pcnt_init(config, *handle) == ESP_OK, ESP_FAIL, _zh_encoder_rollback_task_and_resources();
|
||||
{ZH_ERROR_CHECK_CONT(zh_vector_delete_back(&_vector) == ESP_OK, NULL, "Failed delete vector data.")};
|
||||
heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. PCNT initialization failed.");
|
||||
ZH_ERROR_CHECK(_zh_encoder_gpio_init(config, *handle) == ESP_OK, ESP_FAIL,
|
||||
{ZH_ERROR_CHECK_CONT(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "PCNT unit stop fail.")};
|
||||
@@ -231,7 +250,10 @@ esp_err_t zh_encoder_init(const zh_encoder_init_config_t *config, zh_encoder_han
|
||||
{ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
|
||||
{ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_b_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
|
||||
{ZH_ERROR_CHECK_CONT(pcnt_del_unit((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "PCNT delete unit fail.")};
|
||||
zh_vector_delete_back(&_vector); heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. GPIO initialization failed.");
|
||||
_zh_encoder_rollback_task_and_resources();
|
||||
{ZH_ERROR_CHECK_CONT(zh_vector_delete_back(&_vector) == ESP_OK, NULL, "Failed delete vector data.")};
|
||||
heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. GPIO initialization failed.");
|
||||
portMUX_INITIALIZE(&(*handle)->lock);
|
||||
if (_stats.min_stack_size == 0)
|
||||
{
|
||||
_stats.min_stack_size = config->stack_size;
|
||||
@@ -293,13 +315,13 @@ esp_err_t zh_encoder_reinit(zh_encoder_handle_t **handle, float min, float max,
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder reinitialization failed. Invalid argument.");
|
||||
ZH_ERROR_CHECK(max > min, ESP_ERR_INVALID_ARG, NULL, "Encoder reinitialization failed. Invalid encoder min/max value.");
|
||||
ZH_ERROR_CHECK(step > 0, ESP_ERR_INVALID_ARG, NULL, "Encoder reinitialization failed. Invalid encoder step.");
|
||||
taskENTER_CRITICAL(&_spinlock);
|
||||
taskENTER_CRITICAL(&(*handle)->lock);
|
||||
(*handle)->encoder_min_value = min;
|
||||
(*handle)->encoder_max_value = max;
|
||||
(*handle)->encoder_step = step;
|
||||
(*handle)->encoder_position = ((*handle)->encoder_min_value + (*handle)->encoder_max_value) / 2;
|
||||
(*handle)->count_accumulator = 0;
|
||||
taskEXIT_CRITICAL(&_spinlock);
|
||||
taskEXIT_CRITICAL(&(*handle)->lock);
|
||||
ZH_ERROR_CHECK(pcnt_unit_clear_count((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Encoder reinitialization failed. Internal error.");
|
||||
ZH_LOGI("Encoder reinitialization completed successfully.");
|
||||
return ESP_OK;
|
||||
@@ -309,11 +331,11 @@ esp_err_t zh_encoder_set(zh_encoder_handle_t **handle, float position)
|
||||
{
|
||||
ZH_LOGI("Encoder set position started.");
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder set position failed. Invalid argument.");
|
||||
taskENTER_CRITICAL(&_spinlock);
|
||||
ZH_ERROR_CHECK(position <= (*handle)->encoder_max_value && position >= (*handle)->encoder_min_value, ESP_ERR_INVALID_ARG, taskEXIT_CRITICAL(&_spinlock), "Encoder set position failed. Invalid argument.");
|
||||
taskENTER_CRITICAL(&(*handle)->lock);
|
||||
ZH_ERROR_CHECK(position <= (*handle)->encoder_max_value && position >= (*handle)->encoder_min_value, ESP_ERR_INVALID_ARG, taskEXIT_CRITICAL(&(*handle)->lock), "Encoder set position failed. Invalid argument.");
|
||||
(*handle)->encoder_position = position;
|
||||
(*handle)->count_accumulator = 0;
|
||||
taskEXIT_CRITICAL(&_spinlock);
|
||||
taskEXIT_CRITICAL(&(*handle)->lock);
|
||||
ZH_ERROR_CHECK(pcnt_unit_clear_count((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Encoder set position failed. Internal error.");
|
||||
ZH_LOGI("Encoder set position completed successfully.");
|
||||
return ESP_OK;
|
||||
@@ -323,9 +345,9 @@ esp_err_t zh_encoder_get(zh_encoder_handle_t **handle, float *position)
|
||||
{
|
||||
ZH_LOGI("Encoder get position started.");
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL && position != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder get position failed. Invalid argument.");
|
||||
taskENTER_CRITICAL(&_spinlock);
|
||||
taskENTER_CRITICAL(&(*handle)->lock);
|
||||
*position = (*handle)->encoder_position;
|
||||
taskEXIT_CRITICAL(&_spinlock);
|
||||
taskEXIT_CRITICAL(&(*handle)->lock);
|
||||
ZH_LOGI("Encoder get position completed successfully.");
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -334,10 +356,10 @@ esp_err_t zh_encoder_reset(zh_encoder_handle_t **handle)
|
||||
{
|
||||
ZH_LOGI("Encoder reset started.");
|
||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder reset failed. Invalid argument.");
|
||||
taskENTER_CRITICAL(&_spinlock);
|
||||
taskENTER_CRITICAL(&(*handle)->lock);
|
||||
(*handle)->encoder_position = ((*handle)->encoder_min_value + (*handle)->encoder_max_value) / 2;
|
||||
(*handle)->count_accumulator = 0;
|
||||
taskEXIT_CRITICAL(&_spinlock);
|
||||
taskEXIT_CRITICAL(&(*handle)->lock);
|
||||
ZH_ERROR_CHECK(pcnt_unit_clear_count((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Encoder reset failed. Internal error.");
|
||||
ZH_LOGI("Encoder reset completed successfully.");
|
||||
return ESP_OK;
|
||||
@@ -534,24 +556,46 @@ static esp_err_t _zh_encoder_task_init(const zh_encoder_init_config_t *config)
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void _zh_encoder_rollback_task_and_resources(void)
|
||||
{
|
||||
if (_vector != NULL)
|
||||
{
|
||||
uint16_t vector_size = 0;
|
||||
ZH_ERROR_CHECK_VOID(zh_vector_get_size(&_vector, &vector_size) == ESP_OK, NULL, "Failed to get vector size.");
|
||||
if (vector_size == 1)
|
||||
{
|
||||
if (zh_encoder != NULL)
|
||||
{
|
||||
vTaskDelete(zh_encoder);
|
||||
zh_encoder = NULL;
|
||||
}
|
||||
if (_queue_handle != NULL)
|
||||
{
|
||||
vQueueDelete(_queue_handle);
|
||||
_queue_handle = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool _zh_encoder_isr_handler(pcnt_unit_handle_t unit, const pcnt_watch_event_data_t *edata, void *user_ctx)
|
||||
{
|
||||
(void)edata;
|
||||
zh_encoder_handle_t *encoder_handle = (zh_encoder_handle_t *)user_ctx;
|
||||
zh_encoder_queue_t encoder_queue = {0};
|
||||
int count = 0;
|
||||
taskENTER_CRITICAL_ISR(&_spinlock);
|
||||
taskENTER_CRITICAL_ISR(&encoder_handle->lock);
|
||||
if (pcnt_unit_get_count(unit, &count) != ESP_OK)
|
||||
{
|
||||
taskEXIT_CRITICAL_ISR(&_spinlock);
|
||||
taskEXIT_CRITICAL_ISR(&encoder_handle->lock);
|
||||
return false;
|
||||
}
|
||||
if (pcnt_unit_clear_count(unit) != ESP_OK)
|
||||
{
|
||||
taskEXIT_CRITICAL_ISR(&_spinlock);
|
||||
taskEXIT_CRITICAL_ISR(&encoder_handle->lock);
|
||||
return false;
|
||||
}
|
||||
taskEXIT_CRITICAL_ISR(&_spinlock);
|
||||
taskEXIT_CRITICAL_ISR(&encoder_handle->lock);
|
||||
encoder_queue.count = count;
|
||||
encoder_queue.handle = encoder_handle;
|
||||
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
|
||||
@@ -574,10 +618,10 @@ static void _zh_encoder_isr_processing_task(void *pvParameter)
|
||||
{
|
||||
zh_encoder_handle_t *handle = encoder_queue.handle;
|
||||
bool position_changed = false;
|
||||
bool encoder_status = false;
|
||||
zh_encoder_status_t encoder_status = ZH_ENCODER_STATUS_DECREASED;
|
||||
float encoder_position = 0.0;
|
||||
uint8_t encoder_number = 0;
|
||||
taskENTER_CRITICAL(&_spinlock);
|
||||
taskENTER_CRITICAL(&handle->lock);
|
||||
int32_t total = handle->count_accumulator + encoder_queue.count;
|
||||
int32_t full_steps = total / (int32_t)handle->pcnt_counts_per_step;
|
||||
handle->count_accumulator = total - full_steps * (int32_t)handle->pcnt_counts_per_step;
|
||||
@@ -600,12 +644,12 @@ static void _zh_encoder_isr_processing_task(void *pvParameter)
|
||||
{
|
||||
handle->encoder_position = candidate;
|
||||
position_changed = true;
|
||||
encoder_status = full_steps > 0 ? true : false;
|
||||
encoder_status = full_steps > 0 ? ZH_ENCODER_STATUS_INCREASED : ZH_ENCODER_STATUS_DECREASED;
|
||||
encoder_position = candidate;
|
||||
encoder_number = handle->encoder_number;
|
||||
}
|
||||
}
|
||||
taskEXIT_CRITICAL(&_spinlock);
|
||||
taskEXIT_CRITICAL(&handle->lock);
|
||||
if (position_changed == true)
|
||||
{
|
||||
zh_encoder_event_on_isr_t encoder_data = {0};
|
||||
@@ -628,7 +672,7 @@ static void _zh_encoder_button_timer_cb(TimerHandle_t xTimer)
|
||||
encoder_handle->s_gpio_status = s_gpio_status;
|
||||
zh_encoder_button_event_on_isr_t encoder_data = {0};
|
||||
encoder_data.encoder_number = encoder_handle->encoder_number;
|
||||
encoder_data.button_status = s_gpio_status;
|
||||
encoder_data.button_status = s_gpio_status == true ? ZH_ENCODER_BUTTON_STATUS_RELEASED : ZH_ENCODER_BUTTON_STATUS_PRESSED;
|
||||
ZH_ERROR_CHECK_CONT(esp_event_post(ZH_ENCODER, ZH_BUTTON_EVENT, &encoder_data, sizeof(encoder_data), pdMS_TO_TICKS(10)) == ESP_OK, ++_stats.event_post_error, "Encoder button isr processing failed. Failed to post interrupt event.");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user