#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit led = P0^0;
sbit sound = P2^0;
sbit key1 = P3^0;
sbit key2 = P3^2;
sbit key3 = P3^4;
void delay(uint timer)
{
uchar j = 124;
while(timer--)
{
while(j--);
}
}
void speak(uchar timer)
{
uint i =0 ;
uchar j = 0;
for (i=400;i>0;i--)
{
sound = ~ sound;
led = ~ led;
for(j=timer;j>0;j--);
}
led=1;
sound=0;
}
void keyscan()
{ uchar num=0;
if(num != P3)
{
num=P3;
delay(10);
if(num==P3)
{
if(key1==0)
{
speak(80);
}
if(key2==0)
{
speak(160);
}
if(key3==0)
{
speak(240);
}
}
}
}
void main()
{
led=1;
sound=0;
while(1)
{
keyscan();
}
}
version2
显示函数做了略微的修改
void keyscan()
{ uchar num=0;
if(num != P3)
{
num=P3;
delay(10);
if(num==P3)
{
if(key1==0)
{
speak(90);
}
if(key2==0)
{
speak(90);
delay(10);
speak(90);
}
if(key3==0)
{
speak(90);
speak(240);
}
}
}
}
定时器模拟门铃
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit led = P0^0;
sbit sound = P2^0;
sbit key1 = P3^0;
uint num;
void delay(uint timer)
{
uchar j = 124;
while(timer--)
{
while(j--);
}
}
void timer1() interrupt 3
{
sound = ~ sound;
led = ~ led;
num++;
if(num<400)
{
TH1=(8192-700)/32;
TL1=(8192-700)%32;
} else if(num<800)
{
TH1=(8192-1000)/32;
TL1=(8192-1000)%32;
} else
{
TR1=0;
num=0;
}
}
void timer1_init()
{
TMOD=0x00;
TH1=(8192-700)/32;
TL1=(8192-700)%32;
ET1=1;
EA=1;
}
void keyscan()
{ uchar key_num=0;
led=1;
if(key_num != P3)
{
key_num=P3;
delay(10);
if(key_num==P3)
{
if(key1==0)
{
TR1=1;
}
}
}
}
void main()
{
num=0;
led=1;
sound=0;
timer1_init();
while(1)
{
keyscan();
}
}