ATmega8 Text

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

Transcript of ATmega8 Text

ATmega8 RISC Microcontroller Interfacing and System DesignUsing RMCKIT: ATmega8 RISC Microcontroller Learning KitDesigned, Developed and Built in Bangladesh by the Author

Golam Mostafa

2

Preface

3

1

1.1

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

Figure - 8.1: Physical Pin Diagram for ATmega8 RISC Microcontroller

4

1.2 Pin Functions of the ATmega8 RISC MicrocontrollerIn 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 PC6 Signal Names Port Pin Direction Input and Output Function Simple IO line and is determined by configuring Fuse Bit. To exchange data with external devices. The pin can be operated either as input or output. 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. To exchange data with external devices. Each pin can be independently operated either as input or output. To receive asynchronous serial data from external devices. To transmit asynchronous serial data to external devices. To receive interrupt request signals from the external hardware devices.

RST/

External Reset Pin

Input

PD7 PD0

Port Pins

Input and Output Input Output Input

RxD TxD INT0/, INT1/

Receive Asyc Serial Data

Interrupts

XCK T0 AIN0 AIN1 XTAL2, XTAL1 GND P20 P27

Clock Output Timer-0 Data Write Signal Data Read Signal Crystal In-1 Crystal In-2 Control Data Ports

Output Input Output Output Input Input Input Input and Output Output Output Input and Output Input Timer-0 input pTo receive external pulse events for counting purposes. To asserts write and read commands to the external data memory and ports To connect a frequency determining crystal for the internal oscillator of the MCU. To sink current of the MCU. To exchange data with external devices. Each pin can be independently operated either as input or output. To assert upper 8-bit address lines while accessing external code memory, data memory and ports. Equivalent to read signal while reading program codes form external code memory. To exchange data with external devices. Each pin can be independently operated either as input or output. Supplies Dc Power to the MCU.

A8 A15 PSEN/ P00 P07

Address Lines Program Sense Port Pins

Vcc

DC Supply

5

2 3

Internal Architecture of ATmega8 Block Diagram for the Internal Resources

6

4 ATmega8 IO Register Summary (Registers Marked with * sign Bit Addressable using CBI and SBI Instructions)Name Full Short IO (RAM) Address SREG 3Fh, (5Fh) SPH 3Eh (5Eh) SPL 3Dh (5Dh) Reserved GICR 3Bh (5Bh) GIFR 3Ah (5Ah) TIMSK 39h (59h) TIFR 38h (58h) SPMCR 37h (57h) TWCR 36h (56h) MCUCR 35h (55h) MCUCSR 34h (54h) TCCR0 33h (53h) TCNT0 32h (52h) OSCCAL 31h (51h) SFIOR 30h (50h) TCCR1A TCCR1B TCNT1H TCNT1L OCR1AH OCR1AL OCR1BH OCR1BL ICR1H ICR1L TCCR2 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0

Status Register Stack Pointer Register High Stack Pointer Register Low General Interrupt Control Register General Interrupt Flag Register Timer/Counter Interrupt Mask Register Timer Interrupt Flag Register Store Program Memory Control Register Two Wire Interface Control Register MCU Control Register MCU Control and Status Register Timer/Counter-0 Control Register Timer/Counter-0 Data Register Oscillator Calibration Register Special Function IO Register Timer/Counter-1A Control Register Timer/Counter-1B Control Register Timer/Counter-1 Data Register High Timer/Counter-1 Data Register Low Output Compare Register 1A High Output Compare Register 1A Low Output Compare Register 1B High Output Compare Register 1B Low Input Capture Register 1 High Input Capture Register 1 Low Timer/Counter-2 Control Register

I SP7

T SP6

H SP5

S SP4

V SP3

N SP10 SP2

Z SP9 SP1

C SP8 SP0

INT1 INTF1 OCIE2 OCF2 SPMIE TWINT SE -

INT0 INTF0 TOIE2 TOV2 RWWS B TWEA SM2 -

TICIE1 ICF1 TWSTA SM1 -

OCIE1A OCF1A RWWSR E TWST0 SM0 -

OCIE1B OCF1B BLBSET TWWC ISC11 WDRF -

TOIE1 TOV1 PGWR T TWEN ISC10 BORF CS02

IVSEL OGERS ISC01 EXTRF CS01

IVCE TOIE0 TOV0 SPOM EN TWIE ISC00 PORF CS00

Timer / Counter 0 Register (8-bit) Oscillator Calibration Register ACME PUD PSR2 PSR10

7

TWI Status Register* TWI Bit Rate Register*

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 TWSR TWBR

TWS7 TWBR7

TWS6 TWBR6

TWS5 TWBR5

TWS4 TWBR4

TWS3 TWBR3

TWS2 TWBR2

TWS1T TWBR1

TWS0 TWBR0

8

5

Register Detailed FunctionsStatus 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 I T H S V N Z C T H S V N Z C 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

Timer/Counter Interrupt Mask Register: TIMSKOCIE2 OCIE2 T H S V TOIE1 Timer/Counter-1 Overflow Interrupt Enable: When the TOIE1 bit is set to LH along with LH at I-bit 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 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 TOIE0

TOIE0 Timer/Counter-0 Overflow Interrupt Enable: When the TOIE0 bit is set to LH along with LH at I-bit 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 0 TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE 0 0 0 0 0 0 0 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: MCUCSRWDRF BORF B1 EXTRF B0 PORF

WDRF H S V TOIE1

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

Timer/Counter-1 Overflow Interrupt Enable: When the TOIE1 bit is set to LH along with LH at I-bit 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

TOIE0 Timer/Counter-0 Overflow Interrupt Enable: When the TOIE0 bit is set to LH along with LH at I-bit 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 FileSymbolic Name R31 R30 R29 R28 R27 R26 R25 R24 R23 R22 R21 R20 R19 R18 R17 R16 R15 R14 R13 R12 R11 R10 R9 R8 R7 R6 R5 R4 R3 R2 R1 R0 Size 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit 8-bit Remarks15 R3115 R29 8 7 R28

RAM Address 0x1F 0x1E 0x1D 0x1C 0x1B 0x1A 0x19 0x18 0x17 0x16 0x15 0x14 0x13 0x12 0x11 0x10 0x0F 0x0E 0x0D 0x0C 0x0B 0x0A 0x09 0x08 0x07 0x06 0x05 0x04 0x03 0x02 0x01 0x00

8 7 R30

0

Z- Pointer Register0

Y-Pointer Register0

15 R27

8 7 R26

X- Pointer Register

These registers are not supported by LDI Rd, $XX instruction

For Example: LDI R15, $23 is not a valid instruction

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 R27 15 R29 15 R31 8 7 R30 8 7 R28 0 8 7 R26 0 0

X- Pointer Register Y-Pointer Register

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.Default Fuse Status BOOTRST 1 (default) 0 0 0 0 BOOTSZ1 0 (default) 0 0 1 1 BOOTSZ0 0 (default) 0 1 0 1 Application Section Table 8.1 Boot Section 0xC00 0xFFF 0xC00 0xFFF 0xE00 0xFFF 0xF00- 0xFFF 0xF80 0xFFF Startup Location 0x000 0xC00 0xE00 0xF00 0xF80 Remarks MCU starts at App Section MCU starts at Boot Section MCU starts at Boot Section MCU starts at Boot Section MCU starts at Boot Section

0x000 0xBFF 0x000 0xBFF 0x000 0xDFF 0x000 0xEFF 0x000 0xF7F

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

15 $FFF

8

7

0 Boot Section

$C00 $BFF

Application Section

Startup Location 1509 a

$001 $000 BOOTRST, BOOTSZ1, BOOTSZ0 = 1, 0, 0

Figure 8.2: Default Code Memory Organization with Unprogrammed Fuse Bit, BOOTRST

12

15 $FFF

8

7

0 $FFF Boot Section

15

8

7

0 Boot Section

Startup Location

$C00 $BFF

Startup Location

$E00 $DFF

Application Section

Application Section

$001 $000 1509 a BOOTRST, BOOTSZ1, BOOTSZ0 = 0, 0, 0 1509 a

$001 $000 BOOTRST, BOOTSZ1, BOOTSZ0 = 0, 0, 1

(a)

(b)

15 $FFF

8

7

0 $FFF Boot Section

15

8

7

0 Boot Section

Startup Location

$F00 $EFF

Startup Location

$F78 $F7F

Application Section

Application Section

$001 $000 1509 a BOOTRST, BOOTSZ1, BOOTSZ0 = 0, 1, 0 1509 a

$001 $000 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 RAMRegister File R0 R1 R2 R3 R4 R5 R6 R7 .. R29 R30 R31 IO Registers TWBR ($0000) TWSR ($0001) . SPL ($003D) SPH ($003E) SREG ($003F) RAM Address Space $0000 $0001 $0002 $0003 $0004 $0005 $0006 $0007 . $001D $001E $001F $0020 $0021 . $005D $005E $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. 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. 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

B:

C:

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

$0001 $000055

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. 2. The EEPROM location is automatically self-erased. 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 out ldi out PRTBINIT: ldi out ldi out r16, spl, r16, sph, 0x5F r16 0x04 r16 ; stack initialize

r16, 0xFF ddrb, r16 r20, 0x00 EECR, r20

; 1111 1111 ; all portB pins are output ; EEMWE = 0, EEWE=0

; writing 05 and 02 at 0000h and 0001h ldi r20, 0x00 ; EEPROM address 0000h out EEARH, r20 out EEARL, r20 ldi out ldi out nop ldi out CHKAGN: sbis r20, 0x05 EEDR, r20 r20, 0x04 EECR, r20 r20, 0x06 EECR, r20 EECR, EEWE ; data 05h

rjmp NEXTLOC rjmp CHKAGN NEXTLOC: ldi out ldi out ldi out ldi out nop ldi out r20, 0x00 EEARH, r20 r20, 0x01 EEARL, r20 r20, 0x08 EEDR, r20 r20, 0x04 EECR, r20 r20, 0x06 EECR, r20

; location 0001 ; data 02h ; EEMWE = 1, EEWE=0

16

CHKAGN1: sbis EECR, EEWE rjmp NEXT rjmp CHKAGN1 NEXT: ldi out out ldi out nop in ldi LH out ldi out ldi out nop ldi out in add ldi out SLAVEBUSY: sbi rcall cbi rcall dec brne GHT: rjmp DELAY: cagain: magain: fagain: ldi ldi ldi dec brne dec brne dec brne ret .exit GHT r17, 8 r18, 125 r19, 125 r19 fagain r18 magain r17 cagain r21, 0x01 EECR, r21 EECR, r21 r21, 0x00 EEARH, r21 r21, 0x01 EEARL, r21 r20, 0x00 EEARH, r20 EEARL, r20 r20, 0x01 EECR, r20

; keep polling the EEWE0but for LL ; reading the contents if EEPROM locations

; read enable

r20, EEDR r21, 0x00

; read from location 0000h ; after read 0 must be put at EEWE-bit before make it

; next location

r21, EEDR r20, r21 r21, 0x00 EECR, r21 portb, pb0 DELAY portb, pb0 DELAY r20 SLAVEBUSY

; read from locatio 0001h

; r2 = 07 ; read disable

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 Distribution1MHz 2MHz RC Oscillator -1 +- 3% 4MHz 8MHz K3A K3D CLK Control Unit clkFLASH clkADC clk clkCPU CPU Core RAM Flash and Data EEPROM ADC General IO TC0, TC1, SPI, USART, IO Ports, External Interrupts

clkIO

Y 1 = 1 1.0 592MHz

K1A K1B

9 10

K4 Crystal/ Ceramic Resonator Oscillator -2 for Y1 Y1

K5 TC2 TWI

Asynchronous Oscillator -3 For Crystal Y 2

clkASY = Y2 K6

Y2 = 32.768KHzK2A K2B

48 : 02 = 20101 : GM

Oscillator-1 is a free running RC square wave generator and doesnt 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 VK1 R1 4k71

B7 MCUCSR

B1 EXTRF

B0

RST/ (PC6)

Spike Filter

Reset Circuit AReset Circuit B

SQaQb

QInternal Reset

C1 100uFR2 100R

RFF1

Trig

0V

1MHzCKSEL 3..0 = 001SUT1..0 = 10

Delay Counter

Qc

Vcc RST/ 0.2-0.9 Qa

Qb

Qc

Time-out

QInternal Reset t2

t0 t1

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 CircuitB 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 Reset Circuit

Qa

S R

Q Internal Reset

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

1.4V Vcc Qa

Qc Q

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 Resetbrown

B7 MCUCSR

B1

B0

BO DF

+5V

7

VccBODEN BODLEVBrown O ut Detector Circuit

Reset Circuit AReset Circuit B

SQaQb

QInternal Reset

RFF 1

Trig1MHzCKSEL 0 = 001 3..SUT1 ..0 = 10

Delay Counter

Qc

Vcc4V 65mV` A

B

4V + 65mV

Qa

Qb

Qc

Time-out

QInternal Reset t2

t0 t1

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 Brownout 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 PointB, 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 dont 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 MCUCSR B3 WDRF B1 B0

WDP2..1 Enable ResetWDT Watchdog Oscillator 1 MHz Pre Scaler R FF1 S Q Internal Reset

Trig Delay Counter Qc

WDT

Qc Q

Time-out

Internal Reset t0 t1 t2 watchdog

23

13

Interrupt Vectors

14 Digital Input and Output PortsIntroduction: 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 Fig14.2. The same pin can be configured to count external events for the internal Timer-1 (T1) [Fig1.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.ATmega8L13 12 11 65 4 3 2 50

PD7 PD6 PD5 PD4 PD3 PD2 PD1 PD0

PC6 PC5 PC4 PC3 PC2 PC1 PC0 PB7 PB6 PB5 PB4 PB3 PB2 PB1 PB0

128 27

26 25 24 2310 9 19 18 17 16 15 14

21 20 7 22 8

AREF AVcc Vcc GND GND

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 PUD T1 FF1 Q D CK G1 DDxn RD Rp G3 FF2 Pxn G2 Q D CK PORTxn RP G4 Sleep G6 Synchronizer Q D clkIO FF3 0V 51 G5 RPinx WP WD

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

Internal Data Bus (IDB)

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:Sn1

Instructions Pseudo CodeLH DDB0 FFh DDRB FFh PORTB r16 PORTB r16 PINB

Operations Assembly Codesbi DDRB, DDB0 ldi r16, 0xFF out DDRB, r16 ldi r16, 0xFF out PORTB, r16 in r16, PORTB in r16, PINB PB0 is made output PB7 PB0 are made output LH are written to all port pins pf Port-B register Data comes from FF2 and not from Port pins. Data comes from actual port pins.

RemarkOther ports are unaffected Other ports are unaffected Other ports are unaffected Say LH is written at PBO and it 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. Other ports are unaffected Other ports are unaffected nop instruction is inserted to cause delay. This delay will synchronize the externally applied pin value incase it changes near the edge of the internal clock.

r16 DDRB 2 LL DDB0 00h DDRB r16 PINB

in cbi ldi out nop in

r16, DDRB DDRB, DDB0 r16, 0x00 DDRB, r16 r16, PINB

Port direction bits of Port-B register are read. PB0 is made input PB7 PB0 are made input Data comes from Port pins and not from FF2.

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 RST R1 4k7 PBR PB7 PB6 PB5 PB4 PB3 PB2 PB1 PB0 10 9 19 18 17 16 15 14

1

RST/

LEDR2

C1 100 uF 8, 22 7 20 GND Vcc AVcc

0V

+5V

NC

2-6, 11,21,27,28 1MHz

PC0 PC1 PC2 PC3 PD6 PD7

23 24 25 26 12 13

53 : GM: 03-10

Example 14.1 [\ATmega8\porta2.asm] Build the following display circuit on the breadboard of the jumper RMCKIT using 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+5V RST R1 4k7PBRPB7 10 PB6 9 PB5 19 PB4 18 PB3 17 PB2 16 15 PB1 PB0 14 5 10 9 1 2 4 6 7p g f e d c b a

DPA

DPB

DPC

DPD

DPE

DPF

1

RST/

C1 100uF 8, 22 7 20GND Vcc AVcc

ccA 3

ccB 3

ccC 3

ccD 3

ccE 3

ccF 3

+5V

NC

2-6, 11,21,27,281MHz

23 PC0 24 PC1 25 PC2 26 PC3 12 PD6 13 PD7

52 : GM: 03-10

Figure 14.3: Multiplexed Display Circuit using Digital Ports

27

DP0

DP1

DPE

DPF

Multiplexed CC- code

CC7SDD Unitcc0 cc 1 ccE ccF

S0/ PB

S 1/DP0DP0-DPFDP1

CCX7SDDDP0-DPF

SE /DPE

SF/

DPF

DP0-DPF

DP0Internal RAM

DP1

DPE

DPF

78 H

79H

86H

87H

CC-Code Table (CCCT)Internal RAM CC-Code

LUT

HEX2CC

Digit Vs CCcode

60

CC-0

6F

CC-F

InputInternal RAM52

DP0DP1

DP2DP3

DP4DP5

DP6 DP7

DP8 DP9

DPADPB

DPCDPD

DPEDPF

Hex Table (HEXT)

70 H

71H

72 H

73H

74H

75H

76 H

77H

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 ; stack init STKINIT: ldi r16, 0x5F out SPL, r16 ldi r16, 0x04 out SPH, r16

L1:

; stack initialize

L2: ; CCTAB: ; cc-code table initialization 0060h - 006Fh ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts ldi sts r16, 0x3F 0x60, r16 r16, 0x06 0x61, r16 r16, 0x5B 0x62, r16 r16, 0x4F 0x63, r16 r16, 0x66 0x64, r16 r16, 0x6D 0x65, r16 r16, 0x7D 0x66, r16 r16, 0x07 0x67, r16 r16, 0x7F 0x68, r16 r16, 0x6F 0x69, r16 r16, 0x77 0x6A, r16 r16, 0x7C 0x6B, r16 r16, 0x39 0x6C, r16 r16, 0x5E 0x6D, r16 r16, 0x79 0x6E, r16 r16, 0x71 0x6F, r16 ; cc0code of 0 ; cc0code of 1 ; cc0code of 2 ; cc0code of 3 ; cc0code of 4 ; cc0code of 5 ; cc0code of 6 ; cc0code of 7 ; cc0code of 8 ; cc0code of 9 ; cc0code of A ; cc0code of b ; cc0code of C ; cc0code of d ; CC-code of E ; cc0code of F

L3: ; PortD and PortB as outputs ldi out r16, 0xFF DDRB, r16 ; 1111 1111 ; all portB/C pins are output

29

out sbi sbi L4: ldi sts ldi sts ldi sts L5: rcall L6: rcall L7: rjmp L6

DDRC, r16 DDRD, DDD7 DDRD, DDD6 r16, $12 $75, r16 r16, $34 $76, r16 r16, $56 $77, r16 HEX2CC CCXPB

; PC7, PC6 are outputs

; 123456

;-----------------------------------------HEX2CC: clr r27 clr r29 clr r31 ldi ldi r26, $75 ; X = 0075h r30, $82 ; Z = 0082h STAB CCTAB

AGN: ld

ldi r16, $03 ; 3 byte Hex to convert ;-------------------------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 st Z+, r17 ;-----------------mov andi ldi add r17, r17, r19, r17,

; getting CC-code from LUTAB ; outting into CCTAB

r18 0x0F ; r17 = 01 0x60 r19 ; r17 = 61

mov r28, r17 ;-----------------ld r17, Y st Z+, r17 ;-----------------dec breq rjmp DONE: ret r16 DONE AGN

; getting CC-code from LUTAB

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

30

ld out ldi out sbi sbi rcall ld out ldi out sbi sbi rcall ld out ldi out sbi sbi rcall ld out ldi out sbi sbi rcall ld out ldi out cbi sbi rcall ld out ldi out sbi cbi rcall

r17, Z+ PORTB, r17 r18, $FE PORTC, r18 PORTD, PD6 PORTD, PD7 DELAY r17, Z+ PORTB, r17 r18, $FD PORTC, r18 PORTD, PD6 PORTD, PD7 DELAY r17, Z+ PORTB, r17 r18, $FB PORTC, r18 PORTD, PD6 PORTD, PD7 DELAY r17, Z+ PORTB, r17 r18, $F7 PORTC, r18 PORTD, PD6 PORTD, PD7 DELAY r17, Z+ PORTB, r17 r18, $FF PORTC, r18 PORTD, PD6 PORTD, PD7 DELAY r17, Z+ PORTB, r17 r18, $DF PORTC, r18 PORTD, PD6 PORTD, PD7 DELAY

; DP0 ; 1111 1110 ; PC0 = LL ; LH ---> PD6 ; LH ---> PD7 ; DP1 ; 1111 1101 ; LH ---> PD6 ; LH ---> PD7 ; DP2 ; 1111 1011 ; LH ---> PD6 ; LH ---> PD7 ; DP3 ; 1111 0111 ; LH ---> PD6 ; LH ---> PD7 ; DP4 ; 1110 1111 ; LL ---> PD6 ; LH ---> PD7 ; DP5 ; 1101 1111 ; LH ---> PD6 ; LL ---> PD7

ret ;----------------------------------------------------DELAY: ldi r17, 20 cag: ldi r18, 20 mag: dec r18 brne mag dec r17 brne cag ret DELAY1: cagain: magain: fagain: ldi ldi ldi dec brne dec brne dec brne ret r17, 8 r18, 100 r19, 100 r19 fagain r18 magain r17 cagain

.exit ;

31

15 External Interrupts

16

Internal Interrupts

17 Timer/Counter-0 (TC0) Programming and Operation17.1 IntroductionAs 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. 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. 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 SW1 1 Sw2 7 Counter-0 0 IO

ii. iii.

SW3

XCK

32

17.1 Counter-0 Programming and Operation of ATmega8

18 Timer/Counter-1 (TC1) Programming and Operation18.1 IntroductionThe 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 TCNT1Lldi ldi out out r16, 0x34 r17, 0x45 TCNT1H, r17 TCNT1L, r16 ; 34h is to be kept into TCNT1L ; 45h is to be kept into TCNT1H ; now 45h is written into a temporary ; register and not into TCNT1H ; only now, 45h enters into TCNT1H ; and 34h enters into TCNT1L.

; Reading the 16-but contents if TC1in in register

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

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 TC1In 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 TIMSKregister 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 TCCR1register. The internal structure of the TC1 as Timer/Counter-1 is depicted below in Fig 7.1.1411a3 : GM : 2-10 K3A K3D 1MHz +/- 3% Internal RC Oscillator -1 2MHz +/- 3% 4MHz +/- 3% 8MHz +/- 3% Prescaler CLK CLK/1 CLK/8 CLK/32 CLK/64 CLK/128 K4 K1A Internal Crystal Oscillator -2 K1B 11 T1 (PD5) K2 11.0592 MHz CLK/256 CLK/1024 0 clksys K7A K7H clkIO

9Y1 11.0592MHz

XT 1

10

XT 2

0V

14 PB0 LEDR2

15 TCNT1

0 TOV1

I K5

TOIE1 IRQ : 008 h 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: L3: L4: L5: Configure PBO as output, PD6 as input Start TC1 by closing only K2 (K3, K4 and K7 must remain opened) with the help of TCCR1-register. if (TOV1 ! = LH) ; rollover has not occurred Goto L4 Reload preload value for TCNT1 (FF06h)

34

Clear TOV1 by sending at TOV1-bit of TIFR Flash LEDR2

L6: goto L4The Timing Diagram:TCNT1 Value Max : 0xFFFF

0xFF06 (Preset )

0 TOV1 0 PB0 1634 0 5 sec 5 sec

t

t

t

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 Operation19.1 IntroductionThe 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. b. c. d. e. Generating known Time Ticks by selecting suitable clocking frequency (Normal Mode). Generating Square Wave Signals (SQW) of fixed frequency. (CTC Mode) Generating SQW of continuously varying frequency (CTC Mode). Generating High Frequency (fast) Pulse Width Modulated Signal (Fast PWM). Generating High Resolution Pulse Width Modulated Signal (Phase Correct PWM)

The following registers are associated with the programming and operation of TC2:Name SREG TIMSK TIFR TCCR2 TCNT2 OCR2 ASSR SFIOR DDRB Status Register Timer/Counter Interrupt Mask Register Timer/Counter Interrupt Flag Register Timer/Counter-2 Control Register Timer/Counter-2 Data Register TC2 Output Compare Register Asynchronous Status Register Special Function IO Register Data Direction Register for PORTB Pins1411 a2 : GM : 2-10K3A K3D1MHz +/- 3%Internal RC Oscillator -1

Function Affects the global interrupt enable bit (I-bit) Affects TOIE2 and OCIE2 bits Records the logic values of TOV2 and OCF2 Selects Mode of Operation and prescaler frequency Actual TC2 Data Register Decides at what counts the TCNT2 should reset Selects asynchronous mode clock for TC2 Controls Prescaler and Pullup resistors for ports To set directions of the PB3-pin as outputclksys

K8A K8H CLK CLK/1 CLK/8 CLK/32 Prescaler CLK/64 CLK/128

clkIO

2MHz +/- 3% 4MHz +/- 3% 8MHz +/- 3%

K7

9

XT1

Y1 11.0592MHz

K4

K1ACrystal Oscillator -210 XT2

11. 0592MHz

CLK/256 CLK/1024 0

Y2 32.768KHz

K27

Crystal Oscillator -3

Clkasy (32.768KHz)0

K6ITOIE2 IRQ : 004h

CRETOV2

TCNT2

K9

K10IOCIE2 IRQ : 003h

CME=7 OCR2 0

OCF2

K11Waveform Generator

K12WGM21:0, COM21:0

(PB3-MOSI) OC2

17

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 GeneratorTo 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 (Pin17). 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) 0 OC2-pin Logic

0 1411 a2

t1

t2

t3

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 L3: Load OCR2 count for 100Hz L4: Set PB3 as output L5: Start TC2 by selecting clkIO L6: end

via TCCR2-register get counts from equation fOC2 via DDRB register via TCCR2 register

38

19.3 Timer/Counter2 (TC2) Operation as Fast (High Frequency) Pulse Width Modulator49 : GM : 02-10 TCNT2 Value MAX : FFh OCR2-2 OCR2-1 t

0 TOV2 (CRE) 0 OFC2-1 (CME) 0 OC2-1 pin Logic ONP 0 OC2-2 pin Logic t1 ONP t2

t

t

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 ldi n1 add out r16, r17 OCR2, r16 ; new update value is preserved. r16, n1 r17, n2 ; n1 is an initial value ; n2 is an incremental value and to be added with

;-------------------------------------------------------------------------------------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 ldi n1 add out r16, r17 OCR2, r16 r16, OCR2 r17, n2 ; reading n1 from actual (buffer) of OCR2 ; n2 is an incremental value and to be added with

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 5sec.

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 L3: Set PB3 as output L4: Load OCR2 count for initial PW L5: Start TC2 by selecting clkIO L6: Count TOV2 events to account for 5-sec elapse If (5-sec not elapsed) Goto L6 Reset r21:r20 L7: add 5S with initial PW and sent to OCR2 Flash LED2 Goto L6 The Assembly Codes: ; Single Slope Fast PWM of TC2 .include "m8def.inc" .cseg RESET: .org rjmp $000 L1 f= 3906.25Hz

via TCCR2-register via DDRB register 0x05 via TCCR2 register

5-sec counter

.org $020 L1: ; stack initialization ldi r16, 0x5F out spl, r16 ldi r16, 0x04 out sph, r16 ldi r21, 0x00 ldi r20, 0x00 ldi r22, 0x05 L2: ; Fast PWM Mode Set ldi r16, 0x68 out tccr2, r16 L3: ; PB3 as output ldi r16, 0xFF out ddrb, r16

; stack initialize

; to count 5 sec = 4C4Bh from TOV2 ; initial OW of 5 uS ; Fast PWM

; 1111 1111 ; all portB pins are output ; PW = 20uS

L4: ; Set if Initial PW via OCR2 ;ldi r16, 0x05 out ocr2, r22

L5: ; Start TC2 by selecting clkIO = 1000 000 Hz in ori out r16, tccr2 r16, 0x01 tccr2, r16 ; clk/1

L6: ; check if 5 sec has elapsed in r17, TIFR rol r17 rol r17 brcc L6

; TOV2 is not set

41

in ori out ldi add ldi adc ldi cp brne ldi cp brne ldi ldi

r17, TIFR r17, 0x40 TIFR, r17 r16, r20, r16, r21, 0x01 r16 0x00 r16

; LH --> TOV2 ; coint TOV2 r21:r20

r16, 0x4B r20, r16 L6 r16, 0x4C r21, r16 L6 r21, 0x00 r20, 0x00

; 4C4Bh for 5 sec

L7: ; ipdate OCR2 by 0x05 uS ldi r16, 0x05 add r22, r16 out OCR2, r22 sbi rcall cbi rcall L8: ; repeat rjmp DELAY: cagain: magain: fagain: ldi ldi ldi dec PORTB, PB0 DELAY PORTB, PB0 DELAY L6 ; flash LEDR2 at PB0

r17, 8 r18, 25 r19, 25 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 Operation42

22 Two-wire Serial Interface Programming and OperationTWI Logic Unit of Master Address Match UnitAddress Register (TWAR)

TWI Bus TWI Logic of Slave -1VccInternal Pull-ups Slew Rate Control Spike Filter Slew Rate Control Spike Filter

Bus Interface UnitArbitration Detection Address/Data Shift Register ACK (TWDR) START/STOP Control

SDA SWA SCL

27

27

SDA

Address Comparator

Spike Suppression

28

28

SCL

Blank

Status Register *TWSR)

Prescaler

GRN1

State Machine and Status Conrol57 : GM : 3-2010

PB1 Control Register (TWCR) Bit Rate Register (TWBR) RED1 PB0

Control Unit

Bit Rate Generator

0V

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 the Master device generates START condition on the TWI bus. Transmission Termination (TXT) means that the Master devices generates STOP condition on the TWI bus. The TWI logic checks if the TWI bus is available, and then generates START condition if it is free.

L1:

START

Make LH at SDA SCL , Assert START

L2: NTWINT = LH ?

L3: N

Y

TWSR = 08 ?

Bus Error

Y

Bus at 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 Fig22.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+5V RST R1 4k7PBRPB7 PB6 PB5 PB4 PB3 PB2 PB1 PB0

DPA5 10 9 1 2 4 6 7p g f e d c b a ccA 3

DPB

DPC

DPD

DPE

DPF

1

RST/

C1 100 uF

10 9 19 18 17 16 15 14

ccB 3

ccC 3

0V+5V

ccD 3

ccE 3

ccF 3

8, 22 7 20

GND Vcc AVcc

1MHzPC0 PC1 PC2 PC3 PD6 PD7

+5VNC 2-6, 11,21,27,28TWI Logic

23 24 25 26 12 13

SDA 27 SCL 2852a : GM: 03-10

TWI Bus

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

45

2. 3. 4.

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

; Testing START condition of TWI Interface Protocols .include "m8def.inc" .cseg .org $000 L0: RESET: rjmp L1 ;STKINIT L1: L2: L3: .org $020 ; stack init STKINIT: ; CCTAB: ; cc-code table initialization 0060h - 006Fh ;--------------------------------------; 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 out TWCR, r16 ; polling TWINT bit for LH in r16, TWCR sbrs r16, 7 rjmp L2A ; redaing TWSR in r16, TWSR andi r16, 0b11111000 cpi r16, 0x08 brne ERROR ; TWSR is not 08h ;-------------------------------------------------ldi r17, $10 ; 1 die to LH at TWUNT bit sts $75, r17 ldi sts sts L5: L6: L7: L8: ERROR: rcall r17, $00 $76, r17 $77, r16 HEX2CC ; 08 ; converting HEX to CC-code TWSTA, LH TWEN

Program Codes Listing: \ATmega8\P221.asm

L2A:

L3A:

L4:

; blank DPB - DPD ; transfer CC-code to display rcall CCXPB rjmp L6 ; keep refreshing the display

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 (8bit, 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+5V RST R1 4k7PBRPB7 10 PB6 9 PB5 19 PB4 18 PB3 17 16 PB2 15 PB1 PB0 14 5 10 9 1 2 4 6 7p g f e d c b a

DPA

DPB

DPC

DPD

DPE

DPF

1

RST/

C1 100uF

ccA 3

ccB 3

ccC 3

0V+5V

ccD 3

ccE 3

ccF 3

8, 22 7 20

GND Vcc AVcc

1MHz

+5VNC 2-6, 11,21,27,28TWI Logic

23 PC 0 24 PC 1 25 PC 2 26 PC 3 12 PD 6 13 PD 7

SDA 27 SCL 28

0VTWI Bus

27 28 8

SDA SCL GND

ATmega8L Slave -1

U1XGRN1 0V

PB1 15

PB0 14

RST/ Vcc AVcc

1 7 20

R1=1k5

+5V

RED1

0V

52ab : GM: 03-10

Figure 22.5 :

2. 3. 4. 4. 5. 6.

Power up the RMCKIT. Observe that the RED1 of Slave-1 keeps blinking. Download and execute \ATmega8\Slave1adr.hex Connect the RST/-pin of the Master ATmega8 of the RMCKIT at 0V. Observe that the RED1 keeps blinking. Remove power from the RMCKIT. After a while apply power to RMCK. Observe that RED1 of Slave-1 is blinking. 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..include "m8def.inc" .cseg .org $000 rjmp L1

Master Program Code Listing (\ATmega8\Master1.asm)L0: RESET:

;STKINIT

L11: L21: L31:

;---------------------------------------.org $020 ; stack init STKINIT: ; CCTAB: ; cc-code table initialization 0060h - 006Fh --------------------------------------; 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: L2:

ldi out

r16, 0b11100100 TWCR, r16

; tp assert the START busevent.

;poll TWINT in r16, TWCR sbrs r16, 7 rjmp L2 in andi cpi brne

; at the end of expected busevent, TWINT assumes LH ; finish all tasks before initiating the next busevent.

L3:

r16, TWSR r16, 0b11111000 r16, 0x08 ERROR

; after START busevent, the TWSR must cintain 08h

L3A:

; send Slave-1 address ldi r16, 0x8C ; 10001110 out TWDR, r16

SLA+W = 1000111 0

L3B:

; initiate transmission by TWCR ldi r16, 0xC4 ; 1100 0100 clear TWINT Enable ACK out TWCR, r16 ; poll TWUNT in r16, TWCR sbrs r16, 7 rjmp L4 ; read TWSR for 18h in r16, TWSR andi r16, 0b11111000 cpi r16, 0x18 brne ERROR ; Slave-1 has not received its address ; display status code 18h at DPE and DPF positions sts $75, r17 ldi sts sts r17, $00 $76, r17 $77, r16 HEX2CC ;

L4:

L5:

LX:

LXA: LXB:

rcall

; 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 L1: .org $020 ; 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 ; assert START contion on TWI bus ldi r16, 0xC4 ; 1100 0100 ACK enabled, Clear TWINT out TWCR, r16 sbi rcall cbi rcall PORTB, PB0 DELAY1 PORTB, PB0 DELAY1

L3B:

BLINK1:

L4B:

; checking if any busevent has occurred in r16, TWCR sbrs r16, 7 rjmp BLINK1 ; no busevent has occurred in andi cpi brne ldi LH rcall LL rcall dec brne rjmp r16, TWSR r16, 0xF8 r16, 0x60 BLINK1 r20, 0x04 PB0 DELAY1 PB0 DELAY1 r20 AGNB L0 ; busevent has occurred ; TWSR will be 69h if Slvae-1 receives its own addr. ; busevent is not for Slave-1 address ; Slave-1 has recognized its address ; blink RED1 of Slave-1 for 4 times with long pause

AGNB:

;----------------------------------------------------.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 ; 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 L1: ldi out out sbi sbi ;sbi ;sbi r16, 0xFF DDRB, r16 DDRC, r16 DDRD, DDD7 DDRD, DDD6 PORTC, PC4 PORTC, PC5 ; 1111 1111 ; all portB/C pins are output ; PC7, PC6 are outputs ; pull-ups os enabled/disabled ; doesn't matter, it works

;-----------------------------------ldi r16, 0b10001100 ; slave address 8Ch out TWAR, r16 ; slave address is set AGN: ldi out r16, 0xC5 TWCR, r16 ; 1100 0100 ACK enabled, Claer TWINT

;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 ori out in andi cpi brne ldi sbi rcall rcall rcall rcall cbi rcall rcall rcall rcall dec brne BLINK5: reti .exit r17, TWCR r17, 0x80 TWCR, r17 r16, TWSR r16, 0xF8 r16, 0x60 BLINK5 r20, 0x04 PORTB, PB0 DELAY1 DELAY1 DELAY1 DELAY1 PORTB, PB0 DELAY1 DELAY1 DELAY1 DELAY1 r20 AGNB ; TWINT is LH die to SLA?

AGNB:

50

The TWI Bus Activities:START

SDA

MSBA1 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 24 25

Analog Comparator Unit Watch-dog TimerCovered in Section-19: System Control and Reset

Analog-to-Digital Converter

26 27 28

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

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

31.1 Terminology

Instructions of ATmega8

Status Register (SREG) Z Zero Flag C Carry Flag N Negative Flag V Twos 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.3ADC ADD ADIW AND

Brief Description of ATmega8 InstructionOperands Rd, Rr Rd, Rr Rd+1:Rd, K Rd, Rr Description Operation Arithmetic and Logic Instructions Add with Carry Rd Rd + Rr+C 0 d, r 31 Add without Carry Rd Rd + Rr 0 d, r 31 Add Immediate to Word Rd+1:Rd Rd+1:Rd+K d { 24, 26, 28, 30 }, 0 K 63 Logical AND Rd Rd Rr 0 d, r 31 Affected FlagITHSVNZC ITHSVNZC --- SVNZC ---S0NZ-

Mnemonics

Ck 1

31.4 Detailed Description of Instruction SetSyntax Meaning : : SBIC A, b 0 A 31, 0 b 7 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 Design1605 GM : 30-11-09 a:

EMIFLL (Volt ) i+ SHNT Isense i+

MCU : ATmega8L

BLCF (Balance Field)

PBR

DP0

DP1

DP2

DP3

DP4

DP5

220V 50Hz

C0 (Energy Pulse ) cef 0V16 per 0.01kwh

8p, g,..., b, a

Load-

K1NN

PCR4

PC0

PC1

PC2

PC3

PD6

PD7

RLIFP3.3 (Power OFF )+12

PDR

PFIFINT0 (PD2) (Power Fail )VccPD1 0V SCL SDA

PVIF

FPCP

PRPC (ATmega8L)Vcc1LEDR

PWRSVcc+5 +12 +VDM

0V SCL SDA

PB0R1 1k5

0V

PRIFVcc1CM 1FFFVcc

RST/DM

MRIFVcc

RST/

0000PD 0Security

MCIFMechanical Coupling

Buzzer

BUIF

CM 3FF

0V

PD 5 (Alarm ON )+V

K2

000Security

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

35IBMPC

Design Analysis of RMCKITP1 U1: MAX232U2: 89S52MOSI(P15) MISO (P16) RxTTL SCK(P17) TxTTL

U3: ATmega8MOSI (PB3) MISO (PB4) SCK (PB 5) +5V R5 4k7 R6 1k5 RST/PB0Rx 1MHz 1k5 XT2 XT222

TxRS RxRS COM

RxRS RxTTL TxRS TxTTL COMCOMSW1

COMRSTP10

R4 1k5

RST/(P14)LEDR1

USB1503

---- > RS232 Converter

Q2 C828 0V

+5V

Q3 C9 C828 100 uF

Y2LEDR2

56

LEDR1

U2

LDG

LEDR2

U3

C3

P10P4 D1 D2

C 10

P1

C6 C7

50Hz

C5

P5

R1

R2

U4 7805

Q1

1 2 3

C 11 C 12

M a s te r MCU

1 2 3 4 5 6 7 8 9

T a rg e t (S la v e M C U )

U1

MAX232

C4

SW 1

A Tm ega8L

14R3 C8 Y1

PB0Q2 R6

28 27 26 25 24 23 22 21 20 19 18 17 16 15

Y2R4 R5

C9

Q3

1503ab

36 37 38

Problems and Solutions Index References

39Section14

Program ListingsSubsystemDigital IO

Program..\ATmega8\porta2.asm ..\ATmega8\ex81.asm

PurposeShow 123456 on CC7SDD Continuously blink LEDR2 at PB0-pin

SetupFig-14.1

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 MostafaMr. 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: [email protected]

58

2.2 Default-mode Operational Diagram of ATmega8LDefault-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. b. c. d. e. f. g. Pin-1 will work as RST/-pin to receive external reset signal. Pins: 2, 3, 4, 5, 6, 11, 12, 13 will work as IO lines of Port-D register. Pins: 14, 15, 16, 17, 18, 19, 9, 10 will work as IO lines for Port-B register. Pins: 23, 24, 25, 26, 27, 28 will work as IO lines for Port-C. Pin-7 will work to receive external +5V supply for the digital electronics of the chip. Pin-20 will work to receive external +5V supply for the ADC electronics of the chip. 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.ATmega8L1 2 3 4 5 6 7 8 9 10 11 12 13 14 RST/ PD0 PD1 PD2 PD3 PD4 Vcc GND PB6 PB7 PD5 PD6 PD7 PB0 PC5 PC4 PC3 PC2 PC1 PC0 GND AREF AVcc PB5 PB4 PB3 PB2 PB1 28 27 26 25 24 23 22 21 20 19 18 17 16 15280cd

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

59

60