Interrupts and 16-bit Timer/Counter 1: ATmega328P Timing Subsystems

Reading

The AVR Microcontroller and Embedded Systems using Assembly and C
by Muhammad Ali Mazidi, Sarmad Naimi, and Sepehr Naimi

Sections: 9.1, 9.3

Table of Contents

ATmega328P Timing Subsystem

Figure 1: Block Diagram

The ATmega328P is equipped with two 8-bit timer/counters and one 16-bit counter. These Timer/Counters let you…

  1. Turn on or turn off an external device at a programmed time.
  2. Generate a precision output signal (period, duty cycle, frequency). For example, generate a complex digital waveform with varying pulse width to control the speed of a DC motor
  3. Measure the characteristics (period, duty cycle, frequency) of an incoming digital signal
  4. Count external events

What is a Flip-Flop and a Counter

You can think of a D flip-flop as a one-bit memory. The something to remember on the D input of flip-flop is remembered on the positive edge of the clock input .

Figure 2: D Flip-Flop

Dt Qt+1
0 0
1 1
X Qt

The counter part of an ATmega328P Timer/Counter peripheral subsystem is an example of an asynchronous (ripple) counter, which is a collection of flip-flops with the clock input of stage n connected to the output of stage n -1

Figure 3: Asynchronous Counter

When compared with a synchronous counter, an asynchronous “ripple” counter: generates less noise and is less expensive. On the negative side, an asynchronous “ripple” counter is slower than a synchronous counter.

Timing Terminology

Frequency
The number of times a particular event repeats within a 1-s period. The unit of frequency is Hertz, or cycles per second. For example, a sinusoidal signal with a 60-Hz frequency means that a full cycle of a sinusoid signal repeats itself 60 times each second, or every 16.67 ms. For the digital waveform shown, the frequency is 2 Hz.

Period
The flip side of a frequency is a period. If an event occurs with a rate of 2 Hz, the period of that event is 500 ms. To find a period, given a frequency, or vice versa, we simply need to remember their inverse relationship, F = 1/T where F and T represent a frequency and the corresponding period, respectively.

Duty Cycle
In many applications, periodic pulses are used as control signals. A good example is the use of a periodic pulse to control a servo motor. To control the direction and sometimes the speed of a motor, a periodic pulse signal with a changing duty cycle over time is used.

Duty cycle is defined as the percentage of one period a signal is ON. The periodic pulse signal shown in the Figure is ON for 50% of the signal period and off for the rest of the period. Therefore, we call the signal in a periodic pulse signal with a 50% duty cycle. This special case is also called a square wave.

Figure 4: 50% Duty Cycle

Timer 1 Modes of Operation

Table 1: Waveform Generation Mode Bit Description

Normal Mode

  • The simplest AVR Timer mode of operation is the Normal mode. Waveform Generation Mode for Timer/Counter 1 (WGM1) bits 3:0 = 0. These bits are located in Timer/Counter Control Registers A/B (TCCR1A and TCCR1B).

Figure 5a: Timer/Counter Control Register A


Figure 5: Timer/Counter Control Register B

  • In this mode the Timer/Counter 1 Register (TCNT1H:TCNT1L) counts up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 16-bit value 0xFFFF and then restarts 0x0000.
  • There are no special cases to consider in the Normal mode, a new counter value can be written anytime.

Figure 6: Timer/Counter 1 Register

  • In normal operation the Timer/Counter Overflow Flag (TOV1) bit located in the Timer/Counter1 Interrupt Flag Register (T1FR1) will be set in the same timer clock cycle as the Timer/Counter 1 Register (TCNT1H:TCNT1L) becomes zero. The TOV1 Flag in this case behaves like a 17th bit, except that it is only set, not cleared.

Figure 7: Timer/Counter 1 Interrupt Flag Register

Timer/Counter 1 Prescalar

The clock input to Timer/Counter 1 (TCNT1) can be pre-scaled (divided down) by 5 preset values (1, 8, 64, 256, and 1024).

Table 2: Clock Select Bit Description

Clock Select Counter/Timer 1 (CS1) bits 2:0 are located in Timer/Counter Control Registers B [yellow].

Figure 8: Timing Reference

Timer/Counter 1 Normal Mode – Design Example

  • In this design example, we want to write a 250 msec delay routine assuming a system clock frequency of 16.000 MHz and a prescale divisor of 64.
  • The first step is to discover if our 16-bit Timer/Counter 1 can generate a 250 ms delay.

Variable Definitions
tclk_T1  : period of clock input to Timer/Counter1
fclk : AVR system clock frequency
fTclk_I/O : AVR Timer clock input frequency to Timer/Counter Waveform Generator

How to Calculate Maximum Delay (Normal Mode)

  • The largest time delay possible is achieved by setting both TCNT1H and TCNT1L to zero, which results in the overflow flag TOV1 flag being set after 216 = 65,536 tics of the Timer/Counter1 clock.

, given  then

and therefore

  • Clearly, Timer 1 can generate a delay of 250 msec
  • Our next step is to calculate the TCNT1 load value needed to generate a 250 ms delay.

How to Calculate Timer Load Value

Figure 9: Process to Calculate Timer Load Value

Steps to Calculate to Timer Load Value (Normal Mode)

Problem

Generate a 250 msec delay assuming a clock frequency of 16 MHz and a prescale divisor of 64.

Solution

  1. Divide desired time delay by tclkT1 where tclkT1 = 64/fclkI/O = 64 / 16.000 MHz = 4 µsec/tic
    250msec / 4 µs/tic = 62,500 tics
    short-cut: TCNT1H = high(-62,500) and TCNT1L = low(-62,500)
  2. Subtract 65,536 – step 1
    65,536 – 62,500 = 3,036
  3. Convert step 2 to hexadecimal.
    3,036 = 0x0BDC
    For our example TCNT1H = 0x0B and TCNT1L = 0xDC
  4. Check Answer
    3,036 tics x 4 µs/tic = 12.14 msec
    262.14 msec – 250 msec = 12.14 msec √

Steps to Calculate Clock Divisor (Normal Mode)

In the previous example we assumed a divisor of 64, and then by calculating the maximum delay TMAX verified that this assumption was correct. After that we simply followed the steps defined in the previous slide to calculate the value to be loaded into 16-bit timer/counter TCNT1.

Where:
TMAX = maximum delay
N = divisor
n = number of flip-flops making-up the timer
fclk = system clock frequency

But what if we are not given N and need to find TCNT1 for a given delay tdelay. In this case we know that tdelay ≤ TMAX and applying a little algebra can find an equation for N.

Let’s take a second look at our 250 msec delay problem. This time we will not assume a divisor of 64. Applying equation 2 we have:

From Table 13.5 “Clock Select Bit Description” on page 10, we see that the possible clock divisors are 1, 8, 64, 256, and 1024. From this list we want to select the divisor that is the closest value, yet greater than or equal to N. For our example, not surprisingly the answer is again 64.

Polling Example – Assembly Version

; --------------------------
; ------ Delay 250ms ------
; Called from main program
; Input: none Output: none
; no registers are modified by this subroutine
Delay:
  push r15
  in   r15, SREG
  push r16
wait:
  sbis TIFR1, TOV1
  rjmp wait
  sbi TIFR1, TOV1 // clear flag bit by writing a one (1)
  ldi r16,0x0B    // load value high byte 0x0B
  sts TCNT1H,r16
  ldi r16,0xDC    // load value low byte 0xDC
  sts TCNT1L,r16
  pop r16
  out SREG, r15
  pop r15
  ret

Figure 10: Delay Flow Chart

Polling Example – C Version

; --------------------------
; ------ Delay 250ms ------
; Called from main program
; Input: none Output: none
void T1Delay()
{
  while (!(TIFR & (1<  TIFR = 1<
  TCNT1H = 0x0B;
  TCNT1L = 0xDC;
}

More Looping Examples

Here are six (6) other ways of implementing the looping part of the Polling Example written in assembly. See if you can come up with a few more.

wait:

sbis TIFR1, TOV1 // targets a specific bit
rjmp wait

wait:

in r16, TIFR1
sbrs r16, TOV1
rjmp wait

wait:

in r16, TIFR1
bst r16, TOV1
brtc wait

wait:

in r16, TIFR1
andi r16, 0x01 // bitwise operation
breq wait

wait:

in r16, TIFR1
cbr r16, 0xFE
breq wait

wait:

in r16, TIFR1
ror r16
brcc wait

wait:

in r16, TIFR1
lsr r16
brcc wait