Created
April 4, 2014 04:58
-
-
Save nataliefreed/9968452 to your computer and use it in GitHub Desktop.
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
//count pressed, turn from red to green by Natalie Freed | |
//April 2014 | |
//with debounce code from David Mellis | |
int red = 9; | |
int blue = 10; | |
int green = 11; | |
int buttonPin = A5; | |
int redCounter = 0; | |
int greenCounter = 255; | |
long timeCounter = millis(); | |
long fadeInterval = 300; | |
int buttonState; // the current reading from the input pin | |
int lastButtonState = LOW; // the previous reading from the input pin | |
// the following variables are long's because the time, measured in miliseconds, | |
// will quickly become a bigger number than can be stored in an int. | |
int lastRecordedState = LOW; | |
long lastDebounceTime = 0; // the last time the output pin was toggled | |
long debounceDelay = 50; // the debounce time; increase if the output flickers | |
void setup() | |
{ | |
Serial.begin(9600); | |
pinMode(red, OUTPUT); | |
pinMode(green, OUTPUT); | |
pinMode(blue, OUTPUT); | |
pinMode(buttonPin, INPUT_PULLUP); | |
digitalWrite(blue, HIGH); //turn blue off (common anode) | |
} | |
void loop() | |
{ | |
// read the state of the switch into a local variable: | |
int reading = digitalRead(buttonPin); | |
// check to see if you just pressed the button | |
// (i.e. the input went from LOW to HIGH), and you've waited | |
// long enough since the last press to ignore any noise: | |
// If the switch changed, due to noise or pressing: | |
if (reading != lastButtonState) { | |
// reset the debouncing timer | |
lastDebounceTime = millis(); | |
} | |
if ((millis() - lastDebounceTime) > debounceDelay) { | |
// whatever the reading is at, it's been there for longer | |
// than the debounce delay, so take it as the actual current state: | |
buttonState = reading; | |
Serial.print(buttonState); | |
Serial.print(" "); | |
Serial.println(lastButtonState); | |
if(buttonState == LOW && buttonState != lastRecordedState) | |
{ | |
redCounter += 10; | |
redCounter = constrain(redCounter, 0, 255); | |
greenCounter -= 10; | |
greenCounter = constrain(greenCounter, 0, 255); | |
} | |
lastRecordedState = buttonState; | |
} | |
if(millis() - timeCounter > fadeInterval) | |
{ | |
redCounter--; | |
redCounter = constrain(redCounter, 0, 255); | |
greenCounter++; | |
greenCounter = constrain(greenCounter, 0, 255); | |
timeCounter = millis(); | |
} | |
analogWrite(green, greenCounter); | |
analogWrite(red, redCounter); | |
// save the reading. Next time through the loop, | |
// it'll be the lastButtonState: | |
lastButtonState = reading; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment