TMP102

TMP102.cpp

Committer:
Nikollao
Date:
2016-02-10
Revision:
0:fea9b4d9a373

File content as of revision 0:fea9b4d9a373:

#include "TMP102"

TMP102::TMP102(PinName sda, PinName scl)
{
    is2_ = new I2C(sda,scl);
    led_ = new DigitalOut(LED_RED);
}

 void TMP102::init() {
    
    i2c_->frequency(400000);
    int ack;
    char config_data[2];
    char reg CONFIG_REG;
    
    ack = i2c_->write(TMP102_W_ADD,&reg,1);
    
    if (ack)
        
        error();
        
        i2c_->read(TMP102_R_ADD,&config_data,1);
    
    if (ack)
        
        error();
      
    //set conversion rate to 1 Hz  
    config_data[1] |= (1<<6); //set bit 6
    config_data[1] &= ~(1<<7); //clear bit 7
    
    char data_packet[3] = {reg, config_data[0], config_data[1]};
    
    ack = i2c_->write(TMP102_W_ADD,data_packet,3);
    
    if (ack)
        error();
        
}

void TMP102::read_temperature() {
    
    int ack;
    char data[2];
    char reg TEMP_REG;
    
    ack = i2c_->write (TMP102_W_ADD,&reg,1);
    
    if (ack) 
        error();
    
    ack = i2c_->read(TMP102_R_ADD,data,2);
    
    if (ack)
        error(); //if we don't receive acknowledgment, flash error message
        
    int temperature = (data[0] << 4) | (data[1] >> 4);
    
    temperature_ = temperature*0.0625F;
    
}

float TMP102::get_temperature() {
        
        read_temperature();
        return temperature_;
}

void TMP102::error() {
        
        while (1) {
            
            led_-> write(0);
            wait(0.2);
            led_> write(1);
            wait(0.2);
        }
}