Hardware Reference
In-Depth Information
set the RGB LED to the next state in the color cycle. In the following program
(see Listing 2-6), I have defined seven total color states, plus one off state for the
LED. Using the analogWrite() function, you can choose your own color-mixing
combinations. The only change to the loop() from the previous example is that
instead of flipping a single LED state, an LED state counter is incremented each
time the button is pressed, and it is reset back to zero when you cycle through
all the options. Upload this to your Arduino connected to the circuit you just
built and enjoy your nightlight. Modify the color states by changing the values
of analogWrite() to make your own color options.
Listing 2-6: Toggling LED Nightlight—rgb_nightlight.ino
const int BLED=9; //Blue LED on Pin 9
const int GLED=10; //Green LED on Pin 10
const int RLED=11; //Red LED on Pin 11
const int BUTTON=2; //The Button is connected to pin 2
boolean lastButton = LOW; //Last Button State
boolean currentButton = LOW; //Current Button State
int ledMode = 0; //Cycle between LED states
void setup()
{
pinMode (BLED, OUTPUT); //Set Blue LED as Output
pinMode (GLED, OUTPUT); //Set Green LED as Output
pinMode (RLED, OUTPUT); //Set Red LED as Output
pinMode (BUTTON, INPUT); //Set button as input (not required)
}
/*
* Debouncing Function
* Pass it the previous button state,
* and get back the current debounced button state.
*/
boolean debounce(boolean last)
{
boolean current = digitalRead(BUTTON); //Read the button state
if (last != current) //if it's different...
{
delay(5); //wait 5ms
current = digitalRead(BUTTON); //read it again
}
return current; //return the current value
}
/*
* LED Mode Selection
* Pass a number for the LED state and set it accordingly.
*/
void setMode(int mode)
Search WWH ::




Custom Search