keil c programming tutorial

27
keil C Programming Tutorial: Introduction Introduction The use of C language to program microcontrollers is becoming too common. And most of the time its not easy to buld an application in assembly which instead you can make easily in C. So Its important that you know C language for microcontroller which is commonly known as Embedded C. As we are going to use Keil C51 Compiler, hence we also call it Keil C. ►Keywords: Keil C51 compiler adds few more keywords to the scope C Language: _at_ far sbit alien idata sfr bdata interrupt sfr16 bit large small code pdata _task_ compact _priority_ using data reentrant xdata data/idata: Description: The variable will be stored in internal data memory of controller. example: CODE: unsigned char data x; //or unsigned char idata y; bdata: Description: The variable will be stored in bit addressable memory of controller. example: CODE: unsigned char bdata x; //each bit of the variable x can be accessed as follows x ^ 1 = 1; //1st bit of variable x is set x ^ 0 = 0; //0th bit of variable x is cleared xdata: Description: The variable will be stored in external RAM memory of controller.

Upload: bhautik-daxini

Post on 20-Jan-2016

45 views

Category:

Documents


0 download

DESCRIPTION

Programming of micro controller using Keil C

TRANSCRIPT

Page 1: Keil C Programming Tutorial

keil C Programming Tutorial: Introduction

Introduction

The use of C language to program microcontrollers is becoming too common. And most of the time its not easy to buld an application in assembly which instead you can make easily in C. So Its important that you know C language for microcontroller which is commonly known as Embedded C. As we are going to use Keil C51 Compiler, hence we also call it Keil C.

►Keywords:

Keil C51 compiler adds few more keywords to the scope C Language:

_at_ far sbit

alien idata sfr

bdata interrupt sfr16

bit large small

code pdata _task_

compact _priority_ using

data reentrant xdata

data/idata:Description: The variable will be stored in internal data memory of controller.

example:CODE:unsigned char data x;//orunsigned char idata y; 

bdata:Description: The variable will be stored in bit addressable memory of controller.

example:CODE:unsigned char bdata x;//each bit of the variable x can be accessed as followsx ^ 1 = 1; //1st bit of variable x is setx ^ 0 = 0; //0th bit of variable x is cleared 

xdata:Description: The variable will be stored in external RAM memory of controller.

example:CODE:unsigned char xdata x; 

code:Description: This keyword is used to store a constant variable in code memory. Lets say you have a big

Page 2: Keil C Programming Tutorial

string which is not going to change anywhere in program. Wasting ram for such string will be foolish thing. So instead we will make use of the keyword "code" as shown in example below.

example:CODE:unsigned char code str="this is a constant string"; 

pdata:Description: This keyword will store the variable in paged data memory. This keyword is used occasionally.

example:CODE:unsigned char pdata x; 

_at_:Description: This keyword is used to store a variable on a defined location in ram.

example:CODE:unsigned char idata x _at_ 0x30;// variable x will be stored at location 0x30// in internal data memory 

sbit:Description: This keyword is used to define a special bit from SFR (special function register) memory.

example:CODE:sbit Port0_0 = 0x80;// Special bit with name Port0_0 is defined at address 0x80 

sfr:Description: sfr is used to define an 8-bit special function register from sfr memory.

example:CODE:sfr Port1 = 0x90;// Special function register with name Port1 defined at addrress 0x90 

sfr16:Description: This keyword is used to define a two sequential 8-bit registers in SFR memory.

example:CODE:sfr16 DPTR = 0x82;// 16-bit special function register starting at 0x82// DPL at 0x82, DPH at 0x83 

using:Description: This keyword is used to define register bank for a function. User can specify register bank 0 to 3.

Page 3: Keil C Programming Tutorial

example:CODE:void function () using 2{// code}// Funtion named "function" uses register bank 2 while executing its code 

interrupt:Description: This keyword will tells the compiler that function described is an interrupt service routine. C51 compiler supports interrupt functions for 32 interrupts (0-31). Use the interrupt vector address in the following table to determine the interrupt number.

example:CODE:void External_Int0() interrupt 0{//code} 

►Memory Models:

There are three kind of memory models available for the user:

1. Small: All variables in internal data memory.2. Compact: Variables in one page, maximum 256 variables (limited due to addressing scheme,

memory accessed indirectly using r0 and r1 registers)

Page 4: Keil C Programming Tutorial

3. large: All variables in external ram. variables are accessed using DPTR.

Depending on our hardware configuration we can specify the momory models as shown below:

CODE://For Small Memory model#pragma small//For Compact memory model#pragma compact//For large memory model#pragma large 

keil C Programming Tutorial: Pointers

►Pointers in Keil C

Pointers in keil C is are similar to that of standard C and can perform all the operations that are available in standard C. In addition, keil C extends the operatability of pointers to match with the 8051 Controller architecture. Keil C provides two different types of pointers:

1. Generic Pointers2. Memory-Specific Pointers

►Generic Pointers:Generic Pointers are declared same as standard C Pointers as shown below:

CODE:char *ptr;      //Character Pointerint *num;       //Integer Pointer 

Generic pointers are always stored using three bytes. The first byte is the memory type, the second byte is the high-order byte of the offset, and the third byte is the low-order byte of the offset. Generic pointers maybe used to access any variable regardless of its location.

►Memory-Specific Pointers:Memory specific pointers are defined along with memory type to which the pointer refers to, for example:

CODE:char data *c;//Pointer to character stored in Data memory

char xdata *c1;//Pointer to character stored in External Data Memory.

char code *c2;//Pointer to character stored in Code memory 

Page 5: Keil C Programming Tutorial

As Memory-Specific pointers are defined with a memory type at compile time, so memory type byte as required for generic pointers is not needed. Memory-Specific pointers can be stored using 1 byte (for idata, data, bdata and pdata pointers) or 2 bytes (for code and xdata pointers).

The Code generated by keil C compiler for memory-specific pointer executes mroe quickly than the equivalent code generated for a generic pointer. This is because the memory area accessed by the pointer is known at the compile time rather at run-time. The compiler can use this information to optimize memory access. So If execution speed is your priority then it is recommended to use memory-specific pointers.

Generic pointers and Memory-Specific pointers can be declared with memory area in which they are to be stored. For example:

CODE://Generic Pointerchar * idata ptr;//character pointer stored in data memoryint * xdata ptr1;//Integer pointer stored in external data memory

//Memory Specific pointerchar idata * xdata ptr2;//Pointer to character stored in Internal Data memory//and pointer is going to be stored in External data memoryint xdata * data ptr3;//Pointer to character stored in External Data memory//and pointer is going to be stored in data memory

keil C Programming Tutorial: Functions

►Functions in Keil C

Keil C compiler provides number of extensions for standarad C function declerations. These extensions allows you to:

Specify a function as an interrupt procedure Choose the register bank used Select memory model

►Function Declaration:

[Return_type] Fucntion_name ( [Arguments] ) [Memory_model] [reentrant] [interrupt n] [using n]

Return_type: The type of value returned from the function. If return type of a function is not specified, int is assumed by default.

Function_name: Name of function.

Arguments: Arguments passed to function.

Options:These are options that you can specify along with function declaration.

Page 6: Keil C Programming Tutorial

Memory_model: explicit memory model (Large, Compact, Small) for the function. Example:

CODE:int add_number (int a, int b) Large 

reentrant: To indicate if the function is reentrant or recursive. This option is explained later in the tutorial.

interrupt: Indicates that function is an interrupt service routine. This option is explained later in the tutorial.

using: Specify register bank to be used during function execution. We have three register banks in 8051 architecture. These register banks are specified using number 0 for Bank 0 to 3 for Bank 3 as shown in example

CODE:void function_name () using 2{ //function uses Bank 2        //function code} 

►Interrupt Service Routines:A function can be specified as an interrupt service routine using the keyword interrupt and interrupt number. The interrupt number indicates the interrupt for which the function is declared as service routine.

Following table describes the default interrupts:

As 8051 vendors create new parts, more interrupts are added. Keil C51 compiler supports interrupt functions for 32 interrupts (0-31). Use the interrupt vector address in the following table to determine the interrupt number.

Page 7: Keil C Programming Tutorial

The interrupt function can be declared as follows:

CODE:void isr_name (void) interrupt 2 {// Interrupt routine code} 

Please make sure that interrupt service routines should not have any arguments or return type except void.

►Reentrant Functions:In ANSI C we have recursive function, to meet the same requirement in embedded C, we have reentrant function. These functions can be called recursively and can be called simultaneously by two or more processes.

Now you might be thinking, why special definition for recursive functions?Well you must know how these functions work when they are called recursively. when a function is running there is some runtime data associated with it, like local variables associated with it etc. when the same function called recursively or two process calls same function, CPU has to maintain the state of function along with its local variables.

Reentrant functions can be defined as follows:CODE:void function_name (int argument) reentrant {        //function code} 

Each reentrant function has reentrant stack associated with it, which is defined by startup.A51 file. Reentrant stack area is simulated internal or external memory depending upon the memory model used:

Page 8: Keil C Programming Tutorial

Small model reentrant functions simulate reentrant stack in idata memory.

Compant model reentrant functions simulate reentrant stack in pdata memory.

Large model reentrant functions simulate reentrant stack in xdata memory.

►Real-time Function Tasks:

Keil or C51 provides support for real-time operating system (RTOS) RTX51 Full and RTX51 Tiny. Real-time function task are declared using _task_ and _priority_ keywords. The _task_ defines a function as real-time task. The _priority_ keyword specify the priority of task.

Fucntions are declared as follows:

CODE:void func (void) _task_ Number _priority_ Priority {        //code} 

where:

Number: is task ID from 0 to 255 for RTX51 Full and 0 to 15 for RTX51 Tiny.

Priority: is priority of task.

Real-time task functions must be declared with void return type and void argument list (say no arguments passed to task function).

keil C Programming Tutorial: Writing simple C program in Keil

►Basic of a C program

As we already discussed, Keil C is not much different from a normal C program. If you know assembly, writing a C program is not a problem, only thing you have to keep in mind is forget your controller has general purpose registers, accumulators or whatever. But do not forget about Ports and other on chip peripherals and related registers to them.

In basic C, all programs have atleast one function which is entry point for your application that function is named as "main" function. Similarly in keil, we will have a main function, in which all your application specific work will be defined. Lets move further deep into the working of applications and programs.

When you run your C programs in your PC or computer, you run them as a child program or process to your Operating System so when you exit your programs (exits main function of program) you come back to operating system. Whereas in case of embedded C, you do not have any operating system running in there. So you have to make sure that your program or main file should never exit. This can be done with the help of simple while(1) or for(;;) loop as they are going to run infinitely. Following layout provides a skeleton of Basic C program.

CODE:void main(){//Your one time initialization code will come here

Page 9: Keil C Programming Tutorial

        while(1){                //while 1 loop                //This loop will have all your application code                //which will run infinitely        }} 

When we are working on controller specific code, then we need to add header file for that controller. I am considering you have already gone through "Keil Microvision" tutorial. After project is created, add the C file to project. Now first thing you have to do is adding the header file. All you have to do is right click in editor window, it will show you correct header file for your project.

Figure below shows the windows context for adding header file to your c file.

►Writing Hardware specific code

In harware specific code, we use hardware peripherals like ports, timers and uart etc. Do not forget to add header file for controller you are using, otherwise you will not be able to access registers related to peripherals.

Lets write a simple code to Blink LED on Port1, Pin1.

CODE:#include <REGx51.h> //header file for 89C51void main(){        //main function starts        unsigned int i;        //Initializing Port1 pin1

Page 10: Keil C Programming Tutorial

        P1_1 = 0; //Make Pin1 o/p        while(1){                //Infinite loop main application                //comes here                for(i=0;i<1000;i++)                        ; //delay loop                P1_1 = ~P1_1;                //complement Port1.1                //this will blink LED connected on Port1.1        }} 

You can now try out more programs. "Practice makes a man perfect".In next section of this tutorial, we will learn how to mix C and assembly codes.

keil C Programming Tutorial: C and Assembly together

►Interfacing C program to Assembler

You can easily interface your programs to routines written in 8051 Assembler. All you need to do is follow few programming rules, you can call assembly routines from C and vice-versa. Public variables declared in assembly modules are available to your C program.

There maybe several reasons to call an assembly routine like faster execution of program, accessing SFRs directly using assembly etc. In this part of tutorial we will discuss how to write assembly progarms that can be directly interfaced with C programs.

For any assembly routine to be called from C program, you must know how to pass parameters or arguements to fucntion and get return values from a function.

►Segment naming

C51 compiler generates objects for every program like program code, program data and constant data. These objects are stored in segments which are units of code or data memory. Segment naming is standard for C51 compiler, so every assembly program need to follow this convention.

Segment names include module_name which is the name of the source file in which the object is declared. Each segment has a prefix that corresponds to memory type used for the segment. Prefix is enclosed in question marks (?). The following is the list of the standard segment name prefixes:

Page 11: Keil C Programming Tutorial

►Data Objects:

Data objects are the variables and constants you declare in your C programs. The C51 compiler generates a saperate segment for each memory type for which variable is declared. The following table lists the segment names generated for different variable data objects.

►Program Objects:

Program onjects includes code generated for C programs functions by C51 compiler. Each function in a source module is assigned a separate code segment using the ?PR?function_name?module_name naming convention. For example, for a function name send_char in file name uart.c will have a segment name of ?PR?SEND_CHAR?UART.

C51 compiler creates saperate segments for local variables that are declared within the body of a function. Segment naming conventions for different memory models are given in following tables:

Page 12: Keil C Programming Tutorial

Function names are modified slightly depending on type of function (functions without arguments, functions with arguments and reentrant functions). Following tables explains the segment names:

In next section we will learn regarding defining functions which can be called from any C function and how a C function can be called from assembly.

Page 13: Keil C Programming Tutorial

keil C Programming Tutorial: Interfacing C programs to Assembler

►Function Parameters

C51 make use of registers and memory locations for passing parameters. By default C function pass up to three parameters in registers and further parameters are passed in fixed memory locations. You can disable parameter passing in register using NOREGPARMS keyword. Parameters are passed in fixed memory location if parameter passing in register is disabled or if there are too many parameters to fit in registers.

►Parameter passing in registers

C functions may pass parameter in registers and fixed memory locations. Following table gives an idea how registers are user for parameter passing.

Following example explains a little more clearly the parameter passing technique:

►Parameter passing in Fixed Memory Locations

Page 14: Keil C Programming Tutorial

Parameters passed to assembly routines in fixed memory lcoation use segments named

?function_name?BYTE : All except bit parameters are defined in this segment.

?function_name?BIT : Bit parameters are defined in this segment.

All parameters are assigned in this space even if they are passed using registers. Parameters are stored in the order in which they are declared in each respective segment.

The fixed memory locations used for parameters passing may be in internal data memory or external data memory depending upon the memory model used. The SMALL memory model is the most efficient and uses internal data memory for parameter segment. The COMPACT and LARGE models use external data memory for the parameter passing segments.

►Fucntion Return Values

Function return values are always passed using CPU registers. The following table lists the possible return types and the registers used for each.

►Example

Following example shows how these segment and function decleration is done in assembler.

CODE:;Assembly program example which is compatible;and called from any C program;lets say asm_test.asm is file namename asm_test

;We are going to write a function;add which can be used in c programs as; unsigned long add(unsigned long, unsigned long);; as we are passing arguments to function;so function name is prefixed with '_' (underscore)

;code segment for function "add"?PR?_add?asm_test segment code;data segment for function "add"?DT?_add?asm_test segment data

;let other function use this data space for passing variablespublic ?_add?BYTE

Page 15: Keil C Programming Tutorial

;make function public or accessible to everyonepublic _add

;define the data segment for function addrseg ?DT?_add?asm_test?_add?BYTE:parm1:  DS 4    ;First Parameterparm2:  ds 4    ;Second Parameter

;either you can use parm1 for reading passed value as shown below;or directly use registers used to pass the value.rseg ?PR?_add?asm_test_add:;reading first argument        mov parm1+3,r7        mov parm1+2,r6        mov parm1+1,r5        mov parm1,r4;param2 is stored in fixed location given by param2

;now adding two variables        mov a,parm2+3        add a,parm1+3;after addition of LSB, move it to r7(LSB return register for Long)        mov r7,a        mov a,parm2+2        addc a,parm1+2;store second LSB        mov r6,a        mov a,parm2+1        addc a,parm1+1;store second MSB        mov r5,a        mov a,parm2        addc a,parm1;store MSB of result and return

;keil will automatically store it to;varable reading the resturn value        mov r4,a        ret

        end 

Now calling this above function from a C program is very simple. We make function call as normal function as shown below:

CODE:extern unsigned long add(unsigned long, unsigned long);

void main(){        unsigned long a;        a = add(10,30);        //a will have 40 after execution        while(1);}

Page 16: Keil C Programming Tutorial

SAMPLE PROGRAMS

Example-1: generate a square wave of 10 Hz at pin P1.0 of 8051 using timer

#include <reg51.h>               // include 8051 register file

sbit pin = P1^0;                    // decleare a variable type sbit for P1.0 

main()

{

      P1 = 0x00;                     // clear port

      TMOD = 0x09;                // initialize timer 0 as 16 bit timer 

loop:TL0 = 0xAF;                  // load valur 15535 = 3CAFh so after 

      TH0 = 0x3C;                   // 50000 counts timer 0 will be overflow

       pin = 1;                        // send high logic to P1.0

       TR0 = 1;                       // start timer

       while(TF0 == 0)  {}       // wait for first overflow for 50 ms

       TL0 = 0xAF;                 // again reload count

       TH0 = 0x3C;

       pin = 0;                       // now send 0 to P1.0

      while(TF0 == 0)  {}       // wait for 50 ms again  

  goto loop;                         // continue with the loop  

}

Example-2: write a program to make 8 to 1 multiplexer with enable signal

#include<reg51.h>

sbit D0 = P0^0;                     // set P0.0-P0.7 (D0-D7) as input pins of mux

sbit D1 = P0^1;

sbit D2 = P0^2;

sbit D3 = P0^3;

sbit D4 = P0^4;

sbit D5 = P0^5;

sbit D6 = P0^6;

sbit D7 = P0^7;

sbit S0 = P1^0;                 // set P1.0-P1.2(S0-S2) as select pins of mux

sbit S1 = P1^1;

sbit S2 = P1^2;

sbit EN = P1^7;                // set P1.7 as enable pin

sbit pin = P3^5;               // set P3.5 as output 

Page 17: Keil C Programming Tutorial

main()

{

         P3=0x00;P0=0xFF;      // clear op and set all ips

        TMOD = 0x01;              // set timer 0 for 16 bit timer

 next:TL0 = 0xAF;                 // load count 

        TH0 = 0x3C; 

        while(EN==1){}           // wait till enable pin becomes 0

   if((S0==0)&&(S1==0)&&(S2==0)) pin = D0;                  // if select inputs are 000 op is first ip

   else if((S0==1)&&(S1==0)&&(S2==0)) pin = D1;           // if select inputs are 001 op is second ip

   else if((S0==0)&&(S1==1)&&(S2==0)) pin = D2;           // same as above

   else if((S0==1)&&(S1==1)&&(S2==0)) pin = D3;

   else if((S0==0)&&(S1==0)&&(S2==1)) pin = D4;

   else if((S0==1)&&(S1==0)&&(S2==1)) pin = D5;

   else if((S0==0)&&(S1==1)&&(S2==1)) pin = D6;

   else if((S0==1)&&(S1==1)&&(S2==1)) pin = D7;   

   else pin = 0;                                                                 // by default op is cleared

   TR0 = 1;                                                                      // start timer 0 

   while(TF0==0){}                                                          // wait until overflow means 50ms

   TR0 = 0;                                                                      // stop timer 

   goto next;                                                                    // go for next input 

}  

Example-3:   take parallel input from port P1 convert it into serial and send it via P0.0

#include<reg51.h>

sbit sout = P0^0;                          // serial out on P0.0

sbit D0 = P1^0;                            // parallal input from P1 (D0-D7)

sbit D1 = P1^1;

sbit D2 = P1^2;

sbit D3 = P1^3;

sbit D4 = P1^4;

sbit D5 = P1^5;

sbit D6 = P1^6;

sbit D7 = P1^7;

int i;

void delay(void);                         //  1 ms delay

 

main()

  {

Page 18: Keil C Programming Tutorial

    for(i=0;i<8;i++)                   // rotate loop for 8 times

      {

        sout = D0;                       // first bit out

        D0 = D1;                         // shift all bits in sequence 

        D1 = D2;

        D2 = D3;

        D3 = D4;

        D4 = D5;

        D5 = D6;

        D6 = D7;

        delay();                           // generate 1 ms delay after each bit shifted

      }

   }

void delay()

  {

    int k

    for(k=0;k<1000;k++);

  } 

Example-4: write a program to simultaneously transmit and receive data.

#include <reg51.h>

main()

 {

       TMOD=0x20;          // set timer1 in 16 bit timer mode

       SCON=0x40;          // initialize serial communication

       TL1=0xFD;             // load timer 1 to generate baud rate of 96KBps

       TH1 = 0xFD;

       TR1 = 1;               // start timer 1  

loop:REN = 1;               // enable reception

      while(RI==0){}       // wait until data is received

      RI=0;                     // clear receive flag

      ACC = SBUF;          // get data in to acc

      REN = 0;                // now disable reception

      SBUF = ACC;          // start transmission

      while(TI==0){}       // wait until data transmitted

      TI=0;                    // clear transmission flag   

      goto loop;              // continue this cycle 

}

Page 19: Keil C Programming Tutorial

Example-5:   detect an external interrupt on P3.2 and P3.3. Indicate on LEDs connected on P0.0 & P0.1

#include<reg51.h>

sbit op1=P0^0;                             // LED1 as output on P0.0

sbit op2=P0^1;                             // LED2 as ouput on P0.1

void delay(void);                           // 10 ms delay

void intrupt0(void) interrupt 0        // ext interrupt 0 vector

{

  op1=0;                                     // indication on LED1

  delay();

  op1=1;

}

void intrupt1(void) interrupt 2        // ext interrupt 1 vector

{

  op2=0;                                     // indication on LED2

  delay();

  op2=1;

}

void delay()                                 // delay for 10 ms

{

  int x;

  for(x=0;x<10000;x++);

}

void main()

{

  P0=0xFF;                                 // send all 1's to P0 

  IE=0x85;                                  // enable both ext interrupts

  while(1);                                 // continuous loop

}

 

Example-6: blink a LED on P2.0 for 5 second using timer 1

#include<reg51.h>

int c=0;                                  // initialize counter to 0

sbit LED= P2^0;                      // LED connected to P2.0

void timer1(void) interrupt 3     // timer 1 overflow vactor

  {

     TF1=0;                             // clear overflow flag  

     c++;                                 // increment counter

     if(c==100)                        // if 100 counts of 50 ms(= 5 sec) are over

Page 20: Keil C Programming Tutorial

          {

           TR1=0;                      // stop timer 

           LED=0;                      // LED off 

          } 

     TH1=0x3C;                      // other reaload timer 1 with

     TL1=0xAF;                      // 15535 to count 50 ms  

  }

void main()

  {

         P2=0x00;                   // clear op

        TMOD=0x90;               // set timer 1

        TH1=0x3C;                 // load count 15535

        TL1=0xAF;

        IE=0x88;                    // enable timer 1 interrupt

        LED=1;                      // LED on

        TR1=1;                     // timer 1 start

        while(1);                   // continuous loop

   }

Example 7: send ultrasonic wave through P1.0 and receive its echo through P3.2. generate an interrupt.

Calculate the distance of object.

#include <reg51.h>

sbit tx = P1^0; // transmitter pin

int c=0,d=0; // counter and distance

void tmr0(void) interrupt 1 // timer 0 interrupt vector

   {

      TF0=0;                       // clear timer flag

      c++;                          // increment counter 

      TL0 = 0xAF;               // reload values

      TH0 = 0x3C;

   }

void int0(void) interrupt 0 // ext interrupt 0 vector

   {

       TR0 = 0;                  // stop timer 

       d = c*30;                // get distance = time*velocity

   } 

main()

    {

         IE=0x83;             // enable interrupts 

Page 21: Keil C Programming Tutorial

         IP=0x01;            // high priority for ext interrupt

         TMOD = 0x01;    // timer 0 as 16 bit timer

         P1 = 0x00;        // clear op port

         TL0 = 0xAF;       // load values for 50 ms

         TH0 = 0x3C;

          tx = 1;             // enable transmission

          TR0 = 1;          // start timer

          while(1);

}

Example 8:   take input from P0. Count no of 1 in input

#include <reg51.h>

sbit D0 = B^0; // define D0-D7 as bits of reg B

sbit D1 = B^1;

sbit D2 = B^2;

sbit D3 = B^3;

sbit D4 = B^4;

sbit D5 = B^5;

sbit D6 = B^6;

sbit D7 = B^7;

unsigned bdata reg; // define reg as bit addressable variable

sbit b = reg^0; // define b as bit 0 of reg

void main()

     {

         unsigned int i,c=0; // initialize counter

         B=P0; // take input from P0 to B

         b=0;

         for(i=0;i<8;i++) // rotate bits of reg B

              { // 8 times

                   b=D7;

                   D7=D6;

                   D6=D5;

                   D5=D4;

                   D4=D3;

                   D3=D2;

                   D2=D1;

                   D1=D0;

                   if(b==1)c++; // check every bit if 1

              } 

Page 22: Keil C Programming Tutorial

           while(1); // loop continue 

        }

 

Example 9: connect key with P3.2. Using interrupt count no of key press and display it on common anode

seven segment display connected to P0.

#include<reg51.h>

unsigned int c=0,x=0; //initialize key counter and key flag

void extint0(void) interrupt 0

   {

      x=1;                       // set key flag

      c++;                      // increment key count

      if(c==9)                 // if its 9

         {

           c=0;                // reset it to 0 and

           P0=0xC0;         // display 0

         } 

     } 

void main(void)

    {

           IE=0x81;         // enable ext int 0

           P0=0xC0;        // display 0

    loop:while(!x);      // check key flag

           switch(c)       // if it is set get the count

                  {

                    case 1: 

                        P0=0xF9; // display digit from 1 to 9

                        break;

                    case 2: 

                        P0=0xA4;

                        break;

                   case 3: 

                       P0=0xB0;

                       break;

                   case 4: 

                       P0=0x99;

                       break;

                 case 5: 

Page 23: Keil C Programming Tutorial

                      P0=0x92;

                      break;

                 case 6: 

                      P0=0x82;

                      break;

                 case 7: 

                      P0=0xF8;

                      break;

                 case 8: 

                      P0=0x80;

                      break;

                 case 9: 

                      P0=0x90;

                      break;

                } 

       x=0; // clear key flag

       goto loop; // loop continue

}

Example 10: connect 8 keys with P1. Detect key press and display number on CA 7 segment display

connected to P0.

#include<reg51.h>

void main(void)

    {

        loop:P1=0xFF;                 // send all 1's to P1             

        while(P1==0xFF);            // remain within loop till key is not pressed

         switch(P1)                    // when key pressed detect is

             {

                 case 0xFE: 

                       P0=0xF9; // and display digit from 1 to 8

                       break;

                  case 0xFD: 

                       P0=0xA4;

                       break;

                  case 0xFB: 

                       P0=0xB0;

                       break;

                  case 0xF7: 

                       P0=0x99;

Page 24: Keil C Programming Tutorial

                        break;

                  case 0xEF: 

                       P0=0x92;

                       break;

                   case 0xDF: 

                       P0=0x82;

                        break;

                  case 0xBF: 

                        P0=0xF8;

                        break;

                   case 0x7F: 

                        P0=0x80; 

                        break;

                    }

               goto loop;

        }