Skip to content

Instantly share code, notes, and snippets.

@pvanallen
Last active September 8, 2016 01:23
Show Gist options
  • Save pvanallen/d845c501e53986c55ec4c47fd32a7bc1 to your computer and use it in GitHub Desktop.
Save pvanallen/d845c501e53986c55ec4c47fd32a7bc1 to your computer and use it in GitHub Desktop.
Creative Tech Course: LED Dimmer ON/OFF Extra Credit - Toggle On/Off
/*
Set the brightness of an LED with a potentiometer
Use a momentary switch to toggle the LED on (at the brightness set by pot) or off
Toggle happens each time the button is pressed to the ON position
*/
// These constants won't change.
const int analogInPin = A1; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 3; // Analog output pin that the LED is attached to
const int buttonPin = 2; // the number of the pushbutton pin
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
int buttonState = 0; // variable for reading the pushbutton status
boolean ledState = LOW; // should the LED be on or off?
boolean lastButtonState = LOW; // the state of the button last time we checked
void setup() {
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// determine if the button is pressed or not
buttonState = digitalRead(buttonPin);
// if there's a transition of the button from LOW to HIGH, that's a toggle so swap the LED on/off state
if (buttonState == HIGH && lastButtonState == LOW) {
if (ledState == LOW) { // was LOW, change to HIGH
ledState = HIGH;
} else { // was HIGH, change to LOW
ledState = LOW;
}
}
// save the current button state for the next time through the loop
lastButtonState = buttonState;
// based on the above LED state check, set the LED to be on or off
if (ledState == HIGH) { // turn the LED on
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// set the analog out value:
analogWrite(analogOutPin, outputValue);
} else { // turn the LED off
analogWrite(analogOutPin, 0);
}
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment