SlideShare a Scribd company logo
C Language Programming

                        for the 8051




Prof. Cherrice Traver        EE/CS-152: Microprocessors
Overview
• C for microcontrollers
    –   Review of C basics
    –   Compilation flow for SiLabs IDE
    –   C extensions
    –   In-line assembly
    –   Interfacing with C
•   Examples
•   Arrays and Pointers
•   I/O Circuitry
•   Functions and Header Files
•   Multitasking and multithreading

Prof. Cherrice Traver         EE/CS-152: Microprocessors
C for Microcontrollers
• Of higher level languages, C is the closest
  to assembly languages
    – bit manipulation instructions
    – pointers (indirect addressing)
• Most microcontrollers have available C
  compilers
• Writing in C simplifies code development
  for large projects.

Prof. Cherrice Traver      EE/CS-152: Microprocessors
Available C Compilers
• Kiel – integrated with the IDE we have
  been using for labs.
• Reads51 – available on web site (
  http://www.rigelcorp.com/reads51.htm)
• Freeware: SDCC - Small Device C
  Compiler (http://sdcc.sourceforge.net/)
• Other freeware versions …


Prof. Cherrice Traver   EE/CS-152: Microprocessors
Compilation Process (Keil)
                        program.c

                            no SRC        compile
                            option
program.LST             program.OBJ

                             build/make

                        program.M51




Prof. Cherrice Traver          EE/CS-152: Microprocessors
Modular Programming
• Like most high level languages, C is a
  modular programming language (but NOT
  an object oriented language)
• Each task can be encapsulated as a function.
• Entire program is encapsulated in “main”
  function.




Prof. Cherrice Traver   EE/CS-152: Microprocessors
Basic C Program Structure
1.   Compiler directives and include files
2.   Declarations of global variables and constants
3.   Declaration of functions
4.   Main function
5.   Sub-functions
6.   Interrupt service routines

Example: blinky.c




Prof. Cherrice Traver       EE/CS-152: Microprocessors
Back to C Basics
• All C programs consists of:
    – Variables
    – Functions (one must be “main”)
       • Statements



• To define the SFRs as variables:
    #include <c8051F020.h>



Prof. Cherrice Traver    EE/CS-152: Microprocessors
Variables
• All variables must be declared at top of program, before
  the first statement.
• Declaration includes type and list of variables.
    Example:     void main (void) {
                   int var, tmp;            must go HERE!
• Types:
    –   int (16-bits in our compiler)
    –   char (8-bits)
    –   short (16-bits)
    –   long (32-bits)
    –   sbit (1-bit)              not standard C – an 8051 extension
    –   others that we will discuss later



Prof. Cherrice Traver             EE/CS-152: Microprocessors
Variables
• The following variable types can be signed
  or unsigned:
    signed char (8 bits) –128 to +127
    signed short (16 bits) –32768 to +32767
    signed int (16 bits) –32768 to +32767
    signed long (32 bits) –2147483648 to +2147483648

    unsigned char (8 bits) 0 to + 255
    unsigned short (16 bits) 0 to + 65535
    unsigned int (16 bits) 0 to + 65535
    unsigned long (32 bits) 0 to + 4294967295
       NOTE: Default is signed – it is best to specify.
Prof. Cherrice Traver          EE/CS-152: Microprocessors
Statements
• Assignment statement:

  variable = constant or expression or variable

  examples: upper = 60;
             I = I + 5;
            J = I;



Prof. Cherrice Traver      EE/CS-152: Microprocessors
Operators
•   Arithmetic: +, -, *, /
•   Relational comparisons: >, >=, <, <=
•   Equality comparisons: ==, !=
•   Logical operators: && (and), || (or)
•   Increment and decrement: ++, --
•   Example:
    if (x != y) && (c == b)
    {
        a=c + d*b;
        a++;
    }


Prof. Cherrice Traver            EE/CS-152: Microprocessors
Example – Adder program
                   (add 2 16-bit numbers)
$INCLUDE (C8051F020.inc)           #include <c8051f020.h>
XL equ 0x78                        void main (void) {
XH equ 0x79
YL equ 0x7A                        int x, y, z; //16-bit variables
YH equ 0x7B                          // disable watchdog timer
    cseg at 0                        WDTCN = 0xde;
    ljmp Main                        WDTCN = 0xad;
cseg at 100h                         z = x + y;
; Disable watchdog timer
Main:     mov 0xFF, #0DEh          }
          mov 0xFF, #0ADh
          mov a, XL
          add a, YL
          mov XL, a
          mov a, XH                                       The C version
          addc a, YH
          mov XH, a
          nop               The assembly version
end


Prof. Cherrice Traver            EE/CS-152: Microprocessors
Compilation Process (Keil)
  Use the #pragma CODE
  compiler directive to
  get assembly code           adder.c
  generated in SRC file.

                                        compile     look here in RAM
                                                    when debugging
    adder.SRC                  adder.OBJ

       assemble                        build/make

                              adder.M51
      Map file shows where variables           Symbol Table in M51 file:
                                              ------   DO
      are stored. One map file is
                                               D:0008H       SYMBOL        x
      generated per project.                   D:000AH        SYMBOL       y
                                               D:000CH       SYMBOL        z
                                               ------- ENDDO

Prof. Cherrice Traver             EE/CS-152: Microprocessors
adder.SRC
           x?040:    DS   2
           y?041:    DS   2
           z?042:    DS   2
main:
                              ; SOURCE LINE # 12
; int x, y, z;
;        WDTCN = 0xde;                // disable watchdog timer
                             ; SOURCE LINE # 14
           MOV      WDTCN,#0DEH
;          WDTCN = 0xad;
                             ; SOURCE LINE # 15
           MOV      WDTCN,#0ADH
;          z = x + y;
                             ; SOURCE LINE # 17
           MOV      A,x?040+01H
           ADD      A,y?041+01H
           MOV      z?042+01H,A
           MOV      A,x?040
           ADDC     A,y?041
           MOV      z?042,A
;          }                          ; SOURCE LINE # 18
           RET
;   END OF main
           END



Prof. Cherrice Traver                  EE/CS-152: Microprocessors
Bitwise Logic Instructions
                                  Examples:
•   AND                 &       n = n & 0xF0;
•   OR                   |
•   XOR                  ^
•                               n = n & (0xFF << 4)
    left shift          <<
•   right shift         >>
•   1’s complement       ~      n = n & ~(0xFF >> 4)


Prof. Cherrice Traver   EE/CS-152: Microprocessors
Example – Logic in Assembly and C
Main:                                      void main (void) {
  mov WDTCN, #0DEh                         char x;
  mov WDTCN, #0ADh                         WDTCN = 0xDE;
  xrl a, #0xF0 ; invert bits 7-4           WDTCN = 0xAD;
  orl a, #0x0C ; set bits 3-2              x = x ^ 0xF0;
  anl a, #0xFC ; reset bits 1-0            x = x | 0x0C;
  mov P0, a ; send to port0                x = x & 0xFC;
                                           P0 = x;
                                           }




Prof. Cherrice Traver              EE/CS-152: Microprocessors
Loop Statements - While
• While loop:

    while (condition) { statements }

    while condition is true, execute statements

    if there is only one statement, we can lose the {}

    Example: while (1) ;         // loop forever

Prof. Cherrice Traver      EE/CS-152: Microprocessors
Loop Statements - For
• For statement:

  for (initialization; condition; increment) {statements}

  initialization done before statement is executed

  condition is tested, if true, execute statements
  do increment step and go back and test condition again

  repeat last two steps until condition is not true


 Prof. Cherrice Traver           EE/CS-152: Microprocessors
Example: for loop
             for (n = 0; n<1000; n++)
               n++ means n = n + 1

Be careful with signed integers!

       for (i=0; i < 33000; i++) LED = ~LED;


Why is this an infinite loop?
Prof. Cherrice Traver    EE/CS-152: Microprocessors
Loops: do - while

do
  statements
while (expression);


Test made at the bottom of the loop




Prof. Cherrice Traver   EE/CS-152: Microprocessors
Decision – if statement
if (condition1)
      {statements1}
    else if (condition2)
      {statements2}
    …
    else
      {statementsn}



Prof. Cherrice Traver      EE/CS-152: Microprocessors
Decision – switch statement
switch (expression) {
  case const-expr: statements
  case const-expr: statements
  default: statements
}




Prof. Cherrice Traver   EE/CS-152: Microprocessors
Example: switch
                                     Need a statement
switch (unibble) {                   like “return” or
                                     “break” or execution
  case 0x00 : return (0xC0);         falls through to the
  case 0x01 : return (0xF9);         next case (unlike
                                     VHDL)
  case 0x02 : return (0xA4);
  case 0x03 : return (0xC0);
     default : return (0xFF);
}


Prof. Cherrice Traver    EE/CS-152: Microprocessors
Revisit Toggle and Blink5




Prof. Cherrice Traver   EE/CS-152: Microprocessors
C Extensions: Additional Keywords
                              For accessing SFRs




                               Specify where variables go
                               in memory
Prof. Cherrice Traver   EE/CS-152: Microprocessors
Accessing Specific Memory




Prof. Cherrice Traver   EE/CS-152: Microprocessors
C Access to 8051 Memory
code: program
memory accessed by
movc @a + dptr                                          data

                                               bdata




                         idata
                                               xdata




 Prof. Cherrice Traver     EE/CS-152: Microprocessors
C Extensions for 8051 (Cygnal)
• New data types:

                    Example:
  bit               bit new_flag;    //stored in 20-2F
  sbit              sbit LED = P1^6;
  sfr               sfr SP = 0x81;   //stack pointer

  sfr16             sfr16 DP = 0x82; // data pointer


$INCLUDE (c8051F020.h)

Prof. Cherrice Traver       EE/CS-152: Microprocessors
C Data Types With Extensions




Prof. Cherrice Traver   EE/CS-152: Microprocessors
Declaring Variables in Memory

            char data temp;
            char idata varx;
            int xdata array[100];
            char code text[] = “Enter data”;




Prof. Cherrice Traver    EE/CS-152: Microprocessors
Example: Accessing External Memory
• Program defines two 256 element arrays in
  external memory
• First array is filled with values that increase
  by 2 each location.
• First array is copied to second array.
• Similar to block move exercise done in
  assembly.
• xdata_move.c


Prof. Cherrice Traver   EE/CS-152: Microprocessors
Interrupts – Original 8051




                                            Specify register bank 2

 void timer0 (void) interrupt 1 using 2 {
         if (++interruptcnt == 4000) {           /* count to 4000 */
         second++;                               /* second counter */
         interruptcnt = 0;                       /* clear int counter */
         }
 }
Prof. Cherrice Traver            EE/CS-152: Microprocessors
Other Interrupt Numbers




   Interrupt number is same as “Priority Order” in datasheet

Prof. Cherrice Traver         EE/CS-152: Microprocessors
Revisit Timer Exercise

                        Blinking!




Prof. Cherrice Traver       EE/CS-152: Microprocessors
In-line Assembly
• When it is more efficient, or easier, can
  insert assembly code in C programs.

    #pragma asm
    put your assembly code here
    #pragma endasm




Prof. Cherrice Traver   EE/CS-152: Microprocessors
Compilation Process (Keil)
                        program.c      .OBJ or .SRC can
                                       be generated, not both
   compile
                            no SRC          with SRC
                            option             option
program.LST             program.OBJ       program.SRC

                             build/make           rename file

                        program.M51        program.asm

                          build/make              assemble
                                           program.OBJ
        Must use this path for C programs with in-line assembly
        It is also necessary to add #pragma SRC to code

Prof. Cherrice Traver          EE/CS-152: Microprocessors
Example – Switch/LED Program
 #include <c8051F020.h>
 #pragma SRC                             // Need this to generate .SRC file
 void PORT_Init (void);

 char Get_SW(void) {
 #pragma ASM
 mov a, P3
 anl a, #80h              ; mask all but P3.7
 mov R7, a                ; function value (char) returned in R7
 #pragma ENDASM
 }

 void Set_LED(void) {
 #pragma ASM
 setb P1.6
                                                 Functions can be implemented
 #pragma ENDASM
 }
                                                 in assembly language
 void Clr_LED(void) {
 #pragma ASM
 clr P1.6
 #pragma ENDASM
 }
 void PORT_Init (void){ XBR2   = 0x40;        // Enable crossbar and enable P1.6 (LED) as push-pull output}
 P1MDOUT |= 0x40;                            // enable P1.6 (LED) as push-pull output
 }
 void main(void) {
 PORT_Init();                                     Main function
 while (1)
 if (Get_SW()) Set_LED();
 else Clr_LED();
              }
Prof. Cherrice Traver                                  EE/CS-152: Microprocessors
Interfacing with C
• Example: Temperature Sensor program
    – Configures the external oscillator
    – Configures the ADC0 for temp. sensor
    – Configures Port1 so LED can be used
    – Configures Timer3 to synch the ADC0
    – Uses ADC0 ISR to take temperature samples and
      averages 256 of them and posts average to global
      variable
    – Main program compares average temp. to room temp.
      and lights LED if temp is warmer.
    – Temp_2.c



Prof. Cherrice Traver       EE/CS-152: Microprocessors
Revisit DAC0 Program

               And “C” the difference!




Prof. Cherrice Traver     EE/CS-152: Microprocessors
Converting to Real Values
• C makes it easier to implement equations
Example: Temperature conversion
For analog to digital conversion – assuming left
  justified:                         ADC 0 / 16 Vref
                               V=       12
                                               ×
                                       2         Gain

The temperature sensor:
                                      V − 0.776
                              TempC =
                                       0.00286

Prof. Cherrice Traver     EE/CS-152: Microprocessors
Temperature Conversion
              ADC 0 / 16 Vref
            (    12
                         ×      ) − 0.776
    TempC =     2          Gain
                       0.00286

Let Vref = 2.4V, Gain = 2

                    ADC 0 − 42380
            TempC =
                        156


Prof. Cherrice Traver       EE/CS-152: Microprocessors
C for the Equation
                          ADC 0 − 42380
                  TempC =
                              156
…
unsigned int result, temperature;

…
result = ADC0;                          //read temperature sensor
temperature = result - 42380;
temperature = temperature / 156;

* Must be careful about range of values expected and variable types

 Prof. Cherrice Traver              EE/CS-152: Microprocessors
Make it REAL!

              Temperature Conversion




Prof. Cherrice Traver   EE/CS-152: Microprocessors
Initialization
• When a C program is compiled, some code
  is created that runs BEFORE the main
  program.
• This code clears RAM to zero and
  initializes your variables. Here is a segment
  of this code:            LJMP 0003h
                        0003: MOV R0, #7FH
                              CLR A
                        back: MOV @R0, A
                              DJNZ R0, back
                        ...

Prof. Cherrice Traver      EE/CS-152: Microprocessors
Arrays in C
• Useful for storing data

    type arr_name[dimension]               temp_array[0]
                                           temp_array[1]
                                           temp_array[2]
    char   temp_array[256]                 temp_array[3]
                                           ...
    Array elements are stored in           temp_array[253]
      adjacent locations in memory.        temp_array[254]
                                           temp_array[255]



Prof. Cherrice Traver        EE/CS-152: Microprocessors
Pointers in C
• Pointers are variables that hold memory
  addresses.
• Specified using * prefix.

int *pntr;   // defines a pointer, pntr
pntr = &var; // assigns address of var to pntr




Prof. Cherrice Traver        EE/CS-152: Microprocessors
Pointers and Arrays
Note: the name of an array is a pointer to
the first element:
*temp_array is the same as temp_array[0]
So the following are the same:
   n = *temp_array;
   n = temp_array[0];
                                  temp_array[0]
and these are also the same:      temp_array[1]
                                  temp_array[2]
   n = *(temp_array+5);
                                  temp_array[3]
   n = temp_array[5];             …

Prof. Cherrice Traver            EE/CS-152: Microprocessors
Arrays
• In watch window, address (pointer) of first
  element array is shown.
• Array is not initialized as you specify when
  you download or reset, but it will be when
  Main starts.
unsigned char P0_out[4] = {0x01,0x02,0x04,0x08};




Prof. Cherrice Traver       EE/CS-152: Microprocessors
Array Example




Prof. Cherrice Traver   EE/CS-152: Microprocessors
Compiler Optimization Levels
• Optimization level can be set by compiler
  control directive:
• Examples (default is #pragma (8, speed)
    – #pragma ot (7)
    – #pragma ot (9, size)
    – #pragma ot (size) – reduce memory used at the
      expense of speed.
    – #pragma ot (speed) – reduce execution time at
      the expense of memory.

Prof. Cherrice Traver     EE/CS-152: Microprocessors
Compiler Optimization Levels
Level      Optimizations added for that level

0          Constant Folding: The compiler performs calculations that reduce expressions to numeric constants,
           where possible.This includes calculations of run-time addresses.
           Simple Access Optimizing: The compiler optimizes access of internal data and bit addresses in the
           8051 system.
           Jump Optimizing: The compiler always extends jumps to the final target. Jumps to jumps are deleted.

1          Dead Code Elimination: Unused code fragments and artifacts are eliminated.
           Jump Negation: Conditional jumps are closely examined to see if they can be streamlined or eliminated
           by the inversion of the test logic.

2          ....
3
4
5
6
7
8

9          Common Block Subroutines: Detects recurring instruction sequences and converts them into
           subroutines. Cx51 evenrearranges code to obtain larger recurring sequences.



    Prof. Cherrice Traver                           EE/CS-152: Microprocessors
Example: 7-seg Decoder
// Program to convert 0-F into 7-segment equivalents.
#pragma debug code)
#pragma ot (9)
#include <c8051f020.h>
#define NUM_SAMPLES 16
unsigned char SEGS7[16] = {0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92,
0x82, 0xF8, 0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E};

xdata unsigned char samples[NUM_SAMPLES];

void main (void)
{
   char i;                    // loop counter
   WDTCN = 0xde;
   WDTCN = 0xad;
   for (i=0; i < NUM_SAMPLES; i++)
        {samples[i] = SEGS7[i];}
   while (1);
}



Prof. Cherrice Traver         EE/CS-152: Microprocessors
Effect of Optimization Level on
                 Code Size
                        Level      Code Size
                         0            53
                         1            53
                         2            53
                         3            51
                         4            46
                         5            46
                         6            39
                         7            39
                         8            38
                         9            38




Prof. Cherrice Traver           EE/CS-152: Microprocessors
Level 0 Optimization
   ; FUNCTION main (BEGIN)
   0000 75FFDE             MOV    WDTCN,#0DEH
   0003 75FFAD             MOV    WDTCN,#0ADH
   ;---- Variable 'i' assigned to Register 'R7' ----
   0006 750000      R      MOV    i,#00H
   0009 C3                 CLR    C
   000A E500        R      MOV    A,i
   000C 6480               XRL    A,#080H
   000E 9490               SUBB   A,#090H
   0010 5020               JNC    ?C0004
   0012 AF00        R      MOV    R7,i
   0014 7400        R      MOV    A,#LOW SEGS7
   0016 2F                 ADD    A,R7
   0017 F8                 MOV    R0,A
   0018 E6                 MOV    A,@R0
   …




Prof. Cherrice Traver       EE/CS-152: Microprocessors
Level 9 Optimization

   ; FUNCTION main (BEGIN)
   0000 75FFDE             MOV    WDTCN,#0DEH
   0003 75FFAD             MOV    WDTCN,#0ADH
   ;---- Variable 'i' assigned to Register 'R7' ----
   0006 E4                 CLR    A
   0007 FF                 MOV    R7,A
   0008 7400        R      MOV    A,#LOW SEGS7
   000A 2F                 ADD    A,R7
   000B F8                 MOV    R0,A
   000C E6                 MOV    A,@R0
   …




Prof. Cherrice Traver       EE/CS-152: Microprocessors
Memory Models
• Small - places all function variables and local data segments in the internal
   data memory (RAM) of the 8051 system. This allows very efficient access to
   data objects (direct and register modes). The address space of the SMALL
   memory model, however, is limited.
• Large - all variables and local data segments of functions and procedures
   reside (as defined) in the external data memory of the 8051 system. Up to 64
   KBytes of external data memory may be accessed. This,however, requires the
   long and therefore inefficient form of data access through the data pointer
   (DPTR).
• Selected by compiler directives
• Examples:
    – #pragma small
    – #pragma large


Prof. Cherrice Traver                  EE/CS-152: Microprocessors
Example: LARGE
 0006   E4              CLR    A
 0007   FF              MOV    R7,A
 0008   EF              MOV    A,R7
 0009   FD              MOV    R5,A
 000A   33              RLC    A     ;multiply by 2
 000B   95E0            SUBB   A,ACC
 000D   FC              MOV    R4,A
 000E   7400     R      MOV    A,#LOW SEGS7
 0010   2D              ADD    A,R5
 0011   F582            MOV    DPL,A
 0013   7400     R      MOV    A,#HIGH SEGS7
 0015   3C              ADDC   A,R4
 0016   F583            MOV    DPH,A
 0018   E0              MOVX   A,@DPTR
 ….

Registers R4, R5 keep track of 16-bit data address (external RAM)


Prof. Cherrice Traver          EE/CS-152: Microprocessors
Example: SMALL
 0006   E4              CLR   A
 0007   FF              MOV   R7,A
 0008   7400     R      MOV   A,#LOW SEGS7
 000A   2F              ADD   A,R7
 000B   F8              MOV   R0,A
 000C   E6              MOV   A,@R0
 ….


 Data address = #LOW SEGS7 + R7 (8-bit address, RAM)




Prof. Cherrice Traver         EE/CS-152: Microprocessors
Initialization
• When a C program is compiled, some code
  is created that runs BEFORE the main
  program.
• This code clears RAM to zero and
  initializes your variables. Here is a segment
  of this code:            LJMP 0003h
                        0003: MOV R0, #7FH
                              CLR A
                        back: MOV @R0, A
                              DJNZ R0, back
                        ...

Prof. Cherrice Traver      EE/CS-152: Microprocessors
I/O Circuitry - Exercise
             Bits accessed via SFRs
                                                 Port Bit
                                                 (ex: P1.0)




Prof. Cherrice Traver        EE/CS-152: Microprocessors
Can be disabled.         By default, inputs
                                           are “pulled up” by
                                              weak pullup
                                                transistor




                                                    Therefore, if
                                                    not connected
                                                    to anything,
                                                    inputs are read
                                                    as “1”.



Prof. Cherrice Traver         EE/CS-152: Microprocessors
Port I/O - Output
                        Output circuit:
                        • Only enabled if /PORT-OUTENABLE = 0
                        • PUSH-PULL = 1 enables P transistor
                        • Non-PUSH-PULL allows wired-or outputs




Prof. Cherrice Traver   EE/CS-152: Microprocessors
Port I/O - Input




                 Port 1 can be configured for either digital or
                 analog inputs using a pass transistor and buffer

Prof. Cherrice Traver            EE/CS-152: Microprocessors
Port I/O Example
                        XBR2 = 0x40;          // Enable XBAR2
                        P0MDOUT = 0x0F; // Outputs on P0 (0-3)
                        …
 Port 0                 P0 = 0x07;   // Set pins 2,1,0 and clear pin 3
 Latch    I/O Cells     temp = P0;  // Read Port0
   7
   6
                        input pins
   5
   4
   3
   2
                        output pins
   1
   0

Prof. Cherrice Traver        EE/CS-152: Microprocessors
Keypad Interface




Prof. Cherrice Traver   EE/CS-152: Microprocessors
C for Large Projects
• Use functions to make programs modular
• Break project into separate files if the
  programs get too large
• Use header (#include) files to hold
  definitions used by several programs
• Keep main program short and easy to
  follow
• Consider multi-tasking or multi-threaded
  implementations

Prof. Cherrice Traver   EE/CS-152: Microprocessors
Functions
• The basis for modular structured
  programming in C.

return-type function-name(argument declarations)
{
       declarations and statements
}




Prof. Cherrice Traver      EE/CS-152: Microprocessors
Example – no return value or arguments
void SYSCLK_Init (void) {
  // Delay counter
  int i;
         // Start external oscillator with 22.1184MHz crystal
         OSCXCN = 0x67;
         // Wait for XTLVLD blanking interval (>1ms)
         for (i = 0; i < 256; i++) ;
         // Wait for crystal osc. to settle
         while (!(OSCXCN & 0x80)) ;
         // Select external oscillator as SYSCLK
         OSCICN = 0x88;
}


 Prof. Cherrice Traver              EE/CS-152: Microprocessors
Example – with arguments
void Timer3_Init (int counts) {
   // Stop timer, clear TF3, use SYSCLK as timebase
   TMR3CN = 0x02;
   // Init reload value
   TMR3RL = -counts;
   // Set to reload immediately
   TMR3 = 0xffff;
   // Disable interrupts
   EIE2 &= ~0x01;
   // Start timer
   TMR3CN |= 0x04;
}


Prof. Cherrice Traver          EE/CS-152: Microprocessors
Example – with return value
             char ascii_conv (char num) {
               return num + 30;
               }




Prof. Cherrice Traver       EE/CS-152: Microprocessors
Header Files
    • Use to define global constants and variables
// 16-bit SFR Definitions for 'F02x
      sfr16 TMR3RL = 0x92;           // Timer3 reload value
      sfr16 TMR3 = 0x94;             // Timer3 counter
      sfr16 ADC0 = 0xbe;             // ADC0 data
      sfr16 DAC0 = 0xd2;             // DAC data
      sfr16 DAC1 = 0xd5;
// Global CONSTANTS
      #define SYSCLK 22118400              // SYSCLK frequency in Hz
      sbit LED = P1^6;                     // LED='1' means ON
      sbit SW1 = P3^7;                     // SW1='0' means switch pressed
      #define MAX_DAC ((1<<12)-1)          // Maximum value of the DAC register 12 bits
      #define MAX_INTEGRAL (1L<<24)        // Maximum value of the integral
// Function PROTOTYPES
      void SYSCLK_Init (void);
      void PORT_Init (void);
      void ADC0_Init (void);
      void DAC_Init (void);
      void Timer3_Init (int counts);
      void ADC0_ISR (void);

 Prof. Cherrice Traver                   EE/CS-152: Microprocessors
Multitasking and Multithreading
• Multitasking: Perception of multiple tasks
  being executed simultaneously.
    – Usually a feature of an operating system and
      tasks are separate applications.
    – Embedded systems are usually dedicated to one
      application.
• Multithreading: Perception of multiple tasks
  within a single application being executed.
    – Example: Cygnal IDE color codes while
      echoing characters you type.

Prof. Cherrice Traver    EE/CS-152: Microprocessors
Multitasking and Multithreading
                      A “thread”
void main (void) {                             void SYSCLK_Init (void){
  long temperature;                              int i;
      WDTCN = 0xde;                              OSCXCN = 0x67;
      WDTCN = 0xad;                              for (i=0; i < 256; i++) ;
      SYSCLK_Init():                             while (!(OSCXCN & 0x80)) ;
      PORT_Init ();                              OSCICN = 0x88; }
     Timer3_Init (SYSCLK/SAMPLE_RATE);
      AD0EN = 1;                                               void PORT_Init (void) {
      EA = 1;                                                    XBR0 = 0x04;
      while (1) {                                                XBR1 = 0x00;
               temperature = result;                             XBR2 = 0x40;
            if (temperature < 0xB230) LED = 0;                   P0MDOUT |= 0x01;
            else LED = 1;                                        P1MDOUT |= 0x40;}
            }                   void Timer3_Init (int counts) {
   }                               TMR3CN = 0x02;
                                  TMR3RL = -counts;
                                  TMR3 = 0xffff;
                                  EIE2 &= ~0x01;
                                  TMR3CN |= 0x04; }
  Prof. Cherrice Traver                       EE/CS-152: Microprocessors
Multi-tasking/threading Implementations
• Cooperative multi-tasking – each application runs
  for a short time and then yields control to the next
  application.
• Timer-based multi-tasking – on each timer
  interrupt, tasks are switched.
• When switching between tasks, state of processor
  (internal registers, flags, etc) must be saved and
  previous state from last task restored. This is the
  “overhead” of multitasking. Also called “context
  switching”.

Prof. Cherrice Traver      EE/CS-152: Microprocessors
Multithreading with Interrupts
                        Interrupt
 Foreground thread       Service
   Main program          Routine    Background thread
                           reti

     Subroutines
                        Interrupt
         ret
                         Service
                         Routine    Background thread

                           reti



Prof. Cherrice Traver   EE/CS-152: Microprocessors
Real-Time Operating Systems
                  (RTOS)
• Usually a timer-based task switching
  system that can guarantee a certain response
  time.
• Low level functions implement task
  switching.
• High level functions create and terminate
  threads or tasks.
• Each task might have its own software stack
  for storing processor state.
Prof. Cherrice Traver   EE/CS-152: Microprocessors
Ad

More Related Content

What's hot (20)

Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
MOHAMAD NOH AHMAD
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for Engineering
Vincenzo De Florio
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
Malikireddy Bramhananda Reddy
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
amol_chavan
 
C language introduction
C language introduction C language introduction
C language introduction
musrath mohammad
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
JavaTpoint.Com
 
C PROGRAMMING
C PROGRAMMINGC PROGRAMMING
C PROGRAMMING
Stalongiles Philip
 
C programming
C programmingC programming
C programming
Rounak Samdadia
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
ABHISHEK fulwadhwa
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
Kumar Gaurav
 
C basics
C   basicsC   basics
C basics
thirumalaikumar3
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming Language
Vincenzo De Florio
 
C Programming Language Step by Step Part 1
C Programming Language Step by Step Part 1C Programming Language Step by Step Part 1
C Programming Language Step by Step Part 1
Rumman Ansari
 
C programming language
C programming languageC programming language
C programming language
Maha lakshmi
 
Embedded c program and programming structure for beginners
Embedded c program and programming structure for beginnersEmbedded c program and programming structure for beginners
Embedded c program and programming structure for beginners
Kamesh Mtec
 
COM1407: Introduction to C Programming
COM1407: Introduction to C Programming COM1407: Introduction to C Programming
COM1407: Introduction to C Programming
Hemantha Kulathilake
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
MalikaJoya
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
Mohamed Elsayed
 
Sachin kumar ppt on programming in c
Sachin kumar ppt on programming in cSachin kumar ppt on programming in c
Sachin kumar ppt on programming in c
Sachin Kumar
 
C Language
C LanguageC Language
C Language
Aakash Singh
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
MOHAMAD NOH AHMAD
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for Engineering
Vincenzo De Florio
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
amol_chavan
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
JavaTpoint.Com
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
Kumar Gaurav
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming Language
Vincenzo De Florio
 
C Programming Language Step by Step Part 1
C Programming Language Step by Step Part 1C Programming Language Step by Step Part 1
C Programming Language Step by Step Part 1
Rumman Ansari
 
C programming language
C programming languageC programming language
C programming language
Maha lakshmi
 
Embedded c program and programming structure for beginners
Embedded c program and programming structure for beginnersEmbedded c program and programming structure for beginners
Embedded c program and programming structure for beginners
Kamesh Mtec
 
COM1407: Introduction to C Programming
COM1407: Introduction to C Programming COM1407: Introduction to C Programming
COM1407: Introduction to C Programming
Hemantha Kulathilake
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
MalikaJoya
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
Mohamed Elsayed
 
Sachin kumar ppt on programming in c
Sachin kumar ppt on programming in cSachin kumar ppt on programming in c
Sachin kumar ppt on programming in c
Sachin Kumar
 

Viewers also liked (20)

8051 programming skills using EMBEDDED C
8051 programming skills using EMBEDDED C8051 programming skills using EMBEDDED C
8051 programming skills using EMBEDDED C
Aman Sharma
 
Chapter 7 8051 programming in c
Chapter 7  8051 programming in cChapter 7  8051 programming in c
Chapter 7 8051 programming in c
Abdelrahman Elewah
 
C language programming (description in simple words)
C language programming (description in simple words)C language programming (description in simple words)
C language programming (description in simple words)
mujeeb memon
 
Raghavendra Rao A
Raghavendra Rao ARaghavendra Rao A
Raghavendra Rao A
Raghavendra Rao Amberkar
 
Automating the Configuration of the FlexRay Communication Cycle
Automating the Configuration of the FlexRay Communication CycleAutomating the Configuration of the FlexRay Communication Cycle
Automating the Configuration of the FlexRay Communication Cycle
Nicolas Navet
 
Configuring the communication on FlexRay: the case of the static segment
Configuring the communication on FlexRay: the case of the static segmentConfiguring the communication on FlexRay: the case of the static segment
Configuring the communication on FlexRay: the case of the static segment
Nicolas Navet
 
Final ppt
Final pptFinal ppt
Final ppt
Zankar Sanghvi
 
8051 microcontroller
8051 microcontroller8051 microcontroller
8051 microcontroller
Shubhrika Sehgal
 
1347 assemblylanguageprogrammingof8051-100523023308-phpapp01
1347 assemblylanguageprogrammingof8051-100523023308-phpapp011347 assemblylanguageprogrammingof8051-100523023308-phpapp01
1347 assemblylanguageprogrammingof8051-100523023308-phpapp01
bvenkanna
 
Unit ii microcontrollers final
Unit ii microcontrollers finalUnit ii microcontrollers final
Unit ii microcontrollers final
SARITHA REDDY
 
Keynote 4 cornelius_koetz_v04
Keynote 4 cornelius_koetz_v04Keynote 4 cornelius_koetz_v04
Keynote 4 cornelius_koetz_v04
goodgolier
 
FlexRay
FlexRayFlexRay
FlexRay
Greeshma S
 
8051 basic programming
8051 basic programming8051 basic programming
8051 basic programming
ANJUSHA R
 
The 8051 microcontroller
The 8051  microcontroller The 8051  microcontroller
The 8051 microcontroller
Avinash Mishra
 
flexray technology in modern cars
flexray technology in modern carsflexray technology in modern cars
flexray technology in modern cars
Amit Yerva
 
8051 ch9-950217
8051 ch9-9502178051 ch9-950217
8051 ch9-950217
Gopal Krishna Murthy C R
 
The flex ray protocol
The flex ray protocolThe flex ray protocol
The flex ray protocol
Wissam Kafa
 
8051 programming in c
8051 programming in c8051 programming in c
8051 programming in c
Dr. Ritula Thakur
 
8051 Programming Instruction Set
 8051 Programming Instruction Set 8051 Programming Instruction Set
8051 Programming Instruction Set
Shreyans Pathak
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
SULTHAN BASHA
 
8051 programming skills using EMBEDDED C
8051 programming skills using EMBEDDED C8051 programming skills using EMBEDDED C
8051 programming skills using EMBEDDED C
Aman Sharma
 
Chapter 7 8051 programming in c
Chapter 7  8051 programming in cChapter 7  8051 programming in c
Chapter 7 8051 programming in c
Abdelrahman Elewah
 
C language programming (description in simple words)
C language programming (description in simple words)C language programming (description in simple words)
C language programming (description in simple words)
mujeeb memon
 
Automating the Configuration of the FlexRay Communication Cycle
Automating the Configuration of the FlexRay Communication CycleAutomating the Configuration of the FlexRay Communication Cycle
Automating the Configuration of the FlexRay Communication Cycle
Nicolas Navet
 
Configuring the communication on FlexRay: the case of the static segment
Configuring the communication on FlexRay: the case of the static segmentConfiguring the communication on FlexRay: the case of the static segment
Configuring the communication on FlexRay: the case of the static segment
Nicolas Navet
 
1347 assemblylanguageprogrammingof8051-100523023308-phpapp01
1347 assemblylanguageprogrammingof8051-100523023308-phpapp011347 assemblylanguageprogrammingof8051-100523023308-phpapp01
1347 assemblylanguageprogrammingof8051-100523023308-phpapp01
bvenkanna
 
Unit ii microcontrollers final
Unit ii microcontrollers finalUnit ii microcontrollers final
Unit ii microcontrollers final
SARITHA REDDY
 
Keynote 4 cornelius_koetz_v04
Keynote 4 cornelius_koetz_v04Keynote 4 cornelius_koetz_v04
Keynote 4 cornelius_koetz_v04
goodgolier
 
8051 basic programming
8051 basic programming8051 basic programming
8051 basic programming
ANJUSHA R
 
The 8051 microcontroller
The 8051  microcontroller The 8051  microcontroller
The 8051 microcontroller
Avinash Mishra
 
flexray technology in modern cars
flexray technology in modern carsflexray technology in modern cars
flexray technology in modern cars
Amit Yerva
 
The flex ray protocol
The flex ray protocolThe flex ray protocol
The flex ray protocol
Wissam Kafa
 
8051 Programming Instruction Set
 8051 Programming Instruction Set 8051 Programming Instruction Set
8051 Programming Instruction Set
Shreyans Pathak
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
SULTHAN BASHA
 
Ad

Similar to C language programming (20)

C language programming
C language programmingC language programming
C language programming
Vaibhav Salonia
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5
PRADEEP
 
The 8051 assembly language
The 8051 assembly languageThe 8051 assembly language
The 8051 assembly language
hemant meena
 
6- Threaded Interpretation.docx
6- Threaded Interpretation.docx6- Threaded Interpretation.docx
6- Threaded Interpretation.docx
shruti533256
 
Lecture 01 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001Lecture 01 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001
MahmoudElsamanty
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
PurvaShyama
 
Short Notes on Verilog and SystemVerilog
Short Notes on Verilog and SystemVerilogShort Notes on Verilog and SystemVerilog
Short Notes on Verilog and SystemVerilog
Jason J Pulikkottil
 
Verilogforlab
VerilogforlabVerilogforlab
Verilogforlab
Shankar Bhukya
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Sergey Platonov
 
dokumen.tips_verilog-basic-ppt.pdf
dokumen.tips_verilog-basic-ppt.pdfdokumen.tips_verilog-basic-ppt.pdf
dokumen.tips_verilog-basic-ppt.pdf
Velmathi Saravanan
 
verilog ppt .pdf
verilog ppt .pdfverilog ppt .pdf
verilog ppt .pdf
RavinaBishnoi8
 
Lenguaje de Programación en C Presentacion
Lenguaje de Programación en C PresentacionLenguaje de Programación en C Presentacion
Lenguaje de Programación en C Presentacion
jicemtec
 
Verilog Cheat sheet-2 (1).pdf
Verilog Cheat sheet-2 (1).pdfVerilog Cheat sheet-2 (1).pdf
Verilog Cheat sheet-2 (1).pdf
DrViswanathKalannaga1
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdf
sagar414433
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdf
sagar414433
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
Mohamed Ali
 
College1
College1College1
College1
Sudharsan S
 
LCD_Example.pptx
LCD_Example.pptxLCD_Example.pptx
LCD_Example.pptx
julioalexanderaguila
 
MIPS instruction set microprocessor lecture notes
MIPS instruction set microprocessor lecture notesMIPS instruction set microprocessor lecture notes
MIPS instruction set microprocessor lecture notes
RevathiSoundiran1
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone?
DVClub
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5
PRADEEP
 
The 8051 assembly language
The 8051 assembly languageThe 8051 assembly language
The 8051 assembly language
hemant meena
 
6- Threaded Interpretation.docx
6- Threaded Interpretation.docx6- Threaded Interpretation.docx
6- Threaded Interpretation.docx
shruti533256
 
Lecture 01 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001Lecture 01 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001
MahmoudElsamanty
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
PurvaShyama
 
Short Notes on Verilog and SystemVerilog
Short Notes on Verilog and SystemVerilogShort Notes on Verilog and SystemVerilog
Short Notes on Verilog and SystemVerilog
Jason J Pulikkottil
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Sergey Platonov
 
dokumen.tips_verilog-basic-ppt.pdf
dokumen.tips_verilog-basic-ppt.pdfdokumen.tips_verilog-basic-ppt.pdf
dokumen.tips_verilog-basic-ppt.pdf
Velmathi Saravanan
 
Lenguaje de Programación en C Presentacion
Lenguaje de Programación en C PresentacionLenguaje de Programación en C Presentacion
Lenguaje de Programación en C Presentacion
jicemtec
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdf
sagar414433
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdf
sagar414433
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
Mohamed Ali
 
MIPS instruction set microprocessor lecture notes
MIPS instruction set microprocessor lecture notesMIPS instruction set microprocessor lecture notes
MIPS instruction set microprocessor lecture notes
RevathiSoundiran1
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone?
DVClub
 
Ad

Recently uploaded (20)

*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 

C language programming

  • 1. C Language Programming for the 8051 Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 2. Overview • C for microcontrollers – Review of C basics – Compilation flow for SiLabs IDE – C extensions – In-line assembly – Interfacing with C • Examples • Arrays and Pointers • I/O Circuitry • Functions and Header Files • Multitasking and multithreading Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 3. C for Microcontrollers • Of higher level languages, C is the closest to assembly languages – bit manipulation instructions – pointers (indirect addressing) • Most microcontrollers have available C compilers • Writing in C simplifies code development for large projects. Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 4. Available C Compilers • Kiel – integrated with the IDE we have been using for labs. • Reads51 – available on web site ( http://www.rigelcorp.com/reads51.htm) • Freeware: SDCC - Small Device C Compiler (http://sdcc.sourceforge.net/) • Other freeware versions … Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 5. Compilation Process (Keil) program.c no SRC compile option program.LST program.OBJ build/make program.M51 Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 6. Modular Programming • Like most high level languages, C is a modular programming language (but NOT an object oriented language) • Each task can be encapsulated as a function. • Entire program is encapsulated in “main” function. Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 7. Basic C Program Structure 1. Compiler directives and include files 2. Declarations of global variables and constants 3. Declaration of functions 4. Main function 5. Sub-functions 6. Interrupt service routines Example: blinky.c Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 8. Back to C Basics • All C programs consists of: – Variables – Functions (one must be “main”) • Statements • To define the SFRs as variables: #include <c8051F020.h> Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 9. Variables • All variables must be declared at top of program, before the first statement. • Declaration includes type and list of variables. Example: void main (void) { int var, tmp; must go HERE! • Types: – int (16-bits in our compiler) – char (8-bits) – short (16-bits) – long (32-bits) – sbit (1-bit) not standard C – an 8051 extension – others that we will discuss later Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 10. Variables • The following variable types can be signed or unsigned: signed char (8 bits) –128 to +127 signed short (16 bits) –32768 to +32767 signed int (16 bits) –32768 to +32767 signed long (32 bits) –2147483648 to +2147483648 unsigned char (8 bits) 0 to + 255 unsigned short (16 bits) 0 to + 65535 unsigned int (16 bits) 0 to + 65535 unsigned long (32 bits) 0 to + 4294967295 NOTE: Default is signed – it is best to specify. Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 11. Statements • Assignment statement: variable = constant or expression or variable examples: upper = 60; I = I + 5; J = I; Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 12. Operators • Arithmetic: +, -, *, / • Relational comparisons: >, >=, <, <= • Equality comparisons: ==, != • Logical operators: && (and), || (or) • Increment and decrement: ++, -- • Example: if (x != y) && (c == b) { a=c + d*b; a++; } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 13. Example – Adder program (add 2 16-bit numbers) $INCLUDE (C8051F020.inc) #include <c8051f020.h> XL equ 0x78 void main (void) { XH equ 0x79 YL equ 0x7A int x, y, z; //16-bit variables YH equ 0x7B // disable watchdog timer cseg at 0 WDTCN = 0xde; ljmp Main WDTCN = 0xad; cseg at 100h z = x + y; ; Disable watchdog timer Main: mov 0xFF, #0DEh } mov 0xFF, #0ADh mov a, XL add a, YL mov XL, a mov a, XH The C version addc a, YH mov XH, a nop The assembly version end Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 14. Compilation Process (Keil) Use the #pragma CODE compiler directive to get assembly code adder.c generated in SRC file. compile look here in RAM when debugging adder.SRC adder.OBJ assemble build/make adder.M51 Map file shows where variables Symbol Table in M51 file: ------ DO are stored. One map file is D:0008H SYMBOL x generated per project. D:000AH SYMBOL y D:000CH SYMBOL z ------- ENDDO Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 15. adder.SRC x?040: DS 2 y?041: DS 2 z?042: DS 2 main: ; SOURCE LINE # 12 ; int x, y, z; ; WDTCN = 0xde; // disable watchdog timer ; SOURCE LINE # 14 MOV WDTCN,#0DEH ; WDTCN = 0xad; ; SOURCE LINE # 15 MOV WDTCN,#0ADH ; z = x + y; ; SOURCE LINE # 17 MOV A,x?040+01H ADD A,y?041+01H MOV z?042+01H,A MOV A,x?040 ADDC A,y?041 MOV z?042,A ; } ; SOURCE LINE # 18 RET ; END OF main END Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 16. Bitwise Logic Instructions Examples: • AND & n = n & 0xF0; • OR | • XOR ^ • n = n & (0xFF << 4) left shift << • right shift >> • 1’s complement ~ n = n & ~(0xFF >> 4) Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 17. Example – Logic in Assembly and C Main: void main (void) { mov WDTCN, #0DEh char x; mov WDTCN, #0ADh WDTCN = 0xDE; xrl a, #0xF0 ; invert bits 7-4 WDTCN = 0xAD; orl a, #0x0C ; set bits 3-2 x = x ^ 0xF0; anl a, #0xFC ; reset bits 1-0 x = x | 0x0C; mov P0, a ; send to port0 x = x & 0xFC; P0 = x; } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 18. Loop Statements - While • While loop: while (condition) { statements } while condition is true, execute statements if there is only one statement, we can lose the {} Example: while (1) ; // loop forever Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 19. Loop Statements - For • For statement: for (initialization; condition; increment) {statements} initialization done before statement is executed condition is tested, if true, execute statements do increment step and go back and test condition again repeat last two steps until condition is not true Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 20. Example: for loop for (n = 0; n<1000; n++) n++ means n = n + 1 Be careful with signed integers! for (i=0; i < 33000; i++) LED = ~LED; Why is this an infinite loop? Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 21. Loops: do - while do statements while (expression); Test made at the bottom of the loop Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 22. Decision – if statement if (condition1) {statements1} else if (condition2) {statements2} … else {statementsn} Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 23. Decision – switch statement switch (expression) { case const-expr: statements case const-expr: statements default: statements } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 24. Example: switch Need a statement switch (unibble) { like “return” or “break” or execution case 0x00 : return (0xC0); falls through to the case 0x01 : return (0xF9); next case (unlike VHDL) case 0x02 : return (0xA4); case 0x03 : return (0xC0); default : return (0xFF); } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 25. Revisit Toggle and Blink5 Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 26. C Extensions: Additional Keywords For accessing SFRs Specify where variables go in memory Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 27. Accessing Specific Memory Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 28. C Access to 8051 Memory code: program memory accessed by movc @a + dptr data bdata idata xdata Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 29. C Extensions for 8051 (Cygnal) • New data types: Example: bit bit new_flag; //stored in 20-2F sbit sbit LED = P1^6; sfr sfr SP = 0x81; //stack pointer sfr16 sfr16 DP = 0x82; // data pointer $INCLUDE (c8051F020.h) Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 30. C Data Types With Extensions Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 31. Declaring Variables in Memory char data temp; char idata varx; int xdata array[100]; char code text[] = “Enter data”; Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 32. Example: Accessing External Memory • Program defines two 256 element arrays in external memory • First array is filled with values that increase by 2 each location. • First array is copied to second array. • Similar to block move exercise done in assembly. • xdata_move.c Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 33. Interrupts – Original 8051 Specify register bank 2 void timer0 (void) interrupt 1 using 2 { if (++interruptcnt == 4000) { /* count to 4000 */ second++; /* second counter */ interruptcnt = 0; /* clear int counter */ } } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 34. Other Interrupt Numbers Interrupt number is same as “Priority Order” in datasheet Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 35. Revisit Timer Exercise Blinking! Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 36. In-line Assembly • When it is more efficient, or easier, can insert assembly code in C programs. #pragma asm put your assembly code here #pragma endasm Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 37. Compilation Process (Keil) program.c .OBJ or .SRC can be generated, not both compile no SRC with SRC option option program.LST program.OBJ program.SRC build/make rename file program.M51 program.asm build/make assemble program.OBJ Must use this path for C programs with in-line assembly It is also necessary to add #pragma SRC to code Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 38. Example – Switch/LED Program #include <c8051F020.h> #pragma SRC // Need this to generate .SRC file void PORT_Init (void); char Get_SW(void) { #pragma ASM mov a, P3 anl a, #80h ; mask all but P3.7 mov R7, a ; function value (char) returned in R7 #pragma ENDASM } void Set_LED(void) { #pragma ASM setb P1.6 Functions can be implemented #pragma ENDASM } in assembly language void Clr_LED(void) { #pragma ASM clr P1.6 #pragma ENDASM } void PORT_Init (void){ XBR2 = 0x40; // Enable crossbar and enable P1.6 (LED) as push-pull output} P1MDOUT |= 0x40; // enable P1.6 (LED) as push-pull output } void main(void) { PORT_Init(); Main function while (1) if (Get_SW()) Set_LED(); else Clr_LED(); } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 39. Interfacing with C • Example: Temperature Sensor program – Configures the external oscillator – Configures the ADC0 for temp. sensor – Configures Port1 so LED can be used – Configures Timer3 to synch the ADC0 – Uses ADC0 ISR to take temperature samples and averages 256 of them and posts average to global variable – Main program compares average temp. to room temp. and lights LED if temp is warmer. – Temp_2.c Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 40. Revisit DAC0 Program And “C” the difference! Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 41. Converting to Real Values • C makes it easier to implement equations Example: Temperature conversion For analog to digital conversion – assuming left justified: ADC 0 / 16 Vref V= 12 × 2 Gain The temperature sensor: V − 0.776 TempC = 0.00286 Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 42. Temperature Conversion ADC 0 / 16 Vref ( 12 × ) − 0.776 TempC = 2 Gain 0.00286 Let Vref = 2.4V, Gain = 2 ADC 0 − 42380 TempC = 156 Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 43. C for the Equation ADC 0 − 42380 TempC = 156 … unsigned int result, temperature; … result = ADC0; //read temperature sensor temperature = result - 42380; temperature = temperature / 156; * Must be careful about range of values expected and variable types Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 44. Make it REAL! Temperature Conversion Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 45. Initialization • When a C program is compiled, some code is created that runs BEFORE the main program. • This code clears RAM to zero and initializes your variables. Here is a segment of this code: LJMP 0003h 0003: MOV R0, #7FH CLR A back: MOV @R0, A DJNZ R0, back ... Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 46. Arrays in C • Useful for storing data type arr_name[dimension] temp_array[0] temp_array[1] temp_array[2] char temp_array[256] temp_array[3] ... Array elements are stored in temp_array[253] adjacent locations in memory. temp_array[254] temp_array[255] Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 47. Pointers in C • Pointers are variables that hold memory addresses. • Specified using * prefix. int *pntr; // defines a pointer, pntr pntr = &var; // assigns address of var to pntr Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 48. Pointers and Arrays Note: the name of an array is a pointer to the first element: *temp_array is the same as temp_array[0] So the following are the same: n = *temp_array; n = temp_array[0]; temp_array[0] and these are also the same: temp_array[1] temp_array[2] n = *(temp_array+5); temp_array[3] n = temp_array[5]; … Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 49. Arrays • In watch window, address (pointer) of first element array is shown. • Array is not initialized as you specify when you download or reset, but it will be when Main starts. unsigned char P0_out[4] = {0x01,0x02,0x04,0x08}; Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 50. Array Example Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 51. Compiler Optimization Levels • Optimization level can be set by compiler control directive: • Examples (default is #pragma (8, speed) – #pragma ot (7) – #pragma ot (9, size) – #pragma ot (size) – reduce memory used at the expense of speed. – #pragma ot (speed) – reduce execution time at the expense of memory. Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 52. Compiler Optimization Levels Level Optimizations added for that level 0 Constant Folding: The compiler performs calculations that reduce expressions to numeric constants, where possible.This includes calculations of run-time addresses. Simple Access Optimizing: The compiler optimizes access of internal data and bit addresses in the 8051 system. Jump Optimizing: The compiler always extends jumps to the final target. Jumps to jumps are deleted. 1 Dead Code Elimination: Unused code fragments and artifacts are eliminated. Jump Negation: Conditional jumps are closely examined to see if they can be streamlined or eliminated by the inversion of the test logic. 2 .... 3 4 5 6 7 8 9 Common Block Subroutines: Detects recurring instruction sequences and converts them into subroutines. Cx51 evenrearranges code to obtain larger recurring sequences. Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 53. Example: 7-seg Decoder // Program to convert 0-F into 7-segment equivalents. #pragma debug code) #pragma ot (9) #include <c8051f020.h> #define NUM_SAMPLES 16 unsigned char SEGS7[16] = {0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E}; xdata unsigned char samples[NUM_SAMPLES]; void main (void) { char i; // loop counter WDTCN = 0xde; WDTCN = 0xad; for (i=0; i < NUM_SAMPLES; i++) {samples[i] = SEGS7[i];} while (1); } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 54. Effect of Optimization Level on Code Size Level Code Size 0 53 1 53 2 53 3 51 4 46 5 46 6 39 7 39 8 38 9 38 Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 55. Level 0 Optimization ; FUNCTION main (BEGIN) 0000 75FFDE MOV WDTCN,#0DEH 0003 75FFAD MOV WDTCN,#0ADH ;---- Variable 'i' assigned to Register 'R7' ---- 0006 750000 R MOV i,#00H 0009 C3 CLR C 000A E500 R MOV A,i 000C 6480 XRL A,#080H 000E 9490 SUBB A,#090H 0010 5020 JNC ?C0004 0012 AF00 R MOV R7,i 0014 7400 R MOV A,#LOW SEGS7 0016 2F ADD A,R7 0017 F8 MOV R0,A 0018 E6 MOV A,@R0 … Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 56. Level 9 Optimization ; FUNCTION main (BEGIN) 0000 75FFDE MOV WDTCN,#0DEH 0003 75FFAD MOV WDTCN,#0ADH ;---- Variable 'i' assigned to Register 'R7' ---- 0006 E4 CLR A 0007 FF MOV R7,A 0008 7400 R MOV A,#LOW SEGS7 000A 2F ADD A,R7 000B F8 MOV R0,A 000C E6 MOV A,@R0 … Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 57. Memory Models • Small - places all function variables and local data segments in the internal data memory (RAM) of the 8051 system. This allows very efficient access to data objects (direct and register modes). The address space of the SMALL memory model, however, is limited. • Large - all variables and local data segments of functions and procedures reside (as defined) in the external data memory of the 8051 system. Up to 64 KBytes of external data memory may be accessed. This,however, requires the long and therefore inefficient form of data access through the data pointer (DPTR). • Selected by compiler directives • Examples: – #pragma small – #pragma large Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 58. Example: LARGE 0006 E4 CLR A 0007 FF MOV R7,A 0008 EF MOV A,R7 0009 FD MOV R5,A 000A 33 RLC A ;multiply by 2 000B 95E0 SUBB A,ACC 000D FC MOV R4,A 000E 7400 R MOV A,#LOW SEGS7 0010 2D ADD A,R5 0011 F582 MOV DPL,A 0013 7400 R MOV A,#HIGH SEGS7 0015 3C ADDC A,R4 0016 F583 MOV DPH,A 0018 E0 MOVX A,@DPTR …. Registers R4, R5 keep track of 16-bit data address (external RAM) Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 59. Example: SMALL 0006 E4 CLR A 0007 FF MOV R7,A 0008 7400 R MOV A,#LOW SEGS7 000A 2F ADD A,R7 000B F8 MOV R0,A 000C E6 MOV A,@R0 …. Data address = #LOW SEGS7 + R7 (8-bit address, RAM) Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 60. Initialization • When a C program is compiled, some code is created that runs BEFORE the main program. • This code clears RAM to zero and initializes your variables. Here is a segment of this code: LJMP 0003h 0003: MOV R0, #7FH CLR A back: MOV @R0, A DJNZ R0, back ... Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 61. I/O Circuitry - Exercise Bits accessed via SFRs Port Bit (ex: P1.0) Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 62. Can be disabled. By default, inputs are “pulled up” by weak pullup transistor Therefore, if not connected to anything, inputs are read as “1”. Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 63. Port I/O - Output Output circuit: • Only enabled if /PORT-OUTENABLE = 0 • PUSH-PULL = 1 enables P transistor • Non-PUSH-PULL allows wired-or outputs Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 64. Port I/O - Input Port 1 can be configured for either digital or analog inputs using a pass transistor and buffer Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 65. Port I/O Example XBR2 = 0x40; // Enable XBAR2 P0MDOUT = 0x0F; // Outputs on P0 (0-3) … Port 0 P0 = 0x07; // Set pins 2,1,0 and clear pin 3 Latch I/O Cells temp = P0; // Read Port0 7 6 input pins 5 4 3 2 output pins 1 0 Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 66. Keypad Interface Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 67. C for Large Projects • Use functions to make programs modular • Break project into separate files if the programs get too large • Use header (#include) files to hold definitions used by several programs • Keep main program short and easy to follow • Consider multi-tasking or multi-threaded implementations Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 68. Functions • The basis for modular structured programming in C. return-type function-name(argument declarations) { declarations and statements } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 69. Example – no return value or arguments void SYSCLK_Init (void) { // Delay counter int i; // Start external oscillator with 22.1184MHz crystal OSCXCN = 0x67; // Wait for XTLVLD blanking interval (>1ms) for (i = 0; i < 256; i++) ; // Wait for crystal osc. to settle while (!(OSCXCN & 0x80)) ; // Select external oscillator as SYSCLK OSCICN = 0x88; } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 70. Example – with arguments void Timer3_Init (int counts) { // Stop timer, clear TF3, use SYSCLK as timebase TMR3CN = 0x02; // Init reload value TMR3RL = -counts; // Set to reload immediately TMR3 = 0xffff; // Disable interrupts EIE2 &= ~0x01; // Start timer TMR3CN |= 0x04; } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 71. Example – with return value char ascii_conv (char num) { return num + 30; } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 72. Header Files • Use to define global constants and variables // 16-bit SFR Definitions for 'F02x sfr16 TMR3RL = 0x92; // Timer3 reload value sfr16 TMR3 = 0x94; // Timer3 counter sfr16 ADC0 = 0xbe; // ADC0 data sfr16 DAC0 = 0xd2; // DAC data sfr16 DAC1 = 0xd5; // Global CONSTANTS #define SYSCLK 22118400 // SYSCLK frequency in Hz sbit LED = P1^6; // LED='1' means ON sbit SW1 = P3^7; // SW1='0' means switch pressed #define MAX_DAC ((1<<12)-1) // Maximum value of the DAC register 12 bits #define MAX_INTEGRAL (1L<<24) // Maximum value of the integral // Function PROTOTYPES void SYSCLK_Init (void); void PORT_Init (void); void ADC0_Init (void); void DAC_Init (void); void Timer3_Init (int counts); void ADC0_ISR (void); Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 73. Multitasking and Multithreading • Multitasking: Perception of multiple tasks being executed simultaneously. – Usually a feature of an operating system and tasks are separate applications. – Embedded systems are usually dedicated to one application. • Multithreading: Perception of multiple tasks within a single application being executed. – Example: Cygnal IDE color codes while echoing characters you type. Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 74. Multitasking and Multithreading A “thread” void main (void) { void SYSCLK_Init (void){ long temperature; int i; WDTCN = 0xde; OSCXCN = 0x67; WDTCN = 0xad; for (i=0; i < 256; i++) ; SYSCLK_Init(): while (!(OSCXCN & 0x80)) ; PORT_Init (); OSCICN = 0x88; } Timer3_Init (SYSCLK/SAMPLE_RATE); AD0EN = 1; void PORT_Init (void) { EA = 1; XBR0 = 0x04; while (1) { XBR1 = 0x00; temperature = result; XBR2 = 0x40; if (temperature < 0xB230) LED = 0; P0MDOUT |= 0x01; else LED = 1; P1MDOUT |= 0x40;} } void Timer3_Init (int counts) { } TMR3CN = 0x02; TMR3RL = -counts; TMR3 = 0xffff; EIE2 &= ~0x01; TMR3CN |= 0x04; } Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 75. Multi-tasking/threading Implementations • Cooperative multi-tasking – each application runs for a short time and then yields control to the next application. • Timer-based multi-tasking – on each timer interrupt, tasks are switched. • When switching between tasks, state of processor (internal registers, flags, etc) must be saved and previous state from last task restored. This is the “overhead” of multitasking. Also called “context switching”. Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 76. Multithreading with Interrupts Interrupt Foreground thread Service Main program Routine Background thread reti Subroutines Interrupt ret Service Routine Background thread reti Prof. Cherrice Traver EE/CS-152: Microprocessors
  • 77. Real-Time Operating Systems (RTOS) • Usually a timer-based task switching system that can guarantee a certain response time. • Low level functions implement task switching. • High level functions create and terminate threads or tasks. • Each task might have its own software stack for storing processor state. Prof. Cherrice Traver EE/CS-152: Microprocessors