0% found this document useful (0 votes)
134 views27 pages

MAES - MID - LECTURE 02 - v3

Timer modes on the Arduino include normal mode, CTC mode, and PWM mode. In normal mode, the timer counter simply overflows and resets to zero when it reaches its maximum value. In CTC mode, the counter is cleared to zero when it matches a value stored in the output compare register. Timers are useful for measuring time intervals and generating precise timing signals independently of the CPU. They allow code to run in parallel with timing functions.

Uploaded by

ratul.sunny111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views27 pages

MAES - MID - LECTURE 02 - v3

Timer modes on the Arduino include normal mode, CTC mode, and PWM mode. In normal mode, the timer counter simply overflows and resets to zero when it reaches its maximum value. In CTC mode, the counter is cleared to zero when it matches a value stored in the output compare register. Timers are useful for measuring time intervals and generating precise timing signals independently of the CPU. They allow code to run in parallel with timing functions.

Uploaded by

ratul.sunny111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

AMERICAN INTERNATIONAL UNIVERSITY – BANGLADESH(AIUB)

Where leaders are created

INTRODUCTION TO TIMERS

6 June 2023
INTRODUCTION
• A timer/counter is like a clock,
and can be used to measure
time events. The timer can be
programmed by some special
registers. The controller of the
Arduino is the ATmega328
which has 3 timers, called
timer0, timer1 and timer2.
• Timer0 and timer2 are 8bit
timers, whereas timer1 is a 16bit
timer. The most important
difference between 8bit and
16bit timer is the timer
resolution.
• 8-bit timer is capable of counting
28=256 steps from 0 to 255. 16
bit timer is capable of counting
216=65536 steps from 0 to
2
65535.
USEFULNESS OF TIMER :
• Timer is an important concept in the field of electronics. Every electronic component of
a sequential logic circuit works on a time base to keep all the work synchronized.
• An advantage of the timer is that it is totally independent of the CPU. Thus, it runs
parallel to the CPU and there is no CPU’s intervention, which makes the timer quite
accurate.
• This is why using a timer is preferred for long delays instead of simply using the
delay() function. The drawback of delay() is that your loop gets halted, and functions
above and below the delay() are not being executed during this interval.
• A timer approach is a little harder to implement but the main loop keeps executing and
only excludes the code and functions which a programmer wants to exclude. If the
programmer needs multiple tasks to occur at the same time or if the programmers'
application requires that you constantly read/save data from inputs, using the delay()
function should be avoided.

3
TIMER BASICS: OVERFLOW
• Due to this counting feature, timers are also known as counters. Once they reach their
maximum possible value, the program does not stop executing and the timer count simply
returns to its initial value of zero. In such a situation, we say that the timer/counter
overflows.
• For example, Timer0 is an 8-bit timer, meaning that it can count up from zero to 28-1, or
255. Once that number is reached, the count resets back to zero and starts counting
again.

4
HOW TIMER WORKS:
• Timers on the Arduino count up from zero, incrementing with every clock cycle of the
oscillating crystal that drives the Arduino.
• If smaller frequencies are necessary, it is possible to “divide” the clock through an approach called
pre-scaling.
• How quickly timer reaches the target count depends on the clock divider. With no divider, the
clock would go through 16 million cycles per second (16MHz), and would overflow and reset this
counter many times per second.
• The three timers (called timer0, timer1 and timer2) of Atmega328 can be either
operated in normal mode, CTC mode or PWM mode.
• For lab experiment 3 we will operate in normal mode (counter) using Timer0.

5
TIMER BASICS: REGISTERS (TIMER0)
• The timer can be programmed by some special registers, where we can configure the
pre-scaler for the timer, or the mode of operation and many other things necessary for
proper operation.
• The registers of interest for our purposes are:
• Timer/Counter Register – TCNT0 : to store timer count
• Timer/Counter Control Register – TCCR0A and TCCR0B : to define operation
mode and pre-scaler
• Timer/Counter Interrupt Flag Register– TIFR0 : to observe if there is any
overflow
• Output Compare Register - OCR0A and OCR0B: to match the timer count with
some custom value (for CTC or PWM mode, not needed for normal mode)

6
TIMER BASICS: REGISTERS (TIMER0)

• Timer/Counter Control Register A – TCCR0A : The bits WGM02 (from TCCRB),


WGM01 and WGM00 decide which mode the timer will run on.

Ignore for now (related to PWM) Set timer mode


• Timer/Counter Control Register B – TCCR0B : The three Clock Select bits CS02,
CS01, CS00 select the clock source and prescalar value to be used by the
Timer/Counter.

Ignore for now Set timer mode Set prescaler


TIMER BASICS: REGISTERS (TIMER0)

Please note that if


you do not initialize
this register, all the
bits will remain as
zero and the
timer/counter will
remain stopped.

• Timer/Counter Register – TCNT0 : This is where the 8-bit counter of the timer
resides. The value of the counter is stored here and increases/decreases
automatically. Data can be both read/written from this register. The register resets to
zero after each overflow.

8
TIMER BASICS: REGISTERS (TIMER0)
• Timer/Counter Interrupt Flag Register– TIFR0 : TOV0 bit is set (one) whenever TIMER0 overflows.

• Output Compare Register - OCR0A and OCR0B: Both Output Compare Registers A and B contain 8-bit
values that are continuously compared with the counter value (TCNT0).
• The OCF0A or OCF0B bit in TIFR register is set (one) whenever the count matches the stored value.

9
TIMER BASICS: REGISTERS (TIMER1)
• Most of the registers are very similar to Timer0.
• Timer/Counter Register – TCNT1H and TCNT1L (TCNT1): The main difference
between Timer0 and Timer1 is in the timer/counter register. The two Timer/Counter
I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for
read and for write operations, to the Timer/Counter unit 16-bit counter. The register
resets to zero after each overflow.

• Other differences include:


• The output compare registers are also 16 bit and made up from two 8-bit registers.
• There is an extra Input Capture Register.
• There are several extra modes Timer1 can run on.
TIMER BASICS: TERMINOLOGY

• Definitions of some commonly used terms in Timer:


• BOTTOM: The counter reaches the BOTTOM when it becomes 0x00.
• MAX: The counter reaches its maximum when it becomes 0xFF (decimal 255) in
Timer0 and 0xFFFF (decimal 65535) in Timer1.
• TOP: The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be the fixed value (MAX) or the
value stored in the OCRnA or OCRnB Register. The assignment is dependent on the
mode of operation.
TIMER MODES: NORMAL MODE
• The simplest mode of operation is the Normal mode. In this mode the counting
direction is always up (incrementing), and no counter clear is performed.
• The counter simply overflows when it passes its maximum value and then restarts
from zero.
• In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same
timer clock cycle as the TCNT0 becomes zero.

TIMER MODES: CTC MODE


• In Clear Timer on Compare or CTC mode, the counter is cleared to zero when the
counter value (TCNT0) matches either a value stored in OCR0A register.
• When the wanted value is reached a flag in a status register is set to ‘1’.
• This method can be more efficient than comparing bytes to detect a match as
checking a single flag is simpler.
Counter Unit
3c. Timer/Counter overflow flag set when
2a. Every clock period, timer overflows (goes beyond maximum
signals the Timer to value)
increment/decrement

2b. Sets the


timer’s
count to 2c. Chooses 1. Timer
zero between clock is
increment chosen
• Red: signals entering/exiting a block and
decrement
Contains• Green: description of a block
0a. External
the clock
3a. Signals 3b. Signals
current source
timer • that timer that timer
Red: signals entering/exiting a block
count • count has count has
Green: description of a block 0b. System clock
reached reached
maximum (may or may not be
minimum
pre scaled)
Red: signals entering/exiting a block
Green: description of a block
• Red: signals entering/exiting a block (Normal mode)

Output Compare Unit • Blue: signals entering/exiting a block (CTC/PWM mode)


• Green: description of a block

6a. Signals that timer count has 6b. Signals that timer count has
reached maximum reached minimum

Comparator (checks if zero)

Comparator 1. Current OCFnA 7a. Output compare flag set,


1. Current
timer count timer count interrupt generated if enabled
5. Maximum timer
value chosen
Comparator
3a. Sends
signal if inputs 8a. generate a
equal PWM or variable
frequency output
2a. Count stored in 4. Count
OCRnA stored in OCFnB 7b. Output compare flag set,
OCRnA interrupt generated if enabled

1. Current
timer count
Comparator 3b. Sends signal if inputs equal
2b. Count stored in
8b. generate a
OCRnB
PWM or variable
frequency output
decides which mode the timer will
run on and decides the pre-scaler
for timer clock
TIMER FOR DELAY: CALCULATING COUNT

• Timer needs a clock pulse for each transition from one number to the next, so we want
to establish a formula relating the necessary timer count for a specific delay with the
timer clock period/frequency.
• For F_CPU = 16 MHz, system clock period = 1/16M = 62.5 ns. So, if timer clock is the
same as system clock, it takes only 62.5 ns for every transition (0 to 1, 1 to 2, etc.).

187.5 ns

∗ 𝟏
62.5 ns 62.5 ns 62.5 ns
𝑻=
𝒇
Count = 0 Count = 1 Count = 2

• We can see that 3 time periods are needed to count to 2, so timer count = (number of
periods needed to reach the count) -1.
• Also, we can see that to get a delay of 187.5 ns, we need 3 periods lasting 62.5 ns, so
the number of periods needed = Required delay/Timer clock period.
TIMER FOR DELAY: CALCULATING COUNT
(WITHOUT PRESCALER)
• Suppose we need a delay of 1 ms. To get an idea of how long it takes, let’s calculate the timer
count from the following formula:

∗ 𝟏
𝑇𝑖𝑚𝑒𝑟 𝑐𝑜𝑢𝑛𝑡 =
𝑅𝑒𝑞𝑢𝑖𝑟𝑒𝑑 𝑑𝑒𝑙𝑎𝑦
−1 𝑻=
𝑇𝑖𝑚𝑒𝑟 𝑐𝑙𝑜𝑐𝑘 𝑝𝑒𝑟𝑖𝑜𝑑 𝒇
Or, 𝑻𝒊𝒎𝒆𝒓 𝒄𝒐𝒖𝒏𝒕 = (𝑹𝒆𝒒𝒖𝒊𝒓𝒆𝒅 𝒅𝒆𝒍𝒂𝒚 × 𝑺𝒚𝒔𝒕𝒆𝒎 𝒄𝒍𝒐𝒄𝒌 𝒇𝒓𝒆𝒒𝒖𝒆𝒏𝒄𝒚) − 𝟏

Here required delay = 1 ms and timer clock period = 62.5 ns, so Timer Count = (1m/62.5n)-1= 15999.
• So, the clock needs to tick 15999 times to give a delay of only 1 ms.
• Maximum possible delay for timer0 at 16MHz: 62.5 ns * 256 = 16μs
• Maximum possible delay for timer1 at 16MHz: 62.5 ns * 65536 = 4.096 ms
• If we plan to get delays simply by directly counting at system frequency, it is difficult to use an 8-bit
timer (as it has an upper limit of 255, after which it overflows and resets count to zero). Even with a
16-bit timer (which is capable of counting up to 65535), it is not possibly get longer delays.
TIMER FOR DELAY: CALCULATING COUNT
(WITH PRESCALER)

• To stay in the safe side, we use the highest available prescalar and reduce timer clock
frequency to 16M/1024 = 15625Hz, with a new timer clock period (= System clock
period * prescalar)= 62.5ns*1024= 64 μs. Now the needed timer count = (1m/ 64 μ) -1
= 15.6249.Now that Timer clock frequency = System clock frequency/ prescalar, we
can update the equation to:

𝑅𝑒𝑞𝑢𝑖𝑟𝑒𝑑 𝑑𝑒𝑙𝑎𝑦 × 𝑆𝑦𝑠𝑡𝑒𝑚 𝑐𝑙𝑜𝑐𝑘 𝑓𝑟𝑒𝑞𝑢𝑒𝑛𝑐𝑦


𝑇𝑖𝑚𝑒𝑟 𝑐𝑜𝑢𝑛𝑡 = −1
𝑝𝑟𝑒𝑠𝑐𝑎𝑙𝑎𝑟
• Maximum possible delay for timer0 at 15625Hz: 64μs * 256 = 16.384ms
• Maximum possible delay for timer1 at 15625Hz: 64μs * 65536 = 4.194304 s
• To get longer delays, we will use timer1, and for delays longer than 4s, nested if
statements can be used.
OSCILLATING OPTIONS
Every microcontroller needs a clock source. The CPU, the memory bus, the
peripherals—clock signals are everywhere inside a microcontroller. They govern the
speed at which the processor executes instructions, the baud rate of serial-
communication signals, the amount of time needed to perform analog-to-digital
conversion, and so much more.
All these clocking actions go back to the source of the clock signal, namely the
oscillator. Therefore, the oscillator must be able to provide the desired performance from
the microcontroller. Though some oscillator options are more complex or expensive than
others, so the choice of oscillator should reflect the importance of reducing cost and
complexity whenever possible. CPU clock speed is a good indicator of the
processor’s performance. In general, a higher clock speed means a faster CPU. A
CPU with a clock speed of 3.2 GHz executes 3.2 billion cycles per second.

6 June 2023
19
System Clock Options
The block diagram
represents the principal
clock systems in the AVR
and their distribution.
All the clocks need not be
active at a given time.
To reduce the power
consumption, the clocks to
modules not being used
can be halted by using
different sleep modes.
Problem Statement 1
Make an LED blink every 2 milliseconds while using Arduino system frequency
(F_CPU) 16 MHz, using timer to generate the delay without any application of
delay() function. Delay = 2 ms, so Timer0 can be used with pre-scalar 1024.
Number of count needed to reach 2 ms = (2,000 ms/64 μs) – 1 = 30.25 ≈ 31.

WGM01 and WGM00 set to zero for normal mode

WGM02 set to zero for


normal mode, CS02, CS01,
CS00 set to 1,0,1 for pre-
scalar 1024
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 21
Make LED blink
6 June 2023
PROBLEM STATEMENT 2

• Make an LED blink every 2 seconds while using Arduino system frequency (F_CPU)
16 MHz, using timer to generate the delay without any application of delay() function.
• Delay = 2 s, so Timer1 can be used with prescalar 1024.
• Number of count needed to reach 2s = (2/64 μ)-1=31249
Code:
Same code, only
register names
have 1 instead of 0
and delay length
changed!

Set-up registers are 8-bits even the Timer is 16-bit

6 June 2023 23
QUESTIONS
Q1. Prepare the necessary registers associated with the 8-bit
timer to achieve the necessary time counts. Consider the timer to
be running at normal mode with highest prescaling.
Answer:

Ignore for now (related to PWM) Set timer mode

Ignore for now Set timer mode Set prescaler


PROBLEM
Q1. In a data analysis firm, a performance-checking system has been designed centered around an
Arduino Uno platform which performs a refresh operation in the cache memory at a specified time
interval. It was found that the Timer modules in the Arduino platform are perfect candidates to trigger
this refresh operation periodically. Apply the knowledge of Arduino to compute the required timer
counts for the following time intervals required for the refresh operation: 3 s and 40 ms. The available
timers are Timer0, an 8-bit timer, and Timer1, a 16-bit timer. Assume that the Arduino system clock has
been set at 16 MHz and the available prescalers in the system are 1, 8, 64, 256, and 1024. Considering
the given information, comment on whether the required delays can be implemented using Timer0 or
not.

Q2. If malware is found in the system, the system is designed to sound an alarm every 4s. This 4s count
has to be achieved from a timer directly (without the help of a loop). Select an appropriate timer from
the 2 available timers and set up the necessary registers associated with the used timer to achieve the 3s
time count. You may consider the clock frequency and Prescaler values mentioned in 1(a). Additionally,
compute the maximum possible time which can be counted using this timer.
REFERENCES

• ATMega328 manual
• https://www.avrfreaks.net/forum/tut-c-newbies-guide-avr-timers
• http://maxembedded.com/2011/06/avr-timers-timer0/
• https://cdn.sparkfun.com/assets/c/a/8/e/4/Atmel-42735-8-bit-AVR-Microcontroller-
ATmega328-328P_Datasheet.pdf.
THANKS FOR ATTENDING….

6 June 2023 27

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy