#define PRESSED 0
#define RELEASED 1
#define JUST_PRESSED 2
#define JUST_RELEASED 3
#define LONG_PRESS 4
#define TIME0 2000
#define TIME1 100
#define debounceDelay 50 // the debounce time; increase if the output flickers
const int buttonPin = 2; // Button pin
const int ledPin = 8; // LED pin
const int blinkLed = 11; // Blink LED pin
const int testPin = A0;
// Variables will change:
bool ledState = 0; // Current state of the LED
bool blinkLedState; // Current stateo of blink LED
byte buttonState = RELEASED; // Previous reading from the input pin
unsigned long tNow;
unsigned long blinkLedTime = TIME0; // Used to measure blink time
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(blinkLed, 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:
buttonState = getButtonState();
if (buttonState == JUST_PRESSED) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
}
if (millis()-tNow >= blinkLedTime) {
tNow = millis();
if(blinkLedState == 0){
blinkLedState = 1;
blinkLedTime = TIME1;
}
else{
blinkLedState = 0;
blinkLedTime = TIME0;
}
digitalWrite(blinkLed, blinkLedState);
}
}
byte getButtonState() {
static unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
static unsigned long longPressTime = 0;
static bool readingChange = 0;
static bool lastReading = RELEASED;
static byte state = RELEASED;
if (state == JUST_PRESSED) {
state = PRESSED;
longPressTime = millis();
printState(state);
}
if (state == JUST_RELEASED) {
state = RELEASED;
printState(state);
}
if (state == LONG_PRESS) {
state = PRESSED;
printState(state);
longPressTime = millis();
}
if(state == PRESSED){
if(millis()-longPressTime>=1000){
state = LONG_PRESS;
printState(state);
}
}
int reading = digitalRead(buttonPin);
if (reading != lastReading) {
readingChange = 1;
digitalWrite(testPin, state);
lastReading = reading;
lastDebounceTime = millis();
}
if (readingChange == 1) {
if ((millis() - lastDebounceTime) > debounceDelay) {
//Serial.print(millis()-lastDebounceTime);Serial.print("\t");
lastDebounceTime = millis();
readingChange = 0;
state = reading;
if (reading == PRESSED) {
state = JUST_PRESSED;
}
else {
state = JUST_RELEASED;
}
digitalWrite(testPin, reading);
printState(state);
}
}
return state;
}
void printState(byte state) {
if (state == JUST_PRESSED) {
Serial.println("Just Pressed");
}
else if (state == PRESSED) {
Serial.println("Pressed");
}
else if (state == RELEASED) {
Serial.println("Released");
}
else if (state == JUST_RELEASED) {
Serial.println("Just Released");
}
else if(state == LONG_PRESS){
Serial.println("Long Press");
}
}