Day2 06_Debounce

2024. 1. 18. 19:57arduino

  • 디바운스를 이용해 버튼 누를때 생기는 노이즈의 영향을 받지않아 안정적이게 led 컨트롤 가능
const int buttonPin = 2;    
const int ledPin = 3;      

int ledState = LOW;        
int buttonState= HIGH;            
int lastButtonState = HIGH;  

unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;  

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
}

void loop() {
  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      if (buttonState == LOW) {
        ledState = !ledState;
      }
    }
  }

  digitalWrite(ledPin, ledState);
  lastButtonState = reading;
}

'arduino' 카테고리의 다른 글

Day4 01-debounce  (0) 2024.02.04
Day3 01-dht11  (0) 2024.02.04
Day2 05_IR  (0) 2024.01.18
Day2 04_sonic  (0) 2024.01.18
Day2 03_sensor_led  (0) 2024.01.18