Hello. I've been having trouble recently with my first arduino code. So my initial goal is to do a countdown (not physically) but that has to stop when a sensing signal from a sensor turns on. In my code, yes it does a countdown, but once I trigger a signal from the sensor, it just keeps on going to zero and resets to ten (looping). Here it is:
const int sen = 7;
const int out = 8;
void setup()
{
Serial.begin(9600);
pinMode(sen, INPUT);
pinMode(out, OUTPUT);
}
void loop()
{
int motion =digitalRead(sen);
if(motion)
{
Serial.println("Signal is detected.");
digitalWrite(out,LOW);
}
else
{
for(int counter=10; counter>=0; counter=counter-1){
String string_W, string_X, string_Y, string_Z;
string_W = "No Signal is Detected.";
string_X = "Ending in ";
int timer = counter;
string_Y = timer;
string_Z = " second/s. ";
string_W.concat(" ");
string_W.concat(string_X);
string_X.concat(" ");
string_W.concat(string_Y);
string_Y.concat(" ");
string_W.concat(string_Z);
Serial.println(string_W);
delay(1000);
if(out, LOW)break;
}
Serial.println("End.");
digitalWrite(out,HIGH);
}
delay(1000);
}
The way your code is written, there are a couple of poor ways to achieve what you want, but if you implemented non-blocking delays, it would be a lot more responsive, and could do other things during the countdown… like blinking LEDS, sounding a buzzer on the final three seconds etc.
As you are a beginner you should use normal words to desribe WHAT you want to do.
If you try it as code there might be bugs because you are not yet familiar with the exact syntax how to code it.
I give an example that is surely different from your intentions but shows the principle:
"if the button is pressed a loop shall repeat printing "Hello World" 20 times"
So please give a normal word description of what you want the code to do.
Of course you can break for-loops. There is another kind of loop for "stop if a signal is detected".
You'll have gathered by now that such an approach won't work. It might work when learning a new spoken language, where the listener gets other cues about what you might mean, and you can have a bit of to-and-fro until some understanding is reached, but not with a dumb computer.
I see you marked post 9 as an actual solution: so that means you're sorted and don't need further help?
Yes. I've come to a conclusion that I still lack knowledge on such programming language and I just head on to application proper. I'll get back for more questions soon, thank you all very much for you help.