对于上节的补充:可以用GPIO_ReadOutputDataBit()实现一个按钮控制一个LED。
一、蜂鸣器模块
- 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; // Configure GPIO pin as output in push-pull mode
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; // GPIO pin 12
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; // Set GPIO speed to 50MHz
GPIO_Init(GPIOB, &GPIO_InitStructure); // Initialize GPIOB with the specified configuration
GPIO_SetBits(GPIOB, GPIO_Pin_12); // Set GPIO pin 12 to turn off the buzzer initially
}
void Buzzer_ON(void)
{
GPIO_ResetBits(GPIOB, GPIO_Pin_12); // Reset GPIO pin 12 to turn on the buzzer
}
void Buzzer_OFF(void)
{
GPIO_SetBits(GPIOB, GPIO_Pin_12); // Set GPIO pin 12 to turn off the buzzer
}
void Buzzer_Turn(void)
{
if (GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_12) == 0) // Check if GPIO pin 12 is currently low (buzzer is on)
{
GPIO_SetBits(GPIOB, GPIO_Pin_12); // Set GPIO pin 12 to turn off the buzzer
}
else
{
GPIO_ResetBits(GPIOB, GPIO_Pin_12); // Reset GPIO pin 12 to turn on the buzzer
}
}
- 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
二、光敏传感器模块
- 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; // Configure GPIO pin as input with pull-up
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; // GPIO pin 13
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; // Set GPIO speed to 50MHz
GPIO_Init(GPIOB, &GPIO_InitStructure); // Initialize GPIOB with the specified configuration
}
uint8_t LightSensor_Get(void)
{
return GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_13); // Read the value of GPIO pin 13 and return it
}
- LightSensor.h
#ifndef __BUZZER_H
#define __BUZZER_H
void Buzzer_Init(void);
void Buzzer_ON(void);
void Buzzer_OFF(void);
void Buzzer_Turn(void);
#endif
三、main
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "Buzzer.h"
#include "LightSensor.h"
int main(void)
{
Buzzer_Init(); // Initialize the buzzer
LightSensor_Init(); // Initialize the light sensor
while (1)
{
if (LightSensor_Get() == 1) // Check the value of the light sensor
{
Buzzer_ON(); // Turn on the buzzer if the light sensor detects light
}
else
{
Buzzer_OFF(); // Turn off the buzzer if the light sensor does not detect light
}
}
}
四、连接
蜂鸣器I/O接B12,光敏传感器DO引脚(数字输出)接B13.
五、附一张引脚功能图
FT表示支持5v输入输出