51单片机的一个IO口控制speaker发声

更新时间:2024-05-03 21:56:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

51单片机的一个I/O口控制speaker发声,演奏老鼠爱大米。

主要器件以及电路图

单片机——AT89C51,蜂鸣器——speaker。

C语言程序源码

C语言的程序代码更好读一些,相比较前面两个汇编的蜂鸣器程序,这个程序比较好理解。

/* 蜂鸣器--蜂鸣器奏乐-老鼠爱大米*/ #include

#define uint unsigned int #define uchar unsigned char #define ulong unsigned long sbit beep=P2^7; //蜂鸣器输出引脚

uchar th0_f; //中断装载T0高8位 uchar tl0_f; //T0低8位

uchar code freq[36*2]={ //音阶码表 0xf7,0xd8, //440hz , 1 //0 0xf8,0x50, //466hz , 1# //1 0xf8,0xbc, //494hz , 2 //2 0xf9,0x26, //524hz , 2# //3 0xf9,0x85, //554hz , 3 //4 0xf9,0xe5, //588hz , 4 //5 0xfa,0x3d, //622hz , 4# //6 0xfa,0x92, //660hz , 5 //7 0xfa,0xdd, //698hz , 5# //8 0xfb,0x29, //740hz , 6 //9 0xfb,0x70, //784hz , 6# //10 0xfb,0xb0, //830hz , 7 //11 0xfb,0xef, //880hz , 1 //12 0xfc,0x29, //932hz , 1# //13 0xfc,0x62, //988hz , 2 //14 0xfc,0x95, //1046hz, 2# //15 0xfc,0xc7, //1108hz, 3 //16 0xfc,0xf5, //1174hz, 4 //17 0xfd,0x20, //1244hz, 4# //18 0xfd,0x4c, //1318hz, 5 //19 0xfd,0x72, //1396hz, 5# //20 0xfd,0x97, //1480hz, 6 //21 0xfd,0xbb, //1568hz, 6# //22 0xfd,0xdc, //1662hz, 7 //23

0xfd,0xfb, //1769hz, `1 //24 0xfe,0x18, //1864hz, `1# //25 0xfe,0x34, //1976hz, `2 //26 0xfe,0x4e, //2092hz, `2# //27 0xfe,0x67, //2218hz, `3 //28 0xfe,0x7d, //2350hz, `4 //29 0xfe,0x94, //2488hz, `4# //30 0xfe,0xa8, //2639hz, `5 //31 0xfe,0xbc, //2794hz, `5# //32 0xfe,0xcf, //2960hz, `6 //33 0xfe,0xe0, //3136hz, `6# //34 0xfe,0xf1, //3322hz, `7 //35 };

uchar code diaodata[30]={ //音调代码 0x10,0x0e,0x0c,0x10,0x0e,0x0c, 0x10,0x0e,0x10,0x0c,0x10,0x15, 0x13,0x10,0x13,0x15,0x15,0x13, 0x15,0x13,0x10,0x0e,0x0c,0x0e, 0x0e,0x10,0x0e,0x0c,0x0e,0x00};

uchar code jiedata[30]={ //音长代码 0x04,0x04,0x08,0x06,0x02,0x08, 0x04,0x04,0x04,0x04,0x02,0x06, 0x08,0x02,0x02,0x04,0x04,0x04,

0x04,0x08,0x02,0x02,0x04,0x04, 0x02,0x02,0x04,0x04,0x0c,0x00};

void timer0() interrupt 1 //用于产生音符的T0中断服务程序 {

TH0=th0_f; TL0=tl0_f;

beep=~beep; //取反beep引脚,发声 }

void main(void) {

uchar i,j,k=0; uint n;

TMOD=0X01; //T0方式1 TR0=0; //关闭T0(不发声) ET0=1; //允许T0中断 EA=1; //允许总中断 while(1) {

TR0=1; //开T0

for(i=0;diaodata[i]!=0;i++) {

th0_f=freq[diaodata[i]*2]; tl0_f=freq[diaodata[i]*2+1];

for(j=0;j<20000;n++); TR0=0;

//(jiedata*20000)

for(n=0;n<256;n++); //音符之间的短暂延时 TR0=1; } TR0=0; } }

本文来源:https://www.bwwdw.com/article/gqig.html

Top