hiro yamamoto works

マイコンハード、ソフトを作ったりしています。
お家や現場のお困りごと解決に!
内容利用は自己責任でお願いします。

ESP32pcntカウンタをテストしてみた

2021-12-09 17:25:00 | マイコンソフトウェア

ESP32でpcntカウンタでパルスをただ数えるだけ。
16bitの符号付きの高速なパルスカウンタです。
もっと詳しい事を知りたい方は
esp32 pcntで検索するとなにか見つかると思います。

桁数が足らないので工夫しています。
素人の書いたコードなので間違いがあるかも知れません。

#include "driver/pcnt.h"

#define PULSE_INPUT_PIN 32 //パルスの入力ピン
#define PULSE_CTRL_PIN 33 //制御ピン
#define PCNT_H_LIM_VAL 32768 //カウンタの上限32768 16bit Counter 65536
#define PCNT_L_LIM_VAL -32768 //カウンタの下限-32768

int16_t count = 0; //カウント数
unsigned long currentCount = 0;
unsigned long previousCount = 0;
unsigned long addCount = 0;

unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
pcnt_config_t pcnt_config;//設定用の構造体の宣言
pcnt_config.pulse_gpio_num = PULSE_INPUT_PIN;
//pcnt_config.ctrl_gpio_num = PULSE_CTRL_PIN;//制御信号入力GPIO番号
pcnt_config.ctrl_gpio_num = PCNT_PIN_NOT_USED;
pcnt_config.lctrl_mode = PCNT_MODE_REVERSE;//_REVERSE:invert counter mode(increase -> decrease, decrease -> increase)
pcnt_config.hctrl_mode = PCNT_MODE_KEEP;//_KEEP:won’t change counter mode
// PCNT_MODE_DISABLE:Inhibit counter(counter value will not change in this condition)
pcnt_config.channel = PCNT_CHANNEL_0;
pcnt_config.unit = PCNT_UNIT_0;
//pcnt_config.pos_mode = PCNT_COUNT_INC;//positive edge count mode _INC:Increase counter value
pcnt_config.pos_mode = PCNT_COUNT_DEC;//positive edge count mode _INC:Increase counter value
//pcnt_config.neg_mode = PCNT_COUNT_DEC;//negative edge count mode _DEC:Decrease counter value
pcnt_config.neg_mode = PCNT_COUNT_DIS;//negative edge count mode _DEC:Decrease counter value
pcnt_config.counter_h_lim = PCNT_H_LIM_VAL;
pcnt_config.counter_l_lim = PCNT_L_LIM_VAL;

pcnt_unit_config(&pcnt_config); //ユニット初期化
pcnt_counter_pause(PCNT_UNIT_0); //カウンタ一時停止
pcnt_counter_clear(PCNT_UNIT_0); //カウンタ初期化
Serial.begin(115200);
pcnt_counter_resume(PCNT_UNIT_0); //カウント再開
}

void loop() {
pcnt_get_counter_value(PCNT_UNIT_0, &count);

unsigned long currentMillis = millis();

if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;

currentCount = count;
if ( currentCount > previousCount) { //以前値より現在値が大きい時
//16bitカウンタ(-32,768〜+32,768)では1日の生産数の途中でオーバーフローするので、
//一定時間毎にカウント値の差を算出して変数へ加算する
//addCount:カウント値を加算するための変数
addCount += currentCount - previousCount; //現在値-以前値をaddCountへ加算
} else if (currentCount < previousCount) { //カウンタオーバーフローで以前値より現在値が小さい
addCount += currentCount - previousCount - 4294934529; //カウンタオーバーフロー時の
}
Serial.println(addCount); //カウント値加算する変数を表示
//if(count > 100) pcnt_counter_clear(PCNT_UNIT_0);
//if(count < -100) pcnt_counter_clear(PCNT_UNIT_0);
Serial.print("Counter value: ");

Serial.println(count); //
previousCount = currentCount;
//delay(50);
}
}