3.5 代码(光敏电阻控制蜂鸣器及LED)(封装)- #include "stm32f10x.h" // Device header
- #include "Buzzer.h"
- #include "LightR.h"
- #include "LED.h"
-
-
- /***************************************************/蜂鸣器模块
- #include "Buzzer.h" // Device header
- #include "stm32f10x.h"
-
- GPIO_InitTypeDef buzzer;
-
- void Buzzer_init(uint16_t GPIO_Pin)//需要指定端口Pin进行模式设置
- {
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB ,ENABLE );//使能GPIOB的时钟
-
-
-
- buzzer.GPIO_Mode=GPIO_Mode_Out_PP;//设置为推挽输出模式
- buzzer.GPIO_Pin=GPIO_Pin; //外界参数设置Pin口
- buzzer.GPIO_Speed=GPIO_Speed_50MHz; //输出速度为50MHz,在输入模式下该设置没用
- GPIO_Init( GPIOB,&buzzer); //以上三个都要传入该函数初始化
- }
-
- void Buzzer_run(unsigned char Flag)//设定运行标志位
- {
- if(Flag==0)
- GPIO_ResetBits(GPIOB,buzzer.GPIO_Pin);//置低电平
- else
- GPIO_SetBits(GPIOB,buzzer.GPIO_Pin);//置高电平
- }
-
- /***************************************************/光敏电阻模块
- #include "LightR.h"
- #include "stm32f10x.h"
-
- GPIO_InitTypeDef lightr;
-
- void LightR_init(uint16_t GPIO_Pin)//需要指定端口Pin进行模式设置
- {
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB ,ENABLE);//使能GPIOB的时钟
-
-
-
- lightr.GPIO_Mode=GPIO_Mode_IPU;//设置为 上拉输入 模式
- lightr.GPIO_Pin=GPIO_Pin; //外界参数设置Pin口
- lightr.GPIO_Speed=GPIO_Speed_50MHz; //输出速度为50MHz,在输入模式下该设置没用
- GPIO_Init( GPIOB,&lightr); //以上三个都要传入该函数初始化
- }
-
- uint8_t get_LightR_DO(void)//用来获取光敏电阻输出的数字量DO值
- {
- return GPIO_ReadInputDataBit(GPIOB,lightr.GPIO_Pin);
- }
-
- /***************************************************/LED模块
- #include "LED.h"
- #include "stm32f10x.h" // Device header
-
- GPIO_InitTypeDef led; //定义两个IO的结构体变量 A是PA0口、B是PB0口
-
- void LED_init(uint16_t GPIO_Pin)
- {
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA ,ENABLE );//使能GPIOA的时钟
-
-
- led .GPIO_Mode=GPIO_Mode_Out_PP;//设置为推挽输出模式
- led .GPIO_Pin=GPIO_Pin; //设置为所有Pin口
- led .GPIO_Speed=GPIO_Speed_50MHz; //输出速度为50MHz
- GPIO_Init( GPIOA,&led ); //以上三个都要传入该函数初始化
-
- }
-
- void LED_state(unsigned char Flag)//指定Pin口和对应状态
- {
- if(Flag==0)
- GPIO_ResetBits(GPIOA,led.GPIO_Pin);//置低电平
- else
- GPIO_SetBits(GPIOA,led.GPIO_Pin);//置高电平
- }
-
- /***************************************************/主函数
-
- int main(void)
- {
- uint16_t lightstate;//亮、暗状态
-
- LED_init(GPIO_Pin_0);
- Buzzer_init(GPIO_Pin_0);
- LightR_init(GPIO_Pin_1);
- while(1)
- {
- lightstate =get_LightR_DO();//循环里实时获取
- if(lightstate)//暗 灯灭、蜂鸣器响
- {
- LED_state(1);
- Buzzer_run(0);
- }
- else //亮 灯亮、蜂鸣器不响
- {
- LED_state(0);
- Buzzer_run(1);
- }
- }
- }
|