Embedded Systems

120
Embedded based industrial security system Chapter-1 Embedded Systems 1.1 Introduction An embedded system is a special-purpose system in which the computer is completely encapsulated by the device it controls. Unli general-purpose computer, such as a personal computer, an embedded system performs pre-dened tasks, usually with very specic requirements. ince the system is dedicated to a specic task, design engineers optimi!e it, reducing the si!e and cost of the product. Embedded systems are often mass-produced, so the cost savings may be multiplied by millions of items. "hysically, embedded systems range from portable devices such as digital watches and #"$ players, to large stationary installations like tra%c lights, factory controllers. &omple'ity varies from low, with a single microcontroller chip, to very high with multiple units, peripherals a networks mounted inside a large chassis or enclosure. Embedded systems contain processing cores that are either microcontrollers or digital signal processors () "*. +he key characteristic, however, is being dedicated to handle a particular task. in the embedded system is dedicated to specic tasks, design engineers can optimi!e it to reduce the si!e and cost of the product and increase the reliability and performance. ome embedded systems are mass-produced, beneting from economies of scale. obotics and automation are a part of embedded systems itself. obot development and automation needs study of embedded systems. aba anda ingh ahadur Engineering &ollege, /atehgarh ahib

description

Embedded Systems

Transcript of Embedded Systems

Embedded based industrial security system

Chapter-1

Embedded Systems1.1 IntroductionAn embedded system is a special-purpose system in which the computer is completely encapsulated by the device it controls. Unlike a general-purpose computer, such as a personal computer, an embedded system performs pre-defined tasks, usually with very specific requirements. Since the system is dedicated to a specific task, design engineers can optimize it, reducing the size and cost of the product. Embedded systems are often mass-produced, so the cost savings may be multiplied by millions of items.Physically, embedded systems range from portable devices such asdigital watchesandMP3 players, to large stationary installations like traffic lights,factory controllers. Complexity varies from low, with a singlemicrocontrollerchip, to very high with multiple units,peripherals and networks mounted inside a largechassisor enclosure.Embedded systems contain processing cores that are eithermicrocontrollersordigital signal processors(DSP).The key characteristic, however, is being dedicated to handle a particular task. Since the embedded system is dedicated to specific tasks, design engineers can optimize it to reduce the size and cost of the product and increase the reliability and performance. Some embedded systems are mass-produced, benefiting fromeconomies of scale.Robotics and automation are a part of embedded systems itself. Robot development and automation needs study of embedded systems. Examples of Embedded System areI. automatic teller machines (ATMs)II. avionics, such as inertial guidance systems, flight control hardware/software and other integrated systems in aircraft and missilesIII. cellular telephones and telephone switchesIV. computer equipment such as routers and printersV. engine controllers and antilock brake controllers for automobilesVI. home automation products, like thermostats, air conditioners, sprinklers, and security monitoring systemsVII. handheld calculatorsVIII. household appliances, including microwave ovens, washing machines, television setsIX. medical equipmentX. handheld computersXI. videogame consoles1.2 Characteristics of Embedded System1. Embedded systems are designed to do some specific task, rather than be a general-purpose computer for multiple tasks.

2. The program instructions written for embedded systems are referred to asfirmware, and are stored in read-only memory orFlash memorychips.

3. The embedded systems are special purpose computer systems designed to perform only the specific purposes. For Example- a system designed to display numbers cannot be used to operate motors.

4. Embedded systems range from no user interface at all dedicated only to one task to complexgraphical user interfacesthat resemble modern computer desktop operating systems.

CHAPTER-2

Microcontroller Families

2.1 8051These microcontrollers are old but still trendy and most of the companies fabricate these microcontrollers. TheIntel MCS-51 is aHarvard architecture,CISCinstruction set, single chipmicrocontroller(C) series which was developed byIntelin 1980 for use inembedded systems.2.2 PICProgrammable Interface Controller is usually referred as PIC. They are slightly older than 8051 microcontrollers but excel cause of their small low pin count devices. They perform well and are affordable. The Microchip technology fabricated the single chip microcontroller PIC with Harvard architecture.2.3 AVRAdvanced Version RISC.In 1996, Atmel fabricated this single chip microcontroller with a modified Harvard Architecture. This chip is loaded with C-compiler, Free IDE and many more features.This microcontroller is a bit difficult for the starters to handle.2.4 ARMTheARM architecturesarereduced instruction set computer(RISC)instruction set architectures(ISA), such as 64-bitARMv8 and32-bitARMv7andARMv6 developed by British companyARM Holdings, who have designed and licensed a family ofcomputer processorsthat use these instruction set architectures; some other companies have also designed processors that use the ARM architectures. CHAPTER-38051 Microcontroller

3.1 Introduction

Circumstancesthatwefindourselvesintodayinthefieldofmicrocontrollershadtheirbeginnings in the development of technology of integrated circuits. This development has made it possible tostorehundreds ofthousands oftransistors intoone chip. Thatwas aprerequisite for production of microprocessors, and the first computers were made by adding externalperipherals such as memory, input-output lines, timers and other. Further increasing of the volume of the package resulted in creation of integration circuits.

3.2 Definition of a Microcontroller

Microcontroller,aresmallcontrollers.Theyarelikesinglechipcomputes that are often embedded into other systems to function as processing/controlling unit. For example, the remote control we are using probably has microcontrollers inside that do decoding and other controlling functions. They are also used in automobiles, washing machines, microwave ovens, toys etc, where automation is needed. The key features of microcontrollers include:

High Integration of Functionality Microcontrollers sometimes are called single-chip computers because they have on-chip memory and I/O circuitry and other circuitries that enable them to function as small standalone computerswithout other supportingcircuitry. Microcontrollers often useEEPROMor EPROMas theirstoragedevice toallow fieldprogrammability so they are flexible to use. Once the program is tested to be correct the large quantities of microcontrollers can be programmed to be used in embedded systems. Easy to Use Assembly language is often used inmicrocontrollers and since they usually follow RISC architecture, the instruction set is small. The development package of microcontrollersoftenincludesanassembler,asimulator,aprogrammerto"burn"the chipanda demonstration board. Some packages include a high level language compiler such as a C compiler and more sophisticated libraries. A Timer module toallow the microcontroller to perform tasks for certain time periods.

3.3 AT89C51

AT89C51 is an 8-bit, 40 pin microcontroller that belongs to Atmel's8051 family.ATMEL 89C51has 4KB of Flash programmable and erasable read only memory (PEROM) and 128 bytes of RAM. It can be erased and program to a maximum of 1000 times.

In 40 pin AT89C51, there are four ports designated as P1, P2, P3and P0. All these ports are 8-bit bi-directional ports,i.e., they can be used as both input and output ports. Except P0which needs external pull-ups, rest of the ports have internal pull-ups. When 1s are written to these port pins, they are pulled high by the internal pull-ups and can be used as inputs. These ports are also bit addressable and so their bits can also be accessed individually.

The main features of 8051 are:-

8-bitALUandAccumulator, 8-bitRegisters(one16-bitregister with specialmove instructions), 8-bitdata busand 2x16-bitaddress bus/program counter/data pointerand related 8/11/16-bit operations; hence it is mainly an8-bitmicrocontroller. Booleanprocessor with 17 instructions, 1-bit accumulator, 32 registers (4 bit addressable 8-bit) and up to 144 special 1-bit addressable RAM variables (18 bit addressable 8-bit). 4 fastswitchable register bankswith 8 registers each (memory mapped). Fast interrupt with optional register bank switching. Interruptswith selectable priority. 128bytesof on-chip RAM

Four 8-bitbi-directionalinput/outputport UART (serial port), two 16-bit Counter/timers Power savingmode Fully Static Operation: 0 Hz to 24 MHz

3.4 PIN DESCRIPTION OF AT89C51 Figure 3.1: Pin DiagramWe have 4 ports in8051 micro controller. They are port0, port1, port2, port3 which can be accessed as i/o ports. The pins of themicro controller are explained below.Port 0:-The P0 port is characterized by two functions. If external memory is used then the lower address byte (addresses A0-A7) is applied on it. Otherwise, all bits of this port are configured as inputs/outputs.The other function is expressed when it is configured as an output. Unlike other ports consisting of pins with built-in pull-up resistor connected by its end to 5 V power supply, pins of this port have this resistor left out. This apparently small difference has its consequences. When the pin is configured as an output, it acts as an open drain. By applying logic 0 to a port bit, the appropriate pin will be connected to ground (0V). By applying logic 1, the external output will keep on floating. In order to apply logic 1 (5V) on this output pin, it is necessary to built in an external pull-up resistor. Figure 3.2:Pull up at Port 0Pins 1-8 (Port 1) -Each of these pins can be configured as an input or an output.Pin 9 (Reset) -A logic one on this pin disables the microcontroller and clears the contents of most registers. In other words, the positive voltage on this pin resets the microcontroller. By applying logic zero to this pin, the program starts execution from the beginning.Pins 10- 17 (Port 3) -Similar to port 1, each of these pins can serve as general input or output. Besides, all of them have alternative functions:Pin 10 (RXD) - Serial asynchronous communication input or Serial synchronous communication output.Pin 11(TXD) -Serial asynchronous communication output or Serial synchronous communication clock output.

Pin 12 (INT 0) - Interrupt 0 input.Pin 13(INT 1) -Interrupt 1 input.

Pin 14(T0) -Counter 0 clock input.

Pin 15(T1) -Counter 1 clock input.

Pin 16(WR) -Write to external (additional) RAM.Pin 17 (RD) -Read from external RAM.

Pin 18 and 19(X1, X2) -Internal oscillator input and output. A quartz crystal which specifies operating frequency is usually connected to these pins. Instead of it, miniature ceramics resonators can also be used for frequency stability. Later versions of microcontrollers operate at a frequency of 0 Hz up to over 50 Hz.

Pin 20 (GND) - Ground.

Pin 21-28 (Port 2) -If there is no intention to use external memory then these port pins are configured as general inputs/outputs. In case external memory is used, the higher address byte, i.e. addresses A8-A15 will appear on this port. Even though memory with capacity of 64Kb is not used, which means that not all eight port bits are used for its addressing, the rest of them are not available as inputs/outputs.

Pin 29 (PSEN) - If external ROM is used for storing program then a logic zero (0) appears on it every time the microcontroller reads a byte from memory.

Pin 30 (ALE) - Prior to reading from external memory, the microcontroller puts the lower address byte (A0-A7) on P0 and activates the ALE output. After receiving signal from the ALE pin, the external register memorizes the state of P0 and uses it as a memory chip address. Immediately after that, the ALU pin is returned its previous logic state and P0 is now used as a Data Bus. As seen, port data multiplexing is performed by means of only one additional (and cheap) integrated circuit. In other words, this port is used for both data and address transmission.Pin 31 (EA) -By applying logic zero to this pin, P2 and P3 are used for data and address transmission with no regard to whether there is internal memory or not. It means that even there is a program written to the microcontroller, it will not be executed. Instead, the program written to external ROM will be executed. By applying logic one to the EA pin, the microcontroller will use both memories, first internal then external (if exists).

Pin 40 (Vcc) -+5V power supply.

Reset:It resetstotal 8051 micro controller.

RXD:Itreceivesdatainserialcommunication.

TXD:Ittransmitsdatainserialcommunication.

INT0:Externalinterruptfortimer0.

INT1:Externalinterruptfortimer1

T0: Timer0.T1: Timer1.RD:Toreadintoexternalmemory.

WR:Towriteintoexternalmemory.

XTAL1&XTAL2:Toconnectthe crystaloscillator.

ALE:Addresslatchenablewhichisusedtoaccesstheaddresslocationsfrom externalmemory.

PSEN:Programstoreenablewhichisusedforstoringprogrammingcode into theexternal memory.

EA:ExternalAccess:64KBofROMisthelimitforexternalmemory

3.4.1 Crystal Circuit

Figure 3.3: Crystal circuitXTAL1 and XTAL2 are the input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator. Either a quartz crystal or ceramic resonator may be used. To drive the device from an external clock source, XTAL2 should be left unconnected while XTAL1 is driven as .There are no requirements on the duty cycle of the external clock signal, since the input to the internal clocking circuitry is through a divide-by-two flip-flop, but minimum and maximum voltage high and low time specifications must be observed.

3.4.2 Reset circuit

RESET pin is an input and is active high (normally low).Upon applying a high pulse to this pin, the microcontroller will reset and terminate all activities. This is often referred to as a power-on reset. Activating a power-on reset will cause all values in the registers to be lost.

In order for the RESET input to be effective, it must have a minimum duration of 2 machine cycles. In other words, the high pulse must be high for a minimum of 2 machine cyclesbefore it is allowed to go low.

Figure 3.4: Reset Circuit3.5Architecture of AT89C51

3.5.1Block Diagram.

Address bus-For a device (memory or I/O) to be recognized by the CPU, it must be assigned an address. The address assigned to a given device must be unique. The CPU puts the address on the address bus, and the decoding circuitry finds the device.

Data bus-The CPU either gets data from the deviceor sends data to it.

Control bus-Provides read or write signals to the device to indicate if the CPU is asking for information or sending it information

Figure 3.5: Block diagram of 8051

3.6RAM ARCHITECTURE

Ram Architecture: The 8051 has a bank of 128 bytes ofInternal RAM.This Internal RAM is found on-chip on the 8051 so it is the fastest RAM available, and it is also the most flexible in terms ofreading, writing, and modifying its contents. Internal RAM is volatile, so when the 8051 is reset this memory is cleared. The 128 bytes of internal ram is subdivided as shown on the memory map. The first 8 bytes (00h - 07h) are "register bank 0". These alternative register banks are located in internal RAM in addresses 08h through 1Fh.Bit memory actually resides in internal RAM, from addresses 20h through 2Fh. The 80 bytes remaining of Internal RAM, from addresses 30h through 7Fh,may be used byuser variables thatneed to be accessedfrequently or at high-speed. This area is also utilized by the microcontroller as a storage area for the operatingstack

3.6.1 Memory and RegistersThe 8051 microcontroller has a total of 256 bytes of RAM in which 128 is visible or user accessible and extra 128 is for special function registers. The user accessible RAM is used for temporary data storage. The user accessible RAM is from the address range 00 to 7Fh.From the user accessible RAM, 32 bytes of RAM is used for registers and rest for Stack operations. The 32 Bytes of RAM is divided into four register Banks i.e. Bank0, Bank 1, Bank 2, Bank3. Each of these banks have 8 Registers i.e. R0 to R7 each. RAM locations from 0 to 7 are set aside for bank 0 of R0 R7 where R0 is RAM location 0, Rl is RAM location 1, and R2 is location 2, and so on, until memory location 7, which belongs to R7 of bank 0. The second bank of registers R0 R7 starts at RAM location 08 and goes to location 0FH. The third bank of R0 R7 starts at memory location 10H and goes to location 17H. Finally, RAM locations 18H to 1FH are set aside for the fourth bank of R0 R7.

Figure 3.6: Register BanksGenerally for normal operations, Register bank Bank0 is set by default. But we can switch to other banks by using PSW Commands. Figure 3.7: Bank Selection3.6.2 SFRs (Special Function Register) - These Registers are in extra 128 bytes of the memory. This part of memory is not user accessible and these registers are used for special purposes. These registers range from 80h to FFh. There are a total of only 21 SFRs in this range and all other addresses from 80h to FFh are invalid and there use can cause errors and not valuable results.Some of the SFRs are TCON, SBUF, ACC, B, SCON, TMOD SP, P0, PSW, TL0, and TL1. These all the registers have some specific function that has to be performed after they are programmed.(i) Byte Addressable SFR with byte addressSP Stack printer 81HDPTR Data pointer 2 bytesDPL Low byte 82HDPH High byte 83HTMOD Timer mode control 89HTH0 Timer 0 Higher order bytes 8CHTL0 Timer 0 Low order bytes 8AHTH1 Timer 1 High bytes = 80HTL1 Timer 1 Low order byte = 86HSBUF Serial data buffer = 99HPCON Power control 87H.

3.6.3 Registers

The AccumulatorThe Accumulator, as its name suggests.

The "R" registersThe "R" registers are a set of eight registers that are named R0, R1, etc. up to and including R7. These registers are used as auxiliary registers in many 8-bit(1-operations.

The "B" RegisterThe "B" register is very similar to the Accumulator in the sense that it may hold an byte) value. The "B"register is only used by two 8051 instructions: MUL AB and DIV AB.

The Data Pointer (DPTR)The Data Pointer (DPTR) is the 8051s only user-accessible 16-bit (2-byte) register. The Accumulator, "R" registers, and "B" register are all 1-byte values. DPTR, as the name suggests, is used to point to data. It is used by a number of commands which allow the 8051 to access externalmemory.

Program CounterThe Program Counter (PC) is a 2-byte address which tells the 8051 where the next instruction to execute is found in memory. When the 8051 is initialized PC always starts at0000h and is incremented each time an instruction is executed..

The Stack Pointer (SP)The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte)value. The Stack Pointer is used to indicate where the next value to be removed from the stackshould be

Figure 3.8: RAM allocation3.7 8051 Assembly Language Programming3.7.1 How to Program an 8051 microcontroller[Label:] mnemonic [operands] [; comment]Mnemonics -Assembly level instructions are called mnemonic like MOV R5Operands -On which the operation is performed.Example:Loop: MOVR1, #25H; transfer 25H into R1 Label mnemonics operand comments Two instructions which are used to start and terminate program are

ORG -This instruction indicate the origin of program,Example- ORG 3000H means program starts from 3000H location. This instruction hasnt take any memory space. It is used to show the starting address of program.

END - This instruction show the END of program or it is used to terminate the program.Example:ORG 0H; start compiler from 0h addressAgain: MOV R5, # 25H; transfer 25H to R5ADD A, R5; Add the R5 with AccumulatorSJMP Again; - jump to the location againEND; end the program.

3.7.2 Addressing Modes

Register Addressing Mode-The register addressing instruction involves information transfer between registersExample:MOV R0, AThe instruction transfers the accumulator content into the R0register. The register bank (Bank 0, 1, 2 or 3) must be specified prior to this instruction.In the Register Addressing mode, the instruction involves transfer of information between registers. The accumulator is referred to as the A register.

Direct Addressing Mode- This mode allows you to specify the operand by giving its actual memory address (typically specified in hexadecimal format) or by giving its abbreviated name (e.g. P3).Used for SFR accessesExample:MOV A, P3; Transfer the contents of Port 3 to the accumulatorMOV A, 020H; Transfer the contents of RAM location 20H to the accumulator.Indirect Addressing Mode-In the Indirect Addressing mode, a register is used to hold the effective address of the operand. This register, which holds the address, is called the pointer register and is said to point to the operand.Only registers R0, R1 and DPTR can be used as pointer registers.R0 and R1 registers can hold an 8-bit address whereas DPTR can hold a 16-bit address.DPTR is useful in accessing operands which are in the external memory.Examples:MOV @R0, A; Store the content of accumulator into the memory location pointed to by the contents of register R0. R0 could have an 8-bit address, such as 60H.

MOVX A, @DPTR; Transfer the contents from the memory location pointed to by DPTR into the accumulator. DPTR could have a 16-bit address, such as 1234H.

Immediate Addressing Mode-In the Immediate Constant Addressing mode, the source operand is an 8- or 16-bit constant value. This constant is specified in the instruction itself (rather than in a register or a memory location).The destination register should hold the same data size which is specified by the source operand.Examples:ADD A, #030H; Add 8-bit value of 30H to the accumulator register (which is an 8-bit register).MOV DPTR, #0FE00H; Move 16-bit data constant FE00H into the 16-bit Data Pointer Register.

3.7.3 Instruction TypesThe 8051 instructions are divided into four functional groups: Arithmetic operations Logical operations Data transfer operations Program branching operations

Arithmetic Instructions-This group of operators perform arithmetic operations. Arithmetic operations affect the flags, such as Carry Flag (CY), Overflow Flag (OV) etc., in the PSW register. The appropriate status bits in the PSW are set when specific conditions are met, which allows the user software to manage the different data formats.

Logical Instructions-Logical instructions perform standard Boolean operations such as AND, OR, XOR, NOT (compliment). Other logical operations are clear accumulator, rotate accumulator left and right, and swap nibbles in accumulator.Examples:ANL A, #02H;Mask bit 1ORL TCON, A;TCON=TCON OR A

Data Transfer Instructions- Data transfer instructions can be used to transfer data between an internal RAM location and an SFR location without going through the accumulator.It is also possible to transfer data between the internal and external RAM by using indirect addressing. The upper 128 bytes of data RAM are accessed only by indirect addressing and the SFRs areaccessed only by direct addressing.

Program Branching Instructions- Program branching instructions are used to control the flow of program execution. Some instructions provide decision making capabilities before transferring control to other parts of the program e.g. conditional and unconditional branches

3.7.4 Flags and PSW (Program Status Word) Register in 8051 The program status word (PSW) register, also referred to as the flag register, is an 8 bit register. Only 6 bits are used These four are CY (carry), AC (auxiliary carry), P(parity), and OV (overflow) They are called conditional flags, meaning that they indicate some conditions thatresulted after an instruction was execute. The PSW3 and PSW4 are designed as RS0 and RS1, and are used to change the bank. The two unused bits are user-definable.

PSW 7 PSW 6 PSW 5PSW 4 PSW 3 PSW 2 PSW 1 PSW 0 Figure 3.9: PSW RegisterCAF0RS1RS0OV---------P

CY- PSW.7- Carry flag.AC- PSW.6- Auxiliary Carry flag.F0 (-----) - PSW.5- Available to the user for general purposeRS1 -PSW.4 - Register Bank selector bit 1.RS0- PSW.3 -Register Bank selector bit 0.OV -PSW.2 -Overflow flag.F0 (-----) - PSW.1- User definable bit.P- PSW.0 -Parity flag. Set/cleared by hardware each.

3.8 TIMERS AND COUNTERS3.8.1TimersThe 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Counting the events themselves, 3) Generating baud rates for the serial port.Both Timer 0 and Timer 1 are 16 bits wide.Since 8051 has an 8-bit architecture, each 16-bits timer is accessed as two separate registers of low byte and high byte.

One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated to itself (TH0/TL0 and TH1/TL1).The upper higher bits are TH0 and TH1 and the lower bits are TL0 AND TL1.The TMOD and TCON are two control registers for the two timers.

Figure 3.10 :Timer Registers

(i) TMOD RegisterIt is used to set the various timer operation mode. TMOD is an 8-bit register where the lower 4 bits are set aside for timer 0 and the upper 4 bits are set aside for timer 1.

MSB LSBGate C/TM0M1GATEC/TM0 MI

Timer 1 Timer 0 Figure 3.11:TMOD Register

GATE: To start and stop the timer GATE=1 _Hardware control: is enabled only while INTx pin is 1and TRx control pin (in TCON) is set. GATE=0 _Software control (used frequently)

C/T: Timer or counter selection C/T = 0 _Timer (input from internal system clock) the crystal (1/12) is used to trigger the timer. C/T = 1 _Counter (input from Tx input pin)M1 and M0: Mode selection for timer and counterMode M1 M00 0 0 13-bit timer/counter mode1 0 1 16-bit timer/counter mode2 1 0 8-bit auto reload timer/counter mode3 1 1 split timer/counter mode

(ii) TCON Register

MSBLSBTF1TF0TR1TR0IE1IE0IT1IT0

TIMER 1 TIMER 0 TIMER1TIMER0 Figure 3.12: TCON RegisterTF1: Timer 1 overflows flag TF1=1: Timer/counter 1 overflows. TF1=0: processor vectors to the interrupt services.TR1: Timer 1 run control bit TR1=1: turn Timer 1 ON TR1=0: turn Timer 1 OFFIE1: External interrupt 1 edge flag IE1=1: external interrupt is detected. IE1=0: when interrupt is processed. IT1: Interrupt 1 type control bit IT1=1: falling edge. IT1=0: low level triggered external interrupt.

Gate=0, SETB TR1 _Run Timer 1SETB TR0 _Run Timer 0Gate=0, CLR TR1 _OFF Timer 1CLR TR0 _OFF Timer 0

Timer Mode 0 Mode 0: 13-bit Timer/counter mode 0000 ~ 1FFFH

Timer Mode 2Mode 2: 8-bit auto reload Timer/counter mode (00 ~ FFH). In auto reload, TH is loaded with the initial count and a copy of it is given to TL. This reloading leaves TH unchanged still holding a copy of original values. This mode has many applications, including setting the baud rate in serial communication.

3.8.2 Counters

Counter is used to count input pulses.C/T=0: As Time, using 8051s crystal as the source of the frequency.C/T=1: As counter, a pulse outside of the 8051 that increments the TH and TL register.When the C/T=1, the counter counts up as pulses are fed from Pins P3.4 (for counter 0) or P3.5 (for counter 1).

3.9 INTERUPTS

An interrupt is an external or internal event that interrupts the microcontroller to inform it that a device needs its service. The advantage of interrupts is that the microcontroller can serve many devices. Each device can get the attention of the microcontroller based on the assigned priority. The microcontroller can also ignore (mask) a device request for service.

3.9.1 Hardware and Software interruptThe interrupts in a controller can be either hardware or software. If the interrupts are generated by the controllers inbuilt devices, like timer interrupts; or by the interfaced devices, they are called the hardware interrupts. If the interrupts are generated by a piece of code, they are termed as software interrupts.

The 8051 controller has six hardware interrupts of which five are available to the programmer.

1. RESET Interrupt- This is also known as Power on Reset (POR). When the RESET interrupt is received, the controller restarts executing code from 0000H location. This is an interrupt which is not available to or, better to say, need not be available to the programmer.2. Timer interrupts- Each Timer is associated with a Timer interrupt. A timer interrupt notifies the microcontroller that the corresponding Timer has finished counting. Therefore these are two interrupts for the timers.3. External interrupts- There are two external interrupts EX0 and EX1 to serve external devices. Both these interrupts are active low. InAT89C51, P3.2 (INT0) and P3.3 (INT1) pins are available for external interrupts 0 and 1 respectively. An external interrupt notifies the microcontroller that an external device needs its service.4. Serial interrupt- This interrupt is used forserial communication. When enabled, it notifies the controller whether a byte has been received or transmitted.

Figure3.13: Various Interrupts

CHAPTER-4

Interfacings with 8051 microcontroller4.1 LED InterfacingInterfacing an LED with 8051 is easy. The I/O pins are used as output pins. When any of the bit is set to 1, the LED glows if LED n side is connected to ground and p side with bit. And if p side is connected to power and n side to bit, then on bit low, the LED glows.4.1.1 Assembly Code for led interfacing org 00h back: mov a,#00h mov P0,a acall secdelay mov a,#0ffh mov P0,a acall secdelay Sjmp back secdelay: mov r5,#25 H3: mov r4,#55 H2: mov r3,#ffhH1: djnz r3,H1 djnz r4,H2 djnz r5,H3 ret

Figure 4.1: LED Interfacing4.2 Seven Segment Display InterfacingAseven segmentconsists of eightLEDswhich are aligned in a manner so as to display digits from 0 to 9 when proper combination of LED is switched on. Seven segment uses seven LEDs to display digits from 0 to 9 and the eighth LED is used for the dot. Figure 4.2: Seven Segment DisplayAssembly Code org 00hmov P1,#3fh call delay mov P0,#06h call delay mov P0,#5bh call delay mov P0,#4fh call delay mov P0,#66h call delay mov P0,#6dh call delay mov P0,#7dh call delay mov P0,#07h call delay mov P0,#7fh call delay mov P0,#67h call delay jmp main delay:mov 40h,#0FFh L1:mov 41h,#99h L2:djnz 41h,L2 djnz 40h,L1 ret Figure 4.3: 7 Segment Display Interfacing4.3 LCD INTERFACINGA 16x2LCDmeans it can display 16 characters per line and there are 2 such lines. In this LCD each character is displayed in 5x7 pixel matrix. ThisLCD has two registers.1.Command/Instruction Register- stores the command instructions given to the LCD. A command is an instruction given to LCD to do a predefined task like initializing, clearing the screen, setting the cursor position, controlling display etc.2.Data Register- stores the data to be displayed on the LCD. The data is the ASCII value of the character to be displayed on the LCD. Figure 4.4: LCD Interfacing Table 4.1: LCD Commands Assembly CodeORG 0HMOV A,#38H ACALL COMNWRT ACALL DELAY MOV A,#0EH ACALL COMNWRT ACALL DELAY MOV A,#01 ACALL COMNWRT ACALL DELAY MOV A,#84H ACALL COMNWRT ACALL DELAY MOV A,#c ACALL DATAWRT ACALL DELAY MOV A,#d ACALL DATAWRT AGAIN: SJMP AGAIN MOV A,#a ACALL DATAWRT ACALL DELAY MOV A,#c ACALL DATAWRT AGAIN: SJMP AGAINCOMNWRT: ; MOV P1,A CLR P2.0 CLR P2.1 SETB P2.2 ACALL DELAY CLR P2.2 RETDATAWRT:MOV P1,A SETB P2.0 CLR P2.1 SETB P2.2ACALL DELAY CLR P2.2 RETDELAY: MOV R3,#50 HERE2: MOV R4,#255 HERE: DJNZ R4,HERE DJNZ R3,HERE2RET

4.4 Keypad InterfacingKeyboards are organized in a matrix of rows and columns. The CPU accesses both rows and columns through ports. Therefore, with two 8-bit ports, an 8 x 8 matrix of keys can be connected to a microcontroller. When a key is pressed, a row and a column make a contact. Otherwise, there is no connection between rows and columns. A 4x4 matrix connected to two ports The rows are connected to an output port and the columns are connected to an input port It is the function of the microcontroller to scan the keyboard continuously to detect and identify the key pressed.To detect a pressed key, the microcontroller grounds all rows by providing 0 to the output latch, then it reads the columns.If the data read from columns is D3 D0 =1111, no key has been pressed and the process continues till key press is detected. If one of the column bits has a zero, this means that a key press has occurred.Assembly Codeorg 00hhere:mov p1,#0ffhclr p1.0h1:jb p1.4,h2 mov p2,#3fhh2:jb p1.5,h3 mov p2,#06hh3:jb p1.6,h4 mov p2,#5bhh4:jb p1.7,h5 mov p2,#4fhh5:setb p1.0clr p1.1 jb p1.4,h6 mov p2,#66hh6:jb p1.5,h7 mov p2,#6dhh7:jb p1.6,h8mov p2,#7dhh8:jb p1.7,h9mov p2,#07hh9:setb p1.1clr p1.2 jb p1.4,h10 mov p2,#7fhh10:jb p1.5,h11 mov p2,#67hh11:jb p1.6,h12 mov p2,#77hh12:jb p1.7,h13 mov p2,#7fhh13:setb p1.2clr p1.3 jb p1.4,h14 mov p2,#39hh14:jb p1.5,h15 mov p2,#3fhh15:jb p1.6,h16 mov p2,#79hh16:jb p1.7,h17 mov p2,#71hh17:ljmp here end

Figure 4.5: Keypad Interfacing4.5 Relay interfacingA relays is an electrical switch that opens and closes under control of another electrical circuit. It is therefore connected to ouput pins of the microcontroller and used to turn on/off high-power devices such as motors, transformers, heaters, bulbs, antenna systems etc.

Assembly Code org 00h back: mov a,#00h mov P1,a acall secdelay mov a,#01h mov P1,a acall secdelay Sjmp back Secdelay: mov r5,#25 H3: mov r4,#55H2: mov r3,#ff H1:djnz r3,H1 djnz r4,H2 djnz r5,H3ret

Figure 4.6:Relay Interacing

4.6 Stepper Motor InterfacingA stepper motor (or step motor) is a brushless synchronous electric motor that can divide a full rotation into a large number of steps. The motor's position can be controlled precisely without any feedback mechanism, as long as the motor is carefully sized to the application. Stepper motors are similar to switched reluctance motor (which are very large stepping motors with a reduced pole count, and generally are closed-loop The stepper motor can be interfaced with the 8051 using l293d connected to p1.0,p1.2,p1.3,p1.4Stepper motor two types of step sequence 1) full step and 2) half step sequence. In the full step sequence, two coils are energized at the same time and motor shaft rotates.

Assembly Codeorg 00hmov a,#66hback:mov p2,a rr a acall delay sjmp backdelay:mov r2,#100h1: mov r3,#255h2: djnz r3,h2 djnz r2,h1ret

Figure 4.7: Stepper Motor

4.7 Serial CommunicationWe need a line driver (voltage converter) to convert the R232s signals to TTL voltage levels that will be acceptable to 8051s TxD and RxD pins.

Figure 4.8: MAX232 pin outAssembly CodeORG 00HAGAIN:MOV TMOD,#20H MOV TH1,#-3MOV SCON,#50H SETB TR1 AGAIN: MOV SBUF,#A HERE: JNB TI,HERE CLR TI SJMP AGAIN

CHAPTER-5

AVR MICROCONTROLLER

5.1 Introduction

The acronym AVR has been reported to stand for Advanced Virtual RISC, but it has also been rumored to stand for the initials of the chip's designers. The AVR architecture was conceived by two students at theNorwegian institute of technology, Alf-Egil Bogen and Vegard Wollan Microcontroller was developed by Atmel in 1996TheAVRis amodified Harvard architecture8-bitRISCsingle chipmicrocontroller. The AVR was one of the first microcontroller families to use on-chipflash memoryfor program storage, as opposed toone-time programmable ROM,EPROM, orEEPROMused by other microcontrollers at the time. Among the first of the AVR line was the AT90S8515, which in a 40-pin DIP package has the same pinout as an8051microcontroller, including the external multiplexed address and data bus. The polarity of theRESETline was opposite (8051's having an active-high RESET, while the AVR has an active-lowRESET), but other than that, the pin out was identical.

5.2 Features

High-performance, Low-power AVR 8-bit Microcontroller RISC Architecture 130 Powerful Instructions Most Single Clock Cycle Execution 32 x 8 General Purpose Working Registers Fully Static Operation Up to 16 MIPS Throughput at 16 MHz On-chip 2-cycle Multiplier Nonvolatile Program and Data Memories 8K Bytes of In-System Self-programmable Flash 512 Bytes EEPROM 512 Bytes Internal SRAM Up to 64K Bytes Optional External Memory Space Programming Lock for Software Security Peripheral Features One 8-bit Timer/Counter with Separate Prescaler and Compare Mode One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode Three PWM Channels Programmable Serial USART Master/Slave SPI Serial Interface Programmable Watchdog Timer with Separate On-chip Oscillator On-chip Analog Comparator Special Microcontroller Features External and Internal Interrupt Sources Three Sleep Modes: Idle, Power-down and Standby I/O and Packages 35 Programmable I/O Lines 40-pin PDIP, 44-lead TQFP, 44-lead PLCC, and 44-pad QFN/MLF Operating Voltages 2.7 - 5.5V for ATmega8515L 4.5 - 5.5V for ATmega8515 Speed Grades 0 - 8 MHz for ATmega8515L 0 - 16 MHz for ATmega8515

5.3 Basic FamiliesAVR generally Classified into basically five Groups Tiny AVR- the ATtiny Series - 0.5-8kB program memory - 6-32 pin Package - Limited Peripheral Mega AVR- the ATmega Series - 4-256kB program memory28-100 pin package- Extended instruction set- Extensive peripheral set XMEGA ATxmega series 16-384 kB program memory 44-64-100 pin package. Extended Performa features such as DMA, Event system and cryptography system. Extensive Peripheral Set Application Specific AVR Mega AVR with special features such as LCD controller , Advanced AVR FPSLIC (AVR with FPGA) Field Programmable Specific Language Integrated Circuit is combination of AVR with Field Programmable Gate Array of 5K to 40K gates SRAM for the AVR program code AVR core can be run at up to 50 MHz

5.4 Pin Diagram Figure 5.1: Pin Configuration of AVR VCC Digital supply voltage.

GND Ground.

Port A (PA7..PA0) Port A is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port A output buffers have symmetrical drive characteristics with both high sink and source capability. When pins PA0 to PA7 are used as inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated. The PortA pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port A also serves the functions of various special features of the ATmega8515.

Port B (PB7..PB0) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port B pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not running.

Port C (PC7..PC0) Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port C output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port C pins that are externally pulled low will source current if the pull-up resistors are activated. The Port C pins are tri-stated when a reset condition becomes active, even if the clock is not running.Port D (PD7..PD0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port D output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port D pins that are externally pulled low will source current if the pull-up resistors are activated. The Port D pins are tri-stated when a reset condition becomes active, even if the clock is not running.

Port E(PE2..PE0) Port E is an 3-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port E output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port E pins that are externally pulled low will source current if the pull-up resistors are activated. The Port E pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

RESET Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running.

XTAL1 Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.

XTAL2 Output from the inverting Oscillator amplifier.

5.5 Architecture

Figure 5.2: Architecture of AVRThe AVR core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clockcycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers.

The ATmega8515 provides the following features: 8K bytes of In-System ProgrammableFlash with Read-While-Write capabilities, 512 bytes EEPROM, 512 bytes SRAM, an External memory interface, 35 general purpose I/O lines, 32 general purpose working registers, two flexible Timer/Counters with compare modes, Internal and External interrupts, a Serial Programmable USART, a programmable Watchdog Timer with internal Oscillator, a SPI serial port, and three software selectable power saving modes. The Idle mode stops the CPU while allowing the SRAM, Timer/Counters, SPI port, and Interrupt system to continue functioning. The Power-down mode saves the Register contents but freezes the Oscillator, disabling all other chip functions until the next interrupt or hardware reset. In Standby mode, the crystal/resonator Oscillator is running while the rest of the device is sleeping. This allows very fast start-up combined with low-power consumption.

Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data Space addressing enabling efficient address calculations. One of the these address pointers can also be used as an address pointer for look up tables in Flash Program memory. These added function registers are the 16-bit X-, Y-, and Z-register,.The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated to reflect information about the result of the operation. Program flow is provided by conditional and unconditional jump and call instructions,able to directly address the whole address space. Most AVR instructions have a single 16-bit word format. Every Program memory address contains a 16- or 32-bit instruction.

During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total SRAM size and the usage of the SRAM. All user programs must initialize the SP in the reset routine (before subroutines or interrupts are executed). The Stack Pointer SP is read/write accessible in the I/O space. The data SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture. The memory spaces in the AVR architecture are all linear and regular memory maps. A flexible interrupt module has its Control Registers in the I/O space with an additional Global Interrupt Enable bit in the Status Register. All interrupts have a separate interrupt vector in the Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority. The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O Memory can be accessed directly, or asthe Data Space locations following those of the Register File, $20 - $5F.

ALU Arithmetic Logic Unit

The high-performance AVR ALU operates in direct connection with all the 32 generalPurpose working registers. Within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. The ALU operations are divided into three main categories arithmetic, logical, and bit-functions. Some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format.

Status Register

The Status Register contains information about the result of the most recently executedarithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. The Status Register is updated after all ALU operations, as specified in the Instruction Set Reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code.The AVR Status Register SREG is defined as:

Bit 7 I: Global Interrupt EnableThe Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate Control Registers. If the GlobalInterrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I bit can also be set and cleared by the application with the SEI and CLI instructions Bit 6 T: Bit Copy StorageThe Bit Copy instructions BLD (Bit Load) and BST (Bit Store) use the T-bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction. Bit 5 H: Half Carry FlagThe Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry isuseful in BCD arithmetic. Bit 4 S: Sign Bit, S = N VThe S-bit is always an exclusive or between the Negative Flag N and the Twos Complement Overflow Flag V. Bit 3 V: Twos Complement Overflow FlagThe Twos Complement Overflow Flag V supports twos complement arithmetic. Bit 2 N: Negative FlagThe Negative Flag N indicates a negative result in an arithmetic or logic operation. Bit 1 Z: Zero FlagThe Zero Flag Z indicates a zero result in an arithmetic or logic operation. Bit 0 C: Carry FlagThe Carry Flag C indicates a carry in an arithmetic or logic operation.

Figure 5.3: Status Register

5.6General Purpose Register File

The Register File is optimized for the AVR Enhanced RISC instruction set. In order toachieve the required performance and flexibility, the following input/output schemes are supported by the Register File:

One 8-bit output operand and one 8-bit result input Two 8-bit output operands and one 8-bit result input Two 8-bit output operands and one 16-bit result input One 16-bit output operand and one 16-bit result input

Most of the instructions operating on the Register File have direct access to all registers,and most of them are single cycle instructions. each register is also assigned a Data memory address, mapping them directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the registers, as the X-, Y-, and Z-pointer Registers can be set to index any register in the file.Byte

5.6.1 The X-register, Y-register, and Z-register

The registers R26..R31 have some added functions to their general purpose usage. These registers are 16-bit address pointers for indirect addressing of the Data Space. The three indirect address registers X, Y, and Z In the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement.

5.6.2 Stack Pointer The Stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. The Stack Pointer Register always points to the top of the Stack. the Stack is implemented as growing from higher memory locations to lower memory locations. This implies that a Stack PUSH command decreases the Stack Pointer.The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts are enabled. The. The Stack Pointer is decremented by one whendata is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the return address is pushed onto the Stack with subroutine call or interrupt. The stack Pointer is incremented by one when data is popped from the Stack with the POP instruction, and it is incremented by two when address is popped from the Stack with return from subroutine RET or return from interrupt RETI.The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of bits actually used is implementation dependent.

5.7 I/O Port RegistersEach of the AVR Digital I/O ports is associated with three (3) I/O register. A Data Direction Register (DDRx), A Pin Register (PINx) and a Port Register (PORTx). Wherexis the portA, B,C,etc..

DDRx - Port X Data Direction Register

Figure 5.4: DDR Register DDRx is an 8-bit register which stores configuration information for the pins of Portx. Writing a1in the pin location in the DDRx makes the physical pin of that port an output pin and writing a0makes that pin an input pin.PINx - Port X Input Pins Register

Figure 5.5:Input Pin RegisterPINx is an 8-bit register that stores the logic value, the current state, of the physical pins on Portx. So to read the values on the pins of Portx, you read the values that are in its PIN register.

PORTx - Port X Data Register

Figure 5.6: Port Data RegisterPORTx is an 8-bit register which stores the logic values that currently being outputted on the physical pins of Portx if the pins are configured as output pins. So to write values to a port, you write the values to the PORT register of that port.5.8 Memories5.8.1 Program memory It is a continuous chunk of flash memory. The exact size varies from controller to controller. Program memory is accessed every clock cycle and an instruction is loaded in the Instruction Register. The Instruction Register feeds the Register File, selecting which of the registers will be used for the program execution. The program memory besides storing the instructions also stores the Interrupt Vectors. The ATmega8515 contains 8K bytes On-chip In-System Reprogrammable Flash memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as 4K x 16. For software security, the Flash Program memory space is divided into two sections, Boot Program section and Application Program section. Figure 5.7 :Program Memory5.8.2 Data MemoryA Register File with 32 registers of 8-bit width.8-bit wide I/O registers. Number of I/O registers depends on the on-chip peripherals. Internal SRAM. Used for stack as well as for storing variables. The lower 608 Data Memory locations address the Register File, the I/O Memory, and the internal data SRAM. The first 96 locations address the Register File and I/O Memory, and the next 512 locations address the internal data SRAM.

Figure 5.8: Data Memory5.9 Addressing ModesThe ATmega8515 AVR RISC microcontroller supports powerful and efficient Addressing Modes for access to the program memory (Flash) and data memory (SRAM, Register file and I/O memory). The five different addressing modes for the data memory cover: Register Direct, with 1 and 2 registers I/O Direct Data Direct Data Indirect with pre-decrement with post-increment Code Memory Addressing1.Register DirectRegister Direct (single operand) .Instructions can operate on any of the 32 registers. The group of 32 registers are referred to as the Register File The microcontroller: Reads the data in the register Operates on the data in the register Stores the results back in the registerRegister Direct (two operands):Instructions can operate on any of the 32 registers One of these registers is the source register (Rs) and one is the destinationregister (Rd) Relative to the data.

Figure 5.9: Register Direct Addressing

Figure 5.10: Register Direct addressing(two operands)2. I/O Direct

Used to access I/O space (I/O registers and ports).I/O registers may only be accessed with two instructions:IN: for reading data from an input port: PINxOUT: for sending data out the output port: PORTx

Figure 5.11: I/O Direct Addressing3.Data Direct

Instructions are two word (16-bit).One of the operands is the address of the data (address of where the data is stored).The other operand is a register. Figure 5.12: Data Direct Addressing5. Data Indirect

In Data Direct, one of the operands is an explicitly specified address (to store or retrieve data).In Data Indirect, the address is specified as the contents of the X, Y, or Z .registerX is the combination of r26 & r27.Y is the combination of r28 & r29.Z is the combination of r30 &r31.X, Y, or Z are referred to as the pointer register. Figure 5.13: Data Indirect Addressing 6.Code Memory Addressing

The Z register is used as a pointer to Program Memory Up to 64k (16 bit register) and used for Indirect Jumps or subroutine calls.

Figure 5.14: Program Memory Addressing

5.10 Timers and Counters

The ATmega8515 provides two general-purpose Timer/Counters one 8-bit T/C and one 16-bit T/C. The Timer/Counters have individual prescaling selection from the same 10-bit prescaling timer. Both Timer/Counters can either be used as a timer with an internal clock time base or as a counter with an external pin connection that triggers the counting.

5.10.1 8 bit Timer/Counter 0Timer/Counter0 is a general purpose, single channel, 8-bit Timer/Counter module. Themain features are:

Single Channel Counter Clear Timer on Compare Match (Auto Reload) Frequency Generator External Event Counter 10-bit Clock Prescaler Overflow and Compare Match Interrupt Sources (TOV0 and OCF0)

RegistersThe Timer/Counter (TCNT0) and Output Compare Register (OCR0) are 8-bit registers. Interrupt request signals are all visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK). The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source is selected. The output from the clock select logic is referred to as the timer clock (clkT0).The double buffered Output Compare Register (OCR0) is compared with the Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare Pin (OC0).

5.10.2 8-bit Timer/Counter Register Description

Figure 5.15: TCCR0 Register Bit 7 FOC0: Force Output CompareThe FOC0 bit is only active when the WGM00 bit specifies a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0 is written when operating in PWM mode. When writing a logical one to the FOC0 bit, an immediate Compare Match is forced on the waveform generation unit. The OC0 output is changed according to its COM01:0 bits setting.

Bit 6, 3 WGM01:0: Waveform Generation ModeThese bits control the counting sequence of the counter, the source for the maximum(TOP) counter value, and what type of waveform generation to be used. Modes of operationsupported by the Timer/Counter unit are: Normal mode, Clear Timer on Compare Match (CTC) mode, and two types of Pulse Width Modulation (PWM) modes.

Bit 5:4 COM01:0: Compare Match Output ModeThese bits control the Output Compare pin (OC0) behavior. If one or both of the COM01:0 bits are set, the OC0 output overrides the normal port functionality of the I/O pin it is connected to. Table 5.1: COM01:0 bits settings

Bit 2:0 CS02:0: Clock Select Table 5.2: Clock select bits

Register TCNT0

Figure 5.16: TCNT0 RegisterThe Timer/Counter Register gives direct access, both for read and write operations, tothe Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare Match on the following timer clock.

Output Compare Register OCR0

Figure 5.17: OCR0 RegisterThe Output Compare Register contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an output compare interrupt, or to generate a waveform output on the OC0 pin.

Timer/Counter Interrupt Mask Register TIMSK

Figure 5.18 :TIMSK Register

Bit 1 TOIE0: Timer/Counter0 Overflow Interrupt EnableWhen the TOIE0 bit is written to one, and the I-bit in the Status Register is set (one), the Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter0 occurs, i.e., when the TOV0 bit is set in the Timer/Counter Interrupt Flag Register TIFR.

Bit 0 OCIE0: Timer/Counter0 Output Compare Match Interrupt EnableWhen the OCIE0 bit is written to one, and the I-bit in the Status Register is set (one), the Timer/Counter0 Compare Match interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter0 occurs.

Timer/Counter Interrupt Flag Register TIFR

Figure 5.19:TIFR Register Bit 1 TOV0: Timer/Counter0 Overflow FlagThe bit TOV0 is set (one) when an overflow occurs in Timer/Counter0.

Bit 0 OCF0: Output Compare Flag 0The OCF0 bit is set (one) when a Compare Match occurs between the Timer/Counter0and the data in OCR0 Output Compare Register0.

5.10.3 16-bit Timer/Counter1

The 16-bit Timer/Counter unit allows accurate program execution timing (event management),wave generation, and signal timing measurement. The main features are:

Two Independent Output Compare Units Double Buffered Output Compare Registers One Input Capture Unit Input Capture Noise Canceller Clear Timer on Compare Match (Auto Reload) Frequency Generator External Event Counter Four Independent Interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1)

Registers

The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input CaptureRegister (ICR1) are all 16-bit registers.

5.10.4 16-bit Timer/Counter Register DescriptionTimer/Counter1 Control Register A TCCR1A

Figure 5.20:TCCR1A Register Bit 7:6 COM1A1:0: Compare Output Mode for Channel A Bit 5:4 COM1B1:0: Compare Output Mode for Channel B Bit 7:6 COM1A1:0: Compare Output Mode for Channel A Bit 5:4 COM1B1:0: Compare Output Mode for Channel B

Timer/Counter1 Control Register B TCCR1B

Figure 5.21: TCCR1B Register Table 5.3:Prescalar Setting

Timer/Counter1 TCNT1H and TCNT1L

Figure 5.22: TCNT1H and TCNT1L RegistersThe two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for read and for write operations, to the Timer/Counter unit 16-bit counter.

Output Compare Register 1 A OCR1AH and OCR1AL

Figure 5.23: OCR1AH and OCR1AL RegistersOutput Compare Register 1 B OCR1BH and OCR1BL

Figure 5.24: OCR1BH and OCR1BL Registers

The Output Compare Registers contain a 16-bit value that is continuously compared with the counter value (TCNT1). A match can be used to generate an output compare interrupt, or to generate a waveform output on the OC1x pin.

5.11 USART

AVR has a dedicated hardware for serial communication this part is called the USART - Universal Synchronous Asynchronous Receiver Transmitter. We supply the data we need to transmit and it will do the rest. serial communication occurs at standard speeds of 9600,19200 bps etc and this speeds are slow compared to the AVR CPUs speed.Also the USART automatically senses the start of transmission of RX line and then inputs the whole byte and when it has the byte it informs The PC CPU to read that data from one of its registers. The USART of AVR is very versatile and can be setup for various different mode as required by our application.5.11.1 USART Registers

The USART of the AVR is connected to the CPU by the following six registers.UDR- USART Data Register : Actually this is not one but two register but when we read it we will get the data stored in receive buffer and when we write data to it goes into the transmitters buffer.

UCSRA- USART Control and status Register A : As the name suggests it is used to configure the USART and it also stores some status about the USART. There are two more of this kind theUCSRB and UCSRC.

UBRRHandUBRRL: This is the USART Baud rate register, it is 16BIT wide so UBRRH is the High Byte and UBRRL is Low byte. Figure 5.25: USART Registers

UCSRA: USART Control and Status Register A

Figure 5.26: UCSRA Register RXC-this bit is set when the USART has completed receiving a byte from the host (may be your PC) and the program should read it fromUDR .

TXC-This bit is set (1) when the USART has completed transmitting a byte to the host and your program can write new data to USART via UDR.

UCSRB: USART Control and Status Register B

Figure 5.27 UCSRB RegisterRXCIE: Receive Complete Interrupt Enable- When this bit is written one the associated interrupt is enabled.

TXCIE: Transmit Complete Interrupt Enable- When this bit is written one the the associated interrupt is enabled.

RXEN: Receiver Enable -When you write this bit to 1 the USART receiver is enabled. The normal port functionality of RX pin will be overridden.So you see that the associated I/O pin now switch to its secondary function,i.e. RX for USART.

TXEN: Transmitter Enable

UCSZ2: USART Character Size

UCSRC: USART Control And Status Register C

Figure 5.28 : UCSRC RegisterURSEL: USART register select

UMSEL: USART Mode Select -This bit selects between asynchronous and synchronous mode. As asynchronous mode is more popular with USART .

USBS: USART Stop Bit Select- This bit selects the number of stop bits in the data transfer.

UCSZ: USART Character size- These three bits (one in the UCSRB) selects the number of bits of data that is transmitted in each frame. Table 5.4: Character Size Setting

UBRR: USART Baud Rate Register:

This is the USART Baud rate register, it is 16BIT wide soUBRRHis the High Byte andUBRRLis Low byte. This register is used by the USART to generate the data transmission at specified speed (say 9600Bps).UBRR value is calculated according to following formula

CHAPTER-6

Interfacings with AVR

6.1 LED Interfacing

Figure 6.1: LED InterfacingAssembly Code.include "m8515def.inc".org 0x00ldi r16,0xffout sph,r16ldi r16,0x00out spl,r16ldi r17,0xffout ddra,r17ldi r18,0xaa next:out porta,r18delay:ldi r19,0x1l2: ldi r20,0x1l1: dec r20breq l1 dec r19 breq l2com r18rjmp next

6.2 Switch Interfacing

Figure 6.2: Switch InterfacingAssembly Code.include "m32def.inc".org 0x00ldi r16,high(ramend)out sph,r16ldi r16,low(ramend)out spl,r16ldi r17,0x00out ddrc,r17ldi r18,0xffout ddra,r18here:in r19,pincbst r19,0brts next1bst r19,1brts next2bst r19,2brts next3rjmp herenext1:ldi r20,0x80out porta,r20retnext2:ldi r20,0x40out porta,r20retnext3:ldi r20,0x20out porta,r20ret

6.3 Relay Interfacing Figure 6.3: Relay InterfacingAssembly Code.include "8515def.inc".org 0x00ldi r16,high(ramend)out sph,r16ldi r16,low(ramend)out spl,r16 ldi r17,0xff out ddrc,r17here: ldi r18,0xffout portc,r18rcall delayldi r18,0x00out portc,r18rcall delayrjmp heredelay: ldi r19,0xff l2: ldi r20,0xff l1:dec r20brne l1dec r19brne l2ret6.4 LCD InterfacingAssembly Code.include "m8515def.inc".org 0x00ldi r16,high(ramend)out sph,r16ldi r16,low(ramend)out spl,r16ldi r17,0xf0out ddra,r17ldi r17,0xffout ddrd,r17ldi r17,0xffout ddrc,r17ldi r18,0x38rcall commandrcall delayldi r18,0x0ercall commandrcall delayldi r18,0x01rcall commandrcall delayldi r18,0x06rcall commandrcall delayldi r18,0x84rcall commandrcall delayldi r18,crcall datarcall delayldi r18,drcall datarcall delayldi r18,arcall datarcall delayldi r18,crcall datarcall delayhere:rjmp herecommand: out portd,r18cbi portc,4sbi portc,5rcall delaycbi portc,5retdata: out portd,r18sbi portc,4sbi portc,5rcall delaycbi portc,5ret

delay: ldi r19,0xffl1: ldi r20,0x0fl2: dec r20 brne l2 dec r19 brne l1 ret

Figure 6.4: LCD Interfacing

6.5 Seven Segment Interfacing

Figure 6.5: Seven Segment Interfacing

Assembly Code.include "8515def.inc".org 0LDIR16, low(RAMEND)OUTSPL, R16LDIR16, high(RAMEND)OUTSPH, R16ldi r17,0xffout portd,r17here:ldi r18,0x3fout portd,r18rcall delayrcall delayldi r18,0x06out portd,r18rcall delayrcall delayldi r18,0x5bout portd,r18rcall delayrcall delayldi r18,0x4fout portd,r18rcall delayrcall delayldi r18,0x66out portd,r18rcall delayrcall delayldi r18,0x6dout portd,r18rcall delayrcall delayldi r18,0x7cout portd,r18rcall delayrcall delayldi r18,0x07out portd,r18rcall delayrcall delayldi r18,0x7fout portd,r18rcall delayrcall delayldi r18,0x67out portd,r18rcall delayrcall delayrjmp heredelay: ldi r20,0xffl2:ldi r21,0xff1:dec r21brne l1dec r20brne l2ret6.6 Keypad InterfacingAssembly Code.include "m8515def.inc".org 0x00ldi r16,high(ramend)out sph,r16ldi r16,low(ramend)out spl,r16ldi r17,0xf0out ddra,r17ldi r17,0xffout ddrd,r17ldi r17,0xffout ddrc,r17chek_key:ldi r17,0b11101111out porta,r17rcall delaysbis pina,pa0rjmp next1sbis pina,pa1rjmp next2sbis pina,pa2rjmp next3sbis pina,pa3rjmp next4ldi r17,0b11011111out porta,r17rcall delaysbis pina,pa0rjmp next5sbis pina,pa1rjmp next6sbis pina,pa2rjmp next7sbis pina,pa3rjmp next8ldi r17,0b10111111out porta,r17rcall delaysbis pina,pa0rjmp next9sbis pina,pa1rjmp next10sbis pina,pa2rjmp next11sbis pina,pa3rjmp next12ldi r17,0b01111111out porta,r17rcall delaysbis pina,pa0rjmp next13sbis pina,pa1rjmp next14sbis pina,pa2rjmp next15sbis pina,pa3rjmp next16rjmp chek_keycommandcode:ldi r18,0x38rcall commandrcall delayldi r18,0x0ercall commandrcall delayldi r18,0x01rcall commandrcall delayldi r18,0x06rcall commandrcall delayldi r18,0x84rcall commandrcall delayretnext1: rcall commandcodercall delayldi r18,'0'rcall datarcall delayrjmp chek_keynext2: rcall commandcodercall delayldi r18,'1'rcall datarcall delayrjmp chek_keynext3: rcall commandcodercall delayldi r18,'2'rcall datarcall delayrjmp chek_keynext4: rcall commandcodercall delayldi r18,'3'rcall datarcall delayrjmp chek_keynext5: rcall commandcodercall delayldi r18,'4'rcall datarcall delayrjmp chek_keynext6: rcall commandcodercall delayldi r18,'5'rcall datarcall delayrjmp chek_keynext7: rcall commandcodercall delayldi r18,'6'rcall datarcall delayrjmp chek_keynext8: rcall commandcodercall delayldi r18,'7'rcall datarcall delayrjmp chek_keynext9: rcall commandcodercall delayldi r18,'8'rcall datarcall delayrjmp chek_keynext10: rcall commandcodercall delayldi r18,'9'rcall datarcall delayrjmp chek_keynext11: rcall commandcodercall delay ldi r18,'a'rcall datarcall delayrjmp chek_keynext12: rcall commandcodercall delayldi r18,'b'rcall datarcall delayrjmp chek_keynext13: rcall commandcodercall delayldi r18,'c'rcall datarcall delayrjmp chek_keynext14: rcall commandcodercall delayldi r18,'d'rcall datarcall delayrjmp chek_keynext15: rcall commandcodercall delayldi r18,'e'rcall datarcall delayrjmp chek_keynext16: rcall commandcodercall delayldi r18,'f'rcall datarcall delayrjmp chek_keycommand: out portd,r18cbi portc,4sbi portc,5rcall delaycbi portc,5retdata: out portd,r18sbi portc,4sbi portc,5rcall delaycbi portc,5retdelay: ldi r19,0xffl1: ldi r20,0x0fl2: dec r20 brne l2 dec r19 brne l1 ret

Figure 6.6: Keypad Interfacing

6.7 USART Interfacing

AssemblyCode.include "m8515def.inc".cseg.org 0x00ldi r16,high(ramend)out sph,r16ldi r16,low(ramend)out spl,r16rcall usart_initmain: rcall usart_transmit rcall delay rjmp mainusart_init:ldi r16,0x00out ubrrh,r16ldi r16,51out ubrrl,r16ldi r16,(1