While there are better ways to do this, as pointed out by other posters, for what you're trying to learn right now, your program (almost!) works just fine. You'll need the more advanced techniques as you progress to more complex programs. But for now, I made a couple of edits to your program to get you going:
- The most important one was to use
analogWrite()
for the PWM LED (LED 9). That makes it fade in and out instead of turn on and off (with a long period).
- I turned one LED on and one off at the same time, getting rid of the dark periods and 400ms of combined delay.
- I doubled the fadeAmount to fade in and out a little faster; it wasn't very visible with an increment of 5.
Here it is with those changes:
int led = 9;
int brightness = 0;
int fadeAmount = 10;
void setup() {
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
pinMode(led, OUTPUT);
}
void loop() {
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
delay(200);
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
delay(200);
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30);
}
Update:
what if i wanted to add a a second led
I'm assuming you mean a fading LED, that it's pretty clear where you'd a blinking one?
Blinking in-phase is easy - write the same brightness
to both. To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED.
But note how your code starts getting more complex as you add components and try to manage them in a single loop, with delay()
s? That's when you'll want to try the Blink Without Delay example, and compare adding new LEDs that way, to adding new LEDs to your current program.