//1.
Write a 8051 C Program to find a sum of First 10 integer Numbers
#include <REG51.H>
void main(void)
{
unsigned char i, n, sum = 0;
n= 10; // The number of interger number given through Port0
for (i = 1; i <=n; i++)
{
sum +=i;
}
P1=sum;// The result sum is at Port1
while(1);
}
//2. Write a 8051 C Program to find the Factorial of a given number
#include<REG51.H>
void main(void)
{
unsigned int fact = 1;
unsigned char i,n;
n=P1; //the number to find factorial is given through
Port1
// Calculate factorial
if(n==0)
fact =1;
else if(n>0)
for(i=1; i<=n; i++)
{
fact = fact * i; // the result fact is stored in memory
}
while(1);
}
//Write a 8051 C Program to find Square of a Number(1 to 10) using lookup
table
#include <REG51.H>
// lookup table for squares of numbers 1 to 10 is stored in code memory
unsigned char code lookup[10] = {0x1, 0x4, 0x9, 0x10, 0x19, 0x24, 0x31,
0x40, 0x51, 0x64};
//{1, 4, 9, 16, 25, 36, 49, 64, 81, 100};//(decimal values)
void main(void) {
unsigned char num;
num = P0; //Input is given through Port0 (P0)
P1 = lookup[num-1]; //Ourput is displayed in Port1 (P1)
while(1);
}
//4.Write an 8051 C program to count the number of Ones and zeros in two
consecitive memory locations.
#include<reg51.h>
void main()
{
unsigned char mem[2] = {0XA5, 0XFD}; //the two numbers stored in
memory locations
unsigned char ones=0, zeros = 0;
unsigned char i,j;
for(i=0; i<2;i++)
{
for(j=0; j<8; j++)
{
mem[i] = mem[i]>>1;
if(CY)
ones++;
else
zeros++;
}
P0=zeros; //Outut is sent to port 0 and port1
P1=ones;
}
while(1);
}
Interfacing Programming
//Write an 8051 C program to generate Sine and Square waveforms using DAC
interface
#include <reg51.h>
void main(void)
{
unsigned char sine_values[37] = {128, 150, 172, 192, 211, 226, 239, 250,
254, 255,
254, 250, 239, 226, 211, 192,
172, 150, 128, 106,
85, 64, 46, 30, 17, 8, 2, 0, 2, 8,
17, 30, 46, 64,
85, 106, 128};
unsigned char i;
while(1)
{
for(i=0; i<37; i++)
P2=sine_values[i];
}
}
//Write an 8051 C program to Generate Sine and Square waveforms using DAC
interface
#include <reg51.h>
void delay(void);
void main(void)
{
while(1)
{
P2 = 0xFF;
delay();
P2 = 0X00;
delay();
}
}
void delay()
{
unsigned int i;
{
for(i=0; i<=255; i++);
}
}
Additional Experiment
Write an 8051 C program to Generate Triangular waveforms using DAC interface.
#include <reg51.h>
void main(void)
{ unsigned int i,j;
while(1)
{
for (i=0;i<255; i++)
P2 = i;
for (j=255;j>0; j--)
P2=j;
}
}
Write an 8051 C program to Generate Sawtooth waveforms using DAC interface.
#include <reg51.h>
void main(void)
{ unsigned int i;
while(1)
{
for (i=0;i<255; i++)
P2 = i;
}
}