The AVR Microcontroller and Embedded Systems (PDFDrive)
The AVR Microcontroller and Embedded Systems (PDFDrive)
Online Part
629 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
CONTENTS
CHAPTER 8: AVR HARDWARE CONNECTION, HEX FILE, AND
FLASH LOADERS
SECTION 8.2: AVR FUSE BITS 631
SECTION 8.3: EXPLAINING THE HEX FILE FOR AVR 637
SECTION 8.4: AVR PROGRAMMING AND TRAINER BOARD 642
The AVR Microcontroller & Embedded Systems (Mazidi & Naimi) 630
SECTION 8.2: AVR FUSE BITS
There are some features of the AVR that we can choose by programming
the bits of fuse bytes. These features will reduce system cost by eliminating any
need for external components.
ATmega32 has two fuse bytes. Tables 8-6 and 8-7 give a short description
of the fuse bytes. Notice that the default values can be different from production
to production and time to time. In this section we examine some of the basic fuse
bits. The Atmel website (http://www.atmel.com) provides the complete description
of fuse bits for the AVR microcontrollers. It must be noted that if a fuse bit is incor-
rectly programmed, it can cause the system to fail. An example of this is changing
the SPIEN bit to 1, which disables SPI programming mode. In this case you will
not be able to program the chip any more! Also notice that the fuse bits are ‘0’ if
they are programmed and ‘1’ when they are not programmed.
In addition to the fuse bytes in the AVR, there are 4 lock bits to restrict
access to the Flash memory. These allow you to protect your code from being
copied by others. In the development process it is not recommended to program
lock bits because you may decide to read or verify the contents of Flash memory.
Lock bits are set when the final product is ready to be delivered to market. In this
book we do not discuss lock bits. To study more about lock bits you can read the
data sheets for your chip at http://www.atmel.com.
631 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Clock
Multiplexer
C2
NC XTAL2 XTAL2
22 pF
EXTERNAL C1
OSCILLATOR XTAL1 XTAL1
SIGNAL 22 pF
GND
GND
Solution:
(a) Instruction cycle time is 1/(4 MHz) = 250 ns
(b) Instruction cycle time is 1/(8 MHz) = 125 ns
(c) Instruction cycle time is 1/(10 MHz) = 100 ns
633 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Fuse bits and reset delay
The most difficult time for a system is during power-up. The CPU needs
both a stable clock source and a stable voltage level to function properly. In AVRs,
after all reset sources have gone inactive, a delay counter is activated to make the
reset longer. This short delay allows the power to become stable before normal
operation starts. You can choose the delay time through the SUT1, SUT0, and
CKSEL0 fuses. Table 8-11 shows start-up times for the different values of SUT1,
SUT0, and CKSEL fuse bits and also the recommended usage of each combina-
tion. Notice that the third column of Table 8-11 shows start-up time from power-
down mode. Power-down mode is not discussed in this book.
Brown-out detector
Occasionally, the power source provided to the VCC pin fluctuates, caus-
ing the CPU to malfunction. The ATmega family has a provision for this, called
brown-out detection. The BOD circuit compares VCC with BOD-Level and resets
the chip if VCC falls below the BOD-Level. The BOD-Level can be either 2.7 V
when the BODLEVEL fuse bit is one (not programmed) or 4.0 V when the
BODLEVEL fuse is zero (programmed). You can enable the BOD circuit by pro-
gramming the BODEN fuse bit. When VCC increases above the trigger level, the
BOD circuit releases the reset, and the MCU starts working after the time-out peri-
od has expired.
A good rule of thumb
There is a good rule of thumb for selecting the values of fuse bits. If you
are using an external crystal with a frequency of more than 1 MHz you can set the
CKSEL3, CKSEL2, CKSEL1, SUT1, and SUT0 bits to 1 (not programmed) and
clear CKOPT to 0 (programmed).
Table 8-11: Startup Time for Crystal Oscillator and Recommended Usage
CKSEL0 SUT1...0 Start-Up Time Delay from Recommended
from Power-Down Reset (VCC = 5) Usage
0 00 258 CK 4.1 Ceramic resonator,
fast rising power
0 01 258 CK 65 Ceramic resonator,
slowly rising power
0 10 1K CK - Ceramic resonator,
BOD enabled
0 11 1K CK 4.1 Ceramic resonator,
fast rising power
1 00 1K CK 65 Ceramic resonator,
slowly rising power
1 01 16K CK - Crystal oscillator,
BOD enabled
1 10 16K CK 4.1 Crystal oscillator,
fast rising power
1 11 16K CK 65 Crystal oscillator,
slowly rising power
As an example, examine Program 8-1. It will toggle all the bits of Port B
with some delay between the “on” and “off” states.
DELAY:
LDI R20,16
L1: LDI R21,200
L2: LDI R22,250
L3:
NOP
NOP
DEC R22
BRNE L3
DEC R21
BRNE L2
DEC R20
BRNE L1
RET
635 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Toggle program in C
In Chapter 7 we covered C programming of the AVR using the AVR GCC
compiler. Program 8-2 shows the toggle program written in C. It will toggle all the
bits of Port B with some delay between the “on” and “off” states.
int main(void)
{
DDRB = 0xFF; //Port B is output
while (1)
{ //do forever
PORTB = 0x55;
delay_ms(1000); //delay 1 second
PORTB = 0xAA;
delay_ms(1000); //delay 1 second
}
return 0;
}
void delay_ms(int d)
{
_delay_ms(d); //delay 1000 us
}
Review Questions
1. A given ATmega32-based system has a crystal frequency of 16 MHz. What is
the instruction cycle time for the CPU?
2. How many fuse bytes are available in ATmega32?
3. True or false. Upon power-up, both voltage and frequency are stable instantly.
4. The internal RC oscilator works for the frequency range of _____ to ______
MHz.
5. Which fuse bit is used to disable the BOD?
6. True or false. Upon power-up, the CPU starts working immediately.
7. What is the rule of thumb for ATmega32 fuse bits?
8. The brown-out detection voltage can be set at _______ or ______ by________
fuse bit.
9. True or false. The higher the clock frequency for the system, the lower the
power dissipation.
Intel Hex is a widely used file format designed to standardize the loading
(transferring) of executable machine code into a chip. Therefore, the loaders that
come with every ROM burner (programmer) support the Intel Hex file format. In
many Windows-based assemblers such as AVR Studio, the Intel Hex file is pro-
duced according to the settings you set. In the AVR Studio environment, the object
file is fed into the linker program to produce the Intel hex file. The hex file is used
by a programmer such as the AVRISP to transfer (load) the file into the Flash
memory. The AVR Studio assembler can produce three types of hex files. They are
(a) Intel Intellec 8/MDS (Intel Hex), (b) Motorola S-record, and (c) Generic. See
Table 8-12. In this section we will explain Intel Hex with some examples. We rec-
ommend that you do not use AVR GCC if you want to test the programs in this
section on your computer. It is better to use a simple .asm file like toggle.asm to
understand this concept better.
:BBAAAATTHHHHH.......HHHHCC
637 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
4. TT is for type. This field is 00, 01, or 02. If it is 00, it means that there are more
lines to come after this line. If it is 01, it means that this is the last line and the
loading should stop after this line. If it is 02, it indicates the current segment
address. To calculate the absolute address of each record (line), we have to
shift the current segment address 4 bits to left and then add it to the record
address. Examples 8-2 and 8-3 show how to calculate the absolute address of
a record in extended Intel hex file.
5. HH......H is the real information (data or code). The loader places this informa-
tion into successive memory locations of Flash. The information in this field is
presented as low byte followed by the high byte.
6. CC is a single byte. This last byte is the checksum byte for everything in that
line. The checksum byte is used for error checking. Checksum bytes are dis-
cussed in detail in Chapters 6 and 7. Notice that the checksum byte at the end
of each line represents the checksum byte for everything in that line, and not
just for the data portion.
Example 8-2
What is the absolute address of the first byte of a record that has 0025 in the address
field if the last type 02 record before it has the segment address 0030?
Solution:
To calculate the absolute address of each record (line), we have to shift the segment
address (0030) four bits to the left and then add it to the record address (0025):
0030 (2 bytes segment address) shifted 4 bits to the left --> 00300
0025 (record address) + 25
---------
=> (absolute address) 00325
Example 8-3
What is the absolute address of the first byte of the second record below?
:020000020000FC
:1000000008E00EBF0FE50DBF0FEF07BB05E500953C
Solution:
To calculate the absolute address of the first byte of the second record, we have to shift
left the segment address (0000, as you see in the first record) four bits and then add it
to the second record address (0000, as you see in the second record).
639 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
As we mentioned in Chapter 2, each Flash location in the AVR is 2 bytes
long. So, for example, the first byte of Flash location #2 is Byte #4 of the code.
See Figure 8-9.
Flash Memory
Location #0 Byte #0 Byte #1
Location #1 Byte #2 Byte #3
Location #2 Byte #4 Byte #5
Location #3 Byte #6 Byte #7
Figure 8-10. Intel Hex File Test Program with the Intel Hex Option
Solution:
After the colon (:), we have 10, which means that 16 bytes of data are in this line. 0010H
is the record address, and means that 08, which is the first byte of the record, is placed
in address location 10H (16 decimal). Next, 00 means that this is not the last line of the
record. Then the data, which is 16 bytes, is as follows:
08BB0E940C00FBCF40E158EC6AEF0000. Finally, the last byte, E7, is the checksum byte.
Example 8-5
Compare the data portion of the Intel Hex file of Figure 8-10 with the opcodes in the
list file of the test program given in Figure 8-8. Do they match?
Solution:
In the second line of Figure 8-10, the data portion starts with 08E0H, where the low byte
is followed by the high byte. That means it is E008, the opcode for the instruction
“LDI R16,HIGH(RAMEND)”, as shown in the list file of Figure 8-8. The last byte of the
data in line 5 is 0895, which is the opcode for the “RET” instruction in the list file.
Example 8-6
(a) Verify the checksum byte for line 3 of Figure 8-10. (b) Verify also that the informa-
tion is not corrupted.
Solution:
(a) 10 + 00 + 00 + 00 + 08 + E0 + 0E + BF + 0F + E5 + 0D + BF + 0F +
EF + 07 + BB + 05 + E5 + 00 + 95 = 6C4 in hex. Dropping the carries (6)
gives C4H, and its 2's complement is 3CH, which is the last byte of line 3.
(b) If we add all the information in line 2, including the checksum byte, and drop the
carries we should get 10 + 00 + 00 + 00 + 08 + E0 + 0E + BF + 0F + E5
+ 0D + BF + 0F + EF + 07 + BB + 05 + E5 + 00 + 95 + 3C = 700.
Dropping the carries (7) gives 00H, which means OK.
Review Questions
1. True or false. The Intel Hex file format does not use the checksum byte method
to ensure data integrity.
2. The first byte of a line in an Intel Hex file represents ____.
3. The last byte of a line in an Intel Hex file represents ____.
4. In the TT field of an Intel Hex file, we have 00. What does it indicate?
5. Find the checksum byte for the following values: 22H, 76H, 5FH, 8CH, 99H.
6. In Question 5, add all the values and the checksum byte. What do you get?
641 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
SECTION 8.4: AVR PROGRAMMING AND TRAINER BOARD
In this section, we show various ways of loading a hex file into the AVR
microcontroller. We also discuss the connection for a simple AVR trainer.
Atmel has skillfully designed AVR microcontrollers for maximum flexibil-
ity of loading programs. The three primary ways to load a program are:
1. Parallel programming. In this way a device burner loads the program into the
microcontroller separate from the system. This is useful on a manufacturing
floor where a gang programmer is used to program many chips at one time.
Most mainstream device burners support the AVR families: EETools is a pop-
ular one. The device programming method is straightforward: The chip is pro-
grammed before it is inserted into the circuit. Or, the chip can be removed and
reprogrammed if it is in a socket. A ZIF (zero insertion force) socket is even
quicker and less damaging than a standard socket. When removing and rein-
serting, we must observe ESD (electrostatic discharge) procedures. Although
AVR devices are rugged, there is always a risk when handling them. Using this
method allows all of the device’s resources to be utilized in the design. No pins
are shared, nor are internal resources of the chip used as is the case in the other
two methods. This allows the embedded designer to use the minimum board
space for the design.
2. An in-circuit serial programmer (ISP) allows the developer to program and
debug their microcontroller while it is in the system. This is done by a few
wires with a system setup to accept this configuration. In-circuit serial pro-
gramming is excellent for designs that change or require periodic updating.
AVR has two methods of ISP. They are SPI and JTAG. Most of the ATmega
family supports both methods. The SPI uses 3 pins, one for send, one for
receive, and one for clock. These pins can be used as I/O after the device is
programmed. The designer must make sure that these pins do not conflict with
the programmer. Notice that SPI stands for “serial peripheral interface” and is
a protocol. But ISP stands for “in-circuit serial programming” and is a method
of code loading. AVRISP and many other devices support ISP. To connect
AVRISP to your device you also need to connect VCC, GND, and RESET
pins. You must bring the pins to a header on the board so that the programmer
can connect to it. Figure 8-11 shows the pin connections.
10
Figure 8-11. ISP 10-pin Connections (See www.Atmel.com for 6-pin version)
643 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
SUMMARY
PROBLEMS
23. Which fuse bit is used to set the brown-out detection voltage for the
ATmega32?
24. Which fuse bit is used to enable and disable the brown-out detection voltage
for the ATmega32?
25. If the brown-out detection voltage is set to 4.0 V, what does it mean to the sys-
tem?
26. True or false. The Hex option can be set in AVR Studio.
27. True or false. The extended Intel Hex file can be used for ROM sizes of less
than 64 kilobytes.
28. True or false. The extended Intel Hex file can be used for ROM sizes of more
than 64 kilobytes.
29. Analyze the six parts of line 3 of Figure 8-10.
30. Verify the checksum byte for line 3 of Figure 8-10. Verify also that the infor-
mation is not corrupted.
31. What is the difference between Intel Hex files and extended Intel Hex files?
32. True or false. To use a parallel programmer, we must remove the AVR chip
from the system and place it into the programmer.
33. True or false. ISP can work only with Flash chips.
1. False
2. The number of bytes of data in the line
3. The checksum byte of all the bytes in that line
4. 00 means this is not the last line and that more lines of data follow.
5. 22H + 76H + 5FH + 8CH + 99H = 21CH. Dropping the carries we have 1CH and its 2’s com-
plement, which is E4H.
6. 22H + 76H + 5FH + 8CH + 99H + E4H = 300H. Dropping the carries, we have 00, which
means that the data is not corrupted.
1 Device burner
2. JTAG and boot loader
3. ISP
4. True
5. Pin 9
6. HIGH
645 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
SECTION 18.5: TWI PROGRAMMING WITH CHECKING
STATUS REGISTER
647
Send START
Is Status No
$8?
Yes
Send SLA+W
Is Status No
$18?
Yes
Yes
Send Data
Yes
Want to Is Status
send more data? $28?
No
No
Send STOP
Do error handling
Figure 18-18. Programming Steps of Master Transmitter Mode with Checking of Flags
Data transmitted.
$30 TWCR =(1<<TWEN)|(TWINT)|(TWSTO) STOP condition will be transmitted
NACK received
649
Program 18-14 shows how a master writes 11110000 on a slave with
address 1101000. The program checks the value of the status register in each step
of the operation.
.INCLUDE "M32DEF.INC"
;*********************************************************
I2C_START:
LDI R21, (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)
OUT TWCR,R21 ;transmit a START condition
WAIT1:
IN R21, TWCR ;read control register into R21
SBRS R21, TWINT ;skip next line if TWINT is 1
Program 18-14: Writing a Byte in Master Mode with Status Checking (cont. from prev. page)
Program 18-15 is the C version of Program 18-10 and shows how a mas-
ter writes 11110000 to a slave with address 1101000. The program checks the
value of the status register in each step of the operation.
#include <avr/io.h>
651
//**********************************************************
unsigned char i2c_readStatus(void)
{
unsigned char i = 0;
i = TWSR & 0xF8;
return i;
}
//**********************************************************
void i2c_stop()
{
TWCR = (1<< TWINT)|(1<<TWEN)|(1<<TWSTO);
}
//**********************************************************
void i2c_init(void)
{
TWSR=0x00; //set prescaler bits to zero
TWBR=0x48; //SCL frequency is 50K for XTAL = 8M
TWCR=0x04; //enable the TWI module
}
//**********************************************************
653
Send START
Is Status No
$8?
Yes
Send SLA+R
Is Status No
$40?
Yes
Want to
No read only Yes
one other
byte?
No Yes
No
Send STOP
Do error handling
Figure 18-20. TWI Programming Steps of Master Receiver Mode with Checking of Flags
Figure 18-21. TWSR Register Values for Master Receiver Operating Mode
Program 18-15 shows how a master reads a byte from a slave with address
1101000 and displays the result on Port A. The program checks the value of the
655
status register in each step of the operation.
.INCLUDE "M32DEF.INC"
LDI R21,HIGH(RAMEND);set up stack
OUT SPH,R21
LDI R21,LOW(RAMEND)
OUT SPL,R21
LDI R21,0xFF
OUT DDRA,R21 ;Port A is output
CALL I2C_INIT ;initialize TWI module
CALL I2C_START ;transmit START condition
CALL I2C_READ_STATUS ;read status register
CPI R26, 0x08 ;was start transmitted correctly?
BRNE ERROR ;else jump to error function
LDI R27, 0b11010001 ;SLA (11010000) + R(1)
CALL I2C_WRITE ;write R27 to I2C bus
CALL I2C_READ_STATUS ;read status register
CPI R26, 0x40 ;was SLA+R transmitted, ACK received?
BRNE ERROR ;else jump to error function
CALL I2C_READ
CALL I2C_READ_STATUS ;read status register
CPI R26, 0x58 ;was data transmitted, ACK received?
BRNE ERROR ;else jump to error function
OUT PORTA,R27
CALL I2C_STOP ;transmit STOP condition
HERE: RJMP HERE ;wait here forever
ERROR:RJMP HERE ;you can type error handler here
;*********************************************************
I2C_INIT:
LDI R21, 0
OUT TWSR,R21 ;set prescaler bits to zero
LDI R21, 0x48 ;move 0x48 into R21
OUT TWBR,R21 ;SCL freq. is 50k for 8 MHz XTAL
LDI R21, (1<<TWEN) ;move 0x04 into R21
OUT TWCR,R21 ;enable the TWI
RET
;*********************************************************
I2C_START:
LDI R21, (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)
OUT TWCR,R21 ;transmit a START condition
WAIT1:
IN R21, TWCR ;read control register into R21
SBRS R21, TWINT ;skip next line if TWINT is 1
RJMP WAIT1 ;jump to WAIT1 if TWINT is 0
RET
;*********************************************************
I2C_WRITE:
OUT TWDR, R27 ;move the byte into TWDR
LDI R21, (1<<TWINT)|(1<<TWEN)
OUT TWCR, R21 ;configure TWCR to send TWDR
Program 18-16: TWI Reading a Byte in Master Mode with Status Checking
Program 18-17: TWI Reading a Byte in Master Mode with Status Checking in C
657
void i2c_write(unsigned char data)
{
TWDR = data;
TWCR = (1<< TWINT)|(1<<TWEN);
while ((TWCR & (1 <<TWINT)) == 0);
} //**********************************************************
unsigned char i2c_read(unsigned char isLast)
{
if (isLast == 0) //if want to read more than 1 byte
TWCR = (1<< TWINT)|(1<<TWEN)|(1<<TWEA);
else //if want to read only one byte
TWCR = (1<< TWINT)|(1<<TWEN);
while ((TWCR & (1 <<TWINT)) == 0);
return TWDR;
} //**********************************************************
void i2c_stop()
{
TWCR = (1<< TWINT)|(1<<TWEN)|(1<<TWSTO);
} //**********************************************************
int main (void)
{
DDRA = 0xFF; //Port A is output
unsigned char s,i;
i2c_init();
i2c_start(); //transmit START condition
s = i2c_readStatus();
if (s != 0x08)
{
i2c_showError(s);
return 0;
}
i2c_write(0b11010001); //transmit SLA + R(1)
s = i2c_readStatus();
if (s != 0x40)
{
i2c_showError(s);
return 0;
}
i=i2c_read(1);
s = i2c_readStatus();
if (s != 0x58)
{
i2c_showError(s);
return 0;
}
PORTA= i; //show the byte on Port A
i2c_stop(); //transmit STOP condition
while(1); //stay here forever
return 0;
}
Program 18-17: TWI Reading a Byte in Master Mode with Status Checking in C (continued)
659
1 Wait to be
addressed
No
Is TWIF one?
Yes
No Is Status
Do error handling
$A8?
Yes
No Want to Yes
send only
one other
byte?
No Yes
No
Figure 18-22. TWI Programming Steps of Slave Transmitter Mode with Checking of Flags
Figure 18-23. TWSR Register Values for Slave Transmitter Operating Mode
661
ommend that you use the first one.
Program 18-18 shows how to initialize the TWI module to operate in
slave transmitter mode. In this program the TWI module listens to the bus and
waits to be addressed by a master device. Then it transmits the letter ‘G’ to the
master device.
.INCLUDE "M32DEF.INC"
HERE:
RJMP HERE ;wait here forever
ERROR: ;you can type error handler here
LDI R21,0xFF
OUT DDRA,R21 ;Port A is output
OUT PORTA,R26
RJMP HERE
;*********************************************************
I2C_INIT:
LDI R21, 0x10 ;load 00010000 into R21
OUT TWAR,R21 ;set address register
LDI R21, (1<<TWEN) ;move 0x04 into R21
OUT TWCR,R21 ;enable the TWI
LDI R21, (1<<TWINT)|(1<<TWEN)|(1<<TWEA)
OUT TWCR,R21 ;enable TWI and ACK(can't be ignored)
RET
;*********************************************************
I2C_LISTEN:
W1:
IN R21, TWCR ;read control register into R21
SBRS R21, TWINT ;skip next intruction if TWINT is 1
RJMP W1 ;jump to W1 if TWINT is 0
RET
;*********************************************************
I2C_READ_STATUS:
IN R26, TWSR ;read status register into R21
ANDI R26, 0xF8 ;mask the prescaler bits
RET
Program 18-18: Writing a Byte in Slave Mode with Status Checking (cont. from prev. page)
663
//*********************************************************
//*********************************************************
void i2c_listen()
{
while ((TWCR & (1 <<TWINT))==0); //wait to be addressed
}
//*********************************************************
Program 18-19: Writing a Byte in Slave Mode with Status Checking in C (continued)
1. Poll the TWINT flag in the TWCR register to see when a byte has been
received completely.
2. When the TWINT flag is set to one, we should check the value of the status reg-
ister to see if the SLA + W was received successfully. $60 or $70 (for general
call) means that the SLA + W was received and ACK returned successfully.
Now if you want to receive only one byte of data you should run the
“Receive Data and Return NACK” function. Otherwise, if you want to send more
than one byte of data you should run the “Receive Data and Return ACK” func-
tion. Next, we will examine each function in detail.
Receive data and Return ACK
In slave receiver mode, if you want to receive more than one byte of data
you should receive a byte of data and return ACK by doing the following steps:
1. Set the TWEN, TWINT, and TWEA bits of the TWCR register to one to
receive a byte and return ACK.
2. Poll the TWINT flag in the TWCR register to see when a byte has been
received completely.
3. When the TWINT flag is set to one, you should check the value of the status
register to see if the data was received successfully and ACK was returned. If
the status value is $80 or $90 (for general call), it means that a byte of data has
been received and ACK was returned. You can either repeat this function to
receive more than one bytes of data or you can run the “Receive Data and
Return NACK” function to receive only one byte of data.
4. Copy the received byte from the TWDR.
665
1 Wait to be
addressed
No
Is TWIF one?
Yes
2
No Is Status
$60 or $70?
Do error handling
Yes
Want to
No read only Yes
one other
byte
Want to Yes
Is Status Is Status
send more 2
$80 or $90? $88 or $98?
data?
No Yes
No
Figure 18-24. TWI Programming Steps of Slave Receiver Mode with Checking of Flags
Figure 18-25. TWSR Register Values for Slave Receiver Operating Mode
Program 18-20 shows how to initialize the TWI module to operate in slave
receiver mode. This program receives a byte of data and displays it on Port A after
being addressed by a master device.
.INCLUDE "M32DEF.INC"
667
CALL I2C_LISTEN ;listen to the bus to be addressed
CALL I2C_READ_STATUS
CPI R26, 0x60 ;addressed as slave receiver?
BRNE ERROR ;else jump to error function
CALL I2C_READ ;read a byte and copy it to R27
CALL I2C_READ_STATUS
CPI R26, 0x80 ;addressed as slave receiver?
BRNE ERROR ;else jump to error function
OUT PORTA,R27 ;copy R27 to PORTA
HERE:
RJMP HERE ;wait here forever
ERROR:
RJMP HERE
;*********************************************************
I2C_INIT:
LDI R21, 0x10 ;load 00010000 into R21
OUT TWAR,R21 ;set address register
LDI R21, (1<<TWEN) ;move 0x04 into R21
OUT TWCR,R21 ;enable the TWI
LDI R21, (1<<TWINT)|(1<<TWEN)|(1<<TWEA)
OUT TWCR,R21 ;enable TWI and ACK(can't be ignored)
RET
;*********************************************************
I2C_LISTEN:
W1:
IN R21, TWCR ;read control register into R21
SBRS R21, TWINT ;skip next intruction if TWINT is 1
RJMP W1 ;jump to W1 if TWINT is 0
RET
;*********************************************************
I2C_READ:
LDI R21, (1<<TWINT)|(1<<TWEN)|(1<<TWEA)
OUT TWCR, R21 ;configure TWCR to receive TWDR
W2: IN R21, TWCR ;read control register into R21
SBRS R21, TWINT ;skip next line if TWINT is 1
RJMP W2 ;jump to W2 if TWINT is 0
IN R27,TWDR ;move received data into R21
RET
;*********************************************************
I2C_READ_STATUS:
IN R26, TWSR ;read status register into R21
ANDI R26, 0xF8 ;mask the prescaler bits
RET
Program 18-20: Reading a Byte in Slave Mode with Status Checking (cont. from prev. page)
//**********************************************************
//**********************************************************
//*********************************************************
void i2c_listen()
{
while ((TWCR & (1 <<TWINT))==0); //wait to be addressed
}
//*********************************************************
Program 18-21: Reading a Byte in Slave Mode with Status Checking in C
669
int main (void)
{
DDRA = 0xFF;
i2c_initSlave(0x10); //init. TWI module as
//slave with address
//0b0001000 and do not
//accept general call
i2c_listen(); //listen to be addressed
Program 18-21: Reading a Byte in Slave Mode with Status Checking in C (continued)
Review Questions
1. True or false. We can ignore checking the status register when there is more
than one master on the bus.
2. True or false. We can enable the TWI module and generate aSTART condition
at the same time.
3. How can a slave device read the value of the R/W bit when it is being
addressed by a master device?
4. True or false. We can check the status register to see if a STOP condition has
been transmitted successfully.
5. What is the value of the status register when SLA + W is received and ACK
has been returned?
6. What is the value of the status register when SLA + W is transmitted and ACK
has been received?
7. What is the value of the status register when SLA + R is received and ACK has
been returned?
8. What is the value of the status register when SLA + W is transmitted and ACK
has been received?
OVERVIEW
671
SECTION A.1: INSTRUCTION SUMMARY
672 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
BRANCH INSTRUCTIONS
674 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
ARITHMETIC AND LOGIC INSTRUCTIONS
676 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Example:
andi r17,$0F ;Clear upper nibble of r17
andi r18,$10 ;Isolate bit 4 in r18
BLD Rd, b ; Bit Load from the T Flag in SREG to a Bit in Register
0 ≤ d ≤ 31, 0 ≤ b ≤7 ; Rd(b) ← T
Copies the T flag in the SREG (Status Register) to bit b in register Rd.
Flags: --- Cycles: 1
Example:
bst r1,2 ;Store bit 2 of r1 in T flag
bld r0,4 ;Load T flag into bit 4 of r0
BREAK ; Break
The BREAK instruction is used by the on-chip debug system, and is normally not
used in the application software. When the BREAK instruction is executed, the AVR CPU
is set in the stopped mode. This gives the on-chip debugger access to internal resources.
Flags: --- Cycles: 1
Example: ---
678 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
BRGE k ; Branch if Greater or Equal (Signed)
–64 ≤ k ≤ +63 ; If Rd ≥ Rr (N⊕V = 0) then PC ← PC + k + 1, else PC ← PC + 1
Conditional relative branch. Tests the Signed flag (S) and branches relatively to PC
if S is cleared. If the instruction is executed immediately after any of the instructions CP,
CPI, SUB, or SUBI, the branch will occur if and only if the signed binary number repre-
sented in Rd was greater than or equal to the signed binary number represented in Rr.
Flags: --- Cycles: 1 or 2
Example:
cp r11,r12 ;Compare registers r11 and r12
brge greateq ;Branch if r11 ≥ r12 (signed)
...
greateq: nop ;Branch destination (do nothing)
680 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
number represented in Rd was not equal to the unsigned or signed binary number repre-
sented in Rr.
Flags: --- Cycles: 1 or 2
Example:
eor r27,r27 ;Clear r27
loop: inc r27 ;Increment r27
...
cpi r27,5 ;Compare r27 to 5
brne loop ;Branch if r27 not equal 5
nop ;Loop exit (do nothing)
682 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
CALL k ; Long Call to a Subroutine
0 ≤ k < 64K (Devices with 16 bits PC) or 0 ≤ k < 4M (Devices with 22 bits PC)
Calls to a subroutine within the entire program memory. The return address (to the
instruction after the CALL) will be stored onto the stack. (See also RCALL.) The stack
pointer uses a post-decrement scheme during CALL.
Flags: --- Cycles: 4
Example:
mov r16,r0 ;Copy r0 to r16
call check ;Call subroutine
nop ;Continue (do nothing)
...
check: cpi r16,$42 ;Check if r16 has a special value
breq error ;Branch if equal
ret ;Return from subroutine
...
error: rjmp error ;Infinite loop
684 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
CLV ; Clear Overflow Flag
;V←0
Clears the Overflow flag (V) in SREG (Status Register).
Flags: V ← 0. Cycles: 1
Example:
add r2,r3 ;Add r3 to r2
clv ;Clear Overflow flag
CP Rd,Rr ; Compare
0 ≤ d ≤ 31, 0 ≤ r ≤ 31 ; Rd – Rr
This instruction performs a compare between two registers, Rd and Rr. None of the
registers are changed. All conditional branches can be used after this instruction.
Flags: H, S,V, N, Z, C. Cycles: 1
Example:
cp r4,r19 ;Compare r4 with r19
brne noteq ;Branch if r4 not equal r19
...
noteq: nop ;Branch destination (do nothing)
DEC Rd ; Decrement
0 ≤ d ≤ 31 ; Rd ← Rd – 1
Subtracts one from the contents of register Rd and places the result in the destina-
tion register Rd.
The C flag in SREG is not affected by the operation, thus allowing the DEC
instruction to be used on a loop counter in multiple-precision computations.
When operating on unsigned values, only BREQ and BRNE branches can be
expected to perform consistently. When operating on two’s complement values, all signed
branches are available.
Flags: S,V, N, Z. Cycles: 1
Example:
ldi r17,$10 ;Load constant in r17
loop: add r1,r2 ;Add r2 to r1
dec r17 ;Decrement r17
brne loop ;Branch if r17 not equal 0
nop ;Continue (do nothing)
686 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
FMUL Rd,Rr ; Fractional Multiply Unsigned
16 ≤ d ≤ 23, 16 ≤ r ≤ 23 ; R1:R0 ← Rd × Rr (unsigned ← unsigned × unsigned)
This instruction performs 8-bit × 8-bit → 16-bit unsigned multiplication and shifts
the result one bit left.
Let (N.Q) denote a fractional number with N binary digits left of the radix point,
and Q binary digits right of the radix point. A multiplication between two numbers in the
formats (N1.Q1) and (N2.Q2) results in the format ((N1 + N2).(Q1 + Q2)). For signal pro-
cessing applications, the (1.7) format is widely used for the inputs, resulting in a (2.14)
format for the product. A left shift is required for the high byte of the product to be in the
same format as the inputs. The FMUL instruction incorporates the shift operation in the
same number of cycles as MUL.
The (1.7) format is most commonly used with signed numbers, while FMUL per-
forms an unsigned multiplication. This instruction is therefore most useful for calculating
one of the partial products when performing a signed multiplication with 16-bit inputs in
the (1.15) format, yielding a result in the (1.31) format. (Note: The result of the FMUL
operation may suffer from a 2’s complement overflow if interpreted as a number in the
(1.15) format.) The MSB of the multiplication before shifting must be taken into account,
and is found in the carry bit. See the following example.
The multiplicand Rd and the multiplier Rr are two registers containing unsigned
fractional numbers where the implicit radix point lies between bit 6 and bit 7. The 16-bit
unsigned fractional product with the implicit radix point between bit 14 and bit 15 is
placed in R1 (high byte) and R0 (low byte).
Flags: Z, C. Cycles: 2
Example:
;****************************************************************
;* DESCRIPTION
;* Signed fractional multiply of two 16-bit numbers with 32-bit result.
;* r19:r18:r17:r16 = ( r23:r22 * r21:r20 ) << 1
;****************************************************************
fmuls 16x16_32:
clr r2
fmuls r23, r21 ;((signed)ah *(signed)bh) << 1
movw r19:r18, r1:r0
fmul r22, r20 ;(al * bl) << 1
adc r18, r2
movwr17:r16, r1:r0
fmulsu r23, r20 ;((signed)ah * bl) << 1
sbc r19, r2
add r17, r0
adc r18, r1
adc r19, r2
fmulsu r21, r22 ;((signed)bh * al) << 1
sbc r19, r2
add r17, r0
adc r18, r1
adc r19, r2
Let (N.Q) denote a fractional number with N binary digits left of the radix point,
and Q binary digits right of the radix point. A multiplication between two numbers in the
formats (N1.Q1) and (N2.Q2) results in the format ((N1 + N2).(Q1 + Q2)). For signal pro-
cessing applications, the (1.7) format is widely used for the inputs, resulting in a (2.14)
format for the product. A left shift is required for the high byte of the product to be in the
same format as the inputs. The FMULS instruction incorporates the shift operation in the
same number of cycles as MULS.
The multiplicand Rd and the multiplier Rr are two registers containing signed
fractional numbers where the implicit radix point lies between bit 6 and bit 7. The 16-bit
signed fractional product with the implicit radix point between bit 14 and bit 15 is placed
in R1 (high byte) and R0 (low byte).
Note that when multiplying 0x80 (–1) with 0x80 (–1), the result of the shift oper-
ation is 0x8000 (–1). The shift operation thus gives a two’s complement overflow. This
must be checked and handled by software.
This instruction is not available in all devices. Refer to the device-specific instruc-
tion set summary.
Flags: Z, C. Cycles: 2
Example:
fmuls r23,r22 ;Multiply signed r23 and r22 in
;(1.7) format, result in (1.15) format
movw r23:r22,r1:r0 ;Copy result back in r23:r22
Let (N.Q) denote a fractional number with N binary digits left of the radix point,
and Q binary digits right of the radix point. A multiplication between two numbers in the
formats (N1.Q1) and (N2.Q2) results in the format ((N1 + N2).(Q1 + Q2)). For signal pro-
cessing applications, the (1.7) format is widely used for the inputs, resulting in a (2.14)
format for the product. A left shift is required for the high byte of the product to be in the
same format as the inputs. The FMULSU instruction incorporates the shift operation in
the same number of cycles as MULSU.
The (1.7) format is most commonly used with signed numbers, while FMULSU
688 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
performs a multiplication with one unsigned and one signed input. This instruction is
therefore most useful for calculating two of the partial products when performing a signed
multiplication with 16-bit inputs in the (1.15) format, yielding a result in the (1.31) for-
mat. (Note: The result of the FMULSU operation may suffer from a 2's complement over-
flow if interpreted as a number in the (1.15) format.) The MSB of the multiplication before
shifting must be taken into account, and is found in the carry bit. See the following exam-
ple.
The multiplicand Rd and the multiplier Rr are two registers containing fractional
numbers where the implicit radix point lies between bit 6 and bit 7. The multiplicand Rd
is a signed fractional number, and the multiplier Rr is an unsigned fractional number. The
16-bit signed fractional product with the implicit radix point between bit 14 and bit 15 is
placed in R1 (high byte) and R0 (low byte).
This instruction is not available in all devices. Refer to the device-specific instruc-
tion set summary.
Flags: Z, C. Cycles: 2
Example:
;***************************************************************
;* DESCRIPTION
;* Signed fractional multiply of two 16-bit numbers with 32-bit result.
;* r19:r18:r17:r16 = ( r23:r22 * r21:r20 ) << 1
;***************************************************************
fmuls16x16_32:
clrr2
fmuls r23, r21 ;((signed)ah * (signed)bh) << 1
movwr19:r18, r1:r0
fmul r22, r20 ;(al * bl) << 1
adc r18, r2
movwr17:r16, r1:r0
fmulsu r 23, r20 ;((signed)ah * bl) << 1
sbc r19, r2
add r17, r0
adc r18, r1
adc r19, r2
fmulsu r21, r22 ;((signed)bh * al) << 1
sbc r19, r2
add r17, r0
adc r18, r1
adc r19, r2
Indirect call of a subroutine pointed to by the Z (16 bits) pointer register in the reg-
ister file. The Z-pointer register is 16 bits wide and allows calls to a subroutine within the
lowest 64K words (128K bytes) section in the program memory space. The stack pointer
uses a post-decrement scheme during ICALL.
This instruction is not available in all devices. Refer to the device-specific instruc-
tion set summary.
Flags: --- Cycles: 3
Example:
mov r30,r0 ;Set offset to call table
icall ;Call routine pointed to by r31:r30
Indirect jump to the address pointed to by the Z (16 bits) pointer register in the
register file. The Z-pointer register is 16 bits wide and allows jumps within the lowest
64K words (128K bytes) of the program memory.
This instruction is not available in all devices. Refer to the device-specific instruc-
tion set summary.
Flags:--- Cycles: 2
Example:
mov r30,r0 ;Set offset to jump table
ijmp ;Jump to routine pointed to by r31:r30
INC Rd ; Increment
0 ≤ d ≤ 31 ; Rd ← Rd + 1
Adds one to the contents of register Rd and places the result in the destination reg-
ister Rd.
The C flag in SREG is not affected by the operation, thus allowing the INC
instruction to be used on a loop counter in multiple-precision computations.
When operating on unsigned numbers, only BREQ and BRNE branches can be
expected to perform consistently. When operating on two’s complement values, all signed
branches are available.
Flags: S, V, N, Z. Cycles: 1
Example:
clr r22 ;Clear r22
loop: inc r22 ;Increment r22
...
cpi r22,$4F ;Compare r22 to $4f
brne loop ;Branch if not equal
nop ;Continue (do nothing)
JMP k ; Jump
0 ≤ k < 4M ; PC ← k
Jump to an address within the entire 4M (words) program memory. See also
RJMP.
Flags:--- Cycles: 3
690 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Example:
mov r1,r0 ;Copy r0 to r1
jmp farplc ;Unconditional jump
...
farplc: nop ;Jump destination (do nothing)
Flags:--- Cycles: 2
Example:
clr r27 ;Clear X high byte
ldi r26,$60 ;Set X low byte to $60
ld r0,X+ ;Load r0 with data space loc. $60
;X post inc)
ld r1,X ;Load r1 with data space loc. $61
ldi r26,$63 ;Set X low byte to $63
ld r2,X ;Load r2 with data space loc. $63
ld r3,–X ;Load r3 with data space loc.
;$62(X pre dec)
Flags:--- Cycles: 2
Example:
clr r29 ;Clear Y high byte
ldi r28,$60 ;Set Y low byte to $60
ld r0,Y+ ;Load r0 with data space loc. $60(Y post inc)
ld r1,Y ;Load r1 with data space loc. $61
ldi r28,$63 ;Set Y low byte to $63
ld r2,Y ;Load r2 with data space loc. $63
ld r3,-Y ;Load r3 with data space loc. $62(Y pre dec)
ldd r4,Y+2 ;Load r4 with data space loc. $64
692 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
data space or more than 64K bytes program memory, and the increment/decrement/dis-
placement is added to the entire 24-bit address on such devices.
Flags:--- Cycles: 2
Example:
clr r31 ;Clear Z high byte
ldi r30,$60 ;Set Z low byte to $60
ld r0,Z+ ;Load r0 with data space loc.$60(Z postinc.)
ld r1,Z ;Load r1 with data space loc. $61
ldi r30,$63 ;Set Z low byte to $63
ld r2,Z ;Load r2 with data space loc. $63
ld r3,-Z ;Load r3 with data space loc. $62(Z predec.)
ldd r4,Z+2 ;Load r4 with data space loc. $64
Loads one byte pointed to by the Z-register into the destination register Rd. This
instruction features a 100% space effective constant initialization or constant data fetch.
The program memory is organized in 16-bit words while the Z-pointer is a byte address.
Thus, the least significant bit of the Z-pointer selects either the low byte (ZLSB = 0) or
the high byte (ZLSB = 1). This instruction can address the first 64K bytes (32K words) of
Flags:--- Cycles: 3
Example:
ldi ZH, high(Table_1<<1);Initialize Z-pointer
ldi ZL, low(Table_1<<1)
lpm r16, Z ;Load constant from program
;Memory pointed to by Z (r31:r30)
...
Table_1:
.dw 0x5876 ;0x76 is addresses when ZLSB = 0
;0x58 is addresses when ZLSB = 1
...
NOP ; No Operation
OR Rd,Rr ; Logical OR
0 ≤ d ≤ 31, 0 ≤ r ≤ 31 ; Rd ← Rd OR Rr
Performs the logical OR between the contents of register Rd and register Rr and
places the result in the destination register Rd.
Flags: S, V ← 0, N, Z. Cycles: 1
Example:
or r15,r16 ;Do bitwise or between registers
bst r15,6 ;Store bit 6 of r15 in T flag
brts ok ;Branch if T flag set
...
ok: nop ;Branch destination (do nothing)
696 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
ORI Rd,K ; Logical OR with Immediate
16 ≤ d ≤ 31, 0 ≤ K ≤ 255 ; Rd ← Rd OR K
Performs the logical OR between the contents of register Rd and a constant and
places the result in the destination register Rd.
Flags: S, V ← 0, N, Z. Cycles: 1
Example:
ori r16,$F0 ;Set high nibble of r16
ori r17,1 ;Set bit 0 of r17
Returns from subroutine. The return address is loaded from the stack. The stack
pointer uses a pre-increment scheme during RET.
Flags: ---. Cycles: 4
Example:
call routine ;Call subroutine
...
routine: push r14 ;Save r14 on the stack
...
pop r14 ;Restore r14
ret ;Return from subroutine
Returns from interrupt. The return address is loaded from the stack and the Global
Interrupt flag is set.
Note that the Status Register is not automatically stored when entering an inter-
rupt routine, and it is not restored when returning from an interrupt routine. This must be
handled by the application program. The stack pointer uses a pre-increment scheme dur-
ing RETI.
Flags: ---. Cycles: 4
Example:
...
extint: push r0 ;Save r0 on the stack
...
pop r0 ;Restore r0
reti ;Return and enable interrupts
698 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
RJMP k ; Relative Jump
–2K ≤ k < 2K ; PC ← PC + k + 1
Relative jump to an address within PC – 2K +1 and PC + 2K (words). In the
assembler, labels are used instead of relative operands. For AVR microcontrollers with
program memory not exceeding 4K words (8K bytes) this instruction can address the
entire memory from every address location.
Flags: ---. Cycles: 2
Example:
cpi r16,$42 ;Compare r16 to $42
brne error ;Branch if r16 not equal $42
rjmp ok ;Unconditional branch
error: add r16,r17 ;Add r17 to r16
inc r16 ;Increment r16
ok: nop ;Destination for rjmp (do nothing)
700 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
SBIW Rd + 1:Rd,K ; Subtract Immediate from Word
d ∈ {24,26,28,30}, 0 ≤ K ≤ 63 ; Rd + 1:Rd ← Rd + 1:Rd – K
Subtracts an immediate value (0–63) from a register pair and places the result in
the register pair. This instruction operates on the upper four register pairs, and is well suit-
ed for operations on the pointer registers.
Flags: S, V, N, Z, C. Cycles: 2
Example:
sbiw r25:r24,1 ;Subtract 1 from r25:r24
sbiw YH:YL,63 ;Subtract 63 from the Y-pointer
702 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
SEV ; Set Overflow Flag
;V←1
Sets the Overflow flag (V) in SREG (Status Register).
Flags: V ← 1. Cycles: 1
Example:
sev ;Set Overflow flag
SLEEP
This instruction sets the circuit in sleep mode defined by the MCU control regis-
ter.
Flags: ---. Cycles: 1
Example:
mov r0,r11 ;Copy r11 to r0
ldi r16,(1<<SE) ;Enable sleep mode
out MCUCR, r16
sleep ;Put MCU in sleep mode
SPM can be used to erase a page in the program memory, to write a page in the
program memory (that is already erased), and to set Boot Loader Lock bits. In some
devices, the program memory can be written one word at a time, in other devices an entire
page can be programmed simultaneously after first filling a temporary page buffer. In all
cases, the program memory must be erased one page at a time. When erasing the program
memory, the RAMPZ and Z-register are used as page address. When writing the program
memory, the RAMPZ and Z-register are used as page or word address, and the R1:R0 reg-
ister pair is used as data(1). When setting the Boot Loader Lock bits, the R1:R0 register
pair is used as data.
Refer to the device documentation for detailed description of SPM usage. This
instruction can address the entire program memory.
Flags: ---. Cycles: depends on the operation
Syntax: Operation: Comment:
(i) SPM (RAMPZ:Z) ← $ffff Erase program memory page
(ii) SPM (RAMPZ:Z) ← R1:R0 Write program memory word
(iii) SPM (RAMPZ:Z) ← R1:R0 Write temporary page buffer
(iv) SPM (RAMPZ:Z) ← TEMP Write temporary page buffer
to program memory
(v) SPM BLBITS ← R1:R0 Set Boot Loader Lock bits
Example:
clr r27 ;Clear X high byte
ldi r26,$60 ;Set X low byte to $60
st X+,r0 ;Store r0 in data space loc. $60(X post inc)
st X,r1 ;Store r1 in data space loc. $61
ldi r26,$63 ;Set X low byte to $63
st X,r2 ;Store r2 in data space loc. $63
st -X,r3 ;Store r3 in data space loc. $62(X pre dec)
704 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
arrays, tables, and stack pointer usage of the Y-pointer register. Note that only the low byte
of the Y-pointer is updated in devices with no more than 256 bytes data space. For such
devices, the high byte of the pointer is not used by this instruction and can be used for
other purposes. The RAMPY register in the I/O area is updated in parts with more than
64K bytes data space or more than 64K bytes program memory, and the increment/ decre-
ment/displacement is added to the entire 24-bit address on such devices.
Flags: ---. Cycles:2
Stores one byte indirect with or without displacement from a register to data space.
For parts with SRAM, the data space consists of the register file, I/O memory, and inter-
nal SRAM (and external SRAM if applicable). For parts without SRAM, the data space
consists of the register file only. The EEPROM has a separate address space.
The data location is pointed to by the Z (16 bits) pointer register in the register file.
Memory access is limited to the current data segment of 64K bytes. To access another data
segment in devices with more than 64K bytes data space, the RAMPZ register in the I/O
area has to be changed.
The Z-pointer register can either be left unchanged by the operation, or it can be
post-incremented or pre-decremented. These features are especially suited for stack point-
er usage of the Z-pointer register; however, because the Z-pointer register can be used for
indirect subroutine calls, indirect jumps and table lookup, it is often more convenient to
use the X or Y-pointer as a dedicated stack pointer. Note that only the low byte of the Z-
pointer is updated in devices with no more than 256 bytes data space. For such devices,
the high byte of the pointer is not used by this instruction and can be used for other pur-
poses. The RAMPZ register in the I/O area is updated in parts with more than 64K bytes
data space or more than 64K bytes program memory, and the increment/decrement/dis-
placement is added to the entire 24-bit address on such devices.
Flags: ---. Cycles: 2
706 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Example:
subi r22,$11 ;Subtract $11 from r22
brne noteq ;Branch if r22 not equal $11
...
noteq: nop ;Branch destination (do nothing)
This instruction resets the watchdog timer. This instruction must be executed with-
in a limited time given by the WD prescaler.
Flags:---. Cycles: 1
Example:
wdr ;Reset watchdog timer
708 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
APPENDIX B
BASICS OF
WIRE WRAPPING
OVERVIEW
The AVR Microcontroller & Embedded Systems (Mazidi & Naimi) 709
BASICS OF WIRE WRAPPING
Note: For this tutorial appendix, you will need the following:
Wire-wrapping tool (Radio Shack part number 276-1570)
30-gauge (30-AWG) wire for wire wrapping
(Thanks to Shannon Looper and Greg Boyle for their assistance on this section.)
710 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
nents, such as capacitors, that have round legs, you must also solder these con-
nections. The best way to connect single components is to install individual
wire-wrap pins into the board and then solder the components to the pins. An
alternate method is to use an empty IC socket to hold small components such
as resistors and wrap them to the socket.
10. The wire should be stripped about 1 inch. This will allow 7 to 10 turns for each
connection. The first turn or turn-and-a-half should be insulated. This prevents
stripped wire from coming in contact with other pins. This can be accom-
plished by inserting the wire as far as it will go into the tool before making the
connection.
11. Try to keep wire lengths to a minimum. This prevents the circuit from looking
like a bird nest. Be neat and use color coding as much as possible. Use only
red wires for VCC and black wires for ground connections. Also use different
colors for data, address, and control signal connections. These suggestions will
make troubleshooting much easier.
12. It is standard practice to connect all power lines first and check them for con-
tinuity. This will eliminate trouble later on.
13. It's also a good idea to mark the pin orientation on the bottom of the board.
Plastic templates are available with pin numbers preprinted on them specifi-
cally for this purpose or you can make your own from paper. Forgetting to
reverse pin order when looking at the bottom of the board is a very common
mistake when wire wrapping circuits.
14. To prevent damage to your circuit, place a diode (such as IN5338) in reverse
bias across the power supply. If the power gets hooked up backwards, the
diode will be forward biased and will act as a short, keeping the reversed volt-
age from your circuit.
15. In digital circuits, there can be a problem with current demand on the power
supply. To filter the noise on the power supply, a 100 μF electrolytic capacitor
and a 0.1 μF monolithic capacitor are connected from VCC to ground, in par-
allel with each other, at the entry point of the power supply to the board. These
two together will filter both the high- and the low-frequency noises. Instead of
using two capacitors in parallel, you can use a single 20–100 μF tantalum
capacitor. Remember that the long lead is the positive one.
16. To filter the transient current, use a 0.1 μF monolithic capacitor for each IC.
Place the 0.1 μF monolithic capacitor between VCC and ground of each IC.
Make sure the leads are as short as possible.
IC #1 IC #2 IC #3 IC #4
Figure B-1. Daisy Chain Connection (not recommended for power lines)
IC INTERFACING AND
SYSTEM DESIGN ISSUES
OVERVIEW
713
C.1: OVERVIEW OF IC TECHNOLOGY
Oxide
C
C N D
B D N
B P
G P G
E N E
S N S
714 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
MOS vs. bipolar transistors
There are two types of transistors: bipolar and MOS (metal-oxide semi-
conductor). Both have three leads. In bipolar transistors, the three leads are
referred to as the emitter, base, and collector, while in MOS transistors they are
named source, gate, and drain. In bipolar transistors, the carrier flows from the
emitter to the collector, and the base is used as a flow controller. In MOS transis-
tors, the carrier flows from the source to the drain, and the gate is used as a flow
controller. In NPN-type bipolar transistors, the electron carrier leaving the emitter
must overcome two voltage barriers before it reaches the collector (see Figure C-
1). One is the N-P junction of the emitter-base and the other is the P-N junction of
the base-collector. The voltage barrier of the base-collector is the most difficult
one for the electrons to overcome (because it is reverse-biased) and it causes the
most power dissipation. This led to the design of the unipolar type transistor called
MOS. In N-channel MOS transistors, the electrons leave the source and reach the
drain without going through any voltage barrier. The absence of any voltage bar-
rier in the path of the carrier is one reason why MOS dissipates much less power
than bipolar transistors. The low power dissipation of MOS allows millions of
transistors to fit on a single IC chip. In today's technology, putting 10 million tran-
sistors into an IC is common, and it is all because of MOS technology. Without the
MOS transistor, the advent of desktop personal computers would not have been
possible, at least not so soon. The bipolar transistors in both the mainframes and
minicomputers of the 1960s and 1970s were bulky and required expensive cooling
systems and large rooms. MOS transistors do have one major drawback: They are
slower than bipolar transistors. This is due partly to the gate capacitance of the
MOS transistor. For a MOS to be turned on, the input capacitor of the gate takes
time to charge up to the turn-on (threshold) voltage, leading to a longer propaga-
tion delay.
Overview of logic families
Logic families are judged according to (1) speed, (2) power dissipation, (3)
noise immunity, (4) input/output interface compatibility, and (5) cost. Desirable
qualities are high speed, low power dissipation, and high noise immunity (because
it prevents the occurrence of false logic signals during switching transition). In
interfacing logic families, the more inputs that can be driven by a single output,
the better. This means that high-driving-capability outputs are desired. This, plus
the fact that the input and output voltage levels of MOS and bipolar transistors are
not compatible mean that one must be concerned with the ability of one logic fam-
ily to drive the other one. In terms of the cost of a given logic family, it is high dur-
ing the early years of its introduction but it declines as production and use rise.
The case of inverters
As an example of logic gates, we look at a simple inverter. In a one-tran-
sistor inverter, the transistor plays the role of a switch, and R is the pull-up resis-
tor. See Figure C-2. For this inverter to work most effectively in digital circuits,
however, the R value must be high when the transistor is “on” to limit the current
flow from VCC to ground in order to have low power dissipation (P = VI, where V
Rc Rc Rc
Rc must be a Rc must be a
very high value. very low value.
Vcc
High
Low Q1 Q3
On Off
Input Off Input On
Q2 High Low
Out Out
Q4
Off On
716 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
VDD VDD
“off” “on”
PMOS PMOS
NMOS NMOS
“on” “off”
VSS VSS
IIH 40 μA 20 μA 20 μA 1 μA
IOL 16 mA 8 mA 4 mA 4 mA
IOH −400 μA −400 μA −400 μA 4 mA
Propagation delay 10 ns 9.5 ns 4 ns 9 ns
Static power dissipation (f = 0) 10 mW 2 mW 1 mW 0.0025 nW
Dynamic power dissipation
at f = 100 kHz 10 mW 2 mW 1 mW 0.17 mW
718 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
high-speed bipolar TTL and the low power consumption of CMOS has given birth
to what is called BICMOS. Although BICMOS seems to be the future trend in IC
design, at this time it is expensive due to extra steps required in BICMOS IC fab-
rication, but in some cases there is no other choice. (For example, Intel's Pentium
microprocessor, a BICMOS product, had to use high-speed bipolar transistors to
speed up some of the internal functions.) Table C-3 provides advanced logic char-
acteristics. The “x” is for different speeds designated as A, B, and C. A is the slow-
est one while C is the fastest one. The above data is for the 74244 buffer.
Since the late 1970s, the use of a +5 V power supply has become standard
in all microprocessors and microcontrollers. To reduce power consumption, 3.3 V
VCC is being embraced by many designers. The lowering of VCC to 3.3 V has two
major advantages: (1) It lowers the
power consumption, prolonging Vcc
the life of the battery in systems External
using a battery, and (2) it allows a pull-up
resistor
further reduction of line size Input
(design rule) to submicron dimen- Output
sions. This reduction results in put-
ting more transistors in a given die
size. As fabrication processes
improve, the decline in the line size
is reaching submicron level and
transistor densities are approaching
1 billion transistors.
Figure C-5. Open Collector
External
Open-collector and open-drain pull-up
gates resistor
Of the above two values, the lower number is used to ensure the proper
noise margin. Figure C-7 shows the sinking and sourcing of current when ICs are
connected together.
HIGH LOW
IOL IOH
IOH
“Off” “On”
“On” “Off”
IOL = Σ IIL IOH = Σ IIH
IOL VOL = RON (transistor) × IOL
Notice that in Figure C-7, as the number of input pins connected to a sin-
gle output increases, IOL rises, which causes VOL to rise. If this continues, the rise
of VOL makes the noise margin smaller, and this results in the occurrence of false
logic due to the slightest noise.
720 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Example C-1
Find how many unit loads (UL) can be driven by the output of the LS logic family.
Solution:
The unit load is defined as IIL = 1.6 mA and IIH = 40 μA. Table C-1 shows IOH = 400
μA and IOL = 8 mA for the LS family. Therefore, we have
IOL 8 mA
fan-out (LOW) = = =5
IIL 1.6 mA
IOH 400 μA
fan-out (HIGH) = = = 10
IIH 40 μA
This means that the fan-out is 5. In other words, the LS output must not be connected
to more than 5 inputs with unit load characteristics.
Vcc GND
A1 B1
Vcc 1G A2 B2
1A-1 1Y-1 A3 B3
A4 B4
1A-2 1Y-2
A5 B5
1A-3 1Y-3 A6 B6
1A-4 1Y-4 A7 B7
A8 B8
2A-1 2Y-1
DIR G
2A-2 2Y-2 Direction Enable
control
2A-3 2Y-3
Function Table
2A-4 2Y-4
Direction control
Enable G DIR Operation
L L B Data to A Bus
GND 1G L H A Data to B Bus
H X Isolation
Figure C-8 (a). 74LS244 Octal Buffer Figure C-8 (b). 74LS245 Bidirectional Buffer
(Reprinted by permission of Texas Instruments, Copyright (Reprinted by permission of Texas Instruments, Copyright
Texas Instruments, 1988) Texas Instruments, 1988)
After this background on the fan-out, next we discuss the structure of AVR
ports.
AVR port structure and operation
All the ports of the AVR are bidirectional. They all have three registers that
can be accessed by IN and OUT instructions. We will descuss each register in
detail.
PORTx register
As you can see in Figure C-10, the PORTx register can be accessed using
read and write operations. When we want to write to PORTx, we use the “OUT
PORTx, Rr” instruction. In this case, the WR-PORTx pin is set high and Rr is
loaded into PORTx.
When we want to read from PORTx, we use “IN Rd, PORTx”. In this case,
the PRx pin is set to HIGH, which enables the buffer and makes it possible to read
from PORTx.
The output of PORTx is either connected to the Px pin of the chip or con-
722 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
ON or OFF RDx
depending PUD
on the
value of DATA BUS
PORTxn Q D
DDRxn
Q WR DDRxn
CLK
Pull-up
Resistor RESET
RRx
Pxn Q D
pin of Output Buffer PORTxn
chip WR PORTxn
Q CLK
Sleep RESET
SYNCHRONIZER
Input Buffer
1
D Q D Q
Outside PINxn RPx
L Q Q
AVR RESET RESET
CLKI/O
Inside AVR
Figure C-10. The AVR Ports Structure
trols the pull-up resistor, as we will see next.
DDRx register
As shown in Figure C-10, the DDRx register can be accessed using read
and write operations. When we want to write to DDRx, we use “OUT DDRx, Rr”.
In this case, the WR-DDRx pin is set to HIGH and enables writing to DDRx.
When we want to read from DDRx, we use “IN Rd, DDRx”. In this case, the RDx
pin is set to LOW, which enables the buffer and makes it possible to read from
DDRx.
The DDRx register controls the output buffer and the pull-up resistor.
When the Q of DDRx is HIGH, it enables the output buffer and connects the Q of
the PORTx register to the Px pin of the chip. In this case, the pin is configured as
output. When the Q of DDRx is LOW, it disables the output buffer and configures
the Px pin of the chip as input. In this case, assuming that the PUD bit is LOW, the
Q of PORTx controls the pull-up resistor. When the Q of PORTx is HIGH, it
enables the pull-up resistor, and when it is LOW, it disables the pull-up resistor.
PINx register
As you see in Figure C-10, when the AVR is not in sleep mode, the PINxn
flip-flop is loaded with the value of the AVR pin on each machine cycle. Therefore,
to read the current state of the Px pin of the chip, we should read the content of the
PINx register. To do so, we use “IN Rd,PINx”, which sets RPx high and enables the
input buffer. In this case, the value of PINx passes through the internal data bus of
AVR and will be loaded into the Rd register.
ON or OFF RDx
PUD
depending
on the value
0 DATA BUS
of PORTxn Q D
DDRxn
Q WR DDRxn
CLK
Pull-up
Resistor RESET
0 RRx
pin of chip
Inside AVR
Pxn Q D
PORTxn
WR PORTxn
Q CLK
Sleep RESET
SYNCHRONIZER
D Q D Q
PINxn RPx
L Q Q
RESET RESET
CLK I/O
represents how the content of PORTx register affects the pull -up resistor .
shows how a data can be read from a pin
Figure C-11. Inputting (Reading) from a Pin via a PINx Register in the AVR
724 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
ground signal. Figure C-13 shows what happens if we write “HIGH” to PORTx.n
when DDRx.n = 1. Writing 1 to the PORTx.n makes Q = 1. As a result, a 1 is pro-
vided to the pin of the chip. Therefore, any attempt to read the input pin will
always get the “HIGH” signal.
RDx
PUD
OFF
1 DATA BUS
Q D 0
DDRxn
Q WR DDRxn
CLK
Pull-up
Resistor RESET
RRx
1
pin of chip
Inside AVR
0 0 0 0
Pxn Q D
PORTxn
Sleep WR PORTxn
Q CLK
RESET
SYNCHRONIZER
D Q D Q
PINxn
L Q Q RPx
RESET RESET
CLK I/O
RDx
PUD
OFF
1 DATA BUS
Q D 1
DDRxn
Q WR DDRxn
CLK
Pull-up
Resistor RESET
RRx
1 Inside AVR
pin of chip
1 1 1 1
Pxn Q D
PORTxn
Sleep WR PORTxn
Q CLK
RESET
SYNCHRONIZER
D Q D Q
PINxn
L Q Q RPx
RESET RESET
CLK I/O
VCC
.INCLUDE "M32DEF.INC"
In addition to fan-out, the other issues related to system design are power
dissipation, ground bounce, VCC bounce, crosstalk, and transmission lines. In this
section we provide an overview of these topics.
Power dissipation considerations
Power dissipation is a major concern of system designers, especially for
726 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
laptop and hand-held systems in which batteries provide the power. Power dissi-
pation is a function of frequency and voltage as shown below:
Q = CV
Q CV
= T
T
1 Q
since F= and I =
T T
I = CVF
now P = VI = CV2F
In the above equations, the effects of frequency and VCC voltage should be
noted. While the power dissipation goes up linearly with frequency, the impact of
the power supply voltage is much more pronounced (squared). See Example C-2.
Example C-2
Compare the power consumption of two microcontroller-based systems. One uses 5 V
and the other uses 3 V for VCC.
Solution:
Because P = VI, by substituting I = V/R we have P = V2/R. Assuming that R = 1, we
have P = 52 = 25 W and P = 32 = 9 W. This results in using 16 W less power, which
means power saving of 64% (16/25 × 100) for systems using a 3 V power source.
728 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
D0
Vout
D1
D2
Time
D3
ICCL ICCH
Ground
Crosstalk L0
Table C-6: Line Length Beyond Which Traces Behave Like Transmission Lines
Logic Family Line Length (in.)
LS 25
S, AS 11
F, ACT 8
AS, ECL 6
FCT, FCTA 5
(Reprinted by permission of Integrated Device Technology, copyright IDT 1991)
730 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
APPENDIX D
FLOWCHARTS AND
PSEUDOCODE
OVERVIEW
731
Flowcharts
Terminal
If you have taken any previous
programming courses, you are probably
familiar with flowcharting. Flowcharts
use graphic symbols to represent differ-
ent types of program operations. These Process
symbols are connected together into a
flowchart to show the flow of execution
of a program. Figure D-1 shows some of
the more commonly used symbols.
Flowchart templates are available to help
Decision
you draw the symbols quickly and neatly.
Pseudocode
Flowcharting has been standard
practice in industry for decades. Subroutine
However, some find limitations in using
flowcharts, such as the fact that you can't
write much in the little boxes, and it is
hard to get the “big picture” of what the
program does without getting bogged
down in the details. An alternative to Input/
using flowcharts is pseudocode, which Output
involves writing brief descriptions of the
flow of the code. Figures D-2 through
D-6 show flowcharts and pseudocode for Connector
commonly used control structures.
Statement 1
Statement 1
Statement 2
Statement 2
732 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
tion. Sequence is simply executing instructions one after another. Figure D-2
shows how sequence can be represented in pseudocode and flowcharts.
Figures D-3 and D-4 show two control programming structures: IF-THEN-
ELSE and IF-THEN in both pseudocode and flowcharts.
Note in Figures D-2 through D-6 that “statement” can indicate one state-
ment or a group of statements.
Figures D-5 and D-6 show two iteration control structures: REPEAT
UNTIL and WHILE DO. Both structures execute a statement or group of state-
ments repeatedly. The difference between them is that the REPEAT UNTIL struc-
ture always executes the statement(s) at least once, and checks the condition after
each iteration, whereas the WHILE DO may not execute the statement(s) at all
because the condition is checked at the beginning of each iteration.
Condition
?
IF (condition) THEN
Statement 1
ELSE
Statement 2
Statement 1 Statement 2
No
Condition
?
Yes
IF (condition) THEN
Statement
Statement
REPEAT
Statement
UNTIL (condition)
No
Condition
?
Yes
No
WHILE (condition) DO Condition
Statement ?
Yes
Statement
734 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Count = 5 Start
Address = $140
Repeat
Count = 5
Add next byte Address = $140
Increment address
Decrement counter
Until Count = 0
Add one byte
Store Sum
Increment address
pointer
Decrement counter
No
Count
= 0?
Yes
Store sum
Stop
Program D-1
738 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
APPENDIX F: ASCII CODES 739
APPENDIX G
ASSEMBLERS, DEVELOPMENT
RESOURCES, AND SUPPLIERS
This appendix provides
various sources for AVR assem-
The AVR Studio from Atmel
blers, compilers, and trainers. In
http://www.atmel.com
addition, it lists some suppliers
for chips and other hardware
MicroC from mikroElectronika
needs. While these are all estab-
http://www.mikroe.com
lished products from well-known
companies, neither the author nor
CodeVision
the publisher assumes responsi-
http://www.hpinfotech.ro
bility for any problem that may
arise with any of them. You are
ImageCraft
neither encouraged nor discour-
http://www.imagecraft.com
aged from purchasing any of the
products mentioned; you must
Micro IDE
make your own judgment in eval-
http://www.micro-ide.com
uating the products. This list is
simply provided as a service to Figure G-1. Suppliers of Assemblers and Compilers
the reader. It also must be noted
that the list of products is by no
means complete or exhaustive.
AVR assemblers
The AVR assembler is provided by MicroDigitalEd
Atmel and other companies. Some of the http://www.MicroDigitalEd.com
companies provide shareware versions of
their products, which you can download Digilent
from their websites. However, the size of http://www.digilentinc.com
code for these shareware versions is limited
to a few KB. Figure G-1 lists some suppli- Atmel
ers of assemblers and compilers. http://www.atmel.com
AVR trainers
There are many companies that pro-
duce and market AVR trainers. Figure
G-2 provides a list of some of them. Figure G-2. Trainer Suppliers
740 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
Parts suppliers
Figure G-3 provides a list of suppliers for many electronics parts.
400.0 mA TQFP/MLF
27.2 DC Characteristics
TA = -40qC to 85qC, VCC = 2.7V to 5.5V (Unless Otherwise Noted)
Symbol Parameter Condition Min Typ Max Units
Input Low Voltage except VCC=2.7 - 5.5
VIL -0.5 0.2 VCC(1) V
XTAL1 and RESET pins VCC=4.5 - 5.5
Input High Voltage except VCC=2.7 - 5.5
VIH 0.6 VCC(2) VCC + 0.5 V
XTAL1 and RESET pins VCC=4.5 - 5.5
Input Low Voltage
VIL1 VCC=2.7 - 5.5 -0.5 0.1 VCC(1) V
XTAL1 pin
Input High Voltage VCC=2.7 - 5.5
VIH1 0.7 VCC(2) VCC + 0.5 V
XTAL1 pin VCC=4.5 - 5.5
Input Low Voltage
VIL2 VCC=2.7 - 5.5 -0.5 0.2 VCC V
RESET pin
Input High Voltage
VIH2 VCC=2.7 - 5.5 0.9 VCC(2) VCC + 0.5 V
RESET pin
(3)
Output Low Voltage IOL = 20 mA, VCC = 5V 0.7 V
VOL
(Ports A,B,C,D) IOL = 10 mA, VCC = 3V 0.5 V
Output High Voltage(4) IOH = -20 mA, VCC = 5V 4.2 V
VOH
(Ports A,B,C,D) IOH = -10 mA, VCC = 3V 2.2 V
Input Leakage VCC = 5.5V, pin low
IIL 1 μA
Current I/O Pin (absolute value)
Input Leakage VCC = 5.5V, pin high
IIH 1 μA
Current I/O Pin (absolute value)
RRST Reset Pull-up Resistor 30 60 85 k:
Rpu I/O Pin Pull-up Resistor 20 50 k:
296 ATmega32A
8155A–AVR–06/08
742 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
27.3 Speed Grades
16 MHz
8 MHz
Safe Operating Area
V IH1
V IL1
298 ATmega32A
8155A–AVR–06/08
All AVR data sheets are copyright of Atmel Semiconductor, Inc. 2009, used by permission.
PB2 (AIN0/INT2)
PB3 (AIN1/OC0)
(T1) PB1 PA1 (ADC1)
PB0 (XCK/T0)
PA0 (ADC0)
PA1 (ADC1)
PA2 (ADC2)
PA3 (ADC3)
(INT2/AIN0) PB2 PA2 (ADC2)
PB4 (SS)
PB1 (T1)
(OC0/AIN1) PB3 PA3 (ADC3)
GND
VCC
(SS) PB4 PA4 (ADC4)
(MOSI) PB5 PA5 (ADC5)
(MISO) PB6 PA6 (ADC6)
(SCK) PB7 PA7 (ADC7) (MOSI) PB5 PA4 (ADC4)
(MISO) PB6 PA5 (ADC5)
RESET AREF (SCK) PB7 PA6 (ADC6)
VCC GND RESET PA7 (ADC7)
GND AVCC VCC AREF
GND GND
XTAL2 PC7 (TOSC2) XTAL2 AVCC
XTAL1 PC6 (TOSC1) XTAL1 PC7 (TOSC
(RXD) PD0 (RXD) PD0 PC6 (TOSC
PC5 (TDI)
(TXD) PD1 PC5 (TDI)
(TXD) PD1 PC4 (TDO) (INT0) PD2 PC4 (TDO)
(INT0) PD2 PC3 (TMS)
(INT1) PD3 PC2 (TCK)
(OC1B) PD4 PC1 (SDA)
PD3
PD4
PD5
PD6
PD7
VCC
GND
(SCL) PC0
(SDA) PC1
(TCK) PC2
(TMS) PC3
Note:
(OC1A) PD5 PC0 (SCL) Bottom pad should
(INT1)
(OC1B)
(OC1A)
(ICP1)
(OC2)
(ICP1) PD6 PD7 (OC2) be soldered to ground.
Figure H-1. ATmega16/32 DIP PF5 (ADC5/TMS) Figure H-2. ATmega16/32 TQFP
PF6 (ADC6/TDO)
PF4 (ADC4/TCK)
PF7 (ADC7/TDI)
PF0 (ADC0)
PF1 (ADC1)
PF2 (ADC2)
PF3 (ADC3)
PA0 (AD0)
PA1 (AD1)
PA2 (AD2)
AVCC
AREF
GND
GND
VCC
64
63
62
61
60
59
58
57
56
55
54
53
52
51
50
49
744 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)
PC4 (ADC4/SDA)
PC5 (ADC5/SCL)
PC6 (RESET)
PC3 (ADC3)
PC2 (ADC2)
PD2 (INT0)
PD0 (RXD)
PD1 (TXD)
(RESET) PC6 1 28 PC5 (ADC5/SCL)
(RXD) PD0 2 27 PC4 (ADC4/SDA)
(TXD) PD1 3 26 PC3 (ADC3)
32
31
30
29
28
27
26
25
(INT0) PD2 4 25 PC2 (ADC2)
(INT1) PD3 1 24 PC1 (ADC1)
(INT1) PD3 5 24 PC1 (ADC1)
(XCK/T0) PD4 2 23 PC0 (ADC0)
(XCK/T0) PD4 6 23 PC0 (ADC0) GND 3 22 ADC7
VCC 7 22 GND VCC 4 21 GND
GND 5 20 AREF
GND 8 21 AREF
VCC 6 19 ADC6
(XTAL1/TOSC1) PB6 9 20 AVCC (XTAL1/TOSC1) PB6 7 18 AVCC
(XTAL2/TOSC2) PB7 10 19 PB5 (SCK) (XTAL2/TOSC2) PB7 8 17 PB5 (SCK)
(T1) PD5 11 18 PB4 (MISO)
10
11
12
13
14
15
16
9
(AIN0) PD6 12 17 PB3 (MOSI/OC2)
(T1) PD5
(AIN0) PD6
(AIN1) PD7
(ICP1) PB0
(OC1A) PB1
(SS/OC1B) PB2
(MOSI/OC2) PB3
(MISO) PB4
(AIN1) PD7 13 16 PB2 (SS/OC1B)
(ICP1) PB0 14 15 PB1 (OC1A)
Vcc
C3
16 +
+ 2
C1 1 MAX232 ATmega32
3 6
+ C4 MAX232
4
C2 5 +
T1IN T1OUT (PD0)RXD 14 11
14 2
5
11 14
R1OUT R1IN
12 13 13 3
(PD1)TXD 15 12
T2IN T2OUT
10 7
R2OUT R2IN DB-9
9 8
Figure H-8. (a) Inside MAX232 and (b) Its Connection to the ATmega32 (Null Modem)
X1 Vcc
32.768KHZ
X2 SQW/OUT
LCD
LCD Pin Symbol AVR +5V
1 Ground D0 VCC
PA.0
2 VCC
VEE 10K
3 VEE D7
PA.7 POT
4 RS VSS
5 R/W RS R/W E
6 E PB.0
7 DB0 PB.1
... ... PB.2
14 DB7
LCD LCD
AVR AVR +5V
+5V VCC
D4 VCC D4
PA.4 PA.4
PB.0 PA.0
PB.1 PA.1
PB.2 PA.2
Figure H-11. LCD Connections Using 4-bit Figure H-12. LCD Connections Using a
Data Single Port
746 The AVR Microcontroller & Embedded Systems (Mazidi & Naimi)