#include "mbed.h"
#include "SMTC502AT.h"

SMTC502AT::SMTC502AT(AnalogIn *ain, float R0, float R1, float B, float T0) 
{
    _ain = ain ;
    _r0 = R0 ;
    _r1 = R1 ;
    _b  = B ;
    _t0 = T0 ;
}

SMTC502AT::~SMTC502AT(void)
{
    if (_ain) {
        delete _ain ;
    }
}

/**
 * getTemp returns the temperature
 * operational temperature is -50C to +105C
 */
float SMTC502AT::getTemp(void)
{
    float result = 0.0 ;
    float f, raw, rr1, t ;
    if (_ain) {
        f = _ain->read() ;
#if 0
        if (f < 0.087) { /* +105C */
            printf("Temp is Too high or the sensor is absent\n") ;
            f = 0.087 ;
        }
        if (f > 0.978) { /* -50C */
            printf("Temp is Too low or the sensor encountered a problem\n") ;
            f = 0.978 ;
        }
#endif
        raw = f * 3.3 ;
        rr1 = _r1 * raw / (3.3 - raw) ;
        t = 1.0 / (log(rr1 / _r0) / _b + (1/_t0)) ;
        result = t - 273.15 ;
    }
    return( result ) ;
}
        