This is part 4 in my Sunfounder Superkit series.

In our last experiment, you were probably bedazzled by the alluring display of LEDs.  This time around, we'll go from bedazzling to mesmerizing and use sweet technological magic to make an LED breathe.

via GIPHY

Admittedly, not that kind of magic.  Lucky for you, I'm taking big risks, breaking the Magician's Code and revealing the secret behind the trick: Pulse Width Modulation.

Pulse Width Modulation (PWM)

To get a good understanding of what the heck this bad girl is, let's sprint down history lane and attempt to reproduce our results analog style.  Before the wonderful invention of PWM, most electrical signals were handled continuously by analyzing voltage over time.  

via GIPHY

As you might imagine, this can lead to huge wastes in energy while constantly having to check for changes to the output voltage.  Most electronic applications will likely not need this continuous stream of signal, and to take advantage of this, the GPIO pins on the Raspberry Pi rely on digital signals.  Instead of treating the signal as a continuous stream, digital signals stream a sequence of discrete values.

via GIPHY

Ok, so where the hell does Pulse Width Modulation come in!?  PWM  takes advantage of these digital signals by rapidly turning the voltage off and then turning them on again to a slightly higher or lower voltage.  In our example, this choppy signal will simulate a smooth increase in voltage (LED getting brighter) or decrease in voltage (LED getting dimmer).

Credit: https://www.instructables.com/id/Fade-LED-Arduino-Analog-Output-Tinkercad/

PWM with Ruby!

Ok, enough with the circuits already, and on to the fun part: Ruby!  Luckily for us, the rpi_gpio gem comes with PWM built-in.  With a little elbow grease we can start the mesmerization process.

Wrap Up

We're really starting to dive into the embedded systems waters here.  PWM is a great way to finely control things we want to... modulate.  I'm out of ideas for alternatives on this one, but next time we'll take LEDs to new colored dimensions and I'll invent the simplest of games :-)