FADING LED

Hello Everyone !!!

I have written a program for led fading . The program is as below

int value = 0; // variable to keep the actual value
int ledpin = 9; // light connected to digital pin 9

void setup()
{
// nothing for setup
}

void loop()
{
for(value = 0 ; value <= 255; value+=5) // fade in (from min to max)
{
analogWrite(ledpin, value); // sets the value (range from 0 to 255)
delay(30); // waits for 30 milli seconds to see the dimming effect
}
for(value = 255; value >=0; value-=5) // fade out (from max to min)
{
analogWrite(ledpin, value);
delay(30);
}
}

Now the problem is that when I change the ledpin from 9 to Analog pins , I am not getting the fading infact the led was not at all lit .
So , am I missing anything here ? Also can we give any other voltage except 0 and 5V using digitalWrite program .
Also can we use analog pins as PWM pins ??
Please reply ...

Hello and welcome :slight_smile:

Analog pins are inputs. If you lack PWM pins, you can use the SoftPWM library to use any digital pin as a PWM (and the analog pins can be set to work as digital outputs).

Thank You GUIX

But we can use analog pins as digital outputs also , right ? (using digitalWrite)
Can we use digitalWrite for assigning any value between 0 to 5V like in the case of analogWrite fn used in PWM pins ?

As the analogWrite page says:

The analogWrite function has nothing to do with the analog pins or the analogRead function.

You can use analogWrite on PWM pins only. For the other pins, you must use the SoftPWM library. DigitalWrite is only for HIGH or LOW logic level :wink:

But we can use analog pins as digital outputs also , right ? (using digitalWrite)
Can we use digitalWrite for assigning any value between 0 to 5V like in the case of analogWrite fn used in PWM pins ?

If you remember to set the pinMode for an analogue pin as OUTPUT, you can do an analogWrite to it, but it will only set the pin LOW if the PWM value you write is less than 128, otherwise, it sets it HIGH - it is not possible to do hardware-driven PWM on the analogue pins.