by jamie allen

Standard deviation and variance (one is the square root of the other) are basic measurements of the 'spread' of data. For time series data we can think of it as a measure of the noisiness of the data, or as a 'very' robust way of detecting transient (fast changing) behaviors in noisier or drifting data.

This is a batch-analysis of the data, so 5 samples are needed before we have a standard deviation result. Coding a running-standard deviation would be a good thing to have... :)

#include <math.h>  //required for our sqrt function!

int potPin = 0;    // select the input pin for the potentiometer
int ledPin = 13;   // select the pin for the LED

int accVal = 0;    // accumulation of a sum for averaging
int currentAVG = 0; //current average
int lastVal = 0;  //storage for the 'last' analog input value 
int avg = 0;    // average result
int val[5];       // variable to store the value coming from the sensor
int howManyToAverage = 5;  //number of individual values to average
int sampleDeviation = 0;  //an individual samples' 'deviation'
int sampleDeviation2[5];  //each individual samples' squared (deviation)
int sampleDeviationSum = 0;  //each individual samples' squared (deviation)
int standardDeviation = 0; //the standard deviation result

void setup() {
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
  Serial.begin(9600);	// opens serial port, sets data rate to 9600 bps

void loop() {
  int i;

 digitalWrite(ledPin, HIGH);    // sets the LED off

  accVal = 0;  // clear the accumulator

  for (i=0; i < howManyToAverage; i++)
    val[i] = analogRead(potPin);    // read the value from the sensor

    //Serial.print("Raw Value: ");
    //Serial.println(val, DEC);  // print as an ASCII-encoded decimal

    accVal = accVal + val[i];
    //Serial.print("Accumulator: ");
    //Serial.println(accVal, DEC);  // print as an ASCII-encoded decimal

  avg = accVal/howManyToAverage;
  //Serial.print("Simple Average Value: ");
  //Serial.println(avg, DEC);  // print as an ASCII-encoded decimal

  for (i=0; i<howManyToAverage; i++)
    sampleDeviation = abs(val[i]-avg);
    sampleDeviation2[i] = sampleDeviation*sampleDeviation;        

  sampleDeviationSum = 0;  
  for (i=0; i<howManyToAverage; i++)
    sampleDeviationSum = sampleDeviationSum + sampleDeviation2[i]; 

  standardDeviation = sqrt(sampleDeviationSum/(howManyToAverage-1));

  Serial.print("Standard Deviation Value: ");
  Serial.println(standardDeviation, DEC);  // print as an ASCII-encoded decimal