Thursday, July 26, 2012

Using PWM on atmega16


Things u need
  1. A  MCU (atmega16 or atmega8)
  2. A led and/or motor and/or dc fan.

Difficulty Level
Easy from application point of view, a bit typical from programming point of view.

Time Required
If you are using the code given my me, then 1/2 or 1 hour.

Concept
PWM means Pulse Width Modulation.
PWM


Before lettting you what does it mean, let mew ask you a simple question, How to regulate a motor's speed?
You may answer that using a variable resistance, but what if I need to do it by using programming. Here PWM comes in play. One more famous example is  How to show the dimming effect in a led. Again PWM the answer.
What PWM does is that instead of sending a continuous supply of voltage to load (led, motor, dc fan, etc) it sends the supply in PULSE , that’s why the process is called PULSE WIDTH MODULATION.
Now if we have to control the speed of motor or intensity of led then we have to control the WIDTH of the PULSE.

There are two things to learn to use PWM,
  1. Timers
  2. OCR register
There are two internal Timers in atmega8, T0 (pin6, D4) and T1 (pin11, D5) and in atmega16 also T0 (pin1, B0) and T1 (pin2, B1).
These timers once activated run continuously from 0 to 255 (8 bit) as long as the program runs.

There are 3 OCR registers in both atmega8 as well as atmega16.
In atmega8 pin15 is OC1A, pin16 is OC1B, pin17 is OC2.
In atmega16 pin18,19,21 are OC1A,OC1B and OC2 respectively.
The PULSE WIDTH is set by these OCR registers only.
The time upto which MCU will send supply depends on what is value of OCR register.
Suppose the value of OC1A is 128 then while the timer which is running is between 0-128 the MCU will send supply to pin19 (atmega16) or pin15 (atmega8)   and when its between 129-255 the MCU will not send supply to that pin, so the bottom line is that for exactly half time pin is getting the supply and for exactly half time the supply is off, so the effective voltage reduces from 5v to 2.5v. The motor will run slow , the led will dimmed.

Below is the code shown for using PWM
This will make the LED to glow from minimum intensity (OCR1A=0 ) and then the increases  upto highest intensity (OCR1A=255) . You can add delay to increase the time required to complete one cycle.
To get full code download the link.
Download this link which has the required Header Files (timer0.h,timer1.h,timer0.c,timer1.c).



Please Share it! :)

Post a Comment

No comments: