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.
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
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);
}
}
}
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);
}
}