LESSON 06 – ANALOG WRITE

TILDE DIGITAL PINS ONLY

 

The analogWrite() function can only be used with the digital pins that have a ~ symbol beside their number.  On the Arduino UNO, that is pins 3, 5, 6, 9, 10 and 11.

 

PULSE WIDTH MODULATION (PWM)

 

Pulse Width Modulation is a way of using digital to create an analog voltage.  Essentially, the pin switches back and forth between 0 and 1 (which is 0V and 5V).  When done quickly and regularly, the result is an average voltage between 0 and 5 volts.

 

EXAMPLES OF PWM

 

If the PWM is set so that 50% of the time the pin is at 5V, and the rest of the time, its at 0V, then the resulting analog voltage will be 2.5V.

 

Similarly, if the pin spends 75% of its time at 5V and 25% at 0V, then the resulting analog voltage will be 3.75 volts.

 

VOLTAGE SPECIFICATION

 

When specifying the voltage, you will need to use a number between 0 and 255.  The value 0 represents 0V and the number 255 represents 5V.  If you want 2.5V, then you need to use the number 127.

 

CALCULATING A VOLTAGE NUMBER

 

If you want a voltage of 4V, then the number you need to specify can be calculated by using the ratio:

 

4/5 = X/255

 

So, X = 255 * (4/5).

 

X = 204

 

Of course, you can adapt the above approach for any desited voltage.

 

ANALOG WRITE

 

To write an analog voltage to a pin, we use the analogWrite() function.  We do need to specify the pin number and the voltage (out of 255).

 

Here is an example of setting pin 3 to 4V:

 

     analogWrite(3, 204);

 

NOTE: If you use analogWrite on an analog pin, you will not get the result that you would expect.

 

FREQUENCY OF PWM

 

On the Arduino UNO, the frequency used by PWM is 490Hz for pins 3, 9, 10 and 11.  The frequency is 980Hz for pins 5 & 6.

 

ol

TRY THIS…

 

PRACTICE PROGRAM/CIRCUIT 06

 

Connect an LED and a resistor between pin 3 and GND of the Arduino.

 

Inside setup, do the following:

-       Set 3 to 1V

-       Wait for 0.5 seconds

-       Set 3 to 2V

-       Wait for 0.5 seconds

-       Set 3 to 3V

-       Wait for 0.5 seconds

-       Set 3 to 4V

-       Wait for 0.5 seconds

-       Set 3 to 5V

-       Wait for 0.5 seconds

 

ALTERATIONS

 

A)   Make the LED also fade off.

B)   Move your code to the loop() function to make the LED continuously fade on and off.