Golam Mostafa: Atmega8 Risc Microcontroller Interfacing and System Design
Golam Mostafa: Atmega8 Risc Microcontroller Interfacing and System Design
RISC Microcontroller
Interfacing and System Design
Using RMCKIT: ATmega8 RISC Microcontroller Learning Kit
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
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.
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.
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
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
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:
- - - - 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
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
Application Application
Section Section
$001 $001
$000 $000
(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
(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
CHKAGN:
sbis EECR, EEWE
rjmp NEXTLOC
rjmp CHKAGN
NEXTLOC:
ldi r20, 0x00
out EEARH, r20
ldi r20, 0x01
out EEARL, r20 ; location 0001
nop
ldi r20, 0x06
out EECR, r20
16
CHKAGN1:
sbis EECR, EEWE
rjmp NEXT
rjmp CHKAGN1 ; keep polling the EEWE0but for LL
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
SLAVEBUSY:
sbi portb, pb0
rcall DELAY
cbi portb, pb0
rcall DELAY
dec r20
brne SLAVEBUSY
.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
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.
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.
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:
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.
B7 B1 B0
PORF MCUCSR
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
Vcc
B
A 4V + 65mV
4V – 65mV`
Qa
Qb
Qc Time-out
Internal Reset
t0 t1 t2 t3
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!
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.
FF1
Trig
Delay Counter Qc
WDT
Qc Time-out
Internal Reset
t0 t1 t2
watchdog
23
13 Interrupt Vectors
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
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
Pxn Q D
G2
CK WP
PORTxn
RP
G4
Sleep
G6 RPinx
Synchronizer
Q
D G5
clkIO
FF3
0V
51
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.
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.
+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.
52 : GM: 03-10
27
DP0 DP1 DPE DPF
CC7SDD
Unit
Multiplexed ccF
cc0 cc 1 ccE
CC- code
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
29
out DDRC, r16
sbi DDRD, DDD7 ; PC7, PC6 are outputs
sbi DDRD, DDD6
L7: rjmp L6
;------------------------------------------
HEX2CC:
clr r27
clr r29
clr r31
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
;-----------------------------------------------------
16 Internal Interrupts
PD0 IO
SW1
1
Sw2
7 0
Counter-0
XCK
SW3
32
17.1 Counter-0 Programming and Operation of ATmega8
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.
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.
34
Clear TOV1 by sending at TOV1-bit of TIFR
Flash LEDR2
L6: goto L4
0xFF06 (Preset )
t
0
TOV1
t
0 5 sec
PB0
t
0 5 sec
1634
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
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
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
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
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
.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
in r16, tccr2
ori r16, 0x01 ; clk/1
out tccr2, r16
41
in r17, TIFR
ori r17, 0x40 ; LH --> TOV2
out TIFR, r17
L8: ; repeat
rjmp L6
.exit
19.4 Dual Slope High Resolution Phase Correct PWM using TC2
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
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
L3: Y
N
TWSR = 08
?
Bus at
Bus Error Y START
L5:
SLA+W - Æ TWDR
Clear TWINT to begin Tx
57
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]:
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.
.org $020
L1: ; stack init STKINIT:
;------------------------------------
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
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.
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.
;----------------------------------------
.org $020
L11: ; stack init STKINIT:
L21: ; CCTAB: ; cc-code table initialization 0060h - 006Fh
---------------------------------------
L31: ; PortD and PortB as outputs
;------------------------------------
48
LXC: rjmp LXB
rjmp L0
;-----------------------------------------------------
.exit
.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, 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
.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.
51
23 Analog Comparator Unit
24 Watch-dog Timer
Covered in Section-19: System Control and Reset
25 Analog-to-Digital Converter
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.
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
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
32 Interfacing Experiment
54
32 System Design
1605a: GM : 30-11-09
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
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
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
57
40 Author Profile
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.
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: [email protected]
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
59
60