0
我想通過本教程http://lilypadarduino.org/?page_id=216來學習如何在Arduino上做基本的事情。我想編寫一個程序,讓我用一個開關控制一個3色LED,每次按下開關時,我都希望LED從紅色變成綠色變成藍色。從我所瞭解的循環方法應該一遍又一遍地運行,應該測試以查看是否按下了開關。如果它被按下,那麼它應該增加一個計數器,直到它變爲2(藍色)並且計數器被重置。它將顏色從紅色變爲綠色,而不是當我按下開關時,它只是循環切換,就像開關總是按下一樣。我的代碼如下。無法切換到改變LED顏色,只是循環所有顏色,無論開關是否按下
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);
}