编写一份基于stm32f103的MQ-2烟雾传感器测试代码分为主函数.c和.h文件
时间: 2024-02-15 13:03:50 浏览: 193
以下是一个基于 STM32F103 和 MQ-2 烟雾传感器的测试代码,分为主函数.c和.h文件:
### 烟雾传感器 MQ-2.h
```c
#ifndef __MQ2_H
#define __MQ2_H
#include "stm32f10x.h"
#define ADC_CHANNEL 0
#define ADC_GPIO_PORT GPIOA
#define ADC_GPIO_PIN GPIO_Pin_0
#define ADC_GPIO_CLK RCC_APB2Periph_GPIOA
#define ADC1_CLK RCC_APB2Periph_ADC1
void MQ2_Init(void);
u16 MQ2_GetADCValue(void);
u8 MQ2_Detect(void);
#endif /* __MQ2_H */
```
### 烟雾传感器 MQ-2.c
```c
#include "MQ2.h"
void MQ2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
/* Enable ADC1 and GPIOA clock */
RCC_APB2PeriphClockCmd(ADC1_CLK | ADC_GPIO_CLK, ENABLE);
/* Configure ADC1 Channel0 as analog input */
GPIO_InitStructure.GPIO_Pin = ADC_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(ADC_GPIO_PORT, &GPIO_InitStructure);
/* ADC1 configuration */
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfChannel = 1;
ADC_Init(ADC1, &ADC_InitStructure);
/* ADC1 regular channel0 configuration */
ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_55Cycles5);
/* Enable ADC1 */
ADC_Cmd(ADC1, ENABLE);
}
u16 MQ2_GetADCValue(void)
{
u16 adc_value;
/* Start ADC1 Software Conversion */
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
/* Wait until ADC1 conversion is complete */
while (ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
/* Get ADC1 converted data */
adc_value = ADC_GetConversionValue(ADC1);
return adc_value;
}
u8 MQ2_Detect(void)
{
u8 status = 0;
u16 adc_value = MQ2_GetADCValue();
if (adc_value > 1000) {
status = 1; /* Detected */
} else {
status = 0; /* Not detected */
}
return status;
}
```
### 主函数.c
```c
#include "MQ2.h"
#include <stdio.h>
int main(void)
{
u8 status = 0;
/* Initialize MQ-2 sensor */
MQ2_Init();
while (1) {
/* Detect smoke */
status = MQ2_Detect();
if (status == 1) {
printf("Smoke detected!\n");
} else {
printf("Smoke not detected.\n");
}
}
}
```
请注意,这只是一个简单的测试代码,仅供参考。如果您需要进行更严格的烟雾检测,请根据您的具体应用场景进行更改。
阅读全文