- 單片機(jī)C語(yǔ)言程序設(shè)計(jì)實(shí)訓(xùn)100例
- 彭偉編著
- 372字
- 2018-12-27 05:12:08
3.22 按鍵發(fā)音
本例運(yùn)行時(shí),按下不同按鍵會(huì)聽(tīng)到不同頻率的聲音。
本例電路如圖3-19所示。

圖3-19 按鍵發(fā)音電路
程序設(shè)計(jì)調(diào)試與實(shí)訓(xùn):
本例要點(diǎn)在于Play函數(shù)的編寫(xiě),在按下不同按鍵時(shí),傳給所調(diào)用的函數(shù)Play的參數(shù)值不同,從而使Play函數(shù)內(nèi)部BEEP = ~BEEP后DelayMS(t)的延時(shí)不同,因而產(chǎn)生的頻率也就不同。
讀者可在案例中放置7 個(gè)按鍵,使按鍵按下時(shí)可分別輸出DO、RE、ME、FA、SO、LA、XI的聲音。
源程序代碼:
//----------------------------------------------------------------- // 名稱(chēng): 按鍵發(fā)音 //----------------------------------------------------------------- // 說(shuō)明: 本例運(yùn)行時(shí),按下不同的按鍵會(huì)使SOUNDER發(fā)出不同頻率的聲音。 // 本例使用延時(shí)子程序?qū)崿F(xiàn)不同頻率的聲音輸出,后續(xù)類(lèi)似案例使用 // 的是定時(shí)器技術(shù)。 //----------------------------------------------------------------- #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; //----------------------------------------------------------------- // 延時(shí) //----------------------------------------------------------------- void DelayMS(uint x) { uchar t; while(x--) for(t = 0; t < 120; t++); } //----------------------------------------------------------------- // 按周期t發(fā)音 //----------------------------------------------------------------- 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); } }
推薦閱讀
- Java應(yīng)用與實(shí)戰(zhàn)
- ASP.NET Core 5.0開(kāi)發(fā)入門(mén)與實(shí)戰(zhàn)
- Mastering Natural Language Processing with Python
- Java程序設(shè)計(jì)與計(jì)算思維
- Koa開(kāi)發(fā):入門(mén)、進(jìn)階與實(shí)戰(zhàn)
- Rust Cookbook
- Python自然語(yǔ)言處理(微課版)
- 低代碼平臺(tái)開(kāi)發(fā)實(shí)踐:基于React
- 零基礎(chǔ)入門(mén)學(xué)習(xí)Python(第2版)
- Mastering Business Intelligence with MicroStrategy
- OpenCV 3.0 Computer Vision with Java
- 大規(guī)模語(yǔ)言模型開(kāi)發(fā)基礎(chǔ)與實(shí)踐
- Spring Boot 3:入門(mén)與應(yīng)用實(shí)戰(zhàn)
- ROS Robotics Projects
- Effective DevOps with AWS