     }
     peakValue = sqrt(value);
     return VTOA * sqrt(sumSquares / (double)samples);
+}
+
+void calcAverage(double value)
+{
+    MeasurementCounter++;
+    if(!enoughMeasurements && MeasurementCounter >= NUMMEASURE)
+    {
+        enoughMeasurements = true;
+    }
+    if(enoughMeasurements)
+    {
+        twoMinuteSum -= twoMinuteMeasurements[MeasurementCounter%NUMMEASURE];
+    }
+    twoMinuteSum += value;
+    twoMinuteAverage = twoMinuteSum / NUMMEASURE;
+    twoMinuteMeasurements[MeasurementCounter%NUMMEASURE] = value;
+}
+
+void updateStatemachine()
+{
+    switch(globalState)
+    {
+        case 0:
+            if( twoMinuteAverage > 1 )
+            {
+                globalState = 1;
+            }
+            break;
+        case 1:
+            if( twoMinuteAverage > 10 )
+            {
+                globalState = 2;
+            }
+            break;
+        case 2:
+            if( twoMinuteAverage > 2000 )
+            {
+                globalState = 3;
+            }
+            break;
+        case 3:
+            if( twoMinuteAverage < 1000 )
+            {
+                globalState = 4;
+            }
+            break;
+        case 4:
+            if( twoMinuteAverage > 1000 )
+            {
+                globalState = 5;
+            }
+            break;
+        case 5:
+            if( twoMinuteAverage < 10 )
+            {
+                globalState = 6;
+            }
+            break;
+        case 6:
+            if( twoMinuteAverage < 1 )
+            {
+                globalState = 0;
+            }
+            break;
+    }
 }
 
 void msOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {

#define OFFSET 8820
#define SCALE (1.65/OFFSET)
#define VTOA (22.0/1.65)

double Volts(int digits)
{

    if( (millis() - rmsLastUpdate) > rmsInterval )
    {
        rmsValue = Irms(1);
        if(!calibrated)
        {
            calibrationOffset = rmsValue;
            calibrated = true;
        }
        double measurement = (rmsValue - calibrationOffset) * TENTHOUSAND ;
        calcAverage(measurement);
        Serial.printf("%d Irms: ", millis());
        Serial.print(rmsValue);
        Serial.println("");
