The SmoothAnalogIn class provides a smoothed ADC reading; simply setup pin, sample rate, smoothing factor and scaling factor. Useful for processing signals from temperature or pressure sensors etc.

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SmoothAnalogIn.cpp Source File

SmoothAnalogIn.cpp

00001 // SmoothAnalogIn.cpp: Martyn Stopps / Taneli Holtta : 18-06-10
00002 
00003 // Source file: contains implementation that generates the code (the definition)
00004 
00005 #include "SmoothAnalogIn.h"
00006 #include "mbed.h"                                                  // tested with revision 23
00007 
00008 // Constructor - A class that takes arguments PinName, adc sample rate, smoothing factor and scaling factor
00009 
00010 SmoothAnalogIn::SmoothAnalogIn(PinName pin, float sampleRate, int smoothingFactor, int adcScaling) : _adc(pin)  {   // _adc(pin) means pass pin to the AnalogIn constructor 
00011         
00012     _ticker.attach(this, &SmoothAnalogIn::sampleAdc, sampleRate);  // attach ticker to member function (delivers adc sampleRate)
00013     
00014 // initialize variables
00015     
00016     _smoothingFactor = smoothingFactor;                            // mask in the smoothing factor value
00017     _adcScaling = adcScaling;                                      // mask in the adc scaling factor (adc returns 0 to 1 representing 0  to 3.3V)
00018 
00019                                                                                                                 }
00020         
00021 
00022 // function - sampleAdc   : gets current adc value.
00023 
00024 void SmoothAnalogIn::sampleAdc(void)    {
00025 
00026     double adc_value = _adc.read()*_adcScaling;     // read _adc pin analog value * _adcScaling 
00027     SmoothAnalogIn::smoothValue(adc_value);         // call smoothing function passing in current scaled adc_value
00028                                         }
00029 
00030                                              
00031 // function - smoothValue : Smoothing algorithm
00032       
00033 void SmoothAnalogIn::smoothValue(double newValue)   {
00034                    
00035     if (newValue > smoothed)  smoothed = smoothed + ((newValue - smoothed)/_smoothingFactor);      // rawValue > smoothed value
00036     else if (newValue < smoothed) smoothed = smoothed - ((smoothed - newValue)/_smoothingFactor);  // rawValue < smoothed value
00037                                                     }
00038                                                     
00039                                                     
00040  // function - read   : returns smoothed adc value      
00041         
00042 double SmoothAnalogIn::read(void)   {
00043     
00044     return(smoothed);                               
00045                                     }