- 单片机C语言程序设计实训100例
- 彭伟编著
- 372字
- 2025-02-19 23:22:38
3.22 按键发音
本例运行时,按下不同按键会听到不同频率的声音。
本例电路如图3-19所示。

图3-19 按键发音电路
程序设计调试与实训:
本例要点在于Play函数的编写,在按下不同按键时,传给所调用的函数Play的参数值不同,从而使Play函数内部BEEP = ~BEEP后DelayMS(t)的延时不同,因而产生的频率也就不同。
读者可在案例中放置7 个按键,使按键按下时可分别输出DO、RE、ME、FA、SO、LA、XI的声音。
源程序代码:
//----------------------------------------------------------------- // 名称: 按键发音 //----------------------------------------------------------------- // 说明: 本例运行时,按下不同的按键会使SOUNDER发出不同频率的声音。 // 本例使用延时子程序实现不同频率的声音输出,后续类似案例使用 // 的是定时器技术。 //----------------------------------------------------------------- #include <reg51.h> #define uchar unsigned char #define uint unsigned int sbit BEEP= P3^7; sbit K1 = P1^4; sbit K2 = P1^5; sbit K3 = P1^6; sbit K4 = P1^7; //----------------------------------------------------------------- // 延时 //----------------------------------------------------------------- void DelayMS(uint x) { uchar t; while(x--) for(t = 0; t < 120; t++); } //----------------------------------------------------------------- // 按周期t发音 //----------------------------------------------------------------- void Play(uchar t) { uchar i; for(i = 0; i < 100; i++) { BEEP = ~BEEP; DelayMS(t); } BEEP = 0; } //----------------------------------------------------------------- // 主程序 //----------------------------------------------------------------- void main() { P1 = 0xff; while(1) { if (K1 == 0) Play(1); if (K2 == 0) Play(2); if (K3 == 0) Play(3); if (K4 == 0) Play(4); } }