ESP32マイコンを使いインプットキャプチャ機能を使ってみました。
ソースコード
#include "driver/mcpwm.h"
void setup() {
Serial.begin(115200);
delay(500);
mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM_CAP_0, 37);
mcpwm_capture_enable(MCPWM_UNIT_0, MCPWM_SELECT_CAP0, MCPWM_POS_EDGE, 0);
}
void loop() {
static unsigned int old = 0;
unsigned int number1 = mcpwm_capture_signal_get_value(MCPWM_UNIT_0,MCPWM_SELECT_CAP0);
if(old != number1) {
Serial.print(number1);
Serial.print(" ");
Serial.println(number1 - old);
old = number1;
}
delay(10);
}
解説
インクルードファイル
#include "driver/mcpwm.h"
が必要です。
mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM_CAP_0, 37);
でインプットキャプチャに使うピンをしてします。この例ではタイマユニット0番のキャプチャピン0番をGPIO37で回路に接続することになります。MCPWM_UNIT_は0,1の2つMCPWM_CAP_は0,1,2の3つ合計6つ指定できます。
mcpwm_capture_enable(MCPWM_UNIT_0, MCPWM_SELECT_CAP0, MCPWM_POS_EDGE, 0);
でキャプチャの設定と起動を行います。MCPWM_POS_EDGEは起動するタイミングの設定です。最後の0は指定した回数、信号が入力するまでキャプチャを行いません。0で1回の入力でキャプチャになります。
インプットキャプチャ割り込みルーチンも自作することができます。
ソースコード
#include "driver/mcpwm.h"
volatile unsigned int input_capture_data = 0;
bool input_capture_call_back(mcpwm_unit_t mcpwm, mcpwm_capture_channel_id_t cap_channel, const cap_event_data_t *edata, void *user_data)
{
static unsigned int old_number = 0;
unsigned int number = edata->cap_value;
input_capture_data = number - old_number;
old_number = number;
return false;
}
void setup() {
mcpwm_capture_config_t input_capture_setup;
input_capture_setup.cap_edge = MCPWM_NEG_EDGE;
input_capture_setup.cap_prescale = 1;
input_capture_setup.capture_cb = input_capture_call_back;
input_capture_setup.user_data = NULL;
Serial.begin(115200);
mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM_CAP_0, 37);
mcpwm_capture_enable_channel(MCPWM_UNIT_0, MCPWM_SELECT_CAP0,&input_capture_setup );
}
void loop() {
static unsigned int old_data = 0;
if( old_data != input_capture_data ) {
Serial.println(input_capture_data);
old_data = input_capture_data;
}
delay(1);
}
参考サイト