Arduino串口输入提示重复问题:实现仅打印一次提示并等待输入
Fixing the Repeating Prompt Issue in Your Arduino Code
Got it, let's sort out this problem for you! The root cause of the non-stop "Type something!" messages is that Arduino's loop() function runs continuously—every time it calls your inChar() function, the prompt gets printed all over again. Here's how to adjust the code to only show the prompt once while waiting for user input:
Modified Code
char kbChar; bool promptShown = false; // Tracks if we've already displayed the input prompt void setup() { Serial.begin(9600); } void loop() { inChar(); } void inChar(){ // Only print the prompt if it hasn't been shown yet if(!promptShown){ Serial.println("Type something!"); promptShown = true; } // Check for incoming serial data if(Serial.available()){ kbChar = Serial.read(); Serial.println(kbChar); // Optional: Uncomment this line if you want the prompt to reappear after each input // promptShown = false; } }
What Changed?
- Added a boolean variable
promptShownto keep track of whether we've already displayed the input prompt. This stops the message from being printed every timeloop()runs. - Moved the prompt print statement inside a conditional check: it only runs if
promptShownisfalse, then sets the variable totrueto mark the prompt as displayed. - Included an optional line to reset
promptShownafter a character is received—uncomment this if you want the prompt to come back each time the user finishes typing a character.
Why the Original Code Failed
Your original code had the Serial.println("Type something!") outside any conditional check in inChar(). Since loop() executes thousands of times per second, this line was being called nonstop, resulting in the flood of prompt messages.
内容的提问来源于stack exchange,提问作者Playing with GAS
相关产品推荐
相关产品推荐

