const int buttonPin = 2; // Button pin
const int ledPin = 8; // LED pin
const int blinkLed = 11; // Blink LED pin
const int testPin = A0;
const int debounceDelay = 50; // the debounce time; increase if the output flickers
// Variables will change:
bool ledState = 0; // Current state of the LED
bool blinkState; // Current stateo of blink LED
int lastButtonState = LOW; // Previous reading from the input pin
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long tNow; // Used to measure blink time
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(testPin,OUTPUT);
digitalWrite(testPin,HIGH);
// set initial LED state
digitalWrite(ledPin, ledState);
Serial.begin(115200);
}
void loop() {
// read the state of the switch into a local variable:
if(isButtonPressed()){
ledState = !ledState;
digitalWrite(ledPin,ledState);
}
if(millis()-tNow >=500){
tNow = millis();
blinkState = !blinkState;
digitalWrite(blinkLed,blinkState);
}
}
bool isButtonPressed(){
static bool buttonState;
static bool debouncedButtonState=1;
bool isPressed = false;
int reading = digitalRead(buttonPin);
if (reading != buttonState) {
// reset the debouncing timer
//Serial.print(millis()-lastDebounceTime);Serial.print(":");
//Serial.print(debouncedButtonState);Serial.print(" ");Serial.println(reading);
digitalWrite(testPin,debouncedButtonState);
buttonState = reading;
lastDebounceTime = millis();
}
else{
if ((millis() - lastDebounceTime) > debounceDelay) {
//Serial.print(millis()-lastDebounceTime);Serial.print("\t");
lastDebounceTime = millis();
if(reading == 0 && debouncedButtonState == 1){
isPressed = true;
}
debouncedButtonState = reading;
//Serial.print(debouncedButtonState);Serial.print(" ");Serial.println(reading);
digitalWrite(testPin,debouncedButtonState);
}
}
return isPressed;
}