我正在使用 MIT App Inventor 创建多个电灯开关。每当我从交换机发送文本时,串行监视器都会在不同的行上打印该单词的每个字母。我怎样才能将其更改为整个文本,例如在显示新行文本之前“1on”?
const int led1 = 2;
const int led2 = 3;
const int led3 = 4;
char v = 0;
void setup() {
Serial.begin(9600);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
v = Serial.read();
Serial.println(v);
// Serial.print('\n');
if (v == 'a') {
digitalWrite(led1, HIGH);
} else if (v == 'b') {
digitalWrite(led1, LOW);
}
if (v == 'c') {
digitalWrite(led2, HIGH);
} else if (v == 'd') {
digitalWrite(led2, LOW);
}
if (v == 'e') {
digitalWrite(led3, HIGH);
} else if (v == 'f') {
digitalWrite(led3, LOW);
}
}
}
第 5 行使用 String 或 char 数组,第 16 行使用 readString() 函数读取所有内容。链接
const int led1 = 2;
const int led2 = 3;
const int led3 = 4;
String v = 0; /* use String or char array */
void setup() {
Serial.begin(9600);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
v = Serial.readString(); /* use readString() function to read all */
Serial.println(v);
// Serial.print('\n');
if (v == "1on") {
digitalWrite(led1, HIGH);
} else if (v == "1off") {
digitalWrite(led1, LOW);
}
else if (v == "2on") {
digitalWrite(led2, HIGH);
} else if (v == "2off") {
digitalWrite(led2, LOW);
}
else if (v == "3on") {
digitalWrite(led3, HIGH);
} else if (v == "3on") {
digitalWrite(led3, LOW);
}
}
}