HELP ME WHIT BUTTON AND TIME FUNCTIONS ?

Hi !

First I want to apologize for my bad English.

For a long time I try to do the following thing:

Example: I have a button and one led and I want to do when I hit the button to turn led for 5 seconds and go off but this is only when I press the button (HIGH).

I would be very grateful if you help me because this is my only obstacle to accomplish a long year project.

What have you tried so far? It sounds like digitalRead, digitalWrite, delay and an if statement would get you most of the way.

I want when the button is LOW turn on the led for 5 seconds and stop... And this command no repeat only when the button is LOW i try whit delay but no success

You need to show us your code.
Use code tags (# icon on the toolbar)

int led = 13;
int button = 8;
int val = 0;
unsigned long timedelay = millis();
const int interval = 5000;

// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT); 
  pinMode(button, INPUT);  
}

// the loop routine runs over and over again forever:
void loop() {
  val = digitalRead(button);
  
  if (val == LOW){
  if ((millis()-timedelay) > interval){              // wait for a second
  digitalWrite(led, HIGH);
}
}
}

It is best to use a state machine to do this task. Btw, you have pull up resistor on the button?

  if ((millis()-timedelay) > interval){              // wait for a second
  digitalWrite(led, HIGH);
}

Your comment is completely wrong. This code does not wait for anything.

PaulS:

  if ((millis()-timedelay) > interval){              // wait for a second

digitalWrite(led, HIGH);
}



Your comment is completely wrong. This code does not wait for anything.

I try with this but i want this function turn on only when the button is pressed.

I am ready with the code :slight_smile:

const int switchPin = 8;                   // the number of the input pin
int led = 13;
int pezzo = 12;
int breakpoint = 2000;
long startTime; // the value returned from millis when the switch is pressed
long duration;  // variable to store the duration

void setup()
{
  pinMode(switchPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(pezzo, OUTPUT);
  digitalWrite(switchPin, HIGH); // turn on pull-up resistor
  Serial.begin(9600);
}


void loop()
{
  if(digitalRead(switchPin) == LOW){
  digitalWrite(pezzo, HIGH);
  }
  else{
  digitalWrite(pezzo, LOW);
  }
  
  if(digitalRead(switchPin) == LOW)
  {
    digitalWrite(led, HIGH);
     // here if the switch is pressed
     startTime = millis();
     while(digitalRead(switchPin) == LOW){
        ; // wait while the switch is still pressed
        if (millis() - startTime == breakpoint){
          digitalWrite(led, LOW);
      }  
      }
     long duration = millis() - startTime;
     Serial.println(duration);
  }
  
}

I try with this but i want this function turn on only when the button is pressed

Then you should consider removing the incorrect comment.