Embedded C 8051 Example Programs
Embedded C 8051 Example Programs
Embedded C 8051 Example Programs
TF0=0;
}
SERIAL PORT PROGRAMMING
1. Write a C program for 8051 to transfer the letter A serially at 4800 baud
continuously. Use 8-bit data and 1 stop bit.
#include <reg51.h>
void main(void){
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud rate
SCON=0x50;
TR1=1;
while (1) {
SBUF=A; //place value in buffer
while (TI==0);
TI=0;
}
}
2. Write a C program to send two different strings to the serial port.
Assuming that switch is connected to pin P2.0, monitor its status and
make a decision as follows:
SW=0: send first name
SW=1: send last name
#include <reg51.h>
#include <string.h>
sbit MYSW = P2^0;
void main(void)
{
unsigned char z;
unsigned char fname[]="PRAKASH";
unsigned char lname[]="JOTHI";
while(1)
{
TMOD=0x20;
TH1=0x50;
TR1=1;
if(MYSW == 0)
{
for(z=0;z < strlen(fname);z++)
{
SBUF=fname[z];
while(TI==0);
TI=0;
}
}
else
{
for(z=0;z<strlen(lname);z++)
{
SBUF=lname[z];
while(TI==0);
TI=0;
}
}
}
}
INTERRUPT PROGRAMMING
1. Write a C program that continuously gets a single bit of data from P1.7
and sends it to P1.0, while simultaneously creating a square wave of
200 us period on pin P2.5. Use timer 0 to create the square wave.
#include <reg51.h>
sbit SW = P1^7;
sbit IND = P1^0;
sbit WAVE = P2^5;
void timer0(void) interrupt 1
{
WAVE = ~WAVE;
}
void main()
{
SW=1;
TMOD = 0x02;
TH0 = 0xA4;
IE = 0x82;
TR0 =1;
while(1)
{
IND = SW;
}
}
2. Write a C program that continuously gets a single bit of data from P1.7
and sends it to P1.0 in the main while simultanueously (a) creating a
square wave of 200 us period on pin P2.5 and (b) sending letter A to
the serial port. Use Timer 0 to create the square wave. Assume that
XTAL = 11.0592 MHz. Use the 9600 baud rate.
#include <reg51.h>
sbit SW = P1^7;
sbit IND = P1^0;
sbit WAVE = P2^5;
rs = P2^7;
en = P2^5;
rw = P2^6;
b = P0^7;
writecmd(0x3C);
// initialize LCD
writecmd(0x0E);
writecmd(0x01);
// clear memory and home cursor
writestr("Wel-Come to LCD"); // write message in first line
writecmd(0xC4);
// move cursor to second line 4th pos
writestr("Program");
}
}
Pgm 2:
#include <reg51.h>
#include <string.h>
sfr ldata = 0x90;
sbit rs=P2^0;
sbit rw=P2^1;
sbit en=P2^2;
char j;
char z;
char k;
void lcdcmd(unsigned char a);
void lcddata();
void Delay();
void main()
{
unsigned char x[]="LCD Program";
lcdcmd(0x38);
lcdcmd(0x0E);
lcdcmd(0x01);
lcdcmd(0x06);
lcdcmd(0x80);
for(z=0;z<strlen(x)+1;z++)
{
lcddata();
ldata=x[z];
}
while(1)
{
lcdcmd(0x18);
Delay();
}
}
void lcdcmd(unsigned char a)
{
ldata=a;
rs=0;
rw=0;
en=1;
Delay();
en=0;
return;
}
void lcddata()
{
rs=1;
rw=0;
en=1;
Delay();
en=0;
return;
}
void Delay()
{
long int i=10000;
while(i--);
}