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

Revision:
0:d252aa8196fc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SmoothAnalogIn.cpp	Fri Jun 18 13:54:29 2010 +0000
@@ -0,0 +1,45 @@
+// SmoothAnalogIn.cpp: Martyn Stopps / Taneli Holtta : 18-06-10
+
+// Source file: contains implementation that generates the code (the definition)
+
+#include "SmoothAnalogIn.h"
+#include "mbed.h"                                                  // tested with revision 23
+
+// Constructor - A class that takes arguments PinName, adc sample rate, smoothing factor and scaling factor
+
+SmoothAnalogIn::SmoothAnalogIn(PinName pin, float sampleRate, int smoothingFactor, int adcScaling) : _adc(pin)  {   // _adc(pin) means pass pin to the AnalogIn constructor 
+        
+    _ticker.attach(this, &SmoothAnalogIn::sampleAdc, sampleRate);  // attach ticker to member function (delivers adc sampleRate)
+    
+// initialize variables
+    
+    _smoothingFactor = smoothingFactor;                            // mask in the smoothing factor value
+    _adcScaling = adcScaling;                                      // mask in the adc scaling factor (adc returns 0 to 1 representing 0  to 3.3V)
+
+                                                                                                                }
+        
+
+// function - sampleAdc   : gets current adc value.
+
+void SmoothAnalogIn::sampleAdc(void)    {
+
+    double adc_value = _adc.read()*_adcScaling;     // read _adc pin analog value * _adcScaling 
+    SmoothAnalogIn::smoothValue(adc_value);         // call smoothing function passing in current scaled adc_value
+                                        }
+
+                                             
+// function - smoothValue : Smoothing algorithm
+      
+void SmoothAnalogIn::smoothValue(double newValue)   {
+                   
+    if (newValue > smoothed)  smoothed = smoothed + ((newValue - smoothed)/_smoothingFactor);      // rawValue > smoothed value
+    else if (newValue < smoothed) smoothed = smoothed - ((smoothed - newValue)/_smoothingFactor);  // rawValue < smoothed value
+                                                    }
+                                                    
+                                                    
+ // function - read   : returns smoothed adc value      
+        
+double SmoothAnalogIn::read(void)   {
+    
+    return(smoothed);                               
+                                    }