Clone of the Quicksand QW Sensors library
Fork of QW_Sensors by
LinearTempSensor.cpp
- Committer:
- quicksand
- Date:
- 2015-12-02
- Revision:
- 0:4b56d28cc7e9
File content as of revision 0:4b56d28cc7e9:
/* mbed Linear Temperature Sensor library
* Supports Microchip MCP9700/9701, National Semiconductor LM35
*
* Written by Todotani, Nov 22 2010
*/
#include "LinearTempSensor.h"
LinearTempSensor::LinearTempSensor(PinName ain, int N, SensorType type):
// Initialize private variables using Initialization Lists
// _ain(ain) is equivalent to _ain = new AnalogIn(ain)
// _sample(N) is equivalent to _sample = N
_ain(ain), _samples(N), _type(type) {
sampleBuffer = (float *)malloc(sizeof(float) * _samples);
sampleCount = 0;
index = 0;
Vref = 3300;
bufferNotFilled = true;
// Set constants to calculate temperature from sensor value
switch (_type) {
case LM35:
V0 = 0.0f;
Tc = 10.0f;
break;
case MCP9701:
V0 = 400.0f;
Tc = 19.5f;
break;
case MCP9700:
default:
V0 = 500.0f;
Tc = 10.0f;
}
for (int i = 0; i < _samples; i++)
sampleBuffer[i] = 0.0f;
}
LinearTempSensor::~LinearTempSensor() {
free(sampleBuffer);
}
float LinearTempSensor::Sense() {
float val;
val = _ain * Vref;
sampleBuffer[index] = val;
//printf("Index:%d ", index); // Debug print
if ( ++index >= _samples )
index = 0;
if ( bufferNotFilled && (sampleCount == _samples) ) {
bufferNotFilled = false;
}
//printf("flag:%d ", bufferNotFilled); // Debug print
sampleCount++;
return val;
}
float LinearTempSensor::GetAverageTemp() {
float sum = 0;
int i, numberOfsumples;
if (sampleCount == 0)
return 0;
if (bufferNotFilled) {
// In case number of samples less than buffer lenght
for (i = 0; i < sampleCount; i++) {
sum += sampleBuffer[i];
}
numberOfsumples = sampleCount;
} else {
// In case buffer is filled
for (i = 0; i < _samples; i++) {
sum += sampleBuffer[i];
}
numberOfsumples = _samples;
}
return ((sum / numberOfsumples) - V0) / Tc; // Temp = (Vout - V0) / Tc
}
float LinearTempSensor::GetLatestTemp() {
return (sampleBuffer[(sampleCount-1)%_samples] - V0) / Tc;
}
Lieven Hollevoet
