EZR

Dependencies:   CRC16 FreescaleIAP FreescaleWatchdog GGSProtocol LM75B PIMA Parameters PersistentCircularQueue SerialNumberV2COM mbed-dev-watchdog_2016_03_04

Fork of smartRamalKW by Equipe Firmware V2COM

sensor.cpp

Committer:
tpadovani
Date:
2015-07-02
Revision:
8:e8d86c66283c
Parent:
7:fe8e827f4d1b
Child:
9:e501499af4ef

File content as of revision 8:e8d86c66283c:

#include "sensor.h"

extern AnalogIn voltage[];
extern ParametersBlock APP_PARAMETERS;

Ticker tickerSamples;
Timeout samplesTimeout;
unsigned char currentChannel;
float sample[DEFAULT_SAMPLES];
int currentSample;
bool finished;
bool timeout;

float getTensaoInstantanea(unsigned char channel){
    currentChannel = channel;
    currentSample = 0;
    finished = false;
    timeout = false;
    tickerSamples.attach_us(&readSample, APP_PARAMETERS.SAMPLES_DELAY_US);
    samplesTimeout.attach_us(&timeoutReadingSamples, (DEFAULT_SAMPLES + 2) * APP_PARAMETERS.SAMPLES_DELAY_US);
    
    while(!finished && !timeout){
        wait(0.1f);
    }
    
    return calculateRMS();
}

bool getEstadoSensor(unsigned char channel){
    if(getTensaoInstantanea(channel) > APP_PARAMETERS.LIMITE_TENSAO_SENSOR_V){
        return SENSOR_COM_FORNECIMENTO;
    } else{
        return SENSOR_SEM_FORNECIMENTO;
    }
}

void readSample(){
    sample[currentSample++] = voltage[currentChannel];
    if(currentSample == DEFAULT_SAMPLES){
        finished = true;
        samplesTimeout.detach();
        tickerSamples.detach();
    }
}

void timeoutReadingSamples(){
    tickerSamples.detach();
    timeout = true;
}

float calculateRMS(){
    float rms = 0;
    for(int i=0; i < DEFAULT_SAMPLES; i++){
        sample[i] = sample[i]*APP_PARAMETERS.SAMPLES_ANG_COEF + APP_PARAMETERS.SAMPLES_LIN_COEF;
        rms += sample[i]*sample[i];
    }
    rms = rms / (float)DEFAULT_SAMPLES;
    return sqrt(rms);
}