I have been trying to get an LED string that is Red Blue Purple to cycle through the colors and I FINALLY found some code that does what I want. Now I could really use some help as to why it works instead of an if or if/else statements...
Here's the working code:
/*
Fading
This example shows how to fade an LED using the analogWrite() function.
The circuit:
* LED attached from digital pin 9 to ground.
Created 1 Nov 2008
By David A. Mellis
modified 30 Aug 2011
By Tom Igoe
http://arduino.cc/en/Tutorial/Fading
This example code is in the public domain.
*/
int ledPin = 9; // LED connected to digital pin 9
int ledPin2 = 11; // LED connected to digital pin 11
void setup() {
}
void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin2, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade out from max to min in increments of 5 points:
for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade out from max to min in increments of 5 points:
for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin2, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
One thing is I don't understand why the pins don't have to be specified as an OUTPUT and also IS there a way to do this inside a loop with using if statements. I haven't made it as far in the tutorials as for statements but I get the general idea. What I did by myself was this:
int bluePin = 9; //PWM pin for Blue light
int redPin = 11; //PWM pin for Red light
int redLevel = 0;
int blueLevel = 0;
void setup() {
// set pins for PWM output to control brightness & fading
pinMode(bluePin, OUTPUT);
pinMode(redPin, OUTPUT);
}
void loop() //Designed to fade from Red to Purple to Blue
{
analogWrite(redPin, redLevel);
redLevel = redLevel + 51;
delay(500);
if (redLevel == 255)
{
analogWrite(bluePin, blueLevel);
blueLevel = blueLevel + 51;
delay(500);
}
}
However it never gets to the blue lights, just cycles through the red> I was even trying to mess around with else statements and switch/case statements but alas... I'm a newb and it didn't make sense. Could someone please explain to me why the first code works and the if statements I tried failed miserably... every time...