Compare commits

...
4 Commits
Author SHA1 Message Date
aZholtikov a5bea1e3b9 doc: added wiki 2026-11-03 13:32:44 +03:00
aZholtikov 66c6b13041 doc: updated readme 2026-11-03 12:17:00 +03:00
aZholtikov 7f92fb6cd4 doc: updated comments 2026-11-03 12:13:48 +03:00
aZholtikov 15b498fd6b perf: updated error checks 2026-10-04 22:24:57 +03:00
4 changed files with 386 additions and 65 deletions

No files matched your search

+22 -11
View File
@@ -10,18 +10,13 @@
6. PCNT glitch filter for noise rejection (1000ns). 6. PCNT glitch filter for noise rejection (1000ns).
7. Multiple inclinometer instances support. 7. Multiple inclinometer instances support.
## Note ## Attention
Enable the following settings in menuconfig: 1. The maximum value of encoder_pulses is 8191, limited by the PCNT counter range of +/-32767.
```text
PCNT_CTRL_FUNC_IN_IRAM
PCNT_ISR_IRAM_SAF
```
## Using ## Using
In an existing project, run the following command to install the components: In an existing project, run the following command to install the component:
```bash ```bash
cd ../your_project/components cd ../your_project/components
@@ -34,7 +29,9 @@ In the application, add the component:
#include "zh_inclinometer.h" #include "zh_inclinometer.h"
``` ```
## Example ## Examples
### Basic Example
```c ```c
#include "zh_inclinometer.h" #include "zh_inclinometer.h"
@@ -48,13 +45,27 @@ void app_main(void)
config.a_gpio_number = GPIO_NUM_26; config.a_gpio_number = GPIO_NUM_26;
config.b_gpio_number = GPIO_NUM_27; config.b_gpio_number = GPIO_NUM_27;
config.encoder_pulses = 3600; config.encoder_pulses = 3600;
zh_inclinometer_init(&config, &inclinometer_handle); esp_err_t ret = zh_inclinometer_init(&config, &inclinometer_handle);
if (ret != ESP_OK)
{
printf("Inclinometer initialization error: %s\n", esp_err_to_name(ret));
return;
}
ret = zh_inclinometer_reset(&inclinometer_handle);
if (ret == ESP_OK)
{
printf("Inclinometer position reset to zero.\n");
}
for (;;) for (;;)
{ {
float angle = 0; float angle = 0;
zh_inclinometer_get(&inclinometer_handle, &angle); ret = zh_inclinometer_get(&inclinometer_handle, &angle);
if (ret == ESP_OK)
{
printf("Inclinometer position is %0.2f degrees.\n", angle); printf("Inclinometer position is %0.2f degrees.\n", angle);
}
vTaskDelay(100 / portTICK_PERIOD_MS); vTaskDelay(100 / portTICK_PERIOD_MS);
} }
zh_inclinometer_deinit(&inclinometer_handle);
} }
``` ```
+7 -5
View File
@@ -20,11 +20,14 @@
#pragma once #pragma once
#include "stdbool.h"
#include "stdint.h"
#include "esp_log.h" #include "esp_log.h"
#include "driver/gpio.h" #include "driver/gpio.h"
#include "driver/pulse_cnt.h" #include "driver/pulse_cnt.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "esp_heap_caps.h"
#define ZH_INCLINOMETER_INIT_CONFIG_DEFAULT() \ #define ZH_INCLINOMETER_INIT_CONFIG_DEFAULT() \
{ \ { \
@@ -63,8 +66,8 @@ extern "C"
*/ */
typedef struct typedef struct
{ {
uint8_t a_gpio_number; /*!< Encoder A channel GPIO number */ gpio_num_t a_gpio_number; /*!< Encoder A channel GPIO number */
uint8_t b_gpio_number; /*!< Encoder B channel GPIO number */ gpio_num_t b_gpio_number; /*!< Encoder B channel GPIO number */
bool pullup; /*!< GPIO pull-up resistor enable (true) or disable (false) */ bool pullup; /*!< GPIO pull-up resistor enable (true) or disable (false) */
bool rotation; /*!< Rotation direction: true - positive for CW, false - positive for CCW */ bool rotation; /*!< Rotation direction: true - positive for CW, false - positive for CCW */
uint16_t encoder_pulses; /*!< Number of encoder pulses per one full rotation */ uint16_t encoder_pulses; /*!< Number of encoder pulses per one full rotation */
@@ -78,7 +81,7 @@ extern "C"
* and starts the pulse counter. * and starts the pulse counter.
* *
* @param[in] config Pointer to the inclinometer initialization configuration * @param[in] config Pointer to the inclinometer initialization configuration
* structure. Can point to a temporary variable (must not be NULL) * structure (can point to a temporary variable, must not be NULL)
* @param[out] handle Pointer to the unique inclinometer handle (must be NULL) * @param[out] handle Pointer to the unique inclinometer handle (must be NULL)
* *
* @return ESP_OK on success * @return ESP_OK on success
@@ -96,14 +99,13 @@ extern "C"
* PCNT unit, frees the inclinometer handle memory, and sets the handle to * PCNT unit, frees the inclinometer handle memory, and sets the handle to
* NULL. * NULL.
* *
* @param[in, out] handle Pointer to the unique inclinometer handle (must not be NULL) * @param[in,out] handle Pointer to the inclinometer handle pointer (will be set to NULL)
* *
* @note After deinitialization, the handle is invalidated and must not be * @note After deinitialization, the handle is invalidated and must not be
* used. Call zh_inclinometer_init() again to reinitialize. * used. Call zh_inclinometer_init() again to reinitialize.
* *
* @return ESP_OK on success * @return ESP_OK on success
* @return ESP_ERR_INVALID_ARG if handle or *handle is NULL * @return ESP_ERR_INVALID_ARG if handle or *handle is NULL
* @return ESP_FAIL if PCNT stop, disable, or deletion failed
*/ */
esp_err_t zh_inclinometer_deinit(zh_inclinometer_handle_t **handle); esp_err_t zh_inclinometer_deinit(zh_inclinometer_handle_t **handle);
+294
View File
@@ -0,0 +1,294 @@
# Описание компонента zh_inclinometer
## Общие сведения
**zh_inclinometer** — это компонент ESP-IDF для ESP32, реализующий измерение углового положения с помощью квадратурного оптического энкодера. Компонент использует аппаратный модуль счётчика импульсов (PCNT) из ESP-IDF для подсчёта импульсов с двух каналов энкодера и преобразования их в угол в градусах.
Компонент предоставляет простой API для инициализации, получения текущего угла и сброса счётчика. Поддерживается настройка направлений вращения, режима подтяжки GPIO и разрешения энкодера в импульсах на оборот.
## Основные возможности
1. **Поддержка квадратурного энкодера** — аппаратное декодирование каналов A и B через PCNT.
2. **Настраиваемые GPIO-пины** — задание любых свободных GPIO для каналов A и B.
3. **Настраиваемая подтяжка** — включение или отключение внутренних подтягивающих резисторов.
4. **Настраиваемое направление вращения** — положительный угол для вращения по часовой или против часовой стрелки.
5. **Настраиваемое разрешение** — указание количества импульсов на полный оборот энкодера.
6. **Фильтр глитчей** — аппаратное отсечение помех длительностью менее 1000 нс.
7. **Поддержка нескольких экземпляров** — одновременная работа с несколькими энкодерами.
## Внутреннее устройство
### Структура `zh_inclinometer_handle_t`
Публичный тип — непрозрачный указатель на внутреннюю структуру:
| Поле | Тип | Описание |
| ------ | ----- | ---------- |
| `pcnt_unit_handle` | `pcnt_unit_handle_t` | Указатель на экземпляр PCNT для данного энкодера |
| `pcnt_channel_a_handle` | `pcnt_channel_handle_t` | Указатель на канал A PCNT (подключён к пину энкодера A) |
| `pcnt_channel_b_handle` | `pcnt_channel_handle_t` | Указатель на канал B PCNT (подключён к пину энкодера B) |
| `degrees_per_pulse` | `float` | Угол в градусах, приходящийся на один подсчитанный импульс |
| `rotation` | `bool` | Флаг направления вращения: `true` — положительный угол при вращении по часовой стрелке |
### Структура конфигурации `zh_inclinometer_init_config_t`
Структура передаётся в функцию `zh_inclinometer_init()` при создании экземпляра:
| Поле | Тип | Описание |
| ------ | ----- | ---------- |
| `a_gpio_number` | `gpio_num_t` | Номер GPIO для канала A энкодера |
| `b_gpio_number` | `gpio_num_t` | Номер GPIO для канала B энкодера |
| `pullup` | `bool` | Включить подтягивающий резистор (true) или отключить (false) |
| `rotation` | `bool` | Направление: true — положительный угол при вращении по часовой стрелке |
| `encoder_pulses` | `uint16_t` | Количество импульсов энкодера на один полный оборот |
### Управление памятью
Экземпляр inclinometer выделяется в функции `zh_inclinometer_init()` через `heap_caps_calloc(1, sizeof(zh_inclinometer_handle_t), MALLOC_CAP_8BIT)` и полностью очищается в `zh_inclinometer_deinit()` через `heap_caps_free()`. Ресурсы PCNT (unit и каналы) освобождаются до освобождения самого handle.
## API (интерфейс)
### Инициализация и освобождение
| Функция | Описание |
| --------- | ---------- |
| `zh_inclinometer_init()` | Выделяет память, проверяет конфигурацию, инициализирует PCNT с двумя каналами для квадратурного декодирования и запускает счётчик. |
| `zh_inclinometer_deinit()` | Останавливает и отключает PCNT, удаляет каналы и unit, освобождает память handle и устанавливает его в NULL. |
| `zh_inclinometer_reset()` | Очищает счётчик PCNT, устанавливая текущую позицию в 0 градусов. |
### Получение данных
| Функция | Описание |
|---------|----------|
| `zh_inclinometer_get()` | Считывает текущее значение счётчика PCNT и преобразует его в угол в градусах с учётом направления вращения. |
## Алгоритмы
### Расчёт угла
При инициализации вычисляется коэффициент градусов на импульс:
```text
degrees_per_pulse = 360.0 / (4 * encoder_pulses)
```
Множитель 4 обусловлен квадратурным декодированием: один полный шаг квадратурного энкодера содержит 4 изменения сигнала (по фронту и спаду на обоих каналах A и B), что увеличивает эффективное разрешение в 4 раза.
Текущий угол вычисляется при каждом вызове `zh_inclinometer_get()`:
```text
angle = pcnt_count * degrees_per_pulse
```
Если `rotation == false`, угол инвертируется:
```text
angle = -angle
```
Отрицательный ноль приводится к положительному нулю (`0.0`).
### Декодирование квадратурного сигнала
Инициализация PCNT настраивает два канала для двунаправленного подсчёта. Каждый канал реагирует на фронты своего сигнала (edge action), а направление счёта определяется текущим уровнем второго сигнала (level action):
| Канал | Edge action | Level action |
|-------|-------------|--------------|
| `A` (edge — пин A, level — пин B) | фронт — `DECREASE`, спад — `INCREASE` | `B == 1` — `KEEP`, `B == 0` — `INVERSE` |
| `B` (edge — пин B, level — пин A) | фронт — `INCREASE`, спад — `DECREASE` | `A == 1` — `KEEP`, `A == 0` — `INVERSE` |
`INVERSE` меняет действие счётчика на противоположное, поэтому при одном направлении вращения все четыре перехода сигналов дают `+1`, при противоположном — `-1`. Так реализуется четырёхкратное увеличение разрешения относительно шага энкодера.
Знак результата зависит от физически подключённой последовательности каналов. Параметр `rotation` компенсирует эту разницу: при `rotation == false` знак угла инвертируется при чтении, а конфигурация PCNT остаётся неизменной.
### Фильтр глитчей
Встроенный аппаратный фильтр отбрасывает импульсы длительностью менее 1000 нс (1 мкс). Фильтр настраивается функцией `pcnt_unit_set_glitch_filter()` и работает на уровне периферии, не создавая нагрузки на процессор.
### Очистка при ошибках
При инициализации PCNT реализована каскадная очистка ресурсов: при ошибке создания или настройки каждого последующего ресурса предыдущие удаляются в обратном порядке. Это гарантирует отсутствие утечек ресурсов при неудачной инициализации.
## Примеры использования
### Базовое чтение угла
Пример чтения текущего угла энкодера с периодом 100 мс.
```c
#include "zh_inclinometer.h"
zh_inclinometer_handle_t *inclinometer_handle = NULL;
void app_main(void)
{
esp_log_level_set("zh_inclinometer", ESP_LOG_ERROR);
zh_inclinometer_init_config_t config = ZH_INCLINOMETER_INIT_CONFIG_DEFAULT();
config.a_gpio_number = GPIO_NUM_26;
config.b_gpio_number = GPIO_NUM_27;
config.encoder_pulses = 3600;
config.pullup = true;
config.rotation = true;
esp_err_t ret = zh_inclinometer_init(&config, &inclinometer_handle);
if (ret != ESP_OK)
{
printf("Inclinometer initialization error: %s\n", esp_err_to_name(ret));
return;
}
for (int i = 0; i < 100; i++)
{
float angle = 0;
ret = zh_inclinometer_get(&inclinometer_handle, &angle);
if (ret == ESP_OK)
{
printf("Angle: %.2f deg\n", angle);
}
vTaskDelay(100 / portTICK_PERIOD_MS);
}
zh_inclinometer_deinit(&inclinometer_handle);
}
```
### Сброс позиции и работа с разными конфигурациями
Пример инициализации с отключённой подтяжкой, обратным направлением и периодическим сбросом позиции.
```c
#include "zh_inclinometer.h"
zh_inclinometer_handle_t *inclinometer_handle = NULL;
void app_main(void)
{
esp_log_level_set("zh_inclinometer", ESP_LOG_ERROR);
zh_inclinometer_init_config_t config = ZH_INCLINOMETER_INIT_CONFIG_DEFAULT();
config.a_gpio_number = GPIO_NUM_26;
config.b_gpio_number = GPIO_NUM_27;
config.encoder_pulses = 1800;
config.pullup = false;
config.rotation = false;
esp_err_t ret = zh_inclinometer_init(&config, &inclinometer_handle);
if (ret != ESP_OK)
{
printf("Initialization error: %s\n", esp_err_to_name(ret));
return;
}
for (int i = 0; i < 10; i++)
{
float angle = 0;
ret = zh_inclinometer_get(&inclinometer_handle, &angle);
if (ret == ESP_OK)
{
printf("Angle before reset: %.2f deg\n", angle);
}
ret = zh_inclinometer_reset(&inclinometer_handle);
if (ret == ESP_OK)
{
printf("Position reset to zero.\n");
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
zh_inclinometer_deinit(&inclinometer_handle);
}
```
### Ограничение на количество импульсов
Пример с максимальным разрешением (encoder_pulses = 8191) и демонстрация обработки ошибок.
```c
#include "zh_inclinometer.h"
zh_inclinometer_handle_t *inclinometer_handle = NULL;
void app_main(void)
{
esp_log_level_set("zh_inclinometer", ESP_LOG_ERROR);
zh_inclinometer_init_config_t config = ZH_INCLINOMETER_INIT_CONFIG_DEFAULT();
config.a_gpio_number = GPIO_NUM_26;
config.b_gpio_number = GPIO_NUM_27;
config.encoder_pulses = 8191;
config.pullup = true;
config.rotation = true;
esp_err_t ret = zh_inclinometer_init(&config, &inclinometer_handle);
if (ret != ESP_OK)
{
printf("Inclinometer initialization error: %s\n", esp_err_to_name(ret));
return;
}
float angle = 0;
ret = zh_inclinometer_get(&inclinometer_handle, &angle);
if (ret == ESP_OK)
{
printf("Current angle: %.2f deg\n", angle);
}
ret = zh_inclinometer_reset(&inclinometer_handle);
if (ret == ESP_OK)
{
printf("Position reset.\n");
}
zh_inclinometer_deinit(&inclinometer_handle);
}
```
## Логирование
Компонент использует ESP-IDF логирование с тегом `"zh_inclinometer"`. Уровень логирования настраивается через `esp_log_level_set()`:
```c
esp_log_level_set("zh_inclinometer", ESP_LOG_ERROR);
```
Макросы логирования определены внутри компонента и не требуют отдельного подключения. Доступные уровни: `ESP_LOG_ERROR` и `ESP_LOGI`.
## Ошибки
| Код | Описание |
| ----- | ---------- |
| `ESP_OK` | Успешное выполнение операции |
| `ESP_ERR_INVALID_ARG` | Неверный аргумент: NULL-указатель, невалидный GPIO (>= GPIO_NUM_MAX), одинаковые пины A и B, `encoder_pulses` равно 0 |
| `ESP_ERR_INVALID_STATE` | Повторная инициализация: `*handle` уже не равен NULL |
| `ESP_ERR_NO_MEM` | Не удалось выделить память для handle |
| `ESP_FAIL` | Ошибка инициализации PCNT, GPIO, фильтра глитчей или других ресурсов |
## Ограничения
1. **Максимум 8191 импульс на оборот** — ограничено диапазоном счётчика PCNT (±32767), так как внутренний счётчик умножается на 4 при квадратурном декодировании (`4 * encoder_pulses <= 32767`).
2. **Сброс счётчика при достижении пределов** — аппаратный PCNT автоматически обнуляет счётчик при достижении high_limit или low_limit. Угол «зацикливается» в диапазоне приблизительно от -360° до 360°. При вращении за пределы одного оборота счётчик сбрасывается и угол начинается заново.
3. **Не потокобезопасен** — компонент не использует мьютексы или другие механизмы синхронизации. Одновременный доступ к handle из нескольких задач не поддерживается.
4. **Глитч-фильтр зафиксирован на 1000 нс** — значение не выносится в конфигурацию и не может быть изменено пользователем.
5. **GPIO_NUM_MAX не является допустимым значением** — оба GPIO должны быть явно заданы перед инициализацией. Значение `GPIO_NUM_MAX` в `ZH_INCLINOMETER_INIT_CONFIG_DEFAULT()` служит маркером «не задано».
## Требования для сборки
- ESP-IDF версии 5.0 или выше
- Компонент `driver` (ESP-IDF < 6) или `esp_driver_gpio` + `esp_driver_pcnt` (ESP-IDF 6)
- FreeRTOS (входит в состав ESP-IDF)
- Два свободных GPIO-пина для подключения энкодера
- Модуль PCNT периферии ESP32 (доступен на всех моделях ESP32)
## Установка
```bash
cd ваш_проект/components
git clone https://github.com/aZholtikov/zh_inclinometer
```
```c
#include "zh_inclinometer.h"
```
+63 -49
View File
@@ -1,6 +1,6 @@
#include "zh_inclinometer.h" #include "zh_inclinometer.h"
#define TAG "zh_inclinometer" static const char *TAG = "zh_inclinometer";
#define ZH_LOGI(msg, ...) ESP_LOGI(TAG, msg, ##__VA_ARGS__) #define ZH_LOGI(msg, ...) ESP_LOGI(TAG, msg, ##__VA_ARGS__)
#define ZH_LOGE(msg, err, ...) ESP_LOGE(TAG, "[%s:%d:%s] " msg, __FILE__, __LINE__, esp_err_to_name(err), ##__VA_ARGS__) #define ZH_LOGE(msg, err, ...) ESP_LOGE(TAG, "[%s:%d:%s] " msg, __FILE__, __LINE__, esp_err_to_name(err), ##__VA_ARGS__)
@@ -13,6 +13,13 @@
return err; \ return err; \
} }
#define ZH_ERROR_CHECK_CONT(cond, cleanup, msg, ...) \
if (!(cond)) \
{ \
ZH_LOGE(msg, ESP_FAIL, ##__VA_ARGS__); \
cleanup; \
}
/** /**
* @brief Internal structure holding the inclinometer instance state. * @brief Internal structure holding the inclinometer instance state.
* *
@@ -34,10 +41,10 @@ struct _zh_inclinometer_handle_t
* *
* Checks that all required configuration parameters are within valid ranges. * Checks that all required configuration parameters are within valid ranges.
* *
* @param config Pointer to the initialization configuration structure. * @param config Pointer to the initialization configuration structure
* *
* @return ESP_OK if the configuration is valid * @return ESP_OK if the configuration is valid
* @return ESP_ERR_INVALID_ARG if encoder_pulses is zero or negative * @return ESP_ERR_INVALID_ARG if encoder_pulses is zero or out of range
*/ */
static esp_err_t _zh_inclinometer_validate_config(const zh_inclinometer_init_config_t *config); static esp_err_t _zh_inclinometer_validate_config(const zh_inclinometer_init_config_t *config);
@@ -65,7 +72,7 @@ esp_err_t zh_inclinometer_init(const zh_inclinometer_init_config_t *config, zh_i
*handle = heap_caps_calloc(1, sizeof(zh_inclinometer_handle_t), MALLOC_CAP_8BIT); *handle = heap_caps_calloc(1, sizeof(zh_inclinometer_handle_t), MALLOC_CAP_8BIT);
ZH_ERROR_CHECK(*handle != NULL, ESP_ERR_NO_MEM, NULL, "Inclinometer initialization failed. Failed to allocate inclinometer handle."); ZH_ERROR_CHECK(*handle != NULL, ESP_ERR_NO_MEM, NULL, "Inclinometer initialization failed. Failed to allocate inclinometer handle.");
ZH_ERROR_CHECK(_zh_inclinometer_pcnt_init(config, *handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "Inclinometer initialization failed. PCNT initialization failed."); ZH_ERROR_CHECK(_zh_inclinometer_pcnt_init(config, *handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "Inclinometer initialization failed. PCNT initialization failed.");
(*handle)->degrees_per_pulse = 360.0 / config->encoder_pulses; (*handle)->degrees_per_pulse = 360.0 / (4 * config->encoder_pulses);
(*handle)->rotation = config->rotation; (*handle)->rotation = config->rotation;
ZH_LOGI("Inclinometer initialization completed successfully."); ZH_LOGI("Inclinometer initialization completed successfully.");
return ESP_OK; return ESP_OK;
@@ -75,11 +82,11 @@ esp_err_t zh_inclinometer_deinit(zh_inclinometer_handle_t **handle)
{ {
ZH_LOGI("Inclinometer deinitialization started."); ZH_LOGI("Inclinometer deinitialization started.");
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Inclinometer deinitialization failed. Invalid argument."); ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Inclinometer deinitialization failed. Invalid argument.");
ZH_ERROR_CHECK(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Inclinometer deinitialization failed. PCNT unit stop fail."); ZH_ERROR_CHECK_CONT(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Inclinometer deinitialization failed. PCNT unit stop fail.");
ZH_ERROR_CHECK(pcnt_unit_disable((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Inclinometer deinitialization failed. PCNT unit disable fail."); ZH_ERROR_CHECK_CONT(pcnt_unit_disable((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Inclinometer deinitialization failed. PCNT unit disable fail.");
ZH_ERROR_CHECK(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "Inclinometer deinitialization failed. PCNT delete channel fail."); ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, NULL, "Inclinometer deinitialization failed. PCNT delete channel fail.");
ZH_ERROR_CHECK(pcnt_del_channel((*handle)->pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "Inclinometer deinitialization failed. PCNT delete channel fail."); ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_b_handle) == ESP_OK, NULL, "Inclinometer deinitialization failed. PCNT delete channel fail.");
ZH_ERROR_CHECK(pcnt_del_unit((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Inclinometer deinitialization failed. PCNT delete unit fail."); ZH_ERROR_CHECK_CONT(pcnt_del_unit((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Inclinometer deinitialization failed. PCNT delete unit fail.");
heap_caps_free(*handle); heap_caps_free(*handle);
*handle = NULL; *handle = NULL;
ZH_LOGI("Inclinometer deinitialization completed successfully."); ZH_LOGI("Inclinometer deinitialization completed successfully.");
@@ -93,7 +100,11 @@ esp_err_t zh_inclinometer_get(zh_inclinometer_handle_t **handle, float *angle)
int pcnt_count = 0; int pcnt_count = 0;
ZH_ERROR_CHECK(pcnt_unit_get_count((*handle)->pcnt_unit_handle, &pcnt_count) == ESP_OK, ESP_FAIL, NULL, "Inclinometer get position failed. PCNT unit get count fail."); ZH_ERROR_CHECK(pcnt_unit_get_count((*handle)->pcnt_unit_handle, &pcnt_count) == ESP_OK, ESP_FAIL, NULL, "Inclinometer get position failed. PCNT unit get count fail.");
float angle_temp = pcnt_count * (*handle)->degrees_per_pulse; float angle_temp = pcnt_count * (*handle)->degrees_per_pulse;
*angle = ((*handle)->rotation == true) ? angle_temp : ((angle_temp == 0) ? angle_temp : -angle_temp); *angle = (*handle)->rotation == true ? angle_temp : -angle_temp;
if (*angle == 0.0)
{
*angle = 0.0;
}
ZH_LOGI("Inclinometer get position completed successfully."); ZH_LOGI("Inclinometer get position completed successfully.");
return ESP_OK; return ESP_OK;
} }
@@ -109,7 +120,7 @@ esp_err_t zh_inclinometer_reset(zh_inclinometer_handle_t **handle)
static esp_err_t _zh_inclinometer_validate_config(const zh_inclinometer_init_config_t *config) static esp_err_t _zh_inclinometer_validate_config(const zh_inclinometer_init_config_t *config)
{ {
ZH_ERROR_CHECK(config->encoder_pulses > 0, ESP_ERR_INVALID_ARG, NULL, "Invalid encoder pulses."); ZH_ERROR_CHECK(config->encoder_pulses > 0 && 4 * config->encoder_pulses <= 32767, ESP_ERR_INVALID_ARG, NULL, "Invalid encoder pulses.");
return ESP_OK; return ESP_OK;
} }
@@ -117,9 +128,17 @@ static esp_err_t _zh_inclinometer_pcnt_init(const zh_inclinometer_init_config_t
{ {
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 = config->encoder_pulses, .high_limit = 4 * config->encoder_pulses,
.low_limit = -config->encoder_pulses, .low_limit = -4 * config->encoder_pulses,
}; };
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.");
@@ -127,57 +146,52 @@ static esp_err_t _zh_inclinometer_pcnt_init(const zh_inclinometer_init_config_t
.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(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_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, 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(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_level_action(pcnt_channel_a_handle, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_HOLD) == ESP_OK, ESP_FAIL, 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(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_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, 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(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_b_handle, PCNT_CHANNEL_EDGE_ACTION_INCREASE, PCNT_CHANNEL_EDGE_ACTION_HOLD) == ESP_OK, ESP_FAIL, 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(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_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, 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(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_level_action(pcnt_channel_b_handle, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_HOLD) == ESP_OK, ESP_FAIL, 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(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_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, 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(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_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_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_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, 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(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_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_CONT(pcnt_unit_disable(pcnt_unit_handle) == ESP_OK, NULL, "PCNT unit disable 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_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, 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(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_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_CONT(pcnt_unit_disable(pcnt_unit_handle) == ESP_OK, NULL, "PCNT unit disable 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_channel(pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, 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(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.");
if (config->pullup == false)
{
ZH_ERROR_CHECK(gpio_pullup_dis((gpio_num_t)config->a_gpio_number) == ESP_OK, ESP_FAIL, NULL, "GPIO pullup disable fail.");
ZH_ERROR_CHECK(gpio_pullup_dis((gpio_num_t)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;