小白跟做江科大32单片机之光敏传感器控制蜂鸣器

发布于:2024-06-03 ⋅ 阅读:(93) ⋅ 点赞:(0)

代码部分

1.思路

通过光敏电阻,控制蜂鸣器的发声

2.butter.h代码

#ifndef _BUTTER__H
#define _BUTTER__H

void butter_Init(void);
void butter_on(void);
void butter_off(void);

#endif
 

3.butter.c代码

#include "stm32f10x.h" 
void butter_Init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);    //开启GPIOB的时钟
                                                            //使用各个外设前必须开启时钟,否则对外设的操作无效
    
    /*GPIO初始化*/
    GPIO_InitTypeDef GPIO_InitStructure;                    //定义结构体变量
    
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;        //GPIO模式,赋值为推挽输出模式
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;    //GPIO引脚,赋值为第1,2号引脚
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;        //GPIO速度,赋值为50MHz
    
    GPIO_Init(GPIOB, &GPIO_InitStructure);                    //将赋值后的构体变量传递给GPIO_Init函数
                                                            //函数内部会自动根据结构体的参数配置相应寄存器
                                                            //实现GPIOB的初始化
}
void butter_on(void)
{
    GPIO_ResetBits(GPIOB, GPIO_Pin_12);
}

void butter_off(void)
{
    GPIO_SetBits(GPIOB, GPIO_Pin_12);
}

4.guang.h代码

#ifndef _GUANG__H
#define _GUANG__H

void light_Init(void);
uint8_t light_style(void);


#endif
 

5.guang.c代码

#include "stm32f10x.h" 
void light_Init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);    //开启GPIOB的时钟
                                                            //使用各个外设前必须开启时钟,否则对外设的操作无效
    
    /*GPIO初始化*/
    GPIO_InitTypeDef GPIO_InitStructure;                    //定义结构体变量
    
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;        //GPIO模式,赋值为上拉输出模式
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;    //GPIO引脚,赋值为第1,2号引脚
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;        //GPIO速度,赋值为50MHz
    
    GPIO_Init(GPIOB, &GPIO_InitStructure);                    //将赋值后的构体变量传递给GPIO_Init函数
                                                            //函数内部会自动根据结构体的参数配置相应寄存器
                                                            //实现GPIOB的初始化
}

uint8_t light_style(void)
{
    return GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_13);            //返回PB13输入寄存器的状态
}
 

6.main.c代码

#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "butter.h"
#include "guang.h"


int main()
{
   butter_Init();
     light_Init();
    while (1)
    {
        if(light_style()==1)
        {
            butter_on();
        }
        if(light_style()==0)
        {
            butter_off();
        }
        
    }
}

7.电路连接示意图

8.实验结果

STM32光敏传感器控制蜂鸣器试验结果


网站公告

今日签到

点亮在社区的每一天
去签到