Skip to content

Instantly share code, notes, and snippets.

@radutzan
Created September 5, 2017 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radutzan/3f7d7d7d947f84c46cbedf73c6e46678 to your computer and use it in GitHub Desktop.
Save radutzan/3f7d7d7d947f84c46cbedf73c6e46678 to your computer and use it in GitHub Desktop.
Fade in and out an LED by pressing a button. Fun times
int led = 11;
int buttonPin = 2;
int buttonState = 0;
bool wasOn = false;
bool isOn = false;
bool wasPressed = false;
void setup() {
pinMode(led, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
Serial.println(buttonState);
// digitalWrite(led, buttonState);
if (buttonState == HIGH) {
wasPressed = true;
} else {
wasOn = isOn;
if (wasPressed) {
isOn = !isOn;
}
wasPressed = false;
}
if (isOn) {
if (!wasOn) {
fadeIn(led, 640);
} else {
digitalWrite(led, HIGH);
}
} else {
if (wasOn) {
fadeOut(led, 640);
} else {
digitalWrite(led, LOW);
}
}
}
void blink(int pin, int times, int duration) {
for (int i = 0; i < times; i++) {
digitalWrite(pin, HIGH);
delay(duration);
digitalWrite(pin, LOW);
delay(duration);
}
}
void fadeIn(int pin, unsigned long duration) {
for (int i = 0; i <= 255; i++) {
analogWrite(pin, i);
delay(duration/255);
}
}
void fadeOut(int pin, unsigned long duration) {
for (int i = 255; i >= 0; i--) {
analogWrite(pin, i);
delay(duration/255);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment