Embedded System Programming with C


This is a beginner embedded system programming tutorial where it is shown how to write a C program that turns on a sound alarm when a switch is closed. The 80C51 microcontroller is used to do this. The switch is connected to the pin 0 of port 1 and the sound device is connected to the pin 0 of port 0. The C program continuously monitors the state of the switch and if the switch is switched On, then it sounds alarm that beeps 5 times with one second interval.

Following is the schematic diagram.


The C program is below:

#include <Reg51.H>
#define ON 0
#define OFF 1

sbit BUZZ = P0^0;
sbit BUTTON = P1^0;

void OneSec()  // 1 sec delay function
   {
      unsigned int x;
      for(x=0;x<33000;x++);
      }
     
      main()   //main function
      {
     int i;
   
     BUZZ = OFF;
   
     while(1)
     {
        if(BUTTON==OFF)
        {}
        else
        {
        for(i=1;i<=5;i++)
           {
           BUZZ = ON;
           OneSec();
           BUZZ = OFF;
           OneSec();
           }
        }
      }
     }
   
We defined ON and OFF as 0 and 1 using the preprocessor directive statements #define so that we can write ON and OFF keywords in the program code and it makes it easy to understand the code.

Then we defined two variables BUZZ and BUTTON as sbit data types and assigned them to the port 0, pin 0 and port 1, pin 0.

The OneSec() is a function which when executed takes 1 second. This function will be called in the main function to insert 1 second time interval between sound on and off.

The main function starts with variable initialization. The int i declares an integer i which will be required in outputting 5 signals to the sound device. Then BUZZ = OFF is used to make the port 0, pin 0 an output.

The while(1) statement is used to continuously execute the statements following it(read the state of switch and buzz sound). The if and else statements are used to sound the alarm if the switch is closed or not to sound if it is open.

In the above C program, we could have replaced while(1) with for(;;). Also we could have used while(BUTTON==OFF) instead of if(BUTTON==OFF) in which case the else(and the if) would not be required.

See another beginner embedded C programming tutorial- How to write C program to read/write ports of a microcontroller

Related Posts by Categories

0 comments:

Post a Comment