1、说明
(1)MCU为STM32F103C8,二氧化碳传感器使用型号MH-Z19B; (2)硬件连接:MH-Z19B的串口与STM32的串口2相连接; (3)MH-Z19B的HD引脚连接到STM32的一个引脚,可用于手动校准零点; (4)程序中使用HAL库,代码有CubeMX生成;
2、程序
驱动头文件:mh_co2.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #ifndef __MHCO2_H_ #define __MHCO2_H_
#include "stdbool.h" #include "string.h"
#include "main.h" #include "usart.h" #include "gpio.h"
void co2_init(); void co2_sample(uint16_t *co2);
#endif
|
驱动主文件:mh_co2.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include "mhco2.h" #include "usart.h" #include "SEGGER_RTT.h"
uint8_t rx_cnt = 0; uint8_t rx_buff[16] = {0}; uint8_t rx_data;
void co2_init() { HAL_GPIO_WritePin(MH_HD_GPIO_Port,MH_HD_Pin,1); }
void co2_sample(uint16_t *co2) { uint8_t tx_array[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79}; uint8_t rx_array[9] = {0x00}; uint8_t i; uint32_t start_time = 0;
HAL_UART_Transmit(&huart2, tx_array, 9, 0xffff);
HAL_UART_Receive(&huart2, rx_array, 9, 0xffff);
uint16_t co2_value; if (rx_array[1] == 0x86) { co2_value = (uint16_t)rx_array[2]*256 + (uint16_t)rx_array[3]; } else { co2_value = 0; }
*co2 = co2_value;
}
|
在main主文件进行调用:
1 2 3 4 5
| uint16_t mhco2;
co2_sample(&mhco2);
SEGGER_RTT_printf(0, "mhco2:%d \r\n", mhco2);
|
注意:供电5V,预热时间3min。
结果如下所示: