AVR Workshop

Document Sample
AVR Workshop Powered By Docstoc
					               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      XL
R27      XH
                      X Pointer
R28      YL
R29      YH
                      Y Pointer
R30      ZL
R31      ZH
                      Z Pointer
      Register File
                                        Flash MCU


    Direct Register - ALU Connection




                        Register File
Register operations
take ONE clock pulse
on the EXTERNAL clock
input
                            ALU
                                             Flash MCU



                 Execute 2 Instructions


       1 2   Done!


PIC    1         2       Done!


HC05   1             2               Done!


„C51   1                         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++)                      LDD     R20,Z+0
         LDI     R18,LOW(0)                      LDD     R21,Z+1
         LDI     R19,128                         CP      R18,R20
         CLR     R22                             CPC     R19,R21
?0001:                                           BRGE    ?0005
         CPI       R22,LOW(16)          ; 10.             maximum=array[a];
         BRCC      ?0000                         MOV     R18,R20
; 8.       {                                     MOV     R19,R21
; 9.            if (array[a]>maximum)   ?0005:
         MOV        R30,R22                      INC     R22
         CLR        R31                          RJMP    ?0001
         LSL        R30                 ?0000:
         ROL        R31                 ; 11.        }
         ADD        R30,R16             ; 12.        return (maximum);
         ADC        R31,R17                      MOV      R16,R18
                                                 MOV      R17,R19
                                        ; 13.     }
                                                 RET




   Code Size: 46 Bytes, Execution time: 335 cycles
                                                                                                       Flash MCU


                        C51 Assembly Output
    ; FUNCTION _max (BEGIN)                                         ?C0002:
    ;---- Variable 'array' assigned to Register 'R1/R2/R3' ----                                   ; SOURCE LINE # 14
         ; SOURCE LINE # 4                                                MOV     R6,maximum
         ; SOURCE LINE # 5                                          MOV      R7,maximum+01H
         ; SOURCE LINE # 7                                                                        ; SOURCE LINE # 15
         MOV     maximum,#080H                                      ?C0005:
         MOV     maximum+01H,#00H                                        RET
         ; SOURCE LINE # 9                                              ; FUNCTION _max (END)
    ;---- Variable 'a' assigned to Register 'R5' ----               ?C?ILDOPTR:
         CLR     A                                                      CJNE     R3,#0x01,0x195
         MOV     R5,A                                                   MOV      A,0x82
    ?C0001:                                                             ADD      A,R1
         ; SOURCE LINE # 10                                             MOV      0x82,A
         ; SOURCE LINE # 11                                             MOV      A,0x83
         MOV     A,R5                                                   ADDC     A,R2
         MOV     R7,A                                                   MOV      0x83,A
         RLC     A                                                      MOVX     A,@DPTR
         SUBB    A,ACC                                                  MOV      OxF0,A
         MOV     R6,A                                                   INC         DPTR
         MOV     A,R7                                                   MOVX     A,@DPTR
         ADD     A,ACC                                                  RET
         MOV     R7,A                                                   JNC      0x1A0
         MOV     A,R6                                                   MOV      A,R1
         RLC     A                                                      ADD      A,0x82
         MOV     DPL,R7                                                 MOV      R0,A
         MOV     DPH,A                                                  MOV      0xF0,@R0
         LCALL   ?C?ILDOPTR                                             INC      R0
         MOV     R7,A                                                   MOV      A,@R0
         MOV     R6,B                                                   RET
         SETB    C                                                      CJNE     R3,#0xFE,0xAD
         SUBB    A,maximum+01H                                          MOV      A,R1
         MOV     A,maximum                                              ADD      A,0X82
         XRL     A,#080H                                                MOV      R0,A
         MOV     R0,A                                                   MOV      A,@R0
         MOV     A,R6                                                   MOV      0xF0,A
         XRL     A,#080H                                                INC      R0
         SUBB    A,R0                                                   RET
         JC      ?C0003                                                 MOV      A,0X83
         ; SOURCE LINE # 12                                             ADD      A,R2
         MOV     maximum,R6                                             MOV      0X83,A
         MOV     maximum+01H,R7                                         MOV      A,R1
                                               ; SOURCE LINE # 13       MOVC     A,@A+DPTR
    ?C0003:                                                             RET
         INC     R5
         CJNE    R5,#010H,?C0001




Code Size: 112 Bytes, Execution time: 9384 cycles
                                                                 Flash MCU


                  HC11 Assembly output
; 7.       for (a=0;a<16;a++)           STD      5,X
         TSX                                     INS
         LDD     #-32768                         INS
         STD     1,X                             CPD     3,X
         CLR     0,X                             BLE     ?0005
?0001:                                  ; 10.             maximum=array[a];
         LDAA      0,X                           STD     3,X
         CMPA      #16                  ?0005:
         BHS       ?0000                         TSX
; 8.       {                                     INC     0,X
; 9.            if (array[a]>maximum)            BRA     ?0001
         PSHY                           ?0000:
         TAB                            ; 11.        }
         CLRA                           ; 12.        return (maximum);
         LSLD                                    LDD      1,X
         TSX                            ; 13.     }
         ADDD      0,X                           PULX
         XGDX                                    PULX
         LDD       0,X                           INS
         TSX                                     PULY
                                                 RTS



       Code Size: 57 Bytes, Execution time: 5244 cycles
                                                                                Flash MCU


     PIC16C74 Assembly output
        bcf    3,5
        movwf ?a_maxnum& (0+127)                 subwf   (?a_maxnum+2)& (0+127),w
;MAX_MAIN.C: 4: char a;                   u15
;MAX_MAIN.C: 5: int maximum=-32768;               btfsc 3,0
        clrf   (?a_maxnum+2)& (0+127)             goto   l5
        movlw 128                         ;MAX_MAIN.C: 10: maximum=array[a];
        movwf (?a_maxnum+3)& (0+127)              bcf    3,5
;MAX_MAIN.C: 7: for (a=0;a<16;a++)                movf   (?a_maxnum+1)& (0+127),w
        clrf   (?a_maxnum+1)& (0+127)             addwf (?a_maxnum+1)& (0+127),w
l2                                                addwf ?a_maxnum& (0+127),w
;MAX_MAIN.C: 8: {                                 movwf 4
;MAX_MAIN.C: 9: if (array[a]>maximum)             movf   0,w
        bcf    3,5                                movwf (?a_maxnum+2)& (0+127)
        movf   (?a_maxnum+1)& (0+127),w           incf   4
        addwf (?a_maxnum+1)& (0+127),w            movf   0,w
        addwf ?a_maxnum& (0+127),w                movwf (?a_maxnum+3)& (0+127)
        movwf 4                           l5
        movf   0,w                        ;MAX_MAIN.C: 11: }
        movwf btemp                               bcf    3,5
        incf   4                                  incf   (?a_maxnum+1)& (0+127)
        movf   0,w                                movlw 16
        movwf btemp+1                             subwf (?a_maxnum+1)& (0+127),w
        movf   (?a_maxnum+3)& (0+127),w           btfss 3,0
        xorlw 128                                 goto   l2
        movwf btemp+2                     ;MAX_MAIN.C: 12: return (maximum);
        movf   btemp+1,w                          bcf    3,5
        xorlw 128                                 movf   (?a_maxnum+3)& (0+127),w
        subwf btemp+2,w                           movwf btemp+1
        btfss 3,2                                 movf   (?a_maxnum+2)& (0+127),w
        goto   u15                                movwf btemp
        movf   btemp,w                            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
                     Flash MCU


AVR Product Line cont.
                         Flash MCU


AVR Product Line cont.
                                            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 Self-
  programming 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 Self-
  programming 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



   AVR PRODUCT ROADMAP: 1998
FLASH DENSITY




                                                        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    r0,r4
   cpc   r1,r5
   cpc   r2,r6
   cpc   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”   Logical Shift Left
•   “LSR”   Logical Shift Right
•   “ROL”   Rotate Left Through Carry
•   “ROR”   Rotate Right Through Carry
•   “ASR”   Arithmetic Shift Right
                                  Flash MCU



      Shift / Rotate Operations
           MSB   Register   LSB      Carry

LSR    0


ROR


ASR
                                    Flash MCU



    Data Transfer Instruction Types

                                      # of Cycles


• Data SRAM Register File        (2)
• Program Memory  Register File   (1/2)
• I/O Memory Register File       (1)
                                        Flash MCU




           The 5 Memory Areas

•   General Purpose Register File   32 Bytes
•   Flash Program Memory            8 MB
•   SRAM Data Memory                8 MB
•   I/O Memory                      64 Bytes
•   EEPROM Data Memory              8 MB
                                 Flash MCU




       Memory Interconnections
Program Memory   Register File   SRAM




                  I/O Memory     EEPROM
                             Flash MCU



AVR Pointer Structure
R0
R1
R2
R3




R26       XL
R27       XH
                       X Pointer
R28       YL
R29       YH
                       Y Pointer
R30       ZL
R31       ZH
                       Z Pointer
       Register File
                                                    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”         Store Indirect
• “ST <PTR>+,Rd”        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:
        .def   temp=r16     ;temporary storage register
        .def   cnt=r17      ;loop counter

        ldi    ZH,high(SRAM_LOCATION) ;init Z pointer
        ldi    ZL,low(SRAM_LOCATION)
        clr    YH           ;init Y pointer
        clr    YL
        ldi    cnt,16       ;init loop counter
loop:   ld     temp,Z+      ;get data from SRAM
        st     Y+,temp      ;store data in RF
        dec    cnt          ;decrement counter
        brne   loop         ;loop more if not done
                                             Flash MCU



                … and Store Back
 Example (Continued):

        ldi    cnt,16    ;init loop counter
loop:   ld     temp,-Y   ;get data from RF
        st     Z-,temp   ;store data in SRAM
        dec    cnt       ;decrement counter
        brne   loop      ;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                       LSB




            Selects Program Memory Address            Selects
                                                   Low/High Byte


The byte pointed to by Z is transferred to R0
                                     Flash MCU



   Register File I/O Memory
      Transfer Instructions

• OUT   Transfer a Byte from RF to I/O
• IN    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

                 T1           T2          T3



Fetch          INSTR n+1   INSTR n+2   INSTR n+3

Execute        INSTR n     INSTR n+1   INSTR n+2
                                                           Flash MCU




          Instruction Fetch/Execution
               One Instruction is a Jump


                 T1                   T2          T3



Fetch          INSTR n+1             INSTR m   INSTR m+1

Execute        INSTR n               INSTR n   INSTR m
              (Jump to m)

                            Reject
                                                   Flash MCU


    Conditional Branch Instructions
              (Flag Set)
•   “BREQ”   Branch if Equal
•   “BRSH”   Branch if Same or Higher
•   “BRGE”   Branch if Greater or Equal (Signed)
•   “BRHS”   Branch if Half Carry Set
•   “BRCS”   Branch if Carry Set
•   “BRMI”   Branch if Minus
•   “BRVS”   Branch if Overflow Flag Set
•   “BRTS”   Branch if T Flag Set
•   “BRIE”   Branch if Interrupt Enabled
                                             Flash MCU


    Conditional Branch Instructions
             (Flag Clear)
•   “BRNE”   Branch if Not Equal
•   “BRLO”   Branch if Lower
•   “BRLT”   Branch if Less Than (Signed)
•   “BRHC”   Branch if Half Carry Clear
•   “BRCC”   Branch if Carry Clear
•   “BRPL”   Branch if Plus
•   “BRVC”   Branch if Overflow Flag Clear
•   “BRTC”   Branch if T Flag Clear
•   “BRID”   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
                      BRID   I   BRIE
                     BRTC    T   BRTS

Branches             BRHC    H   BRHS         Branches
if Bit Clear         BRGE    S   BRLT         if Bit Set
                     BRVC    V   BRVS
                     BRPL    N   BRMI
                     BRNE    Z   BREQ
                BRSH, BRCC   C   BRCS, BRLO
                             0
                                                       Flash MCU


       Subroutine Call and Return
              Instructions
• “RCALL”           Relative Subroutine Call *
• “CALL”            Absolute Subroutine Call **
• “ICALL”           Indirect Subroutine Call to
              Routine @Z
• “RET”             Return from Subroutine
• “RETI”            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”       Set Bit(s) in Register *
• “SBI”       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”       Clear Bit(s) in Register *
• “CBI”       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:     ;IRQ0 Routine
$0003<opcode>
$0004<opcode>
          …
$xxxx<opcode>
$xxxxreti           ;Ret. from Interrupt
                                                         Flash MCU



                 Executing an Interrupt
            Episode 1, Interrupt in the Main Program
                  $0123mov       r16,r0
                  $0124add       r20,r0
                  $0125adc       r21,r1
Interrupt         $0126lsl       r0
                  $0127clc
             •     “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
         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
Return   $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:   INPUT
Pull-Up:     OFF
                     Flash MCU



 Switch On Pull-Up
DDx

 0                   Pull-Up

PORTx

 1

PINx                  Physical Pin

 ?                         ?


Direction:   INPUT
Pull-Up:     ON
                         Flash MCU



        Port is Output
DDx

 1                       Pull-Up

PORTx

 1

PINx                      Physical Pin

 1                             1


Direction:   OUTPUT
Pull-Up:     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:        PORTx Reads the Pin
                   and Writes the Latch
• Configuration:   Some PORTx Pins are
                   Outputs, Others are Inputs,
                   Inputs Have Pull-Ups on
• Software Task:   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

           Timer Interrupt Mask                   Timer Interrupt Flag
             Register (TIMSK)                       Register (TIFR)
Data Bus




                                  Control Logic



                                                  T/C0 Control Register
           8-Bit Timer/Counter
                                                        (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
            Timer Interrupt Mask                   Timer Interrupt Flag
              Register (TIMSK)                       Register (TIFR)


                                   Control Logic
Data Bus




           T/C0 Control Register A             T/C0 Control Register B
                 (TCCR1A)                            (TCCR1B)

                                               Input Capture1 Register
            16-Bit Timer/Counter
                                                       (ICR1)

           Timer/Counter1 Output
                                                    16-Bit Comparator
           Compare Reg. (OCR1)
                                        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
            Timer Interrupt Mask                   Timer Interrupt Flag
              Register (TIMSK)                       Register (TIFR)


                                   Control Logic
Data Bus




           T/C2 Control Register
                 (TCCR2)


            8-Bit Timer/Counter                      8-Bit Comparator


           Timer/Counter2 Output                      Asynch. Status
           Compare Reg. (OCR2)                        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           Timer
                                   Value
Compare
 Value 2
Compare
 Value 1


   PWM
Output 1
   PWM
Output 2
                                                 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
           ADC Control and Status             ADC dataregister
             Register(ADCSR)                   (ADCH/ADCL)
Data Bus




                        Succesive approximation logic


                                                    10-bit DAC



                                                          8-              Analog
              ADC multiplexer                           Channel            input
              select(ADMUX)                              Mux
                                      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   MCUCR = 0x35;
sfrb   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                vs.     C
• Full control of Resource            • Limited control of Resource
  Usage                                 usage
• Compact and fast code in            • Larger/slower code in small
  small applications                    applications
• Inneffecient code in larger         • Efficient code in larger
  applications                          applications
• Cryptical code                      • Structured code
• Hard to maintain                    • Easy to maintain
• Non-portable                        • 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:                                   UDRE_empty:
    Store status register                      Store status register
    Read UART data register                    Read data from RAM
    Output data to port B                      Increment Z pointer
If data register not = LF                  If Z data not = LF
    Store data in RAM                          Convert to capitol letters
    Increment Z pointer                        Send data to UDR
Else                                       Else
    Store LF and CR in RAM                     Send LF to UDR
    Init Z pointer to RAM address 0x0060        Init Z pointer to RAM address
    Enable UART Transmit and interrupt         0x0060
Restore status register                         Enable UART Receive and
Return                                         interrupt
                                           Restore status register
                                           Return
                                      Flash MCU



                 Exercise 2

• Convert the program to the IAR assembler
                                                   Flash MCU



     AVR assembler        IAR assembler
.CSEG                     NAME routine
.equ label = expression   #define label expression
   .equ const = 0x50        -#define const 0x50

.def symbol = register    #define symbol register
                            #define temp          R16
   .def temp = R16
                          #include “io8515.h”
.include “8515def.inc”
                          Program address is byte
Program address is word
                             ORG $0005*2
   .ORG $0005

                          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          SUBI R16,1
        SBC R17,R25          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

                   • Compare with carry
                     instruction
CP    R16,R24      • Zero propagation
CPC   R17,R25
CPC   R18,R26      • No restoring
CPC   R19,R27        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

				
DOCUMENT INFO