gpt4 book ai didi

c++ - Arduino函数在调用其他函数后一直循环

转载 作者:行者123 更新时间:2023-11-28 04:52:05 26 4
gpt4 key购买 nike

我是使用 C++ 进行编码的初学者,我一直在尝试通过串行输入使 LED 引脚闪烁,但是当我告诉它关闭时,它一直在闪烁。我认为问题出在代码的底部。

int ledPin = 13;
String readString;

void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
Serial.println("Serial Blinker (Input 'on' to blink and 'off' to stop blinking)");
}
void loop() {
readString = "";
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
readString.trim();
if (readString.length() > 0) {
if (readString == "on") {
Serial.println("switching on");
next();
}
}
}
void next() {
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
readString = "";
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
readString.trim();
if (readString.length() > 0) {
if (readString == "off") {
Serial.println("switching off");
digitalWrite(ledPin, LOW);
}
}
next();
}

最佳答案

试试这段代码

 int ledPin = 13;
String readString;

void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
Serial.println("Serial Blinker (Input 'on' to blink and 'off' to stop blinking)");
}
void loop() {
readString = "";
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
readString.trim();
if (readString.length() > 0) {
if (readString == "on") {
Serial.println("switching on");
next();
}
else if(readString == "off"){
digitalWrite(ledPin, LOW);
}
}
}
void next() {
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
readString = "";
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
readString.trim();

if (readString == "off") {
Serial.print("off");
digitalWrite(ledPin, LOW);
off();
}
else {
next();
}

}

void off(){
Serial.print("in off");
digitalWrite(ledPin, LOW);

}

关于c++ - Arduino函数在调用其他函数后一直循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47959824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com