I will use the Arduino Bite Size posts to share small bits of information relating to the Arduino platform.
Today we will be examining the 2 main pin types that are present on Arduino boards. For this article I will be referring to the Arduino UNO R3, however all Arduino boards contain these pin types, just note that the quantities of the different pins do vary greatly between the different boards.
There are 2 main groups of pins on any Arduino Board, Analog and Digital pins.
On this image the Digital pins are highlighted with a red block and the Analog pins with a yellow block.
So what is the difference between the 2 pin types?
Digital pins can read or write 2 possible values HIGH or LOW (1 or 0), whereas Analog pins can read a value between 0 to 1023 and write a value between 0 to 255.
Keeping this in mind it becomes apparent that the main purpose of these pins differ greatly. A Digital PIN can turn an LED on or off, whereas an Analog pin can turn the same LED on to a variety of brightness levels, not just 1. So if you want to simply turn an LED on and off a Digital pin would be the correct pin to use, but for a servo motor signal cable (that controls the movement of a servo motor) an Analog pin would be required as different values (0 to 255) determines how far the servo turns.
This logic also applies when it comes to sensors, for a switch that has 2 states (on and off) a Digital pin would be ideal, however for a IR range sensor it would not work as usually you would like to know a value that represents the distance the sensor is detecting. For this kind of sensor an Analog pin should be used.
So far this all seems pretty straight forward… Now let us consider that some Digital pins can “act” like Analog pins.
You will see by looking at the image on the Arduino above that certain of the Digital pins have ~ next to them. This indicates that the pin is capable of PWM or Pulse Width Modulation. PWM is a method of producing Analog results utilising a Digital means. This is achieved by the Digital pin switching between on and off at a high frequency and thus producing a square wave, where the time in the on state determines the width of the pulses created.
So what does this mean?
If analogWrite(255) is done to a PWM pin it will be in a permanent HIGH (On) state. Whereas analogWrite(0) would place the pin in a permanent LOW (Off) state.
So if analogWrite(127) is done to a PWM pin it will be in a HIGH (On) state roughly 50% of the time and LOW (Off) state for the remaining 50% of the time. The Arduino PWM frequency is 980Hz, which means that the pin will switch between on and off (HIGH and LOW) approximately every 0.00051 seconds for the 50/50 example above.
Note however that although analogWrite works with PWM pins, analogRead does not. To read a PWM signal the pulseIn method should be used. We will cover the pulseIn method at a later time.