/*
* デジタルストップウォッチ(チャタリング防止)
* 黒ボタンを押すとタイマースタート、白ボタンを押すとタイマーストップ
*/
#include <SevSeg.h>
// ピン番号を定数として定義
const int PIN_BTN_START = 18;
const int PIN_BTN_STOP = 19;
// 7セグ制御用
SevSeg sevseg;
// タイマー
unsigned long timer = 0;
bool timer_start = false;
// プッシュボタン制御用
int state_btn = LOW;
int before_state_start = LOW;
int before_state_stop = LOW;
void setup() {
// プッシュボタンの設定
pinMode(PIN_BTN_START, INPUT);
pinMode(PIN_BTN_STOP, INPUT);
// 7セグメントLEDの設定
byte hardware_config = COMMON_ANODE; // アノードコモン/カソードコモン
byte num_digits = 4; // 桁数
byte digit_pins[] = {5, 4, 3, 2}; // コモン(COM or DIG1~DIG4) ピン番号
byte segment_pins[] = {13, 12, 11, 10, 9, 8, 7, 6}; // セグメント(A~G)&ドット ピン番号
bool resistors_on_segments = false; // セグメント(A~G)&ドット 電流制限抵抗の有無
// begin([アノードコモン/カソードコモン], [桁数], [コモンピン番号配列], [セグメントピン番号配列], [抵抗の有無])
sevseg.begin(hardware_config, num_digits, digit_pins, segment_pins, resistors_on_segments);
// LEDの明るさを指定
sevseg.setBrightness(90);
// Serial.begin(115200);
}
void loop() {
// スタートボタン(黒)
state_btn = digitalRead(PIN_BTN_START);
if (state_btn == LOW)
{
if (before_state_start == HIGH)
{
if (timer_start == false)
{
// タイマースタート
timer_start = true;
// 現在時間を取得
timer = millis();
}
}
before_state_start = LOW;
}
else
{
before_state_start = HIGH;
}
// ストップボタン(白)
state_btn = digitalRead(PIN_BTN_STOP);
if (state_btn == LOW)
{
if (before_state_stop == HIGH)
{
// タイマーストップ
timer_start = false;
}
before_state_stop = LOW;
}
else
{
before_state_stop = HIGH;
}
// ストップウォッチ
if (timer_start)
{
stopwatch();
}
// 7セグ表示更新
sevseg.refreshDisplay();
}
// ストップウォッチ関数
void stopwatch() {
static int deci_seconds = 0; // 1/10[秒]
if (millis() - timer >= 100)
{
timer += 100;
deci_seconds++; // 100ミリ秒 = 1デシ秒
if (deci_seconds == 10000) { // 1000秒以上は表示できないためタイマーリセット
deci_seconds = 0;
}
// 7セグに数値を設定
sevseg.setNumber(deci_seconds, 1);
}
}
START
STOP