Hold a Button

I hope this example will help you create some awesome inventions! My email address is sm11963@gmail.com if you would like to contact me.

int inPin = 14;  // the pin number for input (for me a push button)
int ledPin = 13; 

int current;  // Current state of the button
              // (LOW is pressed b/c i'm using the pullup resistors)
int count;    // How long the button was held (secs)
byte previous = HIGH;
unsigned long firstTime;   // how long since the button was first pressed 


void setup() {
  Serial.begin(9600);         // Use serial for debugging
  pinMode(ledPin, OUTPUT);
  digitalWrite(inPin, HIGH);  // Turn on 20k pullup resistors to simplify switch input
}

void loop() {
  current = digitalRead(inPin);

  // if the button changes to pressed, remember the time 
  if (current == LOW && previous == HIGH && millis() - firstTime > 200) {
    firstTime = millis(); 
  }

  // Notice that we check if the the button has been held for at least 500 ms
  // This is to debounce the input (basically make sure we get the steady state of the button)
  if (current == LOW && ((millis() - firstTime) % 1000) < 20 && millis() - firstTime > 500){
    ledblink(1, 50, ledPin); // Each second the button is held blink the indicator led and
    count++;                 // and add 1 to the counter
  }

  // When the button is released, if the counter is between the
  // two numbers (3-6 blinks or secs) run the program (here just another blink)
  if (current == HIGH && previous == LOW && count >=3 && count < 6){
    ledblink(10,200,ledPin); 
  }

  if (current == HIGH && previous == LOW && count >=0 && count < 3) {
    Serial.println("It Works!!!"); // This is where you would put your own functions
                                   // with different time parameters
  }

  // reset the counter if the button is not pressed
  if (current == HIGH) {
    count = 0;
  }

  previous = current;
}

// Just a simple helper function to blink an led in various patterns
void ledblink(int times, int lengthms, int pinnum){
  for (int x=0; x<times;x++) {
    digitalWrite(pinnum, HIGH);
    delay (lengthms);
    digitalWrite(pinnum, LOW);
    delay(lengthms);
  }
}

Share