按键按一次,蜂鸣器响一次 ,LCD1602同步。
#include <REGX52.H>
#include <INTRINS.H>
unsigned int keynum;
sbit RS=P3^0; //**
sbit RW=P3^1; //**
sbit E=P3^2; //**
sbit buzzer=P1^5;
void delay(unsigned int n)//1ms
{
unsigned char a,b,c,m;
for(m=n;m>0;m--)
for(c=1;c>0;c--)
for(b=142;b>0;b--)
for(a=2;a>0;a--);
}
unsigned char key()
{
unsigned char keynumber=0;
if(P1_0==0)
{
delay(20);
while(P1_0==0);
delay(20);
keynumber=1;
}
if(P1_1==0)
{
delay(10);
while(P1_1==0);
delay(10);
keynumber=2;
}
if(P1_2==0)
{
delay(10);
while(P1_2==0);
delay(10);
keynumber=3;
}
if(P1_3==0)
{
delay(20);
while(P1_3==0);
delay(20);
keynumber=4;
}
return keynumber;
}
void writedat(unsigned char dat)
{
RS=1;
RW=0;
E=0;
P2=dat;
delay(10); //看情况要不要延时
E=1;
E=0;
}
void writecom(unsigned char com)
{
RS=0;
RW=0;
E=0;
P2=com;
delay(10);
E=1;
E=0;
}
void initlcd()
{
writecom(0x38);
writecom(0x0c);
writecom(0x06);
writecom(0x01);
}
void LCD_SetCursor(unsigned char Line,unsigned char Column)
{
if(Line==1)
{
writecom(0x80|(Column-1));
}
else if(Line==2)
{
writecom(0x80|(Column-1+0x40));
}
}
int LCD_Pow(int X,int Y)
{
unsigned char i;
int Result=1;
for(i=0;i<Y;i++)
{
Result*=X;
}
return Result;
}
void LCD_ShowNum(unsigned char Line,unsigned char Column,unsigned int Number,unsigned char Length)
{
unsigned char i;
LCD_SetCursor(Line,Column);
for(i=Length;i>0;i--)
{
writedat(Number/LCD_Pow(10,i-1)%10+'0');
}
}
void buzzer_time(unsigned int ms)
{
unsigned int i;
for(i=0;i<ms;i++)
{
buzzer=!buzzer;
delay(1); //每隔1ms翻转一次,周期为2ms,频率500hz
}
}
void main()
{
initlcd();
while(1)
{
keynum=key();
if(keynum)
{
buzzer_time(500);
LCD_ShowNum(1,1,keynum,1);
}
}
}
《小星星》乐谱
#include <REGX52.H>
#include <INTRINS.H>
unsigned int freqtable[]={63628,63731,63835,63928,64021,64103,64185,64260,64331,64400,64463,64528,64580,64633,64684,64732,64777,64820,64860,64898,64934,64968,65000,65030,65058,65085,65110,65134, 65157,65178,65198,65217,65235,65252,65268,65283,};
unsigned char music[]={
12,4,
12,4,
19,4,
19,4,
21,4,
21,4,
19,4+4,
17,4,
17,4,
16,4,
16,4,
14,4,
14,4,
12,4+4,
};
unsigned char freqselect,musicselect;
unsigned int keynum;
sbit RS=P3^0; //**
sbit RW=P3^1; //**
sbit E=P3^2; //**
sbit buzzer=P1^5;
void delay(unsigned int t)
{
unsigned int i=0,j=0;
for(i=0;i<t;i++)
{
for(j=0;j<120;j++);
}
}
void main()
{
buzzer=0;
inittimer();
//initlcd();
while(1)
{
freqselect=music[musicselect];
musicselect++;
delay(125*music[musicselect]);
musicselect++;
TR0=0;
delay(5);
TR0=1;
}
}
void time0() interrupt 1//定时器0中断函数
{
TH0=freqtable[freqselect]/256; //初值=65536-1000=64536=FC18H,定时1ms
TL0=freqtable[freqselect]%256;
buzzer=!buzzer;///1ms翻转一次,相当于一个周期为2ms,频率500hz
}