You are on page 1of 24

İYTE - Department of Electrical and Electronics Engineering B.

Özdemirel

EE443 - Embedded Systems

Lecture 4
Microcontroller Hardware

Contents:

4.1 Processor
4.2 Memory Organization
4.3 Reset Circuit
4.4 Clock Generator
4.5 I/O Ports, Channels, Buffers
4.5.1 Direct Memory Access
4.6 Serial I/O
4.7 Timers
4.8 Pulse Width Modulation
4.9 ADC / DAC
4.10 Measurement Applications
4.10.1 Application Example: ADC Setup
4.10.2 Application Example: Timer Setup

This lecture summarizes the common components that can be found in a


microcontroller. It is better to combine as many as possible components in a single
chip. The advantages of integration are:
Cost: IC packages, PCB area, and PCB assembly are all major cost items that can
be reduced with integration of components in a single device.
Easy development: You don't need to worry about interfacing external components
and the related noise coupling or interference problems. Accessing an ADC is as
easy as writing and reading a few special function registers when the ADC is
available as an on-chip component of the microcontroller.
Special function registers or SFRs in short, provide easy access to all on-chip
microcontroller peripherals and interface units. SFRs can be read or written using
simple machine instructions much like accessing the on-chip memory. In every
microcontroller data sheet you will find the specifications and functional descriptions
of several SFRs that are dedicated to peripheral functions.
On the other hand, if you end up using an external ADC component, then you
need to find solutions to several design requirements such as, ADC power supply,
clock signal, reference voltage, interface protocol, reserving I/O pins on the
microcontroller, and routing I/O connections on the PCB.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 1


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

Large PCB with two more ICs Small PCB


saved 100 pins

simple fully integrated


external
microcontroller microcontroller
analog
without RAM and (80 pins)
interface
analog interface
(100 pins) (40 pins) analog
RAM
interface

external RAM
(40 pins)

An unnecessarily powerful processor or another useless peripheral is usually


affordable just to have everything needed on a single chip. Addition of an external
component usually costs more.

4.1 Processor
The instruction set architecture (ISA) of the processor determines the main
processing capabilities and efficiency of a microcontroller. Usually a microcontroller
is labeled with a core name that identifies the processor ISA (e.g. . . . . . controller
with ARM core or . . . . . controller with 8051 core). Note that the ISA determines
the main programming features and requirements of a processor. A core ISA may be
used by several microcontroller IC manufacturers. The hardware implementation
may vary from one IC manufacturer to another. Following is a list of the common
processor architectures used in microcontrollers.
AVR (Atmel): A large variety of microcontrollers manufactured by Atmel. One of
these microcontrollers will be used in the laboratory work of this course.
PICXXX (Microchip): PIC is a family of Harvard architecture microcontrollers
manufactured by Microchip Technology. PIC processors are widely used for
industrial applications and hobby purposes. Optimized processor efficiency, serial
programming capability, free development tools, and availability of a large library of
application notes made the PIC processors popular.
8051 (Intel): A Harvard architecture 8-bit microcontroller series developed by Intel in
1980 for use in embedded systems. Today, a large variety of faster and enhanced
8051-core microcontrollers are produced by more than 20 independent
manufacturers.
68XX, 680X0 (Motorola): The 68xx is an 8-bit microprocessor family introduced by
Motorola starting in 1974. The MC6801 and MC6805 were commonly used as
microcontrollers in automotive industry. The Motorola 6809 introduced in 1977 had
some 16-bit features. The Motorola 680x0 is a family of 32-bit processors that were
popular in personal computers and workstations until the mid-1990s. Descendants of
the 680x0 family processors are still widely used in embedded applications.
ARM (ARM7, ARM9, ARM11 - ARM Holdings): ARM architecture is the most
widely used 32-bit ISA in terms of numbers produced. ARM Holdings itself does not
manufacture any processors but they license ARM ISA to independent

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 2


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

manufacturers. ARM processors dominate the mobile and embedded electronics


market (90% of all embedded 32-bit RISC processors in 2009), because they are
suitable for low power applications as relatively low cost, simple, and small
processors.
x86 (386, 486, Pentium, . . . - Intel): The term x86 refers to a family of ISAs based
on the Intel 8086 CPU introduced in 1978. More specifically, x86 implies
compatibility with the instruction set of 32-bit 80386. x86 processors are not widely
used in embedded systems.

Choosing the appropriate processor for an application requires consideration of


several factors.
ISA: The simplest ISA that can answer the requirements of an application is usually
the best choice. An 8-bit ISA with powerful built-in peripherals can handle many
demanding tasks. Microcontrollers including dedicated I/O buffers, interface
modules, and direct memory access controllers significantly reduce the processor
load. A 32-bit ARM processor may be an overkill for a simple controller, but it may be
the only choice for a specific requirement such as Bluetooth communication.
Processor speed: It is often misleading to compare processors solely based on the
clock frequency. There are different hardware implementations of the common ISAs
provided by several IC manufacturers. An instruction that takes 10 clock cycles to
execute in processor-A may take only 3 clock cycles in processor-B. In this case,
processor-B will run faster even if it uses half the clock frequency of processor-A.
The number of instructions executed in unit time is a better measure of the
processing speed for comparing processors that have the same ISA. A commonly
used speed specification unit is MIPS (Million Instructions Per Second).

Processor-A Processor-B

Main clock frequency: 50 MHz 30 MHz

Clock cycles per instruction: 10-15 4-6

Instruction execution rate: 4 MIPS 6 MIPS

Comparison of processor performances with different ISAs based on their MIPS


specification will be misleading too. Incrementing a memory variable may take three
instructions on a typical processor:
LOAD  A, Count;  Load counter variable to accumulator 
ADD  A, #1;  Add 1 immediate to accumulator 
STORE  A, Count;  Store the result back to memory 
PIC16F87x processors can complete this operation in a single instruction:
INCF  Count, f;  Read Count, increment, and store back to memory 
On the other hand, PIC16F87x is very inefficient for some other types of operations .
In some cases, benchmarks can provide more reliable results for evaluation of
processor performance. A benchmark is the measure of time it takes to complete a
certain procedure that requires execution of thousands or millions of instructions.
The benchmark procedure can be the calculation of a PID controller output or
calculation of a discrete Fourier transform on a sample sequence. Benchmarks can

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 3


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

be obtained on previously developed systems or new designs running on simulation


tools. Efficiency of the compilers and optimization of the test programs can be the
other factors that can affect the benchmark results.
All processors can perform addition and subtraction, but implementation of
multiplication and division will require a long series of instructions if these operations
are not supported by a single machine instruction. Also floating point arithmetic
operations take long processing times on the processors that can perform integer
arithmetic only. Digital Signal Processors (DSPs) have accelerator hardware units
for floating point arithmetic operations and they should be preferred for applications
that require extensive mathematical processing. Another processing speed unit is
FLOPS (Floating Point Instructions Per Second) for DSPs and math coprocessors.
Availability of programming tools: Programming support available for the
processor can be another important factor in selection of the microcontroller.
Availability of free assemblers or compilers may significantly reduce the development
cost of embedded systems.

4.2 Memory Organization


There are two common computer architectures that outline the memory
organization in a computer:
1. The Harvard architecture is a computer architecture where instruction and data
memories have distinct address spaces. The instruction address 0x0000 and the
data address 0x0000 target different storage units. In the original Harvard
architecture, instruction and data memories have physically separate address and
data buses that allow simultaneous processor access to the two isolated memories.
The instruction and data memories share the same address and data buses in the
modified Harvard architectures that are more common today. The processor
identifies the target address space using a single control signal. A computer with
Harvard architecture that has 16-bit address bus and 8-bit data bus can have
64 kByte of instruction memory and another 64 KByte to store data.
2. The von Neumann architecture has a single address space. There is only one
sequence of addresses where instructions and data occupy different address ranges.
Addressing of instructions and data memories are the same from the processor's
point of view. A von Neumann machine with 16-bit address bus and 8-bit data bus
can have a total of 64 KByte memory that is shared between code and data.
Harvard Achitecture Von Neumann Achitecture
0000 0000 0000
program
program data memory
memory memory ????
data
FFFF FFFF memory
FFFF

Memory Requirement of an Embedded System:


A stand-alone computer requires two types of memory. First, a non-volatile
memory is necessary to store the program instructions and other permanent
information required for execution. The non-volatile memory does not lose the

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 4


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

stored information when power is turned off. The second type of memory is the
volatile memory to store temporary or dynamically changing information during
program execution.
Non-volatile memory requirement:
 Program storage
 Read-only tables, such as calibration data, system control parameters, user
settings that should be saved when power is turned off.
 At least 20% safety margin for the additional memory that may be required for
future corrections and upgrades.
Volatile memory requirement:
 Variables, arrays
 I/O buffers
 Other data structures, such as stacks and queues.

Common Non-volatile Memory Devices:


ROM (Read-Only Memory): The term, ROM, strictly meant "read-only memory" as it
was used some decades ago. The data stored in a ROM could not be modified by
any means. But today, ROM may refer to all types of non-volatile memory included
within an embedded computer system. The data stored in a ROM remain unchanged
or "read-only" during the normal program execution, but the memory contents can be
modified slowly or with difficulty when it is necessary. The following is a list of other
related memory devices:
PROM (Programmable ROM): Memory contents can be written only once by fusing
(blowing up) or anti-fusing the connections in the device applying high voltages.
EPROM (Erasable Programmable ROM): Memory contents can be written using a
programming device. An EPROM can be erased by exposing it to strong ultraviolet
light through the transparent window placed on top of the chip.
EEPROM (Electrically Erasable Programmable ROM): A version of EPROM
where memory contents can be erased electrically instead of using ultraviolet light.
FLASH Memory: FLASH memory is a kind of EEPROM that is commonly used as
non-volatile memory on the microcontrollers available in the market today. The
EEPROMs other than FLASH are erasable in small blocks (i.e. byte by byte). Large
blocks of data can be erased and written simultaneously in FLASH memories. This
gives a significant speed advantage when writing large amounts of data.

Common Volatile Memory Devices:


RAM (Random Access Memory): Random access means ability to read or write at
any memory address as opposed to restricted addressing methods, such as
sequential access. The term, RAM, may refer to all types of volatile memory in a
computer system. SRAM and DRAM are the two common types of RAM.
SRAM (Static RAM): Memory contents remain intact as long as the power is on.
SRAM is the most common type of volatile memory included in a single-chip
microcontroller. The cache memories on more powerful CPUs are also SRAM
devices.
DRAM (Dynamic RAM): Unlike SRAM, a DRAM device needs to be periodically
refreshed to keep the memory contents intact. DRAMs store each bit of data in a

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 5


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

capacitor, and the voltage on the capacitor needs to be refreshed because the
capacitor charge fades due to leakages. One bit of DRAM storage requires less
silicon area compared to one bit of SRAM. DRAM is the choice for large memory
requirements since the cost per unit of memory is less for DRAMs
SDRAM (Synchronous DRAM): Data transfers to/from SDRAM are synchronized
with a clock signal. Once a memory address is sent to the SDRAM, a sequence of
memory locations can be accessed starting at the specified address. SDRAM does
not exactly match the definition of Random Access Memory, since it behaves more
like a sequential-access memory device. SDRAM replaced DRAM in main memory
modules of all personal computers in 1990s and it inherited the "DRAM" part of its
name.
Sequential access to large memory blocks in SDRAM modules is much faster
compared to true RAM operation in the older DRAM modules. True RAM access to
the main memory is not necessary for the processors with cache memory. Data
transfers between the SDRAM main memory, cache memory and solid state disk
(SSD) or hard disk drive (HDD) are always performed in several kilobyte blocks and
sequential access is preferable for these operations. In a typical personal computer,
access to the main memory is arranged through the Northbridge IC (not shown in the
figure) which is a part of the core logic chipset.
Microcontroller Complex CPU with SRAM cache memory,
with simple SRAM SDRAM or DDR SDRAM main memory and
data memory solid state disk (SSD) or hard disk drive (HDD)
addr SRAM processor
data addr (DDR) addr SSD
CPU data addr SRAM and SDRAM and ( <GB )
memory cache data data
ALE ( <MB ) CPU data main or
memory memory HDD
ALE ( ~MB ) Clk Clk
( ~GB ) ( ~TB )

DDR SDRAM (Double Data Rate SDRAM): DDR SDRAM is an enhanced SDRAM
version that transfers data at a rate twice as high the synchronization clock frequency
by receiving or sending data at both of the rising and falling clock edges.

4.3 Reset Circuit


Active electronic devices require all supply voltages to be within specified limits
to operate properly. The device behavior is unpredictable if a supply voltage is
outside the specified range. A power-on-reset (POR) signal is required to make
sure that all components of a system are in a known idle state until the supply
voltages reach the specified operation limits. Supply monitors (also called "power
monitor" or "voltage monitor") are the dedicated circuits that generate a master reset
signal according to the supply conditions. These are the functions of the master
reset signal:
1. Suspend all operations while the voltage regulators are ramping up until the
supply voltages reach the specified operation limits (power-on-reset).
2. Initialize state of sequential logic circuits.
3. Stop and re-initialize circuit operations if a fault condition occurs at the supplies.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 6


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

Consider an embedded system that requires three voltage regulators to supply


DC power for the following purposes:
 +1.5 V supply for processor core and memory
 +3.3 V supply for I/O with peripherals
 +5.0 V supply for sensors and drivers
VDC +5.0V is
power is +1.5V is +3.3V is ready
(V) ready
turned on ready
5.0

3.3
1.5

0.5 1.0 1.5 2.0 2.5 3.0 t (ms)


master
reset

All voltage regulators start to ramp-up after power is turned on as shown in the timing
diagram given above. It takes time in the order of milliseconds for each supply
voltage to reach its target level. In practice, voltage regulators should be designed to
ramp-up slow enough to keep the current demand at a reasonable level while
charging output and decoupling capacitors after power is turned on. The +1.5V
supply for the processor core is ready 0.5 ms after power up. The master reset
signal should be kept low until all supply voltages reach their target levels.
Otherwise, the processor may try to communicate with the peripherals, sensors, and
drivers that do not have the proper supply voltages. A typical processor can execute
several thousand instructions in 2.0 ms, reading wrong sensor signals and generating
unpredictable driver outputs.
The master reset is an active-low signal (0 means reset) because a valid logic
signal at active-high level cannot be obtained while the voltage regulators are
ramping up. Common supply monitors have open-collector reset outputs so that they
can easily be merged with open-collector or open-drain outputs of other fault
detection circuits.
VCC1 VCC2 VDD VDD VDD VDD

Supply Other fault Processor


monitor detector RPull reset
input

to other
master reset components

The following is a list of the common specifications for a supply monitor:


1. Valid voltage ranges for the supply inputs.
2. Response time and glitch filtering capabilities.
3. Duration of reset pulse after a reset condition.
4. Minimum supply voltage required to generate a valid signal level for the active-low
reset output.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 7


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

4.4 Clock Generator


Clock generators provide the clock signals for all sequential circuit operations.
Most systems use a single clock source that drives the processor and also serves as
a time reference for all time measurements and generation of timing signals. Other
necessary clock frequencies are derived from this reference clock source using
simple frequency dividers or phase lock loops (PLL). The precision of clock timing
depends on the requirements of a particular application. Generation of a pulse-width
modulation (PWM) output, for example, can tolerate large variations in the clock
frequency. The effective value of a PWM output is determined by the duty cycle
which is independent of the clock driving the PWM circuitry as long as the clock
frequency remains relatively constant in each PWM cycle. The timing precision of a
clock signal used for speed measurements on the other hand, should match the
accuracy of the measurements. There are strict frequency matching requirements
for I/O channels that rely on independent clock signals as frequency references.
A microcontroller may require an external clock generator or it may have on-
chip circuitry that supports a frequency resonator. These are the typical
specifications for a clock generator:
_ ppm (particle per
1. Maximum deviation from target frequency specified in +
_ 50 ppm accuracy, then
million). If you purchase a 10 MHz resonator specified with +
you will obtain a resonance frequency between 9,999,500 and 10,000,500 Hz.
2. Temperature dependency of oscillation frequency specified in ppm/ºC. The
maximum frequency deviation guaranties the oscillation frequency range at a
constant temperature (usually at 20ºC or 25ºC). The temperature dependency adds
on to the frequency uncertainty according to the temperature variations.
3. Jitter, or the timing error between clock cycles: Having 10,000,000 clock cycles in
one second does not necessarily mean that each clock cycle will be exactly 100 ns.
Jitter is the measure of timing error from one clock interval to another, that can be an
important factor when matching reference frequency of communication channels.
Example: A 50 MHz clock generator has the following specifications.
_ 100 ppm (at 25ºC)
Maximum deviation from target frequency: +
Temperature dependency of clock frequency: 2 ppm/ºC
Find the total frequency variation if the operating temperature range is -10ºC through
+60ºC.
Maximum frequency variation at 25ºC: + _ 5000 Hz (+
_ 100 ppm of 50 MHz)
_ 35ºC temperature change: +
Variation due to + _ 70 ppm = +_ 3500 Hz
_ 8500 Hz
Total frequency variation: +

4.5 I/O Ports, Channels, Buffers


I/O ports on a microcontroller provide general-purpose access capabilities to
external devices. These ports can be simple I/O pins that can be read or written by
the core processor or they can be combined with more complex interface options.
Some examples of these interface options are:
 Independent access to individual I/O pins as well as 8 or 16 pin groups.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 8


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

 Built in buffering functions for continuous data transfers.


 Direct memory access to or from the port pins for high-speed communication with
external devices without using processor time.
One should be careful about determining the number of available I/O pins on a
microcontroller. Almost all microcontrollers assign multiple functions to many of the
I/O pins. An I/O pin required as an external interrupt input or as an analog interface
pin will not be available for general-purpose I/O functions.

4.5.1 Direct Memory Access


Data transfers between the RAM and I/O units or other storage devices may
take long processing times depending on the amount of data to be transferred. For
example, if the CPU handles a sequence of data transfers from an I/O unit to the
memory, then it performs several operations to transfer each word of data:
1. Read data from the I/O unit into a CPU register.
2. Write data from the CPU register to the RAM.
3. Increment the pointer for the target address in the RAM.
4. Decrement the byte/word counter.
5. Check the byte/word count, and go back to step-1 if there is more data to be
transferred.
A typical CPU executes a number of instructions to perform these operations.
Every data transfer takes 10s of memory R/W cycles considering the operation codes
and the address information loaded for each instruction. As an alternative, a direct
memory access (DMA) controller can be used to speed up the data transfers. The
following figure shows the organization of data and address busses with a DMA
controller.
Address and Data Flow in Direct Memory Access
addr addr
CPU RAM
data data
R/W R/W control
control
outputs
Hold H.Ack
tristated
for DMA
DMA I/O unit
controller data
addr
R/W control
control data

R/W control

DMA controller takes over management of address, data, and R/W control lines
after CPU tristates its outputs. DMA controller generates the required address
sequence for memory and arranges timing of the control signals for memory and I/O
unit. Data words are transferred directly between the memory and the I/O unit. It
takes just one R/W memory cycle to complete the transfer of a data word. Direct
memory access is an order of magnitude faster compared to the CPU operations that
take 10s of memory R/W cycles for each data transfer.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 9


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

CPU programs the DMA controller writing starting memory address, number of
data transfers, and other necessary information into the controller registers. DMA
controller sends a "Hold" signal to the CPU asking for release of memory control
when it is ready to start the transfer sequence. CPU replies with a "Hold
Acknowledgement" after it tristates its outputs. DMA controller returns control of
memory back to the CPU after it completes the data transfers.
The traditional DMA organization described above has been utilized widely in
personal computers. DMA controllers handle data transfers between CPU cache,
main memory, hard disk, and other storage devices. Microcontrollers designed for
specialized I/O functions may have some parts of their data memory dedicated to
DMA. These dedicated memory sections serve as buffers for high speed I/O
interfaces. If uninterrupted CPU operation is crucial in a computer system, then the
CPU access to memory cannot be put to hold during DMA transfers. These systems
use dual-port memories as I/O buffers. One of the memory ports is used for CPU
access while the other port allows data transfers to/from the memory through a DMA
controller or similar I/O hardware.

4.6 Serial I/O


A serial interface will be slower compared to a parallel bus operating at the
same clock frequency. Whenever you don't need the combined speed of all the data
bits in parallel, a serial interface is preferable because of these advantages:
 It requires less number of pins. A serial interface uses 2, 3, or 4 connections,
so it will require 2-4 pins on transmitter and receiver ends. An 8-bit parallel
interface on the other hand, would require 10 or more connections between the
transmitter and receiver ends. Less number of pins means smaller and cheaper
IC packages.
 PCB design will be easier for a serial interface, and it will save PCB area as
well. Simply, you will route 3 connections instead of 10.
 Serial interface will require less power. A serial interface will eventually use
more-less the same amount of average power to transmit the same number of
bits, but the instantaneous power requirement will be different. If you decide to
use a parallel interface, then you had to be prepared for the worst case, where all
data lines switch from 0 to 1 at the same instant.
 Save on noise. Just as simultaneously switching 8 data lines requires more
power, it will also generate more noise on your PCB.

Two different types of serial I/O interfaces can be found on microcontrollers or


embedded processors. The first type of serial interfaces are for "on-board" or "in-
box" communication between the components of a single instrument. Common
examples of on-board serial communication interfaces are TTL-level USART
(Universal Synchronous Asynchronous Receiver Transmitter), SPI, µWIRE, and I2C.
The second type of serial I/O interfaces are used for box-to-box communication
between the independent design units through cables. The typical examples of box-
to-box serial interfaces are USART with RS-232, RS-422 and similar standards, USB
(Universal Serial Bus), Firewire (IEEE 1394), and SATA (Serial AT (Advanced
Technology) Attachment). Another advantage of serial interfaces in box-to-box
communication is the simplicity of the connectors and cables. Long serial

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 10


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

transmission cables can be built at a lower cost compared to the cost of parallel data
cables that support the similar data transfer rates.

4.7 Timers
Timers are counters that can be programmed to perform a variety of functions.
Following are the typical operation modes and possible applications of timers:

Timer operation for timing control


A timer can be used to generate predetermined time delays just like an alarm
clock that reminds the processor to do an operation after some time. This mode of
operation utilizes the internal clock and it does not require any external connection.
The programming of the timer requires the following steps.
1. Select the timer input clock frequency, which can be the system clock
frequency Fsys divided by a factor 2N determined in the timer settings.
2. Set the count limit that will trigger a timer event. There may be multiple count
limit settings all capable of triggering timer events in a single count sequence.
3. Enable the timer event(s). Enable one or more interrupts generated by the
timer. Each interrupt directs processor to call a service routine automatically.
4. Enable activation of output signals, if necessary. The timer can also activate
signals driving other hardware units as it triggers internal events.
5. Set other timer options such as automatic restart of count sequence.
6. Write an interrupt service routine (ISR) that performs the required task in
response to the interrupt and programs the timer again, if necessary.
The processor enables the count operation after all timer parameters are set properly
and it performs other tasks until it receives an interrupt generated by the timer.
Another common usage of programmed operation is the generation of pulse width
modulation (PWM) signals (see the next section). In this case, a timer is
programmed to repeat a count operation automatically, without interrupting processor
operation.
Most of the timers available in common microcontrollers implement the timing
control operations in compare mode. The processor sets the count limits writing into
timer SFRs. The counter is incremented and compared with the values in these
SFRs in every clock cycle. The timer can be programmed to generate an interrupt,
toggle an output signal, and/or reset the counter whenever there is a match between
the counter and one of the SFRs.

Timer operation for time measurements


The count operation can be controlled by an external input to measure on-time,
off-time and period of the external signal. At the end of the measured period, the
counter value is copied into a register that can be read by the processor. Setting up
a timer for time measurements involves the following steps.
1. Select the timer input clock frequency. The internal system clock of the
microcontroller is used as a timing reference. The selected clock frequency at the
timer input determines the resolution of time measurement.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 11


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

2. Enable the timer event(s), if necessary. Enable interrupts generated by the


timer immediately after a measurement result is obtained. Each interrupt directs
processor to call an ISR automatically.
3. Set other timer options such as automatic restart of count sequence.
4. Write an ISR that performs the required task to evaluate the measurement result
and programs the timer again, if necessary.
A multi-purpose timer allows independent selection of events that start and stop the
measured time period. For example, timer counter is started by the processor and
the measurement result is obtained when the external input toggles. As an
alternative, gated timer operation is obtained if the count operation starts at the rising
edge and stops at the falling edge of the external signal.
Common examples of time measurement applications with timers are
measuring revolution time of a motor to detect its rotation speed, or quantification of
time-encoded signals. In practice, typical timers have capture modes to support
operation with external gate or trigger signals. The timer captures or copies the
counter value into a SFR when the external control signal changes. The timer can be
programmed to generate an interrupt, and/or restart the counter after a 0-1 or 1-0
transition at the external signal. The processor reads the captured counter value
from the related SFR to obtain the timing information about the external signal.

Timer operation with external clock


The counter clock input is supplied by an external signal in this operation mode.
The typical applications include quantization of frequency-encoded signals, or
position information generated by linear or rotational encoders. The processor
should use another timer to establish the reference time period for the count
operations. Timer options that can be used with the external clock signal are same
as the timer settings described for the other operation modes.

The specifications for a timer are directly related to the requirements of the
application:
1. Maximum clock frequency determines the timing resolution. The internal clock
frequencies available for timer operations are obtained from the microcontroller
system clock. The accuracy and stability of the system clock determines the timing
accuracy of all timer operations.
2. Number of counter bits determines the count range or the maximum time period
that can be measured depending on the selected clock frequency.
3. Functionality: Having a programmable timer does not necessarily mean that it
will support all operation modes and gating or triggering options. You need to read
the timer description to find out whether it is useful for your application or not. You
may as well need additional features such as buffering of timer count results for
motor speed measurements. A timer with buffered outputs can store the count result
at the end of every motor revolution and re-start the counting process immediately.

Watchdog timers
Although name of these modules contain the word "timer" their functions are
much different than the timer operations described above. Watchdog timers are
special-purpose timers dedicated to ensure the proper execution of microcontroller
functions. The processor is required to restart the watchdog timer before the preset

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 12


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

timer period expires and it repeats this operation as long as the watchdog timer is
enabled.
Most embedded systems operate for very long periods of time without
supervision of a user. A rare power supply glitch or a high voltage interference like a
nearby lightning may distract the regular processor operation causing erratic
behavior. The program written for the microcontroller includes the necessary
statements to restart the watchdog timer periodically as long as the processor works
properly. If the processor fails to restart the watchdog timer, then this indicates a
major functional failure due to corrupt program counter address or some other
reason. In this case, the watchdog timer resets the processor, forcing initialization of
all microcontroller functions.

4.8 Pulse Width Modulation


Pulse width modulation (PWM) is an efficient way of synthesizing analog
waveforms from digital signals. PWM signal is a square wave where the duty cycle
(ratio of active pulse width to the full waveform period) in each PWM period
corresponds to the relative amplitude of the analog signal. The analog waveform is
obtained after taking the time average of the PWM output utilizing a low-pass filter.
Switched mode motor drivers are the most common applications for the PWM
controllers. The average current flowing through a motor winding is controlled by the
duty cycle of the PWM waveform switching on and off between the supply voltage
and ground level. The inductance of the motor winding serves as a low-pass filter
taking time average of the voltage across the winding. The power dissipation on the
switched mode drivers is minimal since either the voltage drop or the current flow
over the driving transistors is practically zero during the active and passive PWM
cycles. Also the PWM output can be filtered with an RC filter to obtain an almost
constant analog voltage proportional to the PWM duty cycle.
The following figure shows generation and filtering of PWM signals together
with the timer clock input. Two PWM periods are zoomed in showing the details of
counter operations that generate 40% and 50% duty cycle outputs.
Rload iload Rflt
vPWM vPWM vflt
Lload Cflt

20% DC 50% DC TPWM = 1 ms 80% DC


vPWM
t
iload
or
vflt
t
TPWM = 1 ms TPWM = 1 ms
vPWM TON = 400 μs TON = 500 μs

t
Timer
Clock t
Timer
Count Cm 0 Cd40 TClk = 1 μs Cm 0 Cd50 Cm 0

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 13


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

The frequency and timer count settings used in this example are listed below.
PWM frequency: FPWM = 1 kHz
Timer clock frequency: FClk = 1 MHz
Maximum timer count value: Cm = 999 (1000 clock periods)
Count limit for 40% duty cycle: Cd40 = 399 (400 clock periods)
Count limit for 50% duty cycle: Cd50 = 499 (500 clock periods)
Most ordinary timers support generation of PWM outputs in operation modes
similar to timing control. A timer used for PWM signal generation should repeat the
count operation up to the maximum count value Cm automatically without any
intervention from the processor. Typically the PWM output signal is activated when
the timer counter restarts at zero, and it is reset when the counter reaches a
predefined count limit (Cd40 or Cd50) stored in an SFR. This count limit divided by the
maximum count value determines the duty cycle and consequently, average value of
the PWM output. All other timer settings are programmed only once, initializing the
counter settings corresponding to the PWM period and amplitude resolution. The
timer continuously generates repeated PWM periods with the last duty cycle setting
without any further commands from the processor. The processor updates the count
limit to change the PWM duty cycle when a new amplitude setting is required. A
single timer can generate multiple PWM outputs where duty cycle of each output is
controlled by a different count limit SFR. Dual PWM outputs are suitable for driving
stepper motors and triple PWM outputs are suitable for driving brushless DC motors.
Timer specifications for PWM are similar to the specifications we have seen
before. The maximum clock frequency and the number of counter bits determine the
amplitude resolution of the synthesized analog waveform. Number of clock cycles in
each PWM period gives the number of possible amplitude settings.

4.9 ADC and DAC


Analog to digital converters (ADC) and digital to analog converters (DAC) are
the bridges between digital and analog domains. The analog input range of an ADC
or output range of a DAC is determined by a reference voltage, Vref.

Vref VDD VDD Vref


D0 D0
vAin D1 D1 vAout
ADC DAC
DN-1 DN-1

Typically for an N-bit converter with unsigned digital I/O and unipolar analog range
(0V .. +Vref), one ΔVLSB step at the analog end is given by:
V
ΔVLSB = ref
2N
Similarly for a bipolar analog range (-Vref .. +Vref), one step at the analog end is:
2 Vref
ΔVLSB =
2N
There is a large variety of ADC and DAC components that can have several options:
 Internal or external reference voltage supply.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 14


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

 Unipolar (0V .. Vref) or bipolar (-Vref .. +Vref) analog signal range.


 Unsigned (0 .. 2N-1) or signed (-2(N-1) .. 2(N-1)-1) digital I/O range.
 Parallel or serial digital interface.
 Number of multiplexed analog inputs for an ADC or number of DAC circuits in a
DAC component (number of analog channels).
 Sequential or simultaneous access to analog channels.
 Initialization options for a DAC after power-on.

Following are the critical specifications for an ADC or DAC that determine the
performance of the converter. For simplicity, specifications related to analog
accuracy are referred to the digital end, and expressed in terms of LSBs (least
significant bit). One LSB error at the digital end corresponds to ΔVLSB inaccuracy in
the analog domain that depends on the Vref voltage used in an application.
1. Resolution: Given by the number of bits at the digital interface. Note that,
useable resolution of a converter is determined by the linearity of its response and
the accuracy of analog reference.
2. Sampling rate: Is the maximum conversion speed expressed in S/s or Sa/s
(samples per second). Converters supporting sampling rates from a few S/s to
several hundred MS/s are commercially available.
3. Settling time and slew rate for DAC: Sampling rate alone does not specify the
actual analog bandwidth of a DAC output (you cannot get full range, 500 kHz square
wave output from a 1 MS/s DAC). Settling time usually gives the time required for a
DAC output to settle within + _ 1 ΔVLSB of the target value after changing digital input
from 1/4 to 3/4 of the full range. The output slew rate expressed in V/s or V/μs is
the measure of how fast the output changes under the specified load conditions.
4. Absolute non-linearity: The variation of analog voltage levels (vertical axis)
corresponding to the digital sample values (horizontal axis) is plotted in the following
figure as an example of the ADC or DAC response. Ideally, we expect a linear
variation of analog voltage given by VA(k) = k ΔVLSB as a function of the digital
sample values (k = 0 .. 2N-1) for an N-bit ADC or DAC. Absolute non-linearity is
the maximum deviation of the actual converter response from the ideal linear
conversion function.
Analog Voltage
VA(k) (V) ideal linear
response
(2N-1)xΔVLSB
absolute
non-linearity

actual
ADC/DAC
response
1xΔVLSB (digital
0xΔVLSB k sample
0 1 2N-1 value)

5. Differential non-linearity: Difference between the analog voltage levels


VA(k) _ VA(k-1) corresponding to successive pairs of digital sample values is plotted

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 15


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

in the following. Ideally, all difference voltages should be exactly one ΔVLSB on the
analog side or one LSB on the digital side throughout the conversion range.
Differential non-linearity is the maximum deviations from this ideal behavior above
and below the ideal response line.
Analog Voltage : ideal linear response
VA(k) : actual ADC/DAC response
(2N-1)xΔVLSB
(2N-2)xΔVLSB

5xΔVLSB
4xΔVLSB
3xΔVLSB
2xΔVLSB
1xΔVLSB
(digital
0xΔVLSB k sample
0 1 2 3 4 5 2N-2 2N-1 value)

Differential : ideal linear response


Analog Voltage
VA(k)-VA(k-1) : actual ADC/DAC response

3xΔVLSB
differential
2xΔVLSB non-linearity

1xΔVLSB

0xΔVLSB

-1xΔVLSB (digital
k sample
1 2 3 4 5 6 7 8 9 10 2N-5 2N-3 2N-1 value)
2N-4 2N-2

Differential non-linearity is a measure of how smoothly the analog signal varies as we


step through the entire range of digital sample values. Normally, differential non-
linearity of an ADC or DAC should be within + _ 1 LSB. If it is greater than +1 LSB,
then the analog voltage increases by more than 2xΔVLSB between two successive
digital values. If it is less than -1 LSB, then the analog voltage decreases while it is
expected to increase.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 16


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

4.10 Conversion Applications


It will be helpful to clarify the frequently used engineering terminology related to
measurement and control applications. Descriptions of the common instrumentation
terms are given below.
Accuracy: Difference between the actual value and the measured value.
Accuracy is a specification of the total measurement error regardless of the type or
source of error.
Resolution: Smallest increment that can be identified with certainty.
Resolution expresses the ability to discriminate nearly equal values, and it mainly
determines the quantization error in digital readings. A device may have a high-
resolution, but it may not have the same accuracy if the readings contain errors. For
example, one can monitor temperature changes in 0.1 ºC steps using a digital
thermometer with 0.1 ºC resolution. If this thermometer has + _ 1.0 ºC linearity error,
then the digit displayed after the decimal point is useless in absolute temperature
measurements.
Sensitivity: The incremental output generated in response to an incremental
change in the input.
Sensitivity simply specifies an average gain or input-to-output transfer function over
the operating range. For example, if a temperature sensor has 10 mV/ºC sensitivity,
then its output increases by 10 mV when the measured temperature rises by 1 ºC.
Linearity: Uniformity of sensitivity in the measurement range.
In practice, linearity error or non-linearity is specified as the maximum deviation
from the best linear fit to the system response.
Stability: Consistency in output for a constant input.
Drifts (slow variations) in sensitivity or offset level may affect the measurements
mostly due to environmental conditions (temperature, humidity, pressure, etc.) or
simply due to time.
Reproducibility: Ability to produce the same output for the same input applied over
some time.

We refer to the specifications included in device datasheets to determine


whether each component is suitable for our purposes in an application. We need to
find answers to several questions related to timing and amplitude specifications.
Timing specifications:
How fast: Bandwidth, slew rate, settling time for analog signals, clock
frequency, response time, setup and hold time requirements for digital signals.
How accurate: Frequency accuracy and stability, time resolution, jitter,
variation in response time.
Amplitude specifications:
How big: Gain, I/O signal range for analog signals, I/O level compatibility (TTL,
CMOS, LVDS, etc.) for digital signals.
How accurate: Amplitude resolution, linearity, noise figure, distortion for
analog signals.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 17


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

Driving capability: Receiver load, termination requirements, wiring or routing


distance.

An embedded system interacting with the physical world converts continuous


input variables of time and amplitude into numbers that can be processed in the
microcontroller, and it converts the resulting numbers into continuous variables at the
output. The conversion process introduces errors in addition to the errors that
already exist in the continuous domain. The following table summarizes the error
sources involved in the conversion process.

Amplitude conversions Time conversion using


Type of error
using ADCs, DACs timers, PWM modules

Error at the input source non-linearity of sensor or timing accuracy, jitter,


or output target driver, distortion, noise bandwidth restrictions

Quantization error _ 1/2 ΔVLSB


+ _ 1/2 Tclk or +
+ _ Tclk

Reference error Vref accuracy Fclk accuracy

ADC/DAC non-linearity, response time variation


Processing error
settling time limitations (if any)

Quantization error: The accuracy in any conversion operation between analog and
digital signal domains is limited by the minimum step size in the analog domain. For
example, the minimum step size is given by ΔVLSB for an ADC. The numbers at the
ADC output correspond to the input voltage levels quantized as 0xΔVLSB, 1xΔVLSB,
2xΔVLSB, . . . If the actual sampled voltage at the ADC analog input is 1.5xΔVLSB,
then the ADC produces either 1 or 2 at the digital output. In any case, we have
+0.5xΔVLSB or -0.5xΔVLSB error after the quantization.
The effect of quantization error in time-related measurements and timing control
can be different depending on the synchronization of the timing signal with the
reference clock. The following two figures show the shortest and longest possible
time periods that may produce the same quantized time value of kxTclk for two
cases. In the first case, beginning of the timing signal is synchronized with the clock.
The counter stops at k, after the falling edge of the timing signal. The actual timing
period may vary between (k-1)xTclk and kxTclk, resulting in a random quantization
_ 1/2 Tclk range.
error in +

Case-1: Beginning of timing signal is synchronized with reference clock:


Ref. Clk

Counter 0 1 2 k-1 k
Shortest Tclk
Timing Signal
~(k-1) Tclk
Longest
Timing Signal
~k Tclk

In the second case, there is no synchronization between the timing signal and
the reference clock. There are timing uncertainties at the beginning and at the end of

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 18


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

the measured period. The quantized value of the time period is kxTclk while the
actual time in continuous domain may vary between (k-1)xTclk and (k+1)xTclk,
_ 1 Tclk range.
resulting in a quantization error in +

Case-2: No synchronization between timing signal and reference clock:


Ref. Clk

Counter 0 1 2 k-1 k
Shortest Tclk
Timing Signal
~(k-1) Tclk
Longest
Timing Signal
~(k+1) Tclk

The second case described above represents a typical situation where a processor
receives a timing signal from an asynchronous source. The quantization error of time
measurements increases by a factor of two when there is no common time reference
for t = 0. Voltage measurements on the other hand, have a reference level for V = 0
given by the signal ground.

Reference error: Accuracy of a measurement cannot be any better than the


accuracy of the reference source used in the measurement. All time conversions rely
on the accuracy of the reference clock, and all amplitude conversions rely on the
accuracy of the reference voltage or current. Generally, the maximum error due to
reference variation occurs at the longest time duration or the highest signal amplitude
involved in the conversions. If an ADC has a 1V + _ 1% reference voltage source, then
_ 1mV error when the input signal is 100mV, and +
this will cause + _ 5mV error when
the input signal is 500mV.

Processing error: This is a generic term that refers to the other errors introduced
during the conversion process. If a time measurement relies on the immediate
response of the processor to some external events, then the accuracy of the
produced result depends on the delay time between the actual event and the
processor's response. The deterministic or repeatable part of the error can be
corrected by using compensation techniques. For example, the error due to the
average response time of a processor can be compensated by applying an offset to
the measured values. On the other hand, random variations in the response time are
not predictable, and they cannot be corrected. Similarly, if the non-linear response of
a sensor or an ADC can be characterized thoroughly, then the non-linearity errors
can be corrected to some extend by using look-up tables and interpolation methods.
Such correction methods demand processor time which may not be available in
simple microcontrollers.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 19


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

4.10.1 Application Example: ADC Setup


A magnetic flux density measurement setup needs to be designed with a Hall-
effect sensor. The design requirement is to obtain the highest possible sampling rate
_ 0.2 mT (milli Tesla) error in the measurements. Following
while having less than +
are the related component parameters, error sources (in red) and available options
(in blue).
 Magnetic flux density range to be measured: 0 -- 60 mT
 Hall-effect sensor sensitivity: 20 V/T, offset: 0 mV
_ 0.1 mT
 Hall-effect sensor non-linearity error: +
 ADC resolution: 12 bit at 10 kS/s, 11 bit at 12 kS/s, 10 bit at 15 kS/s
 ADC absolute non-linearity error: + _ 1 LSB
 Vref reference voltage options for ADC: 1.0 V, 2.0 V and 5.0 V
 Reference voltage accuracy: + _ 400 ppm at 20 ºC
 Reference voltage temperature drift: 5 ppm/ºC
 Temperature range: 0ºC -- 40ºC
The primary objective of all measurement applications is to prevent fatal errors,
such as out-of-range inputs and overflow conditions. Achievement of best possible
accuracy and/or highest possible sampling rate are the secondary objectives. In this
example there are two settings, ADC resolution and reference voltage, that should be
determined according to the design requirements.
First the signal range at the ADC input should be calculated to satisfy the
primary objective. The minimum sensor output is 0 mV according to the magnetic
flux density range, and the maximum sensor output is 60 mT x 20 V/T = 1200 mV.
In order to obtain the best resolution, we should choose the lowest possible reference
voltage that covers the ADC input signal range.
 Vref = 1.0 V does not work because it is lower than 1200 mV.
 Vref = 2.0 V should be selected because it is the lowest reference voltage
higher than 1200 mV.
 Vref = 5.0 V covers the input range too, but the corresponding ΔVLSB will be
much bigger resulting in low voltage resolution.
The error due to reference voltage uncertainties can be calculated after the
_ 400 ppm at 20 ºC
Vref = 2.0 V is determined. The part-to-part variation in Vref is +
and the additional variation due to temperature changes is + _ 20 ºC x 5 ppm/ºC =
_ 100 ppm. The total Vref variation is +
+ _ 500 ppm and the maximum error in the
voltage measurements is + _ 0.6 mV which is +
_ 500 ppm of 1200 mV sensor output
voltage in the worst case.
Normally it is possible to calculate the total error in terms of the measured
magnetic flux density (mT), ADC voltage input (mV) and the digital conversion result
(LSB). However, in this example we do not know the conversion step ΔVLSB
because the ADC resolution is yet to be decided. The following table lists all known
error values and the unknown values are marked as "???".

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 20


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

Known errors in mT, mV and LSB in mT in mV in LSB


Hall-effect sensor non-linearity error _ 0.1
+ _ 2.0
+ ???
Quantization error ??? ??? _ 0.5
+
Maximum error due to Vref uncertainty _ 0.03
+ _ 0.6
+ ???
ADC absolute non-linearity error ??? ??? _ 1.0
+
Total error ??? ??? ???

It is necessary calculate the total error values in mT for all possible ADC resolution
settings as shown in the following table. The quantization error (+ _ 0.5 LSB) and ADC
_
non-linearity error (+1.0 LSB) are constant values in the digital domain, but their
analog equivalents decrease when the ADC resolution increases. The number of
digital steps for each resolution setting is rounded to the nearest thousand (i.e.
210 = 1024 ~ ~ 1000) in calculation of ΔVLSB values for this table.

Calculated errors in mT for all ADC 10-bit ADC 11-bit ADC 12-bit ADC
resolution settings ΔVLSB=2.0mV ΔVLSB=1.0mV ΔVLSB=0.5mV
Hall-effect sensor non-linearity error _ 0.1
+ _ 0.1
+ _ 0.1
+
Quantization error _ 0.05
+ _ 0.025
+ _ 0.0125
+
Maximum error due to Vref uncertainty _ 0.03
+ _ 0.03
+ _ 0.03
+
ADC absolute non-linearity error _ 0.1
+ _ 0.05
+ _ 0.025
+
Total error _ 0.28
+ _ 0.205
+ _ 0.1675
+

According to the above table, the ADC should be used with 12-bit resolution at
10 kS/s sampling rate in order to keep the total error less than + _ 0.2 mT in the
measurements. Higher sampling rates can be obtained with the lower ADC
_ 0.2 mT. The following
resolution settings but the resultant total error is greater than +
table lists all error values in mT, mV and LSB for 12-bit ADC resolution.

Final errors in mT, mV and LSB for


12-bit ADC (ΔVLSB = 0.5 mV) in mT in mV in LSB
Hall-effect sensor non-linearity error _ 0.1
+ _ 2.0
+ _ 4.0
+
Quantization error _ 0.0125
+ _ 0.25
+ _ 0.5
+
Maximum error due to Vref uncertainty _ 0.03
+ _ 0.6
+ _ 1.2
+
ADC absolute non-linearity error _ 0.025
+ _ 0.5
+ _ 1.0
+
Total error _ 0.1675
+ _ 3.35
+ _ 3.8
+

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 21


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

4.10.2 Application Example: Timer Setup


A time measurement setup is required to detect speed of a motor with 0.1 %
accuracy. Motor speed will be determined by measuring the revolution time of the
rotor.

Side view: Sensor Top view:


(optocoupler,
hall effect sensor,
or
back EMFdetector)
Motor Sensor

Jitter

Sensor output:
Timer counter: N0 0 1 2 N1 0 1 2 N2 0 1 2

The sensor generates a short pulse every time it detects the marker attached to the
rotor. A timer is necessary to count the number of clock cycles between the sensor
pulses.
The counter result is a measure of the revolution time Trev and it is inversely
related to the motor speed in rpm: Speed (rpm) = 60,000/Trev (ms). This non-linear
1/x function can be approximated by a linear relation for the analysis of small
variations around a target value as shown in the following plot. If the_ motor speed
varies +_ 5 % around 1200 rpm, then this will result in approximately +5 % variation in
the count result. Similarly, if the reference clock frequency changes by + _ 0.1 %, then
_ 0.1 % error in the count result.
this will result in +
Motor Speed
(rpm)
3000

+
_ 5% 2400

+
_ 5% 1200

800

rev.
0 time
0 20 25 50 75 (ms)
+
_ 5% +
_ 5%

Related MCU Hardware


Clock Generator:
The clock generator will provide the timing reference for the measurements.
Precision and stability of an RC oscillator is not good enough to obtain the required
0.1 % accuracy. For example, precision of the internal RC oscillator provided with
the Atmel ATmega328 microcontroller is limited by 10 %. Even if the oscillator is

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 22


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

tuned exactly at the desired frequency, it may still have 1 % variation due to
temperature changes according to the ATmega328 datasheet. Therefore, a crystal
oscillator should be used to obtain the required 0.1 % accuracy.
Timer:
The timer clock frequency and the number of bits in the timer counter are the critical
specifications that will be determined in this design example. The functionality of the
timer module may introduce additional processing error. In practice, we should refer
to the timer module description and determine whether any CPU processing time is
required to 1) start / stop the timer, and 2) read the count result. If that is the case,
then any random variation in the CPU response time will cause additional errors. In
this example, we will assume that such processing errors are zero for simplicity.
We should first determine some of the design specifications before starting any
calculation:
Motor speed control range: Minimum 1200 rpm, maximum 2400 rpm (determined
according to the application requirements).
Jitter at the sensor output: + _ 10 µs (given in the sensor specifications).
Reference clock precision: + _ 100 ppm over the operating temperature range
(given by the crystal oscillator specifications).
The following table summarizes the design parameters and the error components for
the minimum and maximum motor speeds.

at 1200 rpm at 2400 rpm


Revolutions per second 20 rev/s 40 rev/s
Revolution time 50 ms 25 ms
Maximum allowed error in time measurement
_ 50 µs
+ _ 25 µs
+
_ 0.1 % of the revolution time)
(+
Error at the sensor output (jitter specification) _ 10 µs
+ _ 10 µs
+
should be should be
Quantization error (to be determined according to
less than less than
the timer clock frequency) _ 35 µs _ 12.5 µs
+ +
Reference error (+_ 100 ppm of the measured time
_ 5.0 µs
+ _ 2.5 µs
+
period according to the oscillator specifications)
Processing error (given by the requirements of the
0 µs 0 µs
timer)

We must add up all error components in order to consider the worst case scenario of
all possibilities. The quantization error should be small enough to keep the total error
less than the maximum allowed + _ 0.1 % error over the entire speed range. The
quantization error will be given by the + _ Tclk (clock period) of the timer clock. The
timer clock frequency should be greater than 80 KHz to have the quantization error
less than +_ 12.5 µs, so that the total error is less than +
_ 25 µs at 2400 rpm.
We can determine the number of timer bits after we choose the timer clock
frequency. The timer should be able to count through the longest measurement
period without an overflow. In this case, the longest revolution time is 50 ms at
1200 rpm. If the counter clock input is exactly 80 KHz then the corresponding

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 23


İYTE - Department of Electrical and Electronics Engineering B. Özdemirel

counter result is 4000 (50 ms/12.5 µs). At least a 12-bit counter (212 = 4096) is
required for the revolution time measurements.

Practical Considerations
In practice, we cannot get the exact values required for our design. Instead we
are forced to choose from a set of available predefined options according to the MCU
hardware we are using.
Number of timer bits:
We found that the minimum required number of timer bits is 12 when the timer clock
frequency is 80 KHz. We should note that a 12-bit counter will overflow when the
motor speed drops down to 1172 rpm (revolution time exceeds 51.19 ms).
Depending on the load conditions of the motor, an overflow may easily occur since
1172 rpm is very close to 1200 rpm. It will be wise to use a 13-bit timer that can
provide sufficient safety margin to prevent an overflow. Most of the MCUs have
either 8-bit or 16-bit timers. If a 16-bit timer is available, then the timer clock
frequency can be much higher than 80 KHz.
Timer clock frequency:
Timer modules are usually equipped with a clock prescaler providing a variety of
timer clocks to choose from. The most common type of prescaler is a simple counter
that can reduce the main system clock frequency by a factor of 2N. The divider
power, N, is programmable through the SFRs that control the timer functions. For
example, in an MCU that has 4 MHz main system clock, the timer clock frequency at
the prescaler output can be 4 MHz, 2 MHz, 1 MHz, 500 kHz, 250 kHz, 125 kHz,
62.5 kHz, or 31.25 kHz. The lowest frequency we can choose for a 13-bit timer is
125 KHz, since any clock frequency lower than 80 kHz will result in too much
quantization error. If a 16-bit timer is used, then the maximum clock frequency we
can choose is 1 MHz that allows time measurements up to ~64 ms.

EE443 - Embedded Systems - Lecture 4: Microcontroller Hardware 24

You might also like