我正在尝试编写一个将执行以下操作的程序:
编写代码,如果1然后输入按下或发送点击,然后再次输入1并输入按下或发送点击导致LED 1打开,如果以类似的方式输入'1''0'则LED 1转动关闭,等等LED 2和3,即:'2''1'打开LED 2,'3''0'关闭LED 3。
到目前为止,这是我的代码:
int incomingVal;
int ledPin = 16;
int ledPin2 = 15;
int ledPin3 = 14;
void setup()
{
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
Serial.println("starting");
pinMode(ledPin,OUTPUT);
pinMode(ledPin2,OUTPUT);
pinMode(ledPin3,OUTPUT);
}
void checkForRecvdChar ();
void loop()
{
if (Serial.available() > 0 ) //then chars are in the serial buffer
{
incomingVal = Serial.parseInt();
Serial.print("You entered: ");
Serial.println(incomingVal);
if (incomingVal == 10);//turns off led 1
{
digitalWrite(ledPin, LOW);
}
if (incomingVal == 11);//turns on led 1
{
digitalWrite(ledPin, HIGH);
}
if (incomingVal == 20);//turns off led 2
{
digitalWrite(ledPin2, LOW);
}
if (incomingVal == 21);//turns on led 2
{
digitalWrite(ledPin2, HIGH);
}
if (incomingVal == 30);//turns off led 3
{
digitalWrite(ledPin3, LOW);
}
if (incomingVal == 31);//turns on led 3
{
digitalWrite(ledPin3, HIGH);
}
}
}
现在无论我输入什么组合,它都会打开所有LED
答案 0 :(得分:2)
你的if
语句后面有半冒号,终止了if
语句。因此,所有预期的if
块都会被执行。
例如......
if (incomingVal == 31);//turns on led 3
{
digitalWrite(ledPin3, HIGH);
}
需要
if (incomingVal == 31)
{
digitalWrite(ledPin3, HIGH);
}
答案 1 :(得分:0)
Ok So First It Will Better To Use Switch Case in this Case: 1. You Can Just Use The Same Number To Turn The Led ON and OFF Example: case 1: { if(wFlag == false) { digitalWrite(LED, HIGH); wFlag = true; Serial.println("LED is ON"); } else if (wFlag == true) { digitalWrite(LED, LOW); wFlag = false; Serial.println("LED is OFF"); } break; } 2. The Way You Do It, Your Problem Is Serial Read Gets Only Byte after Byte So When You Press 1 or 11 It Sees 1 Because It is The First one "1" and Then Do Your If Statment. You Can Fix it Like This: while (Serial.available()) { IncomingData = Serial.parseInt(); Temp += String(IncomingData); //Temp String Var } DataIN = Temp.toInt(); //DataIN int Var Temp =""; // Rest The Temp String Switch(DataIN) // Or if(DataIN == 1) { }