I want to make one-time or once-execution syntax inside a forever loop (void loop) for any programming language.
What I found is the solution is to make a new variable boolean "executed" and set it to true after it is executed.
It's okay, but what if I want to do once execution to other syntax? Should I make a new variable boolean again? It will not be efficient. Imagine there are many syntaxes, but I must make a new bool execution for each syntax.
The solution is function, I think.
For example:
void loop()
{
lcd.print("OK");
}
THIS WILL PRINT FOREVER
I wish there's a function like this:
void loop()
{
once(lcd.print("OK"));
}
so "once" is a function with parameter string which its for command/syntax.
once("command")
Following is a very common way of how such an operation is usual made. As you already suggested, with an global boolean:
bool once = true; // global variable
void loop() {
if (once) { // being called only once
lcd.print("OK");
once = false;
}
}
Do something only once after a specific time:
void loop() {
// millis() is the time in milliseconds after the startup
//if you want to print something once after a specific amount of time
//this also includes a little "wait time" of 100 milliseconds as the statement might be asked with a delay
if (mills() >= 1000 && mills() <= 1100) {// time in milliseconds
lcd.print("OK");
}
}
And thanks to this thread, with exiting the loop (might be not what you are searching for):
void loop() {
lcd.print("OK");
exit(0); //The 0 is required to prevent compile error.
}
But I suppose you are trying to make some kind of an interface, where a specific answer is printed regarding to the user input (probably many possibilities)?! In that case it kind of depends on what inputs you are getting:
In case of Integers:
void loop() {
switch (input) { //input must be an integer
case 0:
lcd.print("OK"); //prints "ok" if input is 0
case 1:
lcd.print("Hello"); //prints "Hello" if input is 1
}
}
In case of Stings/chars, you need to go with an "if loop" trough every possible input(or with an array of Strings/chars):
void loop() {
lcd.print("Turn off?"); //asks if it should do something
if (input == "yes") { //String input
lcd.print("OK, shut down!");
//do something
}
else if (input == 'n' || input == 'N') { //char input
lcd.print("OK, no shut down!");
//do something
}
}
A function you are looking for, where a specific answer only prints ONCE regarding to an input can be just archived by if/else loops. If a String should be just printed once at startup, print it in the "setup()" constructor. Otherwise just with global booleans something like that is possible.
Note that those are only my suggestions based on my experience, but it does not necessarily mean that other solutions are not available. Hope that helps still :)