一、电路的连接
1.原理图
2.实物图
二、代码展示
1.main.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "Buzzer.h"
#include "LightSensor.h"
int main(void)
{
BUZZER_Init();//蜂鸣器的初始化
Lightsensor_Init();//光敏感应的初始化
//有东西遮挡时想,没有则不响
while (1)
{
if(LightSensor_Get()==1)
{
BUZZER_ON();
}
else
{
BUZZER_OFF();
}
}
}
2.Buzzer.c
#include "stm32f10x.h" // Device header
void BUZZER_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_SetBits(GPIOB, GPIO_Pin_12);
}
void BUZZER_ON(void)
{
GPIO_ResetBits(GPIOB, GPIO_Pin_12);
}
void BUZZER_OFF(void)
{
GPIO_SetBits(GPIOB, GPIO_Pin_12);
}
void BUZZER_Turn(void)
{
if (GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_12) == 0)
{
GPIO_SetBits(GPIOB, GPIO_Pin_12);
}
else
{
GPIO_ResetBits(GPIOB, GPIO_Pin_12);
}
}
3.Buzzer.h
#ifndef __BUZZER_H
#define __BUZZER_H
void BUZZER_Init(void);
void BUZZER_ON(void);
void BUZZER_OFF(void);
void BUZZER_Turn(void);
#endif
4.LightSensor.c
#include "stm32f10x.h" // Device header
void Lightsensor_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
//返回端口值的函数
uint8_t LightSensor_Get(void)
{
return GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_13);
}
5.LightSensor.h
#ifndef __LIGHT_SENSOR_H
#define __LIGHT_SENSOR_H
void Lightsensor_Init(void);
uint8_t LightSensor_Get(void);
#endif
三、笔记
四个GPIO的读取函数
1.输入
uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
用来读取输入数据的寄存器某个端口的输入值
uint16_t GPIO_Pin:指定端口
uint8_t:读取按键的高低电平
uint16_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx);
读取整个输入数据寄存器
GPIOx:指定外设
uint16_t :每一位代表一个端口值
2.输出
uint8_t GPIO_ReadOutputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
读取数据寄存器的某一位,一般用于输出模式下,看自己输出的是什么
uint16_t GPIO_ReadOutputData(GPIO_TypeDef* GPIOx);
读取整个输出数据寄存器