A simple class to buffer data and compute some statistics on that data.

Dependents:   WattEye

StatisticQueue.cpp

Committer:
WiredHome
Date:
2014-07-26
Revision:
0:8c041d5d34b2

File content as of revision 0:8c041d5d34b2:


#include "StatisticQueue.h"

StatisticQueue::StatisticQueue(int numEntries)
{
    items = (float *)malloc(numEntries * sizeof(float));
    if (items) {
        queueSize = numEntries;
        Clear();
    } else {
        // crash and burn
        printf("Can't get memory\r\n");
        queueSize = -1;
    }
}

StatisticQueue::~StatisticQueue()
{
    if (items)
        free(items);
}
    
void StatisticQueue::Clear(void)
{
    for (int i=0; i<queueSize; i++) {
        items[i] = 0.0f;
    }
    currentCount = 0;
    nextIndex = 0;
}

void StatisticQueue::EnterItem(float value)
{
    __disable_irq();
    items[nextIndex++] = value;
    if (nextIndex >= queueSize)
        nextIndex = 0;
    currentCount++;
    if (currentCount > queueSize)
        currentCount = queueSize;
    __enable_irq();
}

float StatisticQueue::Average(void)
{
    float result = 0.0f;
    for (int i=0; i<currentCount; i++) {
        result += items[i];
    }
    if (currentCount)
        result /= currentCount;
    return result;
}

float StatisticQueue::Max(void)
{
    float result = items[0];
    for (int i=1; i<currentCount; i++) {
        if (items[i] > result) {
            result = items[i];
        }
    }
    return result;
}

float StatisticQueue::Min(void)
{
    float result = items[0];
    for (int i=1; i<currentCount; i++) {
        if (items[i] < result) {
            result = items[i];
        }
    }
    return result;
}

float StatisticQueue::StdDev(void)
{
    float summing = 0.0f;
    float avg = Average();
    for (int i=0; i<currentCount; i++) {
        float temp = (items[i] - avg);
        summing += (temp * temp);
    }
    summing /= currentCount;
    return sqrt(summing);
}