先日Arduinoのソースコードを書いてふと思ったのですが、 何かを作るたびに毎回同じようなコードを書いていることに気づいたため、エレガントに実装できないか考えてみました。
回路図
ESP32を使用していますが、ArduinoUNOやRaspberryPiPicoでも同じです。ただしピンを変更してください。
ソースコードと実装
SwitchInterface classの部分をコピーするなり、適当にSW_IF.hなどの名前で外部記述してincludeすれば、あとはグローバルでインスタンスするだけで使えます。(ここではBUTTONという名前)あまりincludeするファイルを増やしたくないという方は、数十行のコードなので、inoファイルに直接コピーすると良いでしょう。
1 SwitchInterfaceクラスをコピー
2 SwitchInteface インスタンス名(ピン番号)をグローバルで記述
3 インスタンス名.onSWdown()でスイッチが押されたことを検出するので、そのあとの動作を記述
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define PIN_BUTTON 12 | |
#define PIN_LED 26 | |
//---- SWITCH interface class ----- | |
class SwitchInterface { | |
private: | |
uint8_t reg; | |
uint8_t pin; | |
public: | |
SwitchInterface(uint8_t _pin) { | |
reg = 0xFF; | |
pin = _pin; | |
pinMode(pin, INPUT_PULLUP); | |
}; | |
bool onSWdown(){ | |
reg = (reg << 1) | digitalRead(pin); | |
if ((reg & 0x03) == 0x2) return true; | |
else return false; | |
}; | |
bool onSWup(){ | |
reg = (reg << 1) | digitalRead(pin); | |
if ((reg & 0x03) == 0x1) return true; | |
else return false; | |
}; | |
}; | |
// ------- end of SWITCH interface class ---- | |
//instance Switch interface | |
SwitchInterface BUTTON(PIN_BUTTON); | |
void setup() { | |
pinMode(PIN_LED, OUTPUT); | |
} | |
void loop() { | |
if (BUTTON.onSWdown()) { | |
digitalWrite(PIN_LED,!digitalRead(PIN_LED)); | |
} | |
delay(3); // sampling rate 3~20 msec | |
} |
debounceについて
サンプリング周期(最後のほうに記述しているdelay)は3ms~20msで良いと思います。debounceの起こる時間はおよそ3msくらいらしいので、最低でも3msec以上は必要です。
上限は20msecでも100msecでも良いのですが、あまり大きくしすぎるとスイッチの反応が遅くなります。
0 件のコメント:
コメントを投稿