const int LED_1_PIN = 41;
const int LED_2_PIN = 43;
const int LED_3_PIN = 45;
class Button {
const byte buttonPin;
static constexpr byte debounceDelay = 30;
const bool active;
bool lastButtonState = HIGH;
byte lastDebounceTime = 0;
public:
Button(byte attachTo, bool active = LOW) : buttonPin(attachTo), active(active) {}
void begin() {
if (active == LOW)
pinMode(buttonPin, INPUT_PULLUP);
else
pinMode(buttonPin, INPUT);
}
bool wasPressed() {
bool buttonState = LOW;
byte reading = LOW;
if (digitalRead(buttonPin) == active) reading = HIGH;
if (((millis() & 0xFF ) - lastDebounceTime) > debounceDelay)
{
if (reading != lastButtonState && lastButtonState == LOW)
{
buttonState = HIGH;
}
lastDebounceTime = millis() & 0xFF;
lastButtonState = reading;
}
return buttonState;
}
};
Button button1{A0};
Button button2{A1};
Button button3{A2};
Button button4{A3};
int ledBrightness = 10;
int led2BlinkDelay = 500;
int led2State = LOW;
unsigned long previousMillis = 0;
void setup() {
Serial.begin(115200);
button1.begin();
button2.begin();
button3.begin();
button4.begin();
pinMode(LED_1_PIN, OUTPUT);
pinMode(LED_2_PIN, OUTPUT);
pinMode(LED_3_PIN, OUTPUT);
}
void loop() {
analogWrite(LED_3_PIN, ledBrightness);
if (button1.wasPressed())
digitalWrite(LED_1_PIN, !digitalRead(LED_1_PIN));
if (button2.wasPressed())
led2BlinkDelay -= led2BlinkDelay/5;
if (button3.wasPressed())
led2BlinkDelay += led2BlinkDelay/5;
if (button4.wasPressed())
ledBrightness = (ledBrightness == 10) ? 240 : 10;
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= led2BlinkDelay) {
led2State = (led2State == LOW) ? HIGH : LOW;
digitalWrite(LED_2_PIN, led2State);
previousMillis = currentMillis;
}
}