You are on page 1of 25

INTRODUCTION

A digital device like a microcontroller can easily work with inputs and outputs that has only two state, on and off. So you can easily use it to control a LED's state i.e. on or off. In the same way you can use it to control any electrical device on/off by using proper drivers (transistor,triac, relays etc). But sometimes you need more than just "on" & "off " control over the device. Like if you wanna control the brightness of a LED (or any lamp) or the speed of DC motor then digital (on/off) signals simply can't do it. This situation is very smartly handled by a technique called PWM or Pulse Width Modulation. PWM is the technique used to generate analogue signals from a digital device like a MCU. Almost all modern MCUs have dedicated hardware for PWM signal generation. In this tutorial we will learn the basics of PWM technique and later on we will see how to implement PWM generation with AVR microcontrollers.

Page 1

PWM : PULSE WIDTH MODULATION


A digital device, like a microcontroller can only generate two levels on its output lines, HIGH=5v and LOW=0V. But what if we want to generate 2.5v or 3.1v or any voltage between 0-5 volt output ? For these kinds of requirement, instead of generating a constant DC voltage output we generate a square wave, which has high = 5V and Low = 0v (See figure 1).

FIG. 1 - A PWM W AVEFORM.

In the figure you can see a PWM signal. As you can see it is just a digital signal (can easily be generated by MCUs). But let me clarify some of its properties.

The signal remains "ON" for some time and "OFF" for some time. Ton = Time the output remains high. Toff = Time the output remains Low. When output is high the voltage is 5v' When output is low the voltage is 0v T = Time Period = Ton + Toff

Page 2

Pulse-width modulation (PWM), or pulse-duration modulation (PDM) is a modulation technique that conforms the width of the pulse, formally the pulse duration, based on a modulator signal information. Although this modulation technique can be used to encode information for transmission, its main use is to allow the control of the power supplied to electrical devices, especially to inertial loads such as motors. The average value of voltage (and current) fed to the load is controlled by turning the switch between supply and load on and off at a fast pace. The longer the switch is on compared to the off periods, the higher the power supplied to the load is. The PWM switching frequency has to be much faster than what would affect the load, which is to say the device that uses the power. Typically switchings have to be done several times a minute in an electric stove, 120 Hz in a lamp dimmer, from few kilohertz (kHz) to tens of kHz for a motor drive and well into the tens or hundreds of kHz in audio amplifiers and computer power supplies. The term duty cycle describes the proportion of 'on' time to the regular interval or 'period' of time; a low duty cycle corresponds to low power, because the power is off for most of the time. Duty cycle is expressed in percent, 100% being fully on. The main advantage of PWM is that power loss in the switching devices is very low. When a switch is off there is practically no current, and when it is on, there is almost no voltage drop across the switch. Power loss, being the product of voltage and current, is thus in both cases close to zero. PWM also works well with digital controls, which, because of their on/off nature, can easily set the needed duty cycle.

Page 3

DUTY CYCLE.
It is defined by

So you can see it is just the percentage of the total time the output was high. In the above figure (Fig. 1) you can see that Ton = Toff = Half of the time period. So the duty cycle is 50%. If the frequency of such wave is sufficiently high (say 500 Hz) the output you get is half of 5v i.e. 2.5 volts. Thus if this output is connected to a motor(by means of suitable drivers) it will run at 50% of its full speed at 5v. The PWM technique utilizes this fact to generate any voltage between two extremes (for example between 0-12volts). The trick is to vary the duty cycle between 0-100% and get same percentage of input voltage to output. Below are some examples of PWM signals of different duty cycle.

FIG. 2- A PWM WAVEFORM. DUTY CYCLE = 12.5% ANALOG VOLTAGE OUT = 12.5% OF VCC (5V) = 0.625 VOLTS
Page 4

FIG. 3- A PWM WAVEFORM. DUTY CYCLE = 75% ANALOG VOLTAGE OUT = 75% OF VCC (5V) = 3.75 VOLTS

So you just saw how we can generate analog voltage levels from a digital system using PWM technique. If the output is provided with an R/C filter you will get a pure DC signals levels instead of square waves. But this isn't required for driving motors or controlling LED's brightness. You can feed the PWM signals directly to then (by directly I mean without the R/C filter and not the drivers (like transistor etc)).

Page 5

AVR TIMERS AN INTRODUCTION


Timers are standard features of almost every microcontroller. So it is very important to learn their use. Since an AVR microcontroller has very powerful and multifunctional timers, the topic of timer is somewhat vast. Moreover there are many different timers on chip. So this section on timers will be multipart. I will be giving basic introduction first.

WHAT IS A TIMER ?
A timer in simplest term is a register. Timers generally have a resolution of 8 or 16 Bits. So a 8 bit timer is 8Bits wide so capable of holding value withing 0-255. But this register has a magical property ! Its value increases/decreases automatically at a predefined rate (supplied by user). This is the timer clock. And this operation does not need CPUs intervention.

FIG.: BASIC OPERATION OF A TIMER. Since Timer works independently of CPU it can be used to measure time accurately. Timer upon certain conditions take some action automatically or inform CPU. One of the basic condition is the situation when timer OVERFLOWS i.e. its counted upto its maximum value (255 for 8 BIT timers) and rolled back to 0. In this
Page 6

situation timer can issue an interrupt and you must write an Interrupt Service Routine (ISR) to handle the event.

FIG.: BASIC OPERATION OF A TIMER.

USING THE 8 BIT TIMER (TIMER0)


The ATmega16 and ATmega32 has three different timers of which the simplest is TIMER0. Its resolution is 8 BIT i.e. it can count from 0 to 255. Note: Please read theInternal Peripherals of AVRs to have the basic knowledge of techniques used for using the OnChip peripherals(Like timer !) The Prescaler The Prescaler is a mechanism for generating clock for timer by the CPU clock. As you know that CPU has a clock source such as a external crystal of internal oscillator. Normally these have the frequency like 1 MHz,8 MHz, 12 MHz or 16MHz(MAX). The Prescaler is used to divide this clock frequency and produce a clock for TIMER. The Prescaler can be used to get the following clock for timer. No Clock (Timer Stop). No Prescaling (Clock = FCPU) FCPU/8 FCPU/64 FCPU/256 FCPU/1024 Timer can also be externally clocked but I am leaving it for now for simplicity.

Page 7

TIMER0 REGISTERS.
As you may be knowing from the article Internal Peripherals of AVRs every peripheral is connected with CPU from a set of registers used to communicate with it. The registers of TIMERs are given below. TCCR0 Timer Counter Control Register. This will be used to configure the timer.

FIG.: TCCR0 - TIMER COUNTER CONTROL REGISTER 0 As you can see there are 8 Bits in this register each used for certain purpose. For this tutorial I will only focus on the last three bits CS02 CS01 CS00 They are the CLOCK SELECT bits. They are used to set up the Prescaler for timer.

Page 8

TCNT0 Timer Counter 0

Timer Interrup Mask Register TIMSK

This register is used to activate/deactivate interrupts related with timers. This register controls the interrupts of all the three timers. The last two bits (BIT 1 and BIT 0) Controls the interrupts of TIMER0. TIMER0 has two interrupts but in this article I will tell you only about one(second one for next tutorial). TOIE0 : This bit when set to 1 enables the OVERFLOW interrupt. Now time for some practical codes !!! We will set up timer to at a Prescaler of 1024 and our FCPU is 16MHz. We will increment a variable count at every interrupt(OVERFLOW) if count reaches 61 we will toggle PORTC0 which is connected to LED and reset count= 0. Clock input of TIMER0 = 16MHz/1024 = 15625 Hz Frequency of Overflow = 15625 /256 = 61.0352 Hz if we increment a variable count every Overflow when count reach 61 approx one second has elapse.

Page 9

PWM SIGNAL GENERATION BY USING AVR TIMERS.


Generation of PWM signals is such a common need that all modern microcontrollers like AVR has dedicated hardware for that. The dedicated hardware eliminates the load of generation of PWM signal from software (thus frees the CPU ). Its like asking the hardware to generate a PWM signal of a specific duty cycle and the task of CPU is over. The PWM hardware with start delivering the required signal from one of its PINs while the CPU can continue with other tasks. In AVR microcontrolers PWM signals are generated by the TIMER units. (See AVR Timer Tutorials) . In this tutorial I will give you the basic idea of how PWM signals are generated by AVR timers. Their are two methods by which you can generate PWM from AVR TIMER0 (for ATmega16 and ATmega32 MCUs). 1. Fast PWM 2. Phase Correct PWM PWM GENERATION FUNDAS We will use the simplest timer, TIMER0 for PWM generation.(Note TIMER0 of ATmega8 cannot be used for PWM generation, these are valid for ATmega16 and ATmega32). In this part we won't be dealing with any code, we would just analyze the concepts. So lets start! We have a 8bit counter counting from 0-255 and the goes to 0 and so on. This can be shown on graph as

Page 10

FIG. 1 - AVR TIMER COUNT SEQUENCE FOR FAST PWM.

The period depends upon the prescalar settings. Now for PWM generation from this count sequence we have a new "friend" named OCR0 (Output Compare Register Zero , zero because its for TIMER0 and there are more of these for TIMER1 & TIMER2). We can store any value between 0-255 in OCR0, say we store 64 in OCR0 then it would appear in the graph as follows (the RED line).

FIG. 2 - AVR TIMER COUNT SEQUENCE FOR FAST PWM WITH OCR0=64

Page 11

So how does this Output Compare Register generates PWM? Well, the answer follows. When the TIMER0 is configured for fast PWM mode,while up counting whenever the value of TIMER0 counter (TCNT0 register) matches OCR0 register an output PIN is pulled low (0) and when counting sequence begin again from 0 it is SET again (pulled high=VCC). This is shown in the figure 3. This PIN is named OC0 and you can find it in the PIN configuration of ATmega32.

FIG. 3- AVR TIMER COUNT SEQUENCE FOR FAST PWM WITH OCR0=64

From the figure you can see that a wave of duty cycle of 64/256 = 25% is produced by setting OCR0=64. You can set OCR0 to any value and get a PWM of duty cycle of (OCR0 / 256). When you set it to 0 you get 0% dutycycle while setting it to 255 you get 100% duty cycle output. Thus by varying duty cycle you can get an analog voltage output from the OC0 PIN.
Page 12

SETTING UP TIMER0 IN FAST PWM MODE


Setting up the TIMER0 in fast pwm mode is very easy and just require one line of code. You only need to deal with one register named TCCR0 (Timer Counter Control Register For Timer 0). You just need to set up various bits in it to get the required setting. The various bits of TCCR0 is given below. TCCR0 This register is used for configuring the TIMER0. See Timer Tutorial for more info. The explanation of various bits of this register is as follows. Bit No Name Initial Val 7 6 5 4 3 2 1 0

FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00 0 0 1 0 0 0 0 0

(Note The Bits in RED are discussed here) WGM - Wave Form Generation Mode The table below shows the various modes supported by TIMER0. We have covered Normal mode in "Timer0 tutorial" and CTC mode in "Timers In compare mode" tutorial. And this tutorial we are interested in Fast PWM mode.

Page 13

Mode WGM00 WGM01 0 1 2 3 0 0 1 1 0 1 0 1

Mode Of Operation Normal PWM Phase Correct CTC Fast PWM

From the table it is clear that for Fast PWM we need mode 3. To get it we must set WGM00=1 and WGM01=1 COM - Compare Output Mode These bits are used to set the Output mode in various Wave form generation mode. For Fast PWM mode these can be used to achieve following output modes. COM01 COM00 0 1 0 1 0 0 1 1 Output Mode Normal Port Operation (OC0 disconnected) RESERVED Non Inverted PWM Inverted PWM

We need the "Non Inverted PWM output mode" so we set COM01=0 and COM00=1

Page 14

CS - Clock Select These are used to set an Input Clock for TIMER. We set them as follows to get Ftimer=F_CPU (i.e. no prescalling). See "Timer Tutorial" for more info. CS02 = 0 CS01 = 0 CS00 = 1 Now the TIMER is in Fast PWM mode to vary its output duty cycle we just need to set the OCR0 (Output Compare Register for Timer 0). For example setting it to 0 will generate PWM with duty cycle 0% (Totally off) while setting it to 128 will generate 50% duty cycle and 255 will generate 100% duty cycle signals. Note: The output waveform is available in the associated Output Compare Pin of the microcontroller. For example for Timer 0 the associated OC pin is OC0. You can find its location from Pin diagram in datasheet. In ATmega16 and ATmega32 it is on PORTB bit 3, i.e. PB3. This pin must be set to output to get the PWM signals.

Page 15

SAMPLE PROGRAM The in the following program we set up TIMER0 in fast pwm mode and use the generated PWM signals to vary the brightness of a LED. This is the simplest program to get you started with PWM signal generation. We start with minimum brightness and increase it gradually and then again reduce it gradually to zero. This process is repeated as long as the system is powered.
#include <avr/io.h> #include <util/delay.h> void InitPWM() { /* TCCR0 - Timer Counter Control Register (TIMER0) ----------------------------------------------BITS DESCRIPTION NO: NAME DESCRIPTION -------------------------BIT 7 : FOC0 Force Output Compare [Not used in this example] BIT 6 : WGM00 Wave form generartion mode [SET to 1] BIT 5 : COM01 Compare Output Mode [SET to 1] BIT 4 : COM00 Compare Output Mode [SET to 0] BIT 3 : WGM01 Wave form generartion mode [SET to 1] BIT 2 : CS02 Clock Select [SET to 0] BIT 1 : CS01 Clock Select [SET to 0] BIT 0 : CS00 Clock Select [SET to 1] The above settings are for -------------------------Timer Clock = CPU Clock (No Prescalling) Mode = Fast PWM PWM Output = Non Inverted */

TCCR0|=(1<<WGM00)|(1<<WGM01)|(1<<COM01)|(1<<CS00); //Set OC0 PIN as output. It is PB3 on ATmega16 ATmega32 DDRB|=(1<<PB3); }


Page 16

/****************************************************************** Sets the duty cycle of output. Arguments --------duty: Between 0 - 255 0= 0% 255= 100% The Function sets the duty cycle of pwm output generated on OC0 PIN The average voltage on this output pin will be duty Vout= ------ x 5v 255 This can be used to control the brightness of LED or Speed of Motor. *********************************************************************/ void SetPWMOutput(uint8_t duty) { OCR0=duty; }

/******************************************************************** Simple Wait Loop *********************************************************************/ void Wait() { _delay_loop_2(3200); }

Page 17

void main() { uint8_t brightness=0; //Initialize PWM Channel 0 InitPWM(); //Do this forever while(1) { //Now Loop with increasing brightness for(brightness=0;brightness<255;brightness++) { //Now Set The Brighness using PWM SetPWMOutput(brightness); //Now Wait For Some Time Wait(); } //Now Loop with decreasing brightness for(brightness=255;brightness>0;brightness--) { //Now Set The Brighness using PWM SetPWMOutput(brightness); //Now Wait For Some Time Wait(); } } }

Page 18

Hardware Setup
To run and test this program you need an AVR MCU (ATmega16 or ATmega32)(ATmega8 won't work!). To keep the hardware simple we will use the MCU with internal 1MHz oscillator (this is default factory setting for new MCUs). We will add a good quality RED LED to output compare pin (OC0) of the MCU. This is PIN no 4 on ATmega16/32 Micros. Vcc PIN (pin 10) is connected to +5v and Gnd PIN(pin 11,31) is connected to gnd. This is not show in diagram.

Fig. 1 - A PWM controlled LED


Page 19

ATMEGA16
ATmega16 is an 8-bit high performance microcontroller of Atmels Mega AVR family with low power consumption. Atmega16 is based on enhanced RISC (Reduced Instruction Set Computing) architecture with 131 powerful instructions. Most of the instructions execute in one machine cycle. Atmega16 can work on a maximum frequency of 16MHz. ATmega16 has 16 KB programmable flash memory, static RAM of 1 KB and EEPROM of 512 Bytes. The endurance cycle of flash memory and EEPROM is 10,000 and 100,000, respectively. ATmega16 is a 40 pin microcontroller. There are 32 I/O (input/output) lines which are divided into four 8-bit ports designated as PORTA, PORTB, PORTC and PORTD. ATmega16 has various in-built peripherals like USART, ADC, Analog Comparator, SPI, JTAG etc. Each I/O pin has an alternative task related to in-built peripherals. The following table shows the pin description of ATmega16

Page 20

Pin Diagram:

Page 21

Applications
Telecommunications In telecommunications, PWM is a form of signal modulation where the widths of the pulses correspond to specific data values encoded at one end and decoded at the other. Pulses of various lengths (the information itself) will be sent at regular intervals (the carrier frequency of the modulation). The inclusion of a clock signal is not necessary, as the leading edge of the data signal can be used as the clock if a small offset is added to the data value in order to avoid a data value with a zero length pulse. Power delivery PWM can be used to control the amount of power delivered to a load without incurring the losses that would result from linear power delivery by resistive means. Potential drawbacks to this technique are the pulsations defined by the duty cycle, switching frequency and properties of the load. With a sufficiently high switching frequency and, when necessary, using additional passiveelectronic filters, the pulse train can be smoothed and average analog waveform recovered. High frequency PWM power control systems are easily realisable with semiconductor switches. As explained above, almost no power is dissipated by the switch in either on or off state. However, during the transitions between on and off states, both voltage and current are nonzero and thus power is dissipated in the switches. By quickly changing the state between fully on and fully off (typically less than 100 nanoseconds), the power dissipation in the switches can be quite low compared to the power being delivered to the load.
.

Page 22

Voltage regulation PWM is also used in efficient voltage regulators. By switching voltage to the load with the appropriate duty cycle, the output will approximate a voltage at the desired level. The switching noise is usually filtered with an inductor and a capacitor. One method measures the output voltage. When it is lower than the desired voltage, it turns on the switch. When the output voltage is above the desired voltage, it turns off the switch. Audio effects and amplification PWM is sometimes used in sound (music) synthesis, in particular subtractive synthesis, as it gives a sound effect similar to chorus or slightly detuned oscillators played together. (In fact, PWM is equivalent to the difference of two sawtooth waves with one of them inverted. [1]) The ratio between the high and low level is typically modulated with a low frequency oscillator. In addition, varying the duty cycle of a pulse waveform in a subtractivesynthesis instrument creates useful timbral variations. Some synthesizers have a duty-cycle trimmer for their square-wave outputs, and that trimmer can be set by ear; the 50% point (true square wave) was distinctive, because even-numbered harmonics essentially disappear at 50%. Pulse waves, usually 50%, 25%, and 12.5%, make up the soundtracks of classic video games. A new class of audio amplifiers based on the PWM principle is becoming popular. Called "Class-D amplifiers", they produce a PWM equivalent of the analog input signal which is fed to theloudspeaker via a suitable filter network to block the carrier and recover the original audio. These amplifiers are characterized by very good efficiency figures ( 90%) and compact size/light weight for large power outputs. For a few decades, industrial and military PWM amplifiers have been in common use, often for driving servo motors. Field-gradient coils in MRI machines are driven by relatively high-power PWM amplifiers.
Page 23

References
SEMINAR TOPIC FROM : www.edufive.com/projecttopics.html

http://www.google.com www.extremelectronics.com http://www.Wikipedia.com

Page 24

Page 25

You might also like