这是我的代码:
const int RED = 11;
const int GRN = 10;
const int BLU = 9;
String inputString = "";
boolean stringComplete = false;
void setup() {
Serial.begin(9600);
pinMode(RED, OUTPUT);
pinMode(GRN, OUTPUT);
pinMode(BLU, OUTPUT);
inputString.reserve(256);
// I'm using a common-anode led,
//so HIGH and LOW works in reverse
digitalWrite(RED, HIGH);
digitalWrite(GRN, HIGH);
digitalWrite(BLU, HIGH);
}
void loop() {
if(stringComplete) {
inputString.toLowerCase();
Serial.println("received " + inputString);
matchString(inputString, 500);
inputString = "";
stringComplete = false;
}
}
void serialEvent() {
while(Serial.available()) {
char inChar = (char) Serial.read();
inputString += inChar;
if(inChar == '\n')
stringComplete = true;
}
}
void matchString(String input, int duration) {
if(containsString(input,"red")) {
colour(RED, duration);
Serial.write("input matched red\n"); // added for debugging
}
else if(containsString(input, "green")) {
colour(GRN, duration);
Serial.write("input matched green\n");
}
else if(containsString(input, "blue")) {
colour(BLU, duration);
Serial.write("input matched blue\n");
}
else {
delay(duration);
Serial.write("input didn't match anything\n");
}
}
void colour(int pin, int duration) {
digitalWrite(pin, LOW);
delay(duration);
digitalWrite(pin, HIGH);
}
// added for later implementation
void colour(int pin1, int pin2, int duration) {
digitalWrite(pin1, LOW);
digitalWrite(pin2, LOW);
delay(duration);
digitalWrite(pin1, HIGH);
digitalWrite(pin2, HIGH);
}
// attempt to implement String.contains
boolean containsString(String input, String search) {
int max = input.length() - search.length();
for(int i = 0; i <= max; i++) {
if(input.substring(i) == search)
return true;
}
return false;
}
我不确定这里出了什么问题,我知道它读取字符流,但它总是写input didn't match anything
回给我,使 LED 保持不亮...
我在这里做错了什么?