Docstoc

AVR microcontroller

Document Sample
AVR microcontroller Powered By Docstoc
					Industrial Training Report
Carried out at:SEMI-CONDUCTOR LABORATORY (Mohali)

Index
1)Acknowledgement 2)About SCL 3)Introduction to Digital Systems 4)Introduction to Microcontrollers 5)Project Report

ACKNOWLEDGEMENT
Training is agglomeration of the theoretical and practical and technical concepts which enhances our skills in the field of technology. No academic endeavor can be single handedly accomplished our sincere gratitude is the staff of SEMICONDUCTOR COMPLEX Ltd. for their kind assistance and provision of our training. We sincerely acknowledge our thanks to the teachers for their guidance and motivation throughout the training and project work. We would also like to record our gratitude to Mr.P.K. Bangotra for giving us a chance for a successful training here. Last, but not the least, I would like to thanks all our companions for their help which was in abundance. Saurabh Mehra Varun Manchanda Rohit Jindal Romil Garg Ashish Thukral

ABOUT SCL
SCL was setup in 1983, in the green unpolluted environs on the outskirts of Chandigarh just 250 kms north west of he India capital New Delhi. With its objective to design, develop and manufacture VLSIs, VLSI based systems and subsystems, and to create a strong R&D base, SCL commenced production in 5 micron CMOS technology in 1984, through intensive in house efforts SCL developed and produced the next generation 3 micron, 2 micron, 1.2 micron, 0.8 micron as well as EEPROM and CCD technologies. SSCL is leading India’s microelectronics endeavor with a modern six inch wafer fabrication facility. Recognizing the growth potential of MEMS market and leveraging its CMOS experience and infrastructure the company has established India’s first compositeCMOS/MEMS manufacturing facility gaining the strategic advantage to meet wider needs of the customers. Add to this, the plan to further upgrade the technology as well as the capacity and one has the vision of an emerging player in the global microelectronics arena. SCL’s vertically integrated semiconductor operations VLSI design and wafer fabrication, micro controller fabrication, testing, packaging and reliability testing, VLSI based system manufacturing and application support all under one roof within this framework, SCL places a lot of emphasis on its semiconductor operations consistently building on its specialization in the areas like Mixed Signal Devices, Micropower Technology, Digital Signal Processing, Imaging and MEMS Tchnology. This fulfills the demand of its customers in focus areas without ignoring its growing base of customers in consumer and industrial electronics.

Born with a focused mission, SCL has grown chip to chip, system to system and the story still goes on.

INTRODUCTION TO DIGITAL SYSTEM

TYPES OF ADDERS
For single bit adders, there are two general types. A half adder has two inputs, generally labelled A and B, and two outputs, the sum S and carry C. S is the two-bit XOR of A and B, and C is the AND of A and B. Essentially the output of a half adder is the sum of two one-bit numbers, with C being the most significant of these two outputs. The second type of single bit adder is the full adder. The full adder takes into account a carry input such that multiple adders can be used to add larger numbers. To remove ambiguity between the input and output carry lines, the carry in is labelled Ci or Cin while the carry out is labelled Co or Cout.

Half adder

Half adder circuit diagram

A half adder is a logical circuit that performs an addition operation on two binary digits. The half adder produces a sum and a carry value which are both binary digits.

Following is the logic table for a half adder: Input A B 0 0 0 1 1 0 1 1 Output C S 0 0 0 1 0 1 1 0

Full adder

Full adder circuit diagram Inputs: {A, B, CarryIn} → Outputs: {Sum, CarryOut}

Schematic symbol for a 1-bit full adder A full adder is a logical circuit that performs an addition operation on three binary digits. The full adder produces a sum and carry value, which are both binary digits. It can be combined with other full adders (see below) or work on its own.

Input A 0 0 0 B 0 0 1 Ci 0 1 0

Output Co 0 0 0 S 0 1 1

0 1 1 1 1

1 0 0 1 1

1 0 1 0 1

1 0 1 1 1

0 1 0 0 1

Note that the final OR gate before the carry-out output may be replaced by an XOR gate without altering the resulting logic. This is because the only discrepancy between OR and XOR gates occurs when both inputs are 1; for the adder shown here, one can check this is never possible. Using only two types of gates is convenient if one desires to implement the adder directly using common IC chips. A full adder can be constructed from two half adders by connecting A and B to the input of one half adder, connecting the sum from that to an input to the second adder, connecting Ci to the other input and or the two carry outputs. Equivalently, S could be made the three-bit xor of A, B, and C i and Co could be made the three-bit majority function of A, B, and Ci. The output of the full adder is the two-bit arithmetic sum of three one-bit numbers.

Multiple-bit adders
Ripple carry adder
When multiple full adders are used with the carry ins and carry outs chained together then this is called a ripple carry adder because the correct value of the carry bit ripples from one bit to the next.

It is possible to create a logical circuit using several full adders to add multiple-bit numbers. Each full adder inputs a Cin, which is the Cout of the previous adder. This kind of adder is a ripple carry adder, since each carry bit "ripples" to the next full adder. Note that the first (and only the first) full adder may be replaced by a half adder .The layout of a ripple carry adder is simple, which allows for fast design time; however, the ripple carry adder is relatively slow, since each full adder must wait for the carry bit to be calculated from the previous full adder. The gate delay can easily be calculated by inspection of the full adder circuit. Following the path from Cin to Cout shows 2 gates that must be passed through. Ergo, a 32-bit adder requires 31 carry computations and the final sum calculation for a total of 31 * 2 + 1 = 63 gate delays

.

4-bit ripple carry adder circuit diagram

Carry look-ahead adders
To reduce the computation time, engineers devised faster ways to add two binary numbers by using carry look ahead adders. They work by creating Propagate and Generate signals (P and G) for each bit position, based on whether a carry is propagated through from a less significant bit position (at least one input is a '1'), a carry is generated in that bit position (both inputs are '1'), or if a carry is killed in that bit position (both

inputs are '0'). In most cases, P is simply the sum output of a half-adder and G is the carry output of the same adder. After P and G are generated the carries for every bit position are created.

4-bit adder with Carry Look Ahead

Types of Shift Register
Shift registers can have a combination of serial and parallel inputs and outputs, including serial-in, parallel-out (SIPO) and parallel-in, serial-out (PISO) types. There are also types that have both serial and parallel input and types with serial and parallel output. , 4There are also bi-directional shift registers which allow you to vary the direction of the shift register. The serial input and outputs of a register can also be connected together to create a circular shift register. One could also create multi-dimensional shift registers, which can perform more complex computation.Serial-In, Parallel-Out

Bit SIPO Shift Register This configuration allows conversion from serial to parallel format. Data is input seriallyas described in the SISO section above. Once the data has been input, it may be either read off at each output simultaneously, or it can be shifted out and replaced.

Parallel-In, Serial-Out This configuration has the data input on lines D1 through D4 in parallel format. To write the data to the register, the Write/Shift control line must be held LOW. To shift the data, the W/S control line is brought HIGH and the registers are clocked. The arrangement now acts as a SISO shift register, with D1 as the Data Input. However, as long as the number of clock cycles is not more than the length of the data-string, the Data Output, Q,

will be the parallel data read off in order.

Parallel-In, Parallel-Out
This kind of shift register takes the data from the parallel inputs (D0-D3) and shifts it to the corresponding output (Q0-Q3) when the registers are clocked. It can be used as a kind of 'history', retaining old information as the input in another part of the system, until ready for new information, whereupon, the registers are clocked, and the new data is 'let through'.

4-Bit PIPO Shift Register

FLIP-FLOPS

Set-Reset flip-flops (SR flip-flops)

The symbol for SR latch

The most fundamental latch is the simple SR latch (or simple SR flip-flop), where S and R stand for set and reset. It can be constructed from a pair of cross-coupled NOR (negative OR) logic gates. The stored bit is present on the output marked Q.

Normally, in storage mode, the S and R inputs are both low, and feedback maintains the Q and Q outputs in a constant state, with Q the complement of Q. If S (Set) is pulsed high while R is held low, then the Q output is forced high, and stays high when S returns low; similarly, if R (Reset) is pulsed high while S is held low, then the Q output is forced low, and stays low when R returns low. SR latch operation SR 00 01 10 Action Keep state Q=0 Q=1

1 1 Unstable combination,

Toggle flip-flops (T flip-flops)

A circuit symbol for a T-type flip-flop, where > is the clock input, T is the toggle input and Q is the stored data output. If the T input is high, the T flip-flop changes state ("toggles") whenever the clock input is strobed. If the T input is low, the flip-flop holds the previous value. This behavior is described by the characteristic equation: (or, without benefit of the XOR operator, the equivalent: ) and can be described in a truth table: T Q Qnext Comment

0 0 0 1 1 0 1 1

0 1 1 0

hold state hold state toggle toggle

A toggle flip-flop composed of a single RS flip-flop becomes an oscillator, when it is clocked. To achieve toggling, the clock pulse must have exactly the length of half a cycle. While such a pulse generator can be built, a toggle flip-flop composed of two RS flipflops is the easy solution. Thus the toggle flip-flop divides the clock frequency by 2 ie. if clock frequency is 4 MHz, the output frequency obtained from the flip-flop will be 2 MHz. This 'divide by' feature has application in various types of digital counters.

JK flip-flop

JK flip-flop timing diagram The JK flip-flop augments the behavior of the SR flip-flop by interpreting the S = R = 1 condition as a "flip" or toggle command. Specifically, the combination J = 1, K = 0 is a command to set the flip-flop; the combination J = 0, K = 1 is a command to reset the flipflop; and the combination J = K = 1 is a command to toggle the flip-flop, i.e., change its output to the logical complement of its current value. Setting J = K = 0 does NOT result in a D flip-flop, but rather, will hold the current state. To synthesize a D flip-flop, simply set K equal to the complement of J. The JK flip-flop is therefore a universal flip-flop, because it can be configured to work as an SR flip-flop, a D flip-flop or a T flip-flop.

A circuit symbol for a JK flip-flop, where > is the clock input, J and K are data inputs, Q is the stored data output, and Q' is the inverse of Q. The characteristic equation of the JK flip-flop is:

and the corresponding truth table is: J K Qnext Comment 00 01 10 11 hold state reset set toggle

D flip-flop
The Q output always takes on the state of the D input at the moment of a rising clock edge, and never at any other time. [2] It is called the D flip-flop for this reason, since the output takes the value of the D input or Data input, and Delays it by one clock count. The D flip-flop can be interpreted as a primitive memory cell, zero-order hold, or delay line. Truth table: Clock D Q 0 1 Qprev X X

Rising edge 0 Rising edge 1

Non-Rising X constant ('X' denotes a Don't care condition, meaning the signal is irrelevant) These flip flops are very useful, as they form the basis for shift registers, which are an essential part of many electronic devices. The advantage of the D flip-flop over the D-

type latch is that it "captures" the signal at the moment the clock goes high, and subsequent changes of the data line do not influence Q until the next rising clock edge. An exception is that some flip-flops have a 'reset' signal input, which will reset Q (to zero), and may be either asynchronous or synchronous with the clock.

Master-slave D flip-flop
A master-slave D flip-flop is created by connecting two gated D latches in series, and invert the enable input to one of them. It is called master-slave because the second latch

in the series only changes in response to a change in the first (master) latch.

A master slave D flip flop. It responds on the negative edge of the enable input (usually a clock). For a positive-edge triggered master-slave D flip-flop, when the clock signal is low (logical 0) the “enable” seen by the first or “master” D latch (the inverted clock signal) is high (logical 1). This allows the “master” latch to store the input value when the clock signal transitions from low to high. As the clock signal goes high (0 to 1) the inverted “enable” of the first latch goes low (1 to 0) and the value seen at the input to the master latch is “locked”. Nearly simultaneously, the twice inverted “enable” of the second or “slave” D latch transitions from low to high (0 to 1) with the clock signal. This allows the signal captured at the rising edge of the clock by the now “locked” master latch to pass through the “slave” latch. When the clock signal returns to low (1 to 0), the output of the "slave" latch is "locked", and the value seen at the last rising edge of the clock is held while the “master” latch begins to accept new values in preparation for the next rising clock edge.

An implementation of a master-slave D flip-flop that is triggered on the positive edge of the clock. By removing the left-most inverter in the above circuit, a D-type flip flop that strobes on the falling edge of a clock signal can be obtained. This has a truth table like this: DQ > Qnext 0 1

0 X Falling 1 X Falling

Most D-type flip-flops in ICs have the capability to be set and reset, much like an SR flip-flop. Usually, the illegal S = R = 1 condition is resolved in D-type flip-flops. Inputs 0 1 X X 1 0 X X 1 1 X X Outputs Q' 1 0 1 0 1 1

S R D > Q

By setting S = R = 0, the flip-flop can be used as described above.

Edge-triggered D flip-flop

A more efficient way to make a D flip-flop is not as easy to understand, but it works the same way. While the master-slave D flip flop is also triggered on the edge of a clock, its

components are each triggered by clock levels. The "edge-triggered D flip flop" does not have the master slave properties.

A positive-edge-triggered D flip-flop.

Uses
   





A single flip-flop can be used to store one bit, or binary digit, of data. Static RAM, which is the primary type of memory used in registers to store numbers in computers and in many caches, is built out of flip-flops. Any one of the flip-flop types can be used to build any of the others. The data contained in several flip-flops may represent the state of a sequencer, the value of a counter, an ASCII character in a computer's memory or any other piece of information. One use is to build finite state machines from electronic logic. The flip-flops remember the machine's previous state, and digital logic uses that state to calculate the next state. The T flip-flop is useful for constructing various types of counters. Repeated signals to the clock input will cause the flip-flop to change state once per high-tolow transition of the clock input, if its T input is "1". The output from one flipflop can be fed to the clock input of a second and so on. The final output of the circuit, considered as the array of outputs of all the individual flip-flops, is a





count, in binary, of the number of cycles of the first clock input, up to a maximum of 2n -1, where n is the number of flip-flops used. See: Counters One of the problems with such a counter (called a ripple counter) is that the output is briefly invalid as the changes ripple through the logic. There are two solutions to this problem. The first is to sample the output only when it is known to be valid. The second, more widely used, is to use a different type of circuit called a synchronous counter. This uses more complex logic to ensure that the outputs of the counter all change at the same, predictable time. See: Counters Frequency division: a chain of T flip-flops as described above will also function to divide an input in frequency by 2 n, where n is the number of flip-flops used between the input and the output.

Introduction To AVR Microcontrollers
The AVRs are a family of RISC microcontrollers from Atmel. Their internal architecture was conceived by two students: Alf-Egil Bogen and Vegard Wollan, at the Norwegian Institute of Technology (NTH) and further developed at Atmel Norway, a subsidiary founded by the two architects. The AVR is a Harvard architecture machine with programs and data stored separately. Program instructions are stored in semi-permanent Flash memory which loads and manipulates data in the volatile SRAM. The AVRs have thirty-two single-byte registers. The registers, input/output ports, and static RAM make up the data address space. The working registers are mapped in as the first thirty-two memory spaces followed by the I/O ports. The actual usable RAM starts at memory location 100(hex). Atmel's AVRs have a two-stage pipeline design. The next machine instruction is fetched as the current one is executing. Most instructions take just one or two clock cycles, making AVRs relatively fast among the eight-bit microcontrollers. The AVRs were designed for the efficient execution of compiled C code. The AVR instruction set is not completely regular:  Pointer registers X, Y, and Z have addressing capabilities that are different from each other.  Register locations R0 to R15 have different addressing capabilities than register locations R16 to R31.  I/O ports 0 to 31 have different addressing capabilities than I/O ports 32 to 63.  CLR affects flags, while SER does not, even though they are complementary instructions. CLR set all bits to zero and SER sets them to one. AVRs have a large following due to the free and inexpensive development tools available, including reasonably priced development boards and free development software. They are marketed under various names that share the same basic core but with different peripheral and memory combinations. Compatibility amongst chips is fairly good. The acronym AVR has been reported to stand for Advanced Virtual RISC. It's also rumored to stand for the company's founders: Alf and Vegard. Current AVRs offer a wide range of features:  RISC Core Running Many Single-Cycle Instructions  Multifunction, Bi-directional I/O Ports with Internal, Configurable Pull-up Resistors  Internal Oscillators  Internal Instruction Flash Memory up to 256K  Internal Data EEPROM up to 4KB  Internal SRAM up to 8K

                  

8-Bit and 16-Bit Timers PWM Channels & dead time generator Lighting (PWM Specific) Controller models Dedicated I²C Compatible Two-Wire Interface (TWI) Synchronous/Asynchronous Serial Peripherals (UART/USART) (RS-232,RS485, and more) Serial Peripheral Interface (SPI) CAN Controller Support USB Controller Support Proper High-speed hardware & Hub controller with embedded AVR. Also freely available low-speed (HID) software emulation. Cheaper than a real USB interface chip. Ethernet Controller Support Universal Serial Interface for Two-Wire, Three-Wire Synchronous Data Transfer Analog Comparators 10-Bit A/D Converters, usually with 8-way multiplex Brownout Detection Watchdog Timer (WDT) Low-voltage Devices Operating Down to 1.8V Multiple Power-Saving Sleep Modes LCD Controller Support PIN Configuration

VCC GND

Digital supply voltage. Ground.

Port A (PA7..PA0) Port A serves as the analog inputs to the A/D Converter. Port A also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used. Port pins can provide internal pull-up resistors (selected for each bit). 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. Port B (PB7..PB0) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). Port B also serves the functions of various special features of the ATmega16.

Port C (PC7..PC0) Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). Port C also serves the functions of the JTAG interface.

Port D (PD7..PD0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). Port D also serves the functions of various special features of the ATmega16.

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. AVCC AVCC is the supply voltage pin for Port A and the A/D Converter. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. AREF AREF is the analog reference pin for the A/D Converter.

AVR Architecture The figure below shows the basic architecture of ATMega16 AVR microcontroller. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts.

Block Diagram of the AVR MCU Architecture In order to maximize performance and parallelism, the AVR uses Harvard architecture with separate memories and buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory. This concept enables instructions to be executed in every clock cycle. The program memory is InSystem Reprogrammable Flash memory. The fast-access Register file contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands are output from the Register file, the operation is executed, and the result is stored back in the Register file – in one clock cycle. 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 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 32bit instruction. Program Flash memory space is divided in two sections, the Boot program section and the Application Program section. 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. 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 as the 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 general purpose 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 bitfunctions. 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 executed arithmetic 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 Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. This must be handled by software.

The AVR Status Register – SREG – is defined as:

Bit 7 – I: Global Interrupt Enable The 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 Global Interrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. Bit 6 – T: Bit Copy Storage The 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 Flag The Half Carry Flag H indicates a half carry in some arithmetic operations. Half Carry is useful in BCD arithmetic. Bit 4 – S: Sign Bit, S = N xor V The S-bit is always an exclusive or between the negative flag N and the two’s complement overflow flag, V. Bit 3 – V: Two’s Complement Overflow Flag The Two’s Complement Overflow Flag V supports two’s complement arithmetics. Bit 2 – N: Negative Flag The Negative Flag N indicates a negative result in an arithmetic or logic operation. Bit 1 – Z: Zero Flag The Zero Flag Z indicates a zero result in an arithmetic or logic operation. Bit 0 – C: Carry Flag The Carry Flag C indicates a carry in an arithmetic or logic operation.

General Purpose Register File The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve 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

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. 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. 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 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 Stack Pointer must be set to point above $60. The Stack Pointer is decremented by one when data 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 data 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.

Reset and Interrupt Handling The AVR provides several different interrupt sources. These interrupts and the separate reset vector each have a separate program vector in the program memory space. All interrupts are assigned individual enable bits which must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the interrupt. The lowest addresses in the program memory space are by default defined as the Reset and Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 42. The list also determines the priority levels of the different interrupts. The lower the address the higher is the priority level. RESET has the highest priority, and next is INT0 – the External Interrupt Request 0. When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed. There are basically two types of interrupts: 1. The first type is triggered by an event that sets the interrupt flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. Interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding interrupt flag(s) will be set and remembered until the global interrupt enable bit is set, and will then be executed by order of priority.

2. The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have interrupt flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served.

Interrupt Vectors in ATmega16

Interrupt Response Time The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the program vector address for the actual interrupt handling routine is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack. The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If an interrupt occurs during

execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt execution response time is increased by four clock cycles. This increase comes in addition to the start-up time from the selected sleep mode. A return from an interrupt handling routine takes four clock cycles. During these four clock cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is incremented by two, and the I-bit in SREG is set.

System Clock and Clock Options

CPU Clock – clkCPU The CPU clock is routed to parts of the system concerned with operation of the AVR core. Examples of such modules are the General Purpose Register File, the Status Register and the data memory holding the Stack Pointer. Halting the CPU clock inhibits the core from performing general operations and calculations. I/O Clock – clk I/O The I/O clock is used by the majority of the I/O modules, like Timer/Counters, SPI, and USART. The I/O clock is also used by the External Interrupt module, but some external interrupts are detected by asynchronous logic, allowing such interrupts to be detected even if the I/O clock is halted.

Flash Clock – clkFLASH The Flash clock controls operation of the Flash interface. The Flash clock is usually active simultaneously with the CPU clock. Asynchronous Timer Clock – clkASY The Asynchronous Timer clock allows the Asynchronous Timer/Counter to be clocked directly from an external 32 kHz clock crystal. ADC Clock – clkADC The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks in order to reduce noise generated by digital circuitry. This gives more accurate ADC conversion results. Clock Sources 1. Crystal Oscillator : XTAL1 and XTAL2 are input and output, respectively, of an inverting amplifier which can be configured for use as an On-chip Oscillator. Either a quartz crystal or a ceramic resonator may be used. C1 and C2 should always be equal for both crystals and resonators. The optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment.

Low-frequency Crystal Oscillator 3. External RC Oscillator: For timing insensitive applications, the external RC configuration can be used.
2.

The Oscillator can operate in four different modes, each optimized for a specific frequency range. The operating mode is selected by the fuses CKSEL3..0

4. Calibrated Internal RC Oscillator: The Calibrated Internal RC Oscillator provides a fixed 1.0, 2.0, 4.0, or 8.0 MHz clock. All frequencies are nominal values at 5V and 25°C. This clock may be selected as the system clock by programming the CKSEL fuses.

5. External Clock: To drive the device from an external clock source, XTAL1 should be driven as shown below:

6. Timer/Counter Oscillator: For AVR microcontrollers with Timer/Counter Oscillator pins (TOSC1 and TOSC2), the crystal is connected directly between the pins. No external capacitors are needed. The Oscillator is optimized for use with a 32.768 kHz watch crystal.

Sleep Modes Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in addition to the start-up time; it

executes the interrupt routine, and resumes execution from the instruction following SLEEP. There are six different sleep modes available in AVR microcontrollers: 1. Idle Mode: In Idle mode, the CPU stops but SPI, USART, Analog Comparator, ADC, Two-wire Serial Interface, Timer/Counters, Watchdog, and the interrupt system continue operating. This sleep mode basically halts clk CPU and clk FLASH, while allowing the other clocks to run. Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the Timer Overflow and USART Transmit Complete interrupts. 2. ADC noise Reduction Mode: ADC Noise Reduction mode, stopping the CPU but allowing the ADC, the External Interrupts, the Two-wire Serial Interface address watch, Timer/Counter2 and the Watchdog to continue operating (if enabled). This sleep mode basically halts clk I/O , clkCPU, and clkFLASH, while allowing the other clocks to run. This improves the noise environment for the ADC, enabling higher resolution measurements. If the ADC is enabled, a conversion starts automatically when this mode is entered. Apart form the ADC Conversion Complete interrupt, only an External Reset, a Watchdog Reset, a Brown-out Reset, a Two-wire Serial Interface Address Match Interrupt, a Timer/Counter2 interrupt, an SPM/EEPROM ready interrupt, an External level interrupt on INT0 or INT1, or an external interrupt on INT2 can wake up the MCU from ADC Noise Reduction mode. 3. Power Down mode: In this mode, the External Oscillator is stopped, while the External interrupts, the Two-wire Serial Interface address watch, and the Watchdog continue operating (if enabled). Only an External Reset, a Watchdog Reset, a Brown-out Reset, a Two-wire Serial Interface address match interrupt, an External level interrupt on INT0 or INT1, or an External interrupt on INT2 can wake up the MCU. This sleep mode basically halts all generated clocks, allowing operation of asynchronous modules only. 4. Power Save Mode: This mode is identical to Power-down, with one exception: If Timer/Counter2 is clocked asynchronously, i.e., the AS2 bit in ASSR is set, Timer/Counter2 will run during sleep. The device can wake up from either Timer Overflow or Output Compare event from Timer/Counter2 if the corresponding Timer/Counter2 interrupt enable bits are set in TIMSK, and the Global Interrupt Enable bit in SREG is set. 5. Stand-by Mode: This mode is identical to Power-down with the exception that the Oscillator is kept running. From Standby mode, the device wakes up in six clock cycles.

6. Extended Stand-by Mode: This mode is identical to Power-save mode with the

exception that the Oscillator is kept running. From Extended Standby mode, the device wakes up in six clock cycles. To enter any of the six sleep modes, the SE bit in MCUCR must be written to logic one and a SLEEP instruction must be executed. The SM2, SM1, and SM0 bits in the MCUCR Register select which sleep mode (Idle, ADC Noise Reduction, Power-down, Powersave, Standby, or Extended Standby) will be activated by the SLEEP instruction. MCU Control Register – MCUCR The MCU Control Register contains control bits for power management.

 Bits 7, 5, 4 – SM2..0: Sleep Mode Select Bits 2, 1, and 0 These bits select between the six available sleep modes

 Bit 6 – SE: Sleep Enable The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed.

Reset Sources The ATmega16 has four sources of reset:

 Power-on Reset: The MCU is reset when the supply voltage is below the Poweron Reset threshold (VPOT).  External Reset: The MCU is reset when a low level is present on the RESET pin for longer than the minimum pulse length.  Watchdog Reset: The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled.  Brown-out Reset: The MCU is reset when the supply voltage VCC is below the Brown-out Reset threshold (VBOT) and the Brown-out Detector is enabled.

AVR ATMega16 Memories The AVR architecture has two main memory spaces, the Data Memory and the Program Memory space. In addition, the ATmega16 features an EEPROM Memory for data storage. All three memory spaces are linear and regular. In-System Reprogrammable Flash Program Memory The ATmega16 contains 16K 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 8K x 16. For software security, the Flash Program memory space is divided into two sections: Boot Program section and Application Program section. The Flash memory has an endurance of at least 10,000 write/erase cycles. The ATmega16 Program Counter (PC) is 13 bits wide, thus addressing the 8K program memory locations.

Program Memory Map

SRAM Data Memory

The first 96 locations address the Register file and I/O Memory, and the next 1024 locations address the internal data SRAM. The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Predecrement, and Indirect with Post-increment. In the Register file, registers R26 to R31 feature the indirect addressing pointer registers. The direct addressing reaches the entire data space. The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Z-register. When using register indirect addressing modes with automatic pre-decrement and post-increment, the address registers X, Y, and Z are decremented or incremented.

Data Memory Map EEPROM Data Memory The ATmega16 contains 512 bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. EEPROM Read/Write Access When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is executed. When the EEPROM is written, the CPU is halted for two clock cycles before the next instruction are executed. EEPROM Register Description 1. The EEPROM Address Register – EEARH and EEARL

 Bits 15..9 – Res: Reserved Bits These bits are reserved bits in the ATmega16 and will always read as zero.  Bits 8..0 – EEAR8..0: EEPROM Address The EEPROM Address Registers – EEARH and EEARL – specify the EEPROM address in the 512 bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 511. 2. The EEPROM Data Register – EEDR

 Bits 7..0 – EEDR7.0: EEPROM Data For the EEPROM write operation, the EEDR Register contains the data to be written to the EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by EEAR. 3. The EEPROM Control Register – EECR

 Bits 7..4 – Res: Reserved Bits These bits are reserved bits in the ATmega16 and will always read as zero.  Bit 3 – EERIE: EEPROM Ready Interrupt Enable Writing EERIE to one enables the EEPROM Ready Interrupt if the I bit in SREG is set. Writing EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates a constant interrupt when EEWE is cleared.  Bit 2 – EEMWE: EEPROM Master Write Enable

The EEMWE bit determines whether setting EEWE to one causes the EEPROM to be written. When EEMWE is set, setting EEWE within four clock cycles will write data to the EEPROM at the selected address If EEMWE is zero, setting EEWE will have no effect.  Bit 1 – EEWE: EEPROM Write Enable The EEPROM Write Enable Signal EEWE is the write strobe to the EEPROM. When address and data are correctly set up, the EEWE bit must be written to one to write the value into the EEPROM. The EEMWE bit must be written to one before a logical one is written to EEWE, otherwise no EEPROM write takes place.
 Bit 0 – EERE: EEPROM Read Enable

The EEPROM Read Enable Signal – EERE – is the read strobe to the EEPROM. When the correct address is set up in the EEAR register, the EERE bit must be written to a logic one to trigger the EEPROM read. The EEPROM read access takes one instruction, and the requested data is available immediately. When the EEPROM is read, the CPU is halted for four cycles before the next instruction is executed. The user should poll the EEWE bit before starting the read operation. If a write operation is in progress, it is neither possible to read the EEPROM, nor to change the EEAR register.

External Interrupts The External Interrupts are triggered by the INT0, INT1, and INT2 pins. The external interrupts can be triggered by a falling or rising edge or a low level. This is set up as indicated in the specification for the MCU Control Register – MCUCR – and MCU Control and Status Register – MCUCSR. When the external interrupt is enabled and is configured as level triggered (only INT0/INT1), the interrupt will trigger as long as the pin is held low. MCU Control Register – MCUCR The MCU Control Register contains control bits for interrupt sense control and general MCU functions.

 Bit 3, 2 – ISC11, ISC10: Interrupt Sense Control 1 Bit 1 and Bit 0 The External Interrupt 1 is activated by the external pin INT1 if the SREG I-bit and the corresponding interrupt mask in the GICR are set. The table below shows the sense control for INT1:

 Bit 1, 0 – ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0 The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding interrupt mask are set.

MCU Control and Status Register – MCUCSR

 Bit 6 – ISC2: Interrupt Sense Control 2 The Asynchronous External Interrupt 2 is activated by the external pin INT2 if the SREG I-bit and the corresponding interrupt mask in GICR are set. If ISC2 is written to zero, a falling edge on INT2 activates the interrupt. If ISC2 is written to one, a rising edge on INT2 activates the interrupt. General Interrupt Control Register – GICR

 Bit 7 – INT1: External Interrupt Request 1 Enable When the INT1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is enabled.

 Bit 6 – INT0: External Interrupt Request 0 Enable When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is enabled.  Bit 5 – INT2: External Interrupt Request 2 Enable When the INT2 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is enabled. General Interrupt Flag Register – GIFR

 Bit 7 – INTF1: External Interrupt Flag 1 When an edge or logic change on the INT1 pin triggers an interrupt request, INTF1 becomes set (one). If the I-bit in SREG and the INT1 bit in GICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed.  Bit 6 – INTF0: External Interrupt Flag 0 When an edge or logic change on the INT0 pin triggers an interrupt request, INTF0 becomes set (one). If the I-bit in SREG and the INT0 bit in GICR are set (one), the MCU will jump to the corresponding interrupt vector. The flag is cleared when the interrupt routine is executed.  Bit 5 – INTF2: External Interrupt Flag 2 When an event on the INT2 pin triggers an interrupt request, INTF2 becomes set (one). If the I-bit in SREG and the INT2 bit in GICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed.

Analog to Digital Converter Main Features of ATMega16 ADC:           10-bit Resolution 8 Multiplexed Single Ended Input Channels 7 Differential Input Channels 2 Differential Input Channels with Optional Gain of 10x and 200x(1) Optional Left adjustment for ADC Result Readout 0 - VCC ADC Input Voltage Range Selectable 2.56V ADC Reference Voltage Free Running or Single Conversion Mode ADC Start Conversion by Auto Triggering on Interrupt Sources Interrupt on ADC Conversion Complete

ADC Register Description
1. ADC Multiplexer Selection Register – ADMUX

 Bit 7:6 – REFS1:0: Reference Selection Bits These bits select the voltage reference for the ADC.If these bits are changed during a conversion, the change will not go in effect until this conversion is complete.

 Bit 5 – ADLAR: ADC Left Adjust Result The ADLAR bit affects the presentation of the ADC conversion result in the ADC Data Register. Write one to ADLAR to left adjust the result. Otherwise, the result is right adjusted.  Bits 4:0 – MUX4:0: Analog Channel and Gain Selection Bits The value of these bits selects which combination of analog inputs are connected to the ADC. These bits also select the gain for the differential channels.

2. ADC Control and Status Register A – ADCSRA

 Bit 7 – ADEN: ADC Enable Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off.

 Bit 6 – ADSC: ADC Start Conversion In Single Conversion mode, write this bit to one to start each conversion. In Free Running Mode, write this bit to one to start the first conversion.  Bit 5 – ADATE: ADC Auto Trigger Enable When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive edge of the selected trigger signal  Bit 4 – ADIF: ADC Interrupt Flag This bit is set when an ADC conversion completes and the Data Registers are updated.  Bit 3 – ADIE: ADC Interrupt Enable When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Interrupt is activated.  Bits 2:0 – ADPS2:0: ADC Prescaler Select Bits These bits determine the division factor between the XTAL frequency and the input clock to the ADC.

3. The ADC Data Register –ADCL and ADCH

When an ADC conversion is complete, the result is found in these two registers. If differential channels are used, the result is presented in two’s complement form. ADC Operation The ADC converts an analog input voltage to a 10-bit digital value.The minimum value represents GND and the maximum value represents the voltage on the AREF pin minus 1 LSB. Optionally, AVCC or an internal 2.56V reference voltage may be connected to the AREF pin by writing to the REFS n bits in the ADMUX Register. The internal voltage reference may thus be decoupled by an externalcapacitor at the AREF pin to improve noise immunity. The analog input channel and differential gain are selected by writing to the MUX bits in ADMUX. Any of the ADC input pins, as well as GND and a fixed bandgap voltage reference, can be selected as single ended inputs to the ADC. A selection of ADC input pins can be selected as positive and negative inputs to the differential gain amplifier. If differential channels are selected, the differential gain stage amplifies the voltage difference between the selected input channel pair by the selected gain factor. This amplified value then becomes the analog input to the ADC. If single ended channels are used, the gain amplifier is bypassed altogether. The ADC generates a 10-bit result which is presented in the ADC Data Registers, ADCH and ADCL. If the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read ADCH. Otherwise, ADCL must be read first, then ADCH, to ensure that the content of the Data Registers belongs to the same conversion. Once ADCL is read, ADC access to data registers is blocked. This means that if ADCL has been read, and a conversion completes before ADCH is read, neither register is updated and the result from the conversion is lost. When ADCH is read, ADC access to the ADCH and ADCL Registers is re-enabled.

Two-wire Serial Interface (TWI) Main Features of TWI:        Both Master and Slave Operation Supported Device Can Operate as Transmitter or Receiver 7-bit Address Space allows up to 128 Different Slave Addresses Up to 400 kHz Data Transfer Speed Noise Suppression Circuitry Rejects Spikes on Bus Lines Fully Programmable Slave Address with General Call Support Address Recognition causes Wake-up when AVR is in Sleep Mode

The Two-wire Serial Interface (TWI) is ideally suited for typical microcontroller applications. The TWI protocol allows the systems designer to interconnect up to 128 different devices using only two bi-directional bus lines, one for clock (SCL) and one for data (SDA). The only external hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All devices connected to the bus have individual addresses and mechanisms for resolving bus contention are inherent in the TWI protocol. Data Transfer and Frame Format The master initiates and terminates a data transmission. The transmission is initiated when the master issues a START condition on the bus, and it is terminated when the master issues a STOP condition. Between a START and a STOP condition, the bus is considered busy, and no other master should try to seize control of the bus. A special case occurs when a new START condition is issued between a START and STOP condition. This is referred to as a REPEATED START condition, and is used when the master wishes to initiate a new transfer without releasing control of the bus. After a REPEATED START, the bus is considered busy until the next STOP. START and STOP conditions are signaled by changing the level of the SDA line when the SCL line is high. A high to low transition on SDA while SCL is high generates START condition whereas a low to high transition on SDA with SCL held high indicates STOP condition.

Address Packet Format All address packets transmitted on the TWI bus are nine bits long, consisting of seven address bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read operation is to be performed; otherwise a write operation should be performed. When a slave recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL (ACK) cycle. If the addressed slave is busy, or for some other reason can not service the master’s request, the SDA line should be left high in the ACK clock cycle. The master can then transmit a STOP condition, or a REPEATED START condition to initiate a new transmission. An address packet consisting of a slave address and a READ or a WRITE bit is called SLA+R or SLA+W, respectively. The MSB of the address byte is transmitted first. Slave address 0000 000 is reserved for a general call. When a general call is issued, all slaves should respond by pulling the SDA line low in the ACK cycle. A general call is used when a master wishes to transmit the same message to several slaves in the system. When the general call address followed by a Write bit is transmitted on the bus, all slaves set up to acknowledge the general call will pull the SDA line low in the acknowledge cycle. The following data packets will then be received by all the slaves that acknowledged the general call.

Address Packet Format Data Packet Format All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and an acknowledge bit. During a data transfer, the master generates the clock and the START and STOP conditions, while the receiver is responsible for acknowledging the reception. An Acknowledge (ACK) is signaled by the receiver pulling the SDA line low during the ninth SCL cycle. If the receiver leaves the SDA line high, a NACK is signaled. The MSB of the data byte is transmitted first.

TWI Register Description 1. TWI Bit Rate Register – TWBR

 Bits 7..0 – TWI Bit Rate Register TWBR selects the division factor for the bit rate generator. The bit rate generator is a frequency divider which generates the SCL clock frequency in the Master modes. 2. TWI Control Register – TWCR

 Bit 7 – TWINT: TWI Interrupt Flag This bit is set by hardware when the TWI has finished its current job and expects application software response. If the I-bit in SREG and TWIE in TWCR are set, the MCU will jump to the TWI Interrupt Vector. While the TWINT flag is set, the SCL low period is stretched. The TWINT flag must be cleared by software by writing a logic one to it. Clearing this flag starts the operation of the TWI, so all accesses to the TWI Address Register (TWAR), TWI Status Register (TWSR), and TWI Data Register (TWDR) must be complete before clearing this flag.  Bit 6 – TWEA: TWI Enable Acknowledge Bit The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is written to one, the ACK pulse is generated on the TWI bus if the following conditions are met: 1. The device’s own slave address has been received. 2. A general call has been received, while the TWGCE bit in the TWAR is set. 3. A data byte has been received in Master Receiver or Slave Receiver mode.  Bit 5 – TWSTA: TWI START Condition Bit TWSTA bit is written to one to generate START condition in master mode. The TWI hardware checks if the bus is available, and generates a START condition on the bus if it is free. However, if the bus is not free, the TWI waits until a STOP condition is detected, and then generates a new START condition to claim the bus Master status. TWSTA is cleared by the TWI hardware when the START condition has been transmitted.

 Bit 4 – TWSTO: TWI STOP Condition Bit Writing the TWSTO bit to one in Master mode will generate a STOP condition on the Two-wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO bit is cleared automatically.  Bit 3 – TWWC: TWI Write Collision Flag The TWWC bit is set when attempting to write to the TWI Data Register – TWDR when TWINT is low.  Bit 2 – TWEN: TWI Enable Bit The TWEN bit enables TWI operation and activates the TWI interface.  Bit 1 – Res: Reserved Bit This bit is a reserved bit and will always read as zero.  Bit 0 – TWIE: TWI Interrupt Enable When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request will be activated for as long as the TWINT flag is high. 3. TWI Status Register – TWSR

 Bits 7..3 – TWS: TWI Status These five bits reflect the status of the TWI logic and the Two-wire Serial Bus. The value read from TWSR contains both the 5-bit status value and the 2-bit prescaler value. The prescaler bits are masked to zero when checking the Status bits. This makes status checking independent of prescaler setting.  Bit 2 – Res: Reserved Bit This bit is reserved and will always read as zero.  Bits 1..0 – TWPS: TWI Prescaler Bits These bits can be read and written, and control the bit rate prescaler.

4. TWI Data Register – TWDR

In Transmit mode, TWDR contains the next byte to be transmitted. In Receive mode, the TWDR contains the last byte received. 5. TWI (Slave) Address Register – TWAR

 Bits 7..1 – TWA: TWI (Slave) Address Register These seven bits constitute the slave address of the TWI unit.  Bit 0 – TWGCE: TWI General Call Recognition Enable Bit If set, this bit enables the recognition of a General Call given over the Two-wire Serial Bus.

Different Modes of TWI: 1. Master Transmitter Mode In the Master Transmitter mode, a number of data bytes are transmitted to a slave receiver. In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, Master Transmitter mode is entered, if SLA+R is transmitted, Master Receiver mode is entered. Step1: Start Condition A START condition is sent by writing the following value to TWCR:

TWEN must be set to enable the Two-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be written to one to clear the TWINT flag. The TWI will then test the Two-wire Serial Bus and generate a START condition as soon as the bus becomes free. After START

condition has been transmitted, the TWINT flag is set by hardware, and the status code in TWSR will be $08. Step2: Slave address + W bit SLA+W is transmitted by writing SLA+W to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR:

When SLA+W have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in master transmitter mode are: $18: indicates that SLA+W has been transmitted; ACK has been received. $20: indicates SLA+W has been transmitted; NOT ACK has been received $38: Arbitration lost in SLA+W Step3: Transmission of Data byte When SLA+W has been successfully transmitted, a data packet should be transmitted. This is done by writing the data byte to TWDR. TWDR must only be written when TWINT is high. If not, the access will be discarded, and the Write Collision bit (TWWC) will be set in the TWCR register. After updating TWDR, the TWINT bit should be cleared (by writing it to one) to continue the transfer. Different Status codes are possible after the data byte has been transmitted: $28: indicates that data byte has been transmitted; ACK has been received. $30: indicates that data byte has been transmitted; NOT ACK has been received $38: Arbitration lost in data byte transmission This scheme is repeated until the last byte has been sent. Step4: The transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR:

A REPEATED START condition is generated by writing the following value to TWCR:

2. Master Receiver Mode In the Master Receiver mode, a number of data bytes are received from a slave transmitter. In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, Master Transmitter mode is entered, if SLA+R is transmitted, Master Receiver mode is entered. Step1: Start Condition A START condition is sent by writing the following value to TWCR:

TWEN must be set to enable the Two-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be written to one to clear the TWINT flag. The TWI will then test the Two-wire Serial Bus and generate a START condition as soon as the bus becomes free. After START condition has been transmitted, the TWINT flag is set by hardware, and the status code in TWSR will be $08. Step2: Slave address + R bit SLA+R is transmitted by writing SLA+R to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR:

When SLA+R have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in master receiver mode are: $40: indicates that SLA+R has been transmitted; ACK has been received. $48: SLA+R has been transmitted; NOT ACK has been received. $38: Arbitration lost in SLA+R.

Step3: Read data byte When SLA+R has been successfully transmitted, received data is read from the TWDR register when the TWINT flag is set high by hardware. This scheme is repeated until the last byte has been received. After the last byte has been received, the Master Receiver should inform the ST by sending a NACK after the last received data byte. Different Status codes are possible after the data byte has been received: $50: Data byte has been received; ACK has been returned. $58: Data byte has been received; NOT ACK has been returned Step4: STOP condition The transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR:

A REPEATED START condition is generated by writing the following value to TWCR:

After a repeated START condition (state $10) the Two-wire Serial Interface can access the same slave again, or a new slave without transmitting a STOP condition. Repeated START enables the master to switch between slaves, Master Transmitter mode and Master Receiver mode without losing control over the bus.

Project Report
Aim:Display current temperature, day, date, time, month and year on a 16x2 LCD using ATMEL Mega16 AVR microcontroller.

Components Used:            ATMEL MEGA16 AVR microcontroller RTC (Real Time Clock) – DS1307 Temperature Sensor – LM35 LCD 16x2 10k potentiometer Resistors 100K (x 2) 4 legged switches (x3) Crystal Oscillator (32.768 kHz) PCB Connecting Wires Button Cells (3V) Power Supply (5V)

Circuit Diagram:-


				
DOCUMENT INFO
Description: to display reat time , date, temperature on LCD display using AVR microcontroller