perf: updated error checks

This commit is contained in:
aZholtikov committed 2026-10-18 10:18:39 +03:00
1 parent 19e94cfb71
commit 4de0443b35
2 files changed
+301 -212

No files matched your search

+47 -30
View File
@@ -1,19 +1,25 @@
/** /**
* @file zh_encoder.h * @file zh_encoder.h
* *
* @brief Rotary encoder driver for ESP-IDF using PCNT peripheral. * @brief Rotary encoder driver for ESP-IDF using the PCNT peripheral.
* *
* Provides a FreeRTOS-based driver for rotary encoders with optional * Provides a FreeRTOS-based driver for rotary encoders with optional
* push-button support. Uses ESP-IDF PCNT peripheral for quadrature * push-button support. Uses ESP-IDF PCNT peripheral for quadrature
* decoding and esp_event for asynchronous event notification. * decoding and esp_event for asynchronous event notification.
* Rotation counts are accumulated in a shared task, converted into
* configurable steps and clamped to the configured value range.
* *
* Key features: * Key features:
* - Quadrature decoding via PCNT peripheral * - Quadrature decoding via PCNT peripheral (ESP-IDF-style edge/level actions)
* - Configurable min/max/step values with float precision * - Configurable min/max/step values with float precision
* - Push-button support with debouncing * - Configurable PCNT counts per encoder step (detent)
* - Multiple simultaneous encoders (up to 8) * - Push-button support with timer-based debouncing
* - Event-based notification (ISR context) * - Multiple simultaneous encoders (number is limited by available PCNT units and GPIOs)
* - Event-based notification (rotation and button events are posted from task context)
* - Error statistics tracking * - Error statistics tracking
*
* @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).
*/ */
#pragma once #pragma once
@@ -37,12 +43,13 @@
.a_gpio_number = GPIO_NUM_MAX, \ .a_gpio_number = GPIO_NUM_MAX, \
.b_gpio_number = GPIO_NUM_MAX, \ .b_gpio_number = GPIO_NUM_MAX, \
.s_gpio_number = GPIO_NUM_MAX, \ .s_gpio_number = GPIO_NUM_MAX, \
.s_gpio_debounce_time = 10, \ .s_gpio_debounce_time = 15000, \
.pullup = true, \ .pullup = true, \
.encoder_min_value = -10, \ .encoder_min_value = -10, \
.encoder_max_value = 10, \ .encoder_max_value = 10, \
.encoder_step = 1, \ .encoder_step = 1, \
.encoder_number = 0} .pcnt_counts_per_step = 4, \
.encoder_number = 1}
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C"
@@ -56,56 +63,60 @@ extern "C"
/** /**
* @brief Opaque encoder handle. * @brief Opaque encoder handle.
*
* Opaque pointer to the internal encoder structure.
* Used to reference a specific encoder instance across all API functions.
*/ */
typedef struct _zh_encoder_handle_t zh_encoder_handle_t; typedef struct _zh_encoder_handle_t zh_encoder_handle_t;
/** /**
* @brief Configuration structure for encoder initialization. * @brief Configuration structure for encoder initialization.
* *
* Contains all parameters required to configure a rotary encoder, * Holds all parameters required to create an encoder: GPIO assignments,
* including GPIO pins, value range, step size, and task settings. * value range, step size, shared task settings and a unique encoder number.
* Use ZH_ENCODER_INIT_CONFIG_DEFAULT() to obtain a valid starting configuration.
* *
* @note All GPIO numbers must be valid ESP-IDF GPIO numbers or GPIO_NUM_MAX (disabled). * @note All GPIO numbers must be valid ESP-IDF GPIO numbers or GPIO_NUM_MAX (disabled).
* @note encoder_number must be unique across all initialized encoders. * @note encoder_number must be unique across all initialized encoders.
* @note Only the first initialized encoder's task_priority, stack_size and
* queue_size take effect (shared processing task/queue).
*/ */
typedef struct typedef struct
{ {
float encoder_step; /*!< Encoder step. @note Must be greater than 0 */ float encoder_step; /*!< Encoder step per detent. @note Must be greater than 0 */
float encoder_min_value; /*!< Encoder min value. @note Must be less than encoder_max_value */ float encoder_min_value; /*!< Encoder min value. @note Must be less than encoder_max_value */
float encoder_max_value; /*!< Encoder max value. @note Must be greater than encoder_min_value */ float encoder_max_value; /*!< Encoder max value. @note Must be greater than encoder_min_value */
gpio_num_t a_gpio_number; /*!< Encoder A GPIO number */ gpio_num_t a_gpio_number; /*!< Encoder A GPIO number */
gpio_num_t b_gpio_number; /*!< Encoder B GPIO number */ gpio_num_t b_gpio_number; /*!< Encoder B GPIO number */
gpio_num_t s_gpio_number; /*!< Encoder button GPIO number */ gpio_num_t s_gpio_number; /*!< Encoder button GPIO number */
uint16_t s_gpio_debounce_time; /*!< Encoder button debounce_time. @note In microseconds */ uint16_t s_gpio_debounce_time; /*!< Encoder button debounce time in microseconds. Rounded up to whole milliseconds for the debounce timer */
uint16_t stack_size; /*!< Stack size for task for the encoder isr processing processing. @note The minimum size is configMINIMAL_STACK_SIZE */ uint16_t stack_size; /*!< Stack size for the shared processing task. @note Minimum configMINIMAL_STACK_SIZE */
uint8_t task_priority; /*!< Task priority for the encoder isr processing. @note Minimum value is 1 */ uint8_t task_priority; /*!< Task priority for the shared processing task. @note Minimum value is 1 */
uint8_t queue_size; /*!< Queue size for task for the encoder processing. @note Minimum value is 1 */ uint8_t queue_size; /*!< Queue size for the shared processing queue. @note Minimum value is 1 */
uint8_t encoder_number; /*!< Unique encoder number. @note Must be greater than 0 */ uint8_t encoder_number; /*!< Unique encoder number. @note Must be greater than 0 */
bool pullup; /*!< Pullup GPIO enable/disable */ uint8_t pcnt_counts_per_step; /*!< PCNT counts per encoder step (detent). @note Must be greater than 0. Typically 4 for EC11 with proper quadrature */
bool pullup; /*!< Pullup GPIO enable/disable for encoder A/B and button */
} zh_encoder_init_config_t; } zh_encoder_init_config_t;
/** /**
* @brief Structure for encoder error statistics. * @brief Structure for encoder error statistics.
* *
* Tracks runtime errors and task health metrics for diagnostic purposes. * Collects error counters and task health metrics reported by the shared
* processing task and the interrupt handlers.
*/ */
typedef struct typedef struct
{ {
uint32_t event_post_error; /*!< Number of event post error */ uint32_t event_post_error; /*!< Number of event post errors */
uint32_t queue_overflow_error; /*!< Number of queue overflow error */ uint32_t queue_overflow_error; /*!< Number of queue overflow errors */
uint32_t min_stack_size; /*!< Minimum free stack size */ uint32_t min_stack_size; /*!< Minimum free stack size (watermark) */
} zh_encoder_stats_t; } zh_encoder_stats_t;
/** /**
* @brief Encoder event identifiers for esp_event base. * @brief Encoder event identifiers for esp_event base.
*
* Used as the event ID when registering handlers on the ZH_ENCODER event base.
*/ */
typedef enum typedef enum
{ {
ZH_BUTTON_EVENT, /*!< Encoder push-button interrupt event */ ZH_BUTTON_EVENT, /*!< Encoder push-button event */
ZH_ENCODER_EVENT /*!< Encoder rotation interrupt event */ ZH_ENCODER_EVENT /*!< Encoder rotation event */
} zh_encoder_event_id_t; } zh_encoder_event_id_t;
ESP_EVENT_DECLARE_BASE(ZH_ENCODER); ESP_EVENT_DECLARE_BASE(ZH_ENCODER);
@@ -113,7 +124,7 @@ extern "C"
/** /**
* @brief Event data structure for encoder rotation events. * @brief Event data structure for encoder rotation events.
* *
* Posted from ISR context via esp_event_isr_post when encoder position changes. * Posted from the shared processing task via esp_event_post() (not from ISR).
* *
* @note Should be used with ZH_ENCODER event base and ZH_ENCODER_EVENT event ID. * @note Should be used with ZH_ENCODER event base and ZH_ENCODER_EVENT event ID.
*/ */
@@ -121,13 +132,14 @@ extern "C"
{ {
float encoder_position; /*!< Encoder current position */ float encoder_position; /*!< Encoder current position */
uint8_t encoder_number; /*!< Encoder unique number */ uint8_t encoder_number; /*!< Encoder unique number */
bool encoder_status; /*!< Encoder status (true when position increased, false when position reduced) */ bool encoder_status; /*!< true if position increased, false if reduced */
} zh_encoder_event_on_isr_t; } zh_encoder_event_on_isr_t;
/** /**
* @brief Event data structure for encoder button events. * @brief Event data structure for encoder button events.
* *
* Posted from ISR context via esp_event_isr_post when encoder button state changes. * Posted from the button debounce timer callback via esp_event_post() when the
* debounced button state actually changed.
* *
* @note Should be used with ZH_ENCODER event base and ZH_BUTTON_EVENT event ID. * @note Should be used with ZH_ENCODER event base and ZH_BUTTON_EVENT event ID.
*/ */
@@ -160,14 +172,14 @@ extern "C"
/** /**
* @brief Deinitialize encoder and release all resources. * @brief Deinitialize encoder and release all resources.
* *
* Stops the PCNT peripheral, removes GPIO ISR handlers, and frees allocated memory. * Stops the PCNT peripheral, removes GPIO ISR handlers and the button debounce timer,
* If this is the last encoder, the shared processing task and queue are also deleted. * and frees allocated memory. If this is the last encoder, the shared processing task
* and queue are also deleted.
* *
* @param[in,out] handle Pointer to unique encoder handle (must not be NULL) * @param[in,out] handle Pointer to unique encoder handle (must not be NULL)
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if handle is NULL or points to an uninitialized encoder * @return ESP_ERR_INVALID_ARG if handle is NULL or points to an uninitialized encoder
* @return ESP_FAIL if PCNT or GPIO cleanup fails
*/ */
esp_err_t zh_encoder_deinit(zh_encoder_handle_t **handle); esp_err_t zh_encoder_deinit(zh_encoder_handle_t **handle);
@@ -186,6 +198,7 @@ extern "C"
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if handle is NULL, or parameters are invalid * @return ESP_ERR_INVALID_ARG if handle is NULL, or parameters are invalid
* @return ESP_FAIL if PCNT count clear fails
*/ */
esp_err_t zh_encoder_reinit(zh_encoder_handle_t **handle, float min, float max, float step); esp_err_t zh_encoder_reinit(zh_encoder_handle_t **handle, float min, float max, float step);
@@ -197,6 +210,7 @@ extern "C"
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if handle is NULL, or parameters are invalid * @return ESP_ERR_INVALID_ARG if handle is NULL, or parameters are invalid
* @return ESP_FAIL if PCNT count clear fails
*/ */
esp_err_t zh_encoder_set(zh_encoder_handle_t **handle, float position); esp_err_t zh_encoder_set(zh_encoder_handle_t **handle, float position);
@@ -220,6 +234,7 @@ extern "C"
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if handle is NULL * @return ESP_ERR_INVALID_ARG if handle is NULL
* @return ESP_FAIL if PCNT count clear fails
*/ */
esp_err_t zh_encoder_reset(zh_encoder_handle_t **handle); esp_err_t zh_encoder_reset(zh_encoder_handle_t **handle);
@@ -237,6 +252,8 @@ extern "C"
* @brief Reset all error statistics to zero. * @brief Reset all error statistics to zero.
* *
* Clears error counters and stack watermarks. * Clears error counters and stack watermarks.
*
* @return No return value
*/ */
void zh_encoder_reset_stats(void); void zh_encoder_reset_stats(void);
+254 -182
View File
@@ -18,106 +18,115 @@
{ \ { \
ZH_LOGE(msg, ESP_FAIL, ##__VA_ARGS__); \ ZH_LOGE(msg, ESP_FAIL, ##__VA_ARGS__); \
cleanup; \ cleanup; \
continue; \
} }
#define ZH_ENCODER_DIRECTION_CW 1 #define ZH_ENCODER_PCNT_HIGH_LIMIT 100
#define ZH_ENCODER_DIRECTION_CCW -1 #define ZH_ENCODER_PCNT_LOW_LIMIT -100
/** /**
* @brief Internal encoder handle structure. * @brief Internal encoder handle structure.
* *
* Stores all runtime state for a single encoder instance, * Stores the runtime state of a single encoder: button GPIO state and the software
* including GPIO configuration, PCNT handles, and position tracking. * debounce timer, value range and step, PCNT count accumulator, and PCNT unit/channel handles.
*
* @note Fields accessed from both ISR and task context are protected by a spinlock
* in the public API functions.
*/ */
struct _zh_encoder_handle_t struct _zh_encoder_handle_t
{ {
bool s_gpio_status; /*!< Current encoder button status */ bool s_gpio_status; /*!< Current encoder button status */
uint8_t encoder_number; /*!< Unique encoder number */ uint8_t encoder_number; /*!< Unique encoder number */
gpio_num_t s_gpio_number; /*!< Encoder button GPIO number */ gpio_num_t s_gpio_number; /*!< Encoder button GPIO number */
uint16_t s_gpio_debounce_time; /*!< Encoder button debounce time in microseconds */ float encoder_step; /*!< Encoder step per detent */
uint64_t s_gpio_prev_time; /*!< Timestamp of the previous button interrupt */
float encoder_step; /*!< Encoder step size */
float encoder_position; /*!< Current encoder position */ float encoder_position; /*!< Current encoder position */
float encoder_min_value; /*!< Encoder minimum value */ float encoder_min_value; /*!< Encoder minimum value */
float encoder_max_value; /*!< Encoder maximum value */ float encoder_max_value; /*!< Encoder maximum value */
pcnt_unit_handle_t pcnt_unit_handle; /*!< PCNT unit handle for quadrature decoding */ int32_t count_accumulator; /*!< Leftover PCNT counts not yet converted into a full step */
pcnt_channel_handle_t pcnt_channel_a_handle; /*!< PCNT channel A handle (A phase) */ uint8_t pcnt_counts_per_step; /*!< PCNT counts per encoder step (detent) */
pcnt_channel_handle_t pcnt_channel_b_handle; /*!< PCNT channel B handle (B phase) */ pcnt_unit_handle_t pcnt_unit_handle; /*!< PCNT unit handle */
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 */
}; };
/** /**
* @brief Queue message structure for encoder ISR processing. * @brief Queue message structure for encoder ISR processing.
* *
* Sent from ISR context to the processing task when encoder position changes. * Passed from the PCNT watch-point ISR to the shared processing task through
* the queue. Carries the raw PCNT count together with the source encoder handle.
*
* @note The handle pointer is read without holding the spinlock. It is safe because
* the handle is freed in zh_encoder_deinit() only after the processing task
* has been deleted (the last encoder removal).
*/ */
typedef struct typedef struct
{ {
int watch_point_value; /*!< PCNT watch point value (CW or CCW direction) */ int32_t count; /*!< PCNT count read before clearing (signed) */
zh_encoder_handle_t *handle; /*!< Pointer to the encoder handle */ zh_encoder_handle_t *handle; /*!< Pointer to the encoder handle */
} zh_encoder_queue_t; } zh_encoder_queue_t;
TaskHandle_t zh_encoder = NULL; /*!< Handle to the shared encoder ISR processing task */ TaskHandle_t zh_encoder = NULL;
static QueueHandle_t _queue_handle = NULL; /*!< Queue for passing encoder events from ISR to processing task */ static QueueHandle_t _queue_handle = NULL;
static portMUX_TYPE _spinlock = portMUX_INITIALIZER_UNLOCKED; /*!< Spinlock for protecting encoder position access */ static portMUX_TYPE _spinlock = portMUX_INITIALIZER_UNLOCKED;
static zh_encoder_stats_t _stats = {0}; /*!< Global error statistics */ static zh_encoder_stats_t _stats = {0};
static zh_vector_t *_vector = NULL;
static zh_vector_t *_vector = NULL; /*!< Vector storing encoder numbers */
/** /**
* @brief Validate encoder initialization configuration. * @brief Validate the initialization configuration and copy parameters into the handle.
* *
* Checks all configuration parameters for validity and initializes * Checks task, queue, range, step, encoder number and watch-point settings. When a
* the encoder handle with configuration values. * vector of registered encoders exists, verifies that the encoder number is not yet used.
* On success, populates the handle fields and sets the position to the midpoint of the range.
* *
* @param config Pointer to encoder configuration structure * @param config Pointer to the encoder configuration structure
* @param handle Pointer to encoder handle to initialize * @param handle Pointer to the encoder handle to populate
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if any configuration parameter is invalid * @return ESP_ERR_INVALID_ARG if any configuration parameter is invalid or the encoder number is already present
*/ */
static esp_err_t _zh_encoder_validate_config(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle); static esp_err_t _zh_encoder_validate_config(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle);
/** /**
* @brief Initialize PCNT peripheral for quadrature decoding. * @brief Initialize the PCNT unit, channels, watch points and event callbacks.
* *
* Configures PCNT unit with two channels (A and B phases), * Configures encoder A/B GPIOs as inputs, creates a PCNT unit with a glitch filter,
* sets up glitch filter, edge/level actions for CW/CCW counting, * adds two channels with quadrature edge/level actions, registers high and low watch
* registers watch points and event callbacks. * points, then enables, clears and starts the unit. Any failure frees the resources
* created so far before returning.
* *
* @param config Pointer to encoder configuration structure * @param config Pointer to the encoder configuration structure
* @param handle Pointer to encoder handle to populate with PCNT handles * @param handle Pointer to the encoder handle to store PCNT handles in
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if GPIO numbers are invalid or identical * @return ESP_ERR_INVALID_ARG if A/B GPIO numbers are invalid or identical
* @return ESP_FAIL if PCNT peripheral initialization fails * @return ESP_FAIL if any GPIO or PCNT operation fails
*/ */
static esp_err_t _zh_encoder_pcnt_init(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle); static esp_err_t _zh_encoder_pcnt_init(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle);
/** /**
* @brief Initialize GPIO pin for encoder button (if configured). * @brief Initialize the push-button GPIO and register its interrupt handler.
* *
* Configures the button GPIO as input with interrupt on any edge. * Does nothing when the button is disabled (s_gpio_number equals GPIO_NUM_MAX). Installs
* Installs ISR service if not already installed and registers the button ISR handler. * the shared GPIO ISR service when needed, configures the button pin for any-edge
* interrupt, creates the one-shot software debounce timer (microseconds rounded up to
* milliseconds, minimum 1 ms) and registers the button interrupt handler.
* *
* @param config Pointer to encoder configuration structure * @param config Pointer to the encoder configuration structure
* @param handle Pointer to encoder handle to populate with GPIO settings * @param handle Pointer to the encoder handle to store button state in
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if GPIO numbers conflict with encoder pins * @return ESP_ERR_INVALID_ARG if the button GPIO number is invalid or equals the A/B GPIO number
* @return ESP_FAIL if GPIO or ISR service initialization fails * @return ESP_FAIL if GPIO configuration, ISR service installation or handler registration fails
*/ */
static esp_err_t _zh_encoder_gpio_init(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle); static esp_err_t _zh_encoder_gpio_init(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle);
/** /**
* @brief Initialize shared resources (queue) for the first encoder. * @brief Create the shared processing queue for the first registered encoder.
* *
* Creates the FreeRTOS queue used for passing encoder events * The queue is allocated once, when the encoder vector contains exactly one entry.
* from ISR context to the processing task. Only executed once
* when the first encoder is initialized.
* *
* @param config Pointer to encoder configuration structure * @param config Pointer to the encoder configuration structure
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_FAIL if queue creation fails * @return ESP_FAIL if queue creation fails
@@ -125,12 +134,12 @@ static esp_err_t _zh_encoder_gpio_init(const zh_encoder_init_config_t *config, z
static esp_err_t _zh_encoder_resources_init(const zh_encoder_init_config_t *config); static esp_err_t _zh_encoder_resources_init(const zh_encoder_init_config_t *config);
/** /**
* @brief Initialize the shared ISR processing task for the first encoder. * @brief Create the shared ISR processing task for the first registered encoder.
* *
* Creates the FreeRTOS task that processes encoder events from the queue. * The task is created once, when the encoder vector contains exactly one entry,
* Only executed once when the first encoder is initialized. * pinned to no specific core with the configured priority and stack size.
* *
* @param config Pointer to encoder configuration structure * @param config Pointer to the encoder configuration structure
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_FAIL if task creation fails * @return ESP_FAIL if task creation fails
@@ -138,36 +147,59 @@ 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); static esp_err_t _zh_encoder_task_init(const zh_encoder_init_config_t *config);
/** /**
* @brief PCNT event callback invoked when watch point is reached. * @brief PCNT watch-point interrupt handler.
* *
* Clears the PCNT counter and sends the watch point value * Reads and clears the unit count, then posts a queue message to the shared processing
* to the processing task queue. Executed in ISR context. * task. Increments the queue overflow counter when the queue is full.
* *
* @param unit PCNT unit handle that triggered the event * @param unit PCNT unit handle that reached the watch point
* @param edata Pointer to PCNT watch event data * @param edata Watch-point event data (unused)
* @param user_ctx Pointer to encoder handle * @param user_ctx Pointer to the encoder handle passed during callback registration
*
* @return true if a higher priority task was woken and a context switch is required
* @return false otherwise
*/ */
static bool _zh_encoder_isr_handler(pcnt_unit_handle_t unit, const pcnt_watch_event_data_t *edata, void *user_ctx); static bool _zh_encoder_isr_handler(pcnt_unit_handle_t unit, const pcnt_watch_event_data_t *edata, void *user_ctx);
/** /**
* @brief FreeRTOS task for processing encoder events from the queue. * @brief Shared processing task body for encoder rotation events.
* *
* Receives queue messages from the ISR handler, updates encoder position * Receives queue messages, converts raw PCNT counts into whole steps using the
* based on CW/CCW direction, and posts esp_event notifications * accumulator, clamps the position to the configured range, snaps values closer to
* when position changes. Runs indefinitely until the queue is deleted. * zero than half a step to zero, and posts a rotation event when the position changes.
* Updates the stack watermark on each iteration.
* *
* @param pvParameter Task parameter (unused) * @param pvParameter Task parameter (unused)
*
* @return Never returns, the task deletes itself when the queue receive fails
*/ */
static void _zh_encoder_isr_processing_task(void *pvParameter); static void _zh_encoder_isr_processing_task(void *pvParameter);
/** /**
* @brief GPIO ISR handler for encoder button press/release. * @brief Button debounce timer callback.
* *
* Implements debouncing by checking the time since the last interrupt. * Runs in the timer daemon task context after the debounce period elapses. Reads the
* Posts a button event via esp_event_isr_post when button state changes. * button level and posts a button event only when the state actually changed. Increments
* Executed in ISR context. * the event post error counter when posting fails.
* *
* @param arg Pointer to encoder handle * @note @c s_gpio_status is read and written without holding the spinlock. It is safe
* because only this callback ever touches the field, so no concurrent access occurs.
*
* @param xTimer Timer handle whose ID holds the encoder handle pointer
*
* @return No return value
*/
static void _zh_encoder_button_timer_cb(TimerHandle_t xTimer);
/**
* @brief Push-button GPIO interrupt handler.
*
* Restarts the one-shot software debounce timer on every edge. The button state is
* checked in the timer callback, so the ISR itself performs no event posting.
*
* @param arg Pointer to the encoder handle passed during handler registration
*
* @return No return value
*/ */
static void _zh_encoder_button_isr_handler(void *arg); static void _zh_encoder_button_isr_handler(void *arg);
@@ -187,19 +219,19 @@ esp_err_t zh_encoder_init(const zh_encoder_init_config_t *config, zh_encoder_han
} }
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_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_resources_init(config) == ESP_OK, ESP_FAIL, zh_vector_delete_back(&_vector); heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. Resources initialization failed.");
// clang-format off
ZH_ERROR_CHECK(_zh_encoder_task_init(config) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(_zh_encoder_task_init(config) == ESP_OK, ESP_FAIL,
zh_vector_delete_back(&_vector); heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. Processing task initialization failed."); zh_vector_delete_back(&_vector);
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_ERROR_CHECK(_zh_encoder_pcnt_init(config, *handle) == ESP_OK, ESP_FAIL,
zh_vector_delete_back(&_vector); heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. PCNT initialization failed."); zh_vector_delete_back(&_vector);
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(_zh_encoder_gpio_init(config, *handle) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "PCNT unit stop fail.")}; {ZH_ERROR_CHECK_CONT(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "PCNT unit stop fail.")};
{ZH_ERROR_CHECK(pcnt_unit_disable((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "PCNT unit disable fail.")}; {ZH_ERROR_CHECK_CONT(pcnt_unit_disable((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "PCNT unit disable fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel((*handle)->pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = 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(pcnt_del_unit((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "PCNT delete unit 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_vector_delete_back(&_vector); heap_caps_free(*handle); *handle = NULL, "Encoder initialization failed. GPIO initialization failed.");
// clang-format on
if (_stats.min_stack_size == 0) if (_stats.min_stack_size == 0)
{ {
_stats.min_stack_size = config->stack_size; _stats.min_stack_size = config->stack_size;
@@ -212,30 +244,42 @@ esp_err_t zh_encoder_deinit(zh_encoder_handle_t **handle)
{ {
ZH_LOGI("Encoder deinitialization started."); ZH_LOGI("Encoder deinitialization started.");
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder deinitialization failed. Invalid argument."); ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder deinitialization failed. Invalid argument.");
ZH_ERROR_CHECK(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. PCNT unit stop fail."); ZH_ERROR_CHECK_CONT(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Encoder deinitialization failed. PCNT unit stop fail.");
ZH_ERROR_CHECK(pcnt_unit_disable((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. PCNT unit disable fail."); ZH_ERROR_CHECK_CONT(pcnt_unit_disable((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Encoder deinitialization failed. PCNT unit disable fail.");
ZH_ERROR_CHECK(pcnt_unit_remove_watch_point((*handle)->pcnt_unit_handle, ZH_ENCODER_DIRECTION_CW) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. PCNT unit remove watch point fail."); ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point((*handle)->pcnt_unit_handle, (*handle)->pcnt_counts_per_step) == ESP_OK, NULL, "Encoder deinitialization failed. PCNT unit remove watch point fail.");
ZH_ERROR_CHECK(pcnt_unit_remove_watch_point((*handle)->pcnt_unit_handle, ZH_ENCODER_DIRECTION_CCW) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. PCNT unit remove watch point fail."); ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point((*handle)->pcnt_unit_handle, -(*handle)->pcnt_counts_per_step) == ESP_OK, NULL, "Encoder deinitialization failed. PCNT unit remove watch point fail.");
ZH_ERROR_CHECK(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. PCNT delete channel fail."); ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, NULL, "Encoder deinitialization failed. PCNT delete channel fail.");
ZH_ERROR_CHECK(pcnt_del_channel((*handle)->pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. PCNT delete channel fail."); ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_b_handle) == ESP_OK, NULL, "Encoder deinitialization failed. PCNT delete channel fail.");
ZH_ERROR_CHECK(pcnt_del_unit((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. PCNT delete unit fail."); ZH_ERROR_CHECK_CONT(pcnt_del_unit((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Encoder deinitialization failed. PCNT delete unit fail.");
if ((*handle)->s_gpio_number != GPIO_NUM_MAX) if ((*handle)->s_gpio_number != GPIO_NUM_MAX)
{ {
ZH_ERROR_CHECK(gpio_isr_handler_remove((*handle)->s_gpio_number) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. Remove GPIO isr handler failed."); ZH_ERROR_CHECK_CONT(gpio_isr_handler_remove((*handle)->s_gpio_number) == ESP_OK, NULL, "Encoder deinitialization failed. Remove GPIO isr handler failed.");
ZH_ERROR_CHECK(gpio_reset_pin((*handle)->s_gpio_number) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. Reset GPIO failed."); ZH_ERROR_CHECK_CONT(gpio_reset_pin((*handle)->s_gpio_number) == ESP_OK, NULL, "Encoder deinitialization failed. Reset GPIO failed.");
if ((*handle)->button_timer != NULL)
{
xTimerStop((*handle)->button_timer, portMAX_DELAY);
xTimerDelete((*handle)->button_timer, portMAX_DELAY);
(*handle)->button_timer = NULL;
}
} }
int32_t index = 0; int32_t index = 0;
ZH_ERROR_CHECK(zh_vector_find_item(&_vector, &(*handle)->encoder_number, &index) == ESP_ERR_NOT_FOUND, ESP_ERR_INVALID_ARG, NULL, "Encoder deinitialization failed. Failed to find vector item."); ZH_ERROR_CHECK(zh_vector_find_item(&_vector, &(*handle)->encoder_number, &index) == ESP_OK, ESP_ERR_INVALID_ARG, NULL, "Encoder deinitialization failed. Failed to find vector item.");
ZH_ERROR_CHECK(zh_vector_delete_item(&_vector, (uint16_t)index) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. Vector delete item failed."); ZH_ERROR_CHECK(zh_vector_delete_item(&_vector, (uint16_t)index) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. Vector delete item failed.");
uint16_t vector_size = 0; uint16_t vector_size = 0;
ZH_ERROR_CHECK(zh_vector_get_size(&_vector, &vector_size) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. Failed to get vector size."); ZH_ERROR_CHECK(zh_vector_get_size(&_vector, &vector_size) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. Failed to get vector size.");
if (vector_size == 0) if (vector_size == 0)
{ {
vQueueDelete(_queue_handle); if (zh_encoder != NULL)
_queue_handle = NULL; {
vTaskDelete(zh_encoder); vTaskDelete(zh_encoder);
zh_encoder = NULL; zh_encoder = NULL;
ZH_ERROR_CHECK(zh_vector_free(&_vector) == ESP_OK, ESP_FAIL, NULL, "Encoder deinitialization failed. Free vector failed."); }
if (_queue_handle != NULL)
{
vQueueDelete(_queue_handle);
_queue_handle = NULL;
}
ZH_ERROR_CHECK_CONT(zh_vector_free(&_vector) == ESP_OK, NULL, "Encoder deinitialization failed. Free vector failed.");
} }
heap_caps_free(*handle); heap_caps_free(*handle);
*handle = NULL; *handle = NULL;
@@ -254,7 +298,9 @@ esp_err_t zh_encoder_reinit(zh_encoder_handle_t **handle, float min, float max,
(*handle)->encoder_max_value = max; (*handle)->encoder_max_value = max;
(*handle)->encoder_step = step; (*handle)->encoder_step = step;
(*handle)->encoder_position = ((*handle)->encoder_min_value + (*handle)->encoder_max_value) / 2; (*handle)->encoder_position = ((*handle)->encoder_min_value + (*handle)->encoder_max_value) / 2;
(*handle)->count_accumulator = 0;
taskEXIT_CRITICAL(&_spinlock); taskEXIT_CRITICAL(&_spinlock);
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."); ZH_LOGI("Encoder reinitialization completed successfully.");
return ESP_OK; return ESP_OK;
} }
@@ -263,10 +309,12 @@ esp_err_t zh_encoder_set(zh_encoder_handle_t **handle, float position)
{ {
ZH_LOGI("Encoder set position started."); ZH_LOGI("Encoder set position started.");
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder set position failed. Invalid argument."); ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder set position failed. Invalid argument.");
ZH_ERROR_CHECK(position <= (*handle)->encoder_max_value && position >= (*handle)->encoder_min_value, ESP_ERR_INVALID_ARG, NULL, "Encoder set position failed. Invalid argument.");
taskENTER_CRITICAL(&_spinlock); 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.");
(*handle)->encoder_position = position; (*handle)->encoder_position = position;
(*handle)->count_accumulator = 0;
taskEXIT_CRITICAL(&_spinlock); taskEXIT_CRITICAL(&_spinlock);
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."); ZH_LOGI("Encoder set position completed successfully.");
return ESP_OK; return ESP_OK;
} }
@@ -275,7 +323,9 @@ esp_err_t zh_encoder_get(zh_encoder_handle_t **handle, float *position)
{ {
ZH_LOGI("Encoder get position started."); 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."); ZH_ERROR_CHECK(handle != NULL && *handle != NULL && position != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder get position failed. Invalid argument.");
taskENTER_CRITICAL(&_spinlock);
*position = (*handle)->encoder_position; *position = (*handle)->encoder_position;
taskEXIT_CRITICAL(&_spinlock);
ZH_LOGI("Encoder get position completed successfully."); ZH_LOGI("Encoder get position completed successfully.");
return ESP_OK; return ESP_OK;
} }
@@ -286,7 +336,9 @@ esp_err_t zh_encoder_reset(zh_encoder_handle_t **handle)
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder reset failed. Invalid argument."); ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Encoder reset failed. Invalid argument.");
taskENTER_CRITICAL(&_spinlock); taskENTER_CRITICAL(&_spinlock);
(*handle)->encoder_position = ((*handle)->encoder_min_value + (*handle)->encoder_max_value) / 2; (*handle)->encoder_position = ((*handle)->encoder_min_value + (*handle)->encoder_max_value) / 2;
(*handle)->count_accumulator = 0;
taskEXIT_CRITICAL(&_spinlock); taskEXIT_CRITICAL(&_spinlock);
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."); ZH_LOGI("Encoder reset completed successfully.");
return ESP_OK; return ESP_OK;
} }
@@ -312,6 +364,7 @@ static esp_err_t _zh_encoder_validate_config(const zh_encoder_init_config_t *con
ZH_ERROR_CHECK(config->encoder_max_value > config->encoder_min_value, ESP_ERR_INVALID_ARG, NULL, "Invalid encoder min/max value."); ZH_ERROR_CHECK(config->encoder_max_value > config->encoder_min_value, ESP_ERR_INVALID_ARG, NULL, "Invalid encoder min/max value.");
ZH_ERROR_CHECK(config->encoder_step > 0, ESP_ERR_INVALID_ARG, NULL, "Invalid encoder step."); ZH_ERROR_CHECK(config->encoder_step > 0, ESP_ERR_INVALID_ARG, NULL, "Invalid encoder step.");
ZH_ERROR_CHECK(config->encoder_number > 0, ESP_ERR_INVALID_ARG, NULL, "Invalid encoder number."); ZH_ERROR_CHECK(config->encoder_number > 0, ESP_ERR_INVALID_ARG, NULL, "Invalid encoder number.");
ZH_ERROR_CHECK(config->pcnt_counts_per_step > 0, ESP_ERR_INVALID_ARG, NULL, "Invalid pcnt_counts_per_step.");
if (_vector != NULL) if (_vector != NULL)
{ {
int32_t index = 0; int32_t index = 0;
@@ -321,7 +374,9 @@ static esp_err_t _zh_encoder_validate_config(const zh_encoder_init_config_t *con
handle->encoder_min_value = config->encoder_min_value; handle->encoder_min_value = config->encoder_min_value;
handle->encoder_max_value = config->encoder_max_value; handle->encoder_max_value = config->encoder_max_value;
handle->encoder_step = config->encoder_step; handle->encoder_step = config->encoder_step;
handle->pcnt_counts_per_step = config->pcnt_counts_per_step;
handle->encoder_position = (handle->encoder_min_value + handle->encoder_max_value) / 2; handle->encoder_position = (handle->encoder_min_value + handle->encoder_max_value) / 2;
handle->s_gpio_number = GPIO_NUM_MAX;
return ESP_OK; return ESP_OK;
} }
@@ -329,9 +384,17 @@ static esp_err_t _zh_encoder_pcnt_init(const zh_encoder_init_config_t *config, z
{ {
ZH_ERROR_CHECK(config->a_gpio_number < GPIO_NUM_MAX && config->b_gpio_number < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG, NULL, "Invalid GPIO number.") ZH_ERROR_CHECK(config->a_gpio_number < GPIO_NUM_MAX && config->b_gpio_number < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG, NULL, "Invalid GPIO number.")
ZH_ERROR_CHECK(config->a_gpio_number != config->b_gpio_number, ESP_ERR_INVALID_ARG, NULL, "Encoder A and B GPIO is same.") ZH_ERROR_CHECK(config->a_gpio_number != config->b_gpio_number, ESP_ERR_INVALID_ARG, NULL, "Encoder A and B GPIO is same.")
gpio_config_t io_config = {
.pin_bit_mask = (1ULL << config->a_gpio_number) | (1ULL << config->b_gpio_number),
.mode = GPIO_MODE_INPUT,
.pull_up_en = config->pullup == true ? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
ZH_ERROR_CHECK(gpio_config(&io_config) == ESP_OK, ESP_FAIL, NULL, "GPIO initialization failed.");
pcnt_unit_config_t pcnt_unit_config = { pcnt_unit_config_t pcnt_unit_config = {
.high_limit = 10, .high_limit = ZH_ENCODER_PCNT_HIGH_LIMIT,
.low_limit = -10, .low_limit = ZH_ENCODER_PCNT_LOW_LIMIT,
}; };
pcnt_unit_handle_t pcnt_unit_handle = NULL; pcnt_unit_handle_t pcnt_unit_handle = NULL;
ZH_ERROR_CHECK(pcnt_new_unit(&pcnt_unit_config, &pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT initialization failed."); ZH_ERROR_CHECK(pcnt_new_unit(&pcnt_unit_config, &pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT initialization failed.");
@@ -339,44 +402,44 @@ static esp_err_t _zh_encoder_pcnt_init(const zh_encoder_init_config_t *config, z
.max_glitch_ns = 1000, .max_glitch_ns = 1000,
}; };
ZH_ERROR_CHECK(pcnt_unit_set_glitch_filter(pcnt_unit_handle, &pcnt_glitch_filter_config) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_unit_set_glitch_filter(pcnt_unit_handle, &pcnt_glitch_filter_config) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK_CONT(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
pcnt_chan_config_t pcnt_chan_a_config = { pcnt_chan_config_t pcnt_chan_a_config = {
.edge_gpio_num = config->a_gpio_number, .edge_gpio_num = config->a_gpio_number,
.level_gpio_num = config->b_gpio_number, .level_gpio_num = config->b_gpio_number,
}; };
pcnt_channel_handle_t pcnt_channel_a_handle = NULL; pcnt_channel_handle_t pcnt_channel_a_handle = NULL;
ZH_ERROR_CHECK(pcnt_new_channel(pcnt_unit_handle, &pcnt_chan_a_config, &pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_new_channel(pcnt_unit_handle, &pcnt_chan_a_config, &pcnt_channel_a_handle) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK_CONT(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
pcnt_chan_config_t pcnt_chan_b_config = { pcnt_chan_config_t pcnt_chan_b_config = {
.edge_gpio_num = config->b_gpio_number, .edge_gpio_num = config->b_gpio_number,
.level_gpio_num = config->a_gpio_number, .level_gpio_num = config->a_gpio_number,
}; };
pcnt_channel_handle_t pcnt_channel_b_handle = NULL; pcnt_channel_handle_t pcnt_channel_b_handle = NULL;
ZH_ERROR_CHECK(pcnt_new_channel(pcnt_unit_handle, &pcnt_chan_b_config, &pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_new_channel(pcnt_unit_handle, &pcnt_chan_b_config, &pcnt_channel_b_handle) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK_CONT(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_channel_set_edge_action(pcnt_channel_a_handle, PCNT_CHANNEL_EDGE_ACTION_DECREASE, PCNT_CHANNEL_EDGE_ACTION_HOLD) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_channel_set_edge_action(pcnt_channel_a_handle, PCNT_CHANNEL_EDGE_ACTION_DECREASE, PCNT_CHANNEL_EDGE_ACTION_INCREASE) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK_CONT(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_channel_set_level_action(pcnt_channel_a_handle, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_INVERSE) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK_CONT(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_channel_set_edge_action(pcnt_channel_b_handle, PCNT_CHANNEL_EDGE_ACTION_INCREASE, PCNT_CHANNEL_EDGE_ACTION_DECREASE) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK_CONT(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_channel_set_level_action(pcnt_channel_b_handle, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_INVERSE) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK_CONT(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK_CONT(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit_handle, handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_channel_set_level_action(pcnt_channel_a_handle, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_HOLD) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit_handle, -handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_channel_set_edge_action(pcnt_channel_b_handle, PCNT_CHANNEL_EDGE_ACTION_INCREASE, PCNT_CHANNEL_EDGE_ACTION_HOLD) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_channel_set_level_action(pcnt_channel_b_handle, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_HOLD) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CW) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CCW) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
@@ -384,36 +447,31 @@ static esp_err_t _zh_encoder_pcnt_init(const zh_encoder_init_config_t *config, z
.on_reach = _zh_encoder_isr_handler, .on_reach = _zh_encoder_isr_handler,
}; };
ZH_ERROR_CHECK(pcnt_unit_register_event_callbacks(pcnt_unit_handle, &cbs, handle) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_unit_register_event_callbacks(pcnt_unit_handle, &cbs, handle) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CCW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, -handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_unit_enable(pcnt_unit_handle) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_unit_enable(pcnt_unit_handle) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CCW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, -handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_unit_clear_count(pcnt_unit_handle) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_unit_clear_count(pcnt_unit_handle) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_unit_disable(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT unit disable fail.")}; {ZH_ERROR_CHECK(pcnt_unit_disable(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT unit disable fail.")};
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CCW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, -handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
ZH_ERROR_CHECK(pcnt_unit_start(pcnt_unit_handle) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(pcnt_unit_start(pcnt_unit_handle) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(pcnt_unit_disable(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT unit disable fail.")}; {ZH_ERROR_CHECK(pcnt_unit_disable(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT unit disable fail.")};
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, ZH_ENCODER_DIRECTION_CCW) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")}; {ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, -handle->pcnt_counts_per_step) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")}; {ZH_ERROR_CHECK(pcnt_del_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete channel fail.")};
{ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed."); {ZH_ERROR_CHECK(pcnt_del_unit(pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "PCNT delete unit fail.")}, "PCNT initialization failed.");
if (config->pullup == false)
{
ZH_ERROR_CHECK(gpio_pullup_dis(config->a_gpio_number) == ESP_OK, ESP_FAIL, NULL, "GPIO pullup disable fail.");
ZH_ERROR_CHECK(gpio_pullup_dis(config->b_gpio_number) == ESP_OK, ESP_FAIL, NULL, "GPIO pullup disable fail.");
}
handle->pcnt_unit_handle = pcnt_unit_handle; handle->pcnt_unit_handle = pcnt_unit_handle;
handle->pcnt_channel_a_handle = pcnt_channel_a_handle; handle->pcnt_channel_a_handle = pcnt_channel_a_handle;
handle->pcnt_channel_b_handle = pcnt_channel_b_handle; handle->pcnt_channel_b_handle = pcnt_channel_b_handle;
@@ -422,8 +480,8 @@ static esp_err_t _zh_encoder_pcnt_init(const zh_encoder_init_config_t *config, z
static esp_err_t _zh_encoder_gpio_init(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle) static esp_err_t _zh_encoder_gpio_init(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle)
{ {
ZH_ERROR_CHECK(config->s_gpio_number <= GPIO_NUM_MAX, ESP_ERR_INVALID_ARG, NULL, "Invalid GPIO number.") ZH_ERROR_CHECK(config->s_gpio_number <= GPIO_NUM_MAX, ESP_ERR_INVALID_ARG, NULL, "Invalid GPIO number.");
ZH_ERROR_CHECK(config->a_gpio_number != config->s_gpio_number && config->b_gpio_number != config->s_gpio_number, ESP_ERR_INVALID_ARG, NULL, "Encoder GPIO and button GPIO is same.") ZH_ERROR_CHECK(config->a_gpio_number != config->s_gpio_number && config->b_gpio_number != config->s_gpio_number, ESP_ERR_INVALID_ARG, NULL, "Encoder GPIO and button GPIO is the same.");
if (config->s_gpio_number != GPIO_NUM_MAX) if (config->s_gpio_number != GPIO_NUM_MAX)
{ {
gpio_config_t pin_config = { gpio_config_t pin_config = {
@@ -432,14 +490,22 @@ static esp_err_t _zh_encoder_gpio_init(const zh_encoder_init_config_t *config, z
.pin_bit_mask = (1ULL << config->s_gpio_number), .pin_bit_mask = (1ULL << config->s_gpio_number),
.intr_type = GPIO_INTR_ANYEDGE}; .intr_type = GPIO_INTR_ANYEDGE};
ZH_ERROR_CHECK(gpio_config(&pin_config) == ESP_OK, ESP_FAIL, NULL, "GPIO initialization failed."); ZH_ERROR_CHECK(gpio_config(&pin_config) == ESP_OK, ESP_FAIL, NULL, "GPIO initialization failed.");
uint32_t debounce_ms = (config->s_gpio_debounce_time + 999) / 1000;
if (debounce_ms < 1)
{
debounce_ms = 1;
}
handle->button_timer = xTimerCreate("zh_encoder_button_timer", pdMS_TO_TICKS(debounce_ms), pdFALSE, handle, _zh_encoder_button_timer_cb);
ZH_ERROR_CHECK(handle->button_timer != NULL, ESP_FAIL, gpio_isr_handler_remove(config->s_gpio_number); gpio_reset_pin(config->s_gpio_number), "Failed to create button debounce timer.");
handle->s_gpio_number = config->s_gpio_number;
handle->s_gpio_status = gpio_get_level(config->s_gpio_number);
esp_err_t err = gpio_install_isr_service(ESP_INTR_FLAG_LOWMED); 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(err == ESP_OK || err == ESP_ERR_INVALID_STATE, ESP_FAIL,
{ZH_ERROR_CHECK(gpio_reset_pin(config->s_gpio_number) == ESP_OK, ESP_FAIL, NULL, "Reset GPIO failed.")}, "Failed install isr service."); {ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->s_gpio_number) == ESP_OK, NULL, "Reset GPIO failed.")};
xTimerDelete(handle->button_timer, portMAX_DELAY); handle->button_timer = NULL, "Failed install isr service.");
ZH_ERROR_CHECK(gpio_isr_handler_add(config->s_gpio_number, _zh_encoder_button_isr_handler, handle) == ESP_OK, ESP_FAIL, ZH_ERROR_CHECK(gpio_isr_handler_add(config->s_gpio_number, _zh_encoder_button_isr_handler, handle) == ESP_OK, ESP_FAIL,
{ZH_ERROR_CHECK(gpio_reset_pin(config->s_gpio_number) == ESP_OK, ESP_FAIL, NULL, "Reset GPIO failed.")}, "Interrupt initialization failed."); {ZH_ERROR_CHECK_CONT(gpio_reset_pin(config->s_gpio_number) == ESP_OK, NULL, "Reset GPIO failed.")};
handle->s_gpio_number = config->s_gpio_number; xTimerDelete(handle->button_timer, portMAX_DELAY); handle->button_timer = NULL, "Interrupt initialization failed.");
handle->s_gpio_debounce_time = config->s_gpio_debounce_time;
handle->s_gpio_status = gpio_get_level(config->s_gpio_number);
} }
return ESP_OK; return ESP_OK;
} }
@@ -468,17 +534,27 @@ static esp_err_t _zh_encoder_task_init(const zh_encoder_init_config_t *config)
return ESP_OK; return ESP_OK;
} }
static bool IRAM_ATTR _zh_encoder_isr_handler(pcnt_unit_handle_t unit, const pcnt_watch_event_data_t *edata, void *user_ctx) 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_handle_t *encoder_handle = (zh_encoder_handle_t *)user_ctx;
zh_encoder_queue_t encoder_queue = {0}; zh_encoder_queue_t encoder_queue = {0};
BaseType_t xHigherPriorityTaskWoken = pdFALSE; int count = 0;
if (pcnt_unit_clear_count(unit) != ESP_OK) taskENTER_CRITICAL_ISR(&_spinlock);
if (pcnt_unit_get_count(unit, &count) != ESP_OK)
{ {
taskEXIT_CRITICAL_ISR(&_spinlock);
return false; return false;
} }
encoder_queue.watch_point_value = edata->watch_point_value; if (pcnt_unit_clear_count(unit) != ESP_OK)
{
taskEXIT_CRITICAL_ISR(&_spinlock);
return false;
}
taskEXIT_CRITICAL_ISR(&_spinlock);
encoder_queue.count = count;
encoder_queue.handle = encoder_handle; encoder_queue.handle = encoder_handle;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if (xQueueSendFromISR(_queue_handle, &encoder_queue, &xHigherPriorityTaskWoken) != pdTRUE) if (xQueueSendFromISR(_queue_handle, &encoder_queue, &xHigherPriorityTaskWoken) != pdTRUE)
{ {
++_stats.queue_overflow_error; ++_stats.queue_overflow_error;
@@ -490,84 +566,80 @@ static bool IRAM_ATTR _zh_encoder_isr_handler(pcnt_unit_handle_t unit, const pcn
return false; return false;
} }
static void IRAM_ATTR _zh_encoder_isr_processing_task(void *pvParameter) static void _zh_encoder_isr_processing_task(void *pvParameter)
{ {
(void)pvParameter; (void)pvParameter;
zh_encoder_queue_t encoder_queue = {0}; zh_encoder_queue_t encoder_queue = {0};
while (xQueueReceive(_queue_handle, &encoder_queue, portMAX_DELAY) == pdTRUE) while (xQueueReceive(_queue_handle, &encoder_queue, portMAX_DELAY) == pdTRUE)
{ {
bool is_value_changed = false; zh_encoder_handle_t *handle = encoder_queue.handle;
bool position_changed = false;
bool encoder_status = false; bool encoder_status = false;
zh_encoder_handle_t *encoder_handle = encoder_queue.handle; float encoder_position = 0.0;
switch (encoder_queue.watch_point_value) uint8_t encoder_number = 0;
taskENTER_CRITICAL(&_spinlock);
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;
if (full_steps != 0)
{ {
case ZH_ENCODER_DIRECTION_CW: float candidate = handle->encoder_position + (float)full_steps * handle->encoder_step;
if (encoder_handle->encoder_position < encoder_handle->encoder_max_value) if (candidate > handle->encoder_max_value)
{ {
encoder_handle->encoder_position = encoder_handle->encoder_position + encoder_handle->encoder_step; candidate = handle->encoder_max_value;
if (encoder_handle->encoder_position > encoder_handle->encoder_max_value)
{
encoder_handle->encoder_position = encoder_handle->encoder_max_value;
} }
is_value_changed = true; else if (candidate < handle->encoder_min_value)
encoder_status = true;
}
break;
case ZH_ENCODER_DIRECTION_CCW:
if (encoder_handle->encoder_position > encoder_handle->encoder_min_value)
{ {
encoder_handle->encoder_position = encoder_handle->encoder_position - encoder_handle->encoder_step; candidate = handle->encoder_min_value;
if (encoder_handle->encoder_position < encoder_handle->encoder_min_value) }
if (fabsf(candidate) < handle->encoder_step * 0.5f)
{ {
encoder_handle->encoder_position = encoder_handle->encoder_min_value; candidate = 0.0f;
} }
is_value_changed = true; if (candidate != handle->encoder_position)
{
handle->encoder_position = candidate;
position_changed = true;
encoder_status = full_steps > 0 ? true : false;
encoder_position = candidate;
encoder_number = handle->encoder_number;
} }
break;
default:
break;
} }
if (is_value_changed == true) taskEXIT_CRITICAL(&_spinlock);
if (position_changed == true)
{ {
is_value_changed = false;
zh_encoder_event_on_isr_t encoder_data = {0}; zh_encoder_event_on_isr_t encoder_data = {0};
encoder_data.encoder_number = encoder_handle->encoder_number; encoder_data.encoder_number = encoder_number;
if (fabsf(encoder_handle->encoder_position) < 1e-6f) encoder_data.encoder_position = encoder_position;
{
memset(&encoder_handle->encoder_position, 0, sizeof(float));
}
encoder_data.encoder_position = encoder_handle->encoder_position;
encoder_data.encoder_status = encoder_status; encoder_data.encoder_status = encoder_status;
ZH_ERROR_CHECK_CONT(esp_event_post(ZH_ENCODER, ZH_ENCODER_EVENT, &encoder_data, sizeof(zh_encoder_event_on_isr_t), 1000 / portTICK_PERIOD_MS) == ESP_OK, ++_stats.event_post_error, "Encoder isr processing failed. Failed to post interrupt event."); ZH_ERROR_CHECK_CONT(esp_event_post(ZH_ENCODER, ZH_ENCODER_EVENT, &encoder_data, sizeof(zh_encoder_event_on_isr_t), pdMS_TO_TICKS(10)) == ESP_OK, ++_stats.event_post_error, "Encoder isr processing failed. Failed to post interrupt event.");
} }
_stats.min_stack_size = (uint32_t)uxTaskGetStackHighWaterMark(NULL); _stats.min_stack_size = (uint32_t)uxTaskGetStackHighWaterMark(NULL);
} }
vTaskDelete(NULL); vTaskDelete(NULL);
} }
static void IRAM_ATTR _zh_encoder_button_isr_handler(void *arg) static void _zh_encoder_button_timer_cb(TimerHandle_t xTimer)
{ {
zh_encoder_handle_t *encoder_handle = (zh_encoder_handle_t *)arg; zh_encoder_handle_t *encoder_handle = (zh_encoder_handle_t *)pvTimerGetTimerID(xTimer);
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
uint64_t _current_us = esp_timer_get_time();
if (_current_us - encoder_handle->s_gpio_prev_time >= encoder_handle->s_gpio_debounce_time)
{
bool s_gpio_status = gpio_get_level(encoder_handle->s_gpio_number); bool s_gpio_status = gpio_get_level(encoder_handle->s_gpio_number);
if (encoder_handle->s_gpio_status != s_gpio_status) if (encoder_handle->s_gpio_status != s_gpio_status)
{ {
encoder_handle->s_gpio_status = s_gpio_status; encoder_handle->s_gpio_status = s_gpio_status;
zh_encoder_button_event_on_isr_t encoder_data = {0}; zh_encoder_button_event_on_isr_t encoder_data = {0};
encoder_data.encoder_number = encoder_handle->encoder_number; encoder_data.encoder_number = encoder_handle->encoder_number;
encoder_data.button_status = encoder_handle->s_gpio_status; encoder_data.button_status = s_gpio_status;
if (esp_event_isr_post(ZH_ENCODER, ZH_BUTTON_EVENT, &encoder_data, sizeof(zh_encoder_button_event_on_isr_t), &xHigherPriorityTaskWoken) != ESP_OK) 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.");
{
++_stats.event_post_error;
} }
} }
}
encoder_handle->s_gpio_prev_time = _current_us; static void _zh_encoder_button_isr_handler(void *arg)
{
zh_encoder_handle_t *encoder_handle = (zh_encoder_handle_t *)arg;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xTimerResetFromISR(encoder_handle->button_timer, &xHigherPriorityTaskWoken);
if (xHigherPriorityTaskWoken == pdTRUE) if (xHigherPriorityTaskWoken == pdTRUE)
{ {
portYIELD_FROM_ISR(); portYIELD_FROM_ISR();
}; }
} }