You are on page 1of 60

ATmega8

RISC Microcontroller
Interfacing and System Design
Using RMCKIT: ATmega8 RISC Microcontroller Learning Kit

Designed, Developed and Built in Bangladesh by the Author

Golam Mostafa
2
Preface

3
1 External Architecture of ATmega8
1.1 Physical Pin Diagram of ATmega8L

280cde
ATmega8L
1 PC6(RST/) PC5(ADC5-SCL) 28
2 PD0(RXD) PC4(ADC4-SDA) 27
3 PD1(TXD) PC3(ADC3) 26
4 PD2(INT0) PC2(ADC2) 25
5 PD3(INT1) PC1(ADC1) 24
6 PD4(XCK-T0) PC0(ADC0) 23
7 Vcc GND 22
8 GND AREF 21
9 PB6(XT1-TOSC1) AVcc 20
10 PB7(XT2-TOSC2) PB5(SCK) 19
11 PD5(T1) PB4(MISO) 18
12 PD6(AIN0) PB3(MOSI-OC2) 17
13 PD7(AIN1) PB2(SS/-OC1B) 16
14 PB0(ICP1) PB1(OC1A) 15

Figure - 8.1: Physical Pin Diagram for ATmega8 RISC Microcontroller

4
1.2 Pin Functions of the ATmega8 RISC Microcontroller
In the following table, we have briefly described the pin-functions of the ATmega8 MCU.
Detailed function description and the programming are given under relevant topics.
Pin Signals Signal Names Direction Function
PC6 Port Pin Input and Simple IO line and is determined by configuring Fuse Bit.
Output To exchange data with external devices. The pin can be
operated either as input or output.

RST/ External Reset Pin Input By default it is an input pin to receive external active low
reset signal for the MCU. This pin can be prevented from
working as RST/-pin by programming the Fuse Bit.
PD7 – PD0 Port Pins Input and To exchange data with external devices. Each pin can be
Output independently operated either as input or output.

RxD Receive Asyc Serial Data Input To receive asynchronous serial data from external devices.
TxD Output To transmit asynchronous serial data to external devices.

INT0/, INT1/ Interrupts Input To receive interrupt request signals from the external
hardware devices.

XCK Clock Output Output

T0 Timer-0 Input Timer-0 input pTo receive external pulse events for
counting purposes.
AIN0 Data Write Signal Output
Data Read Signal Output To asserts write and read commands to the external data
AIN1 memory and ports
XTAL2, Crystal In-1 Input To connect a frequency determining crystal for the internal
XTAL1 Crystal In-2 Input oscillator of the MCU.
GND Control Input To sink current of the MCU.
P20 – P27 Data Ports Input and To exchange data with external devices. Each pin can be
Output independently operated either as input or output.

A8 – A15 Address Lines Output To assert upper 8-bit address lines while accessing external
code memory, data memory and ports.
PSEN/ Program Sense Output Equivalent to read signal while reading program codes
form external code memory.
P00 – P07 Port Pins Input and To exchange data with external devices. Each pin can be
Output independently operated either as input or output.

Vcc DC Supply Input Supplies Dc Power to the MCU.

5
2 Internal Architecture of ATmega8
3 Block Diagram for the Internal Resources

6
4 ATmega8 IO Register Summary
(Registers Marked with * sign Bit Addressable using CBI and SBI Instructions)
Name Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0

Full Short
IO (RAM)
Address
Status Register SREG I T H S V N Z C
3Fh, (5Fh)
Stack Pointer SPH - - - - - SP10 SP9 SP8
Register – High 3Eh (5Eh)
Stack Pointer SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0
Register – Low 3Dh (5Dh)
Reserved
General Interrupt GICR INT1 INT0 - - - - IVSEL IVCE
Control Register 3Bh (5Bh)
General Interrupt Flag GIFR INTF1 INTF0 - - - - - -
Register 3Ah (5Ah)
Timer/Counter TIMSK OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 - TOIE0
Interrupt Mask Register 39h (59h)
Timer Interrupt Flag TIFR OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 - TOV0
Register 38h (58h)
Store Program Memory SPMCR SPMIE RWWS - RWWSR BLBSET PGWR OGERS SPOM
Control Register 37h (57h) B E T EN
Two Wire Interface TWCR TWINT TWEA TWSTA TWST0 TWWC TWEN - TWIE
Control Register 36h (56h)
MCU Control Register MCUCR SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00
35h (55h)
MCU Control and MCUCSR - - - - WDRF BORF EXTRF PORF
Status Register 34h (54h)
Timer/Counter-0 TCCR0 - - - - - CS02 CS01 CS00
Control Register 33h (53h)
Timer/Counter-0 TCNT0 Timer / Counter – 0 Register (8-bit)
Data Register 32h (52h)
Oscillator Calibration OSCCAL Oscillator Calibration Register
Register 31h (51h)
Special Function SFIOR - - - - ACME PUD PSR2 PSR10
IO Register 30h (50h)
Timer/Counter-1A TCCR1A
Control Register
Timer/Counter-1B TCCR1B
Control Register
Timer/Counter-1 TCNT1H
Data Register High
Timer/Counter-1 TCNT1L
Data Register Low
Output Compare OCR1AH
Register – 1A High
Output Compare OCR1AL
Register – 1A Low
Output Compare OCR1BH
Register – 1B High
Output Compare OCR1BL
Register – 1B Low
Input Capture ICR1H
Register – 1 High
Input Capture ICR1L
Register – 1 Low
Timer/Counter-2 TCCR2
Control Register

7
TCNT2
OCR2
ASSR
WDTCR
UBRRH
UCSRC
EEARH
EEARL
EEDR
EECR
Reserved
Reserved
Reserved
PORTB
DDRB
PINB
PORTC
DDRC
PINC
PORTD
DDRD
PIND
SPDR
SPSR
SPCR
UDR
UCSRA
UCSRB
UBRRL
ACSR
ADMUX
ADCSRA
ADCH
ADCL
TWDR
TWAR
TWI Status Register* TWSR TWS7 TWS6 TWS5 TWS4 TWS3 TWS2 TWS1T TWS0
TWI Bit Rate Register* TWBR TWBR7 TWBR6 TWBR5 TWBR4 TWBR3 TWBR2 TWBR1 TWBR0

8
5 Register Detailed Functions

Status Register: SREG

There are eight buts in the Status Register. The logic levels of these buts are iodated after the execution of every
arithmetic and logical instructions. The MCU uses these buts to take decision as to which task to do out-of-many
alternatives. The SREG is not automatically saved onto Stack during interrupt and subroutine calls.

I T H S V N Z C
I Interrupt Enable: The I-bit controls all the external/must be set to LH to allow the MCU to jump to an
ISR in response to an external or internal interrupt. The
T
H
S
V
N
Z
C

Timer/Counter Interrupt Mask Register: TIMSK

OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 - TOIE0

OCIE2

T
H
S
V

Timer/Counter-1 Overflow Interrupt Enable: When the TOIE1 – bit is set to LH along with LH at I-bit
TOIE1 of SREG, the TC1 overflow interrupt is enabled. Now, the MCU will respond to interrupt request due
to TC1 overflow condition (TC1 rollovers from all 1s to all 0s), which puts LH at TOV1 - bit of TIFR

Timer/Counter-0 Overflow Interrupt Enable: When the TOIE0 –bit is set to LH along with LH at I-bit
TOIE0 of SREG, the TC0 overflow interrupt is enabled. Now, the MCU will respond to interrupt request due
to TC0 overflow condition (TC0 rollovers from all 1s to all 0s), which puts LH at TOV0-bit of TIFR.

9
Significance of TWINT-bit:

TWI Control Register: TWCR


The TWCR register

TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE


0 0 0 0 0 0 0 0
TWINT TWI Interrupt Flag: Initially it is at LL state and later on it assumes LH state to indicate that a TWI
operation (TWI bus assumed START condition, A Slave address has been transmitted over the TWI bus
and so on..) has taken place. The SCL line is at LL-state indicating ‘no activities’ on the TWI bus.
Writing LH at this bit allows clearing the bit and initiates transmission on the TWI bus. At the end of
current busevent, the TWINT-but again assumes LH-state.
TWEA
TWSTA
TWSTO
TWWC
TWEN TWI Enable Bit: When LH is put into this bit, the IO pins 27 and 28 are configured as SDA (Serial Data)
and SCL (Serial Clock) lines for TWI bus and are connected with the internal TWI Logic [Fig – 22.1]. If
this bit is written to zero, the TWI interface is switched off and all TWI transmissions are terminated.
The SDA and SCL lines are at LH-states.
-
TWIE

MCU Control and Status Register: MCUCSR

- - - - WDRF BORF B1 B0
EXTRF PORF

WDRF Watchdog Reset Flag: Thus bit assumes LH-state when the Watchdog Timer times out and the MCU
reset occurs. The bit is reset by Power-on Reset or by writing LL into thus WDRF bit
H
S
V

Timer/Counter-1 Overflow Interrupt Enable: When the TOIE1 – bit is set to LH along with LH at I-bit
TOIE1 of SREG, the TC1 overflow interrupt is enabled. Now, the MCU will respond to interrupt request due
to TC1 overflow condition (TC1 rollovers from all 1s to all 0s), which puts LH at TOV1 - bit of TIFR

Timer/Counter-0 Overflow Interrupt Enable: When the TOIE0 –bit is set to LH along with LH at I-bit
TOIE0 of SREG, the TC0 overflow interrupt is enabled. Now, the MCU will respond to interrupt request due
to TC0 overflow condition (TC0 rollovers from all 1s to all 0s), which puts LH at TOV0-bit of TIFR.

10
6 General Purpose Register File
RAM Address Symbolic Name Size Remarks
0x1F R31 8-bit 15 8 7 0
R31 R30 Z- Pointer Register
0x1E R30 8-bit
0x1D R29 8-bit 15 8 7 0
R29 R28 Y-Pointer Register
0x1C R28 8-bit
0x1B R27 8-bit 15 8 7 0
R27 R26 X- Pointer Register
0x1A R26 8-bit
0x19 R25 8-bit
0x18 R24 8-bit
0x17 R23 8-bit
0x16 R22 8-bit
0x15 R21 8-bit
0x14 R20 8-bit
0x13 R19 8-bit
0x12 R18 8-bit
0x11 R17 8-bit
0x10 R16 8-bit
0x0F R15 8-bit
0x0E R14 8-bit
0x0D R13 8-bit
0x0C R12 8-bit
0x0B R11 8-bit
0x0A R10 8-bit
0x09 R9 8-bit These registers are not supported by
0x08 R8 8-bit
0x07 R7 8-bit LDI Rd, $XX instruction
0x06 R6 8-bit
For Example:
0x05 R5 8-bit
LDI R15, $23 is not a valid instruction
0x04 R4 8-bit
0x03 R3 8-bit
0x02 R2 8-bit
0x01 R1 8-bit
0x00 R0 8-bit

There are 32 general-purpose 8-bit registers in the register file of the ATmega8. Most of the
instructions of the microcontroller have direct access to all registers. The following registers can
be cascaded to form 16-bit registers and are known as pointer registers. These registers can be
pre- or post- incremented/decremented and point any register of the register file.
15 8 7 0
R27 R26 X- Pointer Register
15 8 7 0
R29 R28 Y-Pointer Register

15 8 7 0
R31 R30 Z- Pointer Register

11
7 Internal Flash Program Memory Organization
The ATmega8 has 4 K-Word (000h – FFFh = $00 - $FFF = 0x000 – 0xFFF) internal Flash Memory
to hold Program Codes. Each memory location can hold 16-bit code. A 12-bit Program Counter
asserts the addresses of the program space during the execution phase of a program. The
memory space is organized as follows:
a. As lower 8-bit and upper 8-bit [Fig – 8.2].
b. As pages and each page contains 32 word locations (64 byte locations).
c. ‘Application Section’ and ‘Boot Section’ [Fig – 8.2 to 8.5].
Application Section: If the fuse bit – BOOTRST is not programmed [Table – 8.3], the MCU
will start program execution from location 000h.
Boot Section: If the fuse bit – BOOTRST is programmed [Table – 8.3] ; the ATmega8
supports the optional ‘Booting Space’ [Fig – 8.3 to 8.5]. The ATmega8 starts program
execution from a different memory location other than 000h and are detailed in Table –
8.1. This feature of the ATmega8 provides extra security to the ATmega8-based system
[Section – 8.11].
d. ‘Boot Section’ and ‘Application Section’ have separate ‘Security Bits = Lock Bits’.

The operational mapping of the internal program memory (PM) of the ATmega8 depends on the
values of its fuse bits, which are: BOOTRST, BOOTSZ1 and BOOTSZ0. The possible mappings
are shown below in Table – 8.1 and Figs – 8.2 to 8.5.
Table – 8.1
Default Fuse Status Application Boot Startup Remarks
BOOTRST BOOTSZ1 BOOTSZ0 Section Section Location
1 (default) 0 (default) 0 (default) 0x000 – 0xBFF 0xC00 – 0xFFF 0x000 MCU starts at App Section
0 0 0 0x000 – 0xBFF 0xC00 – 0xFFF 0xC00 MCU starts at Boot Section
0 0 1 0x000 – 0xDFF 0xE00 – 0xFFF 0xE00 MCU starts at Boot Section
0 1 0 0x000 – 0xEFF 0xF00- 0xFFF 0xF00 MCU starts at Boot Section
0 1 1 0x000 – 0xF7F 0xF80 – 0xFFF 0xF80 MCU starts at Boot Section

Notes: ‘Fuse Status 1’ means that the fuse is not programmed, ‘Fuse Status 0’ means that the fuse is programmed

15 8 7 0
$FFF
Boot
Section
$C00
$BFF

Application
Section

$001
Startup Location $000

1509 a BOOTRST, BOOTSZ1, BOOTSZ0 = 1, 0, 0

Figure – 8.2: Default Code Memory Organization with Unprogrammed Fuse Bit, BOOTRST
12
15 8 7 0 15 8 7 0
$FFF $FFF

Boot Boot
Section Section

Startup Location $C00 Startup Location $E00


$BFF $DFF

Application Application
Section Section

$001 $001
$000 $000

BOOTRST, BOOTSZ1, BOOTSZ0 = 0, 0, 0 1509 a BOOTRST, BOOTSZ1, BOOTSZ0 = 0, 0, 1


1509 a

(a) (b)

15 8 7 0 15 8 7 0
$FFF $FFF
Boot Boot
Section Section
Startup Location $F00 Startup Location $F78
$EFF $F7F

Application Application
Section Section

$001 $001
$000 $000

1509 a BOOTRST, BOOTSZ1, BOOTSZ0 = 0, 1, 0 1509 a BOOTRST, BOOTSZ1, BOOTSZ0 = 0, 1, 1

(c) (d)

Figure – 8.3: Memory Organization of ATmega8 with Programmed Fuse Bit, BOOTRST

13
8 Internal SRAM Data Memory Organization or simply RAM
Register File RAM Address Space
R0 $0000
R1 $0001
R2 $0002
R3 $0003
R4 $0004
R5 $0005
R6 $0006
R7 $0007
…………………….. ………………………….
R29 $001D
R30 $001E
R31 $001F
IO Registers
TWBR ($0000) $0020
TWSR ($0001) $0021
………………………. ……………….
SPL ($003D) $005D
SPH ($003E) $005E
SREG ($003F) $005F
Internal RAM
$0060
$0061
$0062
…………….
$045E
$045F

The ATmega8 has 1120 ($0000 - $045F) byte internal static RAM memory. It is recommended that
a user should take of the RAM as per division shown above during programming.
A: Internal RAM Space
The space $0060 - $045F is allocated for RAM space. Therefore, the Stack Pointer must be
initializes at location $045F. We may note that there is no harm to use any other location as a
RAM space.
B: IO Registers
The IO registers can be addresses for data read/write operations in the following ways:
i. Using its Symbolic Name : in r16, SREG ; SREG → r16
ii. Using IO Address : in r16, $003F ; SREG → r16
iii. Using RAM Address : ldi r16, $005F ; SREG → R16
The above three instructions do the same job – they read content of the SREG-register.
C: Register File
The registers of the Register File can be addressed in the following ways:
i. Using its Symbolic Name : ldi r17, $23 ; 23h → r17
ii. Using RAM Address :

14
9 Internal EEPROM Data Memory Organization or simply EEPROM
7 0
$01FF
$01FE

$0001
$0000
55

The ATmega8 contains 512 bytes EEPROM data memory to hold critical data like ‘the Balance of
a Prepaid Electrical Energy Meter’. The memory can hold data even at the loss of power. The
memory locations occupy the space: $0000 - $01FF. Each of the memory locations can be
individually read and written in the following ways:
a. When the chip is not in a system
i. Using a Universal ROM Programmer – called Parallel Programming
ii. Using a ISP Programmer (like the RMCKIT)
b. When the chip is in a system
The ATmega8 has special instructions to perform data read/write operations with each
of the EEPROM locations. This is known as ‘Instructions Directed Programming (IDP)’.
During IDP programming, the sequences to follow are:
i. The address of the target EEPROM location is asserted using the EEPROM
Address Registers, EEARH and EEARL.
ii. The 8-bit data is submitted to the selected EEPROM location using the
EEPROM Data Register, EEDR.
iii. Software write command is issued to the selected location using the EEPROM
Control Register, EECR. After the issuance of the write command, the
following events take place:
1. The EEPROM location is automatically self-erased.
2. An internal self-timing function is generated, which stretches upto 8.5mS to
complete the data write operation. The ‘write delay’ is about 8448 oscillator
cycles provided that the ATmega8 uses the internal calibrated RC oscillator as
Clock Source. The ‘write command’ is issued by putting LH at the EEWE-bit
of the EECR. At the end of write-up, the EEWE-bit assumes LL-state.
Therefore, the user must wait for 8.5mS (10mS) time or keep polling the
EEWE-bit for LL to decide when to write into the next EEPROM location.

The EEPROM can be erased and written (called endurance) for 100 000 times. If the user program
contains instructions that write the EEPROM (like saving the Balance of the Prepaid Electrical
Energy Meter) during power failure, some precautions must be taken to avoid corruption into the
EEPROM existing data. In heavily filtered power supplies, Vcc is likely to rise or fall on Power
up/down. This causes the ATmega8 to operate at an under voltage for some period of time and
the EEPROM data write instructions cannot be executed correctly or the MCI can itself execute
instructions randomly that might over-write the EEPROM. Keeping the Atega8 at reset condition
during periods of insufficient power supply voltage makes the solution. This can be easily
implemented by enabling the ‘Brown-out Detection Circuit’ of the ATmega8.
15
When the EEPROM is read, the MCU is halted for four clock cycles and then the next instruction
is executed. During write cycle, the MCU is halted for two cycles before the next instruction is
executed.

Example – 9.1 [IDP Programming for data Read/Writ operation; …\ATmega8\ATmega82.asm] Download
and execute the program ..\ATmega8\ATmega82.asm. Observe that the LEDR2 of the TMCKIT blinks for
05+08 = 13 times. Thus program writes 05h and 08h into the EEPROM locations 0000h and 0001h
respectively. After that the MCU reads the contents of these two locations, add these and it is 08H. The
LEDR2 blinks for 8 times.

; write counts into EEPROM, read from it and Blink LEDR2 at PB0 for count times
.include "m8def.inc"
.cseg
.org $000
RESET:
rjmp STKINIT

.org $020
STKINIT:
ldi r16, 0x5F ; stack initialize
out spl, r16
ldi r16, 0x04
out sph, r16
PRTBINIT:
ldi r16, 0xFF ; 1111 1111
out ddrb, r16 ; all portB pins are output

ldi r20, 0x00 ; EEMWE = 0, EEWE=0


out EECR, r20

; writing 05 and 02 at 0000h and 0001h


ldi r20, 0x00 ; EEPROM address 0000h
out EEARH, r20
out EEARL, r20
ldi r20, 0x05
out EEDR, r20 ; data 05h
ldi r20, 0x04
out EECR, r20
nop

ldi r20, 0x06


out EECR, r20

CHKAGN:
sbis EECR, EEWE

rjmp NEXTLOC
rjmp CHKAGN

NEXTLOC:
ldi r20, 0x00
out EEARH, r20
ldi r20, 0x01
out EEARL, r20 ; location 0001

ldi r20, 0x08


out EEDR, r20 ; data 02h

ldi r20, 0x04 ; EEMWE = 1, EEWE=0


out EECR, r20

nop
ldi r20, 0x06
out EECR, r20
16
CHKAGN1:
sbis EECR, EEWE
rjmp NEXT
rjmp CHKAGN1 ; keep polling the EEWE0but for LL

NEXT: ldi r20, 0x00 ; reading the contents if EEPROM locations


out EEARH, r20
out EEARL, r20

ldi r20, 0x01 ; read enable


out EECR, r20

nop
in r20, EEDR ; read from location 0000h

ldi r21, 0x00 ; after read 0 must be put at EEWE-bit before make it
LH
out EECR, r21
ldi r21, 0x00
out EEARH, r21 ; next location
ldi r21, 0x01
out EEARL, r21

nop

ldi r21, 0x01


out EECR, r21

in r21, EEDR ; read from locatio 0001h


add r20, r21 ; r2 = 07

ldi r21, 0x00


out EECR, r21 ; read disable

SLAVEBUSY:
sbi portb, pb0
rcall DELAY
cbi portb, pb0
rcall DELAY
dec r20
brne SLAVEBUSY

GHT: rjmp GHT


DELAY: ldi r17, 8
cagain: ldi r18, 125
magain: ldi r19, 125
fagain: dec r19
brne fagain
dec r18
brne magain
dec r17
brne cagain
ret

.exit

17
Example – 9.2 [Write into EEPROM using RMCKIT and Read by Instruction ….\Atmega8\P92.asm] In
this example, we will write 03h and 07h into EEPROM locations 0020h and 0300h of the ATmega8 using the
ISP Port of the RMCKIT. The program P92.asm will read the contents of these EEPROM locations, add them
and then blink LEDR2 for 8 times.

Procedures:
1. Download P92.hex into the code memory of ATmega8
2. Create the following data files (…\ATmega8\D92.asm) using MIDE-51.
ORG 0020H
DB 03H
ORG 0100H
DB 05H

END

3. Build the file to make the D92.hex file


:0100200003DC
:0101000005F9
:00000001FF

4. Use the GUI Interface and download the D92.hex file into the EEPROM of the ATmega8 of the
RMCKIT.
5. Observe that the LEDr2 blinks for 10 times.

10 ATmega8 Clock Sources and Distribution

1MHz clk clkCPU CPU Core


2MHz RAM
4MHz clkFLASH Flash and
RC
Data EEPROM
Oscillator -1 clkADC
+- 3% 8MHz ADC
CLK
K3A – K3D General IO
Control TC0, TC1,
Unit clkIO
SPI, USART, IO Ports,
External Interrupts
Y 1 = 1 1.0 592MHz

K1A – K1B
9 K4 K5
Crystal/
Y1
Ceramic TC2
Resonator
10 Oscillator -2 for Y1 TWI

Asynchronous
Oscillator -3 clkASY = Y2
For Crystal Y 2 K6
Y2 = 32.768KHz
K2A – K2B
48 : 02 = 20101 : GM

Oscillator-1 is a free running RC square wave generator and doesn’t use any external
components. It can generate frequency of 1MHz, 2 MHz, 4 MHz and 8MHz with ± 3% accuracy.
The desired frequency is selected by programming the appropriate Fuse Bits (Section – 4). The
choice of the oscillator-1 is preferred where the accuracy of the clocking frequency is not very
critical. But, in the case of serial communication with IBMPC, where we need matching baud rate,
the accuracy of the clocking frequency is very important. Under this situation, we must use
Oscilltaor-2, which uses external crystal Y1 of known frequency (say, 11.0592MHz).
18
As we see in the diagram, the functioning of the various parts and devices of the ATmega8 are
synchronous with the system clock, clk. However, the exception is that the devices TC2 and TWI
can also be operated asynchronously using a separate clock source, clkASY. The clkASY is
produced by Oscillator-3, which uses external crystal Y2 (32.768KHz) over the physical Oins-9,
10. However, if the clkASY is used, then the system clk must be derived from the Oscillator-1.

11 Power Management and Sleep Mode

19
12 System Control and Reset
Reset the ATmega8 microcontroller means – apply some kind of signal (called activating signal)
to the ATmega8 microcontroller either from external sources or form internal sources so that the
states of the internal logic of the microcontroller are brought to some known conditions (called
Reset or initial conditions) and once the activating signal disappears (or removed), the MCU
starts program execution from a known memory location called the Boot Location. Assuming
that the Fuse Bits (Section – 3.14) are at default values, the ATmega8 can be brought at Reset state
in one of the following ways:

12.1 External Reset:


By default, the Pin-1 of the ATmega8 works as an external reset pin as per following diagram. If
Pin-1 is used as a digital IO pin (PC6), then the reset signal for the MCU is generated from the
internal Power-on Reset circuit of the ATmega8.
Reset : GM : 3-10

Vcc
VRST = 0.2 – 0.9 V B7 B1 B0
MCUCSR EXTRF
R1
4k7
K1
1 RST/ (PC6) Spike Filter Reset Circuit S Q
A Internal Reset
Qa
C1
Reset Circuit Qb R
100uF
B
R2 FF1
100R Trig
1MHz
0V Delay Counter
CKSEL 3..0 = 001
Qc
SUT1..0 = 10

Vcc

RST/

0.2-0.9

Qa

Qb

Qc Time-out

Internal Reset
t0 t1 t2 t3

At the moment t0 the reset switch K1 is pressed down, the voltage at RST/-pin starts falling. At
time t1, when the voltage falls within 0.2V – 0.9V, the Reset Circuit-A gets triggered and the pulse
Qa is generated. As a result, the EXTRF (External Reset Flag) flag of the MCUCSR register
assumes LH-state. The Q of FF1 also goes to LH-state and the internal reset sequence of the MCU
begins. At time t2, the external reset period (t2 – t1) is over. At this moment of t2, the Reset Circuit-
B gets triggered and the Qb pulse is generated. The Qb pulse triggers the ‘Delay Counter’, which
waits for the time equal to ‘Time-out’ and then puts LH at its Qc output. The Qc resets the FF1
20
and as a result the ‘Internal Reset’ sequence of the Atmega8 is terminated. The microcontroller
enters into active state and begins the program execution at the Boot Location. The ‘Time-out’
period is adjustable by changing the CLKSEL3..0 and SUT1..0 fuses. The ‘Time-out’ period
allows the power (Vcc) to reach a stable level before normal operation starts. The diagram
includes the default values for these fuses and they approximately offer a time-out delay for 6
clock cycles (about 6 µS for 1MHz internal oscillator). The total start-up delay is: External Delay
(t2 – t1) + Time-out delay.

12.2 Power-on Reset:

B7 B1 B0
PORF MCUCSR

+5V 7 Vcc Power -on Qa S Q


Reset Circuit Internal Reset
R
1 RST/ (PC6)
FF1
Trig
1MHz
CKSEL3..0 = 001 Delay Counter
Qc
SUT1..0 = 10

1.4V
Vcc

Qa

Qc Time-out

Internal Reset
t0 t1 t2
Reset 2 : GM : 3-10

The fuses are at default values. So, the Pin-1 is still able to receive external reset signal. But, in the
present case, we have tied the RST/-pin to Vcc (+5V) supply in order to understand the working
principle of the Power-on Reset Circuit of the ATmega8. However, on practical situation, we
might be using Pin-1 as IO pin (PC6) and in that case, the Power-on Reset Circuit will provide
the internal reset signal for the MCU.

The Vcc supply starts rising from 0V at time t0. At Vcc = 1.4V (called VPOT = Power-on Reset
Threshold at rising), the ‘Power-on Reset Circuit (POR)’ triggers and generates the pulse, Qa. As
a result, the PORF (Power-on Reset Flag) of MCUCSR register assumes LH-state indicating that
*an Internal Power-on Reset (start-up) has occurred. The POR circuit can also be used to detect a
failure in ‘Vcc Power Supply’ and in this case the detection threshold is VPOT = 1.3V.

The Qa pulse triggers the ‘Delay Counter’, which waits for ‘Time-out’ period to reset the FF1. As
a result, the MCU gets a time equal to ‘Time-out’ for the reset of the internal logic and start-up.
21
12.3 Brown-out Detection Reset
brown

B7 B1 B0
MCUCSR BO DF

+5V 7 Vcc Reset Circuit S Q


Brown A
O ut Qa Internal Reset
BODEN
Detector Qb R
Reset Circuit
BODLEV Circuit
B
FF1
Trig
1MHz
CKSEL3.. 0 = 001 Delay Counter
Qc
SUT1 ..0 = 10

Vcc
B
A 4V + 65mV
4V – 65mV`

Qa

Qb

Qc Time-out

Internal Reset
t0 t1 t2 t3

Why do we need to detect Vcc Failure?


Assume that we have designed a Prepaid Electrical Energy Meter using ATmega8
microcontroller. The EEPROM memory of the MCU contains critical data like ‘Balance, Meter
Serial Number.’ In practical situation, the meter will experience power failure and resumption
and in that case the +5V Vcc supply for the electronics of the meter will decay and rise again.
Under this circumstance, we want that the critical data within the EEPROM of ATmega8 remains
protected from possible over-write. But, unfortunately, the EEPROM memory of ATmega8
erratically gets corrupted when the Vcc supply falls below 3V. Therefore, in order to prevent the
EEPROM of ATmega8 from being corrupted, we need to monitor the Vcc failure and when it
reaches to (say at 4V), the ATmega8 must be brought into reset condition so that all kinds of
undesired erratic read/write operations are stopped. This monitoring circuit is known as Brown-
out Detection Circuit (BOD). Fortunately, the ATmega8 microcontroller has built-in BOD circuit.
Working Principle of BOD Circuit of ATmega8:
The trigger level of the BOD has a hysteresis of about 130mV to ensure spike-free Brown-out
detection. At Point-A, when the Vcc crosses 3935mV (known as VBOT- = Brown-out Reset
Threshold Voltage = VBOT - VHYS /2), the BOD circuit generates the Qa pulse, which sets the FF1.
The MCU enters into reset state. If it is a genuine power failure then the MCU has no chance to
resume operation. If it is a transient failure, then the Vcc supply may rise again after Brown-out
detection at Point-A. To ensure that the MCU starts functioning after a stable Vcc, the Point-B of
the BOD circuit comes into play with detection level VBOT+ = VBOT + VHYS/2 = 4065mV. At Point-
B, the pulse Qb is generated, which triggers the ‘Delay Circuit’. As a result, a ‘Time-out’ period is
inserted, the reset time is stretched and the Vcc finds a way to arrive at a stable value.
22
12.3 Watchdog Reset
What is Watchdog?
Many house owners keep dogs to watch around for locating unknown persons and then
informing the owners through barking. This is the origin of the word ‘Watchdog’.

In computers, we write and execute our own application programs. Most of the times, the
programs have bugs, which cause them to remain in infinite loop. As a result, the same program
or some part of the program gets executed again and again without causing the computer to
crash. We don’t want desire to encounter such situation and therefore there must exist a way to
bring out the computer from this infinite loop. The ‘Watchdog’ concept can help us!

What is a Watchdog Timer?


A Watchdog Timer is an electronic circuit, which keeps counting some known frequencies and
always compares the ‘Counting Time’ with the ‘Preset Time’. At the moment the Watchdog
times out (the Counting Time = Preset Time), a reset sequence is automatically generated for the
microcontroller.

Now, let us assume that we have an application program, which may or may not have bugs. We
have some idea about the ‘time (say, t1 = 1.0s)’ the program will take for successful execution. Let
us initialize (preset) the Watchdog Timer for 2.0s time and run it and then execute own
application program.

If the application program falls in a loop or it takes execution time greater than 2.0s, the
Watchdog will time out after 2.0s The MCU will execute a reset sequence and will prompt the
user to correct her application program.

Watchdog Timer of ATmega8:


B7 B3 B1 B0
MCUCSR WDRF
WDP2..1
Enable
Reset
WDT
S Q
Watchdog Internal Reset
Oscillator Pre Scaler
1 MHz R

FF1

Trig

Delay Counter Qc

WDT

Qc Time-out

Internal Reset
t0 t1 t2
watchdog

23
13 Interrupt Vectors

14 Digital Input and Output Ports


Introduction: A physical pin (say, Pin-11) is said to be working as a ‘Digital Input/Output Port’
when the MCU exchanges digital signals like LH or LL with external input/output (IO) devices.
The signals are routed to the internal data bus (IDB) of the MCU through the circuitry of Fig-
14.2. The same pin can be configured to count external events for the internal Timer-1 (T1) [Fig-
1.1] and then the signals will be routed to the IDB bus as per diagram of Fig-15.3. An ‘input port’
receives data from external input and ‘output port’ transmits data to an external output device.

The ATmega8 can be programmed to support digital IO services over its various pins as per
following diagram of Fig-14.1. Each digital IO pin can also be configured to serve alternate
functions [Fig – 1.1], which are not shown here for the clarity of the diagram. As digital IO lines,
all the pins have almost identical features. Therefore, features described for a port-pin are
applicable for all the pins of all the ports (Port-B, C, D) of the device.

ATmega8L 50

13 PD7 PC6 1
12 PD6 PC5 28
11 PD5 PC4 27
6 PD4 PC3 26
5 PD3 PC2 25
4 PD2 PC1 24
3 PD1 PC0 23
2 PD0
PB7 10
PB6 9
21 AREF PB5 19
20 AVcc PB4 18
7 Vcc PB3 17
22 GND PB2 16
8 GND PB1 15
PB0 14

Figure – 14.1: Port-mode Operational Diagram of ATmega8

24
Internal Structure of a Port: The internal structure of a digital IO port is depicted in Fig-14.2. In
this diagram, Pxn refers to a Bit-n (n=0,1,….,7) of a Port-x (x = B, C, D). This way, the symbolic
name PD0 refers to Bit-0 of Port-D. The functional description to be made here is applicable for
all the pins of all the ports.

The port pins are individually programmable to work either as input or output. In fact, the bits of
the Atmega8 registers with IO address 00h – 1Fh (RAM address 20h – 3Fh) are all individually
programmable [Section – 3.5].

The direction of a port pin is made output by writing LH into the corresponding Data Direction
Register (DDxn = DDD7). When LH is written into the DDxn via FF1, the Transistor T1 is OFF via
G1 and there is no pullup resistor (Rp). The direction bit of the port can be known via G3 and can
be changed dynamically if necessary. The actual digital data LH or LL is written into FF2, which
travels to physical port-pin (Pxn) via G2. The buffer G2 is capable enough to deliver 20mA and
sink almost the same amount of current. The data written to the FF1 can also be known via G4.
The data write operations with the output ports are synchronized with the MCU clock.
Vcc
FF1
PUD
T1 Q D

CK WD
G1
DDxn

RD
Rp G3

Internal Data Bus (IDB)


FF2

Pxn Q D

G2
CK WP

PORTxn

RP
G4
Sleep

G6 RPinx
Synchronizer

Q
D G5
clkIO

FF3
0V
51

Figure – 14.2: Internal Structure of a Single Port Pin as Digital IO

To operate Pxn as input, we need to write LL into the corresponding DDxn via FF1. As a result,
the G2 is disabled and the data from the Pxn is routed ton the IDB bus via G6, FF3 and G5. The
necessity and the functions of G6 and FF3 with the input port are discussed in Section – 18
(Problems and Solutions). The readers may notice that the data read from an input pin is
synchronized with both the IO_Clock (clkIO) and the MCU_Clock (Read PINB3, RPnx).

25
As we see in Fig-14.2, the pullup resistor (Rp) can be engaged/disengaged with the input pin by
manipulating the direction bit, FF2 output and PUD-bit. The PUD-bit (Power Up Disable)
belongs to the SFIOR register and when set to LH, it disengages the Rp from all the port pins of
Port-B, C, D. By default, the PUD-bit is at LL value and thus the Rp are in place for all the input
pins of all the ports (Port0B, C and D).

Practically, there seems to be no problem to read data from the input pin (input port) even with
the Rp disengaged. However, there are operational occasions that require the need for the
engagement of the Rp [Section – 15].

Regardless of the setting of DDxn, the value of Pxn can always be read by the execution of the in
r16, PINB instruction.

Assembly Instructions to handle IO Ports:


Sn Instructions Operations Remark
Pseudo Code Assembly Code
1 LH → DDB0 sbi DDRB, DDB0 PB0 is made output Other ports are unaffected
FFh → DDRB ldi r16, 0xFF PB7– PB0 are made output Other ports are unaffected
out DDRB, r16
FFh → PORTB ldi r16, 0xFF LH are written to all port Other ports are unaffected
out PORTB, r16 pins pf Port-B register
r16 ← PORTB in r16, PORTB Data comes from FF2 and -
not from Port pins.
r16 ← PINB in r16, PINB Data comes from actual port Say LH is written at PBO and it
pins. drives the base of a npn transistor.
Then the present instruction will
read LL from PB0. We are not
getting the right status of PB0. To
get it we have to execute the
instruction in r16, DDRB.
r16 ← DDRB in r16, DDRB Port direction bits of Port-B -
register are read.
2 LL → DDB0 cbi DDRB, DDB0 PB0 is made input Other ports are unaffected
00h → DDRB ldi r16, 0x00 PB7– PB0 are made input Other ports are unaffected
out DDRB, r16
r16 ← PINB nop Data comes from Port pins nop instruction is inserted to cause
in r16, PINB and not from FF2. delay. This delay will synchronize
the externally applied pin value
incase it changes near the edge of
the internal clock.

26
Example – 14.1 [….\ATmega8\ex81.asm] The following interface circuit is a stand alone copy of the
RMCKIT. Download and execute the program..\ATmega8\ex81.hex, the LED2 should start blinking.

U3: ATmega8L RMCU

+5V PBR
PB7 10
RST PB6 9
PB5 19
R1
4k7 PB4 18
1 17 LEDR2
RST/ PB3
PB2 16
PB1 15
C1 14 0V
100 uF PB0

8, 22 GND
+5V 7 Vcc
20 23
AVcc PC0 24
PC1 25
PC2
26
2-6, 11,21,27,28 PC3 12
NC PD6
13
PD7
1MHz

53 : GM: 03-10

Example – 14.1 […\ATmega8\porta2.asm] Build the following display circuit on the breadboard of the
RMCKIT using jumper
wires. Do not build the Reset Circuit (RCKT) at the moment because it is not needed. The RCKT will be
needed when we intend operate the ATmega8L without the help of the RMCKIT. The MCU uses internal
1MHZ RC oscillator for the driving clock. Download and execute …\ATmega8\Porta2.hex. Observe that
the display shows the message: 1 2 3 4 5 6.

U3: ATmega8L RMCU


DPA DPB DPC DPD DPE DPF
+5V PBR
PB7 10 5 p
RST PB6 9 10 g
PB5 19 9 f
R1 1 e
4k7 PB4 18
1 2 d
RST/ PB3 17
PB2 16 4 c
15 6 b
C1 PB1
PB0 14 7 a
100uF ccA ccB ccC ccD ccE ccF
3 3 3 3 3 3
8, 22
GND
+5V 7 Vcc
20 23
AVcc PC0 24
PC1 25
PC2
26
2-6, 11,21,27,28 PC3 12
NC PD6
13
PD7
1MHz

52 : GM: 03-10

Figure – 14.3: Multiplexed Display Circuit using Digital Ports

27
DP0 DP1 DPE DPF

CC7SDD
Unit
Multiplexed ccF
cc0 cc 1 ccE
CC- code

S0/ S 1/ CCX7SDD SE / SF/


DPE
PB DP0 DP1
DP0-DPF DP0-DPF DPF

DP0-DPF

CC-Code
DP0 DP1 DPE DPF
Table
(CCCT)
Internal RAM 78 H 79H 86H 87H
Internal RAM
CC-Code
LUT
60 CC-0
Digit
HEX2CC Vs
CCcode
6F CC-F

Hex
Input DP0DP1 DP2DP3 DP4DP5 DP6 DP7 DP8 DP9 DPADPB DPCDPD DPEDPF Table
(HEXT)
Internal RAM 70 H 71H 72 H 73H 74H 75H 76 H 77H
52

Figure – 14.4: Data Structure for the Driving Program of Multiplexed Display Circuit using Digital Ports

;………………………………………………………………………………………………………………………….
Program Logic:
org $0000
L0: rjmp L1

org $0020
L1: Stack Initialization at $005F
L2: Initialize Lookup Table : 60h – 6Fh = cc-0, ……, cc-F
L3: Set Port Direction
L4: Keep 123456 into HEXT : 75h – 77h
L5: Convert Hex Value into CC Value and save CC-c9de Table : 82h – 87h
L6: Send CC-code from CCCT into CC7SDD
L7: goto L6
; ………………………………………………………………………………………………………………………….

28
Assembly Codes:
; Druvung CC7SDD devices by Port-B and Port-C, D
.include "m8def.inc"
.cseg
.org $000
L0:
RESET: rjmp L1 ;STKINIT

.org $020
L1: ; stack init STKINIT:
ldi r16, 0x5F ; stack initialize
out SPL, r16
ldi r16, 0x04
out SPH, r16

L2: ; CCTAB: ; cc-code table initialization 0060h - 006Fh

ldi r16, 0x3F ; cc0code of 0


sts 0x60, r16

ldi r16, 0x06 ; cc0code of 1


sts 0x61, r16

ldi r16, 0x5B ; cc0code of 2


sts 0x62, r16

ldi r16, 0x4F ; cc0code of 3


sts 0x63, r16

ldi r16, 0x66 ; cc0code of 4


sts 0x64, r16

ldi r16, 0x6D ; cc0code of 5


sts 0x65, r16

ldi r16, 0x7D ; cc0code of 6


sts 0x66, r16

ldi r16, 0x07 ; cc0code of 7


sts 0x67, r16

ldi r16, 0x7F ; cc0code of 8


sts 0x68, r16

ldi r16, 0x6F ; cc0code of 9


sts 0x69, r16

ldi r16, 0x77 ; cc0code of A


sts 0x6A, r16

ldi r16, 0x7C ; cc0code of b


sts 0x6B, r16

ldi r16, 0x39 ; cc0code of C


sts 0x6C, r16

ldi r16, 0x5E ; cc0code of d


sts 0x6D, r16

ldi r16, 0x79 ; CC-code of E


sts 0x6E, r16

ldi r16, 0x71 ; cc0code of F


sts 0x6F, r16

L3: ; PortD and PortB as outputs


ldi r16, 0xFF ; 1111 1111
out DDRB, r16 ; all portB/C pins are output

29
out DDRC, r16
sbi DDRD, DDD7 ; PC7, PC6 are outputs
sbi DDRD, DDD6

L4: ldi r16, $12


sts $75, r16

ldi r16, $34


sts $76, r16

ldi r16, $56


sts $77, r16 ; 123456

L5: rcall HEX2CC


L6: rcall CCXPB

L7: rjmp L6

;------------------------------------------
HEX2CC:
clr r27
clr r29
clr r31

ldi r26, $75 ; X = 0075h STAB


ldi r30, $82 ; Z = 0082h CCTAB

ldi r16, $03 ; 3 byte Hex to convert


;--------------------------
AGN: ld r17, X+ ; r17 = 12 X points at STAB
mov r18, r17 ; r18 = 12
swap r17
andi r17, 0x0F ; r17 = 01
ldi r19, 0x60
add r17, r19 ; r17 = 61

mov r28, r17


;------------------
ld r17, Y ; getting CC-code from LUTAB
st Z+, r17 ; outting into CCTAB
;------------------

mov r17, r18


andi r17, 0x0F ; r17 = 01
ldi r19, 0x60
add r17, r19 ; r17 = 61
mov r28, r17
;------------------
ld r17, Y ; getting CC-code from LUTAB
st Z+, r17
;------------------
dec r16

breq DONE

rjmp AGN

DONE: ret
;------------------------------------------------------
;----------------------------------------------------
CCXPB:
clr r31
ldi r30, $82
ldi r16, $06

30
ld r17, Z+ ; DP0
out PORTB, r17
ldi r18, $FE ; 1111 1110
out PORTC, r18 ; PC0 = LL
sbi PORTD, PD6 ; LH ---> PD6
sbi PORTD, PD7 ; LH ---> PD7
rcall DELAY

ld r17, Z+ ; DP1
out PORTB, r17
ldi r18, $FD ; 1111 1101
out PORTC, r18
sbi PORTD, PD6 ; LH ---> PD6
sbi PORTD, PD7 ; LH ---> PD7
rcall DELAY
ld r17, Z+ ; DP2
out PORTB, r17
ldi r18, $FB ; 1111 1011
out PORTC, r18
sbi PORTD, PD6 ; LH ---> PD6
sbi PORTD, PD7 ; LH ---> PD7
rcall DELAY

ld r17, Z+ ; DP3
out PORTB, r17
ldi r18, $F7 ; 1111 0111
out PORTC, r18
sbi PORTD, PD6 ; LH ---> PD6
sbi PORTD, PD7 ; LH ---> PD7
rcall DELAY

ld r17, Z+ ; DP4
out PORTB, r17
ldi r18, $FF ; 1110 1111
out PORTC, r18
cbi PORTD, PD6 ; LL ---> PD6
sbi PORTD, PD7 ; LH ---> PD7
rcall DELAY
ld r17, Z+ ; DP5
out PORTB, r17
ldi r18, $DF ; 1101 1111
out PORTC, r18
sbi PORTD, PD6 ; LH ---> PD6
cbi PORTD, PD7 ; LL ---> PD7
rcall DELAY

ret
;-----------------------------------------------------

DELAY: ldi r17, 20


cag: ldi r18, 20
mag: dec r18
brne mag
dec r17
brne cag
ret

DELAY1: ldi r17, 8


cagain: ldi r18, 100
magain: ldi r19, 100
fagain: dec r19
brne fagain
dec r18
brne magain
dec r17
brne cagain
ret
.exit
;…………………………………………………………………………………………………………………………………………………………………………………………………………………………………
31
15 External Interrupts

16 Internal Interrupts

17 Timer/Counter-0 (TC0) Programming and Operation


17.1 Introduction
As we see in Fig – 1.1, the Pin-6 of the Atmega8 is associated with the signals: (XCK-T0) PD4. The
interpretation for the pin signals stand as:
i. If the signal PD4 is associated, then it is meant that the Pin-1 is programmed to
exchange (input and output) 1-bit digital data with the external IO devices as per layout
of diagram Fig-17.1.
ii. If the signal T0 is attached, then it is meant that the Pin-1 will receive external pulses for
the internal Counter-0 as per diagram of Fig-17.1.
iii. If the signal XCK is attached, then it means that the Pin-1 will output clock frequency
from the internal UART as per diagram of Fig-17.1.

PD0 IO
SW1

1
Sw2
7 0
Counter-0

XCK
SW3

32
17.1 Counter-0 Programming and Operation of ATmega8

18 Timer/Counter-1 (TC1) Programming and Operation


18.1 Introduction
The TC1 can be operated in the following modes of operations

18.2 Accessing 16-bit TC1 Register using 8-bit Data Bus:


The TC1 is a 16-bit register and is composed of: TCNT1H and TCNT1L. The read/write
operations with these registers are accomplished in the following ways:
a. The ATmega8 architecture says that the 16-bit read/write operation is triggered when
the user instruction accesses the Low byte register. The same rule applies for all
available 16-bit registers of the ATmega8.
b. The mechanism works with the help of a temporary register (TR) into which the
intended value for the High byte register is automatically stored when the following
instructions are executed.
; Writing 4534h into TC1 Register ; 45h →TCNT1H ; 34h → TCNT1L
ldi r16, 0x34 ; 34h is to be kept into TCNT1L
ldi r17, 0x45 ; 45h is to be kept into TCNT1H
out TCNT1H, r17 ; now 45h is written into a temporary
; register and not into TCNT1H
out TCNT1L, r16 ; only now, 45h enters into TCNT1H
; and 34h enters into TCNT1L.

; Reading the 16-but contents if TC1


in r16, TCNT1L ; now (TCNT1L) enters into r16
; and (TCNT1H) enters into Temporary register
in r17, TCNT1H ; now (TCNT1H) has entered into r17
register

c. We see above that here are two accesses that are made to perform 16-bit data
read/write operations with the TC1. Now, if an interrupt occurs between the two
accesses and the ISR changes the contents of the TR then the user might end up with
corrupted result for the TC1. Therefore, it is a good practice to disable the interrupt (LL
at I-bit of SREG) while accessing the 16-but registers.

18.3 Normal Mode Operation of TC1


In ‘Normal Mode’ operation, the TC1 works as a simple 16-bit upcounter. It starts from counting
0000h or any other ‘manually pre-loaded’ value and reaches to the maximum count of FFFFh. At
the arrival of the next input pulse, the TC1 rollovers from all 1s to all 0s. The rollover event is
reflected as LH at the TOV1 (TC1 Overflow Flag) bit of the TIFR-register. The TOV1 is
automatically reset when the MCU vectors to ISR. The TOV1 can also be cleared to LL by writing
LH at the TOV1 flag bit itself via the TIFR-register.

The TOV1 flag in association with the I-bit of the SREG-register and the TOIE1-bit of the TIMSK-
register can interrupt the MCU. As a result, the MCU jumps at location 008h [Table – 7, P234] to
serve the Interrupt Sub Routine (ISR).

33
The clocking pulse of the TC1 could be obtained from external sources using the T1-pin (Pin-11)
or from the internal oscillators [Fig – 34]. When the TC1 receives the clocking pulses from the
external source, we say that the TC1 is working as Counter-1 (C1) and when the TC1 receives its
clocking pulses from the internal oscillator, we say that the TC1 works as Timer-1 (T1). The TC1
gets started when the clocking signal is applied. The TC1 is stopped when the clocking signal is
removed. The application and removal of the clocking signal is done with the help of the TCCR1-
register. The internal structure of the TC1 as Timer/Counter-1 is depicted below in Fig – 7.1.
1411a3 : GM : 2-10
clksys
K3A – K3D K7A – K7H
1MHz +/- 3% CLK CLK/1 clkIO
Internal 2MHz +/- 3%
RC CLK/8
Oscillator -1 4MHz +/- 3% CLK/32
8MHz +/- 3% Prescaler CLK/64

CLK/128
9 XT 1
K4
11.0592MHz

CLK/256
K1A 11.0592 MHz
Internal
Y1

Crystal CLK/1024

10 XT 2 Oscillator -2 0
K1B K2
11 T1 (PD5)

0V 14 PB0 15 0 I TOIE1
LEDR2 TCNT1 TOV1 IRQ : 008 h
K5 K6

Example – 7.2.1 [Counting External Pulses at T1-pin] Configure and operate TC1 as Counter-1 (C1) to
count every 250 pulses that arrives at its T1-pin from an external source and then will flash the LEDR2.
Assume that the external source is a 50Hz zero-crossing detector, which produces 20mS SQW [Fig – 7/5].
Counting of 250 pulses will result a time delay of: 250x20 mS = 5000mS = 5 sec. Also draw the timing
diagram to depict the relationships among TCNT1, TOV1 and PB0.

Procedures: Download and execute program …\ATmega8\TC1a1.asm (works OK! 17-02-2010) using
RMCKIT and check that the LEDR2 of the RMCKIT flashes at every 5-sec interval.

The program Structure:


L0: Initialize everything as needed
L1: Preload TCNT1 with count n so that rollover occurs at the end of counting exactly 250 pulses.
⇒ 250 = 0x00FA = 00FAh
⇒ n + 00FA = 0000
⇒ n = |0000 – 00FA| = FF06h
0xFF → r17 → TCNT1H
0x06 → r16 → TCNT1L
L2: Configure PBO as output, PD6 as input
L3: Start TC1 by closing only K2 (K3, K4 and K7 must remain opened) with the help of TCCR1-register.
L4: if (TOV1 ! = LH) ; rollover has not occurred
Goto L4
L5: Reload preload value for TCNT1 (FF06h)

34
Clear TOV1 by sending at TOV1-bit of TIFR
Flash LEDR2
L6: goto L4

The Timing Diagram:


TCNT1 Value
Max : 0xFFFF

0xFF06 (Preset )

t
0
TOV1
t
0 5 sec

PB0
t
0 5 sec
1634

Example – 7.2.2 [Measuring Pulse Width of Signal at ICP1-pin]

CTC (Clear Timer on Compare) Mode Operation of TC1


18.4 Capturing External Event using TC1
Capturing the ‘ON Period’ of an External Pulse:

35
19 Timer/Counter-2 (TC2) Programming and Operation
19.1 Introduction
The TC2 is a programmable 8-bit register, which can perform upcounting or downcounting
depending on the mode of operation. Like TC0 or TC1, there is no physical pin associated with
this register [Fig – 19.1] to receive external pulses. As we see in Fig-19.1, the source of the clocking
signal for TC2 can be either OSC-1 (Oscillator-1) or OSC-2 or OSC-3. If OSC-3 is used as a source
of clock for TC2, then we say that the TC2 is working in asynchronous mode. In async mode
operation, the external crystal should be changed to 32.768KHz because the design of OSC-3 has
been optimized for 32.768KHz watch crystal. The applications of TC2 are:
a. Generating known Time Ticks by selecting suitable clocking frequency (Normal Mode).
b. Generating Square Wave Signals (SQW) of fixed frequency. (CTC Mode)
c. Generating SQW of continuously varying frequency (CTC Mode).
d. Generating High Frequency (fast) Pulse Width Modulated Signal (Fast PWM).
e. Generating High Resolution Pulse Width Modulated Signal (Phase Correct PWM)

The following registers are associated with the programming and operation of TC2:
Name Function
SREG Status Register Affects the global interrupt enable bit (I-bit)
TIMSK Timer/Counter Interrupt Mask Register Affects TOIE2 and OCIE2 bits
TIFR Timer/Counter Interrupt Flag Register Records the logic values of TOV2 and OCF2
TCCR2 Timer/Counter-2 Control Register Selects Mode of Operation and prescaler frequency
TCNT2 Timer/Counter-2 Data Register Actual TC2 Data Register
OCR2 TC2 Output Compare Register Decides at what counts the TCNT2 should reset
ASSR Asynchronous Status Register Selects asynchronous mode clock for TC2
SFIOR Special Function IO Register Controls Prescaler and Pullup resistors for ports
DDRB Data Direction Register for PORTB Pins To set directions of the PB3-pin as output
1411 a2 : GM : 2-10
clksys
K3A – K3D K8A – K8H
1MHz +/- 3% CLK CLK/1 clkIO
Internal 2MHz +/- 3% K7
CLK/8
RC
Oscillator -1 4MHz +/- 3% CLK/32

8MHz +/- 3% Prescaler CLK/64

CLK/128
9 XT1
K4
11.0592MHz

CLK/256
K1A 11. 0592MHz
Crystal
Y1

CLK/1024
Oscillator -2
10 XT2 0

Clkasy
Crystal
32.768KHz

Oscillator -3
K2 (32.768KHz) K6
Y2

CRE
7 0 I TOIE2
TCNT2 TOV2 IRQ : 004h
K9 K10
CME
I OCIE2
= OCF2 IRQ : 003h
K11 K12
7 0 WGM21:0, COM21:0
(PB3-MOSI) OC2 17
Waveform
OCR2
Generator K13

Figure – 19.1: Structure of Timer/Counter-2


36
19.2 Timer/Counter2 (TC2) Operation as Time Tick Generator
19.3 Timer/Counter2 (TC2) Operation as Square Wave Generator
To deliver SQW signal, the TC2 is programmed in the CTC Mode. The CTC mode is set with the
help of TCCR2-register, which configures ‘Waveform Generator Module’ of Fig-1.19 to generate
SQW signal. The CTC stands for ‘Clear Timer on Compare Match), which means that the TC2, in
the process of counting will reset to 00s if its current content matches with the content of the
OCR2-register. The value loaded into the OCR2 register is known as TOP. The TC2 will never
reach to its maximum count of FFh. The ‘count reset event (CRE)’ and the ‘compare match event
(CME)’ are recorder as LH at the TOV2 and OCF2 bits respectively of the TIFR-register. To clear
these flag bits, one has to write LH into these bits via the TIFR register. The TOV2 and OCF2 flag
bits can be used to interrupt the MCU to take actions if there is any [Fig-19.1]!

The TC2 of the ATmega8L can be configured to deliver square wave signals at its OC2-pin (Pin-
17). The frequency of the output signal has been given by:
fOC2 = CLK / ( 2. N. (1+ OCR2))
Where: N refers to prescale factor (1, 8, 32, 64, 128, 256 or 1024) of Prescaler.
OCR2 refers to the value that is preloaded into OCR2 register to obtain
fOC2.
Let us assume that we want output frequency, fOC2 = 100Hz (expected)
1. CLK is set at 1MHz
2. N is set at 256
3. Then the content of OCR2 register is : 19.5312 = 13h

The actual frequency range of fOC2 is:


1. (100000 – 30000)/(2 x 256 x (1+19)) = 94.73 Hz [with - 3% error in 1MHz CLK]
2. (100000 + 30000)/(2 x 256 x (1+19)) = 100.59 Hz [with + 3% error in 1MHz CLK]

3. To obtain accurate frequency for the output signal, we have to use external crystal.
The value that should be stored in OCR2 is computed from the given equation of fOC2 and is then
stored into the OCR2 register. And finally, the clkIO is selected from the prescaler, which initiates
the generation of the square wave signal. In Normal and CTC mode, the OCR2 double buffering
is disabled. The MCU can directly access the content of OCR2.
The TCNT2 (TC2) starts counting up the clkIO pulses and its current content is being
continuously compared with the content of OCR2 register. When the two values become equal, a
‘compare match event (CME)’ occurs, which does the following:
1. It clears the TCNT2. As a result, the TCNT2 starts counting up from 00h and proceeds to
generate the next ‘match event’.
2. It triggers the waveform generator, which in turn sets the OC2-pin.The OC2-pin remains
at LH until the next ‘match event’ is received by the waveform generator. At the next
‘match event, the OC2-pin gets cleared and remain in clear state until the next ‘compare
match event’ arrives. This way, a square wave signal (SQW) is asserted on the OC2-pin of
the ATmega8 chip through the programming of the TC2 in CTC mode. The signal
generation mechanism is diagrammed in Fig-19.2.

37
3. To be able to see SQW at the OC2-pin, the direction of PB3-pin must be set as output
through the DDRB register.

TCNT2 Value

MAX : FFh
OCR2 = 13h

for 100Hz

0
TOV2 (CRE)

0
OFC2 (CME)

OC2-pin Logic

0 t1 t2 t3

1411 a2
Figure – 19.2: TC2 as Square Wave Generator in CTC Mode

Example – 19.1 [TC2 as 100Hz SQW] To configure and operate TC2 of ATmega8 as 100Hz Square Wave
Generator using RMCKIT.
Procedures: Use RMCKIT for ATmega8 and download/execute program ….\ATmega8\TC2a1.asm. We
will be able to see approx 100Hz SQW signal on oscilloscope at Pin-17.
The Program Structure:
L1: Init Stack
L2: SQW (CTC) Mode Set via TCCR2-register
L3: Load OCR2 count for 100Hz get counts from equation fOC2
L4: Set PB3 as output via DDRB register
L5: Start TC2 by selecting clkIO via TCCR2 register
L6: end

38
19.3 Timer/Counter2 (TC2) Operation as Fast (High Frequency) Pulse Width
Modulator
49 : GM : 02-10
TCNT2 Value

MAX : FFh
OCR2-2
OCR2-1

0 t
TOV2 (CRE)
t
0
OFC2-1 (CME)

t
0

OC2-1 pin Logic


ONP
0 t1 t2

OC2-2 pin Logic


ONP
t
T

Figure – 19.2 : Timing Diagram of TC2 Generated Single Slope Fast PWM

Pulse Width Modulation (PWM) refers to the continuous change in the ‘ON Period’ of a fixed
frequency signal. Fast PWM (FPWM) refers to a particular type of PWM, which can operate
relatively at a higher frequency.

To generate FPWM, the TC2 is configured to operate in ‘Fast PWM Mode’ with the help of
TCCR2 register. The TCCR2 register, in turn sets the ‘Waveform Generator Module’ of Fig-19.1 to
operate in the specified mode. The frequency of the FPWM remains confined within the
‘upcounting time’ of the TC2 and hence it is called ‘Single Slope PWM’ [Fig-19.3].

In a ‘Dual Slope PWM’, the frequency of the PWM remains confined within the time period of
‘upcounting and downcounting’ [Fig-19.4] of TC2. ‘Phase Correct PWM’ is an example of a ‘Dual
Slope PWM’.

Let is refer to Fig-19.1 and 19.5 to understand the working principle of the FPWM. The frequency
of the FPWM is given by the following equation:
fOC2OFOWM = clkIO/(N x 256)

Let us take one for N (prescaler factor) and the clkIO = CLK = 1MHz and then the expected
frequency is about 3906.25KHz. The duration of the ‘ON Period = ONP’ of the PWM is
determined by the content of the OCR2 register [Fig-19.6].

39
After the PWM mode set, the TC2 starts counting from 00h and its output faces continuous
comparison with the content of OCR2 [Fig-19.1]. The OC2-pin is initially kept at LH (non
inverting) but it can also be kept at LL (inverting) by TCCR2. When a ‘compare match event
(CME)’ occurs, the OC2-pin goes to LL-state and remains in this state until the TC2 reaches to its
max count and gets resetted [Fig-19.7]. After the CME event in the upcounting edge, the TC2
continues upcounting and reaches to max count of FFh. At this point, when the next pulse
arrives, the TC2 undergoes rollover and its content becomes 00h. This is the ‘count reset event
(CRE)’, which forces the OC2-pin to assume LH-state again. Thus, we see that a complete signal
cycle (let us call PWM) has appeared within the ‘upcounting period = UCP’ of the TC2. The ONP
feature of this signal can be varied dynamically by changing the contents of the OCR2-register.
However, for obvious reason, the frequency of the PW will remain unchanged.

The CME and the CRE events set the OCF2 and TOV2 flags of the TIFR register. These flags buts
can be effectively used to interrupt the MCU fir taking actins if there is any like updating the
content of the oCR2.

In a practical situation like controlling the output current of a Battery Charger [Section – 34], the
ONP of the PWM will be changing all the times. Therefore, there must exist a mechanism for
updating the contents of the OCR2. In PWM mode, the OCR2 is ‘double buffered’ for write
operations. This means that the user program can write new value for OCR2 at any time and it
will first enter into the temporary register and then into the actual OCR2-register at the next CRE
event. The following codes could be used to write new value into the OCR2.
ldi r16, n1 ; n1 is an initial value
ldi r17, n2 ; n2 is an incremental value and to be added with
n1
add r16, r17 ; new update value is preserved.
out OCR2, r16
;--------------------------------------------------------------------------------------

The following codes do not work, which means that in the PWM mode, the actual OCR2 and its
buffer are not accessible for read operation.
in r16, OCR2 ; reading n1 from actual (buffer) of OCR2
ldi r17, n2 ; n2 is an incremental value and to be added with
n1
add r16, r17
out OCR2, r16

If the updating of the OCR2 is to occur after the elapse of fixed amount of time (say, 5 sec), then
this time can be accounted by counting the CRE (TOV2) events. The number of CRE events for
every 5 sec time will remain fixed because the operating frequency of FPWM is fixed.

Example – 19.2 [TC2 as 3906.25Hz Fast PWM] To configure and operate TC2 of ATmega8 as 3906.25Hz Fast
PWM using RMCKIT.
Procedures: Use RMCKIT for ATmega8 and download/execute program ….\ATmega8\TC2a2.asm. We
will be able to see FPWM on oscilloscope at Pin-17. The LEDR2 (connected at PB0) will also flash at every 5-
sec.

40
The Program Structure:
L1: Init Stack
Reserve r21:r20 for 5-sec count
Reserve r22 for initial PW (Pulse Width)
L2: Fast PWM Mode Set via TCCR2-register
L3: Set PB3 as output via DDRB register
L4: Load OCR2 count for initial PW 0x05
L5: Start TC2 by selecting clkIO via TCCR2 register
L6: Count TOV2 events to account for 5-sec elapse
If (5-sec not elapsed)
Goto L6
Reset r21:r20 5-sec counter
L7: add 5µS with initial PW and sent to OCR2
Flash LED2
Goto L6

The Assembly Codes:


; Single Slope Fast PWM of TC2 f= 3906.25Hz

.include "m8def.inc"
.cseg

.org $000
RESET: rjmp L1

.org $020
L1: ; stack initialization
ldi r16, 0x5F ; stack initialize
out spl, r16
ldi r16, 0x04
out sph, r16

ldi r21, 0x00


ldi r20, 0x00 ; to count 5 sec = 4C4Bh from TOV2
ldi r22, 0x05 ; initial OW of 5 uS
L2: ; Fast PWM Mode Set
ldi r16, 0x68 ; Fast PWM
out tccr2, r16

L3: ; PB3 as output


ldi r16, 0xFF ; 1111 1111
out ddrb, r16 ; all portB pins are output

L4: ; Set if Initial PW via OCR2


;ldi r16, 0x05 ; PW = 20uS
out ocr2, r22

L5: ; Start TC2 by selecting clkIO = 1000 000 Hz

in r16, tccr2
ori r16, 0x01 ; clk/1
out tccr2, r16

L6: ; check if 5 sec has elapsed


in r17, TIFR
rol r17
rol r17
brcc L6 ; TOV2 is not set

41
in r17, TIFR
ori r17, 0x40 ; LH --> TOV2
out TIFR, r17

ldi r16, 0x01 ; coint TOV2 r21:r20


add r20, r16
ldi r16, 0x00
adc r21, r16

ldi r16, 0x4B ; 4C4Bh for 5 sec


cp r20, r16
brne L6
ldi r16, 0x4C
cp r21, r16
brne L6

ldi r21, 0x00


ldi r20, 0x00

L7: ; ipdate OCR2 by 0x05 uS


ldi r16, 0x05
add r22, r16
out OCR2, r22

sbi PORTB, PB0 ; flash LEDR2 at PB0


rcall DELAY
cbi PORTB, PB0
rcall DELAY

L8: ; repeat
rjmp L6

DELAY: ldi r17, 8


cagain: ldi r18, 25
magain: ldi r19, 25
fagain: dec r19
brne fagain
dec r18
brne magain
dec r17
brne cagain
ret

.exit

19.4 Dual Slope High Resolution Phase Correct PWM using TC2

20 Serial Peripheral Interface Operation and Programming

21 USART Interface Programming and Operation

42
22 Two-wire Serial Interface Programming and Operation
TWI Logic Unit of Master TWI Bus TWI Logic of Slave-1
Vcc
Address Match Unit Bus Interface Unit Internal Pull-ups
Slew Rate
Control
27 27
Address Arbitration START/STOP SDA SDA
Spike
Register (TWAR) Detection Control Filter
SWA
Address/Data Slew Rate
Address Spike Control 28 28
Comparator Shift Register ACK SCL SCL
(TWDR) Suppression
Spike
Filter

Blank Status Register Prescaler GRN1


*TWSR)

PB1
State Machine Bit Rate
Control Register RED1
and Status Register (TWBR)
(TWCR)
Conrol
PB0
Control Unit Bit Rate Generator 0V
57 : GM : 3-2010

Fig – 22.1 : Internal TWI Logic

Who is the Master in this TWI System? ATmega8-A or ATmega8-B?

The device that initiates and terminates transmission on the TWI


bus is called a Master. Transmission Initiation (TXI) means that L1: START

the Master device generates START condition on the TWI bus.


Transmission Termination (TXT) means that the Master devices Make LH at SDA, SCL
Assert START
generates STOP condition on the TWI bus. The TWI logic checks L2:
if the TWI bus is available, and then generates START condition N
if it is free.
TWINT = LH
?

L3: Y

N
TWSR = 08
?
Bus at
Bus Error Y START

L5:
SLA+W - Æ TWDR
Clear TWINT to begin Tx

57

Fig-22.2 : Flow Chart

What is the meaning of TWI Bus is Free?


Let us assume that the device ATmega8-A desires to seize the bus for data transmission. The
device carries out the following actions:
1. An attempt is made to connect the SDA and SCL pins with its internal TWI logic.
2. An attempt is made to bring the SDA and SCL lines into LH-states.
3. An attempt is made to bring the SDA-line into LL-state.
43
It is expected that the above actions be done automatically when the MCU loads the 10100100b
into its TWCR-register.
ldi r16, 0b10100100
out TWCR, r16

LH at Bit-2 (TWEN = TWI Enable of TWCR) connects the SDA and SCL pins with the TWI logic.

LH at Bit-7 (TWINT = TWI Interrupt of TWCR) clears the TWINT-bit and as a result, the SDA
and SCL lines assume LH-states.

Immediately, after the application has cleared the TWINT-bit by writing LH at this bit, the TWI
logic will generate START condition on the TWI bus. Changing the level of the SDA line when
the SCL line is high signals the START condition [Fig – 22.1].

LH at Bit-5 (TWSTA = TWI START of TWCR) brings the SDA line to LL-state. When the SDA line
has actually assumed LL-state and there is a little delay and then the TWINT-bit becomes LH and
as a result the SCL line immediately goes to LL-state and remains at LL-state until the TWINT-bit
is cleared [Fig – 22.1].

The user program keeps polling the TWINT-bit for LH-state and when it is found at LH-state, it
is said that a ‘BusEvent’ has occurred[ at t2 in Fig – 22.1].

The current busevent is the START condition of the TWI bus and if this condition has really
happened, the TWSR-register is supposed to contain 00001 at its upper 8-bit.

When the MCU finds 00001 at the upper 5-bits of the TWSR, it is said that the MCU has acquired
the bus (the bus is not busy) and the device ATmega8-A may proceed to accomplish data
transmission over the TWI bus.

Fig-22.3:

44
To initiate transmission (say telling the Slave-1 of Fig–22.1 to blink the GRN1 LED for 3 times) by
the Master on the TWI bus, the following events take place (assume that Slave-1 has been
initialized properly, Section – 22.2]:

A: To bring START condition on the TWI bus.


START condition refers to:
• Connect the IO pins 27 and 28 with the internal TWI logic of the Master so that the
lines may work as SDA (Serial Data) and SCL (Serial Clock) lines.
This happens when LH is written into the TWEN bit of the TWCR register.
• Bring up the SDA and SCL lines at LH states [Fig – 22.3].
This happens when LH is written into TWEN-bit of the TWCR register.
• Bring down the SDA and SCL lines at LL states [Fig – 22.3]. This state of the TWI
bus is known as ‘No Transmission State = NTS)’ or the ‘Idle State’.
This happens when LH is written into the TWSTA bit of the TWCR register.
• Clear the TWINT bit of the TWCR register so that the TWINT bit can assume LH
state after the occurrence of the START busevent (or any other busevent) on the
TWI bus.
This happens when LH is written into the TWINT bit itself of the TWCR.
• Getting the following Return Values:
a. LH at the TWINT bit indicating that the TWI bus is at NTS state.
b. 08h into the TWSR indicating that the START condition has occurred on
the TWI bus.

Verification using RMCKIT:


1. Build the following display circuit [Fig – 22.4] on the breadboard and connect it with
the indicated pins of the ATmega8 of the RMCKIT via the edge connectors.

U3: ATmega8L RMCU


DPA DPB DPC DPD DPE DPF
+5V
PBR
10 5 p
PB7
RST 9 10 g
PB6
PB5 19 9 f
R1 18 1 e
4k7 PB4
1 17 2 d
RST/ PB3
16 4 c
PB2
15 6 b
C1 PB1
PB0 14 7 a
100 uF ccA ccB ccC ccD ccE ccF
3 3 3 3 3 3
0V 8, 22 1MHz
GND
+5V 7
Vcc
20 23
AVcc PC0 24
PC1 25
+5V PC2
26
2-6, 11,21,27,28 PC3 12
NC PD6
13
PD7
TWI Logic
SDA 27
SCL 28 TWI Bus

52a : GM: 03-10

Fig-22.4: RMCKIT Based Circuit Setup to verify START Condition of TWI Bus

45
2. Download the …\ATmega8\P221.hex program into the RMCKIT and execute it.
3. Observe that DPA show 1, which is the content of the TWINT bit of the TWCR.
4. Observe that DPE and DPF positions show 08h, which is the content of TWSR.

Program Codes Listing: …\ATmega8\P221.asm


; Testing START condition of TWI Interface Protocols
.include "m8def.inc"
.cseg
.org $000
L0:
RESET: rjmp L1 ;STKINIT

.org $020
L1: ; stack init STKINIT:

L2: ; CCTAB: ; cc-code table initialization 0060h - 006Fh


;---------------------------------------
L3: ; PortD and PortB as outputs
; Enable internal Pullups for SDA and SCL as TWI terminators
sbi PORTC, PC4 ; pull-ups os enabled verifued that
sbi PORTC, PC5 ; internal pull-ups work as TWI bus terminators

;------------------------------------
L1A: ; asserting START condition on TWI bus
ldi r16, 0b10100100 ; LH Æ TWINT, LH -Æ TWSTA, LH -Æ TWEN
out TWCR, r16
L2A: ; polling TWINT bit for LH
in r16, TWCR
sbrs r16, 7
rjmp L2A

L3A: ; redaing TWSR


in r16, TWSR
andi r16, 0b11111000
cpi r16, 0x08
brne ERROR ; TWSR is not 08h
;--------------------------------------------------
L4: ldi r17, $10 ; 1 die to LH at TWUNT bit
sts $75, r17

ldi r17, $00


sts $76, r17

sts $77, r16 ; 08

L5: rcall HEX2CC ; converting HEX to CC-code


L6: ; blank DPB - DPD

L7: ; transfer CC-code to display


rcall CCXPB

L8: rjmp L6 ; keep refreshing the display

ERROR: rjmp ERROR


;------------------------------------------
.exit
;----------------------------------------------------------------------------------------

46
B: Send Slave-1 Address (SLA = 7-bit, 1000110) and Data Write Command (LL = 1-bit)
Now, the TWI bus is at NTS (No Transmission State) state. The TWINT bit contains LH. The
transmission will begin (bus activity) when the TWINT bit is cleared by writing LH into it and LL
at TWSTA-bit and LH at TWEN-bit. Before writing the above bits into the TWCR, the SLA+W (8-
bit, 1000 1100) must be written into TWDR.

Assume that the Slave-1 has been initialized with the address 1000 110b. It is also programmed to
assert ACK (acknowledgement = pulling down the SDA line for 1-bit period after receiving the
SLA +W bits) bit provided that slave address (SLA) send by the Master matched with its own
address.

Verification using RMCKIT:


The Procedures:
1. Build the following the Slave-1 circuit on the breadboard (extreme left) and connect it with
the ATmega8 of the RMCKIT.

U3: ATmega8 L RMCU


DPA DPB DPC DPD DPE DPF
+5V
PBR
5 p
PB7 10
RST 10 g
PB6 9
R1 PB5 19 9 f
PB4 18 1 e
4k7 1
RST/ PB3 17 2 d
16 4 c
PB2
15 6 b
C1 PB1
100uF PB0 14 7 a
ccA ccB ccC ccD ccE ccF
3 3 3 3 3 3
0V 8, 22 1MHz
GND
+5V 7
Vcc
20 23
AVcc PC 0 24
PC 1 25
+5V PC 2
26
2-6, 11,21,27,28 PC 3 12
NC PD 6
13
PD 7
TWI Logic R1=1k5
SDA 27 27 SDA 1 +5V
ATmega8L RST/
SCL 28 28 SCL 7
Slave -1 Vcc
0V 8 20
GND AVcc
TWI Bus PB1 PB0
U1X
15 14
GRN1 RED1
0V 0V
52ab : GM: 03-10

Figure – 22.5 :
2. Power up the RMCKIT. Observe that the RED1 of Slave-1 keeps blinking.
3. Download and execute …\ATmega8\Slave1adr.hex
4. Connect the RST/-pin of the Master ATmega8 of the RMCKIT at 0V. Observe that the RED1
keeps blinking.
4. Remove power from the RMCKIT.
5. After a while apply power to RMCK. Observe that RED1 of Slave-1 is blinking.
6. Remove the RST/-pin of the Master from the 0V. Observe that the RED1 blinks only for 4
times with a long pause between the blinking and then blinks normally. It indicates that the
Slave-1 has received its own address transmitted by the Master.
47
7. Also observe that the DPE and DPF positions of the display show 18h. It indicates that that
SLA+W has been accepted by the Slave-1.

Master Program Code Listing (…\ATmega8\Master1.asm)


.include "m8def.inc"
.cseg
.org $000
L0:
RESET: rjmp L1 ;STKINIT

;----------------------------------------
.org $020
L11: ; stack init STKINIT:
L21: ; CCTAB: ; cc-code table initialization 0060h - 006Fh
---------------------------------------
L31: ; PortD and PortB as outputs

; Internal pullips for TWI bus


sbi PORTC, PC4 ; pull-ups os enabled verifued that
sbi PORTC, PC5 ; internal pull-ups work as TWI bus terminators

;------------------------------------

L1: ldi r16, 0b11100100 ; tp assert the START busevent.


out TWCR, r16

L2: ;poll TWINT


in r16, TWCR ; at the end of expected busevent, TWINT assumes LH
sbrs r16, 7 ; finish all tasks before initiating the next busevent.
rjmp L2
L3: in r16, TWSR
andi r16, 0b11111000
cpi r16, 0x08 ; after START busevent, the TWSR must cintain 08h
brne ERROR

L3A: ; send Slave-1 address


ldi r16, 0x8C ; 10001110 SLA+W = 1000111 0
out TWDR, r16
L3B: ; initiate transmission by TWCR
ldi r16, 0xC4 ; 1100 0100 clear TWINT Enable ACK
out TWCR, r16

L4: ; poll TWUNT


in r16, TWCR
sbrs r16, 7
rjmp L4
L5: ; read TWSR for 18h
in r16, TWSR
andi r16, 0b11111000
cpi r16, 0x18
brne ERROR ; Slave-1 has not received its address
LX: ; display status code 18h at DPE and DPF positions
sts $75, r17
ldi r17, $00
sts $76, r17

sts $77, r16 ;

LXA: rcall HEX2CC

LXB: ; blank DPA - DPD


rcall CCXPB

48
LXC: rjmp LXB

ERROR: rjmp ERROR


;------------------------------------------
.exit

Slave-1 (Polling the TWINT Bit) Program Code Listing (…\ATmega8\Slave1.asm):


; TWI Slave Receiver
.include "m8def.inc"
.cseg
.org $000
L0:
RESET: rjmp L1 ;STKINIT
.org $020
L1: ; stack init STKINIT:
;---------------------------------------
L3: ; PortD and PortB as outputs
L3A: ; initialize slave-1 address
ldi r16, 0b10001100 ; slave address 8Ch
out TWAR, r16 ; slave address is set

L3B: ; assert START contion on TWI bus


ldi r16, 0xC4 ; 1100 0100 ACK enabled, Clear TWINT
out TWCR, r16

BLINK1: sbi PORTB, PB0


rcall DELAY1
cbi PORTB, PB0
rcall DELAY1

L4B: ; checking if any busevent has occurred


in r16, TWCR
sbrs r16, 7
rjmp BLINK1 ; no busevent has occurred
in r16, TWSR ; busevent has occurred
andi r16, 0xF8
cpi r16, 0x60 ; TWSR will be 69h if Slvae-1 receives its own addr.
brne BLINK1 ; busevent is not for Slave-1 address

ldi r20, 0x04 ; Slave-1 has recognized its address


AGNB: LH -Æ PB0 ; blink RED1 of Slave-1 for 4 times with long pause
rcall DELAY1
LL Æ PB0
rcall DELAY1
dec r20
brne AGNB

rjmp L0

;-----------------------------------------------------
.exit

Slave-1 (Vectored Interrupt) Program Code Listing (…\ATmega8\Slave2.asm):


; TWI Slave Receiver
.include "m8def.inc"
.cseg
.org $000
L0:
RESET: rjmp L1 ;STKINIT

.org $011
rjmp TWISR

49
.org $020
L1: ; stack init STKINIT:
ldi r16, 0x5F ; stack initialize
out SPL, r16
ldi r16, 0x04
out SPH, r16
;-------------------------------------------
sei ; Global Interript Bit is enabled
;---------------------------------------
L3: ; PortD and PortB as outputs

ldi r16, 0xFF ; 1111 1111


out DDRB, r16 ; all portB/C pins are output
out DDRC, r16
sbi DDRD, DDD7 ; PC7, PC6 are outputs
sbi DDRD, DDD6

;sbi PORTC, PC4 ; pull-ups os enabled/disabled


;sbi PORTC, PC5 ; doesn't matter, it works

;------------------------------------
ldi r16, 0b10001100 ; slave address 8Ch
out TWAR, r16 ; slave address is set

AGN: ldi r16, 0xC5 ; 1100 0100 ACK enabled, Claer TWINT
out TWCR, r16

;Mainline Program:
;----------------------------------------
BLINK1: sbi PORTB, PB0
rcall DELAY1
cbi PORTB, PB0
rcall DELAY1
L4B: ; wait1
;in r16, TWCR
;sbrs r16, 7
rjmp BLINK1
;------------------------------------
;Interrupt Sub Routine

TWISR: in r17, TWCR


ori r17, 0x80
out TWCR, r17

in r16, TWSR ; TWINT is LH die to SLA?


andi r16, 0xF8
cpi r16, 0x60
brne BLINK5

ldi r20, 0x04


AGNB: sbi PORTB, PB0
rcall DELAY1
rcall DELAY1
rcall DELAY1
rcall DELAY1
cbi PORTB, PB0
rcall DELAY1
rcall DELAY1
rcall DELAY1
rcall DELAY1
dec r20
brne AGNB
BLINK5: reti

.exit

50
The TWI Bus Activities:

START MSBA
SDA
1 0 0 0 1 1 0 0 (Write) 0 (ACK)

SCL

1 2 3 4 5 6 7 8 9

t1 t2 t3
15-03-2010 : GM :57

Figure – 22.6:

Working Principle:
1. The Slave-1 is running and is busy in normal blinking of RED1 LED. During blinking the
Slave-1 checks by looking at its TWINT bit if a busevent has occurred [L4B of
…\ATmega8\Slave1.asm.].
2. The SDA and SCL lines at the Master side [Fig – 22/6] is idle after the START condition.
3. The Master loads the TWDR with the address of the Slave-1 [ L3A: of
…\ATmega8\Master1.asm].
4. The Master initiates transmission by activating the TWCR [L3B: of
…..\ATmega8\Master1.asm].
5. The TWI bus activities of Fig-22.6 are automatically generated. The Master generates 8 clock
pulses over the SCL line for the 8 SLA+W buts. It then generates one more clock pulse to
receive the ACK (LL of the Slvae-1 has received its own address) bit. After that, the SDA and
SCL lines come down to LL states indicating NTS state.

C: Send Data 07h to the Slave-1


Now, the Master will send a data byte of 07h to the Slave-1. The Slave-1 will receive it
successfully and if so it will blink the GRN1 LED for 7 times. The DPE and DPF positions of the
RMCKIT will show 28h indicating that the busevent has correctly occurred.

51
23 Analog Comparator Unit

24 Watch-dog Timer
Covered in Section-19: System Control and Reset
25 Analog-to-Digital Converter

26 Boot Loader Programming

27 Code memory Programming

28 Data Memory Programming

29 Fuse Bits Programming


Fuse Bits Configuration and Function
4.1 Fuse Bit Definitions
The ATmega8 contains two fuse bytes (16 Fuse Bits), which can be broken (programmed, 0) and
established back (unprogrammed, 1) by software programming. The configuration of the fuse
bytes determines the mode of operation of the ATmega8 chip. The functional definitions of the
fuses are given in the following table:

Table – 8.2: Fuse Low Byte


Fuse Bit Name Bit No. Description Default Remarks
BODLEVEL 7 Brown out detector trigger level 1 Unprogrammed
BODEN 6 Brown out detector enable 1 BOD disabled
SUT1 5 Select MCU start-up time 1 The default values give
SUT0 4 Select MCU startup time 0 maximum start-up time
CKSEL3 3 Select clock source for MCU 0 The default values for
CKSEL2 2 Select clock source for MCU 0 CKSEL3..0 sets the MCU to
CKSEL1 1 Select clock source for MCU 0 operate at 1MHZ ± 3% of the
CKSEL0 0 Select clock source for MCU 1 internal RC oscillator

Table – 8.3: Fuse High Byte


Fuse Bit Name Bit No. Description Default Remarks
RSTDISBL 7 Select PC6 as IO pin or RST/-pin 1 PC6 works a RST/-pin
WDTON 6 Watch dog timer is always ON 1 WDT is enabled
SPIEN 5 ISP Programming 0 ISP is enabled
CKOPT 4 Oscillator option 1 Related with CKSEL3..0
EESAVE 3 Data EEPROM is 1 Not preserved
preserved during chip erase
BOOTSZ1 2 Select Boot Size 0 The default values results in
BOOTSZ0 1 Select Boot Size 0 maximum Boot Size
BOOTRST 0 Select Reset Vector 1 Startup Location is : 000h

52
4.2 Fuse Bit Programming Procedures
ISP Programmer: The ISP Programmer (Section – 3.4) can change any fuse bit provided that the
‘ISP Programming Mode’ remains enabled. This is to say that the SPIEN fuse bit must not be
changed to LH. In case the SPIEN fuse bit is mistakenly turned to LH during ISP Programming,
then the ISP programmer could no longer be able to program the ATmega8. The chip appears to
be fully disabled. Under this circumstance, the Parallel Programmer (Section 4.5) must be used to
bring the fuse bits of the chip into its original factory settings. The factory a setting brings the
SPIEN bit into programmed condition and then the ISP programmer can again be used. One
member of the ATmega8 forum has claimed that the chip can still be brought back to the factory
setting by ISP Programmer in the following way:
Inject about 4MHz signal at the XTAL1-pin of the chip and then issue Erase Command from
the ISP Programmer! I have not yet tried it.

Parallel Programmer: The Parallel Programmer (Section – 5.6) provided full programming
facilities for the ATMega8 that includes the manipulation of the fuse bits as per requirement of
the user.

30 Lock Bits Programming

31 Instructions of ATmega8
31.1 Terminology
Status Register (SREG)
Z Zero Flag
C Carry Flag
N Negative Flag
V Two’s Complement Overflow Flag
S N ⊕ V, for Signed Tests
H Half Carry (Auxiliary) Flag
T Transfer Bit used BLD and BST Instructions
I Global Interrupt Enable/Disable Flag

Registers and Operands


Rd Destination/Source register (d) in the Register File
Rr Source Register (r) in the Register File.
R Result after the instruction is executed
K Constant data
k Constant address
b Bit in the Register File or IO Register (3-bit)
s Bit in the status registers (3-bit)
X Indirect Pointer Register [X = R27:R26]
Y Indirect Pointer Register [Y = R29:R28]
Z Indirect Pointer Register [Z = R31:R30]
A IO Location Address
q Displacement for direct addressing (6-bit)

53
31.2 Instruction Set Summary

Arithmetic Instructions
ADD Add without Carry
ADC Add with Carry
ADIW Add with Immediate to Word
SUB Subtract without Carry
SUBI Subtract Immediate
SBC Subtract with Carry
SBCI Subtract Immediate with Carry
SBIW Subtract Immediate from Word

31.3 Brief Description of ATmega8 Instruction


Mnemonics Operands Description Operation Affected Flag Ck
Arithmetic and Logic Instructions
ADC Rd, Rr Add with Carry Rd ← Rd + Rr+C 0≤ d, r ≤ 31 ITHSVNZC 1
ADD Rd, Rr Add without Carry Rd ← Rd + Rr 0≤ d, r ≤ 31 ITHSVNZC
ADIW Rd+1:Rd, K Add Immediate to Word Rd+1:Rd ← Rd+1:Rd+K --- SVNZC
d ∈{ 24, 26, 28, 30 }, 0≤ K ≤ 63
AND Rd, Rr Logical AND Rd ← Rd • Rr 0≤ d, r ≤ 31 ---S0NZ-

31.4 Detailed Description of Instruction Set

Syntax : SBIC A, b 0 ≤ A ≤ 31, 0 ≤ b ≤ 7


Meaning : Skip the execution of the next instruction after this SBIC If Bit-b of IO register A
is found Clear

32 Interfacing Experiment

54
32 System Design
1605a: GM : 30-11-09

EMIF MCU : ATmega8L BLCF (Balance Field)


L L (Volt ) PBR DP0 DP1 DP2 DP3 DP4 DP5
i+
SHNT Isense
i-
8
220V + C0 (Energy Pulse )
50Hz Load cef p, g,..., b, a
- 0V
16 per
K1 0.01kwh

N N PC0 PC1 PC2 PC3 PD6 PD7


PCR
4
RLIF
P3.3 (Power OFF ) PDR
+12 PRPC
PFIF PVIF FPCP (ATmega8L)
INT0 (PD2)
(Power Fail ) Vcc Vcc1

PD1 LEDR
PWRS 0V 0V
Vcc SCL SCL
+5 0V
DM SDA SDA PB0
+12 R1
+V PRIF 1k5
Vcc1 RST/
CM
MRIF 1FFF
Vcc DM
Vcc
RST/
0000
PD 0 MCIF
CM
Security Mechanical Coupling 3FF
Buzzer BUIF 0V
PD 5 (Alarm ON ) K2 000
Security
+V

1. SHNT : Shunt 2. EMIF : Energy Measure Interface 3. RLIF : Relay Interface 4. PFIF : Power Fail Interface 5. PWRS : DC Power Supply
6. MRIF : MCU Reset Interface 7. BUIF : Buffer Interface 8. MCU : Microcontroller 9. BLCF : Balance Filed 10. PSIF : Prepaid Card Vcc Interface
11. FPCP : Four Pin Connector for Prepaid card 12. PRIF : Prepaid Card Reset Interface 13. MCIF : Mechanical Coupling Interface

55
34 Operating Procedures of RMCKIT

35 Design Analysis of RMCKIT

IBMPC P1 U1: MAX232 U2: 89S52 U3: ATmega8

MOSI(P15) MOSI (PB3) 22


MISO (P16) MISO (PB4)
TxRS RxRS RxTTL RxTTL SCK(P17) SCK (PB 5)
RxRS TxRS TxTTL TxTTL +5V
R5 R6 PB0
COM COM COM COM 4k7 1k5
RST/ Rx
SW1 RST R4 1k5
1MHz
RST/(P14) 1k5
P10 XT2 XT2
Q2 Q3
USB Å---- > RS232 C9 C828
Y2
LEDR1 C828
Converter +5V 0V 100 uF LEDR2
1503

56
LEDR1 U2 LDG LEDR2 U3 C3

P10
P4 C 10
D1
1
D2
2
3 C 11
M a s te r 1 28

Q1
C 12
MCU 2 27
U4
3 26
7805

R2
R1
4 25
P1 5 24
C5
6 23

50Hz
P5

C6 7 22
T a rg e t
8 21
C7 (S la v e M C U )
9 20
C4 19
U1

MAX232

Y2
A Tm ega8L 18
SW 1
17
16
14 PB0 15
R3 Y1 R4
C9 R5 R6 Q3
Q2
C8
1503ab

36 Problems and Solutions

37 Index

38 References

39 Program Listings
Section Subsystem Program Purpose Setup
14 Digital IO ..\ATmega8\porta2.asm Show 123456 on CC7SDD Fig-14.1
..\ATmega8\ex81.asm Continuously blink LEDR2 at PB0-pin

EEPROM ..\ATmega8\atmega82.asm Blink LEDR2 at PB0 for n times; where


n = read n1, n2 from EEPROM and add

57
40 Author Profile

Profile of the Author

Golam Mostafa

Mr. Golam Mostafa obtained B.Sc. Engg (EE) and M.Sc. Engg (CSE) degrees from BUET. He has
28 years of working experience that includes 17 years in home and abroad with renowned
companies like BCIC, GEC and Schlumberger and 11 years in teaching at university level. He has
offered varieties of courses of EEE/CSE engineering at the undergraduate and graduate levels
but the most interesting subject to him is the ‘Microprocessor and Microcontroller Based
Systems’, which he has taught for as many as 83 semesters.

He is presently serving as Associate Professor in the Dept. of EEE of Ahsanullah University of


Science and Technology. Mr. Mostafa has designed, developed, built and distributed MPU/MCU
Learning/Development Systems to various educational institutes of Bangladesh and these are
MicroTalk-8085, MicroTalk-8086, MicroTalk-80286. MicroTalk-80386, MicroTalk-8051 and
AMCKIT.

Mr. Mostafa has also designed, developed and filed tested MCU-based 100% tamper-proof
Digital Taximeter, which is now ready for marketing. He has also finished the design,
development and prototyping of an 89S8252-7755-2313 CISC/RISC microcontroller based
Prepaid Energy Meter. He can be reached at:
Phone: 7161846, M-01726341559
Email: mostafagb@yahoo.com

58
2.2 Default-mode Operational Diagram of ATmega8L
‘Default-mode’ of operation of the ATmega8L refers to its operation under factory settings. The
ATmega8L chip is shipped from the factory with the following settings. The settings can be
changed by a procedure known Fuse Programming (Section – 8.4).
a. Pin-1 will work as RST/-pin to receive external reset signal.
b. Pins: 2, 3, 4, 5, 6, 11, 12, 13 will work as IO lines of Port-D register.
c. Pins: 14, 15, 16, 17, 18, 19, 9, 10 will work as IO lines for Port-B register.
d. Pins: 23, 24, 25, 26, 27, 28 will work as IO lines for Port-C.
e. Pin-7 will work to receive external +5V supply for the digital electronics of the chip.
f. Pin-20 will work to receive external +5V supply for the ADC electronics of the chip.
g. Pin-21 will work to receive external reference supply for the ADC electronics of the
chip.
h. Pins: 8, 22 will connect the chip with the ground (0V) points of the external DC power
supplies.
i. The chip will receive its operating frequency from an internal 1MHz RC oscillator.
j. The chip will start program execution starting at location 000h, which is being pointed
by a 12-bit Program Counter.
k. Under default-mode of operation. The physical pin diagram of the ATmega8 appears
as in Fig – 8.5.
ATmega8L 280cd

1 RST/ PC5 28
2 PD0 PC4 27
3 PD1 PC3 26
4 PD2 PC2 25
5 PD3 PC1 24
6 PD4 PC0 23
7 Vcc GND 22
8 GND AREF 21
9 PB6 AVcc 20
10 PB7 PB5 19
11 PD5 PB4 18
12 PD6 PB3 17
13 PD7 PB2 16
14 PB0 PB1 15

Figure – 8.5 Physical Pin Diagram of ATmega8 at Default- mode of Operation

59
60