Sample program to get ambient temperature from MCP9700 sensor
Fork of TempSensor by
LinearTempSensor/LinearTempSensor.cpp
- Committer:
- d0773d
- Date:
- 2013-06-17
- Revision:
- 1:6a589f1dd263
- Parent:
- 0:6dde232b3b3b
File content as of revision 1:6a589f1dd263:
/* 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; }