You are on page 1of 31

# PWM IMPLEMENTATION

WHAT IS PWM?
PWM (PULSE WIDTH MODULATION)

TIMERS

## TIMER BLOCK DIAGRAM

TIMER OPERATION
1.
2.
3.
4.
5.
6.
7.
8.

ONE SHOT
CONTINUOUS MODE
COUNTER MODE
COMPARATOR COUNTER MODE
PWM MODE
CAPTURE MODE
COMPARE MODE
GATED MODE

PWM SYSTEM
THE TIMER OUTPUTS A PWM SIGNAL THROUGH
A GPIO PORT PIN
THE TIMER INPUT IS THE SYSTEM CLOCK
(18.432 MHz)

PWM ALGORITHM
1. THE TIMER COUNTS UP TO THE 16-BIT PWM
HIGH AND LOW BYTE REGISTERS.
(TxPWMH,TxPWML)
2. WHEN THE TIMER COUNT VALUE MATCHES
THE PWM VALUE, THE TIMER OUTPUT
TOGGLES.
3. THE TIMER CONTINUES COUNTING UNTIL IT
REACHES THE RELOAD VALUE STORED IN THE
TIMER RELOAD HIGH AND LOW BYTE
REGISTERS

PWM ALGORITHM
4. UPON REACHING THE RELOAD VALUE, THE
TIMER GENERATES AN INTERRUPT;THE COUNT
VALUE IN THE TIMER HIGH AND LOW BYTE
REGISTERS IS RESET TO 0001H AND
COUNTING RESUMES.
5. SET THE TIMER I/O POLARITY (TPOL)
REGISTER ENTRY.
0 TIMER OUTPUT SIGNAL BEGIN AS low
1 - TIMER OUTPUT SIGNAL BEGIN AS high

PWM CONFIGURATION

PWM CONFIGURATION

PWM COMPUTATION

## BASIC TIMER OPERATION

count = 1;
while (count<limit)
count++;
count = 1;
Note:
1. the timer counter replaces the count; the timer
2. Both registers are 16-bits wide

PRESCALE SYSTEM
Z8 encore clock - 18.432 MHz
16 bit counter
Problem???
they are not enough to produce significant
delay values.
Solution!!!
Prescaling to slow down the timer clock to
generate longer delays

PRESCALING COMPUTATION
Setting the prescaler to divide by N = 64;
18.432 MHz/64 = 288 kHz
NOTE: prescaler can be set to divide by powers
of 2 from 20 = 1 to 27 = 128

## TIMER 0-3 CONTROL 1 REGISTER

(TxCTL1)

TIMER MODE/OPERATION

TIMER INITIALIZATION
1. Disable the timer
2. Set the mode, prescaler value, and timer
polarity
3. Set the counter start value
5. Setup or disable timer interrupt and ISR
6. Enable timer

## SAMPLE CODE FOR PWM

REQUIREMENT:
Generate a 1-kHz PWM signal with a
50% duty cycle at the PC1 pin.

GIVEN PARAMETERS
1. TIMER 1 configured in PWM mode
2. Reload period of 1ms (freq = 1khz)
3. DUTY CYCLE = 50%

#include <ez8.h>
//PWM period (sec.) = (RELOAD x Prescaler)/system

//clock (Hz)
#define PWM_VALUE 9216

#define TMODE
0x03
//Timer
mode is PWM mode
#define PRESCALER 0x00
//prescaler = 1

DI();
T1CTL &= ~0x80;
//Disable Timer 1
T1CTL |= (0x00 << 3)| 0x03;//Prescaler = 0, PWM mode
T1CTL |= 0x40; //TPOL = 1. PC1/T1OUT output set to
high
//PWM output is initially high and
//toggle to low when PWM_VALUE is
reached

T1H = 0x00;
T1L = 0x01;

//initial value is 1

## T1PWMH = (PWM_VALUE >> 8);

T1PWML = (PWM_VALUE & ~0xFF00);

## T1RH = (RELOAD_VALUE >> 8);

period
IRQ0ENH &= ~0x40;
IRQ0ENL &= ~0x40; //Timer 1 interrupt
disabled

PCDD |= 0x02;
PCAF |= 0x02;

## //PCI/T1OUT pin is output

//turn on alternate function of PC1,

T1CTL |= 0x80;

//Enable Timer1
//After the previous line of code, PWM will
automatically start.
//PWM period is 1 kHz, with 50% duty
cycle

EI();