0% found this document useful (0 votes)
24 views

C7

Uploaded by

Sơn Đinh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

C7

Uploaded by

Sơn Đinh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Chapter 7

TIMER/ COUNTER/ PWM STRUCTURE


TIMER
Measuring time: Timers are used to measure time in applications such as speed measurement, response time
measurement, waiting time measurement, time between events measurement, etc.
Frequency control: Timers are used to generate pulse signals with fixed or variable frequencies, which are used to
control peripheral devices such as motors, light bulbs, speakers, etc.
Communication: Timers are used to generate pulse signals for data communication between devices, as in protocols
such as UART, SPI, I2C, etc.
Display: Timers are used to scan LED lights to display numbers or characters on LED, LCD screens, etc.
Accuracy checking: Timers are used to check the accuracy of quartz crystals or other frequency sources.
Scheduling: Timers are used to set schedules for applications such as clocks, alarms, etc. Protection: Timers are used
to monitor system activities and protect them from errors such as overcurrent, overload.
TIMER
Timer là một chức năng quan trọng của vi điều khiển và có nhiều ứng dụng khác nhau trong các hệ thống
điện tử và các ứng dụng lập trình nhúng. Sau đây là một số ứng dụng của timer:

1.Đo thời gian: Timer được sử dụng để đo thời gian trong các ứng dụng như đo tốc độ, đo thời gian phản hồi,
đo thời gian chờ, đo thời gian giữa các sự kiện, vv.
2.Điều khiển tần số: Timer được sử dụng để tạo ra các tín hiệu xung với tần số cố định hoặc biến đổi, được
sử dụng để điều khiển các thiết bị ngoại vi như động cơ, bóng đèn, loa, vv.
3.Giao tiếp: Timer được sử dụng để tạo ra các tín hiệu xung để truyền thông dữ liệu giữa các thiết bị, như
trong các giao thức như UART, SPI, I2C, vv.
4.Hiển thị: Timer được sử dụng để quét các đèn LED để hiển thị các số hoặc ký tự trên các màn hình LED,
LCD, vv.
5.Kiểm tra độ chính xác: Timer được sử dụng để kiểm tra độ chính xác của các thạch anh hoặc các nguồn
tần số khác.
6.Lập lịch: Timer được sử dụng để thiết lập lịch cho các ứng dụng như đồng hồ, báo thức, vv.
7.Bảo vệ: Timer được sử dụng để giám sát các hoạt động của hệ thống và bảo vệ chúng khỏi các lỗi như quá
dòng, quá tải.
Counter mode and Timer mode
• There are counter registers in microcontrollers to count an
event or generate time delays.
• When we connect the external event source to the clock pin
of the counter register. This is counter mode.
• When we connect the oscillator to the clock pin of the
counter. This is timer mode
• one way to generate a time delay is to clear the counter at
the start time and wait until the counter reaches a certain
number.
Counter mode and Timer mode
• In the microcontrollers, there is a flag for each of the
counters. The flag is set when the counter overflows, and
is cleared by software.
• The second method to generate a time delay is to load
the counter register and wait until the counter overflows
and the flag is set.
• In ATmega32,ATmega16, there are three timers: Timer0,
Timer1, and Timer2. TimerO and Timer2 are 8-bit, while
Timer1 is 16-bit.
• In AVR, for each of the timers, there is a TCNTn
(timer/counter) register. In ATmega32 we have TCNTO,
TCNT1, and TCNT2.
• The TCNTn register is a counter. Upon reset, the TCNTn
contains zero. It counts up with each pulse. The contents
of the timers/ counters can be accessed using the
TCNTn. You can load/read a value into the TCNTn register
Basic Registers of Timers
• Each timer has a TOVn
(Timer Overflow) flag, When a
timer overflows, its TOVn flag is
set.
• Each timer also has the TCCRn
(timer/counter control register)
register for setting modes(timer
or counter) of operation.
• Each timer also has an OCRn
(Output Compare Register). The
content of the OCRn is
compared with the content of
the TCNTn. When they are
equal the OCFn (Output
Compare Flag) flag is set.
Timer0 Programming
• Timer0 is 8-bit in ATmega32; thus, TCNT0 (timer/ counter
register) is 8-bit.

• TCCRO (Timer/Counter Control Register) register is an 8-bit


register used for control of Timer0.
• CS02:CS00 (Timer0 clock source)
• These bits in the TCCRO register are used to choose the
clock source. If CS02:CS00 = 000, then the counter is
stopped. If CS02:CS00 have values between 001 and 101,
the oscillator is used as clock source and the timer/counter
acts as a timer. In this case, the timers are often used for
time delay generation. If CS02:CS00 are 110 or 111, the
external clock source is used and it acts as a counter
Bit D7 D6 D5 D4 D3 D2 D1 D0
FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00
Read/Write W RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0
FOC0 D7 Force compare match: this is a write-only bit, which can be used while generating a wave. Writing 1 to
it causes the wave generator to act as if a compare match had occurred.
WGM00, WGM01 D6 D3 Timer0 mode selector bits
0 0 Normal

0 1 CTC (Clear Timer on Compare Match)

1 0 PWM, Phase Correct

1 1 Fast PWM

COM01 COM00 D5 D4 Compare Output Mode:


These bits control the waveform generator (See chapter 15)

CS02 CS01 CS00 D2 D1 D0 Timer0 Clock Selector


0 0 0 No clock source (Timer/Counter stopped)
0 0 1 CLK (No Pre-scaling)

0 1 0 CLK / 8

0 1 1 CLK / 64
1 0 0 CLK / 256
1 0 1 CLK / 1024

1 1 0 External clock source on T0 pin. Clock on falling edge


1 1 1 External clock source on T0 pin. Clock on rising edge
WGM01:WGM00
• Timer0 can work in four different modes: Normal,
phase correct PWM, CTC, and Fast PWM. The
WGM01 and WGMOO bits are used to choose one of
them.
Timer0 Programming
TIFR (Timer/counter Interrupt Flag Register)
• The TIFR contains the flags of different timers.
Bit D7 D6 D5 D4 D3 D2 D1 D0
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0
Read/Write RW RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0

TOV0 D0 Timer0 Overflow Flag bit

0= Timer0 did not overflow

1= Timer 0 has overflowed (going from 0xFF to 0x00)

OCF0 D1 Timer0 Output Compare flag bit


0= Compare match did not occur
1= Compare match occurred
TOV1 D2 Timer1 Overflow Flag bit
OCF1B D3 Timer1 Output Compare B match flag
OCF1A D4 Timer1 Output Compare A match flag
ICF1 D5 Input Capture Flag
TOV2 D6 Timer2 Overflow Flag
OCF2 D7 Timer2 Output Compare match flag
Timer0 Programming
TOV0 (Timer0 Overflow)
• The flag is set when the timer rolls over from FF to 00. The
TOV0 flag is set to 1 and it remains set until the software
clears it.
• The strange thing about this flag is that in order to clear it
we need to write 1 to it.
• Indeed this rule applies to all flags of the AVR chip. In AVR,
when we want to clear a given flag of a register we write 1 to
it and 0 to the other bits.
Normal mode
• In this mode, the content of the timer/counter increments
with each clock. It counts up until it reaches its max of FF.
When it rolls over from FF to 00, it sets high a flag bit called
TOV0 (Timer Overflow).
Steps to program Timer0 in Normal mode
1. Load the TCNT0 register with the initial count value.
2. Load the value into the TCCR0 register, indicating which
mode (8-bit or 16-bit) is to be used and the prescaler option.
When you select the clock source, the timer/counter starts
to count, and each tick causes the content of the
timer/counter to increment by 1.
3. Keep monitoring the timer overflow flag (TOVO) to see if it is
raised. Get out of the loop when TOVO becomes high.
4. Stop the timer by disconnecting the clock source, using the
following instructions:
5. Clear the TOVO flag for the next round.
6. Go back to Step 1 to load TCNT0 again.
LET’S CODE IT!
toggle bits of PORTB continuously with
some delay
Registers Related to Timer0
• TCNT2 register - the number of pulse Timer2 counts
bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0

 OCR2 register - the value with which the comparison is


made bit6
bit7 bit5 bit4bit7 bit3 bit2 bit1 bit0

 TIMSK register – all INTERRUPT ENABLE BITS (all Timers)


OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 OCIE0 TOIE0

 TIFR registers - all INTERRUPT FLAGS (all Timers)


OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0
TIFR (Timer/Counter) Interrupt Flag
Register
TIFR Register
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0

Timer 2 Timer 1 Timer 0


TOV0 Timer0 flag bit; 0- did not overflow, 1-has overflowed (FF->00)
OCF0 Timer0 output compare flag bit; 0-did nor match, 1-matched
TOV1 Timer1 flag bit;
OCF1B Timer 1 output compare B match flag
OCF1A Timer 1 output compare A match flag
ICF1 Input Capture flag
TOV2 Timer2 flag bit
OCF2 Timer2 output compare flag bit
TIMSK Register
OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 OCIE0 TOIE0

TOIE0 Timer0 Overflow Interrupt Enable


OCIE0 Timer0 Output Compare Interrupt Enable
TOIE1 Timer1 Overflow Interrupt Enable;
OCIE1BTimer 1 Output Compare B match Interrupt Enable
OCIE1A Timer 1 Output Compare A match Interrupt Enable
TICIE1 Timer/Counter1, Input Capture Interrupt Enable
TOIE2 Timer2 Overflow interrupt Enable
OCIE2 Timer2 output compare Interrupt Enable
Timer2 Programming
• Timer2 is very similar to Time0, both being 8-bit timers.
• But there are two distinct differences between the two.
• Timer2 can be connected to real time counter. For that, we
should connect a crystal of 32.768 kHz to TOSC1 and TOSC2
terminals and set AS2 bit of ASSR register.
• Timer2 can NOT be used as counter of external events. Rather
all setting of CS22:CS20 (3bits of TCCR2 register) are for
internal frequency select. Of course the meaning of some of
the combinations have different meaning than that of Timer0.
TOSC1 & TOSC2 Pins
Timer2 Programming
TCCR2 Register
FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20

 FOC2 – Bit 7 – Force Compare Match. This is a


write only bit, writing 1 to it causes to act as if a
compare match has occurred.
 WGM20, WGM21 – Bit 6 and 3 – Mode Selector
0 0 – Normal
0 1 – CTC (Clear Timer on Compare Match)
1 0 – PWM, Phase Correct
1 1 – Fast PWM
Timer2 Programming (Contd.)
TCCR2 Register
FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20
• COM 21:20 – Bit 5 and 4
Compare output mode This mode controls the
waveform generator (will be discussed in another
lecture)
• CS22:20 – Bit 2, 1 and 0 – Timer clock selector
(see the next slide)
Block Diagram for Timer2
CLkI/O STOP 0
CLK 1 WGM21 WGM20
CLK/8 2
CLK/32 3
CONTROL
PRESCALER CLK/64 4 MUX UNIT
CLK/128 5
CLK/256 6 COUNT UP/ CLEAR
CLK/1024 DOWN OCR2
7 0
2 1 TCNT2
AS2 CLK
TOV2 COMPARATOR =
CS01CS00
T/C Oscillator CS02
OCF2
CLKI/O
TOSC1 TOSC2
TIFR (Timer/Counter) Interrupt Flag
Register
TIFR Register
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0

Timer 2
TOV2 Timer2 Overflow flag bit
OCF2Timer2 output compare flag bit
ASSR (Asynchronous Status Register)

ASSR Register
AS2 TCN2UB OCR2UB TCR2UB

AS2 – When it is zero, Timer2 is clocked from


CLKI/O,
When it is set Timer2 works as RTC
The Circuit Developed in Proteus
Generation of a Train of Rectangular Pulses of a
Fixed Frequency Using Timer2
• Let us say, we want to generate a train of rectangular pulses having a
frequency of 0.5 Hz.
• Therefore, the time period will be (1/0.5) sec or 2 sec.
• So the time in half cycle will be 1 sec.
• If we send high signal to a port pin for 1 Sec and then low for next 1
Sec and repeat this sequence, a train of pulse of 0.5 Hz will be
generated.
• If we configure TIMER2 to be interrupted at every 1 Sec, and if we
toggle a Port pin we shall obtain desired wave shape.
• Let us use external clock of 32.768 kHz with a Prescaling factor of
1024. Therefore duration of each pulse will be of (1024/32768) Sec.
• In other words, we need 32768/1024 or 32 (or 0x20) number of
pulses for a time of 1 Sec.
• Therefore, in compare method, TCNT2=0x00; OCR2=0x20;
• And in TCCR2 > CS22:CS21:CS20=111;
One Correction in Calculation of Initial Value for TCNTn
Registers for Overflow Method
• In order to count ‘n’ number of pulses, the number to be
loaded in TCNTn Register (in Overflow method)
= 255-n+1
NOT 256-n+1
Because the decimal corresponding to FF is
255
EXAMPLE :TIMER
#include <TimerOne.h>

The int led = 13;

Program void setup() {


pinMode(led, OUTPUT);
Code Timer1.initialize(1000000); // thiết lập timer 1s
(Timer) }
Timer1.attachInterrupt(blinkLED); // gọi hàm blinkLED mỗi 1s

void blinkLED(){
digitalWrite(led, !digitalRead(led));
}

void loop() {
// code khác có thể chạy ở đây mà không bị chặn bởi delay()
}
#include <TimerOne.h>
The #define sensorPin 2
volatile unsigned long pulseCount;
Program void setup(){
Code Serial.begin(9600);
pinMode(sensorPin, INPUT);
(Counter) Timer1.initialize(100000); // 100ms
Timer1.attachInterrupt(pulseCounter);
}

void pulseCounter(){
pulseCount++;
}
void loop(){
Serial.println(pulseCount);
pulseCount = 0;
delay(100);
}
The #include <TimerOne.h>
// Khai báo chân tín hiệu đếm xung void loop() {
Program const byte sensorPin = 2; // In ra số xung đếm được
Serial.println(pulseCount);
Code // Biến đếm xung
volatile unsigned long pulseCount; // Reset biến đếm
(Counter) void setup() {
pulseCount = 0;

Serial.begin(9600); // Delay 1s
delay(1000);
// Đặt chân tín hiệu là INPUT }
pinMode(sensorPin, INPUT);

// Cấu hình Timer1, tần số là 20kHz


Timer1.initialize(50);

// Gán hàm xử lý ngắt timer


Timer1.attachInterrupt(pulseCounter);
}

// Hàm xử lý ngắt
void pulseCounter(){
pulseCount++;
}
The Outputs
Summary on Operation of Timer1
Timer0 and Timer2 also
Can be obtained using

1. No auto output is required


2. Auto output in OC1A or OC1B pin, (Square Wave)
Timer Register Resets : (2a.Normal) or (2b. CTC)
3. Auto output in OC1A or OC1B pin,

Output
(PWM Wave of discrete frequency)
Timer Register Resets : Normal

4. Auto output in OC1A or OC1B pin,


(PWM Wave of Variable frequency)
Timer Register Resets : Normal

5. Input Capture in ICP1 pin, (Time Period)

Input
6. Input Capture in ICP1 pin, (Time Period & DC)
Generation of PWM having Variable Frequency
• Previously we discussed about fixed frequency
PWM
• It was fixed frequency because the Timer register
Resets at TOP value
• In order to obtain variable frequency PWM we
need to have a choice of WGM where Timer
Register Resents at ICR1 register value.
• Let us follow the diagram of the next slide.
Value increases
Value in in TCNT0 Register
ICR1

Your Set
Values in
OCR0

WGM = FAST PWM with ICR1A as RESET Value Pulses


Output
at OC0 TON
pin

Time Period, T1
ARDUINO CODE TIMER

#include <TimerOne.h>

int count = 0; // Biến đếm số lần ngắt xảy ra

void setup() {
Serial.begin(9600); // Khởi tạo cổng Serial để in kết quả
Timer1.initialize(1000000); // Thiết lập timer0 với chu kỳ 1 giây
Timer1.attachInterrupt(timer_callback); // Bật ngắt khi timer0 đếm đến overflow
}

void loop() {
// Không có gì để làm trong hàm loop()
}

void timer_callback() {
count++; // Tăng biến đếm khi có ngắt xảy ra
Serial.println("Timer interrupt #" + String(count));
1 // In kết quả
}
div 5.6
div
ARDUINO CODE TIMER
// Khai báo chân kết nối encoder void loop() {
#define ENC_A 2 // Tính toán thời gian từ lần đọc trước đó đến hiện tại
#define ENC_B 3 unsigned long deltaTime = millis() - lastTime;

// Biến lưu trữ số lượng xung // Nếu thời gian đọc encoder đã đủ 1 giây
volatile int count = 0; if (deltaTime >= 1000) {
// Tính toán tốc độ dựa trên số lượng xung đọc được và thời
// Biến lưu trữ thời gian đọc encoder trước đó gian đã trôi qua
unsigned long lastTime = 0; speed = (float)count / deltaTime * 1000;

// Biến lưu trữ tốc độ hiện tại // Reset số lượng xung và thời gian đọc encoder trước đó
volatile float speed = 0; count = 0;
lastTime = millis();
void setup() {
// Khai báo chân kết nối encoder là INPUT_PULLUP // In ra tốc độ hiện tại trên Serial Monitor
pinMode(ENC_A, INPUT_PULLUP); Serial.print("Speed: ");
pinMode(ENC_B, INPUT_PULLUP); Serial.print(speed);
1 Serial.println(" RPM");
// Bật interrupt cho chân A của encoder div 5.6}
attachInterrupt(digitalPinToInterrupt(ENC_A), }
readEncoder, CHANGE); div
}
void readEncoder() {
// Đọc trạng thái của chân A và chân B của encoder
int a = digitalRead(ENC_A);
int b = digitalRead(ENC_B);

// Nếu chân A thay đổi


if (a != b) {
// Tăng biến đếm số lượng xung
count++;
} else {
// Giảm biến đếm số lượng xung
count--;
}
}
analogWriteFrequency(pwmPin, 5000);
analogWrite()

analogWrite(pin, number);
The #include <TimerOne.h>

Program int led = 9;

Code void setup() {

(PWM) pinMode(led, OUTPUT);


Timer1.initialize(500); // 500us = 2kHz
Timer1.pwm(led, 512);
}

void loop() {
// không cần code ở đây
}

You might also like