Demo

Dependencies:   mbed

PeripheralLayer/PeMod_MHZ19.cpp

Committer:
nightseas
Date:
2016-05-19
Revision:
2:0ee90da44162
Parent:
PeripheralLayer/PeMod_ESP01.cpp@ 1:0c1053275589

File content as of revision 2:0ee90da44162:

#include "SysConfig.h"

#define MHZ19_CMD_LEN   9
#define MHZ19_DAT_LEN   9

#define uart_mhz19 uart_sen
//#define uart_db uart_pc

const uint8_t MHZ19_CmdMCalZero[MHZ19_CMD_LEN] = {0xFF, 0x01, 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78};
const uint8_t MHZ19_CmdMCalFull[MHZ19_CMD_LEN] = {0xFF, 0x01, 0x88, 0x07, 0xD0, 0x00, 0x00, 0x00, 0xA0};
const uint8_t MHZ19_CmdReadCO2[MHZ19_CMD_LEN] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};

int MHZ19_Init(void)
{
    return 0;   
}

int MHZ19_ReadCO2(void)
{
    int co2Vol, i, sum = 0; 
    uint8_t data[MHZ19_DAT_LEN];
           
    for(i=0; i<MHZ19_CMD_LEN; i++)
        uart_mhz19.putc(MHZ19_CmdReadCO2[i]);
        
    #if defined uart_db
    uart_db.printf("\n\rMHZ19 return ");
    #endif
        
    for(i=0; i<MHZ19_DAT_LEN; i++)
    {
        while(!uart_mhz19.readable());
        data[i] = uart_mhz19.getc();
        #if defined uart_db
        uart_db.printf("0x%02X ", data[i]);
        #endif
    }    
    
    #if defined uart_db
    uart_db.printf(".\n\r");
    #endif
    
    sum = MHZ19_CalCheckSum(data);
    if(data[MHZ19_DAT_LEN - 1] == sum)
    {
        co2Vol = data[2] *256 + data[3];
        return co2Vol;
    }
    else
    {
        #if defined uart_db
        uart_db.printf("Incorrect checksum 0x%02X, expect 0x%02X.\n\r", sum, data[MHZ19_DAT_LEN - 1]);
        #endif
        return -1;
    }
}

int MHZ19_CalZero(void)
{ 
    for(int i=0; i<MHZ19_CMD_LEN; i++)
        uart_mhz19.putc(MHZ19_CmdMCalZero[i]);
        
    return 0;        
}

int MHZ19_CalFull(void)
{
    for(int i=0; i<MHZ19_CMD_LEN; i++)
        uart_mhz19.putc(MHZ19_CmdMCalFull[i]);
        
    return 0;        
}

uint8_t MHZ19_CalCheckSum(uint8_t *packet)
{
    uint8_t i, checksum = 0;
    for( i = 1; i < 8; i++)
    {
        checksum += packet[i];
    }
    checksum = 0xff - checksum;
    checksum += 1;
    return checksum;
}