Own fork of MbedSmartRestMain

Dependencies:   C027_Support C12832 LM75B MMA7660 MbedSmartRest mbed-rtos mbed

Fork of MbedSmartRestMain by Cumulocity Official

measurement/Potentiometer.cpp

Committer:
xinlei
Date:
2016-08-08
Revision:
138:f8ab852e83e7
Parent:
136:a52821cdb108

File content as of revision 138:f8ab852e83e7:

#include <stdio.h>
#include "rtos.h"
#include "Potentiometer.h"
#include "SmartRestConf.h"
#include "logging.h"

// Cutoff for avoiding sending similar sensor data.
#define THRESHOLD_PERCENT_ANA 0.02
// Timeout for forcing a sending even if  readings are similar [seconds]
#define TIME_LIMIT_ANA 900

AnalogIn analog1(A0);
AnalogIn analog2(A1);

static inline bool valueChanged(float *V0, float *V1)
{
        if (abs(V0[0]-V1[0]) <= abs(V0[0])*THRESHOLD_PERCENT_ANA &&
            abs(V0[1]-V1[1]) <= abs(V0[1])*THRESHOLD_PERCENT_ANA)
                return false;
        else
                return true;
}

int Potentiometer::read(char *buf, size_t maxLen, char *status, size_t num)
{
        static const char *fmt = "107,%ld,%f,%f\r\n";
        float data[2] = {0, 0};
        float min[2] = {100, 100};
        float max[2] = {0, 0};
        // multiple sampling for data smoothing
        const unsigned short N = 20;
        for (unsigned short i = 0; i < N; ++i) {
                float d0 = (float)analog1*100;
                float d1 = (float)analog2*100;
                data[0] += d0;
                data[1] += d1;
                min[0] = min[0] <= d0 ? min[0] : d0;
                min[1] = min[1] <= d1 ? min[1] : d1;
                max[0] = max[0] >= d0 ? max[0] : d0;
                max[1] = max[1] >= d1 ? max[1] : d1;
                Thread::wait(10);
        }
        data[0] = (data[0]-min[0]-max[0]) / (N-2);
        data[1] = (data[1]-min[1]-max[1]) / (N-2);

        float t_interval = timer.read();
        if (!valueChanged(oldValues, data) && t_interval < TIME_LIMIT_ANA) {
                return 0;
        }

        size_t l = snprintf(buf, maxLen, fmt, deviceID, data[0], data[1]);
        if (status) {
                snprintf(status, num, "Send Poti %.1f,%.1f", data[0], data[1]);
        }
        oldValues[0] = data[0];
        oldValues[1] = data[1];
        timer.reset();
        return l;
}