You are on page 1of 99

AVR Micro Controller

Presented by ABDUL SATHAR .M

Agenda
Introduction to Micro controllers Traditional Technologies in micro controller Proposed Technologies in Micro controller Introduction to AVR Micro controllers Introduction to ATMEGA128 Micro controllers Getting Started Programming

Introduction to Micro controllers

Embedded Systems
An embedded system is a special-purpose computer system designed to perform one or a few dedicated functions. The computer on one hand is designed to perform all the general purpose tasks on a single machine like you can use a computer to run a software to perform calculations or you can use a computer to store some multimedia file or to access INTERNET through the browser. whereas the micro controllers are meant to perform only the specific tasks. for e.g., switching the AC off automatically when room temperature drops to a certain defined limit and again turning it ON when temperature rises above the

Computer

Micro Controller

Processor And Controller Families


There are number of popular families of micro controllers which are used in different applications as per their capability and feasibility to perform the desired task. Most common of these are 8051, AVR micro controllers. In this article we will introduce you with AVR family of micro controllers

Processor Familes

Processor Familes

Controller Familes

Continue..

Micro controller

Micro controller Applications


Engine management systems in automobiles. Keyboard of a PC. Electronic measurement instruments (such as digital multimeters, frequency synthesisers, and oscilloscopes) Printers. Mobile phones. Televisions, radios, CD players, tape recording equipment. Hearing aids.

Security alarm systems, fire alarm systems, and building services systems.

Traditional Technologies in Micro controller

Traditional Micro controllers


As microprocessors and Controllers(8051) evolved, devices increased in complexity with new hardware and new instructions to accomplish new tasks. These microprocessors became known as CISC or Complex Instruction Set Computing. Complex is often an understatement; some of the CISCs that Ive worked with have mind-numbingly complex instruction sets. Some of the devices have so many instructions that it becomes difficult to figure out the most efficient way to do anything that isnt built into the hardware.

Classification Of Architecture Of Micro controllers

Difference between data and program memory


When the program is compiled and linked different parts of the program is organised in seperate segments. That is our code will be in one segment, code means the instructions to be excuted this is called as code segment or program memory this is usually readonly. Then there are datas which on which the code operates,these datas get stored in segment called data segment or datamemory.. Stack memory is a part of programs memory which will be used as stack in case of function calls to store the IP and parameters variables of the current function. The three types of memory are owned by the program memory, like datamemory,program memory,stack memory...

Disadvantages of Von Neumann Architecture


Because memory is common to data and instructions, the whole execution process is slower because two memory accesses need to be made: first to access data, and then to access the instruction (or opposite). Slower Process

What is CISC?
CISC is an acronym for Complex Instruction Set Computer and are chips that are easy to program and which make efficient use of memory.. Most common microprocessor designs such as the Intel 80x86 and Motorola 68K series followed the CISC philosophy. CISC was developed to make compiler development simpler. It shifts most of the burden of generating machine instructions to the processor. For example, instead of having to make a compiler write long machine instructions to calculate a square-root, a CISC processor would have a built-in ability to do this.

CISC Problems
Rarely used high-level instructions Sometimes slower than equivalent sequence Pipelining lower clock rates Interrupt handling can complicate even more

Proposed Technologies in Microcontroller

Separate instruction and data paths Simultaneous accesses to instructions & data Hardware can be optimized for access type and bus width.

RISC
Reduced instruction set Computing . Less complex, simple instructions. Hardwired control unit and machine instructions. Few addressing schemes for memory operands. LOAD and STORE Many symmetric registers which are organized into a register file. Single-clock for Instruction Execution.

Machine Cycle

Basic five-stage pipeline in a RISC machine (IF = Instruction Fetch, ID = Instruction Decode, EX = Execute, MEM = Memory access, WB = Register write back). The vertical axis is successive instructions; the horizontal axis is time. So in the green column, the earliest instruction is in WB stage, and the latest instruction is undergoing instruction fetch.

RISC Disadvantages

There is still considerable controversy among experts about the ultimate value of RISC architectures. Its proponents argue that RISC machines are both cheaper and faster, and are therefore the machines of the future. However, by making the hardware simpler, RISC architectures put a greater burden on the software.

CISC versus RISC


CISC
Emphasis on hardware Includes multi-clock complex instructions Memory-to-memory: "LOAD" and "STORE" incorporated in instructions Small code sizes, high cycles per second Transistors used for storing complex instructions

RISC
Emphasis on software Single-clock, reduced instruction only Register to register: "LOAD" and "STORE" are independent instructions Low cycles per second, large code sizes Spends more transistors on memory registers

Multiplying Two Numbers in Memory

The CISC Approach


MOV R0, 2:3 MOV R1, 5:2 MOV A, R1 MOV A,RO MULT R3,A

The RISC Approach


LOAD A, 2 LOAD B, 5 PROD A, B STORE A

Introduction to AVR Micro controllers

What does AVR mean?


The acronym AVR has been reported to stand for: Advanced Virtual RISC Alf-Egil Bogen and Vegard Wollan Reduced instruction set computing. who designed the basic architecture at the Norwegian Institute of Technology. Atmel Version Risc Based Microcontroler ..by ATMEL

Modified Harvard architecture 8-bit RISC single chip micro controller Complete System-on-a-chip
On Board Memory (FLASH, SRAM & EEPROM) On Board Peripherals

Advanced (for 8 bit processors) technology Developed by Atmel in 1996

TinyAVR Less memory, small size, suitable only for simpler applications MegaAVR These are the most popular ones having good amount of memory (upto 256 KB), higher number of inbuilt peripherals and suitable for moderate to complex applications. XmegaAVR Used commercially for complex applications, which require large program memory and high speed.

Continue..
Flash Memory 0.5-8 KB Special Feature Small in size

Series Name TinyAVR

Pins 6-32

MegaAVR

28-100

4-256KB

Extended peripherals

XmegaAVR

44-100

16-384KB

Event System included DMA

Comparison of AVR series of Micro controllers:


Compare with 8051 micro controller executes the instructions in single execution cycle(RISC). AVRs are about 4 times faster than PICs, they consume less power and can be operated in different power saving modes. AVR is much faster than PIC. AVR runs a full clock speed so a 16 MHz AVR performs almost 16 MIPS. PICs divide the clock by 4, so a 20 MHz PIC performs under 5 MIPS.

Continue..
C compilers for AVR produces normally more compact code than PIC C compilers, because the AVR architecture is designed specially to work well with C compilers. Lets do the comparison between the three most commonly used families of micro controllers

Comparison of Existing Controllers over AVR


SPEED MEMORY ARCHITECT URE ADC Timers PWM Channels 8051 Slow Small CISC Not Present Inbuilt Not Present PIC Moderate Large RISC Inbuilt Inbuilt Inbuilt AVR Fast Large RISC Inbuilt Inbuilt Inbuilt

Introduction to AVR ATMEGA 128

AVR ATMEGA 128

ATmega128 Features
CPU: 8 bit, 16 MHz 133 RISC instructions Typically 1 clk/instruction Memory: 128K Flash (program) 4K EEPROM + 4K internal SRAM (data) 32 register

43

AVR block diagram

44

Ports and Port Pins

4 I/O ports: Port A, B, C, D,E,F,G also denoted as PA, PB, PC, PD,PE,PF,PG Each port has 8 lines that can be independently set as H/L Each of the 8 lines can be configured independently as an input or an output pin The above feature is called True Read Modify Write Functionality Pin drivers are strong enough to drive LEDs directly All pins have voltage invariant internal pull up resistors Each of them can be individually pulled up as H/L

ATmega128 programming
AVR: Atmel RISC processor family,
ATmega128: AVR processor 128K flash memory (Advanced Virtual RISC)

Development tool: AVRStudio


Assembly s C language (AVR-GCC, WinAVR) Programming (ISP, In System Programming) and debug (JTAG-ICE, In
Circuit Emulation)

46

Peripheral Features
128Kbytes of In-System Self-programmable Flash program memory 4Kbytes EEPROM 4Kbytes Internal SRAM Write/Erase cycles: 10,000 Flash/100,000 EEPROM Data retention: 20 years at 85C/100 years at 25C(1) Optional Boot Code Section with Independent Lock Bits In-System Programming by On-chip Boot Program True Read-While-Write Operation

Continue..
Up to 64Kbytes Optional External Memory Space Programming Lock for Software Security SPI Interface for In-System Programming Two 8-bit Timer/Counters with Separate Prescalers and Compare Modes Two Expanded 16-bit Timer/Counters with Separate Prescaler, Compare Mode and Capture Mode Real Time Counter with Separate Oscillator Two 8-bit PWM Channels

Continue..
6 PWM Channels with Programmable Resolution from 2 to 16 Bits Output Compare Modulator 8-channel, 10-bit ADC Byte-oriented Two-wire Serial Interface Dual Programmable Serial USARTs Master/Slave SPI Serial Interface Programmable Watchdog Timer with On-chip Oscillator On-chip Analog Comparator

Special Micro controller Features


Power-on Reset and Programmable Brown-out Detection Internal Calibrated RC Oscillator External and Internal Interrupt Sources Six Sleep Modes: Idle, ADC Noise Reduction, Powersave, Power-down, Standby, and Extended Standby Software Selectable Clock Frequency ATmega103 Compatibility Mode Selected by a Fuse

Continue
Global Pull-up Disable I/O and Packages 53 Programmable I/O Lines 64-lead TQFP and 64-pad QFN/MLF Operating Voltages 2.7 - 5.5V ATmega128L 4.5 - 5.5V ATmega128 Speed Grades 0 - 8MHz ATmega128L 0 - 16MHz ATmega128

Non-volatile program space storage 0.5-128 K Bit width At least 10,000 write/erase cycles

32 Registers 64 I/O Registers 160 External I/O Reg Internal SRAM (512/1024/2048x8)

0x0000 0x001F 0x0020 0x005F

0x00060 0x00FF
0x0100

0x04FF/0x6FF/0x8FF

External SRAM

Electrically Erasable Programmable Read Only Memory 8 bit width Requires special write sequence Non-volatile storage for program specific data, constants, etc. At least 100,000 write/erase cycles

Clock control module generates clocks for memory and IO devices Multiple internal clock sources Provisions for external crystal clock source (max 20 MHz) Default is internal RC 8 MHz oscillator with 8 prescale yielding 1 MHz CPU clock Default is only 5-10% accurate

Multiple power down modes


Power down mode
Wake on external reset or watchdog reset

Power save mode


Wake on timer events

Several standby modes

Unused modules can be shut down

Power on reset External reset Watchdog system reset Brown out detect (BOD) reset

Atmel Atmega128 Overview


Serial Interfaces SPI (Serial Peripheral Interface) -full duplex, three wire interface -MSB first or last, programmable bit rates to clock/2

Universal Synchronous and Asynchronous serial Receiver and Transmitter High Resolution Baud Rate Generator Can provide serial terminal interface -2 identical and separate units, USART0, USART1 -full duplex serial communications -programmable number of bits, parity, stop bit, error detection -interrupt on tx done, rx ready, or tx register empty

USART

Atmel Atmega128 Overview


Serial Interfaces USART0,1

I2C
Serial Interfaces TWI (two wire interface) -half duplex serial communications -7 bit device addressing -multi-master operation -400khz data rate -I2C compatible

Some chips have JTAG interface


Industry standard for debugging chips in circuit Connect to special JTAG signals Can program
FLASH EEPROM All fuses Lock bits

ISP (In-System Programmer) Connect to 6 or 10 pin connector SPI interface Special cable required
Can program
FLASH EEPROM Some fuses Lock bits

Choose a language
BASCOM C/C++ Assembler (machine language)

Choose a platform
Linux Windows

Text Editor / IDE Tool Chain


Compiler Libraries

Programmer (cable & software)

Linux
AVR-GCC
Based on GNU toolset Open Source AVR-LIBC libraries

Windows
WIN-AVR
Port of AVR-GCC to Windows

Linux
Editors & command line tools Eclipse IDE

Windows
Atmel AVR Studio
Includes ISP programming support

Eclipse IDE

STK 200/300/400/500
Atmel AVR starter kit and development system Interfaces to AVR Studio

avrdude
Programming support for all memories

ATmega 48/88/128/328 ATmega 164/324/644/1284

JTAG interface All 4 IO Ports A,B,C & D More memory

PDIP Plastic Dual In-line Package TQFP Thin Quad Flat Pack MLF MicroLeadFrame
28 & 32 pin

www.atmel.com www.polulu.com http://winavr.sourceforge.net www.avrfreaks.net www.wrighthobbies.net www.eclipse.org Just Google AVR

Programming

Compiling
C code
Preprocessor C source (makros (#define; #include)
gcc E prog.c

Compiler Assembly code (architecture dependant, optimized)


gcc S prog.c

Assembler

Object code
Linker

Libraries

Executable

(.com, .exe, ELF)

LED

LED
Almost all digital ports of the ATmega128 can be individually configured for input or output. Three registers are used to control or monitor each port.
Port register When the port is configured for output, we can clear each bit to drive the corresponding output low or set the bit to drive it high. Pin register When the port is configured for input, then each bit reflects the status at the corresponding input pin. The bit is zero, when the input is low or set if the input is driven high. Data direction register This register is used to configure the mode of each port pin. When the bit is set, then the port pin works in output mode.

I/O ports
direction DDRx value Output value / pullup PORTx value

DDRx

PORTx

(out/) input value

PINx

79

Registers Associated With Ports


Each port is associated with 3 registers: The data registers (PORTa), the data direction register (DDRa) and the Input pin register (PINa) Each port pin, PA3 for eg, is associated with 3 pins: DDa3, PORTa3, PINa3 While programming the letters are capped.

LED Program sample


#include<avr/io.h> #include<util/delay.h // This is for using the _delay_ms() function.
int main() // Execution Starts here { DDRC = 0b00000001; // DDR is used to set the I/O 0-> Input 1-> Output ... here PC0 is set as output. PORTC = 0; // This initialises the port pins while(1) // Infinite Loop { PORTC = PORTC ^ 0b00000001; //Used to assign the status of the pin _delay_ms(500); // Delay of 500 milli Seconds };

LCD

Peripheral Programming
Important Registers to be considered while using peripherals Control register Used to specify mode of operation, control interrupts Status register Contains interrupt flags and other flags indicating state of operation Data register Contains end data,finished results

LCD Program Example


#include "lcd.h main() { unsigned char ch,str[32]; ch='A; str[32]="ABDUL"; while(1) { lcd_putchar(ch); lcd_string(str); }}

Header file
void delay(unsigned int m); void lcd_init(void); void lcd_cmd(unsigned char cmd); void toggleE(void); void lcd_char(unsigned char single); void lcd_string(unsigned char str[32]); void lcd_showvalue(unsigned char a); void lcd_gotoxy1(unsigned char pos); void lcd_gotoxy2(unsigned char pos);

String
void lcd_string(unsigned char str[32]) { unsigned char k=0; CLEARBIT(PORTC,BITS(2)); { if(k==16) { lcd_cmd(LINE2); } PORTC=((str[k])&0xF0)|(PORTC & (BITS(3)+BITS(1))); SETBIT(PORTC,BITS(0)); toggleE(); PORTC=((str[k]&(0x0F))*16)|(PORTC & (BITS(3)+BITS(1))); SETBIT(PORTC,BITS(0)); toggleE(); k++; } } // selects data register RS=1 // selects data register RS=1 // Disable the LCD while(str[k]!='\0') //Till null character is encountered

character
void lcd_putchar(unsigned char sig) { PORTC=((str[k])&0xF0)|(PORTC & (BITS(3)+BITS(1))); SETBIT(PORTC,BITS(0)); // selects data register RS=1 toggleE(); PORTC=((str[k]&(0x0F))*16)|(PORTC & (BITS(3)+BITS(1))); SETBIT(PORTC,BITS(0)); // selects data register RS=1 toggleE(); }

INIT
void lcd_init(void) //init the lcd { DDRC=0xFF; delay(15); lcd_cmd(0x03); delay(15); lcd_cmd(0x02); delay(15); CLEARBIT(PORTC,(BITS(0)+BITS(2))); // RS to 0 means select COmmand register, E to 0 .. lcd_cmd(0x01); lcd_cmd(0x0F); lcd_cmd(0x02); lcd_cmd(LINE1); delay(15); } // Cmd for clear display // Cmd for display ON and cursor blinking // Cmd for returning home // declare it as an o/p port // Given in datasheet ( Cmd for selecting 4 bit mode )

number
unsigned char p,q,r; void lcd_showvalue(unsigned char a) {

p=a/100;
q=a%100; q=q/10; r=a%10; if(p!=0) lcd_char(p+48); lcd_char(q+48); lcd_char(r+48);

Latch
void toggleE(void) { delay(100); SETBIT(PORTC,BITS(2)); delay(100); CLEARBIT(PORTC,BITS(0)); }

command
void lcd_cmd(unsigned char cmd) { CLEARBIT(PORTC,(BITS(0)+BITS(2))); // RS to 0 means select COmmand register, E to 0 .. PORTC=(cmd&0xF0)|((PORTC & (BITS(3)+BITS(1))); toggleE(); PORTC=((cmd&(0x0F))*16)|((PORTC & (BITS(3)+BITS(1))); toggleE(); }

UART

Uart
#include<avr/io.h> #include "uart.h" int main(void) { unsigned char ch; uart_init(); while(1) { uart_str("\n\rSTART MAIN "); uart_str("\n\rPress any key ..."); ch = uart_rx(); uart_tx(ch); } } /* read a character from UART */ /* write a character from UART */

uart_str("\n\rEND OF MAIN");

init
void uart_init(void) { UBRR1H=0; UBRR1L=0x0067;//9600 BAUDE RATE UCSR1C|=(1<<UCSZ1)|(1<<UCSZ0);// O BIT DATA ,1 STOP BIT ,NO parity UCSR1B|=(1<<RXEN)|(1<<TXEN);//ENABLE RECEPTION AND TRANSMISSION }

UART rx
unsigned char uart_rx( void ) { while (!(UCSR1A & (1<<RXC))); /* Wait for data to be received */
return UDR1; /* Get and return received data from buffer */ }

Uart_tx
void uart_tx( unsigned char data ) { while (!(UCSR1A & (1<<UDRE))); /* Wait for empty transmit buffer */

UDR1 = data; /* Put data into buffer, sends the data */ }

string
void uart_str(unsigned char *Mystr_ptr) { while((*Mystr_ptr) != '\0') /* print char from str pointer and point to next location */ uart_tx((*Mystr_ptr++)); }