const int buttonPin = 13;
const int ledPin = 3;
bool buttonState = HIGH;
bool animationPaused = false;
unsigned long lastButtonPressTime = 0;
const unsigned long debounceDelay = 50; // Adjust as needed
// Set initial brightness and direction
int brightness = 0;
int fadeAmount = 1; // 10ms per increment, adjust as needed
const int maxBrightness = 255;
const int minBrightness = 0;
// Initialize timing variables
unsigned long previousMillis = 0;
const unsigned long interval = 5; // 10ms per increment
const unsigned long exhaleDuration = 1000; // 1 second exhale duration, adjust as needed
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
// Check if the interval has passed
if (currentMillis - previousMillis >= interval && !animationPaused) {
previousMillis = currentMillis;
// Update brightness
brightness += fadeAmount;
// Ensure brightness stays within valid range (0 to 255)
brightness = constrain(brightness, minBrightness, maxBrightness);
// Apply brightness to the LED
analogWrite(ledPin, brightness);
// Reverse direction when brightness reaches maximum or minimum
if (brightness == maxBrightness || brightness == minBrightness) {
fadeAmount *= -1;
}
}
// Add a pause (exhale duration) after each cycle
if (brightness == minBrightness) {
delay(exhaleDuration);
}
// Debounce button state
if (millis() - lastButtonPressTime >= debounceDelay) {
bool currentButtonState = digitalRead(buttonPin);
if (buttonState == LOW && currentButtonState == HIGH) {
buttonState = HIGH;
animationPaused = !animationPaused; // Pause animation on button press
} else if (buttonState == HIGH && currentButtonState == LOW) {
buttonState = LOW;
}
lastButtonPressTime = millis();
}
}