基于stm32f103的SR505的示例代码
时间: 2023-08-14 14:02:18 浏览: 74
以下是基于STM32F103的SR505示例代码:
```C++
#include "stm32f10x.h"
#define SENSOR_PIN GPIO_Pin_0
#define SENSOR_PORT GPIOA
#define LED_PIN GPIO_Pin_1
#define LED_PORT GPIOA
void GPIO_Configuration(void);
void EXTI_Configuration(void);
int main(void) {
GPIO_Configuration();
EXTI_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为输出模式
GPIO_InitStructure.GPIO_Pin = LED_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 EXTI0_IRQHandler(void) {
if (EXTI_GetITStatus(EXTI_Line0) != RESET) {
// SR505检测到有人体靠近
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_SET);
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
```
请注意,这只是一个基本的示例代码,您可以根据自己的需求进行修改和优化。另外,需要注意的是,SR505的输出信号需要通过外部中断来触发,所以需要配置相应的中断线路。
阅读全文