中级会员
 
- 积分
- 405
- 金钱
- 405
- 注册时间
- 2019-3-21
- 在线时间
- 107 小时
|

楼主 |
发表于 2019-3-28 14:44:55
|
显示全部楼层
#include "CO2_Sensor.h"
#include "timer.h"
#include "usart.h"
uint8_t data_buf[32];
uint8_t counter;
uint8_t total;
uint8_t total1;
void CO2_config(void)
{
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);
SysTick_Config_Init();
CO2_gpio_config();
CO2_usart_config();
co2_receivedata();
co2_data_anl();
}
void CO2_gpio_config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
void CO2_usart_config(void)
{
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600; /*波特率*/
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; /*流控*/
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_InitStructure.USART_WordLength = USART_WordLength_8b; /*数据位,8*/
USART_InitStructure.USART_Parity = USART_Parity_No; /*校验位,n*/
USART_InitStructure.USART_StopBits = USART_StopBits_1; /*停止位,1*/
USART_Init(USART3,&USART_InitStructure);
USART_ClearFlag(USART3,USART_FLAG_TC); //清除发送完成标志位
USART_Cmd(USART3,ENABLE); //使能串口3
USART_ITConfig(USART3,USART_IT_RXNE,ENABLE);
}
uint8_t co2_receivedata(void) //左字节*256+右字节 = CO2浓度
{
uint8_t state = 0; //状态
uint8_t data = 12; //数据
if(state == 0 && data == 0x42) //起始符 1
{
data_buf[0] = data;
state = 1;
counter = 1;
}
else if(state == 1 && data == 0x4d) //起始符 2
{
data_buf[1] = data;
state = 2;
}
else if(state == 2 && data > 0) //接收数据
{
data--;
data_buf[counter++] = data;
if(data == 0) //接收满
{
state = 3;
}
}
else if(state == 3)
{
state = 0;
data = 32;
counter = 0;
co2_data_anl();
}
return state;
}
uint8_t co2_data_anl(void) //解析数据
{
for(counter = 0; counter < 10; counter++) // 0-29字节 非校验位
{
total += data_buf[counter];
}
total1 = data_buf[10] + data_buf[11]; //校验位
if(total == total1)
{
return 1; //校验正确
}
else
{
return 0; //校验错误
}
}
int main()
{
static uint32_t led_timer = 0;
usart_config();
led_gpio_init();
CO2_config();
while(1)
{
if (tick1ms - led_timer >= 500)
{
led_timer = tick1ms;
//GPIO_ResetBits(GPIOB,GPIO_Pin_7);
GPIOB->ODR ^= GPIO_Pin_7;
}
while (counter == 12)
{
int CO2;
CO2 = (int)data_buf[4] * 256 + (int)data_buf[5];
printf("CO2 is %d ppm\r\n",CO2);
if (counter > 11)
{
counter = 0;
}
}
}
} |
|