Created
September 5, 2017 22:13
-
-
Save radutzan/3f7d7d7d947f84c46cbedf73c6e46678 to your computer and use it in GitHub Desktop.
Fade in and out an LED by pressing a button. Fun times
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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