/*
* ESP32のパルスカウンタ(PCNT)でロータリーエンコーダ(KY-040)を読み取る
* 参考サイト:https://kano-x.jp/blog/1959/
* 参考サイト:https://lang-ship.com/blog/work/esp32-pulse-counter/
* 参考サイト:https://tool-lab.com/arduino-basic-1-15/
* 2024/03/09(土)
*/
#include "driver/pcnt.h"
#define PULSE_PIN_CLK 13 // エンコーダー A相
#define PULSE_PIN_DT 12 // エンコーダー B相
#define PULSE_PIN_SW 19 // リセットスイッチ
int16_t count = 5;
void setup() {
// ピンモード設定
pinMode(PULSE_PIN_CLK, INPUT);
pinMode(PULSE_PIN_DT, INPUT);
pinMode(PULSE_PIN_SW, INPUT);
// シリアルモニタ初期化
Serial.begin(115200);
delay(1000);
pcnt_config_t pcnt_config1 = {}; // 設定用の構造体の宣言
pcnt_config1.pulse_gpio_num = PULSE_PIN_CLK;
pcnt_config1.ctrl_gpio_num = PULSE_PIN_DT;
pcnt_config1.lctrl_mode = PCNT_MODE_KEEP;
pcnt_config1.hctrl_mode = PCNT_MODE_REVERSE;
pcnt_config1.pos_mode = PCNT_COUNT_INC;
pcnt_config1.neg_mode = PCNT_COUNT_DEC;
pcnt_config1.counter_h_lim = 2400;
pcnt_config1.counter_l_lim = -2400;
pcnt_config1.unit = PCNT_UNIT_0;
pcnt_config1.channel = PCNT_CHANNEL_0;
// pcnt_config_t pcnt_config2 = {};
// pcnt_config2.pulse_gpio_num = PULSE_PIN_DT;
// pcnt_config2.ctrl_gpio_num = PULSE_PIN_CLK;
// pcnt_config2.lctrl_mode = PCNT_MODE_REVERSE;
// pcnt_config2.hctrl_mode = PCNT_MODE_KEEP;
// pcnt_config2.pos_mode = PCNT_COUNT_INC;
// pcnt_config2.neg_mode = PCNT_COUNT_DEC;
// pcnt_config2.counter_h_lim = 2400;
// pcnt_config2.counter_l_lim = -2400;
// pcnt_config2.unit = PCNT_UNIT_0;
// pcnt_config2.channel = PCNT_CHANNEL_1;
pcnt_unit_config(&pcnt_config1); //ユニット1初期化
// pcnt_unit_config(&pcnt_config2); //ユニット2初期化
pcnt_counter_pause(PCNT_UNIT_0); //カウンタ一時停止
pcnt_counter_clear(PCNT_UNIT_0); //カウンタ初期化
pcnt_counter_resume(PCNT_UNIT_0); //カウント開始
}
void loop() {
// 0.01秒ごとにカウンタの状態をシリアルモニタに表示
pcnt_get_counter_value(PCNT_UNIT_0, &count);
Serial.print("Counter value: ");
Serial.println(count);
if (digitalRead(PULSE_PIN_SW) == LOW) {
pcnt_counter_clear(PCNT_UNIT_0);
}
delay(1000);
}