Calculate temperature based on resistance from thermistor with lookup chart

thermister_ert-j0eg1.cpp

Committer:
joeata2wh
Date:
2016-07-15
Revision:
4:25c01de9fb3f
Parent:
1:cc492e6ba333

File content as of revision 4:25c01de9fb3f:

#include "mbed.h"
#include "ohms.h"  // from library ohms_law

// Set of resistance values from data sheet used to lookup temperature to find
// location in a 5V band. 
static long thermisterResistance[] = {205200,154800,117900,90690,70370,50570,43440,34530,27640,22270,18060,14740,12110,
                  10000,8309,6941,5828,4916,4165,3542,3027,2595,2233,1929,1672,1451,1261,1097,956,836,732,642,565,499};                  
static int thermisterBase = -40;
static int thermisterStep = 5;
static int thermisterMaxTemp = 125;
const float adc_ref = 3.30;



float conv_c_to_f(float tempC) {  
  return (tempC * 1.8f) + 32.0f;
}


/* Read Thermister Temperature using ADC and voltage dividor 
 Lookup the range of resistance by finding the first resistance
 lower than our specified value which gives us temp with 5C spread
 then adjust by how far our sensor reading is above the lower
 bound of the range.*/
float readTemp(AnalogIn adcpin) {    
    //sensorValue = avgRead(adcpin,3,2);
    float sensorValue = adcpin.read() * adc_ref;    
    long sensorResist =  calcResistV(22100, adc_ref, sensorValue);
    int tempCnt = thermisterBase;   
    int tempndx = 0;
    
    if  (sensorValue >= thermisterResistance[0]) {
      return -255;
    }
    
    while (sensorResist < thermisterResistance[tempndx]) {     
       tempndx++;
       tempCnt += thermisterStep;
       if (tempCnt >= thermisterMaxTemp) {
         return 255;
       }
    }
    tempCnt -= thermisterStep; // backup to begin of range    
    int lowTempResist = thermisterResistance[tempndx -1];
    int highTempResist = thermisterResistance[tempndx];
    int resistRangeDelta = lowTempResist - highTempResist;
    float degreesPerUnit = (float) thermisterStep / (float) (resistRangeDelta);
    int unitOverlow = lowTempResist - sensorResist;
    float degreeAdj = (float) unitOverlow * degreesPerUnit;
    return (float) tempCnt + degreeAdj;
}

float avgReadTemp(AnalogIn adcpin, int numRead) {
  float sum = 0;
  int ndx; 
  for (ndx = 0; ndx < numRead; ndx++) {
    wait(0.005);
    sum += readTemp(adcpin);
  }
  return (float) ((float) sum / (float) ndx);
}