基于stm32F103的防盗装置
时间: 2023-07-26 18:25:30 浏览: 82
基于stm32f103的控制器方案
以下是基于STM32F103的简单防盗装置示例代码:
```C++
#include "stm32f10x.h"
#define SENSOR_PIN GPIO_Pin_0
#define SENSOR_PORT GPIOA
#define LED_PIN GPIO_Pin_1
#define LED_PORT GPIOA
#define BUZZER_PIN GPIO_Pin_2
#define BUZZER_PORT GPIOA
void GPIO_Configuration(void);
void EXTI_Configuration(void);
void Buzzer_Configuration(void);
int main(void) {
GPIO_Configuration();
EXTI_Configuration();
Buzzer_Configuration();
while (1) {
// 等待中断触发
}
}
void GPIO_Configuration(void) {
GPIO_InitTypeDef GPIO_InitStructure;
// 使能GPIOA时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置SENSOR_PIN为输入模式
GPIO_InitStructure.GPIO_Pin = SENSOR_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(SENSOR_PORT, &GPIO_InitStructure);
// 配置LED_PIN和BUZZER_PIN为输出模式
GPIO_InitStructure.GPIO_Pin = LED_PIN | BUZZER_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
}
void EXTI_Configuration(void) {
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// 使能AFIO时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
// 配置SENSOR_PIN为中断输入模式
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource0);
// 配置EXTI线路
EXTI_InitStructure.EXTI_Line = EXTI_Line0;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
// 配置中断优先级
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void Buzzer_Configuration(void) {
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
// 使能TIM2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
// 配置TIM2的时间基准
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = 7199;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置TIM2的PWM输出模式
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 499;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
// 启动TIM2
TIM_Cmd(TIM2, ENABLE);
}
void EXTI0_IRQHandler(void) {
if (EXTI_GetITStatus(EXTI_Line0) != RESET) {
// SR505检测到有人体靠近
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_SET);
TIM_SetCompare1(TIM2, 799); // 使蜂鸣器发出声音
delay(500); // 延迟500毫秒
TIM_SetCompare1(TIM2, 0); // 关闭蜂鸣器
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
void delay(uint32_t nCount) {
uint32_t i;
for (i = 0; i < nCount; i++);
}
```
该示例代码使用SR505检测有人体靠近,当检测到有人靠近时,LED会亮起来,同时蜂鸣器会发出声音,以起到防盗的作用。需要注意的是,蜂鸣器的控制采用的是PWM输出,可以通过调整占空比来控制声音大小。
阅读全文