memomem

備忘録・メモ置き場

Arduinoでのイベント

// イベント実装方法サンプル
// https://github.com/bakercp/PacketSerial/blob/master/src/PacketSerial.h
class BtnInput
{
  public:
    typedef void (*BtnPressHandler)(bool v);

    BtnInput(int buttonPin_, int pushLimit_){
      buttonPin = buttonPin_;
      pushLimit = pushLimit_;
    }

    void setup(){
      pinMode(buttonPin, INPUT_PULLUP);
    }

    void setListener(BtnPressHandler eventBtnPress_) {
      eventBtnPress = eventBtnPress_;
    }

    void dispatchBtnEvent(bool press) {
      if (eventBtnPress) {
        eventBtnPress(press);
      }
    }

    void loop(){
      // チャタリング防止。カウントアップを行い閾値をこえたところで Pressとする
      int buttonState = digitalRead(buttonPin);
      if(buttonState == LOW){
        gauge++;
      }else{
        gauge--;
      }
      gauge = constrain(gauge, 0, pushLimit);
      // USBSerial.println(gauge);
      if (gauge >= pushLimit)
      {
        // Press
        dispatchBtnEvent(true);
      }
      if (gauge <= 0)
      {
        // Release
        dispatchBtnEvent(false);
      }
    }

  private:
    int buttonPin;
    int gauge;
    int pushLimit;

    BtnPressHandler eventBtnPress = nullptr;
};
/*
AtomS3
https://lang-ship.com/blog/work/esp32-s3atoms3%E3%81%A7usb%E3%83%87%E3%83%90%E3%82%A4%E3%82%B9%E3%81%A7%E3%83%9E%E3%82%A6%E3%82%B9%E3%81%A8%E3%82%AD%E3%83%BC%E3%83%9C%E3%83%BC%E3%83%89%E5%AE%9F%E9%A8%93/
USBHIDKeyboardを使う場合、動作確認が終わって新しいファームウエアを転送する場合には、
ATOMS3の場合にはリセットボタンを2秒以上押してダウンロードモードに戻す必要があります。
*/
#include <M5AtomS3.h>

#include "USB.h"
#include "USBHIDKeyboard.h"
USBHIDKeyboard Keyboard;

#include "BtnInput.h"

// 処理速度で変更する必要あり
#define PUSH_LIMIT 20

const int buttonPin0 = 1;
char key0 = 'b';
BtnInput btnInput0 = BtnInput(buttonPin0, PUSH_LIMIT);

const int buttonPin1 = 2;
char key1 = 'c';
BtnInput btnInput1 = BtnInput(buttonPin1, PUSH_LIMIT);

void setup() {
  M5.begin(true, true, false, false);

  M5.Lcd.setTextSize(2);
  M5.Lcd.println("USBHIDKeyboard");

  btnInput0.setup();
  btnInput1.setup();

  btnInput0.setListener(&OnPress0);
  btnInput1.setListener(&OnPress1);
  //
  Keyboard.begin();
  USB.begin();
}

void OnPress0(bool press){
  if(press){
    Keyboard.press(key0);
  }else{
    Keyboard.release(key0);
  }
}

void OnPress1(bool press){
  if(press){
    Keyboard.press(key1);
  }else{
    Keyboard.release(key1);
  }
}

int gauge = 0;
bool isAct = false;

void loop() {
  M5.update();

  if (M5.Btn.isPressed()){
    Keyboard.press('a');
  }else{
    Keyboard.release('a');
  }

  btnInput0.loop();
  btnInput1.loop();
}