SlideShare a Scribd company logo
1 of 19
‘C’ for Microcontrollers,
  Just Being Efficient
     Lloyd Moore, President


      Lloyd@CyberData-Robotics.com
       www.CyberData-Robotics.com




       Seattle Robotics Society 9/15/2012
Agenda

  MicrocontrollerResources
  Knowing Your Environment
  Memory Usage
  Code Structure
  Optimization
  Summary
Disclaimer
  Some   microcontroller techniques necessarily
   need to trade one benefit for another –
   typically lower resource usage for
   maintainability
  Point of this presentation is to point out various
   techniques that can be used as needed
  Use these suggestions when necessary
  Feel free to suggest better solutions as we go
   along
Microcontroller Resources
  EVERYTHING    resides on one die inside one
   package: RAM, Flash, Processor, I/O
  Cost is a MAJOR design consideration
      Typical costs are $0.25 to $25 each (1000’s)
  RAM:  16 BYTES to 256K Bytes typical
  Flash/ROM: 384 BYTES to 1M Byte
  Clock Speed: 4MHz to 175MHz typical
      Much lower for battery saving modes (32KHz)
  Busis 8, 16, or 32 bits wide
  Have dedicated peripherals (MAC, Phys, etc)
Power Consumption
  Microcontrollers
                  typically used in battery
   operated devices
  Power requirements can be
   EXTREMELY tight
    Energy  harvesting applications
    Long term battery installations (remote
     controls, hard to reach devices, etc.)
  EVERY  instruction executed consumes
  power, even if you have the time and
  memory!
Know Your Environment
  Traditionallywe ignore hardware details
  Need to tailor code to hardware
   available
    Specialized   hardware MUCH more efficient
  Compilers     typically have extensions
    Interrupt – specifies code as being ISR
    Memory model – may handle banked
     memory and/or simultaneous access banks
    Multiple data pointers / address generators

  Debugger      may use some resources
Memory Usage
    Put constant data into program memory (Flash/ROM)
    Alignment / padding issues
        Typically NOT an issue, non-aligned access ok
    Avoid dynamic memory allocation, even if available
        Take extra space and processing time
        Memory fragmentation a big issue
    Use and reuse static buffers
        Reduces variable passing overhead
        Allows for smaller / faster code due to reduced indirections
        Does bring back over write bugs if not done carefully
        More reliable for mission critical systems
    Use the appropriate variable type
        Don’t use int and double for everything!!
        Affects processing time as well as storage
C99 Datatypes – inttypes.h

  int8_t,int16_t, int32_t, int64_t
  uint8_t, uint16_t, uint32_t, uint_64_t


  Avoids   the ambiguity of int and uint
   when moving code between processors
   of different native size
  Makes code more portable and
   upgradable over time
Char vs. Int Increment on 8051
            char cX;                          int iX;
            cX++;                             iX++;
                                   0000   900000        MOV     DPTR,#iX
 000A   900000   MOV    DPTR,#cX   0003   E4            CLR     A
 000D   E0       MOVX   A,@DPTR    0004   75F001        MOV     B,#01H
 000E   04       INC    A          0007   120000        LCALL   ?C?IILDX
 000F   F0       MOVX   @DPTR,A



                                      10 Bytes of Flash +
 6  Bytes of Flash                    subroutine overhead
  4 Instruction cycles               Many more than 4
                                       instruction cycles with a
                                       LCALL
Code Structure
  Count    down instead of up
     Saves a subtraction on all processors
     Decrement-jump-not-zero style instruction on some
      processors
  Pointers    vs. array notation
       Generally better using pointers
  Bit   Shifting
     May not always generate what you think
     May or may not have barrel shifter hardware

     May or may not have logical vs. arithmetic shifts
Shifting Example on 8051
  cX = cX << 3;                                   cA = 3;
                                                  cX = cX << cA;
   0006   33         RLC        A
                                           000B   900000   MOV      DPTR,#cA
   0007   33         RLC        A
                                           000E   E0       MOVX     A,@DPTR
   0008   33         RLC        A
                                           000F   FE       MOV      R6,A
   0009   54F8       ANL        A,#0F8H
                                           0010   EF       MOV      A,R7
                                           0011   A806     MOV      R0,AR6
                                           0013   08       INC      R0
                                           0014   8002     SJMP     ?C0005
                                           0016            ?C0004:
      Constants turn into seperate        0016   C3       CLR      C
       statements                          0017   33       RLC      A
      Variables turn into loops           0018            ?C0005
                                           0018   D8FC     DJNZ    R0,?C0004
      Both of these can be one
       instruction with a barrel shifter
Indexed Array vs Pointer on M8C
 ucMode = g_Channels[uc_Channel].ucMode;   ucMode = pChannel->ucMode;

  01DC   52FC     mov A,[X-4]               01ED   5201        mov   A,[X+1]
  01DE   5300     mov [__r1],A              01EF   5300        mov   [__r1],A
  01E0   5000     mov A,0
                                            01F1   3E00        mvi   A,[__r1]
  01E2   08       push A
  01E3   5100     mov A,[__r1]              01F3   5405        mov   [X+5],A
  01E5   08       push A
  01E6   5000     mov A,0                   Does the same thing
  01E8   08       push A                    Saves 29 bytes of memory AND a
  01E9   5007     mov A,7
  01EB   08       push A
                                             call to a 16 bit multiplication routine!
  01EC   7C0000   xcall __mul16             Pointer version will be at least 4x
  01EF   38FC     add SP,-4                  faster to execute as well, maybe 10x
  01F1   5F0000   mov [__r1],[__rX]         Most compilers not this bad – but you
  01F4   5F0000   mov [__r0],[__rY]          do find some!
  01F7   060000   add[__r1],<_g_Channels
  01FA   0E0000   adc[__r0],>_g_Channels
  01FD   3E00     mvi A,[__r1]
  01FF   5403     mov [X+3],A
More Code Structure
    Actual parameters typically passed in registers if
     available
        Keep function parameters to less than 3
        May also be passed on stack or special parameter area
        May be more efficient to pass pointer to struct
    Global variables
        While generally frowned upon for most code can be very
         helpful here
        Typically ends up being a direct access
    Read assembly code for critical areas
    Know which optimizations are present
        Small compilers do not always have common optimizations
        Inline, loop unrolling, loop invariant, pointer conversion
Switch Statement Implementation

    Switch statements can be implemented in various
     ways
        Sequential compares
        In line table look up for case block
        Special function with look up table
    Specific implementation can also vary based case
     clauses
        Clean sequence (1, 2, 3, 4, 5)
        Gaps in sequence (1, 10, 30, 255)
        Ordering of sequence (5, 4, 1, 2, 3)
    Knowing which method gets implemented is critical to
     optimizing!
Switch Statement Example
 switch(cA)            0006   900000          MOV        DPTR,#cA
 {                     0009   E0              MOVX       A,@DPTR
                       000A   FF              MOV        R7,A
     case 0:
                       000B   EF              MOV        A,R7
            cX = 4;    000C   120000          LCALL      ?C?CCASE
            break;     000F   0000            DW         ?C0003
     case 1:           0011   00              DB         00H
            cX = 10;   0012   0000            DW         ?C0002
            break;     0014   01              DB         01H
     case 2:           0015   0000            DW         ?C0004
            cX = 30;   0017   02              DB         02H
            break;     0018   0000            DW         00H
     default:          001A   0000            DW         ?C0005
            cX = 0;
            break;     001C             ?C0002:
 }                     001C   900000        MOV          DPTR,#cX
                       001F   7404          MOV          A,#04H
                       0021   F0            MOVX         @DPTR,A
                       0022   8015          SJMP         ?C0006

                       ...More blocks follow for each case
Optimization Process
  Step  0 – Before coding anything, think about
   risk points and prototype unknowns!!!
      Use available dedicated hardware
  Step   1 – Get it working!!
    Fast but wrong is of no use to anyone
    Optimization will typically reduce readability

  Step   2 – Profile to know where to optimize
    Usually only one or two routines are critical
    You need to have specific performance metrics to
     target
Optimization Process
  Step 3 – Let the tools do as much as
   they can
    Turn off debugging!
    Select the correct memory model
    Select the correct optimization level

  Step   4 – Do it manually
    Read  the generated code! Might be able to
     make a simple code or structure change.
    Last – think about assembly coding
Summary

  Microcontrollers  are a resource
   constrained environment
  Be familiar with the hardware in your
   microcontroller
  Be familiar with your compiler options
   and how it translates your code
  For time or space critical code look at
   the assembly listing from time to time
Questions?

More Related Content

What's hot

SPICE MODEL of KGH15N120NDA (Professional+FWDS Model) in SPICE PARK
SPICE MODEL of KGH15N120NDA (Professional+FWDS Model) in SPICE PARKSPICE MODEL of KGH15N120NDA (Professional+FWDS Model) in SPICE PARK
SPICE MODEL of KGH15N120NDA (Professional+FWDS Model) in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of 1MBH15D-060 (Professional+FWDS Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWDS Model) in SPICE PARKSPICE MODEL of 1MBH15D-060 (Professional+FWDS Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWDS Model) in SPICE PARKTsuyoshi Horigome
 
Buy Embedded Systems Projects Online,Buy B tech Projects Online
Buy Embedded Systems Projects Online,Buy B tech Projects OnlineBuy Embedded Systems Projects Online,Buy B tech Projects Online
Buy Embedded Systems Projects Online,Buy B tech Projects OnlineTechnogroovy
 
SPICE MODEL of 1MBH15D-060 (Professional+FWDP Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWDP Model) in SPICE PARKSPICE MODEL of 1MBH15D-060 (Professional+FWDP Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWDP Model) in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of TC75S59FE in SPICE PARK
SPICE MODEL of TC75S59FE in SPICE PARKSPICE MODEL of TC75S59FE in SPICE PARK
SPICE MODEL of TC75S59FE in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of 2SA1020(Y) in SPICE PARK
SPICE MODEL of 2SA1020(Y) in SPICE PARKSPICE MODEL of 2SA1020(Y) in SPICE PARK
SPICE MODEL of 2SA1020(Y) in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of 2SK3667 (Standard+BDS Model) in SPICE PARK
SPICE MODEL of 2SK3667 (Standard+BDS Model) in SPICE PARKSPICE MODEL of 2SK3667 (Standard+BDS Model) in SPICE PARK
SPICE MODEL of 2SK3667 (Standard+BDS Model) in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of SSM6K203FE (Professional+BDP Model) in SPICE PARK
SPICE MODEL of SSM6K203FE (Professional+BDP Model) in SPICE PARKSPICE MODEL of SSM6K203FE (Professional+BDP Model) in SPICE PARK
SPICE MODEL of SSM6K203FE (Professional+BDP Model) in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of 1MBH15D-060 (Professional+FWD+SP Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWD+SP Model) in SPICE PARKSPICE MODEL of 1MBH15D-060 (Professional+FWD+SP Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWD+SP Model) in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of UP05C8G in SPICE PARK
SPICE MODEL of UP05C8G in SPICE PARKSPICE MODEL of UP05C8G in SPICE PARK
SPICE MODEL of UP05C8G in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of TPCF8A01 (Professional+BDS+SBDS Model) in SPICE PARK
SPICE MODEL of TPCF8A01 (Professional+BDS+SBDS Model) in SPICE PARKSPICE MODEL of TPCF8A01 (Professional+BDS+SBDS Model) in SPICE PARK
SPICE MODEL of TPCF8A01 (Professional+BDS+SBDS Model) in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of TPCF8A01 (Professional+BDP+SBDS Model) in SPICE PARK
SPICE MODEL of TPCF8A01 (Professional+BDP+SBDS Model) in SPICE PARKSPICE MODEL of TPCF8A01 (Professional+BDP+SBDS Model) in SPICE PARK
SPICE MODEL of TPCF8A01 (Professional+BDP+SBDS Model) in SPICE PARKTsuyoshi Horigome
 
SPICE MODEL of NJU7031M in SPICE PARK
SPICE MODEL of NJU7031M in SPICE PARKSPICE MODEL of NJU7031M in SPICE PARK
SPICE MODEL of NJU7031M in SPICE PARKTsuyoshi Horigome
 

What's hot (13)

SPICE MODEL of KGH15N120NDA (Professional+FWDS Model) in SPICE PARK
SPICE MODEL of KGH15N120NDA (Professional+FWDS Model) in SPICE PARKSPICE MODEL of KGH15N120NDA (Professional+FWDS Model) in SPICE PARK
SPICE MODEL of KGH15N120NDA (Professional+FWDS Model) in SPICE PARK
 
SPICE MODEL of 1MBH15D-060 (Professional+FWDS Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWDS Model) in SPICE PARKSPICE MODEL of 1MBH15D-060 (Professional+FWDS Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWDS Model) in SPICE PARK
 
Buy Embedded Systems Projects Online,Buy B tech Projects Online
Buy Embedded Systems Projects Online,Buy B tech Projects OnlineBuy Embedded Systems Projects Online,Buy B tech Projects Online
Buy Embedded Systems Projects Online,Buy B tech Projects Online
 
SPICE MODEL of 1MBH15D-060 (Professional+FWDP Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWDP Model) in SPICE PARKSPICE MODEL of 1MBH15D-060 (Professional+FWDP Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWDP Model) in SPICE PARK
 
SPICE MODEL of TC75S59FE in SPICE PARK
SPICE MODEL of TC75S59FE in SPICE PARKSPICE MODEL of TC75S59FE in SPICE PARK
SPICE MODEL of TC75S59FE in SPICE PARK
 
SPICE MODEL of 2SA1020(Y) in SPICE PARK
SPICE MODEL of 2SA1020(Y) in SPICE PARKSPICE MODEL of 2SA1020(Y) in SPICE PARK
SPICE MODEL of 2SA1020(Y) in SPICE PARK
 
SPICE MODEL of 2SK3667 (Standard+BDS Model) in SPICE PARK
SPICE MODEL of 2SK3667 (Standard+BDS Model) in SPICE PARKSPICE MODEL of 2SK3667 (Standard+BDS Model) in SPICE PARK
SPICE MODEL of 2SK3667 (Standard+BDS Model) in SPICE PARK
 
SPICE MODEL of SSM6K203FE (Professional+BDP Model) in SPICE PARK
SPICE MODEL of SSM6K203FE (Professional+BDP Model) in SPICE PARKSPICE MODEL of SSM6K203FE (Professional+BDP Model) in SPICE PARK
SPICE MODEL of SSM6K203FE (Professional+BDP Model) in SPICE PARK
 
SPICE MODEL of 1MBH15D-060 (Professional+FWD+SP Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWD+SP Model) in SPICE PARKSPICE MODEL of 1MBH15D-060 (Professional+FWD+SP Model) in SPICE PARK
SPICE MODEL of 1MBH15D-060 (Professional+FWD+SP Model) in SPICE PARK
 
SPICE MODEL of UP05C8G in SPICE PARK
SPICE MODEL of UP05C8G in SPICE PARKSPICE MODEL of UP05C8G in SPICE PARK
SPICE MODEL of UP05C8G in SPICE PARK
 
SPICE MODEL of TPCF8A01 (Professional+BDS+SBDS Model) in SPICE PARK
SPICE MODEL of TPCF8A01 (Professional+BDS+SBDS Model) in SPICE PARKSPICE MODEL of TPCF8A01 (Professional+BDS+SBDS Model) in SPICE PARK
SPICE MODEL of TPCF8A01 (Professional+BDS+SBDS Model) in SPICE PARK
 
SPICE MODEL of TPCF8A01 (Professional+BDP+SBDS Model) in SPICE PARK
SPICE MODEL of TPCF8A01 (Professional+BDP+SBDS Model) in SPICE PARKSPICE MODEL of TPCF8A01 (Professional+BDP+SBDS Model) in SPICE PARK
SPICE MODEL of TPCF8A01 (Professional+BDP+SBDS Model) in SPICE PARK
 
SPICE MODEL of NJU7031M in SPICE PARK
SPICE MODEL of NJU7031M in SPICE PARKSPICE MODEL of NJU7031M in SPICE PARK
SPICE MODEL of NJU7031M in SPICE PARK
 

Viewers also liked

[mobiconf 2014] Shazam mobile apps - Data Driven Project Management
[mobiconf 2014] Shazam mobile apps - Data Driven Project Management[mobiconf 2014] Shazam mobile apps - Data Driven Project Management
[mobiconf 2014] Shazam mobile apps - Data Driven Project ManagementTomasz Kustrzynski MSc
 
121113 rese tom veerman printout
121113 rese tom veerman printout121113 rese tom veerman printout
121113 rese tom veerman printoutTom Veerman
 
Starting Raspberry Pi
Starting Raspberry PiStarting Raspberry Pi
Starting Raspberry PiLloydMoore
 
Real Time Debugging - What to do when a breakpoint just won't do
Real Time Debugging - What to do when a breakpoint just won't doReal Time Debugging - What to do when a breakpoint just won't do
Real Time Debugging - What to do when a breakpoint just won't doLloydMoore
 
High Reliabilty Systems
High Reliabilty SystemsHigh Reliabilty Systems
High Reliabilty SystemsLloydMoore
 
Caronne.eu 3rd presentation at 17th nov 2014 meetup FinTech Startups France
Caronne.eu 3rd presentation at 17th nov 2014 meetup FinTech Startups FranceCaronne.eu 3rd presentation at 17th nov 2014 meetup FinTech Startups France
Caronne.eu 3rd presentation at 17th nov 2014 meetup FinTech Startups FranceJames Nacass
 
[appclub] Shazam mobile apps - Data Driven Project Management
[appclub] Shazam mobile apps - Data Driven Project Management[appclub] Shazam mobile apps - Data Driven Project Management
[appclub] Shazam mobile apps - Data Driven Project ManagementTomasz Kustrzynski MSc
 
130424 zorgverzekeraars en us ps
130424   zorgverzekeraars en us ps130424   zorgverzekeraars en us ps
130424 zorgverzekeraars en us psTom Veerman
 
Raspberry pi robotics
Raspberry pi roboticsRaspberry pi robotics
Raspberry pi roboticsLloydMoore
 
Rpt kssr tahun 6 pendidikan islam - acrobat.pdf
Rpt kssr tahun 6   pendidikan islam - acrobat.pdfRpt kssr tahun 6   pendidikan islam - acrobat.pdf
Rpt kssr tahun 6 pendidikan islam - acrobat.pdfayen2010
 
Using the Cypress PSoC Processor
Using the Cypress PSoC ProcessorUsing the Cypress PSoC Processor
Using the Cypress PSoC ProcessorLloydMoore
 
Using PSoC Creator
Using PSoC CreatorUsing PSoC Creator
Using PSoC CreatorLloydMoore
 

Viewers also liked (16)

[mobiconf 2014] Shazam mobile apps - Data Driven Project Management
[mobiconf 2014] Shazam mobile apps - Data Driven Project Management[mobiconf 2014] Shazam mobile apps - Data Driven Project Management
[mobiconf 2014] Shazam mobile apps - Data Driven Project Management
 
MBFT 2015
MBFT 2015MBFT 2015
MBFT 2015
 
121113 rese tom veerman printout
121113 rese tom veerman printout121113 rese tom veerman printout
121113 rese tom veerman printout
 
Leading Edge Auction
Leading Edge AuctionLeading Edge Auction
Leading Edge Auction
 
Starting Raspberry Pi
Starting Raspberry PiStarting Raspberry Pi
Starting Raspberry Pi
 
Bang chao gia 03
Bang chao gia 03Bang chao gia 03
Bang chao gia 03
 
Real Time Debugging - What to do when a breakpoint just won't do
Real Time Debugging - What to do when a breakpoint just won't doReal Time Debugging - What to do when a breakpoint just won't do
Real Time Debugging - What to do when a breakpoint just won't do
 
High Reliabilty Systems
High Reliabilty SystemsHigh Reliabilty Systems
High Reliabilty Systems
 
Caronne.eu 3rd presentation at 17th nov 2014 meetup FinTech Startups France
Caronne.eu 3rd presentation at 17th nov 2014 meetup FinTech Startups FranceCaronne.eu 3rd presentation at 17th nov 2014 meetup FinTech Startups France
Caronne.eu 3rd presentation at 17th nov 2014 meetup FinTech Startups France
 
[appclub] Shazam mobile apps - Data Driven Project Management
[appclub] Shazam mobile apps - Data Driven Project Management[appclub] Shazam mobile apps - Data Driven Project Management
[appclub] Shazam mobile apps - Data Driven Project Management
 
130424 zorgverzekeraars en us ps
130424   zorgverzekeraars en us ps130424   zorgverzekeraars en us ps
130424 zorgverzekeraars en us ps
 
Raspberry pi robotics
Raspberry pi roboticsRaspberry pi robotics
Raspberry pi robotics
 
PSoC USB HID
PSoC USB HIDPSoC USB HID
PSoC USB HID
 
Rpt kssr tahun 6 pendidikan islam - acrobat.pdf
Rpt kssr tahun 6   pendidikan islam - acrobat.pdfRpt kssr tahun 6   pendidikan islam - acrobat.pdf
Rpt kssr tahun 6 pendidikan islam - acrobat.pdf
 
Using the Cypress PSoC Processor
Using the Cypress PSoC ProcessorUsing the Cypress PSoC Processor
Using the Cypress PSoC Processor
 
Using PSoC Creator
Using PSoC CreatorUsing PSoC Creator
Using PSoC Creator
 

Similar to C for Microcontrollers

Microcontroller 8051- soft.ppt
Microcontroller 8051- soft.pptMicrocontroller 8051- soft.ppt
Microcontroller 8051- soft.pptsteffydean
 
Microcontroller base project
Microcontroller base projectMicrocontroller base project
Microcontroller base projectNeeraj Deshani
 
Addressing mode and instruction set using 8051
Addressing mode and instruction set using 8051Addressing mode and instruction set using 8051
Addressing mode and instruction set using 8051logesh waran
 
Chp6 assembly language programming for pic copy
Chp6 assembly language programming for pic   copyChp6 assembly language programming for pic   copy
Chp6 assembly language programming for pic copymkazree
 
Windows debugging sisimon
Windows debugging   sisimonWindows debugging   sisimon
Windows debugging sisimonSisimon Soman
 
Reverse engineering of binary programs for custom virtual machines
Reverse engineering of binary programs for custom virtual machinesReverse engineering of binary programs for custom virtual machines
Reverse engineering of binary programs for custom virtual machinesSmartDec
 
Micro controller(pratheesh)
Micro controller(pratheesh)Micro controller(pratheesh)
Micro controller(pratheesh)Pratheesh Pala
 
Topviewsimulator
TopviewsimulatorTopviewsimulator
TopviewsimulatorRashmi
 
implementation of data instrucions in emu8086
implementation of data instrucions in emu8086implementation of data instrucions in emu8086
implementation of data instrucions in emu8086COMSATS Abbottabad
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsMaicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsNoor Tahasildar
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsMaicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsnoorahamed tahasildar
 

Similar to C for Microcontrollers (20)

Microcontroller 8051- soft.ppt
Microcontroller 8051- soft.pptMicrocontroller 8051- soft.ppt
Microcontroller 8051- soft.ppt
 
Microcontroller base project
Microcontroller base projectMicrocontroller base project
Microcontroller base project
 
Addressing mode and instruction set using 8051
Addressing mode and instruction set using 8051Addressing mode and instruction set using 8051
Addressing mode and instruction set using 8051
 
Microcontroller 8051
Microcontroller 8051Microcontroller 8051
Microcontroller 8051
 
8085 instruction-set part 1
8085 instruction-set part 18085 instruction-set part 1
8085 instruction-set part 1
 
microprocessors
microprocessorsmicroprocessors
microprocessors
 
Chp6 assembly language programming for pic copy
Chp6 assembly language programming for pic   copyChp6 assembly language programming for pic   copy
Chp6 assembly language programming for pic copy
 
One day-workshop on tms320 f2812
One day-workshop on tms320 f2812One day-workshop on tms320 f2812
One day-workshop on tms320 f2812
 
Analog to Digital Converter
Analog to Digital ConverterAnalog to Digital Converter
Analog to Digital Converter
 
ARM 64bit has come!
ARM 64bit has come!ARM 64bit has come!
ARM 64bit has come!
 
RISC-V Zce Extension
RISC-V Zce ExtensionRISC-V Zce Extension
RISC-V Zce Extension
 
chapter 4
chapter 4chapter 4
chapter 4
 
Windows debugging sisimon
Windows debugging   sisimonWindows debugging   sisimon
Windows debugging sisimon
 
Reverse engineering of binary programs for custom virtual machines
Reverse engineering of binary programs for custom virtual machinesReverse engineering of binary programs for custom virtual machines
Reverse engineering of binary programs for custom virtual machines
 
Micro controller(pratheesh)
Micro controller(pratheesh)Micro controller(pratheesh)
Micro controller(pratheesh)
 
12_Microcontrollers.ppt
12_Microcontrollers.ppt12_Microcontrollers.ppt
12_Microcontrollers.ppt
 
Topviewsimulator
TopviewsimulatorTopviewsimulator
Topviewsimulator
 
implementation of data instrucions in emu8086
implementation of data instrucions in emu8086implementation of data instrucions in emu8086
implementation of data instrucions in emu8086
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsMaicrocontroller lab basic experiments
Maicrocontroller lab basic experiments
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsMaicrocontroller lab basic experiments
Maicrocontroller lab basic experiments
 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

C for Microcontrollers

  • 1. ‘C’ for Microcontrollers, Just Being Efficient Lloyd Moore, President Lloyd@CyberData-Robotics.com www.CyberData-Robotics.com Seattle Robotics Society 9/15/2012
  • 2. Agenda  MicrocontrollerResources  Knowing Your Environment  Memory Usage  Code Structure  Optimization  Summary
  • 3. Disclaimer  Some microcontroller techniques necessarily need to trade one benefit for another – typically lower resource usage for maintainability  Point of this presentation is to point out various techniques that can be used as needed  Use these suggestions when necessary  Feel free to suggest better solutions as we go along
  • 4. Microcontroller Resources  EVERYTHING resides on one die inside one package: RAM, Flash, Processor, I/O  Cost is a MAJOR design consideration  Typical costs are $0.25 to $25 each (1000’s)  RAM: 16 BYTES to 256K Bytes typical  Flash/ROM: 384 BYTES to 1M Byte  Clock Speed: 4MHz to 175MHz typical  Much lower for battery saving modes (32KHz)  Busis 8, 16, or 32 bits wide  Have dedicated peripherals (MAC, Phys, etc)
  • 5. Power Consumption  Microcontrollers typically used in battery operated devices  Power requirements can be EXTREMELY tight  Energy harvesting applications  Long term battery installations (remote controls, hard to reach devices, etc.)  EVERY instruction executed consumes power, even if you have the time and memory!
  • 6. Know Your Environment  Traditionallywe ignore hardware details  Need to tailor code to hardware available  Specialized hardware MUCH more efficient  Compilers typically have extensions  Interrupt – specifies code as being ISR  Memory model – may handle banked memory and/or simultaneous access banks  Multiple data pointers / address generators  Debugger may use some resources
  • 7. Memory Usage  Put constant data into program memory (Flash/ROM)  Alignment / padding issues  Typically NOT an issue, non-aligned access ok  Avoid dynamic memory allocation, even if available  Take extra space and processing time  Memory fragmentation a big issue  Use and reuse static buffers  Reduces variable passing overhead  Allows for smaller / faster code due to reduced indirections  Does bring back over write bugs if not done carefully  More reliable for mission critical systems  Use the appropriate variable type  Don’t use int and double for everything!!  Affects processing time as well as storage
  • 8. C99 Datatypes – inttypes.h  int8_t,int16_t, int32_t, int64_t  uint8_t, uint16_t, uint32_t, uint_64_t  Avoids the ambiguity of int and uint when moving code between processors of different native size  Makes code more portable and upgradable over time
  • 9. Char vs. Int Increment on 8051 char cX; int iX; cX++; iX++; 0000 900000 MOV DPTR,#iX 000A 900000 MOV DPTR,#cX 0003 E4 CLR A 000D E0 MOVX A,@DPTR 0004 75F001 MOV B,#01H 000E 04 INC A 0007 120000 LCALL ?C?IILDX 000F F0 MOVX @DPTR,A  10 Bytes of Flash + 6 Bytes of Flash subroutine overhead  4 Instruction cycles  Many more than 4 instruction cycles with a LCALL
  • 10. Code Structure  Count down instead of up  Saves a subtraction on all processors  Decrement-jump-not-zero style instruction on some processors  Pointers vs. array notation  Generally better using pointers  Bit Shifting  May not always generate what you think  May or may not have barrel shifter hardware  May or may not have logical vs. arithmetic shifts
  • 11. Shifting Example on 8051 cX = cX << 3; cA = 3; cX = cX << cA; 0006 33 RLC A 000B 900000 MOV DPTR,#cA 0007 33 RLC A 000E E0 MOVX A,@DPTR 0008 33 RLC A 000F FE MOV R6,A 0009 54F8 ANL A,#0F8H 0010 EF MOV A,R7 0011 A806 MOV R0,AR6 0013 08 INC R0 0014 8002 SJMP ?C0005 0016 ?C0004:  Constants turn into seperate 0016 C3 CLR C statements 0017 33 RLC A  Variables turn into loops 0018 ?C0005 0018 D8FC DJNZ R0,?C0004  Both of these can be one instruction with a barrel shifter
  • 12. Indexed Array vs Pointer on M8C ucMode = g_Channels[uc_Channel].ucMode; ucMode = pChannel->ucMode; 01DC 52FC mov A,[X-4] 01ED 5201 mov A,[X+1] 01DE 5300 mov [__r1],A 01EF 5300 mov [__r1],A 01E0 5000 mov A,0 01F1 3E00 mvi A,[__r1] 01E2 08 push A 01E3 5100 mov A,[__r1] 01F3 5405 mov [X+5],A 01E5 08 push A 01E6 5000 mov A,0  Does the same thing 01E8 08 push A  Saves 29 bytes of memory AND a 01E9 5007 mov A,7 01EB 08 push A call to a 16 bit multiplication routine! 01EC 7C0000 xcall __mul16  Pointer version will be at least 4x 01EF 38FC add SP,-4 faster to execute as well, maybe 10x 01F1 5F0000 mov [__r1],[__rX]  Most compilers not this bad – but you 01F4 5F0000 mov [__r0],[__rY] do find some! 01F7 060000 add[__r1],<_g_Channels 01FA 0E0000 adc[__r0],>_g_Channels 01FD 3E00 mvi A,[__r1] 01FF 5403 mov [X+3],A
  • 13. More Code Structure  Actual parameters typically passed in registers if available  Keep function parameters to less than 3  May also be passed on stack or special parameter area  May be more efficient to pass pointer to struct  Global variables  While generally frowned upon for most code can be very helpful here  Typically ends up being a direct access  Read assembly code for critical areas  Know which optimizations are present  Small compilers do not always have common optimizations  Inline, loop unrolling, loop invariant, pointer conversion
  • 14. Switch Statement Implementation  Switch statements can be implemented in various ways  Sequential compares  In line table look up for case block  Special function with look up table  Specific implementation can also vary based case clauses  Clean sequence (1, 2, 3, 4, 5)  Gaps in sequence (1, 10, 30, 255)  Ordering of sequence (5, 4, 1, 2, 3)  Knowing which method gets implemented is critical to optimizing!
  • 15. Switch Statement Example switch(cA) 0006 900000 MOV DPTR,#cA { 0009 E0 MOVX A,@DPTR 000A FF MOV R7,A case 0: 000B EF MOV A,R7 cX = 4; 000C 120000 LCALL ?C?CCASE break; 000F 0000 DW ?C0003 case 1: 0011 00 DB 00H cX = 10; 0012 0000 DW ?C0002 break; 0014 01 DB 01H case 2: 0015 0000 DW ?C0004 cX = 30; 0017 02 DB 02H break; 0018 0000 DW 00H default: 001A 0000 DW ?C0005 cX = 0; break; 001C ?C0002: } 001C 900000 MOV DPTR,#cX 001F 7404 MOV A,#04H 0021 F0 MOVX @DPTR,A 0022 8015 SJMP ?C0006 ...More blocks follow for each case
  • 16. Optimization Process  Step 0 – Before coding anything, think about risk points and prototype unknowns!!!  Use available dedicated hardware  Step 1 – Get it working!!  Fast but wrong is of no use to anyone  Optimization will typically reduce readability  Step 2 – Profile to know where to optimize  Usually only one or two routines are critical  You need to have specific performance metrics to target
  • 17. Optimization Process  Step 3 – Let the tools do as much as they can  Turn off debugging!  Select the correct memory model  Select the correct optimization level  Step 4 – Do it manually  Read the generated code! Might be able to make a simple code or structure change.  Last – think about assembly coding
  • 18. Summary  Microcontrollers are a resource constrained environment  Be familiar with the hardware in your microcontroller  Be familiar with your compiler options and how it translates your code  For time or space critical code look at the assembly listing from time to time