Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering

Sample Programs in Keil for 8051

By Ashutosh Bhatt

Keil is a German based Software development company. It provides several development tools like

•         IDE (Integrated Development environment)

•         Project Manager

•         Simulator

•         Debugger

•         C Cross Compiler , Cross Assembler, Locator/Linker

Keil Software provides you with software development tools for the 8051 family of microcontrollers. With these tools, you can generate embedded applications for the multitude of 8051 derivatives. Keil provides following tools for 8051 development

1.     C51 Optimizing C Cross Compiler,

2.     A51 Macro Assembler,

3.     8051 Utilities (linker, object file converter, library manager),

4.     Source-Level Debugger/Simulator,

5.     µVision for Windows Integrated Development Environment.

 

Let’s see some simple Keil Based Programs

Generate a square wave


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  
}

 

Make 8 to 1 multiplexer with enable signal


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 

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 
}  

Parallel Input to Serial Output


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()
  {
    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++);
  } 

Simultaneous Transmission & Reception of Data


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 

}

Interrupt Detection and Display on LED


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
}

 

Blink LED for 5 seconds


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
          {
           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
   }

 

SONAR


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 
         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);

}

 

Counting Number of 1s in input


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
              } 
           while(1); // loop continue 
        }

 

Count number of Keypress


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: 
                      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
}

 

Detecting & Showing Number of Keypressess


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;
                        break;
                  case 0xEF: 
                       P0=0x92;
                       break;
                   case 0xDF: 
                       P0=0x82;
                        break;
                  case 0xBF: 
                        P0=0xF8;
                        break;
                   case 0x7F: 
                        P0=0x80; 
                        break;
                    }
               goto loop;
        }

 


Filed Under: Tutorials
Tagged With: 8051, kiel, microcontroller, program
 

Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


Featured Tutorials

  • PS2 Keyboard To Store Text In SD Card Using Arduino Circuit Setup On Breadboard
    How To Use PS2 Keyboard To Store Text In SD Card Using Arduino- (Part 42/49)
  • Wireless Path Tracking System Using Mouse, XBee And Arduino Circuit Setup On Breadboard
    How To Make A Wireless Path Tracking System Using Mouse, XBee And Arduino- (Part 43/49)
  • How to Make a Wireless Keyboard Using Xbee with Arduino- (Part 44/49)
  • Making Phone Call From GSM Module Using Arduino Circuit Setup On Breadboard
    How to Make Phonecall From GSM Module Using Arduino- (Part 45/49)
  • How to Make a Call using Keyboard, GSM Module and Arduino
    How To Make A Call Using Keyboard, GSM Module And Arduino- (Part 46/49)
  • Receiving SMS Using GSM Module With Arduino Prototype
    How to Receive SMS Using GSM Module with Arduino- (Part 47/49)

Stay Up To Date

Newsletter Signup

Sign up and receive our weekly newsletter for latest Tech articles, Electronics Projects, Tutorial series and other insightful tech content.

EE Training Center Classrooms

EE Classrooms

Recent Articles

  • Renesas delivers intelligent sensor solutions for IoT applications
  • Microchip Technology releases AVR-IoT Cellular Mini Development Board
  • Qualcomm acquires Cellwize to accelerate 5G adoption and spur infrastructure innovation
  • MediaTek’s chipset offers high-performance option for 5G smartphones
  • Nexperia’s new level translators support legacy and future mobile SIM cards

Most Popular

5G 555 timer circuit 8051 ai Arduino atmega16 automotive avr bluetooth dc motor display Electronic Part Electronic Parts Fujitsu ic infineontechnologies integratedcircuit Intel IoT ir lcd led maximintegratedproducts microchip microchiptechnology Microchip Technology microcontroller microcontrollers mosfet motor powermanagement Raspberry Pi remote renesaselectronics renesaselectronicscorporation Research samsung semiconductor sensor software STMicroelectronics switch Technology vishayintertechnology wireless

RSS EDABOARD.com Discussions

  • SRF04 module measure distance
  • Adaptive filters fundamental
  • Using LTspice to check Current sense transformer reset?
  • Thermal pad construction on pcb
  • lna+mixer noise figure problem

RSS Electro-Tech-Online.com Discussions

  • Are Cross-wind compensation and Road crown compensation functions inputs to LKA function?
  • Interfacing ZMOD4410 with Arduino UNO
  • Help diagnosing a coffee maker PCB
  • Capacitor to eliminate speaker hum
  • Identify a circuit.
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • About Us
  • Contact Us
  • Advertise

Copyright © 2022 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy | Advertising | About Us

Search Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering