[英]How can I toggle an LED on and off using the arduino serial monitor
I am trying to toggle 3 LED's on and off.我正在尝试打开和关闭 3 个 LED。 So basically input 1 into the serial monitor and LED one will turn on, I have this part done but then when I press 1 again LED one will turn off.所以基本上输入 1 到串行监视器和 LED 之一会打开,我已经完成了这部分但是当我再次按下 1 时 LED 会关闭。 The second part is what im having issues with, I need to create some sort of toggle.第二部分是我遇到的问题,我需要创建某种切换。
Here is my code这是我的代码
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");
}
}
}
digitalWrite(ledPin, !digitalRead(ledPin));
That way you always invert the current pin state.这样,您始终可以反转当前引脚 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.