How GPIO pins work

If we look at our last project, we can observe from the code that we're writing values to an Led object in Johnny-Five, and it's changing the state and brightness of an LED. How does this work? While the in-depth details are beyond the scope of this book, we will go a little into how this works; this uses the concept of GPIO, or General-Purpose Input/Output, pins.

A GPIO pin is a pin that provides electric current to or reads electric current from a circuit. In our last project, we used this to provide varying levels of power to our LED. These pins can be configured by users (that's us!) to be used as input (read electric current) or output (provide electric current). For now, we're going to focus on the output pins, of which there are two main types: Digital and PWM.

Digital output pins

Digital output pins are only capable of providing two levels of electric current to our circuits: 1 and 0, HI and LOW, or ON and OFF. This means if we plug an LED into a digital pin, we can only turn it on or off.

However, in our case, when we ran the pulse() method, our LED exhibited varying levels of brightness. What does this mean? This means we used a PWM pin in our previous examples.

PWM output pins

A PWM (Pulse-Width Modulation) pin is capable of sending varying levels of power to our circuit (sort of). The way this works is actually by setting the pin to HIGH and then LOW very quickly in a timed manner, which emulates varying levels of power.

Programmatically, you can set a PWM pin to any value between 0 and 255, inclusive. The value you set the pin to decides how often the pin is set to HIGH; for instance, the value 0 would mean the PWM pin is set to HIGH for 0% of the time. The value 85 is one-third of 255, and would mean the pin is set to HIGH for one-third of the time—this emulates one-third power, or in the case of our LED, one-third brightness.

Our first example uses a PWM pin to show varying degrees of brightness of our LED, but there are nearly infinite uses for PWM pins—as we'll see later in this chapter, we can even make music with them!

How to tell the difference between Digital and PWM pins

How can you check which pins are PWM on a microcontroller? This really depends on the microcontroller you're using. For the Arduino Uno, which we have used in this book, the PWM pins are marked with a ~, or tilde, symbol. This means, on an Uno, the PWM pins are 3, 5, 6, 9, 10, and 11.

How to tell the difference between Digital and PWM pins

Determining the PWM pins on an Arduino Uno

Next, we'll explore the differences between the pins by wiring up several LEDs and playing with the Led API.

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

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