Demo

Dependencies:   mbed

PeripheralLayer/PeMod_ZPH01.cpp

Committer:
nightseas
Date:
2016-05-19
Revision:
2:0ee90da44162
Parent:
1:0c1053275589

File content as of revision 2:0ee90da44162:

#include "SysConfig.h"

#define ZPH01_CMD_LEN   0
#define ZPH01_DAT_LEN   9
#define ZPH01_GAS_ID    0x18

#define uart_zph01 uart_sen
//#define uart_db uart_pc

int ZPH01_Init(void)
{    
    return 0;    
}

float ZPH01_ReadPM25(void)
{
    int tmp, sum, i;
    uint8_t data[ZPH01_DAT_LEN];
                   
    #if defined uart_db
    uart_db.printf("\n\rZPH01 return ");
    #endif
    
    do{
        while(!uart_zph01.readable());
        
        tmp = uart_zph01.getc();
        #if defined uart_db
        uart_db.printf("0x%02X ", tmp);
        #endif
    }while(tmp != 0xFF);
    data[0] = 0xFF;
    
    do{
        while(!uart_zph01.readable());
        tmp = uart_zph01.getc();
        #if defined uart_db
        uart_db.printf("0x%02X ", tmp);
        #endif
    }while(tmp != ZPH01_GAS_ID);
    data[1] = ZPH01_GAS_ID;
               
    for(i=2; i<ZPH01_DAT_LEN; i++)
    {        
        data[i] = uart_zph01.getc();
        #if defined uart_db
        uart_db.printf("0x%02X ", data[i]);
        #endif
    }    
    
    #if defined uart_db
    uart_db.printf(".\n\r");
    #endif
    
    sum = ZPH01_CalCheckSum(data);
    if(data[ZPH01_DAT_LEN - 1] == sum)
    {
        //Unit: percents(%)
        float ratioPM25 = data[3] * 1.0 + data[4] / 100.0;
        #if defined uart_db
        uart_db.printf("PM2.5 PWM ratio is %f%%.\n\r", ratioPM25);
        #endif
        //Unit: ug/m^3
        float volPM25 = ratioPM25 * 20.43;
        return volPM25;
    }
    else
    {
        #if defined uart_db
        uart_db.printf("Incorrect checksum 0x%02X, expect 0x%02X.\n\r", sum, data[ZPH01_DAT_LEN - 1]);
        #endif
        return -1;
    }
}

uint8_t ZPH01_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;
}