Skip to content

Arduino: Fade and pulse a LED with just using a DigitalPort

This is a nice experiment I did to fade and pulse a LED by just using a digital port. Digital? On/Off, 1/0 - how can this work? Well it does, check this out:

http://www.youtube.com/watch?v=kB62BrQBjTg

The key is, I’m switching the LED on & off very fast which appears the human eye as it’s on all the time (similar to a LED Matrix). Now, I change the time period between switching the LED on and off. Is the off period time longer, the LED lights low, is the off period time short, the LED lights high. Fading the period time, makes the LED pulse… nice!

Check this (still quite ugly) code:
[c]
int ledPin = 13; // LED connected to digital pin 13
int value = LOW; // previous value of the LED
long cnt = 0; // will store last time LED was updated
long low = 0; // interval at which to blink (milliseconds)
long high = 1000; // interval at which to blink (milliseconds)
int op = 3;
long a = 0;

void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}

void loop()
{
a += op;
blinkl( a+30, 10 );
if( a > 200 || a < 0 ) op *= -1;
}

void blinkl(long low, long high )
{
int c = 5;
while ( c > 0 ) {
blink( low, high );
c-=1;
}
}

void blink( long low, long high )
{
long period = 4000;
long pt = period * high / (low + high );
int value = LOW;
digitalWrite(ledPin, value);

while( period > 0 ) {
if (period < pt && value == LOW ) {
value = HIGH;
digitalWrite(ledPin, value);
}
period -= 1;
}
}
[/c]