Compare commits
4
Commits
ad415b14a4
...
9150b05373
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9150b05373 | ||
|
|
eb6518f207 | ||
|
|
0a9a177289 | ||
|
|
50f3af41e7 |
No files matched your search
@@ -10,18 +10,9 @@
|
|||||||
6. Watch points at ±32767 for overflow detection.
|
6. Watch points at ±32767 for overflow detection.
|
||||||
7. Multiple tachometers supported — each requires its own PCNT unit and timer.
|
7. Multiple tachometers supported — each requires its own PCNT unit and timer.
|
||||||
|
|
||||||
## Note
|
|
||||||
|
|
||||||
Enable the following settings in menuconfig:
|
|
||||||
|
|
||||||
```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,37 +25,38 @@ In the application, add the component:
|
|||||||
#include "zh_tachometer.h"
|
#include "zh_tachometer.h"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Example
|
## Examples
|
||||||
|
|
||||||
|
### Basic Example
|
||||||
|
|
||||||
```c
|
```c
|
||||||
#include "zh_tachometer.h"
|
#include "zh_tachometer.h"
|
||||||
|
|
||||||
static zh_tachometer_handle_t *tachometer_handle = NULL;
|
zh_tachometer_handle_t *tachometer_handle = NULL;
|
||||||
|
|
||||||
void app_main(void)
|
void app_main(void)
|
||||||
{
|
{
|
||||||
esp_log_level_set("zh_tachometer", ESP_LOG_ERROR);
|
esp_log_level_set("zh_tachometer", ESP_LOG_ERROR);
|
||||||
|
|
||||||
zh_tachometer_init_config_t config = ZH_TACHOMETER_INIT_CONFIG_DEFAULT();
|
zh_tachometer_init_config_t config = ZH_TACHOMETER_INIT_CONFIG_DEFAULT();
|
||||||
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;
|
||||||
|
|
||||||
esp_err_t ret = zh_tachometer_init(&config, &tachometer_handle);
|
esp_err_t ret = zh_tachometer_init(&config, &tachometer_handle);
|
||||||
if (ret != ESP_OK) {
|
if (ret != ESP_OK)
|
||||||
ESP_LOG_ERROR("zh_tachometer", "Initialization failed: %s", esp_err_to_name(ret));
|
{
|
||||||
|
printf("Tachometer initialization error\n");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
for (;;)
|
||||||
for (;;) {
|
{
|
||||||
uint16_t rpm = 0;
|
uint16_t value = 0;
|
||||||
ret = zh_tachometer_get(&tachometer_handle, &rpm);
|
ret = zh_tachometer_get(&tachometer_handle, &value);
|
||||||
if (ret == ESP_OK) {
|
if (ret == ESP_OK)
|
||||||
printf("Tachometer value is %d rpm.\n", rpm);
|
{
|
||||||
|
printf("Tachometer value is %u rpm.\n", value);
|
||||||
}
|
}
|
||||||
vTaskDelay(100 / portTICK_PERIOD_MS);
|
vTaskDelay(100 / portTICK_PERIOD_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
zh_tachometer_deinit(&tachometer_handle);
|
zh_tachometer_deinit(&tachometer_handle);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -62,8 +62,8 @@ extern "C"
|
|||||||
*/
|
*/
|
||||||
typedef struct
|
typedef struct
|
||||||
{
|
{
|
||||||
uint8_t a_gpio_number; /*!< Encoder A phase GPIO number */
|
gpio_num_t a_gpio_number; /*!< Encoder A phase GPIO number */
|
||||||
uint8_t b_gpio_number; /*!< Encoder B phase GPIO number */
|
gpio_num_t b_gpio_number; /*!< Encoder B phase GPIO number */
|
||||||
bool pullup; /*!< Enable or disable GPIO pull-up resistors */
|
bool pullup; /*!< Enable or disable GPIO pull-up resistors */
|
||||||
uint16_t encoder_pulses; /*!< Number of pulses per one full rotation */
|
uint16_t encoder_pulses; /*!< Number of pulses per one full rotation */
|
||||||
} zh_tachometer_init_config_t;
|
} zh_tachometer_init_config_t;
|
||||||
@@ -78,7 +78,7 @@ extern "C"
|
|||||||
* @param[out] handle Pointer to receive the created tachometer handle (must be NULL)
|
* @param[out] handle Pointer to receive the created tachometer handle (must be NULL)
|
||||||
*
|
*
|
||||||
* @return ESP_OK on success
|
* @return ESP_OK on success
|
||||||
* @return ESP_ERR_INVALID_ARG if `config` or `handle` is NULL, or `encoder_pulses` is zero
|
* @return ESP_ERR_INVALID_ARG if `config` or `handle` is NULL, `encoder_pulses` is zero, or GPIO numbers are invalid or identical
|
||||||
* @return ESP_ERR_INVALID_STATE if the handle is already initialized
|
* @return ESP_ERR_INVALID_STATE if the handle is already initialized
|
||||||
* @return ESP_ERR_NO_MEM if memory allocation fails
|
* @return ESP_ERR_NO_MEM if memory allocation fails
|
||||||
* @return ESP_FAIL if PCNT initialization or configuration failed
|
* @return ESP_FAIL if PCNT initialization or configuration failed
|
||||||
@@ -110,11 +110,11 @@ extern "C"
|
|||||||
* The value represents absolute RPM (direction is discarded); negative
|
* The value represents absolute RPM (direction is discarded); negative
|
||||||
* rotation is reported as a positive value.
|
* rotation is reported as a positive value.
|
||||||
*
|
*
|
||||||
* @param[in] handle Pointer to the tachometer handle (must not be NULL)
|
* @param[in] handle Pointer to the tachometer handle (must not be NULL, and *handle must not be NULL)
|
||||||
* @param[out] value Pointer to receive the RPM value (must not be NULL)
|
* @param[out] value Pointer to receive the RPM value (must not be NULL)
|
||||||
*
|
*
|
||||||
* @return ESP_OK on success
|
* @return ESP_OK on success
|
||||||
* @return ESP_ERR_INVALID_ARG if `handle` or `value` is NULL
|
* @return ESP_ERR_INVALID_ARG if `handle`, `*handle`, or `value` is NULL
|
||||||
*
|
*
|
||||||
* @note This function is non-blocking and returns the most recent value
|
* @note This function is non-blocking and returns the most recent value
|
||||||
* without accessing the PCNT peripheral directly.
|
* without accessing the PCNT peripheral directly.
|
||||||
|
|||||||
+241
@@ -0,0 +1,241 @@
|
|||||||
|
# Описание компонента zh_tachometer
|
||||||
|
|
||||||
|
**zh_tachometer** — драйвер для ESP-IDF, измеряющий скорость вращения на основе квадратурного энкодера. Компонент использует периферийный модуль PCNT ESP32 в режиме квадратурного декодера для подсчёта импульсов энкодера и ESP-Timer, работающего с частотой 100 Гц, для периодического считывания накопленного значения и вычисления оборотов в минуту (RPM). Результатом является неблокирующий, совместимый с RTOS интерфейс, подходящий для мониторинга скорости двигателей.
|
||||||
|
|
||||||
|
Компонент поддерживает одновременную работу нескольких тахометров, каждый из которых использует собственный модуль PCNT и таймер.
|
||||||
|
|
||||||
|
## Основные возможности
|
||||||
|
|
||||||
|
- **Поддержка квадратурного энкодера** — подсчёт импульсов по двум фазам (A/B) через периферийный модуль PCNT в режиме квадратурного декодера.
|
||||||
|
- **Автоматический расчёт RPM** — вычисление оборотов в минуту на основе настраиваемого количества импульсов на полный оборот энкодера.
|
||||||
|
- **Периодическое дискретное считывание** — ESP-Timer запускается с частотой 100 Гц (интервал 10 мс) для чтения накопленного счёта PCNT и перевода в RPM.
|
||||||
|
- **Настраиваемые подтягивающие резисторы GPIO** — возможность включения или отключения внутренних подтягивающих резисторов для линий A и B энкодера.
|
||||||
|
- **Фильтр глитчей PCNT** — подавление ложных переходов с настройкой 1000 нс через встроенный фильтр PCNT.
|
||||||
|
- **Поддержка нескольких тахометров** — каждый тахометр использует отдельный модуль PCNT и таймер ESP-Timer.
|
||||||
|
|
||||||
|
## Внутреннее устройство
|
||||||
|
|
||||||
|
### Структура `zh_tachometer_handle_t`
|
||||||
|
|
||||||
|
Внутренняя структура тахометра содержит ссылки на все используемые периферийные модули, последнее вычисленное значение RPM и конфигурацию энкодера.
|
||||||
|
|
||||||
|
| Поле | Тип | Описание |
|
||||||
|
| ------ | ----- | ---------- |
|
||||||
|
| `pcnt_unit_handle` | `pcnt_unit_handle_t` | Управляющий объект модуля PCNT для квадратурного декодирования |
|
||||||
|
| `pcnt_channel_a_handle` | `pcnt_channel_handle_t` | Управляющий объект канала PCNT A (детектор фронтов) |
|
||||||
|
| `pcnt_channel_b_handle` | `pcnt_channel_handle_t` | Управляющий объект канала PCNT B (детектор фронтов) |
|
||||||
|
| `esp_timer_handle` | `esp_timer_handle_t` | Управляющий объект ESP-Timer для дискретного считывания RPM (100 Гц) |
|
||||||
|
| `value` | `volatile uint16_t` | Последнее вычисленное значение RPM (абсолютное, направление отбрасывается) |
|
||||||
|
| `encoder_pulses` | `uint16_t` | Количество импульсов на один полный оборот энкодера |
|
||||||
|
|
||||||
|
Структура является непрозрачной для вызывающего кода — доступ осуществляется только через публичные функции API.
|
||||||
|
|
||||||
|
### Структура конфигурации `zh_tachometer_init_config_t`
|
||||||
|
|
||||||
|
Передаётся в функцию `zh_tachometer_init()` для настройки пин GPIO, подтягивающих резисторов и коэффициента импульсов на оборот.
|
||||||
|
|
||||||
|
| Поле | Тип | Описание |
|
||||||
|
| ------ | ----- | ---------- |
|
||||||
|
| `a_gpio_number` | `gpio_num_t` | Номер GPIO линии фазы A энкодера |
|
||||||
|
| `b_gpio_number` | `gpio_num_t` | Номер GPIO линии фазы B энкодера |
|
||||||
|
| `pullup` | `bool` | Включение или отключение подтягивающих резисторов GPIO |
|
||||||
|
| `encoder_pulses` | `uint16_t` | Количество импульсов на один полный оборот энкодера |
|
||||||
|
|
||||||
|
По умолчанию `ZH_TACHOMETER_INIT_CONFIG_DEFAULT()` устанавливает GPIO в `GPIO_NUM_MAX`, подтягивание в `true`, а импульсы в `0`.
|
||||||
|
|
||||||
|
### Управление памятью
|
||||||
|
|
||||||
|
Память для структуры `zh_tachometer_handle_t` выделяется через `heap_caps_calloc()` с флагом `MALLOC_CAP_8BIT` при вызове `zh_tachometer_init()` и освобождается через `heap_caps_free()` при вызове `zh_tachometer_deinit()`. Управляющие объекты PCNT и ESP-Timer освобождаются через соответствующие функции ESP-IDF API (`pcnt_del_unit()`, `pcnt_del_channel()`, `esp_timer_delete()`).
|
||||||
|
|
||||||
|
## API (интерфейс)
|
||||||
|
|
||||||
|
### Инициализация и освобождение
|
||||||
|
|
||||||
|
| Функция | Описание |
|
||||||
|
|---------|----------|
|
||||||
|
| `zh_tachometer_init()` | Создаёт объект тахометра, настраивает ESP-Timer (100 Гц) и периферийный модуль PCNT в режиме квадратурного декодера с фильтром глитчей |
|
||||||
|
| `zh_tachometer_deinit()` | Останавливает модуль PCNT, удаляет каналы и точки наблюдения, удаляет ESP-Timer и освобождает память объекта |
|
||||||
|
|
||||||
|
### Получение данных
|
||||||
|
|
||||||
|
| Функция | Описание |
|
||||||
|
|---------|----------|
|
||||||
|
| `zh_tachometer_get()` | Возвращает последнее вычисленное значение RPM. Значение является абсолютным (направление вращения отбрасывается), функция не блокирует выполнение и не обращается к периферийному модулю PCNT напрямую |
|
||||||
|
|
||||||
|
## Потокобезопасность
|
||||||
|
|
||||||
|
1. **Общий доступ к данным** — последнее значение RPM хранится в поле `value` с квалификатором `volatile`, что обеспечивает корректное чтение из любого контекса. Функция `zh_tachometer_get()` просто копирует значение из структуры, не требуя блокировок.
|
||||||
|
|
||||||
|
2. **Контекст таймера** — обратный вызов ESP-Timer выполняется в контексте задачи `esp_timer service task` (метод диспетчеризации `ESP_TIMER_TASK` по умолчанию), а не из прерывания. Блокирующие или длительные операции в обратном вызове следует избегать.
|
||||||
|
|
||||||
|
## Алгоритмы
|
||||||
|
|
||||||
|
### Формула расчёта RPM
|
||||||
|
|
||||||
|
Обратный вызов ESP-Timer выполняется каждые 10 мс (100 Гц). За этот интервал считывается накопленное значение PCNT, обнуляется и преобразуется в RPM по формуле:
|
||||||
|
|
||||||
|
```
|
||||||
|
RPM = (count * 100.0 / (4.0 * pulses_per_rev)) * 60.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Где:
|
||||||
|
|
||||||
|
- `count` — накопленное значение PCNT за 10 мс.
|
||||||
|
- `100.0` — масштабный коэффициент для перевода 10 мс в секунду (1000 мс / 10 мс).
|
||||||
|
- `4.0` — коэффициент квадратурного кодирования: 4 фронта за один цикл (фазы A и B имеют сдвиг 90°).
|
||||||
|
- `pulses_per_rev` — количество импульсов на полный оборот энкодера, задаётся в конфигурации.
|
||||||
|
- `60.0` — перевод оборотов в секунду в обороты в минуту.
|
||||||
|
|
||||||
|
Результат берётся по модулю (`fabsf()`) — направление вращения игнорируется, возвращается абсолютное значение RPM.
|
||||||
|
|
||||||
|
### Конфигурация PCNT
|
||||||
|
|
||||||
|
Модуль PCNT настраивается в режиме квадратурного декодера:
|
||||||
|
|
||||||
|
- Канал A: фронт по фазе A вызывает увеличение (`INCREASE`) или уменьшение (`DECREASE`) счётчика в зависимости от уровня фазы B.
|
||||||
|
- Канал A: уровень фазы A удерживает счёт (`KEEP`) или инвертирует направление (`INVERSE`).
|
||||||
|
- Канал B: фронт по фазе B вызывает увеличение или уменьшение счётчика в зависимости от уровня фазы A (обратное каналу A).
|
||||||
|
- Канал B: уровень фазы B удерживает или инвертирует направление (обратное каналу A).
|
||||||
|
- Фильтр глитчей: 1000 нс.
|
||||||
|
- Точки наблюдения: ±32767 для обнаружения переполнения.
|
||||||
|
- Накопление: включено (`accum_count = true`).
|
||||||
|
|
||||||
|
### Процесс деинициализации
|
||||||
|
|
||||||
|
При вызове `zh_tachometer_deinit()` ресурсы освобождаются в строгом порядке:
|
||||||
|
|
||||||
|
1. Остановка ESP-Timer (`esp_timer_stop`).
|
||||||
|
2. Удаление ESP-Timer (`esp_timer_delete`).
|
||||||
|
3. Остановка PCNT (`pcnt_unit_stop`).
|
||||||
|
4. Отключение PCNT (`pcnt_unit_disable`).
|
||||||
|
5. Удаление точек наблюдения: +32767, затем -32767.
|
||||||
|
6. Удаление каналов A и B (`pcnt_del_channel`).
|
||||||
|
7. Удаление модуля PCNT (`pcnt_del_unit`).
|
||||||
|
8. Освобождение памяти объекта (`heap_caps_free`).
|
||||||
|
9. Обнуление указателя на объект.
|
||||||
|
|
||||||
|
Все шаги используют `ZH_ERROR_CHECK_CONT` — ошибка логируется, но процесс деинициализации продолжается до полного освобождения ресурсов.
|
||||||
|
|
||||||
|
## Примеры использования
|
||||||
|
|
||||||
|
### Базовое использование
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "zh_tachometer.h"
|
||||||
|
|
||||||
|
zh_tachometer_handle_t *tachometer_handle = NULL;
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
esp_log_level_set("zh_tachometer", ESP_LOG_ERROR);
|
||||||
|
|
||||||
|
zh_tachometer_init_config_t config = ZH_TACHOMETER_INIT_CONFIG_DEFAULT();
|
||||||
|
config.a_gpio_number = GPIO_NUM_26;
|
||||||
|
config.b_gpio_number = GPIO_NUM_27;
|
||||||
|
config.encoder_pulses = 3600;
|
||||||
|
|
||||||
|
esp_err_t ret = zh_tachometer_init(&config, &tachometer_handle);
|
||||||
|
if (ret != ESP_OK)
|
||||||
|
{
|
||||||
|
printf("Tachometer initialization error: %s\n", esp_err_to_name(ret));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (;;)
|
||||||
|
{
|
||||||
|
uint16_t value = 0;
|
||||||
|
ret = zh_tachometer_get(&tachometer_handle, &value);
|
||||||
|
if (ret == ESP_OK)
|
||||||
|
{
|
||||||
|
printf("Current RPM: %u\n", value);
|
||||||
|
}
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(100));
|
||||||
|
}
|
||||||
|
|
||||||
|
zh_tachometer_deinit(&tachometer_handle);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Настройка с отключёнными подтягивающими резисторами
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "zh_tachometer.h"
|
||||||
|
|
||||||
|
zh_tachometer_handle_t *tachometer_handle = NULL;
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
esp_log_level_set("zh_tachometer", ESP_LOG_ERROR);
|
||||||
|
|
||||||
|
zh_tachometer_init_config_t config = ZH_TACHOMETER_INIT_CONFIG_DEFAULT();
|
||||||
|
config.a_gpio_number = GPIO_NUM_12;
|
||||||
|
config.b_gpio_number = GPIO_NUM_13;
|
||||||
|
config.pullup = false;
|
||||||
|
config.encoder_pulses = 1800;
|
||||||
|
|
||||||
|
esp_err_t ret = zh_tachometer_init(&config, &tachometer_handle);
|
||||||
|
if (ret != ESP_OK)
|
||||||
|
{
|
||||||
|
printf("Tachometer initialization error: %s\n", esp_err_to_name(ret));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t rpm_value = 0;
|
||||||
|
ret = zh_tachometer_get(&tachometer_handle, &rpm_value);
|
||||||
|
if (ret == ESP_OK)
|
||||||
|
{
|
||||||
|
printf("RPM value: %u\n", rpm_value);
|
||||||
|
}
|
||||||
|
|
||||||
|
zh_tachometer_deinit(&tachometer_handle);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Логирование
|
||||||
|
|
||||||
|
Компонент использует ESP-IDF логирование с тегом `"zh_tachometer"`.
|
||||||
|
|
||||||
|
```c
|
||||||
|
esp_log_level_set("zh_tachometer", ESP_LOG_ERROR);
|
||||||
|
```
|
||||||
|
|
||||||
|
Доступные уровни: `ESP_LOG_ERROR`, `ESP_LOG_INFO`. Макрос `ZH_LOGI` выводит информационные сообщения о начале и завершении операций. Макрос `ZH_LOGE` выводит сообщения об ошибках с указанием файла, строки и имени кода ошибки.
|
||||||
|
|
||||||
|
## Ошибки
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
| ----- | ---------- |
|
||||||
|
| `ESP_OK` | Успешное выполнение |
|
||||||
|
| `ESP_ERR_INVALID_ARG` | Неверный аргумент: `config` или `handle` равен NULL, `encoder_pulses` равен нулю, номера GPIO недействительны или совпадают, `*handle` или `value` равен NULL |
|
||||||
|
| `ESP_ERR_INVALID_STATE` | Объект тахометра уже инициализирован (`*handle` не равен NULL) |
|
||||||
|
| `ESP_ERR_NO_MEM` | Не удалось выделить память для объекта тахометра |
|
||||||
|
| `ESP_FAIL` | Ошибка инициализации или конфигурации PCNT, ошибка создания или запуска ESP-Timer |
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
1. **Переполнение PCNT счётчика** — модуль PCNT использует точки наблюдения на ±32767. При высоких значениях RPM накопленный счётчик может переполниться. Необходимо убедиться, что комбинация количества импульсов на оборот и ожидаемого диапазона RPM остаётся в безопасных пределах.
|
||||||
|
|
||||||
|
2. **Абсолютное значение RPM** — направление вращения игнорируется. Компонент возвращает только модуль скорости, без информации о направлении.
|
||||||
|
|
||||||
|
3. **16-битное значение RPM** — возвращаемое значение имеет тип `uint16_t`, максимальное значение — 65535. При очень высоких скоростях вращения значение может не поместиться.
|
||||||
|
|
||||||
|
4. **Один GPIO на фазу** — каждая фаза энкодера (A и B) должна быть назначена на отдельный GPIO. Назначение одинакового номера GPIO на обе фазы вернёт ошибку `ESP_ERR_INVALID_ARG`.
|
||||||
|
|
||||||
|
## Требования для сборки
|
||||||
|
|
||||||
|
- ESP-IDF (фреймворк для ESP32)
|
||||||
|
- FreeRTOS (входит в состав ESP-IDF)
|
||||||
|
- Компонент ESP-IDF `pulse_cnt` (драйвер PCNT)
|
||||||
|
- Компонент ESP-IDF `esp_timer` (ESP-Timer)
|
||||||
|
- Компонент ESP-IDF `driver` (GPIO driver)
|
||||||
|
|
||||||
|
## Установка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ваш_проект/components
|
||||||
|
git clone https://github.com/aZholtikov/zh_tachometer
|
||||||
|
```
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "zh_tachometer.h"
|
||||||
|
```
|
||||||
+95
-78
@@ -1,6 +1,6 @@
|
|||||||
#include "zh_tachometer.h"
|
#include "zh_tachometer.h"
|
||||||
|
|
||||||
#define TAG "zh_tachometer"
|
static const char *TAG = "zh_tachometer";
|
||||||
|
|
||||||
#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__)
|
||||||
@@ -21,6 +21,13 @@
|
|||||||
return; \
|
return; \
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#define ZH_ERROR_CHECK_CONT(cond, cleanup, msg, ...) \
|
||||||
|
if (!(cond)) \
|
||||||
|
{ \
|
||||||
|
ZH_LOGE(msg, ESP_FAIL, ##__VA_ARGS__); \
|
||||||
|
cleanup; \
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Internal handle structure for the tachometer driver.
|
* @brief Internal handle structure for the tachometer driver.
|
||||||
*
|
*
|
||||||
@@ -30,8 +37,10 @@
|
|||||||
*
|
*
|
||||||
* @note This structure is opaque to callers and must only be accessed
|
* @note This structure is opaque to callers and must only be accessed
|
||||||
* through the public API functions.
|
* through the public API functions.
|
||||||
* @warning The timer callback runs from ISR context and must not call
|
* @warning The timer callback runs from the esp_timer service task context
|
||||||
* blocking or long-running operations.
|
* (default ESP_TIMER_TASK dispatch method), not from an ISR. Blocking
|
||||||
|
* or long-running operations in the callback will delay other esp_timer
|
||||||
|
* callbacks and must be avoided.
|
||||||
*/
|
*/
|
||||||
struct _zh_tachometer_handle_t
|
struct _zh_tachometer_handle_t
|
||||||
{
|
{
|
||||||
@@ -39,7 +48,7 @@ struct _zh_tachometer_handle_t
|
|||||||
pcnt_channel_handle_t pcnt_channel_a_handle; /*!< PCNT channel A handle (edge detector) */
|
pcnt_channel_handle_t pcnt_channel_a_handle; /*!< PCNT channel A handle (edge detector) */
|
||||||
pcnt_channel_handle_t pcnt_channel_b_handle; /*!< PCNT channel B handle (edge detector) */
|
pcnt_channel_handle_t pcnt_channel_b_handle; /*!< PCNT channel B handle (edge detector) */
|
||||||
esp_timer_handle_t esp_timer_handle; /*!< ESP-Timer handle for 100 Hz RPM sampling */
|
esp_timer_handle_t esp_timer_handle; /*!< ESP-Timer handle for 100 Hz RPM sampling */
|
||||||
uint16_t value; /*!< Last computed RPM value (absolute) */
|
volatile uint16_t value; /*!< Last computed RPM value (absolute) */
|
||||||
uint16_t encoder_pulses; /*!< Pulses per one full rotation */
|
uint16_t encoder_pulses; /*!< Pulses per one full rotation */
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -61,7 +70,7 @@ static esp_err_t _zh_tachometer_validate_config(const zh_tachometer_init_config_
|
|||||||
* Configures the PCNT unit with accumulation mode, glitch filter (1000 ns),
|
* Configures the PCNT unit with accumulation mode, glitch filter (1000 ns),
|
||||||
* two channels for encoder phases A and B, edge/level actions for direction
|
* two channels for encoder phases A and B, edge/level actions for direction
|
||||||
* counting, and watch points at ±32767. Starts the unit and clears the
|
* counting, and watch points at ±32767. Starts the unit and clears the
|
||||||
* counter. Optionally disables GPIO pull-ups if configured.
|
* counter. Configures GPIO pull-ups according to the `pullup` setting.
|
||||||
*
|
*
|
||||||
* @param config Pointer to the initialization configuration
|
* @param config Pointer to the initialization configuration
|
||||||
* @param handle Pointer to the initialized tachometer handle
|
* @param handle Pointer to the initialized tachometer handle
|
||||||
@@ -88,11 +97,13 @@ static esp_err_t _zh_tachometer_timer_init(zh_tachometer_handle_t *handle);
|
|||||||
/**
|
/**
|
||||||
* @brief ESP-Timer alarm callback for RPM sampling.
|
* @brief ESP-Timer alarm callback for RPM sampling.
|
||||||
*
|
*
|
||||||
* Executed every 10 ms from ISR context. Reads the accumulated PCNT count,
|
* Executed every 10 ms from the esp_timer service task context (default
|
||||||
|
* ESP_TIMER_TASK dispatch method). Reads the accumulated PCNT count,
|
||||||
* clears it, and converts it to RPM using the formula:
|
* clears it, and converts it to RPM using the formula:
|
||||||
*
|
*
|
||||||
* RPM = (count * 100.0 / pulses_per_rev) * 60
|
* RPM = (count * 100.0 / (4 * pulses_per_rev)) * 60
|
||||||
*
|
*
|
||||||
|
* The factor of 4 accounts for quadrature encoding (4 edges per cycle).
|
||||||
* The result is stored as an absolute value (direction discarded).
|
* The result is stored as an absolute value (direction discarded).
|
||||||
*
|
*
|
||||||
* @param arg Pointer to the tachometer handle
|
* @param arg Pointer to the tachometer handle
|
||||||
@@ -108,11 +119,11 @@ esp_err_t zh_tachometer_init(const zh_tachometer_init_config_t *config, zh_tacho
|
|||||||
*handle = heap_caps_calloc(1, sizeof(zh_tachometer_handle_t), MALLOC_CAP_8BIT);
|
*handle = heap_caps_calloc(1, sizeof(zh_tachometer_handle_t), MALLOC_CAP_8BIT);
|
||||||
ZH_ERROR_CHECK(*handle != NULL, ESP_ERR_NO_MEM, NULL, "Tachometer initialization failed. Failed to allocate tachometer handle.");
|
ZH_ERROR_CHECK(*handle != NULL, ESP_ERR_NO_MEM, NULL, "Tachometer initialization failed. Failed to allocate tachometer handle.");
|
||||||
ZH_ERROR_CHECK(_zh_tachometer_timer_init(*handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "Tachometer initialization failed. Timer initialization failed.");
|
ZH_ERROR_CHECK(_zh_tachometer_timer_init(*handle) == ESP_OK, ESP_FAIL, heap_caps_free(*handle); *handle = NULL, "Tachometer initialization failed. Timer initialization failed.");
|
||||||
ZH_ERROR_CHECK(_zh_tachometer_pcnt_init(config, *handle) == ESP_OK, ESP_FAIL,
|
|
||||||
{ZH_ERROR_CHECK(esp_timer_stop((*handle)->esp_timer_handle) == ESP_OK, ESP_FAIL, NULL, "Timer stop fail.")};
|
|
||||||
{ZH_ERROR_CHECK(esp_timer_delete((*handle)->esp_timer_handle) == ESP_OK, ESP_FAIL, NULL, "Timer delete fail.")};
|
|
||||||
heap_caps_free(*handle); *handle = NULL, "Tachometer initialization failed. PCNT initialization failed.");
|
|
||||||
(*handle)->encoder_pulses = config->encoder_pulses;
|
(*handle)->encoder_pulses = config->encoder_pulses;
|
||||||
|
ZH_ERROR_CHECK(_zh_tachometer_pcnt_init(config, *handle) == ESP_OK, ESP_FAIL,
|
||||||
|
{ZH_ERROR_CHECK_CONT(esp_timer_stop((*handle)->esp_timer_handle) == ESP_OK, NULL, "Timer stop fail.")};
|
||||||
|
{ZH_ERROR_CHECK_CONT(esp_timer_delete((*handle)->esp_timer_handle) == ESP_OK, NULL, "Timer delete fail.")};
|
||||||
|
heap_caps_free(*handle); *handle = NULL, "Tachometer initialization failed. PCNT initialization failed.");
|
||||||
ZH_LOGI("Tachometer initialization completed successfully.");
|
ZH_LOGI("Tachometer initialization completed successfully.");
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
@@ -121,15 +132,15 @@ esp_err_t zh_tachometer_deinit(zh_tachometer_handle_t **handle)
|
|||||||
{
|
{
|
||||||
ZH_LOGI("Tachometer deinitialization started.");
|
ZH_LOGI("Tachometer deinitialization started.");
|
||||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Tachometer deinitialization failed. Invalid argument.");
|
ZH_ERROR_CHECK(handle != NULL && *handle != NULL, ESP_ERR_INVALID_ARG, NULL, "Tachometer deinitialization failed. Invalid argument.");
|
||||||
ZH_ERROR_CHECK(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. PCNT unit stop fail.");
|
ZH_ERROR_CHECK_CONT(esp_timer_stop((*handle)->esp_timer_handle) == ESP_OK, NULL, "Tachometer deinitialization failed. Timer stop fail.");
|
||||||
ZH_ERROR_CHECK(pcnt_unit_disable((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. PCNT unit disable fail.");
|
ZH_ERROR_CHECK_CONT(esp_timer_delete((*handle)->esp_timer_handle) == ESP_OK, NULL, "Tachometer deinitialization failed. Timer delete fail.");
|
||||||
ZH_ERROR_CHECK(pcnt_unit_remove_watch_point((*handle)->pcnt_unit_handle, 32767) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. PCNT unit remove watch point fail.");
|
ZH_ERROR_CHECK_CONT(pcnt_unit_stop((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Tachometer deinitialization failed. PCNT unit stop fail.");
|
||||||
ZH_ERROR_CHECK(pcnt_unit_remove_watch_point((*handle)->pcnt_unit_handle, -32767) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. PCNT unit remove watch point fail.");
|
ZH_ERROR_CHECK_CONT(pcnt_unit_disable((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Tachometer deinitialization failed. PCNT unit disable fail.");
|
||||||
ZH_ERROR_CHECK(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. PCNT delete channel fail.");
|
ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point((*handle)->pcnt_unit_handle, 32767) == ESP_OK, NULL, "Tachometer deinitialization failed. PCNT unit remove watch point fail.");
|
||||||
ZH_ERROR_CHECK(pcnt_del_channel((*handle)->pcnt_channel_b_handle) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. PCNT delete channel fail.");
|
ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point((*handle)->pcnt_unit_handle, -32767) == ESP_OK, NULL, "Tachometer deinitialization failed. PCNT unit remove watch point fail.");
|
||||||
ZH_ERROR_CHECK(pcnt_del_unit((*handle)->pcnt_unit_handle) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. PCNT delete unit fail.");
|
ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_a_handle) == ESP_OK, NULL, "Tachometer deinitialization failed. PCNT delete channel fail.");
|
||||||
ZH_ERROR_CHECK(esp_timer_stop((*handle)->esp_timer_handle) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. Timer stop fail.");
|
ZH_ERROR_CHECK_CONT(pcnt_del_channel((*handle)->pcnt_channel_b_handle) == ESP_OK, NULL, "Tachometer deinitialization failed. PCNT delete channel fail.");
|
||||||
ZH_ERROR_CHECK(esp_timer_delete((*handle)->esp_timer_handle) == ESP_OK, ESP_FAIL, NULL, "Tachometer deinitialization failed. Timer delete fail.");
|
ZH_ERROR_CHECK_CONT(pcnt_del_unit((*handle)->pcnt_unit_handle) == ESP_OK, NULL, "Tachometer deinitialization failed. PCNT delete unit fail.");
|
||||||
heap_caps_free(*handle);
|
heap_caps_free(*handle);
|
||||||
*handle = NULL;
|
*handle = NULL;
|
||||||
ZH_LOGI("Tachometer deinitialization completed successfully.");
|
ZH_LOGI("Tachometer deinitialization completed successfully.");
|
||||||
@@ -138,10 +149,10 @@ esp_err_t zh_tachometer_deinit(zh_tachometer_handle_t **handle)
|
|||||||
|
|
||||||
esp_err_t zh_tachometer_get(zh_tachometer_handle_t **handle, uint16_t *value)
|
esp_err_t zh_tachometer_get(zh_tachometer_handle_t **handle, uint16_t *value)
|
||||||
{
|
{
|
||||||
ZH_LOGI("Tachometer get position started.");
|
ZH_LOGI("Tachometer get RPM started.");
|
||||||
ZH_ERROR_CHECK(handle != NULL && *handle != NULL && value != NULL, ESP_ERR_INVALID_ARG, NULL, "Tachometer get position failed. Invalid argument.");
|
ZH_ERROR_CHECK(handle != NULL && *handle != NULL && value != NULL, ESP_ERR_INVALID_ARG, NULL, "Tachometer get RPM failed. Invalid argument.");
|
||||||
*value = (*handle)->value;
|
*value = (*handle)->value;
|
||||||
ZH_LOGI("Tachometer get position completed successfully.");
|
ZH_LOGI("Tachometer get RPM completed successfully.");
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,8 +164,16 @@ static esp_err_t _zh_tachometer_validate_config(const zh_tachometer_init_config_
|
|||||||
|
|
||||||
static esp_err_t _zh_tachometer_pcnt_init(const zh_tachometer_init_config_t *config, zh_tachometer_handle_t *handle)
|
static esp_err_t _zh_tachometer_pcnt_init(const zh_tachometer_init_config_t *config, zh_tachometer_handle_t *handle)
|
||||||
{
|
{
|
||||||
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 = 32767,
|
.high_limit = 32767,
|
||||||
.low_limit = -32767,
|
.low_limit = -32767,
|
||||||
@@ -166,72 +185,67 @@ static esp_err_t _zh_tachometer_pcnt_init(const zh_tachometer_init_config_t *con
|
|||||||
.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_add_watch_point(pcnt_unit_handle, 32767) == ESP_OK, ESP_FAIL,
|
ZH_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit_handle, 32767) == 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_add_watch_point(pcnt_unit_handle, -32767) == ESP_OK, ESP_FAIL,
|
ZH_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit_handle, -32767) == ESP_OK, ESP_FAIL,
|
||||||
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, 32767) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
|
{ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point(pcnt_unit_handle, 32767) == ESP_OK, 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_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_unit_remove_watch_point(pcnt_unit_handle, 32767) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
|
{ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point(pcnt_unit_handle, 32767) == ESP_OK, NULL, "PCNT unit remove watch point fail.")};
|
||||||
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, -32767) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
|
{ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point(pcnt_unit_handle, -32767) == ESP_OK, 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_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_unit_remove_watch_point(pcnt_unit_handle, 32767) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
|
{ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point(pcnt_unit_handle, 32767) == ESP_OK, NULL, "PCNT unit remove watch point fail.")};
|
||||||
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, -32767) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
|
{ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point(pcnt_unit_handle, -32767) == ESP_OK, 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_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_unit_remove_watch_point(pcnt_unit_handle, 32767) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
|
{ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point(pcnt_unit_handle, 32767) == ESP_OK, NULL, "PCNT unit remove watch point fail.")};
|
||||||
{ZH_ERROR_CHECK(pcnt_unit_remove_watch_point(pcnt_unit_handle, -32767) == ESP_OK, ESP_FAIL, NULL, "PCNT unit remove watch point fail.")};
|
{ZH_ERROR_CHECK_CONT(pcnt_unit_remove_watch_point(pcnt_unit_handle, -32767) == ESP_OK, 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_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;
|
||||||
@@ -246,16 +260,19 @@ static esp_err_t _zh_tachometer_timer_init(zh_tachometer_handle_t *handle)
|
|||||||
};
|
};
|
||||||
ZH_ERROR_CHECK(esp_timer_create(&timer_args, &handle->esp_timer_handle) == ESP_OK, ESP_FAIL, NULL, "Timer initialization failed.");
|
ZH_ERROR_CHECK(esp_timer_create(&timer_args, &handle->esp_timer_handle) == ESP_OK, ESP_FAIL, NULL, "Timer initialization failed.");
|
||||||
ZH_ERROR_CHECK(esp_timer_start_periodic(handle->esp_timer_handle, 10000) == ESP_OK, ESP_FAIL,
|
ZH_ERROR_CHECK(esp_timer_start_periodic(handle->esp_timer_handle, 10000) == ESP_OK, ESP_FAIL,
|
||||||
{ZH_ERROR_CHECK(esp_timer_delete(handle->esp_timer_handle) == ESP_OK, ESP_FAIL, NULL, "Timer delete fail.")}, "Timer initialization failed.");
|
{ZH_ERROR_CHECK_CONT(esp_timer_delete(handle->esp_timer_handle) == ESP_OK, NULL, "Timer delete fail.")}, "Timer initialization failed.");
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void IRAM_ATTR _zh_tachometer_timer_on_alarm_cb(void *arg)
|
static void _zh_tachometer_timer_on_alarm_cb(void *arg)
|
||||||
{
|
{
|
||||||
zh_tachometer_handle_t *handle = (zh_tachometer_handle_t *)arg;
|
zh_tachometer_handle_t *handle = (zh_tachometer_handle_t *)arg;
|
||||||
int pcnt_count = 0;
|
int pcnt_count = 0;
|
||||||
|
if (handle->pcnt_unit_handle != NULL)
|
||||||
|
{
|
||||||
ZH_ERROR_CHECK_VOID(pcnt_unit_get_count(handle->pcnt_unit_handle, &pcnt_count) == ESP_OK, NULL, "PCNT internal error.");
|
ZH_ERROR_CHECK_VOID(pcnt_unit_get_count(handle->pcnt_unit_handle, &pcnt_count) == ESP_OK, NULL, "PCNT internal error.");
|
||||||
ZH_ERROR_CHECK_VOID(pcnt_unit_clear_count(handle->pcnt_unit_handle) == ESP_OK, NULL, "PCNT internal error.");
|
ZH_ERROR_CHECK_VOID(pcnt_unit_clear_count(handle->pcnt_unit_handle) == ESP_OK, NULL, "PCNT internal error.");
|
||||||
float value_temp = ((pcnt_count * 100.0) / handle->encoder_pulses) * 60;
|
float value_temp = (pcnt_count * 100.0) / (4.0 * handle->encoder_pulses) * 60.0;
|
||||||
handle->value = (uint16_t)fabs(value_temp);
|
handle->value = (uint16_t)fabsf(value_temp);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user