WhatsApp Video 2025-01-25 at 21.25.02_d3e3c0ca.mp4
const int ledPinRed = 5;
const int controlPin = 6;
// number of steps = 2^PWM resolution:
const int steps = 255;
int change = 5;
int currentLevel = 1;
bool isTurnOn = false;
void setup() {
Serial.begin(9600);
// wait for serial monitor to open:
if (!Serial) delay(3000);
// initialize digital pin 5 as an output:
pinMode(controlPin, INPUT);
pinMode(ledPinRed, OUTPUT);
}
void loop() {
if (digitalRead(controlPin) == HIGH) {
isTurnOn = !isTurnOn;
Serial.print("Flag toggled. New value: ");
Serial.println(isTurnOn);
if (!isTurnOn) { currentLevel = 1;}
}
if (isTurnOn) {
// add change to brightness:
currentLevel = currentLevel + change;
// and constrain to 0-255:
currentLevel = constrain(currentLevel, 0, steps);
// if brightness is at either extreme, change the
// direction of fading:
if (currentLevel == 0 || currentLevel == steps) {
change = -change;
}
// change the light:
analogWrite(ledPinRed, currentLevel);
// Serial.println(currentLevel);
} else {
analogWrite(ledPinRed, 0);
}
delay(100);
}