我正在尝试打开和关闭3个LED。因此,基本上将1输入到串行监视器中,并且LED指示灯将亮起,我完成了这一部分,但是当我再次按下1时,LED指示灯将熄灭。第二部分是我遇到的问题,我需要创建某种切换。
这是我的代码
const int greenPin = 2;
const int yellowPin = 3;
const int redPin = 4;
void setup()
{
pinMode(greenPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(redPin, OUTPUT);
Serial.begin(9600);
while (!Serial);
Serial.println("Input 1 to Turn LED on and 2 to off");
}
void loop() {
if (Serial.available())
{
int state = Serial.parseInt();
if (state == 1)
{
digitalWrite(greenPin, HIGH);
digitalWrite(yellowPin, LOW);
digitalWrite(redPin, LOW);
Serial.println("Command completed LED turned ON");
}
if (state == 2)
{
digitalWrite(greenPin, LOW);
digitalWrite(yellowPin, HIGH);
digitalWrite(redPin, LOW);
Serial.println("Command completed LED turned OFF");
}
if (state == 3)
{
digitalWrite(greenPin, LOW);
digitalWrite(yellowPin, LOW);
digitalWrite(redPin, HIGH);
Serial.println("Command completed LED turned OFF");
}
}
}
答案 0 :(得分:0)
digitalWrite(ledPin, !digitalRead(ledPin));
那样,您总是会反转当前的引脚状态。