I ́m trying to make a pause in a loop, but just for the first time it loops. The next loops i would like the program to NOT do the pause. Just once time, each time a button is pressed. Does anybody knows how to do it? Thanks! This is the code i want to pause just once:
void loop() {
if(digitalRead(switch_pin) == LOW){
digitalWrite(led_green_pin,LOW);
digitalWrite(led_red_pin,HIGH);
lastMotionState = currentMotionState;
currentMotionState = digitalRead(MOTION_SENSOR_PIN); //
if (currentMotionState == LOW && lastMotionState == HIGH) {
servo.write(90);
}
else
if (currentMotionState == HIGH && lastMotionState == LOW) { // pin state change: HIGH -> LOW
servo.write(0);
}
}
2 Answers 2
The following code will pause (Give some delay) when it runs for the first time and also when you press the button.
void loop() {
static int status = true;
if(status){
//Pause
delay(15);
status=false;
return;
}
if(digitalRead(switch_pin) == LOW){
digitalWrite(led_green_pin,LOW);
digitalWrite(led_red_pin,HIGH);
lastMotionState = currentMotionState;
currentMotionState = digitalRead(MOTION_SENSOR_PIN); //
if (currentMotionState == LOW && lastMotionState == HIGH) {
servo.write(90);
}
else if (currentMotionState == HIGH && lastMotionState == LOW) { // pin state change: HIGH -> LOW
servo.write(0);
}
}
else{
status = true;
}
}
Give delay according to your need.
-
3I don't know what that
continue;
line does when there isn't a for/while/do-loop.Gerben– Gerben2021年04月22日 18:10:27 +00:00Commented Apr 22, 2021 at 18:10 -
Better would be
void loop() { static int status = true; ... }
keeping the scope ofstatus
inside ofloop()
instead of global.lurker– lurker2021年04月22日 19:04:21 +00:00Commented Apr 22, 2021 at 19:04 -
1@Gerben and lurker thanks for pointing that out. I have made the changes accordingly. Instead of continue I have added return which will work as desired.HARSH MITTAL– HARSH MITTAL2021年04月23日 07:30:41 +00:00Commented Apr 23, 2021 at 7:30
This is pretty simple, although you shouldn't see any difference, because loop()
is running a lots of times in one second. But:
bool firstrun = true;
void loop() {
if(firstrun == true){};
else{
if(digitalRead(switch_pin) == LOW){
digitalWrite(led_green_pin,LOW);
digitalWrite(led_red_pin,HIGH);
lastMotionState = currentMotionState;
currentMotionState = digitalRead(MOTION_SENSOR_PIN); //
if (currentMotionState == LOW && lastMotionState == HIGH) {
servo.write(90);
}
else if (currentMotionState == HIGH && lastMotionState == LOW) { // pin state change: HIGH -> LOW
servo.write(0);
}
}
}
firstrun = false;
}
Does anybody knows how to do it?
is not a question that asks how to do it ... it is not a question about the arduinopause
? ... that implies that the code would somehow start up again, but you said nothing about what would stop it and what would start it again and where it should "pause"