我是使用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();
}
答案 0 :(得分:1)
试试此代码
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);
}