const int ledPin = 9; // PWM-capable digital pin connected to the MOSFET gate
const int buttonPin = 2; // Digital pin connected to the button
int brightnessLevels[] = {0, 64, 128, 255}; // PWM values for off, 25%, 50%, and 100% brightness
int currentLevel = 0; // Current brightness level index
bool buttonState = HIGH; // Current state of the button
bool lastButtonState = HIGH; // Previous state of the button
unsigned long lastDebounceTime = 0; // The last time the button was toggled
unsigned long debounceDelay = 50; // The debounce time; increase if the output flickers
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
Serial.begin(9600);
while (true)
{
int reading = digitalRead(buttonPin);
// Check if the button state has changed
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
// Check if enough time has passed to consider the button state stable
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
// Only toggle the brightness if the new button state is LOW (button pressed)
if (buttonState == LOW) {
currentLevel = (currentLevel + 1) % 4; // Cycle through brightness levels including off
analogWrite(ledPin, brightnessLevels[currentLevel]); // Set LED brightness
Serial.print("Brightness Level: ");
Serial.println(currentLevel);
}
}
}
lastButtonState = reading;
}
}
void loop() {}