用HC-SR501检测人接近,控制L9110风扇模块启动,用DHT11检测环境温度,调整风扇转速,人离开后关闭风扇,STM32F103ZET6生成代码
时间: 2023-06-18 10:06:00 浏览: 140
以下是使用HC-SR501、L9110和DHT11进行人体接近检测和风扇调速的STM32F103ZET6代码:
```c
#include "dht11.h"
#include "delay.h"
#include "stm32f10x.h"
#define FAN_CONTROL_PIN GPIO_Pin_8
#define FAN_CONTROL_PORT GPIOB
#define MOTION_DETECTION_PIN GPIO_Pin_0
#define MOTION_DETECTION_PORT GPIOB
uint16_t DHT11_Temperature = 0;
uint16_t DHT11_Humidity = 0;
uint16_t fan_speed = 0;
void init_GPIO(void);
void init_TIM1(void);
void init_USART1(void);
void delay_ms(uint16_t ms);
int main(void)
{
init_GPIO();
init_TIM1();
init_USART1();
DHT11_Init();
while (1)
{
uint8_t motion_detected = GPIO_ReadInputDataBit(MOTION_DETECTION_PORT, MOTION_DETECTION_PIN);
if (motion_detected)
{
fan_speed = 1000;
TIM_SetCompare1(TIM1, fan_speed);
delay_ms(1000);
DHT11_Read_Data(&DHT11_Temperature, &DHT11_Humidity);
if (DHT11_Temperature > 280)
{
fan_speed = 2000;
TIM_SetCompare1(TIM1, fan_speed);
}
else if (DHT11_Temperature > 260)
{
fan_speed = 1500;
TIM_SetCompare1(TIM1, fan_speed);
}
else if (DHT11_Temperature > 240)
{
fan_speed = 1000;
TIM_SetCompare1(TIM1, fan_speed);
}
else
{
fan_speed = 0;
TIM_SetCompare1(TIM1, fan_speed);
}
}
else
{
fan_speed = 0;
TIM_SetCompare1(TIM1, fan_speed);
}
}
}
void init_GPIO(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = FAN_CONTROL_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(FAN_CONTROL_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = MOTION_DETECTION_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(MOTION_DETECTION_PORT, &GPIO_InitStructure);
}
void init_TIM1(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 40000 - 1;
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_Cmd(TIM1, ENABLE);
}
void delay_ms(uint16_t ms)
{
while (ms--)
{
delay_us(1000);
}
}
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
uint8_t data = USART_ReceiveData(USART1);
USART_SendData(USART1, data);
}
}
```
需要注意的是,此代码中使用了DHT11库和延时库,需要自行下载并添加到项目中。此外,需要在STM32CubeMX中配置USART1串口和GPIOB的PB6和PB7引脚作为串口通信使用。
阅读全文