Skip to content

Instantly share code, notes, and snippets.

@marchawkins
Last active January 3, 2016 05:09
Show Gist options
  • Save marchawkins/b318d9fd9d16a9ad36d8 to your computer and use it in GitHub Desktop.
Save marchawkins/b318d9fd9d16a9ad36d8 to your computer and use it in GitHub Desktop.
Using a push button control on an Arduino board to control an LED's brightness. Press the button to turn LED on. Hold it down to increase the LED's brightness until it reaches 100%. After reaching full brightness, the LED will return to 0% brightness and repeat.
// turn on LED when button is pressed, keep it on after release (simple de-bouncing)
// if button held, brightness changes
const int LED = 9; // pin for LED
const int BUTTON = 7; // pin of the pushbutton
int val = 0; // stores state of input (pin 7)
int old_val = 0; // stores previous value of val
int state = 0; // state of LED (0 is off, 1 is on)
int brightness = 128; // stores brightness of LED (start at 50%)
unsigned long startTime = 0; // keep track of when the 'push' started
void setup() {
pinMode(LED,OUTPUT); // LED is an output
pinMode(BUTTON,INPUT); // BUTTON is an input
}
void loop() {
val = digitalRead(BUTTON); // read input value of button and store in val
// check for transition
if((val==HIGH) && (old_val==LOW)) {
state = 1 - state; // change on/off
startTime = millis(); // the arduino clock - returns how many milliseconds have passed since board has been reset
// used to remember when button was last pressed
delay(10);
}
// check if button is held down
if((val==HIGH) && (old_val==HIGH)) {
// if button held for more than 500ms
if(state==1 && (millis() - startTime) > 500) {
brightness++; // increase brightness by 1
delay(10); // use delay to stop brightness from going up too fast
if(brightness > 255) { // check for max brightness
brightness = 0; // reset to 0 if brightness is above 255
}
}
}
old_val = val; // val is old, store it
if(state==1) {
analogWrite(LED,brightness); // turn LED on at current brightness
} else {
analogWrite(LED,0); // turn LED off
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment