连衡_ 发表于 2018-12-2 10:52 思路参考我在14楼说的就可以了 |
zzzy 发表于 2018-12-1 21:34 改变里面的延时长度只是改变蜂鸣的声音,还是一直响,不断的那种 ![]() |
本帖最后由 wulin 于 2018-12-2 10:47 编辑 给你一个利用定时器作驱动信号的无源蜂鸣器示例,详细注释。按一次键,响3下。 #include<reg51.h> #define uchar unsigned char #define uint unsigned int sbit key1 = P1^4; sbit beep = P1^5; uchar num=0; //响铃计数变量 uint count=0; //中断计数变量 void Timer0Init() //250微秒@12.000MHz { TMOD |= 0x02; //自动重载模式 TL0 = 0x06; //设置定时初值 TH0 = 0x06; //设置定时重载值 TR0 = 1; //定时器0开始计时 EA=1; //开总中断 ET0=1; //开T0中断 } void delay(uint z)//延时ms { uint x,y; for(x=z;x>0;x--) for(y=114;y>0;y--); } void keyscan()//按键扫描 { if(!key1) { delay(10); if(!key1) num=3;//响铃3次 while(!key1); } } void main() { Timer0Init();//初始化定时器 while(1) { keyscan();//按键扫描 } } void timer0() interrupt 1 //T0中断 { if(num>0) { count++; if(count<=1000) beep=~beep; //蜂鸣器端口取反 if(count>1000) //0.25秒时间到 beep=1; if(count>=2000)//0.5秒时间到 { count=0; //计数清0 num--; } } } |
循环结构就行 |
无源的 做个符合频率的定时器,在中断处理中 if(stop==0) beep =!beep; main函数中 stop =1; for(i=0;i<3;i++) { stop = 0; delay(500); stop = 1; delay(500); } |
while(1)死循环不要了 delay(5)太短了,500试试不明显再加倍 |
用for循环加个变量来计数 |
这个方法很多,给一个脉冲响一次,时间长度看脉冲长度,给三次就是响三下 |
将a定义为全程变量 |
用这个程序就可以,虽然程序很幼稚,但你要求的功能达到了,嘿嘿嘿。 #include <reg51.h> sbit FMQ=P1^5; void Delay25us() //@12.000MHz { unsigned char i; i = 10; while (--i); } void main (void) { unsigned char i; unsigned int j; for (j=0;j<5000;j++) { FMQ=1; for (i=0;i<5;i++) { Delay25us(); } FMQ=0; for (i=0;i<5;i++) { Delay25us(); } } for (j=0;j<5000;j++) { FMQ=0; for (i=0;i<5;i++) { Delay25us(); } FMQ=0; for (i=0;i<5;i++) { Delay25us(); } } for (j=0;j<5000;j++) { FMQ=1; for (i=0;i<5;i++) { Delay25us(); } FMQ=0; for (i=0;i<5;i++) { Delay25us(); } } for (j=0;j<5000;j++) { FMQ=0; for (i=0;i<5;i++) { Delay25us(); } FMQ=0; for (i=0;i<5;i++) { Delay25us(); } } for (j=0;j<5000;j++) { FMQ=1; for (i=0;i<5;i++) { Delay25us(); } FMQ=0; for (i=0;i<5;i++) { Delay25us(); } } for (j=0;j<5000;j++) { FMQ=0; for (i=0;i<5;i++) { Delay25us(); } FMQ=0; for (i=0;i<5;i++) { Delay25us(); } } while (1); } |
将a定义为全程变量 |
在for循环里面加个while(1) while(1) { for(a=0;a<3;a++) { } while(1) } |
永远的柽柳 发表于 2018-12-1 19:29 图片的就是for循环呀,没用,请问还有其他方法吗 |
for循环3次跳出 |
用for循环 |
无源的 |
是无源的 |