#include <EEPROM.h>
// Define pins
const int ledPin = 0; // PB0, PWM-capable pin
const int buttonOnOff = 1; // PB1
const int buttonUp = 2; // PB2
const int buttonDown = 3; // PB3
// Variables to store the state of the LED and brightness
bool ledState = false;
int brightness = 128; // Initial brightness (range 0-255)
const int brightnessStep = 15; // Adjust brightness by this value
void setup() {
// Initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
// Initialize the button pins as inputs with internal pull-up resistors
pinMode(buttonOnOff, INPUT_PULLUP);
pinMode(buttonUp, INPUT_PULLUP);
pinMode(buttonDown, INPUT_PULLUP);
// Read the last saved brightness from EEPROM
brightness = EEPROM.read(0);
// If the value read from EEPROM is not in the valid range, reset to default brightness
if (brightness < 0 || brightness > 255) {
brightness = 128;
}
// Set initial LED state
analogWrite(ledPin, ledState ? brightness : 0);
}
void loop() {
// Check the on/off button
if (digitalRead(buttonOnOff) == LOW) {
delay(50); // Debounce delay
if (digitalRead(buttonOnOff) == LOW) {
ledState = !ledState; // Toggle LED state
analogWrite(ledPin, ledState ? brightness : 0);
while (digitalRead(buttonOnOff) == LOW); // Wait for button release
}
}
// Check the brightness up button
if (digitalRead(buttonUp) == LOW) {
delay(50); // Debounce delay
if (digitalRead(buttonUp) == LOW) {
brightness = min(255, brightness + brightnessStep); // Increase brightness
if (ledState) {
analogWrite(ledPin, brightness);
}
// Save the new brightness value to EEPROM
EEPROM.write(0, brightness);
while (digitalRead(buttonUp) == LOW); // Wait for button release
}
}
// Check the brightness down button
if (digitalRead(buttonDown) == LOW) {
delay(50); // Debounce delay
if (digitalRead(buttonDown) == LOW) {
brightness = max(0, brightness - brightnessStep); // Decrease brightness
if (ledState) {
analogWrite(ledPin, brightness);
}
// Save the new brightness value to EEPROM
EEPROM.write(0, brightness);
while (digitalRead(buttonDown) == LOW); // Wait for button release
}
}
}