One button, Two actions(but how?)

I am trying to make that when a button is pressed for a short time action A happens, but when I press the switch for 5000 milliseconds action B happens. Now my question is if you can take a look at my code, because I am not able to figure out why this code doesn’t work. I connected pin 2 to a momentary switch with a pulldown resistor as described in the tutorials on arduino.cc and then put in a LED with resistor on pin 8. They are both connected to ground.

int buttonState=0;
int lastButtonState=0;
int held=0;
void setup(){
  pinMode(2,INPUT);
  pinMode(8,OUTPUT);
}
void loop(){
  buttonState=digitalRead(2);
  if(digitalRead(2)==HIGH&&held>=5000){
    digitalWrite(8,HIGH);
    delay(250);
    digitalWrite(8,LOW);
    delay(1000);digitalWrite(8,HIGH);
    delay(250);
    digitalWrite(8,LOW);
    delay(1000);digitalWrite(8,HIGH);
    delay(250);
    digitalWrite(8,LOW);
    delay(1000);digitalWrite(8,HIGH);
    delay(250);
    digitalWrite(8,LOW);
    delay(1000);digitalWrite(8,HIGH);
    delay(250);
    digitalWrite(8,LOW);
  }
  if(buttonState!=lastButtonState){
    if(buttonState==HIGH){
    digitalWrite(8,HIGH);
    delay(250);
    digitalWrite(8,LOW);
  }
  lastButtonState=buttonState;
  }
}

try the ClickButton library

For switch timing pushes try switch manager.

/*SwitchManager skeleton 
 
 
 This sketch is to introduce new people to the SwitchManager library written by Nick Gammon
 
 The library handles switch de-bouncing and provides timing and state change information in your sketch.
 The SwitchManager.h file should be placed in your libraries folder, i.e.
 C:\Users\YourName\Documents\Arduino\libraries\SwitchManager\SwitchManager.h
 You can download the library at:
 http://gammon.com.au/Arduino/SwitchManager.zip    Thank you Nick!
 
 In this example we have 2 normally open (N.O.) switches connected to the Arduino - increment and decrement.
 The increment switch will also be used as a "Reset" switch if pressed for more than two seconds.
 The two switches are connected between GND (0 volts) and an Arduino input pin.
 The library enables pull-up resistors for your switch inputs.
 Pushing a switch makes its pin LOW. Releasing a switch makes its pin HIGH.
 
 The SwitchManager library provides 10ms de-bounce for switches. 
 i.e. enum { debounceTime = 10, noSwitch = -1 };
 If you need more time, edit the SwitchManager.h file
 i.e. enum { debounceTime = 50, noSwitch = -1 }; //here it is changed to 50ms
 */

#include <SwitchManager.h>             
//object instantiations
SwitchManager myIncSwitch;
SwitchManager myDecSwitch;

unsigned long currentMillis;
unsigned long heartBeatMillis;
unsigned long heartFlashRate  = 500UL; // time the led will change state       
unsigned long incShortPress   = 500UL; // 1/2 second
unsigned long incLongPress    = 2000UL;// 2 seconds 
unsigned long decShortPress   = 500UL; // 1/2 second

const byte heartBeatLED       = 13;
const byte incSwitch          = 4; //increment switch is on Arduino pin 4
const byte decSwitch          = 5; //decrement switch is on Arduino pin 5

int myCounter;

//======================================================================

void setup()
{
  Serial.begin(9600);

  //gives a visual indication if the sketch is blocking
  pinMode(heartBeatLED, OUTPUT);  

  myIncSwitch.begin (incSwitch, handleSwitchPresses); 
  myDecSwitch.begin (decSwitch, handleSwitchPresses);
  //the handleSwitchPresses() function is called when a switch changes state

} //                   E N D  O F  s e t u p ( )

//======================================================================

void loop()
{
  //leave this line of code at the top of loop()
  currentMillis = millis();

  //***************************
  //some code to see if the sketch is blocking
  if (CheckTime(heartBeatMillis, heartFlashRate, true))
  {
    //toggle the heartBeatLED
    digitalWrite(heartBeatLED,!digitalRead(heartBeatLED));
  }

  //***************************
  //check to see what's happening with the switches
  //"Do not use delay()s" in your sketch as it will make switch changes unresponsive 
  //Use BlinkWithoutDelay (BWD) techniques instead.
  myIncSwitch.check ();  
  myDecSwitch.check (); 

  //***************************
  //put other non-blocking stuff here


} //                      E N D  O F  l o o p ( )


//======================================================================
//                          F U N C T I O N S
//======================================================================


//                        C h e c k T i m e ( ) 
//**********************************************************************
//Delay time expired function
//parameters:
//lastMillis = time we started
//wait = delay in ms
//restart = do we start again  

boolean CheckTime(unsigned long  & lastMillis, unsigned long wait, boolean restart) 
{
  //has time expired for this task?
  if (currentMillis - lastMillis >= wait) 
  {
    //should this start again? 
    if(restart)
    {
      //yes, get ready for the next iteration
      lastMillis = millis();  
    }
    return true;
  }
  return false;

} //                 E N D   o f   C h e c k T i m e ( )


//                h a n d l e S w i t c h P r e s s e s( )
//**********************************************************************

void handleSwitchPresses(const byte newState, const unsigned long interval, const byte whichPin)
{
  //  You get here "ONLY" if there has been a change in a switches state.

  //When a switch has changed state, SwitchManager passes this function 3 arguments:
  //"newState" this will be HIGH or LOW. This is the state the switch is in now.
  //"interval" the number of milliseconds the switch stayed in the previous state
  //"whichPin" is the switch pin that we are examining  

  switch (whichPin)
  {
    //***************************
    //are we dealing with this switch?
  case incSwitch: 

    //has this switch gone from LOW to HIGH (gone from pressed to not pressed)
    //this happens with normally open switches wired as mentioned at the top of this sketch
    if (newState == HIGH)
    {
      //The incSwitch was just released
      //was this a short press followed by a switch release
      if(interval <= incShortPress) 
      {
        Serial.print("My counter value is = ");
        myCounter++;
        if(myCounter > 1000)
        {
          //limit the counter to a maximum of 1000
          myCounter = 1000; 
        }
        Serial.println(myCounter);
      }

      //was this a long press followed by a switch release
      else if(interval >= incLongPress) 
        //we could also have an upper limit
        //if incLongMillis was 2000UL; we could then have a window between 2-3 seconds
        //else if(interval >= incLongMillis && interval <= incLongMillis + 1000UL) 
      {
        //this could be used to change states in a StateMachine
        //in this example however, we will just reset myCounter
        myCounter = 0;
        Serial.print("My counter value is = ");
        Serial.println(myCounter);
      }

    }

    //if the switch is a normally closed (N.C.) and opens on a press this section would be used
    //the switch must have gone from HIGH to LOW 
    else 
    {
      Serial.println("The incSwitch was just pushed");
    } 

    break; //End of case incSwitch

    //*************************** 
    //are we dealing with this switch?
  case decSwitch: 

    //has this switch gone from LOW to HIGH (gone from pressed to not pressed)
    //this happens with normally open switches wired as mentioned at the top of this sketch
    if (newState == HIGH)
    {
      //The decSwitch was just released
      //was this a short press followed by a switch release
      if(interval <= decShortPress) 
      {
        Serial.print("My counter value is = ");
        myCounter--;
        if(myCounter < 0) 
        {
          //don't go below zero
          myCounter = 0;
        }
        Serial.println(myCounter);
      }

    }

    //if the switch is a normally closed (N.C.) and opens on a press this section would be used
    //the switch must have gone from HIGH to LOW
    else 
    {
      Serial.println("The decSwitch switch was just pushed");
    } 

    break; //End of case decSwitch

    //*************************** 
    //Put default stuff here
    //default:
    //break; //END of default

  } //End switch (whichPin)

} //      E n d   o f   h a n d l e S w i t c h P r e s s e s ( )


//======================================================================
//                      E N D  O F  C O D E
//======================================================================

I connected pin 2 to a momentary switch with a pulldown resistor as described in the tutorials on arduino.cc

Which one? Post a schematic showing how YOU wired the switch. Or, put the unnecessary resistor away, and use INPUT_PULLUP as the mode. Connect one leg to the pin and the other leg to ground. HIGH will mean not pressed. LOW will mean pressed.

I used the wiring as in https://www.arduino.cc/en/Tutorial/Button this tutorial, but I used an external LED instead of the build-in one. Thank you for sending these libraries, but can you tell me what I’m doing wrong in my own code? This would be extra helpfull as I also learn from it.

but can you tell me what I'm doing wrong in my own code?

In your code, where do you assign a new value to held?

PaulS:
In your code, where do you assign a new value to held?

Why would I have to assign a new value to held? (I'm sorry if this is a stupid question)

Why would I have to assign a new value to held?

What is held suppose to contain? The name suggests to me that the value in the variable represents how long the switch has been held down. The context of how it is used suggests the same thing. Since the only value ever assigned to held is 0, it seems unlikely that held will ever equal or exceed 5000.

NiekS:
Why would I have to assign a new value to held? (I'm sorry if this is a stupid question)

A simple way is to look at the time when the button is released and compare that to when it was pressed.

you should find non-blocking methods to do your loop() stuff, but the libraries will basically do something like this:

const byte buttonPin = 7;

void setup(void)
{
  Serial.begin(9600);
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  Serial.println("ready");
}

void loop(void)
{
  switch(buttonPress())
  {
    case 1:
      Serial.println("short press");
      break;
    case 2:
      Serial.println("long press");
      break;
  }
  blinkLed(13);
}

int buttonPress(void)
{
  static unsigned long lastUpMillis = 0;
  static byte lastState = HIGH;
  const byte currentState = digitalRead(buttonPin);
  delay(50);  // crude debouncing here 
  if(lastState != currentState)
  {
    lastState = currentState;
    if(currentState == HIGH) // button released
    {
      if(millis() - lastUpMillis > 1000) // long press
      {
        return 2; 
      }
      else 
      {
        return 1;
      }
    }
    else
    {
      lastUpMillis = millis();
    }
  }
  return 0;
}

void blinkLed(byte pin)
{
  static unsigned long lastMillis = 0;
  if(millis() - lastMillis > 250)
  {
    digitalWrite(pin, !digitalRead(pin));
    lastMillis = millis();
  }
}

PaulS:
The name suggests to me that the value in the variable represents how long the switch has been held down. The context of how it is used suggests the same thing. Since the only value ever assigned to held is 0, it seems unlikely that held will ever equal or exceed 5000.

This is exectly what I want to use it for, can you tell me what I should place behind the variable held?

NiekS:
This is exectly what I want to use it for, can you tell me what I should place behind the variable held?

read post 8