调用其他函数后,Arduino函数保持循环
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调用其他函数后,Arduino函数保持循环相关的知识,希望对你有一定的参考价值。
我是使用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);
}
以上是关于调用其他函数后,Arduino函数保持循环的主要内容,如果未能解决你的问题,请参考以下文章