stm32f103zet6连接mq2传感器串口打印采样值
时间: 2023-12-27 13:04:20 浏览: 130
以下是使用STM32F103ZET6连接MQ2传感器并通过串口打印采样值的示例代码:
```c
#include "stm32f10x.h"
#define MQ2_PIN GPIO_Pin_0
#define MQ2_PORT GPIOA
void init_GPIO(void);
void init_USART1(void);
void USART_puts(USART_TypeDef* USARTx, volatile char *s);
int main(void)
{
volatile uint16_t mq2_value;
init_GPIO();
init_USART1();
while (1)
{
mq2_value = ADC_GetConversionValue(ADC1);
char str[10];
sprintf(str, "%d\n", mq2_value);
USART_puts(USART1, str);
delay_ms(1000);
}
}
void init_GPIO(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = MQ2_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(MQ2_PORT, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
RCC_ADCCLKConfig(RCC_PCLK2_Div6);
ADC_InitTypeDef ADC_InitStructure;
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);
ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_239Cycles5);
ADC_Cmd(ADC1, ENABLE);
ADC_ResetCalibration(ADC1);
while(ADC_GetResetCalibrationStatus(ADC1));
ADC_StartCalibration(ADC1);
while(ADC_GetCalibrationStatus(ADC1));
}
void init_USART1(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void USART_puts(USART_TypeDef* USARTx, volatile char *s)
{
while(*s)
{
while(USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
USART_SendData(USARTx, *s);
*s++;
}
}
void delay_ms(uint16_t ms)
{
volatile uint32_t count = ms * 1000;
while(count--);
}
```
该代码使用ADC采集MQ2传感器的模拟输出值,并通过串口将采样值打印出来。在初始化函数中,使用GPIO初始化MQ2传感器的输入引脚,使用ADC初始化ADC1并配置其采样通道为PA0。在主函数中,通过ADC_GetConversionValue函数获取ADC转换后的值,并使用sprintf将其转换为字符串格式,最后通过USART_puts函数将字符串发送到串口。由于MQ2传感器的响应速度较慢,为避免多次读取同一采样值,使用delay_ms函数添加延时。
阅读全文