int value = 0; // PWM value
int ledPin = 9; // the LED
int buttonPin = 7; // button with input pullup, tied to ground
int buttonVal; // HIGH or LOW
int dir = 0; // fade direction UP
void setup() {
Serial.begin(9600);
Serial.print(" Fade UP ");
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
buttonVal = digitalRead(buttonPin); // read the button
while (buttonVal == LOW ) { // if button is pressed
delay(100);
buttonVal = HIGH;
if (dir == 0) { // if direction is up, fade to max
value += 5;
Serial.print(".");
analogWrite(ledPin, value); // 0 to 255
delay(30);
if (value >= 250) {
Serial.print("\nFade DOWN ");
dir = 1;
}
}
if (dir == 1) { // if direction is down, fade to min
value -= 5;
Serial.print(".");
analogWrite(ledPin, value);
delay(30);
if (value <= 0) {
Serial.print("\n Fade UP ");
dir = 0;
}
}
}
}ON
OFF