Friday, 17 March 2017

Arduino - analogWrite() Command & PWM

 The analogWrite command writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. 
 
Earlier, we learnt how to do digital writes -- where you can set a pin to output HIGH or LOW
There are13 pins that can do this.
 
After a call to analogWrite(), the pin will generate a steady rectangular wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite()) on the same pin.
 
PWM Pins for the uno - 3,5, 6,9,10,11. (the numbers with the ~)
So rather than only being able to out HIGH & LOW voltages as in the digitalWrite command,
the analogWrite command allows us to do voltages between 0V & 5V

 

Syntax

analogWrite(pin, value)

The resistor is 330 ohm


 The code:

--------------------------------------------------------------------

// Variables
int redPin=9; // chooses the pin
int bright=255; // sets the brightness of LED
                // changing number will change the voltage

void setup()
{
  pinMode(redPin,OUTPUT);
}

void loop()
{
  analogWrite(redPin,bright);
  // use a number between 0 and 255
  // 0 = 0V, 255 = 5V, 125 = 2.5V
  // 1, 2, 4, 16, 32,64, 128, 256
  // 2 to the power of 8
  // 258 = 8 bits resolution
 
 
}

--------------------------------


PWM (Pulse width modulation) doesn't give us a true analog voltage.
It is a technique for getting analog results with digital means.
 
It creates square waves  ie, a signal switched between on and off.
If you repeat this on-off pattern fast enough the result is as if the signal is a steady voltage 

By changing the period of time (duty cycle) the signal is on 5V vs the period its on 0V, you get an average of the voltage, and this is your "fake analog voltage".

 
If you really want an analog voltage, you can place a capacitor ... this will smooth that up/down voltage fluctuation.
1000uF is a good value to use.
 (put the -ve of the capacitor to the -ve (ground) & the +ve to +ve)


 ---------------------------------
-------------------------------------
 

No comments:

Post a Comment