给你一个例程看看。
/*
本实例利用无源蜂鸣器发出音乐声音。
还用到了定时计数器0
*/
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit voice=P1^5;//蜂鸣器接口
uchar code sound[]={0xff,
0x30,0x10,0x2b,0x10,0x26,0x80,0xff,0x40,0x30,0x20,0x30,0x10,0x39,0x10,
0x40,0x80,0xff,0x40,0xff,0x20,0x40,0x20,0x26,0x20,0x26,0x10,0x2b,0x10,
0x2b,0x40,0xff,0x20,0x40,0x20,0x26,0x20,0x2b,0x20,0x2b,0x80,0xff,0x40,
0xff,0x10,0x40,0x10,0x40,0x10,0x40,0x10,0x1c,0x20,0x20,0x20,0x1c,0x20,
0x26,0x20,0x26,0x20,0xff,0x20,0x2b,0x30,0x30,0x10,0x26,0x10,0x2b,0x60,
0xff,0x20,0x39,0x20,0x30,0x20,0x39,0x20,0x30,0x40,0xff,0x20,0xff,0x20,
0xff,0x20,0x39,0x10,0x39,0x10,0x2b,0x20,0x2b,0x20,0x30,0x40,0xff,0x40,
0x26,0x80,0xff,0x20,0x2b,0x20,0x30,0x20,0x30,0x10,0x39,0x10,0x40,0x80,
0xff,0x40,0xff,0x20,0x40,0x10,0x40,0x10,0x1c,0x20,0x20,0x60,0xff,0x20,
0x30,0x20,0x2b,0x20,0x26,0x10,0x2b,0x10,0x2b,0x80,0xff,0x40,0xff,0x20,
0x40,0x10,0x40,0x10,0x39,0x20,0x40,0x20,0x1c,0x30,0x20,0x10,0xff,0x20,
0x1c,0x20,0x20,0x20,0x1c,0x20,0x26,0x80,0xff,0x30,0x2b,0x10,0x2b,0x20,
0x30,0x10,0x26,0x20,0x2b,0x60,0xff,0x40,0x39,0x20,0x30,0x20,0x30,0x80,
0xff,0x40,0xff,0x40,0x40,0x20,0x39,0x20,0x30,0x20,0x2b,0x20,0x26,0x20,
0x1c,0x20,0x20,0x40,0x1c,0x20,0x1c,0x20,0x1c,0x20,0x1c,0x10,0x20,0x10,
0x20,0x20,0x20,0x10,0x26,0x10,0x26,0x40,0x26,0x20,0x26,0x20,0x26,0x20,
0x26,0x10,0x2b,0x10,0x2b,0x20,0x30,0x10,0x33,0x10,0x39,0x40,0x30,0x20,
0x30,0x20,0x30,0x20,0x39,0x10,0x40,0x10,0x40,0x80,0x40,0x20,0x39,0x20,
0x30,0x20,0x2b,0x20,0x26,0x20,0x1c,0x20,0x20,0x40,0x1c,0x20,0x1c,0x20,
0x1c,0x20,0x1c,0x10,0x20,0x10,0x20,0x20,0x20,0x10,0x26,0x10,0x26,0x40,
0x26,0x20,0x26,0x20,0x26,0x20,0x26,0x10,0x2b,0x10,0x2b,0x20,0x2b,0x10,
0x30,0x10,0x39,0x40,0x2b,0x20,0x2b,0x20,0x2b,0x20,0x2b,0x10,0x30,0x10,
0x30,0x80,0x00};
uchar zdjs=0, jp;
void del(yj);
void main(void)
{
uint dpjs=0;
uchar yj;
TMOD=0x01;
IE=0x82;
TL0=0xf0;
TR0=1;
while(1)
{
zdjs=0;
dpjs++; yj=sound[dpjs];
dpjs++; jp=sound[dpjs];
while(zdjs!=jp)
{
if(yj!=0xff)
{
if(yj!=0)
{
voice=!voice;
del(yj);
}
else
{
dpjs=0;
break;
}
}
else
{
voice=1;
del(jp);
}
}
}
}
void time0() interrupt 1
{
TH0=0xd8;
TL0=0xf0;
zdjs++;
}
void del(yj)
{
uchar yj2=2;
while(yj!=0)
{
while(yj2!=0)
{
yj2--;
}
yj2=2;
yj--;
}
}
|