HDC1080 sensor library

HDC1080.cpp

Committer:
MACRUM
Date:
2019-11-10
Revision:
4:250aceaa7a01
Parent:
3:d7627c8dcfe3

File content as of revision 4:250aceaa7a01:


#include "mbed.h"
#include "HDC1080.h"

#define     HDC_TEMP_OFF        0x00
#define     HDC_HUMID_OFF       0x01
#define     HDC_CONFIG_OFF      0x02
#define     HDC_MANID_OFF       0xFE
#define     HDC_SER_OFF_FIRST   0xFB
#define     HDC_SER_OFF_MID     0xFC
#define     HDC_SER_OFF_LAST    0xFD
#define     I2C_FREQ            100000
#define     CHIP_ADDRESS        (0x40 << 1)

const float HDC_CHIP_ERROR = -255;
const unsigned long HDC_CHIP_SER_ERROR = 0;

#if MBED_MINOR_VERSION < 14
#define thread_sleep_for(X) wait_ms(X)
#endif

HDC1080::HDC1080(PinName sda, PinName slc) : I2C(sda, slc)
{
    memset(_buffer,'\0',5);
    _buffer[0] = HDC_CONFIG_OFF;
    this->frequency(I2C_FREQ);
    int res = this->write(CHIP_ADDRESS, _buffer, 2);
}

int HDC1080::ReadSignature(void)
{
    uint16_t Manufacturer_ID = read2Bytes(CHIP_ADDRESS, HDC_MANID_OFF);

    if (Manufacturer_ID == 0) {
        return (int)HDC_CHIP_ERROR;
    } else {
        return Manufacturer_ID;
    }
}

float HDC1080::readTemperature()
{
    uint16_t  rawT = read2Bytes(CHIP_ADDRESS, HDC_TEMP_OFF);

    if (rawT == 0) {
        return HDC_CHIP_ERROR;
    } else {
        float temp = ((float) rawT / pow(2.0f, 16.0f)) * 165.0f - 40.0f;
        return temp;
    }
}

float HDC1080::readHumidity()
{
    uint16_t  rawH = read2Bytes(CHIP_ADDRESS, HDC_HUMID_OFF);

    if (rawH == 0) {
        return HDC_CHIP_ERROR;
    } else {
        float humidity = ((float) rawH / pow(2.0f, 16.0f)) * 100.0f;
        return humidity;
    }
}

unsigned long HDC1080::readSerialNumber(void)
{
    thread_sleep_for(15);
    memset(_buffer,0,4);
    _buffer[0] = HDC_MANID_OFF;
    
    int res = this->write(CHIP_ADDRESS, _buffer, 1);
    if (res != 0) {
        return (unsigned long) HDC_CHIP_SER_ERROR;
    }

    thread_sleep_for(15);
    memset(_buffer,0,4);
    
    res = this->read(CHIP_ADDRESS, _buffer,4);
    if (res != 0) {
        return (unsigned long) HDC_CHIP_SER_ERROR;
    }

    unsigned long rawser = _buffer[2] << 16 | _buffer[1] << 8 | _buffer[0];
    return rawser;
}

//Private Member functions

uint16_t HDC1080::read2Bytes(int chip_addr, int offset)
{
    memset(_buffer,0,3);
    
    // send chip address onto buss
    _buffer[0] = offset;
    int res =this->write(chip_addr, _buffer, 1);
    if (res != 0) {
        return 0;
    }
    
    // read data from chip
    thread_sleep_for(15);
    memset(_buffer,0,3);
    res = this->read(CHIP_ADDRESS, _buffer,2);
    if (res != 0) {
        return 0;
    }
    return  _buffer[0] << 8 | _buffer[1];
}