How do PWM pins work?

You don't always want an LED to at its full brightness, especially in the case of RGB LEDs, where the brightness of each channel (red, green, and blue) determines the perceived color of the LED. The pins on most microcontrollers are digital: they are either HIGH at 5V or LOW at 0V. So how do you adjust the brightness of an LED with these types of pins? The answer involves the idea of average voltage and the speed at which we can flip a digital pin from HIGH to LOW. 

Pulse-width modulation, or PWM, pins operate by setting, effectively, the percentage of time that a pin is HIGH and LOW. The following screenshot shows an oscilloscope reading for the state of a pin running at 50% over a short period of time:

Oscilloscope reading for a 50% PWM pin

Instead of the LED flickering on and off, this results in the LED appearing to glow at half-brightness: this is because the human eye cannot keep up with the speed of the state changes, and sees the LED as on, but dimmed. This helps us to use RGB LEDs to create thousands of different colors by combining a red, green, and blue channel at varying degrees of brightness.

When we set the colors in our Johnny-Five code, we can pass values from 0 to 255 for red, green, and blue. This works well with web hex colors, which use the same range. In general, you can set a PWM pin from 0 to 255 (with some exceptions outside the scope of this book).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.1.239