아두이노 아케이드 버튼 ON/OFF

기존에 사용하던 작은 버튼을 대신할 아케이드 푸시 버튼
LED가 있어서 on/off 를 정확히 확인 할 수 있다.

#include "PushButton.h"

const uint8_t buttonPin = 3;
const uint8_t ledPin = 10;
const uint8_t buttonPin1 = 2;
const uint8_t ledPin1 = 9;

PushButton button = {buttonPin}; // a debounced button object that detects falling edges
PushButton button1 = {buttonPin1}; // a debounced button object that detects falling edges

bool ledState = LOW;
bool ledState1 = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin1, OUTPUT);
}

void loop() {
  if (button.isPressed()) { // on a falling edge of the button (if it's pressed)
    ledState = !ledState; // invert the state of the LED
    digitalWrite(ledPin, ledState); // write the state to the output
  }
  if (button1.isPressed()) { // on a falling edge of the button (if it's pressed)
    ledState1 = !ledState1; // invert the state of the LED
    digitalWrite(ledPin1, ledState1); // write the state to the output
  }

  Serial.print("ledState = ");
  Serial.println(ledState);
  
}
#ifndef PUSHBUTTON_H_
#define PUSHBUTTON_H_

class PushButton
{
  public:
    PushButton(uint8_t pin) // Constructor (executes when a PushButton object is created)
      : pin(pin) { // remember the push button pin
      pinMode(pin, INPUT_PULLUP); // enable the internal pull-up resistor
    };
    bool isPressed() // read the button state check if the button has been pressed, debounce the button as well
    {
      bool pressed = false;
      bool state = digitalRead(pin);               // read the button's state
      int8_t stateChange = state - previousState;  // calculate the state change since last time

      if (stateChange == falling) { // If the button is pressed (went from high to low)
        if (millis() - previousBounceTime > debounceTime) { // check if the time since the last bounce is higher than the threshold
          pressed = true; // the button is pressed
        }
      }
      if (stateChange == rising) { // if the button is released or bounces
        previousBounceTime = millis(); // remember when this happened
      }

      previousState = state; // remember the current state
      return pressed; // return true if the button was pressed and didn't bounce
    };
  private:
    uint8_t pin;
    bool previousState = HIGH;
    unsigned long previousBounceTime = 0;

    const static unsigned int debounceTime = 25;
    const static int8_t rising = HIGH - LOW;
    const static int8_t falling = LOW - HIGH;
};

#endif // PUSHBUTTON_H_

출처 :
https://forum.arduino.cc/index.php?topic=500101.0

카테고리: arduino

댓글 남기기