有害气体检测传感器MQ-135在stm32f103c8t6的测试代码,并能在串口上打印出来
时间: 2023-05-24 07:06:18 浏览: 1013
基于STM32F103c8t6的空气质量传感器 MQ135传感器 有害气体检测模块(串口显示)
5星 · 资源好评率100%
以下是MQ-135检测传感器的测试代码,可以在stm32f103c8t6上连线测试,并在串口上打印出检测到的有害气体浓度数值。
```c
#include "stdio.h"
#include "stm32f10x.h"
#define MQ135_PIN GPIO_Pin_0
#define MQ135_PORT GPIOA
#define UART_PORT GPIOA
#define UART_TX_PIN GPIO_Pin_9
#define UART_RX_PIN GPIO_Pin_10
#define UART_BAUDRATE 9600
#define ADC_CHANNEL 0
void GPIO_Config()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = MQ135_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(MQ135_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = UART_TX_PIN | UART_RX_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(UART_PORT, &GPIO_InitStructure);
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
USART_InitStructure.USART_BaudRate = UART_BAUDRATE;
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 ADC_Init()
{
RCC_ADCCLKConfig(RCC_PCLK2_Div6);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
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_Cmd(ADC1, ENABLE);
ADC_RegularChannelConfig(ADC1, ADC_CHANNEL, 1, ADC_SampleTime_55Cycles5);
}
int GetMQ135Value()
{
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while (!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));
return ADC_GetConversionValue(ADC1);
}
void USART_SendChar(char ch)
{
USART_SendData(USART1, ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
void USART_SendString(char* str)
{
while(*str)
{
USART_SendChar(*str++);
}
}
void USART_PrintValue(int value)
{
char buffer[16];
sprintf(buffer, "%d", value);
USART_SendString(buffer);
USART_SendString("\n");
}
int main(void)
{
GPIO_Config();
ADC_Init();
while(1)
{
int rawValue = GetMQ135Value();
USART_PrintValue(rawValue);
HAL_Delay(1000);
}
}
```
注:
该代码仅供参考,具体实现可能需要根据硬件环境和传感器型号进行相应的调整和修改。
阅读全文