Skip to content

Instantly share code, notes, and snippets.

@ochaochaocha3
Created November 11, 2016 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ochaochaocha3/a9cc9a0d9dd363a06ffe86e0ed30cb98 to your computer and use it in GitHub Desktop.
Save ochaochaocha3/a9cc9a0d9dd363a06ffe86e0ed30cb98 to your computer and use it in GitHub Desktop.
Raspberry Pi:チャタリング対策付き負論理タクトスイッチのC++クラス
/**
* @file tact_switch.cpp
* @brief タクトスイッチ
*/
#include "tact_switch.h"
#include <wiringPi.h>
namespace rpi {
TactSwitch::TactSwitch(const int pin, const int push_count) :
pin_(pin),
push_count_(push_count),
down_count_(0),
is_pushed_read_(false)
{
}
void TactSwitch::setup() {
pinMode(pin_, INPUT);
pullUpDnControl(pin_, PUD_UP);
}
void TactSwitch::clean_up() {
pullUpDnControl(pin_, PUD_OFF);
}
TactSwitch::State TactSwitch::read_state() {
if (digitalRead(pin_) == LOW) {
// スイッチが下がっている場合
if (is_pushed_read_) {
return PUSHED_READ;
}
if (down_count_ < push_count_) {
++down_count_;
}
if (down_count_ >= push_count_) {
is_pushed_read_ = true;
return PUSHED;
}
is_pushed_read_ = false;
return DOWN;
}
// スイッチが上がっている場合
down_count_ = 0;
is_pushed_read_ = false;
return UP;
}
}
/**
* @file tact_switch.h
* @brief タクトスイッチのヘッダファイル
*/
#pragma once
namespace rpi {
/**
* タクトスイッチのクラス
*
* タクトスイッチは負論理で動作するように接続する。
* 内蔵のプルアップ抵抗を使用するため、抵抗を付ける必要はない。
*
* チャタリング対策として指定回数スイッチが下げられている状態を
* 連続で読み込んだ場合に「押された」と認識するようにしている。
*/
class TactSwitch {
public:
/** スイッチの状態を表す型 */
enum State {
/** 上がっている */
UP,
/** 下がっている */
DOWN,
/** 押された */
PUSHED,
/** 押された状態で読み取られた */
PUSHED_READ
};
/**
* コンストラクタ
*
* @param pin ピン番号
* @param push_count 押されたと認識されるのに必要なカウント数
*/
TactSwitch(const int pin, const int push_count);
/**
* ピンの設定を行う
*/
void setup();
/**
* 後片付けを行う
*/
void clean_up();
/**
* 現在の状態を読み出す
*
* 押しっぱなしの場合の最初の 1 回だけ反応するようにするには
* 戻り値が PUSHED である場合のみ処理を行うようにする。
*
* @return UP スイッチが押されていない場合
* @return DOWN スイッチが押されているが、まだ指定回数だけ読み出していない場合
* @return PUSHED スイッチが押され、ちょうど指定回数だけ読み出した場合
* @return PUSHED_READ スイッチが押され、指定回数より多く読み出した場合
*/
State read_state();
private:
/** ピン番号 */
const int pin_;
/** 押されたと認識されるのに必要なカウント数 */
const int push_count_;
/** 下がっている状態のカウント数 */
int down_count_;
/** 押された状態が読み取られたか */
bool is_pushed_read_;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment