Created
July 24, 2012 20:01
-
-
Save aaronvb/3172262 to your computer and use it in GitHub Desktop.
Increase and Decrease LED with button
This file contains 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
/* | |
Increase LED Brightness with long press, Lower LED brightness with short press | |
Holding down the button with increase the brightness continuously. | |
A short press of the button will decrease the brightness by 20% | |
created 2012 | |
by Aaron Van Bokhoven | |
*/ | |
const int buttonPin = 2; // number of the button pin | |
const int ledPin = 9; // number of the LED pin | |
float brightness = 0; // brightness of LED starts at 0 | |
int fadeAmount = 51; // fadeAmount is equal to 20% of 255(max LED brightness) | |
float buttonPressedCounter = 0.0; // timer set to 0 whe depressing button | |
void setup() { | |
// set button as input | |
pinMode(buttonPin, INPUT); | |
// set LED as output | |
pinMode(ledPin, OUTPUT); | |
// init serialize communication at 9600 bits per second | |
Serial.begin(9600); | |
} | |
void loop() { | |
// activate when button is being held down | |
if (buttonState == HIGH) { | |
// on press, when counter is greater than 33, assume button is being held down | |
if (buttonPressedCounter > 33) { | |
// button was held down for longer than 33 | |
if (brightness < 255) { | |
Serial.print("increasing brightness: "); | |
Serial.println(brightness); | |
brightness = brightness + 5; | |
analogWrite(ledPin, brightness); | |
} | |
} else { | |
buttonPressedCounter ++; | |
Serial.print("holding: "); | |
Serial.println(buttonPressedCounter); | |
} | |
} else if (buttonState == LOW) { | |
// on release if button pressed counter was less than 33, assume it was a short press | |
if ((buttonPressedCounter < 33) & (buttonPressedCounter != 0)) { | |
Serial.print("lower LED: "); | |
if (brightness - fadeAmount < 0.0) { | |
brightness = 0; | |
} else { | |
brightness = brightness - fadeAmount; | |
} | |
Serial.println(brightness); | |
analogWrite(ledPin, brightness); | |
} | |
buttonPressedCounter = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment