蜂鸣器实验
一.参考资料:
探索者STM32F4开发板:
《STM32F4开发指南-库函数版本》-第7章 蜂鸣器实验
STM32F4xx官方资料:
《STM32F4xx中文参考手册》-第7章通用IO
二.蜂鸣器硬件连接:
三.注意事项:
1.使能IO口时钟。调用函数RCC_AHB1PeriphClockCmd();
**不同的外设调用的时钟使能函数可能不一样**
2.初始化IO口模式。调用函数GPIO_Init();
3.操作IO口,输出高低电平。
具体操作:
步骤同跑马灯实验
1.beep.h文件代码:
#define __BEEP_H #include "sys.h" //LED¶Ë¿Ú¶¨Òå #define BEEP PFout(8) // ·äÃùÆ÷¿ØÖÆIO void BEEP_Init(void);//³õʼ»¯ #endif
2.beep.c文件代码:
#include "beep.h" void BEEP_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);//ʹÄÜGPIOFʱÖÓ //³õʼ»¯·äÃùÆ÷¶ÔÓ¦Òý½ÅGPIOF8 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;//ÆÕͨÊä³öģʽ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//ÍÆÍìÊä³ö GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;//100MHz GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;//ÏÂÀ GPIO_Init(GPIOF, &GPIO_InitStructure);//³õʼ»¯GPIO GPIO_ResetBits(GPIOF,GPIO_Pin_8); //·äÃùÆ÷¶ÔÓ¦Òý½ÅGPIOF8ÀµÍ£¬ }
3.main.c文件代码:
#include "sys.h" #include "delay.h" #include "usart.h" #include "led.h" #include "beep.h" int main(void) { delay_init(168); //³õʼ»¯ÑÓʱº¯Êý LED_Init(); //³õʼ»¯LED¶Ë¿Ú BEEP_Init(); //³õʼ»¯·äÃùÆ÷¶Ë¿Ú while(1) { GPIO_ResetBits(GPIOF,GPIO_Pin_9); // DS0ÀµÍ£¬ÁÁ µÈͬLED0=0; GPIO_ResetBits(GPIOF,GPIO_Pin_8); //BEEPÒý½ÅÀµÍ£¬ µÈͬBEEP=0; delay_ms(300); //ÑÓʱ300ms GPIO_SetBits(GPIOF,GPIO_Pin_9); // DS0À¸ß£¬Ãð µÈͬLED0=1; GPIO_SetBits(GPIOF,GPIO_Pin_8); //BEEPÒý½ÅÀ¸ß£¬ µÈͬBEEP=1; delay_ms(300); //ÑÓʱ300ms } }
4.注意要将led.c和led.h文件保留在这个工程中,因为在main主代码中会使用到led。