Skip to content

pComp: Digital Pulse-Width Modulation of LEDs via Arduino

2008 September 8
by Tedb0t

Day 1 consisted of just plugging the Arduino in to see if it works and transmits properly.  Today, despite an incipient cold (wtf?), I made better headway into learning about the device.

After some initial tests blinking an LED, I decided to make a little sinusoidal pulse-width modulator and blink two LEDs:

Pulse-Width Modulation of LEDs

If you watch it you can see the LEDs blink faster and faster and then slower and slower (the avi’s framerate of ~15 of course interferes with this).  The relevant code is:

blinkFreq = ((sin((i * PI / 180))+1) / 2) * freqMod;
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, LOW);
delay(blinkFreq / 2); 
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, HIGH);
delay(blinkFreq / 2);

where i is incremented in the Arduino loop and reset after 360.  I could have just used radians but then I’d be incrementing a float value or something so… meh.

I’m not sure if there’s a better or more logical PWM algorithm, I haven’t tried looking one up as this basically does the trick.

Related Posts:

Comments are closed.