Flash MCU Workshop Atmel Korea Flash MCU Workshop Goals • Detailed Architecture Knowledge • Hands on experience with the AVR Tools – IAR Assembler and C-Compiler – AVR Studio – AVR Emulator • Design your own AVR Beer Altimeter Flash MCU AVR Presentation • Architecture • Instruction set • Peripherals Flash MCU Key Features • • • • • • • Highest Performance 8-Bit MCU Real RISC Architecture 32 Registers, 2-Address Machine, Single Cycle Execution Low Power 8 MB Direct Address Reach Fast Context Switching Efficient C Language Code Density RISC Performance with CISC Code Density Flash MCU Breaking Traditions Code Density Traditional CISC Traditional RISC Speed Flash MCU AVR Architecture An introduction to the MCU Flash MCU Block Diagram Flash MCU Register File R0 R1 R2 R3 R26 R27 R28 R29 R30 R31 XL XH YL YH ZL ZH Register File X Pointer Y Pointer Z Pointer Flash MCU Direct Register - ALU Connection Register operations take ONE clock pulse on the EXTERNAL clock input Register File ALU Flash MCU Execute 2 Instructions 1 2 PIC 1 HC05 1 ‘C51 1 Done! 2 Done! 2 Done! 2 Done! Flash MCU A C-Code Example The following example illustrates how the AVR benefits in terms of: Code Size Throughput Power Consumption Flash MCU A Small C Function /* Return the maximum value of a table of 16 integers */ int max(int *array) { char a; int maximum=-32768; for (a=0;a<16;a++) if (array[a]>maximum) maximum=array[a]; return (maximum); } Flash MCU AVR Assembly output ; 7. for (a=0;a<16;a++) LDI R18,LOW(0) LDI R19,128 CLR R22 LDD LDD CP CPC BRGE ?0001: ; 8. ; 9. CPI R22,LOW(16) BRCC ?0000 { if (array[a]>maximum) MOV R30,R22 CLR R31 LSL R30 ROL R31 ADD R30,R16 ADC R31,R17 MOV MOV R20,Z+0 R21,Z+1 R18,R20 R19,R21 ?0005 maximum=array[a]; R18,R20 R19,R21 INC RJMP R22 ?0001 ; 10. ?0005: ?0000: ; 11. ; 12. ; 13. } return (maximum); MOV R16,R18 MOV R17,R19 } RET Code Size: 46 Bytes, Execution time: 335 cycles Flash MCU C51 Assembly Output ; FUNCTION _max (BEGIN) ;---- Variable 'array' assigned to Register 'R1/R2/R3' ---; SOURCE LINE # 4 ; SOURCE LINE # 5 ; SOURCE LINE # 7 MOV maximum,#080H MOV maximum+01H,#00H ; SOURCE LINE # 9 ;---- Variable 'a' assigned to Register 'R5' ---CLR A MOV R5,A ?C0001: ; SOURCE LINE # 10 ; SOURCE LINE # 11 MOV A,R5 MOV R7,A RLC A SUBB A,ACC MOV R6,A MOV A,R7 ADD A,ACC MOV R7,A MOV A,R6 RLC A MOV DPL,R7 MOV DPH,A LCALL ?C?ILDOPTR MOV R7,A MOV R6,B SETB C SUBB A,maximum+01H MOV A,maximum XRL A,#080H MOV R0,A MOV A,R6 XRL A,#080H SUBB A,R0 JC ?C0003 ; SOURCE LINE # 12 MOV maximum,R6 MOV maximum+01H,R7 ; SOURCE LINE # 13 ?C0003: INC R5 CJNE R5,#010H,?C0001 ?C0002: ; SOURCE LINE # 14 MOV MOV R6,maximum R7,maximum+01H ; SOURCE LINE # 15 ?C0005: RET ; FUNCTION _max (END) ?C?ILDOPTR: CJNE R3,#0x01,0x195 MOV A,0x82 ADD A,R1 MOV 0x82,A MOV A,0x83 ADDC A,R2 MOV 0x83,A MOVX A,@DPTR MOV OxF0,A INC DPTR MOVX A,@DPTR RET JNC 0x1A0 MOV A,R1 ADD A,0x82 MOV R0,A MOV 0xF0,@R0 INC R0 MOV A,@R0 RET CJNE R3,#0xFE,0xAD MOV A,R1 ADD A,0X82 MOV R0,A MOV A,@R0 MOV 0xF0,A INC R0 RET MOV A,0X83 ADD A,R2 MOV 0X83,A MOV A,R1 MOVC A,@A+DPTR RET Code Size: 112 Bytes, Execution time: 9384 cycles Flash MCU HC11 Assembly output ; 7. for (a=0;a<16;a++) TSX LDD #-32768 STD 1,X CLR 0,X ?0001: ; 8. ; 9. STD 5,X INS INS CPD BLE STD 3,X ?0005 maximum=array[a]; 3,X TSX INC BRA 0,X ?0001 ; 10. LDAA 0,X CMPA #16 BHS ?0000 { if (array[a]>maximum) PSHY TAB CLRA LSLD TSX ADDD 0,X XGDX LDD 0,X TSX ?0005: ?0000: ; 11. ; 12. ; 13. } return (maximum); LDD 1,X } PULX PULX INS PULY RTS Code Size: 57 Bytes, Execution time: 5244 cycles Flash MCU PIC16C74 Assembly output bcf 3,5 movwf ?a_maxnum& (0+127) ;MAX_MAIN.C: 4: char a; ;MAX_MAIN.C: 5: int maximum=-32768; clrf (?a_maxnum+2)& (0+127) movlw 128 movwf (?a_maxnum+3)& (0+127) ;MAX_MAIN.C: 7: for (a=0;a<16;a++) clrf (?a_maxnum+1)& (0+127) l2 ;MAX_MAIN.C: 8: { ;MAX_MAIN.C: 9: if (array[a]>maximum) bcf 3,5 movf (?a_maxnum+1)& (0+127),w addwf (?a_maxnum+1)& (0+127),w addwf ?a_maxnum& (0+127),w movwf 4 movf 0,w movwf btemp incf 4 movf 0,w movwf btemp+1 movf (?a_maxnum+3)& (0+127),w xorlw 128 movwf btemp+2 movf btemp+1,w xorlw 128 subwf btemp+2,w btfss 3,2 goto u15 movf btemp,w subwf (?a_maxnum+2)& (0+127),w u15 btfsc 3,0 goto l5 ;MAX_MAIN.C: 10: maximum=array[a]; bcf 3,5 movf (?a_maxnum+1)& (0+127),w addwf (?a_maxnum+1)& (0+127),w addwf ?a_maxnum& (0+127),w movwf 4 movf 0,w movwf (?a_maxnum+2)& (0+127) incf 4 movf 0,w movwf (?a_maxnum+3)& (0+127) l5 ;MAX_MAIN.C: 11: } bcf 3,5 incf (?a_maxnum+1)& (0+127) movlw 16 subwf (?a_maxnum+1)& (0+127),w btfss 3,0 goto l2 ;MAX_MAIN.C: 12: return (maximum); bcf 3,5 movf (?a_maxnum+3)& (0+127),w movwf btemp+1 movf (?a_maxnum+2)& (0+127),w movwf btemp return Code Size: 87 Bytes, Execution time: 2492 cycles Flash MCU Some Conclusions on THIS Case • The C51 would have to run at 224 MHz to match the 8 MHz AVR. • The HC11 is quite code efficient, but delivers only one 16th of the processing power at more than twice the current consumption • The PIC is a fast microcontroller, but the AVR delivers more than 3.5 times higher throughput per mW. Flash MCU What made the AVR do better? • Excellent support for 16-bit arithmetic's. (Zero-Flag Propagation on Compare) • A lot of registers which eliminate move to and from SRAM • Single Cycle execution Flash MCU AVR Microcontrollers Which AVR Devices are available today? Flash MCU Current AVR Product Line ‘S1200 FAMILY ‘S2323 ‘S2343 ‘S2313 ‘S4414 ‘S8515 Classic Classic Classic Classic Classic Classic ‘mega103 Mega PINS 20 8 8 20 40/44 40/44 64 FLASH 1K 2K 2K 2K 4K 8K 128K 0+32 128+32 128+32 128+32 256+32 512+32 4K+32 64 128 128 128 256 512 4K UART - - - YES YES YES YES PWMs - - - 1 2 2 4 ADC(10-bits) - - - - - - 8Ch AVAILABLE NOW NOW NOW NOW NOW NOW NOW SRAM+REGs EEPROM Flash MCU AVR Product Line cont. ‘S4434 FAMILY PINS FLASH ‘S8535 ‘S4433 ‘S2333 ‘mega161 ‘mega163 ‘mega603 Classic Classic Classic Classic Mega Mega Mega 40/44 40/44 28/32 28/32 40/44 EgaAVR 40/44 64 4K 8K 4K 2K 16K 16K 64K 512+32 256+32 128+32 1K+32 1K+32 4K SRAM+REGs 256+32 EEPROM 256 512 256 128 512 512 2K UART YES YES YES YES YES YES YES PWMs 3 3 1 1 4 4 4 ADC(10-bits) 8Ch 8Ch 6Ch 6Ch - 8Ch 8Ch AVAILABLE NOW NOW NOW NOW 3Q00 3Q00 NOW Flash MCU AVR Product Line cont. ‘tiny10/11 ‘tiny12 FAMILY ‘tiny15 ‘tiny19 ‘tiny22 ‘tiny28 ‘tiny26 Tiny Tiny Tiny Tiny Tiny Tiny Tiny 8 8 8 28 8 28 20 FLASH 1K 1K 1K 1K 2K 2K 2K SRAM+REGs 32 32 32 32 128+32 32 64+32 - 64 64 - 128 - 128 NO YES YES NO YES NO YES I/O’s 6 6 6 20 5 20 16 T/C 1 1 2 1 1 1 2 PWM - - 1 - - - 2 ADC(10-bits) - - 4Ch - - - 11Ch AVAILABLE NOW 2Q00 2Q00 2Q00 NOW 2Q00 PINS EEPROM ISP 2Q00 Flash MCU AT90S1200 · · · · · · · · · World’s Highest Performance 8-bit MCU 20-pin Device 1 Kbytes ISP Flash 64 bytes ISP EEPROM 15 Programmable I/O lines 8-bit Timer Counter 1 External Interrupt Analog Comparator RC-Oscillator Flash MCU AT90S4414 / AT90S8515 · · · · · · · · · · · 40-pin Device 4/8 Kbytes of ISP Flash 256/512 bytes of ISP EEPROM 256/512 bytes SRAM Full Duplex UART SPI-Serial Interface 8- and 16-bits Timer/Counter Dual PWM 2 External Interrupts Analog Comparator Fast start up possibility Flash MCU AT90S2313 / AT90LS2313 · · · · · · · · · · · 20-pin Device 2 Kb ISP Flash 128 bytes ISP EEPROM 128 bytes SRAM 8-bit Timer Counter 16-bit Timer Counter with capture/compare Full Duplex UART Selectable 8, 9 or 10-bit PWM 2 External interrupts On Chip Analog Comparator Fast start up possibility Flash MCU AT90S2323 / AT90LS2323 · · · · · · · · 8-pin Device 2 Kbytes ISP Flash 128 bytes ISP EEPROM 128 bytes SRAM 8-bit Timer/Counter0 1 External Interrupt 3 I/O Pins External Crystal Oscillator Only Flash MCU AT90S2343 / AT90LS2343 · · · · · · 8-pin Package 2 Kbytes ISP Flash 128 bytes ISP EEPROM 128 bytes SRAM 8 bit timer 5(4) I/O Pins Int. RC: 5 I/O pins + RESET, VCC and GND Ext. Clock: 4 I/O pins + RESET, XTAL1, VCC and GND · External Clock or Internal RC Oscillator Selected with fuse · Fast Wake-up Flash MCU AT90S4433/ AT90S2333 · · · · · · · · 28 Pins package 4/2 Kb ISP Flash 128 bytes ISP EEPROM 256/128 bytes SRAM 8-bit Timer Counter 16-bit Timer Counter with capture/compare/PWM Full Duplex UART 10-bit ADC with 6 Multiplexed Inputs Flash MCU AT90S4434 / AT90LS4434 • 40/44-pin Device • 10-bit ADC with 8 Multiplexed Inputs • 3.6 - 14.3 ksamples/sec (Single Conversion Mode) • 3.9 - 15.4 ksamples/sec (Free Running Mode) • RTC with Separate 32 kHz Oscillator • Power Save Mode: Only RTC running <7mA power consumption • Functionally Equal to AT90S4414 • New Pin-out to improve ADC noise immunity • No External SRAM interface • Port C pin order swapped Flash MCU AT90S8535 / AT90LS8535 • 40/44-pin Device • 10-bit ADC with 8 Multiplexed Inputs • 3.6 - 14.3 ksamples/sec (Single Conversion Mode) • 3.9 - 15.4 ksamples/sec (Free Running Mode) • RTC with Separate 32 kHz Oscillator • New Power Save Mode: Only RTC Running • Functionally Equal to AT90S8515 • New Pin-out to improve ADC noise immunity • No External SRAM interface • Port C pin order swapped Flash MCU ATmega103 / ATmega103L • • • • • 64-pin Device (48 I/O, 16 Special Function) 128 Kbytes ISP Flash 4Kbytes SRAM 4Kbytes EEPROM 10-bit ADC with 8 Multiplexed Inputs • 3.3 - 13.3 ksamples/sec (Single Conversion Mode) • 3.6 - 14.3 ksamples/sec (Free Running Mode) • Separate 32 kHz Oscillator with RTC • Power Save Mode: Only RTC running <7mA power consumption Flash MCU ATmega603 / ATmega603L • • • • • 64-pin Device (48 I/O, 16 Special Function) 64 Kbytes ISP Flash 4Kbytes SRAM 2Kbytes EEPROM 10-bit ADC with 8 Multiplexed Inputs • 3.3 - 13.3 ksamples/sec (Single Conversion Mode) • 3.6 - 14.3 ksamples/sec (Free Running Mode) • Separate 32 kHz Oscillator with RTC • Power Save Mode: Only RTC running <7mA power consumption Flash MCU ATmega161 / ATmega161L • 40/44-pin Device • 16 Kbytes ISP Flash with Optional Boot Sector for Selfprogramming of program and data memories. • 1Kbytes SRAM • 512bytes EEPROM • Separate 32 kHz Oscillator with RTC • Power Save Mode: Only RTC running <7mA power consumption • On-Chip 2cycle Multiplier • 4 ch PWM, Dual UART and SPI • Programmable Brown-Out detection circuit Flash MCU ATmega163 / ATmega163L • 40/44-pin Device • 16 Kbytes ISP Flash with Optional Boot Sector for Selfprogramming of program and data memories. • 1Kbytes SRAM & 512bytes EEPROM • 10-bit ADC with 8 Multiplexed Inputs • 3.3 - 13.3 ksamples/sec (Single Conversion Mode) • 3.6 - 14.3 ksamples/sec (Free Running Mode) • Separate 32 kHz Oscillator with RTC • Power Save Mode: Only RTC running <7mA power consumption • On-Chip 2cycle Multiplier • 4 ch PWM, Dual UART and SPI • Programmable Brown-Out detection circuit Flash MCU Tiny 10/11 · · · · · · · · 8 Pins package 1 Kb ISP Flash 6 Programmable I/O lines 1 external interrupt 8-bit Timer Counter Analog Comparator Wake up on pin change Ultra low cost OTP version(Tiny10) Flash MCU Tiny 12/12L/12V · · · · · · · · · 8 Pins package 1 Kb ISP Flash 64B On-chip EEPROM 6 Programmable I/O lines 1 external interrupt 8-bit Timer Counter Analog Comparator Wake up on pin change Internal Calibrated RC oscillator Flash MCU Tiny 15/15L · · · · 8 Pins package & 6 Programmable I/O lines 1 Kb ISP Flash & 64B On-chip EEPROM Two 8-bit Timer Counter & 150KHz High speed PWM 4Ch 10bit ADC (One differencial Input with Optional Gain of 20x) & Analog Comparator · Internal 1.6MHz Tuneable oscillator · Programmable Brown-Out detection circuit Flash MCU Tiny 22/22L · · · · · · · · 8 Pins package 2 Kb ISP Flash 128B SRAM & EEPROM 5 Programmable I/O lines 1 external interrupt 8-bit Timer Counter Wake up on pin change Selectable On-chip RC oscillator Flash MCU Tiny 26/26L · · · · · · · · 20 Pins package 2 Kb ISP Flash, 64B SRAM & 128B EEPROM 16 Programmable I/O lines 8-bit Timer Counter & 2Ch High speed PWM External interrupt & Pin change interrupt on 8 pins Internal Calibrated RC oscillator Programmable Brown-Out detector 10-bits ADC - 11 single ended, 6 differential ADC channels - 2 differential ADC Channels with Optional Gain of 20x Flash MCU AVR Road Map What will we see in the near future? Flash MCU The Three AVR Families • megaAVR ATmegaXXX ( 16kB - 128 kB) • Targets complex applications with requirements for large program memories • classicAVR AT90XXXX ( 1- 8kB ) • Targets medium-range applications where high throughput and low power is important • tinyAVR ATtinyXX ( 1 - 2kB ) • Targets cost-sensitive applications in the very low end of the 8-bit MCU market Flash MCU FLASH DENSITY AVR PRODUCT ROADMAP: 1998 megaAVR FAMILY 16KB TO 128KB classicAVR FAMILY 1KB TO 8KB tinyAVR FAMILY 1KB & 2KB DEVICE COMPLEXITY Flash MCU tinyAVR applications • • • • • • • • • Automotive low-end control applications Toys Games and Game-Cards PC Motherboard Connector Control Security Controller for mobile Phones (SIS Code) Battery Chargers Communication IF controllers White and Brown Goods Smoke Detectors Flash MCU classicAVR applications • • • • • • • • PC Modems Cable Modems Battery Chargers (advanced) Smart Cards and Smart Card Readers Tool Road Pay Tags Set-top Boxes Pay-TV Decoders Various Industrial Control Applications Flash MCU megaAVR applications • • • • • • Analog Mobile Phones (NMT, ETACS, AMPS, and D-AMPS) Digital Mobile Phones (GSM and CDMA) Printers and Printer Switches/Controllers Fax Controller Disk Drive Controllers CD-ROM Controllers Flash MCU In-System Programmable Flash and EEPROM Now Offered on an MCU by a technology leader in Non-Volatile memories Flash MCU This is ISP Flash and EEPROM 5-wire serial programming interface Your device sits in the application. It is clocked from the application clock, and VCC can be as low as 2.7V. Now, with four logical signals + Ground, you can REPROGRAM THE FLASH AND THE EEPROM NO +12V PROGRAMMING VOLTAGE REQUIRED! Flash MCU Just Imagine... • No OTP parts thrown away • No 5-minute UV erase time • No sleepless nights after mask tape-out • No stocking of multiple system versions • No surprises in moving from OTP to mask • No 10-week lead time … instead ... • Easy update of new features • Easy bug fix • Easy testing • Easy in-line calibration Flash MCU AVR for ASIC • • • • • RTL softcore enables a varity of processes RTL for Standard I/O modules AVR ASIC ICE available with reference designs AVR ASIC handbook Ready to go NOW ! Flash MCU The AVR Offers... …Industry’s Highest 8-bit Performance …Low Power Consumption …a broad Family of MCUs …a Variety of Peripherals …excellent C Language Code Density …In-System Programmable Flash and EEPROM Flash MCU Instruction Set & Architecture A Guided Tour Through the Architecture, Instruction by Instruction Flash MCU Instruction Set General Features • All Instructions (with a few exceptions) are 16 Bits Wide • Most Instructions are Executed in One Clock Cycle Flash MCU Instruction Classes • • • • Arithmetic/Logic Instructions Data Transfer Instructions Program Control Instructions Bit Set/Test Instructions Flash MCU Arithmetic/Logical Instruction • • • • • Add / Increment Subtract / Decrement Compare Logical (AND, OR, XOR) Shift / Rotate All True Single Cycle Flash MCU Add Instructions • • • • “ADD” Add Two Registers “ADC” Add Two Registers and Carry “INC” Increment a Register “ADIW”Add Immediate to Word * * Works on the 4 Uppermost Register Pairs Flash MCU Subtract Instructions • • • • “SUB” Subtract Two Registers “SBC” Subtract with Carry Two Registers “SUBI” Subtract Immediate from Register* “SBCI” Subtract with Carry Immediate from Register* • “DEC” Decrement Register • “SBIW “ Subtract Immediate From Word** * ** Works on Registers R16 - R31 Works on the 4 Uppermost Register Pairs Flash MCU Executing “subi r16,k” Instruction Word Register File Immediate Operand Instruction ALU Flash MCU Compare Instructions • “CP” Compare Two Registers • ”CPC” Compare with Carry Two Registers • “CPI” Compare Register and Immediate* • “CPSE” Compare Two Registers and Skip Next Instruction if Equal * Works on Registers R16 - R31 Flash MCU 16/32-Bit Data Support The AVR Supports Code and Time Efficient 16 and 32-bit Arithmetic's Through the Following: • Single Cycle Execution • A Register File That Holds Several 16/32-Bit Values • Carry and Zero Flag Propagation on Subtract and Compare Flash MCU Subtract Two 16-Bit Values Without Zero Flag Propagation R1:R0 - R3:R2 ($E104 - $E101) R1 R0 Z E1 04 X sub r0,r2 E1 03 0 sbc r1,r3 00 03 1 Wrong! Flash MCU Subtract Two 16-Bit Values With Zero Flag Propagation R1:R0 - R3:R2 ($E104 - $E101) R1 R0 Z E1 04 X sub r0,r2 E1 03 0 sbc r1,r3 00 03 0 Correct! Flash MCU Compare Two 32-Bit Values Example: Compare R3:R2:R1:R0 and R7:R6:R5:R4 cp cpc cpc cpc r0,r4 r1,r5 r2,r6 r3,r7 At the end, the Status Register Indicates Equal, Higher, Lower, Greater (signed), Less Than (signed). Besides, it takes only 4 instructions and 4 clock cycles to do it... Flash MCU Logical Instructions • “AND” Logical AND Two Registers • “ANDI” Logical AND Immediate and Register * • “OR” Logical OR Two Registers • “ORI” Logical OR Immediate and Register * • “EOR” Logical XOR Two Registers * Works on Registers R16 - R31 Flash MCU Shift / Rotate Instructions • • • • • “LSL” “LSR” “ROL” “ROR” “ASR” Logical Shift Left Logical Shift Right Rotate Left Through Carry Rotate Right Through Carry Arithmetic Shift Right Flash MCU Shift / Rotate Operations MSB LSR ROR ASR 0 Register LSB Carry Flash MCU Data Transfer Instruction Types # of Cycles • Data SRAM Register File • Program Memory Register File • I/O Memory Register File (2) (1/2) (1) Flash MCU The 5 Memory Areas • • • • • General Purpose Register File Flash Program Memory SRAM Data Memory I/O Memory EEPROM Data Memory 32 Bytes 8 MB 8 MB 64 Bytes 8 MB Flash MCU Memory Interconnections Program Memory Register File I/O Memory SRAM EEPROM Flash MCU AVR Pointer Structure R0 R1 R2 R3 R26 R27 R28 R29 R30 R31 XL XH YL YH ZL ZH Register File X Pointer Y Pointer Z Pointer Flash MCU Data SRAM Register File Instructions • “LD Rd,<PTR>” Load Indirect • “LD Rd,<PTR>+” Load Indirect with Post-Increment • “LD Rd,-<PTR>” Load Indirect with Pre-Decrement • “LDD Rd,<PTR>+q” Load Indirect with Displacement (0-63)* • “LDS Rd,<ADDR>“ Load Direct from SRAM (16-bit ADDR)** * ** PTR =X, Y or Z Parts with SRAM > 64k bytes, memory page selected using the RAMPZ register Flash MCU Data SRAM Register File Instructions • “ST <PTR>,Rd” • “ST <PTR>+,Rd” Store Indirect Store Indirect with Post-Increment • “ST -<PTR>,Rd” Store Indirect with Pre-Decrement • “STD <PTR>+q,Rd” Store Indirect with Displacement (0-63) * • “STS <ADDR>,Rd” Store Direct from SRAM (16-bit ADDR)** * ** PTR = X, Y or Z Parts with SRAM > 64k bytes, memory page selected using the RAMPZ register Flash MCU Move 16 Bytes SRAM RF... Example: loop: .def .def temp=r16 cnt=r17 ;temporary storage register ;loop counter ldi ldi clr clr ldi ld st dec brne ZH,high(SRAM_LOCATION) ;init Z pointer ZL,low(SRAM_LOCATION) YH ;init Y pointer YL cnt,16 ;init loop counter temp,Z+ ;get data from SRAM Y+,temp ;store data in RF cnt ;decrement counter loop ;loop more if not done Flash MCU … and Store Back Example (Continued): loop: ldi ld st dec brne cnt,16 temp,-Y Z-,temp cnt loop ;init loop counter ;get data from RF ;store data in SRAM ;decrement counter ;loop more if not done Flash MCU Data Transfer RF SRAM Stack Instructions • “PUSH” PUSH a register on the stack • “POP” POP a register from the stack Flash MCU Data Transfer Prog. Memory RF Instructions • “LDI” Load a Register with an Immediate Value (1 Cycle) * • “LPM” Transfer a byte from Program Memory@Z to R0 (2 Cycles) ** * Works on R16 - R31, ** Available on parts with SRAM, only Flash MCU The LPM Instruction MSB Z Pointer Selects Program Memory Address The byte pointed to by Z is transferred to R0 LSB Selects Low/High Byte Flash MCU Register File I/O Memory Transfer Instructions • OUT • IN Transfer a Byte from RF to I/O Transfer a Byte from I/O to RF Flash MCU Program Control Instruction Types • Unconditional Jumps • Conditional Branches • Subroutine Call and Returns Flash MCU Unconditional Jump Instructions • “RJMP” Relative Jump * • “JMP” Absolute Jump ** • “IJMP” Indirect Jump to Program Location@Z - Reaches ± 2K instructions from current program location. - Wrap-around ** 4-Byte Instruction * Flash MCU Instruction Fetch/Execution Instructions are Sequential Fetch Execute T1 T2 T3 INSTR n+1 INSTR n+2 INSTR n+3 INSTR n INSTR n+1 INSTR n+2 Flash MCU Instruction Fetch/Execution One Instruction is a Jump Fetch Execute T1 T2 INSTR n+1 INSTR m INSTR m+1 INSTR n INSTR n INSTR m (Jump to m) Reject T3 Flash MCU Conditional Branch Instructions (Flag Set) • • • • • • • • • “BREQ” “BRSH” “BRGE” “BRHS” “BRCS” “BRMI” “BRVS” “BRTS” “BRIE” Branch if Equal Branch if Same or Higher Branch if Greater or Equal (Signed) Branch if Half Carry Set Branch if Carry Set Branch if Minus Branch if Overflow Flag Set Branch if T Flag Set Branch if Interrupt Enabled Flash MCU Conditional Branch Instructions (Flag Clear) • • • • • • • • • “BRNE” “BRLO” “BRLT” “BRHC” “BRCC” “BRPL” “BRVC” “BRTC” “BRID” Branch if Not Equal Branch if Lower Branch if Less Than (Signed) Branch if Half Carry Clear Branch if Carry Clear Branch if Plus Branch if Overflow Flag Clear Branch if T Flag Clear Branch if Interrupt Disabled Flash MCU The Status Register - SREG 7 Interrupt Enable I Enables Global Interrupts when Set T Flag T Source and Destination for BLD and BST Half Carry H Set if an Add/Sub. has Carry between Bits 4&3 Signed Flag S Used for Signed Tests Overflow Flag V Set if an Add/Sub Results in Signed Overflow Neagative Flag N Set if a Result is Negative Zero Flag Z Set if a Result is Zero Carry Flag C Set if an Add/Subtract has Carry 0 Flash MCU Branch on SREG Settings 7 Branches if Bit Clear BRID I BRIE BRTC T BRTS BRHC H BRHS BRGE S BRLT BRVC V BRVS BRPL N BRMI BRNE Z BREQ BRSH, BRCC C BRCS, BRLO 0 Branches if Bit Set Flash MCU Subroutine Call and Return Instructions • “RCALL” • “CALL” • “ICALL” • “RET” • “RETI” Relative Subroutine Call * Absolute Subroutine Call ** Indirect Subroutine Call to Routine @Z Return from Subroutine Return from Interrupt Routine - Reaches ± 2K instructions from current program location - Wrap-around ** 4-Byte Instruction * Flash MCU Bit Set and Bit Test Instructions • “SBR” • “SBI” Set Bit(s) in Register * Set Bit in I/O Register ** • “SBRS” Skip if Bit in Register Set • “SBIS” Skip if Bit in I/O Register Set ** * Works on Registers R16 - R31 ** Works on I/O Addresses $00 - $1F Flash MCU Bit Clear and Bit Test Instructions • “CBR” • “CBI” Clear Bit(s) in Register * Clear Bit in I/O Register ** • “SBRC” Skip if Bit in Register Clear • “SBIC” Skip if Bit in I/O Register Clear ** * Works on Registers R16 - R31 ** Works on I/O Addresses $00 - $1F Flash MCU Interrupt System and Sleep Modes Flash MCU Interrupt System Features • Short Response Time (4 Clock Cycles + RJMP to Routine) • Automatic Interrupt Flag Clearing • Automatic Disable of Other Interrupts Inside the Interrupt Routine Flash MCU Interrupt Vector Example $0000rjmp RESET;Reset Vector $0001rjmp IRQ0 ;IRQ0 Vector $0002rjmp IRQ1 ;IRQ1 Vector IRQ0: $0003<opcode> $0004<opcode> … $xxxx<opcode> $xxxxreti ;IRQ0 Routine ;Ret. from Interrupt Flash MCU Executing an Interrupt Episode 1, Interrupt in the Main Program $0123mov $0124add $0125adc $0126lsl $0127clc Interrupt • • • • • r16,r0 r20,r0 r21,r1 r0 “lsl r0” is Completed $0127 is Pushed onto the Stack The Interrupt Flag is Cleared The I-bit in SREG is Cleared The Program Jumps to the IRQ Vector 4 Clock Cycles Flash MCU Executing an Interrupt Return Episode 2, The Interrupt Vector and Routine $0000RJMP RESET ;Reset Vector $0001RJMP IRQ0 ;IRQ0 Vector $0002RJMP IRQ1 ;IRQ1 Vector IRQ0: ;IRQ0 Routine $0003in r0,PINB $0004out PORTD,r0 $0005reti ;Ret from IRQ0 • • • The I-bit in SREG is Set $0127 is Popped of the Stack Program Execution Resumes from $0127 4 Clock Cycles Flash MCU Sleep Modes • Idle Mode • Power Down Mode Sleep Mode is entered by executing the “SLEEP” Instruction with the “SE” Bit in the “MCUCR” Register Set. If the “SM” Bit in “MCUCR” is set, the MCU enters Power Down Mode when “SLEEP” is executed Flash MCU Idle Mode • • • • CPU is Stopped XTAL Oscillator Runs Timer/Counters and other Peripherals Operate Reset + All Enabled Interrupts Can Wake Up the MCU Flash MCU Power Down Mode • • • • CPU is Stopped XTAL Oscillator is Stopped Timer/Counters and Other Peripherals are Stopped Internal RC Oscillator Runs if the Watchdog is Enabled. • Reset + External Level Interrupt Can Wake up the MCU Flash MCU Power Save Mode • CPU is Stopped • XTAL Oscillator is Stopped • Timer 2 is clocked asynchronously – Optimized for external 32.768 Khz crystal • Power consumption < 7uA@5V • Easy Real Time Clock implementation Flash MCU Wake-Up from Sleep Mode • RESET: The MCU Starts Execution from the Reset Vector • INTERRUPT: The MCU Enters the Interrupt Routine, Runs it and Resumes Execution from the Instruction following “SLEEP”. Flash MCU Peripherals I/O Ports Timer/Counters Comparator Watchdog UART A/D converter Flash MCU I/O Ports General Features • • • • • • • Push-Pull Drivers High Current Drive (sinks up to 40 mA) Pinwise Controlled Pull-Up Resistors Pinwise Controlled Data Direction Fully Synchronized Inputs Three Control/Status Bits per Bit/Pin Real Read-Modify-Write Flash MCU 3 Control/Status Bits per Pin • DDx Data Direction Control Bit • PORTx Output Data or Pull-Up Control Bit • PINx Pin Level Bit X = A, B, C, ... Flash MCU Default Configuration DDx 0 Pull-Up PORTx 0 PINx Physical Pin ? ? Direction: Pull-Up: INPUT OFF Flash MCU Switch On Pull-Up DDx 0 Pull-Up PORTx 1 PINx Physical Pin ? ? Direction: Pull-Up: INPUT ON Flash MCU Port is Output DDx 1 Pull-Up PORTx 1 PINx Physical Pin 1 1 Direction: Pull-Up: OUTPUT OFF Flash MCU Why Three Addresses? Why not let WRITE PORTx write the LATCH and READ PORTx read the PINS? (just like Microchip, Hitachi, Motorola...) A Two-address Port means NO REAL Read-Modify-Write Flash MCU The Two-Address Problem Example: • I/O Type: • Configuration: • Software Task: PORTx Reads the Pin and Writes the Latch Some PORTx Pins are Outputs, Others are Inputs, Inputs Have Pull-Ups on Set One of the Output Pins PROBLEM! Flash MCU The Two-Address Problem (Continued) • Setting an I/O Pin is Done Like This: – Read PORTx (Read) – OR With All Zeros Except Bit to be Set (Modify) – Write PORTx (Write) • If the Signal on an Input Pin is Low When PORTx is Read... Write Back WILL TURN OFF THE PULL-UP. Flash MCU From the PIC16C64 Datasheet: “Reading the PORT register, reads the values of the PORT pins. Writing to the PORT register writes the value to the PORTB latch. When using read modify write instructions (ex. BCF, BSF, etc.) on a PORT, the value of the PORT pins is read, the desired operation is done to this value, and the value is then written to the PORT latch” .” … “…care must be exercised if a write followed by a read operation is carried out on the same I/O port. The sequence of instructions should be such to allow the pin voltage to stabilize (load dependent) before the next instruction … otherwise, the previous state of that pin may be read into the CPU rather than the new state … it is better to separate these instructions with a NOP or another instruction not accessing this I/O port.” Flash MCU From HITACHI’s H8/300 Programming Manual: “BSET, BCLR, … are read-modify-write instructions. They read a byte of data, modify one bit in the byte, then write the byte back. Care is required when these instructions are applied to registers with write-only bits and to the I/O port registers.” … “Programming Solution: The switching of the pull-ups can be avoided by storing the same data both in the port data register and in a work area in RAM” Flash MCU Timer/Counters Standard AVR Timer/Counter Modules • Timer/Counter0 - 8 Bit • Timer/Counter1 - 16 Bit • Timer/Counter2 - 8 Bit Flash MCU General T/C Features • Clock Prescaling Options: 1, 8, 64, 256, 1024 • Can Run at Undivided XTAL Frequency (High Resolution) • Can be Set to Any Value at Any Time • Can be Clocked Externally by Signals with Transition Periods down to XTAL/2 • Can be Clocked Externally on both Rising and Falling Edge. Flash MCU Timer/Counter0 • 8-Bit • Overflow Interrupt Flash MCU T/C0 Block Diagram Data Bus Timer Interrupt Mask Register (TIMSK) Timer Interrupt Flag Register (TIFR) Control Logic 8-Bit Timer/Counter T/C0 Control Register (TCCR0) Flash MCU Timer/Counter1 • • • • • 16-Bit Overflow Interrupt Output Compare Function with Interrupt Input Capture with Interrupt and Noise Canceler 10, 9 or 8-Bit PWM Function Flash MCU T/C1 Block Diagram Data Bus Timer Interrupt Mask Register (TIMSK) Timer Interrupt Flag Register (TIFR) Control Logic T/C0 Control Register A (TCCR1A) T/C0 Control Register B (TCCR1B) 16-Bit Timer/Counter Input Capture1 Register (ICR1) Timer/Counter1 Output Compare Reg. (OCR1) 16-Bit Comparator Flash MCU Timer/Counter2 • • • • • 8-Bit Overflow Interrupt Output Compare Function with Interrupt 8-Bit PWM Function Real Time Clock function Flash MCU T/C2 Block Diagram Data Bus Timer Interrupt Mask Register (TIMSK) Timer Interrupt Flag Register (TIFR) Control Logic T/C2 Control Register (TCCR2) 8-Bit Timer/Counter 8-Bit Comparator Timer/Counter2 Output Compare Reg. (OCR2) Asynch. Status Register(ASSR) Flash MCU Output Compare Features • Compare match can control an external pin (Rise, Fall or Toggle) even if the Interrupt is disabled. • As an option, the timer can be automatically cleared when a compare match occurs. Flash MCU Input Capture Features • Capture Can Trigger on Rising or Falling Edge (Optional) • The Input Capture Noise Canceler will not trigger the Capture until 4 Subsequent samples of the same value are seen. The Noise Canceler is Optional Flash MCU PWM Features • • • • • Selectable 10, 9 or 8-Bit Resolution. Frequency @ 10 MHz (8-bit): 19 KHz Centered Pulses Glitch-Free Pulse Width Change Selectable Polarity Flash MCU PWM Operation Compare Value 2 Compare Value 1 PWM Output 1 PWM Output 2 Timer Value Flash MCU Analog Comparator Features • Comparator has its own Interrupt on Output Transitions • Interrupt has selectable trigger on Rise, Fall or Toggle • The Comparator Output can be Connected to the Input Capture of Timer/Counter1 – Enables Pulse-Width Measurement of Analog Signals – Enables Easy Implementation of Dual Slope ADC Flash MCU A/D Converter • • • • • • Succesive Approximation A/D 10 Bit resolution 1/2 LSB Accuracy 65-260 uS conversion time 8 Multiplexed input channels Interrupt on AD conversion complete Flash MCU A/D converter Data Bus ADC Control and Status Register(ADCSR) ADC dataregister (ADCH/ADCL) Succesive approximation logic 10-bit DAC ADC multiplexer select(ADMUX) 8Channel Mux Analog input Flash MCU Watchdog • Clocked from Internal 1 MHz R-C Oscillator • Time-Out Adjustable 16 - 2048 ms. • Watchdog Timer Reset is done by executing the “WDR” instruction Flash MCU UART Features • • • • • • Full Duplex 8 or 9 Data Bits Framing Error Detection False Start Bit Detection Noise Canceling High BAUD Rates at low XTAL Frequencies E.g. 115,200 Baud at 1.8432 MHz • Can run at Practically any Baud Rate • Three Interrupts with Separate Vectors Flash MCU Development Tools Flash MCU Development Tools Overview • • • • • • • • ANSI compliant C Compiler Macro-Assemblers Linker/Librarian Debugger/Simulator RTOS In-Circuit Emulator Evaluation boards Programmers Flash MCU In-Circuit Emulator Easy to use MS-Windows interface Unlimited number of Breakpoints Trace buffer Logic analyzer interface External trigger inputs/outputs Reconfigurable I/O Flash MCU Event Memory • Breakpoints – Eight different Breakpoints for each location – Break mask register • Control – Two bits for trace control – Three bits for external triggers – Three bits for auxillary use Flash MCU Trace buffer • Control in Event memory – Trace on, Trace off, Toggle, No action • 32K deep • 96 bit wide Flash MCU Connectors • Two connectors for logic analyzer – Program memory address (20 bit) – Program memory data (16 bit) – Clock • Auxillary connector – Trigger inputs – Trigger outputs Flash MCU Flash MCU AVR Studio • • • • • Easy to Use MS-Windows interface Controls the AVR In-Circuit Emulator Uses AVR Simulator if AVR ICE not present C and Assembly source level debugging Reads different object formats, including UBROF from IAR development tools • Project information Flash MCU AVR Studio Source View • C and Assembly display • Toggle execution level • Breakpoints insertion and removal • Run to cursor • Module selection • Source code search Flash MCU AVR Studio Symbol Watch • • • • Maintains scope information Binds watches automatically Simple variables Arrays, Structs, Unions and Pointers Flash MCU AVR Studio Register View • Simple window to view register contents • Registers can be modified when execution is stopped • Red colour on active registers Flash MCU AVR Studio Memory View • SRAM, Program Memory, EEPROM and I/O • Various representations • Modifications possible when execution stopped Flash MCU AVR Studio Processor View • Displays essential information about debug target • Values modifiable when execution stopped Flash MCU AVR Studio I/O Views • Specialized views for I/O devices – – – – – – – Timer UART Port SPI Analog Comparator EEPROM ADC Flash MCU IAR Development Tools for Fully ANSI compliant C Compiler Built-In AT90S specific optimizer Includes Embedded Workbench Assembler, Librarian and Linker C And Assembly level debugger Windows-95, Win 3.11, Windows NT and DOS Flash MCU Chip Specific Extensions • • • • • • Initialization function for Hardware setup Special Function Register (SFR) for I/O access Interrupt functions Monitor functions for critical regions Routines for accessing Flash Intrinsic functions: – SEI, CLI, NOP, OPC, LPM, SLEEP, WDR • EEPROM access routines – EEPUT, EEGET Flash MCU Example: SFR / Intrinsics sfrb sfrb MCUCR = 0x35; GIMSK = 0x3B; int __low_level_init(void) { GIMSK = 0xC0; /* Enable ext interrupts */ MCUCR = 0x0F; /* Extern int on ris edge */ _SEI(); /* Enable interrupts */ return(1); } Flash MCU Example: Interrupts interrupt[TIM1_CAPT_vect] void tim1capt(void) { int uCapture; uCapture = ICR1 ; if(uCapture > CONST) { … } } Flash MCU Example: Monitor functions monitor int P(char *flag) { if(!*flag) return(*flag = 1); else return(0); } Flash MCU AVR Development Tools • Complete development tools package • State-of-the-art graphical user interface • Effective C Compiler and processor core results in compact code • Compiler well suited for embedded applications Flash MCU Hands On Training Using the AVR Assembler Flash MCU Assembly • Full control of Resource Usage • Compact and fast code in small applications • Inneffecient code in larger applications • Cryptical code • Hard to maintain • Non-portable vs. C • Limited control of Resource usage • Larger/slower code in small applications • Efficient code in larger applications • Structured code • Easy to maintain • Portable Flash MCU Assembler exercise 1 • Write a assembler program that reads input on the serial port and send it as hex value to the LEDS • Store the data in SRAM until LF(Line Feed) is pressed (0x0A) • Convert the data to capital letters and send them on the serial port • EXTRA: Write “WORKSHOP” on the serial port after RESET (Tip: use LPM) Flash MCU Hints and tricks • Remember to initalize interrupt vectors and stack pointer • Clear high byte of Z pointer • Data from PC ends with CR(0x0D) and LF(0x0A) • Subtract 0x20 to convert to uppercase Flash MCU Main Program Set up interrupt vectors Init stack pointer Set PORTB as output Set baud rate = 9600 @ 4Mhz crystal Enable UART receive and interrupt Init Z pointer to RAM address 0x0060 Enable global interrupt loop: goto loop Flash MCU Interrupt Functions UART_RX: Store status register Read UART data register Output data to port B If data register not = LF Store data in RAM Increment Z pointer Else Store LF and CR in RAM Init Z pointer to RAM address 0x0060 Enable UART Transmit and interrupt Restore status register Return UDRE_empty: Store status register Read data from RAM Increment Z pointer If Z data not = LF Convert to capitol letters Send data to UDR Else Send LF to UDR Init Z pointer to RAM address 0x0060 Enable UART Receive and interrupt Restore status register Return Flash MCU Exercise 2 • Convert the program to the IAR assembler Flash MCU AVR assembler .CSEG .equ label = expression .equ const = 0x50 .def symbol = register .def temp = R16 .include “8515def.inc” Program address is word .ORG $0005 IAR assembler NAME routine #define label expression -#define const 0x50 #define symbol register #define temp R16 #include “io8515.h” Program address is byte ORG $0005*2 END Flash MCU Optimized for High Level Languages Flash MCU High Level Languages • Increased importance for Microcontrollers – – – – – – Time to market Simplified maintenance Portability Learning time Reusability Libraries • Potential drawbacks – Increased codesize – Decreased speed Flash MCU AVR Architecture and Instruction Set influenced by IAR • Compiler development project initiated before Architecture / Instruction Set frozen • Potential Bottlenecks identified and removed • IAR feedback reflected in Hardware • Several iterations • Result of modifications frequently observed in generated code Flash MCU C-like Addressing Modes C Source unsigned char *var1, *var2; *var1++ = *--var2; Generated code LD R16,-X ST Z+,R16 Flash MCU Indirect with Displacement • Effective for accessing arrays and structs • Autos placed on Software Stack Flash MCU Four memory pointers • Memory to memory copy • Minimize pointer reloading • High functionality Flash MCU 16 and 32 bit support • Carry instructions – – – – Addition and Subtraction Register with register Register with immediate Zero flag propagation SUB R16,R24 SBC R17,R25 SUBI R16,1 SBCI R17,0 All branches can be made based on last result Flash MCU 16 Bit instructions • Additions and Subtractions of small values • Ideal for index variables and pointer manipulations • Software Stack Flash MCU Non-destructive comparison CP CPC CPC CPC R16,R24 R17,R25 R18,R26 R19,R27 • Compare with carry instruction • Zero propagation • No restoring necessary • All conditional branches available Flash MCU Switch Support • Switches very frequently used by CASE tools • Straight forward approach inefficient and time differentiating • Indirect jumps well suited for compact switch constructions • General library routines manages switches Flash MCU Compiler Features • • • • • • Fully compatible with the ANSI standard All required data types supported Fully reentrant code General optimizations AVR specific optimizations AVR specific extensions Flash MCU Optimization • Code and Speed optimization • C and Assembly level optimizations – – – – – – – – – – – Algebraic identities Common subexpression elimination Removal of branch chains Condition reversal Constant folding Register allocation Bit operations Peephole optimizations Cross jumping and hoisting Removal of unreachable code Redundant assignment removal Flash MCU Summary • AVR Architecture originally designed with High Level Languages in mind • Cooperation between Atmel and IAR on Architecture and Instruction Set tuning • Resulting Compiler generates highly efficient code • Incorporated changes frequently exploited in generated code