switch with a delay

I am trying to do something that would seem simple...

button with a delay. press button, delays "x", digitalWrite(high) and when button is released, no delay. digitalWrite(low).

When I do the button code and add a delay, the delay occures before and after the button pushing.

How do I create code that has a local delay, and not a global delay.

this is a tiny part of a larger problem...but small steps...

thanks

There are several ways to accomplish this, but here's an easy one:

void setup()
{
  pinMode(10, INPUT); // button
  pinMode(11, OUTPUT); // LED
  digitalWrite(11, LOW);
}

int pinState = HIGH;
const int x = 500; // 500ms delay

void loop()
{
  int newState = digitalRead(10);
  if (pinState != newState) // button state differs from last recorded state?
  {
    pinState = newState;
    if (pinState == LOW) // button newly pressed?
      delay(x);
    digitalWrite(11, !pinState); // set LED HIGH if button LOW and vice versa
  }
}

Mikal

This is great, thanks.
Question: Does the delay cause the whole program to pause ? I will need to be able to have a 10 second delay...while watching the state of another pin, and digitalWrite if that state changes....

Does the delay cause the whole program to pause?

Yes. If you need to monitor an input continuously or do more than one thing at once, it is best to avoid calling delay.

A good strategy in circumstances like this is to do something like this in your loop:

  1. Check the inputs to see if they have changed state. If so, respond accordingly. For example, if the button has just been released, turn off the LED. If the event needs to trigger some action in the future, then record the current time (millis()) and set a flag so that at a future time you can perform the action.
static bool button_pressed_earlier = false;
if (... button pressed...)
{
  button_pressed_earlier = true;
  button_press_time = millis();
}
  1. Perform any actions that you scheduled earlier using:
if (button_pressed_earlier && millis() - button_press_time > 10000) // action completed 10 seconds later
{
  digitalWrite(10, HIGH); // turn on led
  button_pressed_earlier = false;
}

This strategy will help you avoid having to use delay() and allow you to check all inputs continuously.

Mikal