Compare commits

...

7 Commits

Author SHA1 Message Date
e60224662e wip: 2025-06-14 10:56:21 +03:00
fab461f771 wip: 2025-06-14 10:51:45 +03:00
f4ec446606 wip: 2025-06-14 10:40:16 +03:00
db0e997aad wip: 2025-06-14 08:33:02 +03:00
1b872f8b82 wip: 2025-06-08 13:11:32 +03:00
27f59c6d92 wip: 2025-06-08 13:00:28 +03:00
ff58109ff8 wip: 2025-06-07 12:50:26 +03:00
8 changed files with 402 additions and 7 deletions

4
.gitignore vendored
View File

@@ -1,5 +1 @@
.DS_Store
.vscode
build
sdkconfig
sdkconfig.old

View File

@@ -1 +1,6 @@
idf_component_register(SRCS "main.c" INCLUDE_DIRS "include")
if(${IDF_TARGET} STREQUAL esp8266)
set(requires driver)
else()
set(requires driver esp_event)
endif()
idf_component_register(SRCS "zh_encoder.c" INCLUDE_DIRS "include" REQUIRES ${requires})

View File

@@ -1,3 +1,88 @@
# esp_component_template
esp_component_template
#include "zh_encoder.h"
zh_encoder_handle_t encoder_handle = {0};
void zh_encoder_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data);
// #define ROT_ENC_A_GPIO (CONFIG_ROT_ENC_A_GPIO)
// #define ROT_ENC_B_GPIO (CONFIG_ROT_ENC_B_GPIO)
// #define ENABLE_HALF_STEPS false // Set to true to enable tracking of rotary encoder at half step resolution
// #define RESET_AT 0 // Set to a positive non-zero number to reset the position if this value is exceeded
// #define FLIP_DIRECTION false // Set to true to reverse the clockwise/counterclockwise sense
void app_main(void)
{
esp_log_level_set("zh_encoder", ESP_LOG_NONE); // For ESP8266 first enable "Component config -> Log output -> Enable log set level" via menuconfig.
esp_event_loop_create_default();
#ifdef CONFIG_IDF_TARGET_ESP8266
esp_event_handler_register(ZH_ENCODER, ESP_EVENT_ANY_ID, &zh_encoder_event_handler, NULL);
#else
esp_event_handler_instance_register(ZH_ENCODER, ESP_EVENT_ANY_ID, &zh_encoder_event_handler, NULL, NULL);
#endif
zh_encoder_init_config_t encoder_init_config = ZH_ENCODER_INIT_CONFIG_DEFAULT();
encoder_init_config.a_gpio_number = GPIO_NUM_26;
encoder_init_config.b_gpio_number = GPIO_NUM_27;
encoder_init_config.encoder_min_value = -10; // Just for example.
encoder_init_config.encoder_max_value = 20; // Just for example.
encoder_init_config.encoder_step = 0.1; // Just for example.
encoder_init_config.encoder_number = 1;
zh_encoder_init(&encoder_init_config, &encoder_handle);
zh_encoder_reset(&encoder_handle); // Just for example.
zh_encoder_set(&encoder_handle, 5); // Just for example.
// esp32-rotary-encoder requires that the GPIO ISR service is installed before calling rotary_encoder_register()
// ESP_ERROR_CHECK(gpio_install_isr_service(0));
// // Initialise the rotary encoder device with the GPIOs for A and B signals
// rotary_encoder_info_t info = { 0 };
// ESP_ERROR_CHECK(rotary_encoder_init(&info, ROT_ENC_A_GPIO, ROT_ENC_B_GPIO));
// ESP_ERROR_CHECK(rotary_encoder_enable_half_steps(&info, ENABLE_HALF_STEPS));
// #ifdef FLIP_DIRECTION
// // ESP_ERROR_CHECK(rotary_encoder_flip_direction(&info));
// #endif
// // Create a queue for events from the rotary encoder driver.
// // Tasks can read from this queue to receive up to date position information.
// QueueHandle_t event_queue = rotary_encoder_create_queue();
// ESP_ERROR_CHECK(rotary_encoder_set_queue(&info, event_queue));
// while (1)
// {
// // Wait for incoming events on the event queue.
// rotary_encoder_event_t event = { 0 };
// if (xQueueReceive(event_queue, &event, portMAX_DELAY) == pdTRUE)
// {
// ESP_LOGI(TAG, "Event: position %ld, direction %s", event.state.position,
// event.state.direction ? (event.state.direction == ROTARY_ENCODER_DIRECTION_CLOCKWISE ? "CW" : "CCW") : "NOT_SET");
// }
// // else
// {
// // Poll current position and direction
// rotary_encoder_state_t state = { 0 };
// ESP_ERROR_CHECK(rotary_encoder_get_state(&info, &state));
// ESP_LOGI(TAG, "Poll: position %ld, direction %s", state.position,
// state.direction ? (state.direction == ROTARY_ENCODER_DIRECTION_CLOCKWISE ? "CW" : "CCW") : "NOT_SET");
// // Reset the device
// if (RESET_AT && (state.position >= RESET_AT || state.position <= -RESET_AT))
// {
// ESP_LOGI(TAG, "Reset");
// ESP_ERROR_CHECK(rotary_encoder_reset(&info));
// }
// }
// }
// ESP_LOGE(TAG, "queue receive failed");
// ESP_ERROR_CHECK(rotary_encoder_uninit(&info));
}
void zh_encoder_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
zh_encoder_event_on_isr_t *event = event_data;
printf("Uncoder number %d position %f.\n", event->encoder_number, event->encoder_position);
}

View File

99
include/zh_encoder.h Normal file
View File

@@ -0,0 +1,99 @@
#pragma once
#include "esp_log.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_event.h"
#define ZH_ENCODER_INIT_CONFIG_DEFAULT() \
{ \
.task_priority = 10, \
.stack_size = 3072, \
.queue_size = 10, \
.a_gpio_number = 0, \
.b_gpio_number = 0, \
.encoder_min_value = -100, \
.encoder_max_value = 100, \
.encoder_step = 1, \
.encoder_number = 0}
#ifdef __cplusplus
extern "C"
{
#endif
typedef struct // Structure for initial initialization of encoder.
{
uint8_t task_priority; // Task priority for the encoder isr processing. @note It is not recommended to set a value less than 10.
uint16_t stack_size; // Stack size for task for the encoder isr processing processing. @note The minimum size is 3072 bytes.
uint8_t queue_size; // Queue size for task for the encoder processing. @note It is not recommended to set a value less than 10.
uint8_t a_gpio_number; // Encoder A GPIO number.
uint8_t b_gpio_number; // Encoder B GPIO number.
int32_t encoder_min_value; // Encoder min value. @note Must be less than encoder_max_value.
int32_t encoder_max_value; // Encoder max value. @note Must be greater than encoder_min_value.
double encoder_step; // Encoder step. @note Must be greater than 0.
uint8_t encoder_number; // Unique encoder number.
} zh_encoder_init_config_t;
typedef struct // Encoder handle.
{
uint8_t a_gpio_number; // Encoder A GPIO number.
uint8_t b_gpio_number; // Encoder B GPIO number.
int32_t encoder_min_value; // Encoder min value. @note Must be less than encoder_max_value.
int32_t encoder_max_value; // Encoder max value. @note Must be greater than encoder_min_value.
double encoder_step; // Encoder step. @note Must be greater than 0.
double encoder_position; // Encoder position.
uint8_t encoder_number; // Encoder unique number.
uint8_t encoder_state; // Encoder internal state.
bool is_initialized; // Encoder initialization flag.
} zh_encoder_handle_t;
ESP_EVENT_DECLARE_BASE(ZH_ENCODER);
typedef struct // Structure for sending data to the event handler when cause an interrupt. @note Should be used with ZH_ENCODER event base.
{
uint8_t encoder_number; // Encoder unique number.
double encoder_position; // Encoder current position.
} zh_encoder_event_on_isr_t;
/**
* @brief Initialize encoder.
*
* @note The encoder will be set to the position (encoder_min_value + encoder_max_value)/2.
*
* @param[in] config Pointer to encoder initialized configuration structure. Can point to a temporary variable.
* @param[out] handle Pointer to unique encoder handle.
*
* @note Before initialize the encoder recommend initialize zh_encoder_init_config_t structure with default values.
*
* @code zh_encoder_init_config_t config = ZH_ENCODER_INIT_CONFIG_DEFAULT() @endcode
*
* @return ESP_OK if success or an error code otherwise.
*/
esp_err_t zh_encoder_init(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle);
/**
* @brief Set encoder position.
*
* @param[in, out] handle Pointer to unique encoder handle.
* @param[in] position Encoder position (must be between encoder_min_value and encoder_max_value).
*
* @return ESP_OK if success or an error code otherwise.
*/
esp_err_t zh_encoder_set(zh_encoder_handle_t *handle, double position);
/**
* @brief Reset encoder position.
*
* @note The encoder will be set to the position (encoder_min_value + encoder_max_value)/2.
*
* @param[in, out] handle Pointer to unique encoder handle.
*
* @return ESP_OK if success or an error code otherwise.
*/
esp_err_t zh_encoder_reset(zh_encoder_handle_t *handle);
#ifdef __cplusplus
}
#endif

0
main.c
View File

View File

@@ -0,0 +1 @@
1.0.0

209
zh_encoder.c Normal file
View File

@@ -0,0 +1,209 @@
#include "zh_encoder.h"
#define TAG "zh_encoder"
#define ZH_ENCODER_LOGI(msg, ...) ESP_LOGI(TAG, msg, ##__VA_ARGS__)
#define ZH_ENCODER_LOGW(msg, ...) ESP_LOGW(TAG, msg, ##__VA_ARGS__)
#define ZH_ENCODER_LOGE(msg, ...) ESP_LOGE(TAG, msg, ##__VA_ARGS__)
#define ZH_ENCODER_LOGE_ERR(msg, err, ...) ESP_LOGE(TAG, "[%s:%d:%s] " msg, __FILE__, __LINE__, esp_err_to_name(err), ##__VA_ARGS__)
#define ZH_ENCODER_CHECK(cond, err, msg, ...) \
if (!(cond)) \
{ \
ZH_ENCODER_LOGE_ERR(msg, err); \
return err; \
}
#define ZH_ENCODER_DIRECTION_CW 0x10
#define ZH_ENCODER_DIRECTION_CCW 0x20
static const uint8_t _encoder_matrix[7][4] = {
{0x03, 0x02, 0x01, 0x00},
{0x23, 0x00, 0x01, 0x00},
{0x13, 0x02, 0x00, 0x00},
{0x03, 0x05, 0x04, 0x00},
{0x03, 0x03, 0x04, 0x00},
{0x03, 0x05, 0x03, 0x00},
};
static QueueHandle_t _queue_handle = NULL;
static bool _is_initialized = false;
static esp_err_t _zh_encoder_validate_config(const zh_encoder_init_config_t *config);
static esp_err_t _zh_encoder_gpio_init(const zh_encoder_init_config_t *config);
static esp_err_t _zh_encoder_configure_interrupts(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle);
static esp_err_t _zh_encoder_init_resources(const zh_encoder_init_config_t *config);
static esp_err_t _zh_encoder_create_task(const zh_encoder_init_config_t *config);
static void _zh_encoder_isr_handler(void *arg);
static void _zh_encoder_isr_processing_task(void *pvParameter);
ESP_EVENT_DEFINE_BASE(ZH_ENCODER);
esp_err_t zh_encoder_init(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle)
{
ZH_ENCODER_LOGI("Encoder initialization started.");
esp_err_t err = _zh_encoder_validate_config(config);
ZH_ENCODER_CHECK(err == ESP_OK, err, "Encoder initialization failed. Initial configuration check failed.");
ZH_ENCODER_LOGI("Encoder initial configuration check completed successfully.");
handle->encoder_number = config->encoder_number;
handle->encoder_min_value = config->encoder_min_value;
handle->encoder_max_value = config->encoder_max_value;
handle->encoder_step = config->encoder_step;
handle->encoder_position = (handle->encoder_min_value + handle->encoder_max_value) / 2;
err = _zh_encoder_gpio_init(config);
ZH_ENCODER_CHECK(err == ESP_OK, err, "Encoder initialization failed. GPIO initialization failed.");
ZH_ENCODER_LOGI("Encoder GPIO initialization completed successfully.");
handle->a_gpio_number = config->a_gpio_number;
handle->b_gpio_number = config->b_gpio_number;
err = _zh_encoder_configure_interrupts(config, handle);
ZH_ENCODER_CHECK(err == ESP_OK, err, "Encoder initialization failed. Interrupt initialization failed.");
ZH_ENCODER_LOGI("Encoder interrupt initialization completed successfully.");
err = _zh_encoder_init_resources(config);
ZH_ENCODER_CHECK(err == ESP_OK, err, "Encoder initialization failed. Resources initialization failed.");
ZH_ENCODER_LOGI("Encoder resources initialization completed successfully.");
err = _zh_encoder_create_task(config);
ZH_ENCODER_CHECK(err == ESP_OK, err, "Encoder initialization failed. Processing task initialization failed.");
ZH_ENCODER_LOGI("Encoder processing task initialization completed successfully.");
handle->is_initialized = true;
_is_initialized = true;
ZH_ENCODER_LOGI("Encoder initialization completed successfully.");
return ESP_OK;
}
esp_err_t zh_encoder_set(zh_encoder_handle_t *handle, double position)
{
ZH_ENCODER_LOGI("Encoder set position started.");
ZH_ENCODER_CHECK(handle->is_initialized == true, ESP_FAIL, "Encoder set position failed. Encoder not initialized.");
ZH_ENCODER_CHECK(position <= handle->encoder_max_value && position >= handle->encoder_min_value, ESP_ERR_INVALID_ARG, "Encoder set position failed. Invalid argument.");
handle->encoder_position = position;
ZH_ENCODER_LOGI("Encoder set position completed successfully.");
return ESP_OK;
}
esp_err_t zh_encoder_reset(zh_encoder_handle_t *handle)
{
ZH_ENCODER_LOGI("Encoder reset started.");
ZH_ENCODER_CHECK(handle->is_initialized == true, ESP_FAIL, "Encoder reset failed. Encoder not initialized.");
handle->encoder_position = (handle->encoder_min_value + handle->encoder_max_value) / 2;
ZH_ENCODER_LOGI("Encoder reset completed successfully.");
return ESP_OK;
}
static esp_err_t _zh_encoder_validate_config(const zh_encoder_init_config_t *config)
{
ZH_ENCODER_CHECK(config != NULL, ESP_ERR_INVALID_ARG, "Invalid configuration.");
ZH_ENCODER_CHECK(config->task_priority >= 10 && config->stack_size >= 3072, ESP_ERR_INVALID_ARG, "Invalid task settings.");
ZH_ENCODER_CHECK(config->queue_size >= 10, ESP_ERR_INVALID_ARG, "Invalid queue size.");
ZH_ENCODER_CHECK(config->encoder_max_value > config->encoder_min_value, ESP_ERR_INVALID_ARG, "Invalid encoder min/max value.");
ZH_ENCODER_CHECK(config->encoder_step > 0, ESP_ERR_INVALID_ARG, "Invalid encoder step.");
return ESP_OK;
}
static esp_err_t _zh_encoder_gpio_init(const zh_encoder_init_config_t *config)
{
ZH_ENCODER_CHECK(config->a_gpio_number < GPIO_NUM_MAX || config->b_gpio_number < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG, "Invalid GPIO number.")
ZH_ENCODER_CHECK(config->a_gpio_number != config->b_gpio_number, ESP_ERR_INVALID_ARG, "Invalid GPIO number.")
gpio_config_t pin_config = {
.mode = GPIO_MODE_INPUT,
.pin_bit_mask = (1ULL << config->a_gpio_number) | (1ULL << config->b_gpio_number),
.pull_up_en = GPIO_PULLUP_ENABLE,
.intr_type = GPIO_INTR_ANYEDGE};
esp_err_t err = gpio_config(&pin_config);
ZH_ENCODER_CHECK(err == ESP_OK, err, "GPIO initialization failed.");
return ESP_OK;
}
static esp_err_t _zh_encoder_configure_interrupts(const zh_encoder_init_config_t *config, zh_encoder_handle_t *handle)
{
gpio_install_isr_service(0);
esp_err_t err = gpio_isr_handler_add(config->a_gpio_number, _zh_encoder_isr_handler, handle);
ZH_ENCODER_CHECK(err == ESP_OK, err, "Interrupt initialization failed.");
err = gpio_isr_handler_add(config->b_gpio_number, _zh_encoder_isr_handler, handle);
ZH_ENCODER_CHECK(err == ESP_OK, err, "Interrupt initialization failed.");
return ESP_OK;
}
static esp_err_t _zh_encoder_init_resources(const zh_encoder_init_config_t *config)
{
if (_is_initialized == false)
{
_queue_handle = xQueueCreate(config->queue_size, sizeof(zh_encoder_handle_t));
ZH_ENCODER_CHECK(_queue_handle != NULL, ESP_FAIL, "Queue creation failed.");
}
return ESP_OK;
}
static esp_err_t _zh_encoder_create_task(const zh_encoder_init_config_t *config)
{
if (_is_initialized == false)
{
BaseType_t err = xTaskCreatePinnedToCore(
&_zh_encoder_isr_processing_task,
"zh_encoder_isr_processing",
config->stack_size,
NULL,
config->task_priority,
NULL,
tskNO_AFFINITY);
ZH_ENCODER_CHECK(err == pdPASS, ESP_FAIL, "Task creation failed.");
}
return ESP_OK;
}
static void IRAM_ATTR _zh_encoder_isr_handler(void *arg)
{
zh_encoder_handle_t *encoder_handle = (zh_encoder_handle_t *)arg;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
encoder_handle->encoder_state = _encoder_matrix[encoder_handle->encoder_state & 0x0F]
[(gpio_get_level(encoder_handle->b_gpio_number) << 1) | gpio_get_level(encoder_handle->a_gpio_number)];
switch (encoder_handle->encoder_state & 0x30)
{
case ZH_ENCODER_DIRECTION_CW:
if (encoder_handle->encoder_position < encoder_handle->encoder_max_value)
{
encoder_handle->encoder_position = encoder_handle->encoder_position + encoder_handle->encoder_step;
if (encoder_handle->encoder_position > encoder_handle->encoder_max_value)
{
encoder_handle->encoder_position = encoder_handle->encoder_max_value;
}
xQueueSendFromISR(_queue_handle, encoder_handle, &xHigherPriorityTaskWoken);
}
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;
if (encoder_handle->encoder_position < encoder_handle->encoder_min_value)
{
encoder_handle->encoder_position = encoder_handle->encoder_min_value;
}
xQueueSendFromISR(_queue_handle, encoder_handle, &xHigherPriorityTaskWoken);
}
break;
default:
break;
}
if (xHigherPriorityTaskWoken == pdTRUE)
{
portYIELD_FROM_ISR();
};
}
static void IRAM_ATTR _zh_encoder_isr_processing_task(void *pvParameter)
{
zh_encoder_handle_t queue = {0};
zh_encoder_event_on_isr_t encoder_data = {0};
while (xQueueReceive(_queue_handle, &queue, portMAX_DELAY) == pdTRUE)
{
ZH_ENCODER_LOGI("Encoder isr processing begin.");
encoder_data.encoder_number = queue.encoder_number;
encoder_data.encoder_position = queue.encoder_position;
esp_err_t err = esp_event_post(ZH_ENCODER, 0, &encoder_data, sizeof(zh_encoder_event_on_isr_t), portTICK_PERIOD_MS);
if (err != ESP_OK)
{
ZH_ENCODER_LOGE_ERR("Encoder isr processing failed. Failed to post interrupt event.", err);
}
ZH_ENCODER_LOGI("Encoder isr processing completed successfully.");
}
vTaskDelete(NULL);
}