Skip to content

Instantly share code, notes, and snippets.

@KeitetsuWorks
Last active January 31, 2022 14:50
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 KeitetsuWorks/6cd7df75467613269a1829c766b0f125 to your computer and use it in GitHub Desktop.
Save KeitetsuWorks/6cd7df75467613269a1829c766b0f125 to your computer and use it in GitHub Desktop.
Arduino: スイッチ押下4回目でLEDが点灯し,押下5回目でLEDが消灯して初期状態に戻る
/**
* @file button_led.ino
* @brief Button and LED
* @author Keitetsu
* @date 2022/01/31
* @copyright Copyright (c) 2022 Keitetsu
* @par License
* This software is released under the MIT License.
*/
#define SW_PIN 2 /**< タクトスイッチ接続したデジタルピン */
#define SW_VAL_CURR 0 /**< タクトスイッチの現在の状態の格納位置 */
#define SW_VAL_PREV 1 /**< タクトスイッチの前回の状態の格納位置 */
#define SW_COUNT_LED_ON 4 /**< LEDをONにするスイッチの押下回数 */
#define SW_COUNT_LED_OFF 5 /**< LEDをOFFにするスイッチの押下回数 */
/* LEDはHIGHで消灯,LOWで点灯 */
#define LED_PIN 12 /**< LEDを接続したデジタルピン */
#define LED_OFF HIGH /**< LEDはHIGHで消灯 */
#define LED_ON LOW /**< LEDはLOWで点灯 */
#define INTERVAL_TIME 20 /**< 周期実行の間隔 (ミリ秒) */
static uint8_t sw_val[2]; /**< タクトスイッチの状態 */
static uint8_t sw_count; /**< タクトスイッチの押下回数 */
static unsigned long prev_time; /**< 周期実行の前回実行時刻 */
static unsigned long interval_time; /**< 周期実行の間隔 */
/**
* @brief セットアップ関数
*/
void setup() {
// タクトスイッチの初期化
pinMode(SW_PIN, INPUT);
sw_val[SW_VAL_CURR] = digitalRead(SW_PIN);
sw_val[SW_VAL_PREV] = sw_val[SW_VAL_CURR];
sw_count = 0;
// LEDの初期化
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LED_OFF);
// 周期実行の初期化
prev_time = 0;
interval_time = INTERVAL_TIME;
}
/**
* @brief ループ関数
*/
void loop() {
unsigned long curr_time;
// 現在時刻を取得する
curr_time = millis();
// 周期実行
if ((curr_time - prev_time) >= interval_time) {
prev_time += interval_time;
sw_count += getSW();
if (sw_count == SW_COUNT_LED_ON) {
digitalWrite(LED_PIN, LED_ON);
} else if (sw_count >= SW_COUNT_LED_OFF) {
sw_count = 0;
digitalWrite(LED_PIN, LED_OFF);
}
}
}
/**
* @brief タクトスイッチの状態を取得する
* @retval 0 押下されていないもしくはチャタリング対策の無効時間
* @retval 1 押下された
*/
uint8_t getSW() {
uint8_t sw_falling;
sw_falling = 0;
sw_val[SW_VAL_CURR] = digitalRead(SW_PIN);
if ((sw_val[SW_VAL_PREV] == HIGH) && (sw_val[SW_VAL_CURR] == LOW)) {
sw_falling = 1;
}
sw_val[SW_VAL_PREV] = sw_val[SW_VAL_CURR];
return sw_falling;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment