当前位置:网站首页>一段用蜂鸣器编的音乐(成都)

一段用蜂鸣器编的音乐(成都)

2022-07-06 09:20:00 axu_990707

代码和仿真可通过如下链接下载

资源链接: 点击下载 下载免费

仿真图示

在这里插入图片描述

蜂鸣器采用无源蜂鸣器speaker,可以通过定时器定时从而改变发音频率。
通过查询音阶对应的频率,制作出不同的定时,产生不同的频率。然后配合曲谱,即可奏乐。
操作较为简单。

#include<reg51.h>
sbit P10=P1^0;
sbit P17=P1^7;
void delay(unsigned char k){
    
	unsigned char h,i,j;
	for(h=0;h<k;h++){
    
		for(i=0;i<25;i++){
    
			for(j=0;j<20;j++);
		}
	}
}
/**delay方法使用介绍 *功能说明: *可以作程序延时使用 *延时时长由传入的参数决定 *传入参数的单位为ms *如输入“1”代表延时1ms *以此类推 */
void speaker(unsigned int SSC,unsigned int fre){
    
	unsigned int j=fre;
	TMOD=0x11;			
	TR0=1;
	TR1=1;	
	EA=1;
	ET0=1;
	ET1=1;		
	P10=1;				
	TH0=SSC/256;
	TL0=SSC%256;
	TH1=60928/256;
	TL1=60928%256;
	while(j>0){
    
		while(TF1==0){
    			
			while(TF0==0){
    
				;	
			}
			TR0=0;			
			TH0=SSC/256;
			TL0=SSC%256;
			P10=~P10;
			TR0=1;
			TF0=0;
		}
		TH1=60928/256;
		TL1=60928%256;
		TF1=0;
		j--;
		TF1=0;
	}
	j=fre;
}
void musician(unsigned int tone,unsigned int duration){
    
	unsigned int box1[]={
    
		0,63628,63835,64021,64103,64260,64400,64524,
		//低1(1) 低2(2) 低3(3) 低4(4) 低5(5) 低6(6) 低7(7) 
		64580,64680,64750,64800,64898,64968,65030, 
		//中1(8) 中2(9) 中3(10) 中4(11) 中5(12) 中6(13) 中7(14)
		65058,65110,65160,65178	
		//高1(15) 高2(16) 高3(17) 高4(18)
	};
	unsigned int box2[]={
    
		0,/*1*/30,/*2*/60,90,/*4*/120,150,/*6*/150,210,240,270,300,
		//时值
		//0.1S(1)~1S(10)


	};
	speaker(box1[tone],box2[duration]);
	P10=1;
	delay(20);		
}
void main(){
    
	while(P17==0){
    
		musician(12,6);
		musician(12,2);
		musician(10,2);
		musician(12,2);
		musician(13,4);
		musician(13,2);
		musician(10,4);
		musician(9,2);
		musician(8,2);
		musician(5,1);
		musician(6,1);
		musician(8,2);
		musician(9,2);
		musician(10,2);
		musician(9,2);
		musician(10,6);
		musician(12,6);
		musician(12,2);
		musician(10,2);
		musician(12,2);
		musician(13,4);
		musician(13,2);
		musician(10,4);
		musician(9,2);
		musician(8,2);
		musician(5,1);
		musician(6,1);
		musician(8,2);
		musician(9,2);
		musician(12,2);
		musician(9,2);
		musician(8,6);
		musician(12,2);
		musician(10,2);
		musician(9,2);
		musician(8,6);
		musician(5,4);
	}	
}
原网站

版权声明
本文为[axu_990707]所创,转载请带上原文链接,感谢
https://blog.csdn.net/axu_990707/article/details/124816200