输入A10000,让led灯亮灭10秒,输入B0led灯灭,我输入第一A10000后,在十秒亮灭时间中,在输入2000时没有反应。我想输入一次后,再次输入2000,自动更新led灯的亮灭时间。延时哪里该怎么写?int ledPin = 8;
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
pinMode(ledPin,OUTPUT);
}
void loop() {
// 换行符到达时条件为真:
if (stringComplete) {
long result = 0; //程序执行秒数
char charOne = (char) inputString.charAt(0);//返回字符串中第一个字符
String subString = inputString.substring(1);//从截取字符串
Serial.print("截取字符串的值:");
Serial.println(subString);
int timeNumber = subString.toInt(); //返回字符串中数字为整数
if(charOne == 'A'){ //当字符等于A时闪亮
while(result >= timeNumber ){
long start1 = millis(); //millis();返回程序当前运行的毫秒数
digitalWrite(ledPin,HIGH);
delayMicroseconds(100000);
digitalWrite(ledPin,LOW);
delayMicroseconds(100000);
int end1 = millis();
long ms = end1-start1; //一次循环的毫秒数
result = result + ms; //总秒数
}
}else if(charOne == 'B'){ //当等于B是设置为灯灭
digitalWrite(ledPin,LOW);
}
// clear the string:
inputString = "";
stringComplete = false;
}else{ //没有输入时执行
Serial.println("当前没有输入指令!请输入:");
// digitalWrite(ledPin,HIGH); //led常亮
}
}
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
|