如何在Arduino的loop()函数中仅执行指定代码段一次?
Hey there! I get exactly what you're trying to do with your water intake monitor—you need most of your loop() code to run continuously (to keep tracking the water level), but that specific LCD print statement should only execute once, right? Using setup() isn’t an option because the code has to live in loop(), and wrapping things in while(1) would freeze the entire loop after one run.
Here’s the most straightforward fix using a boolean flag variable to track whether the one-time code has executed already:
Step 1: Add a Global Flag Variable
First, declare a boolean variable outside of both setup() and loop(). This variable will retain its value between loop iterations because it’s global:
// Add this at the top with your other global variables bool hasPrintedInitialVolume = false;
Step 2: Modify Your loop() Code
Update your loop() to check the flag before running the one-time LCD print. Once it runs once, set the flag to true so it never runs again:
void loop() { // Clear trigPin level digitalWrite(trigPin, LOW); delayMicroseconds(2); // Set trigPin high for 10 microseconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read echoPin, return sound wave travel time (microseconds) duration = pulseIn(echoPin, HIGH); // Convert time to distance in centimeters // Note: Removed the extra 'double' here—you already declared cdist globally! cdist = duration / 29 / 2; // Calculate remaining water volume double volume_of_rem_height = 3.14 * 3 * 3 * cdist; Serial.println(1800 - volume_of_rem_height); // Check if we haven't printed the initial volume yet if (!hasPrintedInitialVolume) { // This code runs ONLY once lcd.print(1800 - volume_of_rem_height); // Set the flag to true so this block never runs again hasPrintedInitialVolume = true; } }
Key Notes:
- Why this works: The global
hasPrintedInitialVolumestarts asfalse. The first timeloop()runs, theifcondition passes, the LCD prints, and we set the flag totrue. Every subsequent loop iteration will skip this block while all other code continues to run normally. - Bug fix: I removed the
doublefromdouble cdist = duration / 29 / 2;in your loop—you already declaredcdistas a global variable, so re-declaring it here would create a local variable that doesn’t update the global one, which was likely causing unexpected behavior!
Alternative (If You Need to Reset the Flag Later)
If you ever need to re-run that one-time code (e.g., when a new day starts), you can simply set hasPrintedInitialVolume = false; again somewhere else in your code (like when a reset button is pressed, or after your 1-hour interval).
内容的提问来源于stack exchange,提问作者Devika Sujith

