If statement 无法使开关改变LED颜色,无论开关是否按下,只要循环所有颜色即可
我正在通过本教程学习如何在Arduino上做一些基本的事情。我想写一个程序,让我能够控制一个3色LED开关,每次按下开关,我希望LED从红色变为绿色变为蓝色。据我所知,循环方法应该一次又一次地运行,以测试开关是否按下。如果已按下,则应增加一个计数器,直到达到2(蓝色)且计数器复位。它的颜色从红色变为绿色再变为蓝色,但当我按下开关时,它只是在它们之间循环,就好像开关总是被按下一样。我的代码如下If statement 无法使开关改变LED颜色,无论开关是否按下,只要循环所有颜色即可,if-statement,arduino,led,If Statement,Arduino,Led,我正在通过本教程学习如何在Arduino上做一些基本的事情。我想写一个程序,让我能够控制一个3色LED开关,每次按下开关,我希望LED从红色变为绿色变为蓝色。据我所知,循环方法应该一次又一次地运行,以测试开关是否按下。如果已按下,则应增加一个计数器,直到达到2(蓝色)且计数器复位。它的颜色从红色变为绿色再变为蓝色,但当我按下开关时,它只是在它们之间循环,就好像开关总是被按下一样。我的代码如下 int ledPin = 13; // LED is connected to digital p
int ledPin = 13; // LED is connected to digital pin 13
int redPin = 11; // R petal on RGB LED module connected to digital pin 11
int greenPin = 9; // G petal on RGB LED module connected to digital pin 9
int bluePin = 10; // B petal on RGB LED module connected to digital pin 10
int switchValue;
int switchPin = 2;
int count = 0;
int red = 255; //red value, initially set at 255
int blue = 0; //blue value, initially set at 0
void setup()
{
pinMode(ledPin, OUTPUT); // sets the ledPin to be an output
pinMode(redPin, OUTPUT); // sets the redPin to be an output
pinMode(greenPin, OUTPUT); // sets the greenPin to be an output
pinMode(bluePin, OUTPUT); // sets the bluePin to be an output
//redtoblue();
}
void loop() // run over and over again
{
if(switchValue == LOW){
if (count == 0){
color(255, 0, 0); // turn the RGB LED red
delay(1000); // delay for 1 second
count += 1; //increment the count
}
else if (count == 1){
color(0,255, 0); // turn the RGB LED green
delay(1000); // delay for 1 second
count += 1; //increment the count
}
else if (count == 2){
color(0, 0, 255); // turn the RGB LED blue
delay(1000); // delay for 1 second
count = 0; // set the count back to 0
}
}
}
void color (unsigned char red, unsigned char green, unsigned char blue) // the color generating function
{
analogWrite(redPin, 255-red);
analogWrite(bluePin, 255-blue);
analogWrite(greenPin, 255-green);
}
您没有读取开关引脚的值,也没有将引脚设置为输入 所以SwitchValue总是很低,而您的条件总是真实的。所以它只是循环