#include <Adafruit_NeoPixel.h>
#define PIN_PIXEL 5
#define PIN_BUTTON 4
#define NUM_PIXELS 1
Adafruit_NeoPixel pixels(NUM_PIXELS, PIN_PIXEL, NEO_GRB + NEO_KHZ800);
#define COLOR_RED pixels.Color(255, 0, 0)
#define COLOR_YELLOW pixels.Color(255, 255, 0)
#define COLOR_GREEN pixels.Color(0, 255, 0)
#define COLOR_OFF pixels.Color(0, 0, 0)
unsigned long buttonPressStartTime = 0;
bool buttonPressed = false;
bool buttonState = HIGH;
bool lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
Serial.begin(9600);
pixels.begin();
pinMode(PIN_BUTTON, INPUT_PULLUP);
}
void loop() {
int reading = digitalRead(PIN_BUTTON);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) { // Button pressed
if (!buttonPressed) { // Button was just pressed
buttonPressed = true;
buttonPressStartTime = millis();
Serial.println("Button pressed");
}
} else { // Button released
if (buttonPressed) { // Button was just released
unsigned long buttonPressDuration = millis() - buttonPressStartTime;
Serial.print("Button released after ");
Serial.print(buttonPressDuration);
Serial.println(" ms");
if (buttonPressDuration > 5000) { // Long press (> 5 seconds)
pixels.setPixelColor(0, COLOR_RED);
} else if (buttonPressDuration >= 2000 && buttonPressDuration <= 5000) { // Medium press (2 to 5 seconds)
pixels.setPixelColor(0, COLOR_YELLOW);
} else { // Short press (< 2 seconds)
pixels.setPixelColor(0, COLOR_GREEN);
}
pixels.show();
delay(1000); // Wait for 1 second
pixels.setPixelColor(0, COLOR_OFF);
pixels.show();
buttonPressed = false;
}
}
}
}
lastButtonState = reading;
}