Atmel AVR Microcontroller
Atmel AVR Microcontroller
www.morganclaypool.com
DOI: 10.2200/S00100ED1V01Y200712DCS015
A Publication in the Morgan & Claypool Publishers series
Lecture #15
Series Editor: Mitchell A. Thornton, Southern Methodist University
Series ISSN
Steven F. Barrett
University of Wyoming
Daniel J. Pack
United States Air Force Academy
Why Atmel? There are many excellent international companies that produce
microcontrollers. As Atmel states, ‘‘Atmel Corporation is an industry leader in
the design and manufacture of advanced semiconductors, with focus on
microcontrollers, nonvolatile memory, logic, radio frequency components and
sensors.’’ Some of the highlights of the Atmel AVR line include
Although all of these features are extremely important, we have chosen to focus
on the Atmel AVR line of microcontrollers for this primer for a number of other
related reasons:
• The learning curve for Atmel microcontrollers is gentle. If this is your first
exposure to microcontrollers, you will quickly come up to speed on
microcontroller programming and interfacing. If you already know another
line of processors, you can quickly apply your knowledge to this powerful
line of 8-bit processors.
• The AVR line provides a full range of processing power, from small 8-pin
processors to complex 100-pin processors. The same compiler and
programming hardware may be used with a wide variety of
microcontrollers.
• Many of the AVR microcontrollers are available in dual inline package,
which makes them readily useable on a printed circuit board prototype
(e.g., senior design projects).
• Many of the microcontrollers in the AVRline are pin-for-pin compatible
with one another.This allows you to easily move up and down the AVR line
as your project becomes better defined.
• Atmel has documentation available for every microcontroller at your
fingertips. Simply visit www.atmel.com Furthermore, Atmel customer
support is good and responsive.
• There is worldwide interest in the AVR microcontroller line. We would be
remiss to not mention AVR Freaks. This is a dedicated, international group
of AVR experts who share their expertise online with other high-power
users and novices alike.
Most of all, we thank our families. We acknowledge our parents. Thank you,
Moms (Eleanore and Jackie), and thank you, Dad (Frank), for always believing in
me (S.B.). Thank you, Moms (Young Shin and Rana), and thank you, Dads (Sung
Bock and Chong Kon), for your encouragement and unfailing support (D.P.).
Finally, our work could not have come to fruition without the sacrifices of our
family members: Cindy, Heidi, Heather, Jon R., Christine, Jon B.,Andrew, and
Graham. As always, without you none of this would matter. We love you!
1.1 ATmega16ArchitectureOverview...................................................... 1
1.1.1 Reduced Instruction Set Computer ......................................... 1
1.1.2 Assembly Language Instruction Set ........................................ 2
1.1.3 ATmega16ArchitectureOverview ............................................ 3
We will program the Atmel ATmega16 using the C language throughout the
text. The C programming language allows for direct control of microcontroller
hardware at the register level while being portable to other microcontrollers in
the AVR line. When a C program is compiled during the software development
process, the program is first converted to assembly language and then to the
machine code for the specific microcontroller. We must emphasize that
programming in C is not better than assembly language or vice versa. Both
approaches have their inherent advantages and disadvantages. We have chosen
to use C in this textbook for the reasons previously discussed.
As can be seen from the figure, the ATmega16 has external connections for power
supplies (VCC, GND, AVCC, and AREF), an external time base (XTAL1 and XTAL2) input
pins to drive its clocks, processor reset (active low RESET), and four 8-bit ports (PA0-PA7,
PC0-PC7, PB0-PB7, and PD0-PD7), which are used to interact with the external world. As
we shall soon see, these ports may be used as general purpose digital input/output (I/O)
ports or they may be used for the alternate functions. The ports are interconnected with
the ATmega16’s CPU and internal subsystems via an internal bus. The ATmega16 also
contains a timer subsystem, an analog-to-digital converter (ADC), an interrupt subsystem,
memory components, and a communication subsystem.
Can be programmed outside its resident circuit using a flash programmer board. We will
use this technique throughout the book. Specifically, we will use the Atmel STK500 AVR
Flash MCU Starter Kit for programming the ATmega16. This inexpensive development
board (less than $100) is readily available from a number of suppliers.
As shown in Figure 1.2, each port has three registers associated with it:
• Data Direction Register (DDRx)---used to set a specific port pin to either output (1)
or input (0), and
• Input Pin Address (PINx)---used to read input data from the port.
Figure 1.2(b) describes the settings required to configure a specific port pin to either
input or output. If selected for input, the pin may be selected for either an input pin or
to operate in the high-impedance (Hi-Z) mode. In Hi-Z mode, the input appears as high
impedance to a particular pin. If selected for output, the pin may be further configured
for either logic low or logic high.
Port pins are usually configured at the beginning of a program for either input or
output, and their initial values are then set. Usually, all eight pins for a given port are
configured simultaneously. A code example is provided below to show how ports are
configured. Note that because we are using the C programming language with a compiler
include file, the register contents are simply referred to by name. Note that the data
direction register (DDRx) is first used to set the pins as either input or output, and then
the data register (PORTx) is used to set the initial value of the output port pins.
//***************************************************************
//initialize_ports: provides initial configuration for I/O ports
//***************************************************************
void initialize_ports(void)
{
DDRA=0xfc; //set PORTA[7:2] as output, PORTA[1:0]
//as input (1111_1100)
PORTA=0x03; //initialize PORTA[7:2] low, PORTA[1:0]
//current source
DDRB=0xa0; //PORTB[7:4] as output, set PORTB[3:0] as input
PORTB=0x00; //disable PORTB pull-up resistors
To read the value from a port pin configured as input, the following code could
be used. Note the variable used to read the value fromthe input pins is declared as an
unsigned char because both the port and this variable type are 8 bits wide.
:
:
:
To provide for a wider range of frequency selections, an external time source may
be used. The external time sources, in order of increasing accuracy and stability, are an
external RC network, a ceramic resonator, or a crystal oscillator. The system designer
chooses the time base frequency and clock source device appropriate for the application
at hand.
The ATmega16 is equipped with four PWM channels. The PWM channels coupled
with the flexibility of dividing the time base down to different PWMsubsystemclock
source frequencies allows the user to generate a wide variety of PWMsignals, from
relatively high-frequency, low-duty cycle signals to relatively low-frequency, high-duty
cycle signals. PWMsignals are used in a wide variety of applications, including controlling
the position of a servo motor and controlling the speed of a DC motor. We discuss the
operation, programming, and application of the PWMsystem in Chapter 5 of the text.
1.4.4.2 Serial Peripheral Interface. The ATmega16 SPI can also be used for two-
way serial communication between a transmitter and a receiver. In the SPI system,
the transmitter and receiver share a common clock source. This requires an
additional clock line between the transmitter and receiver but allows for higher
data transmission rates as compared with the USART.
The SPI may be viewed as a synchronous 16-bit shift register with an 8-bit
half residing in the transmitter and the other 8-bit half residing in the receiver.
The transmitter is designated the master because it provides the synchronizing
clock source between the transmitter and the receiver. The receiver is designated
as the slave. We discuss the operation, programming, and application of the SPI
in Chapter 2 of the text.
1.4.4.3 Two-Wire Serial Interface. The TWI subsystem allows the system
designer to network a number of related devices (microcontrollers, transducers,
displays, memory storage, etc.) together into a system using a two-wire
interconnecting scheme. The TWI allows a maximum of 128 devices to be
connected together. Each device has its own unique address and may both
transmit and receive over the two-wire bus at frequencies up to 400 kHz. This
allows the device to freely exchange information with other devices in the
network within a small area.
1.4.6 Interrupts
The normal execution of a program step follows a designated sequence of instructions.
However, sometimes, this normal sequence of events must be interrupted to respond to
high-priority faults and status both inside and outside the microcontroller. When these
higher-priority events occur, the microcontroller must temporarily suspend normal
operation and execute event specific actions called an interrupt service routine. Once the
higher priority event has been serviced, the microcontroller returns and continues
processing the normal program.
1.5.1 Packaging
The ATmega16 comes in three different packaging styles: a 40-pin plastic dual in-line
package (DIP), a 44-lead thin quad flat pack package, and a 44-pad quad flat
nonlead/microlead frame package. The Pinout Diagram for the different packaging
options are provided in Figure 1.3.
The current draw for the microcontroller is quite low. For example, when the
ATmega16L is actively operating at 3 MHz from a 3-VDC power source, the current draw
is 1.1 mA. When placed in the idle mode, the microcontroller current draw reduces to less
than 0.35 mA. Finally, in the power-down mode, the microcontroller will draw less than
1 µA of current from the voltage source.
To minimize power consumption, the microcontroller can be placed into various
low current sleep modes. There are six different sleep modes available to the system
designer. The
Aside from the input hardware on PORTB and the output display hardware on PORTA of
the controller, there are power (pins 10, 30, and 32) and ground (pins 11 and 31)
connections. A standard 5-VDC power supply may be used for the power connections. For
portable applications, a 9-VDC battery equipped with a 5-VDC regulator (LM340-05 or
uA7805) may be used as a power source. Pins 9 through 11 have a resistor (1 M), two
capacitors (1.0 µF), and a tact switch configured to provide a reset switch for the
microcontroller. We use a ZTT 10-MHz ceramic resonator as the time base for the
Testbench. It is connected to pins 12 (XTAL2) and 13 (XTAL1) of the ATmega16.
//*************************************************************
//file name: testbench.c
//function: provides test bench for ATMEL AVR ATmega16 controller
//target controller: ATMEL ATmega16
//
//ATMEL AVR ATmega16 Controller Pin Assignments
//Chip Port Function I/O Source/Dest Asserted Notes
//Pin 1 PB0 to active high RC debounced switch
//Pin 2 PB1 to active high RC debounced switch
//Pin 3 PB2 to active high RC debounced switch
16 ATMEL AVRMICROCONTROLLERPRIMER: PROGRAMMINGANDINTERFACING
//Pin 40 PA0
//
//author: Steven Barrett and Daniel Pack
//created: July 12, 2007
//last revised: July 12, 2007
//***************************************************************
//include files**************************************************
#include<iom16v.h> //ImageCraft ICC AVR
//include file
//for ATmega16
//function prototypes********************************************
//main program***************************************************
//global variables
unsigned char old_PORTB = 0x00; //present value of PORTB
unsigned char new_PORTB; //new values of PORTB
void main(void)
{
initialize_ports(); //initialize ports
while(1){//main loop
new_PORTB = PINB; //read PORTB
//***************************************************************
//initialize_ports: provides initial configuration for I/O ports
//***************************************************************
void initialize_ports(void)
{
DDRA=0xff; //set PORTA[7:0] as output
PORTA=0x00; //initialize PORTA[7:0] low
Software tools: Throughout the text, we use the ImageCraft ICC AVR
compiler. This is an excellent, user-friendly compiler. There are other excellent
compilers available. The compiler is used to translate the source file (testbench.c)
into machine language for loading into the ATmega16. We use Atmel’s AVR Studio
to load the machine code into the ATmega16.
Hardware tools: We use Atmel’s STK500 AVR Flash MCU Starter Kit
(STK500) for programming the ATmega16. The STK500 provides the interface
hardware between the host PC and the ATmega16 for machine code loading. The
STK500 is equipped with a complement of DIP sockets, which allows for
programming all of the microcontrollers in the Atmel AVR line.
The software techniques discussed in the textbook are based on the ATmega16;
however, the developed software may be easily ported for use with other Atmel
AVR microcontrollers. To ease the transition to another microcontroller, it is
suggested using a direct bit assignment technique. Instead of setting an entire
register content at once, selected bits may be set. The individual bit definitions
for the ATmega16 are provided in Appendix B.
For example, to set the UCSRB register, the following individual bit
assignments may be used:
as opposed to:
When transporting code, the header file for the specific microcontroller must be
used, and also, the interrupt vector numbers may require change.
1.9 SUMMARY
In serial transmission, a byte of data is sent a single bit at a time. Once 8 bits
have been received at the receiver, the data byte is reconstructed. Although this
is inefficient froma time point of view, it only requires a line (or two) to transmit
the data.
Data transmission rates are typically specified as a baud or bits per second rate.
For example, 9600 baud indicates data are being transferred at 9600 bits per
second.
Often, serial communication systems must both transmit and receive data. To do
both transmissionand reception simultaneously requires separate hardware for
transmission and reception. A single duplex system has a single complement of
hardware that must be switched from transmission to reception configuration. A
full duplex serial communication system has separate hardware for transmission
and reception.
There are many different coding standards used within serial communications.
The important point is the transmitter and receiver must use a common coding
standard so data may be interpreted correctly at the receiving end. The Atmel
ATmega16 [2] uses a nonreturn to zero coding standard. In nonreturn to zero,
coding a logic 1 is signaled by a logic high during the entire time slot allocated
for a single bit, whereas a logic 0 is signaled by a logic low during the entire time
slot allocated for
a single bit.
SERIAL COMMUNICATIONSUBSYSTEM 27
2.2.6 Parity
To further enhance data integrity during transmission, parity techniques
may be used. Parity is an additional bit (or bits) that may be transmitted with the
data byte. The ATmega16 uses a single parity bit. With a single parity bit, a single-
bit error may be detected. Parity may be even or odd. In even parity, the parity
bit is set to 1 or 0, such that the number of 1’s in the data byte including the
parity bit is even. In odd parity, the parity bit is set to 1 or 0, such that the number
of 1’s in the data byte including the parity bit is odd. At the receiver, the number
of bits within a data byte including the parity bit are counted to ensure that parity
has not changed, indicating an error, during transmission.
FIGURE 2.1: ASCII Code. The ASCII code is used to encode alphanumeric
characters. The ‘‘0x’’ indicates hexadecimal notation in the C programming
language.
The ATmega16 USART is quite flexible. It has the capability to be set to a variety
of data transmission or baud (bits per second) rates. The USART may also be set
for data bit widths of 5 to 9 bits with one or two stop bits. Furthermore, the
ATmega16 is equipped with a hardware-generated parity bit (even or odd) and
parity check hardware at the receiver. A single parity bit allows for the detection
of a single bit error within a byte of data. The USART may also be configured to
operate in a synchronous mode. We now discuss the operation, programming,
and application of the USART. Because of space limitations, we cover only the
most basic capability of this flexible and powerful serial communication system.
SERIAL COMMUNICATIONSUBSYSTEM 29
FIGURE 2.2: Atmel AVR ATmega16 USART block diagram. Figure used with
permission of Atmel.
2.3.1 SystemOverview
The block diagram for the USART is provided in Figure 2.2. The block diagram
may appear a bit overwhelming, but realize there are four basic pieces to the
diagram: the clock generator, the transmission hardware, the receiver hardware,
and three control registers (UCSRA, UCSBR, and UCSRC). We discuss each in turn.
2.3.1.1 USART Clock Generator. The USART Clock Generator provides the clock
source for the USART system and sets the baud rate for the USART. The baud rate
is derived from the
30 ATMEL AVRMICROCONTROLLERPRIMER: PROGRAMMINGANDINTERFACING
overall microcontroller clock source. The overall system clock is divided by the USART
baud rate registers UBRR[H:L] and several additional dividers to set the baud rate. For the
asynchronous normal mode (U2X bit = 0), the baud rate is determined using the following
expression:
where UBRR is the content of the UBRRH and UBRRL registers (0--4095). Solving for UBRR
yields
2.3.1.2 USART Transmitter. The USART transmitter consists of a Transmit Shift Register.
The data to be transmitted are loaded into the Transmit Shift Register via the USART I/O
Data Register (UDR). The start and stop framing bits are automatically appended to the
data within the Transmit Shift Register. The parity is automatically calculated and
appended to the Transmit Shift Register. Data are then shifted out of the Transmit Shift
Register via the TxD pin a single bit at a time at the established baud rate. The USART
transmitter is equipped with two status flags: the USART Data Register Empty (UDRE) and
the transmit complete (TXC) flags. The UDRE flag sets when the transmit buffer is empty,
indicating it is ready to receive new data. This bit should be written to a zero when writing
the USART Control and Status Register A (UCSRA). The UDRE bit is cleared by writing to
the UDR. The TXC flag bit is set to logic 1 when the entire frame in the Transmit Shift
Register has been shifted out and there are no new data currently present in the transmit
buffer. The TXC bit may be reset by writing a logic 1 to it.
2.3.1.4 USART Registers. In this section, we discuss the register settings for controlling
the USART system. We have already discussed the function of the UDR and the USART
baud rate registers (UBRRH and UBRRL). Note: The USART Control and Status Register C
(UCSRC) and the USART baud rate register high (UBRRH) are assigned to the same I/O
location in the memory map (Figure 2.3). The URSEL bit (bit 7 of both registers)
determines which register
SERIAL COMMUNICATIONSUBSYSTEM 31
is being accessed. The URSEL bit must be 1 when writing to the UCSRC register
and 0 when writing to the UBRRH register. UCSRA. This contains the RXC, TXC,
and the UDRE bits. The function of these bits has already been discussed. UCSRB.
This contains the receiver and transmitter enable bits (RXEN and TXEN,
respectively). These bits are the ‘‘on/off’’ switch for the receiver and transmitter,
respectively. The UCSRB register also contains the UCSZ2 bit. The UCSZ2 bit in
the UCSRB register and the UCSZ[1:0] bits contained in the UCSRC register
together set the data character size.
32 ATMEL AVRMICROCONTROLLERPRIMER: PROGRAMMINGANDINTERFACING
UCSRC. This allows the user to customize the data features to the application at
hand. It should be emphasized that both the transmitter and receiver be
configured with the same data features for proper data transmission. The UCSRC
contains the following bits:
/*************************************************************
//USART_init: initializes the USART system
//************************************************************
void USART_init(void)
{
UCSRA = 0x00; //control register initialization
UCSRB = 0x08; //enable transmitter
UCSRC = 0x86; //async, no parity, 1 stop bit,
UBRRH = 0x00;
UBRRL = 0x40;
}
//************************************************************
//USART_transmit: transmits single byte of data
//************************************************************
//************************************************************
//USART_receive: receives single byte of data
//************************************************************
//************************************************************
The ATmega16 SPI also provides for two-way serial communication between a
transmitter and a receiver. In the SPI system, the transmitter and receiver share
a common clock source. This requires an additional clock line between the
transmitter and receiver but allows for higher data transmission rates as
compared with the USART. The SPI system allows for fast and efficient data
exchange between microcontrollers or peripheral devices. There are many SPI-
compatible external systems available to extend the features of the
microcontroller. For example, a liquid crystal display (LCD) or a digital-to-analog
converter (DAC) could be added to the microcontroller using the SPI system.
2.3.3.1 SPI Operation. The SPI maybe viewed as asynchronous 16- bit shift
register with an 8-bit half residing in the transmitter and the other 8-bit half
residing in the receiver as shown in Figure 2.5. The transmitter is designated the
master because it provides the synchronizing clock source between the
transmitter and the receiver. The receiver is designated as the slave. A slave is
chosen for reception by taking its slave select ( SS) line low. When the SS line is
taken low, the slave’s shifting capability is enabled. SPI transmission is initiated
by loading a data byte into the master configured SPI Data Register (SPDR). At that
time, the SPI clock generator provides clock pulses to the master and also to the
slave via the SCK pin. A single bit is shifted out of the master designated shift
register on the Master Out Slave In (MOSI) microcontroller pin on every
SERIAL COMMUNICATIONSUBSYSTEM 35
SCK pulse. The data are received at the MOSI pin of the slave designated device.
At the same time, a single bit is shifted out of the Master In Slave Out (MISO) pin
of the slave device and into the MISO pin of the master device. After eight master
SCK clock pulses, a byte of data has been exchanged between the master and
slave designated SPI devices. Completion of data transmission in the master and
data reception in the slave is signaled by the SPI Interrupt Flag (SPIF) in both
devices. The SPIF flag is located in the SPI Status Register (SPSR) of each device.
At that time, another data byte may be transmitted.
2.3.3.2 Registers. The registers for the SPI system are provided in Figure 2.6. We
will discuss each one in turn. SPI Control Register. The SPI Control Register (SPCR)
contains the ‘‘on/off’’ switch for the SPI system. It also provides the flexibility
for the SPI to be connected to a wide variety of devices with different data
formats. It is important that both the SPI master and slave devices be configured
for compatible data formats for proper data transmission. The SPCR contains the
following bits:
• SPI Enable (SPE) is the ‘‘on/off’’ switch for the SPI system. A logic 1 turns
the systemon and logic 0 turns it off.
36 ATMEL AVRMICROCONTROLLERPRIMER: PROGRAMMINGANDINTERFACING
• Data Order (DORD) allows the direction of shift from master to slave to be
controlled. When the DORD bit is set to 1, the least significant bit (LSB) of
the SPDR is transmitted first. When the DORD bit is set to 0, the Most
Significant Bit (MSB) of the SPDR is transmitted first. • The Master/Slave
Select (MSTR) bit determines if the SPI system will serve as a master (logic
1) or slave (logic 0).
• The Clock Polarity (CPOL) bit allows determines the idle condition of the
SCK pin. When CPOL is 1, SCK will idle logic high, whereas when CPOL is 0,
SCK will idle logic 0.
• TheClockPhase(CPHA)determinesifthedatabitwillbesampledontheleading(
0) or trailing (1) edge of the SCK.
• The SPI SCK is derived from the microcontroller’s systemclock source. The
systemclock is divided down to form the SPI SCK. The SPI Clock Rate Select
(SPR[1:0]) bits and the Double SPI Speed (SPI2X) bit are used to set the
division factor. The following divisions may be selected using SPI2X, SPR1,
and SPR0:
SPI Status Register. This contains the SPIF. The flag sets when eight data
bits have been transferred from the master to the slave. The SPIF bit is cleared by
first reading the SPSR after the SPIF flag has been set and then reading the SPDR.
The SPSR also contains the SPI2X bit used to set the SCK frequency.
SPI Data Register. As previously mentioned, writing a data byte to the SPDR
initiates SPI transmission.
2.3.3.3 Programming. To program the SPI system, the system must first be
initialized with the desired data format. Data transmission may then commence.
Functions for initialization, transmission, and reception are provided below. In
this specific example, we divide the clock oscillator frequency by 128 to set the
SCK clock frequency.
//************************************************************
//spi_init: initializes spi system
//************************************************************
//************************************************************
//spi_write: Used by SPI master to transmit a data byte
//************************************************************
SPDR = byte;
while (!(SPSR & 0x80));
}
//************************************************************
//spi_read: Used by SPI slave to receive data byte
//************************************************************
return SPDR;
}
//************************************************************
The TWI subsystem allows the system designer to network a number of related
devices (microcontrollers, transducers, displays, memory storage, etc.) together
into a system using a two-wire interconnecting scheme. The TWI allows a
maximum of 128 devices to be connected together. Each device has its own
unique address and may both transmit and receive over the two-wire bus at
frequencies up to 400 kHz. This allows the device to freely exchange information
with other devices in the network within a small area. Space does not permit a
detailed discussion of this advanced serial communication system.
2.5 SUMMARY
In this chapter, we have discussed the differences between parallel and serial
communications and key serial communication-related terminology. We then, in
turn, discussed the operation of USART, SPI, and TWI serial communication
systems. We also provided basic code examples to communicate with the USART
and SPI systems.
Analog-to-Digital Conversion
3.1 BACKGROUNDTHEORY
Before we discuss the ADC process, we need to familiarize you with underlying
theories that support the process. We start with some definitions on analog and
digital signals.
42 ATMEL AVRMICROCONTROLLERPRIMER: PROGRAMMINGANDINTERFACING
intensity changes in the spatial axis. The same analysis can be performed as we
move from the top to the bottom of the image.
Signals using digital signals. For example, human voices must be converted
to corresponding digital signals before they can be routed by digital switching
circuits in telephone communication systems. Similarly, voice commands to
robots must be converted to a digital form before robots can understand the
command.
As shown in the examples above, we live in an analog world; that is,
physical variables are analog signals. It is precisely this reason why the ADC is
so very important in any digital systems that interact with an analog
environment.
Harry Nyquist from Bell Laboratory studied the sampling process and
derived a criterion that determines the minimum sampling rate for any
continuous analog signals. His, now famous, minimum sampling rate is known
as the Nyquist sampling rate, which states that one must sample a signal at least
twice as fast as the highest frequency content of the signal of interest. For
example, if we are dealing with the human voice signal that contains frequency
components that span from about 20 Hz to 4 kHz, the Nyquist sample theorem
tells us that we must sample the signal at least at 8 kHz, 8000 ‘‘snapshots’’ every
second. Engineers who work for telephone companies must deal with such issues.
For further study on the Nyquist sampling rate, refer to Barrett
ANALOG-TO-DIGITALCONVERSION 45
and Pack [2] listed in the References section. Sampling is important because when
we want to represent an analog signal in a digital system, such as a computer, we
must use the appropriate sampling rate to capture the analog signal for a faithful
representation in digital systems.
Figure 3.4 shows how n bits are used to quantize a range of values. In many
digital systems, the incoming signals are voltage signals. The voltage signals are
first obtained from physical signals with the help of transducers, such as
microphones, angle sensors, and infrared sensors. The voltage signals are then
conditioned to map their range with the input range of a digital system, typically
0to5V.InFigure3.4, n bits allow you to divide the input signal range of a digital
system into
of quantization error introduced for both samples. Now consider Figure 3.5. The
same signal is sampled at the same time but quantized using a less number of
bits. Note that the quantization error is inversely proportional to the number of
bits used to quantize the signal. Once a sampled signal is quantized, the encoding
process involves representing the quantization level with the available bits. Thus,
for the first sample, the encoded sampled value is 0000 0001, whereas the
encoded sampled value for the second sample is 1100 0110. As a result of the
encoding process, sampled analog signals are now represented as a set of binary
numbers. Thus, the encoding is the last necessary step to represent a sampled
analog signal into its corresponding digital form, shown in Figure 3.6.
a range of 5 V and 1 bit to represent an analog signal. The resolution in this case
is 2.5 V, a very poor resolution. You can imagine how your TV screen will look if
you only had only two levels to represent each pixel, black and white. The
maximum error, called the resolution error, is 2.5 V for the current case, 50% of
the total range of the input signal. Suppose you now have 4 bits to represent
quantization levels. The resolution now becomes 1.25 V, or 25% of the input
range. Suppose you have 20 bits for quantization levels. The resolution now
becomes 4.77 × 10 , 9.54 × 10-5 % of the total range. The discussion we presented
simply illustrates that as we increase the available number of quantization levels
within a range, the distance between adjacent levels decreases, reducing the
quantization error of a sampled signal. As the number grows, the error decreases,
making the representation of a sampled analog signal more accurate in the
corresponding digital form. The number of bits used for the quantization is
directly proportional to the resolution of a system. You now should understand
the technical background when you watch high-definition television
broadcasting.
Now let us move onto the discussion of the data rate. The definition of the
data rate is the amount of data generated by a system per some time unit.
Typically, the number of bits or the number of bytes per second is used as the
data rate of a system. We just saw that the more bits we use for the quantization
levels, the more accurate we can represent a sampled analog signal. Why not use
the maximum number of bits current technologies can offer for all digital
systems, when we convert analog signals to digital counterparts? It has to do with
the cost involved. In particular, suppose you are working for a telephone
company and your switching system must accommodate 100,000 customers. For
each individual phone conversation, suppose the company uses an 8-kHz
sampling rate and you are using 10 bits for the quantization levels for each
sampled signal. If all customers are making out-of-town calls, what is the number
of bits your switching system must process to accommodate all calls? The answer
will be 100,000 × 8000 × 10, or 8 billion bits per every second! You will need
some major computing power to meet the requirement. For such reasons, when
designers make decisions on the number of bits used for the quantization levels,
they must consider the computational burden the selection will produce on the
computational capabilities of a digital system versus the required
systemresolution.
You will also encounter the term dynamic range when you consider finding
appropriate ADCs. The dynamic range is a measure used to describe the signal to
noise ratio. The unit used for the measurement is decibel, which is the strength
of a signal with respect to a reference signal. The greater the decibel number, the
stronger the signal is compared with a noise signal. The definition of the dynamic
range is 20 log 2 1b ,whereb is the number of bits used to convert analog signals
For the sake of our discussion, we ignore other overheads involved in processing a phone call such as
multiplexing, demultiplexing, and serial-to-parallel conversion.
50 ATMEL AVRMICROCONTROLLERPRIMER: PROGRAMMINGANDINTERFACING
to digital signals. Typically, you will find 8 to 12 bits used in commercial ADCs,
8
translating the dynamic range from 20 log 2 dB to 20 log 212 dB (Oppenheim and Schafer
[3]).
3.2 ANALOG-TO-DIGITALCONVERSIONPROCESS
The goal of the ADC process is to accurately represent analog signals as digital signals.
Toward this end, three signal processing procedures, sampling, quantization, and
encoding, described in the previous section must be combined together. Before the ADC
process takes place, we first need to convert a physical signal into an electrical signal
with the help of a transducer. A transducer is an electrical and/or mechanical system that
converts physical signals into electrical signals or electrical signals to physical signals.
Depending on the purpose, we categorize a transducer as an input transducer or an
output transducer. If the conversion is from physical to electrical, we call it an input
transducer. The mouse, the keyboard, and the microphone for your PC all fall under this
category. A camera, an infrared sensor, and a temperature sensor are also input
transducers. The output transducer converts electrical signals to physical signals. The
computer screen and the printer for your computer are output transducers. Speakers and
electrical motors are also output transducers. Therefore, transducers play the central part
for digital systems to operate in our physical world by transforming physical signals to
and from electrical signals.
In general, the scaling and bias process may be described by two equations :
FIGURE 3.7: A block diagram of the signal conditioning for an ADC. The range of the sensor voltage
output is mapped to the ADC input voltage range. The scalar multiplier maps the magnitudes of
the two ranges, and the bias voltage is used to align two limits.
The variable V min represents the maximum output voltage from the input transducer.
This voltage occurs when the maximum physical variable (X 1max ) is presented to the input
transducer. This voltage must be scaled by the scalar multiplier (K ) and then have a DC
offset bias voltage (B) added to provide the voltage V 2max max to the input of the ADC
converter.
Similarly, The variable V min represents the minimum output voltage from the input
transducer. This voltage occurs when the minimum physical variable (X1min ) is presented
to the input transducer. This voltage must be scaled by the scalar multiplier (K ) and then
have a DC offset bias voltage (B) added to produce voltage V2 min to the input of the ADC
converter.
Usually, the values of V1max and V1min are provided with the documentation for the
transducer. Also, the values of V 2max and V 2min are known. They are the high and low
reference voltages for the ADC system (usually 5 and 0 VDC for a microcontroller). We
thus have two equations and two unknowns to solve for K and B. The circuits to scale by
K and add the offset B are usually implemented with operational amplifiers. We refer
interested readers to Thomas and Rosa [4] listed in the References section.
Once a physical signal has been converted to its corresponding electrical signal
with the help of an input transducer and the output of the transducer mapped correctly
to the input of the ADC, the ADC process can start. The first step of the ADC process is
the sampling of the analog signal. When selecting a converter, one must consider the type
of physical signal that is being converted to properly ensure the sampling rate. As
discussed in the previous section, using the proper sampling rate is the first step that
determines whether an analog signal will be represented correctly in digital
52 ATMEL AVRMICROCONTROLLERPRIMER: PROGRAMMINGANDINTERFACING
systems. What this means for the reader is to select an ADC that can handle a required
conversion rate. Because most microcontrollers now come with a built-in ADC, one must
study the user manual portion discussing the conversion rate and make sure that the
required sampling rate for the application falls under the advertised conversion rate. For
example, if you need to convert the signal representing a person’s blood pressure, the
sampling rate with 100 Hz (100 samples per second) will suffice. On the other hand, if
you are dealing with human voice, you need at least an 8-kHz sampling rate capacity (see
Enderle et al. [5] for details).
Once the analog signal has been sampled, the quantization process takes place.
For this process, again one must decide how much quantization error can be allowed. At
one extreme where you are only concerned with finding out only two states, say on and
off, quantization error of 1 V is not important. We can operate safely with 2 bits with
maximum quantization error of 1.25 V. On the other hand, if we can only operate with
maximum quantization error of 0.01 V, we need to choose a converter with, at minimum,
10 bits (about 5 mV). To determine the number of bits and its corresponding maximum
quantization error, we use the following equation.
𝑟𝑎𝑛𝑔𝑒
Resolution =
2𝑏
Thus, we can determine the number of bits that will meet the error requirement using the
equation above.
Once the quantization level has been determined, we can now encode it using the
available bits. As seen in the previous section, the process is a simple conversion of a
decimal number (quantization level) to a binary number. Note that the binary number
should use all available bits. For example, quantization level 4 using 8 bits is converted
as 0000 0100, not 100.
In summary, the ADC process has three steps for completion: sampling,
quantization, and encoding. In the next section, we delve into four different technologies
used to implement the ADC process.