fuck this

Dependencies:   BMP280

Sampling.cpp

Committer:
Swaggie
Date:
2018-01-04
Revision:
7:bf9f92ff02e8
Parent:
6:8e1795a5886b
Child:
8:dbb57b4d5ba4

File content as of revision 7:bf9f92ff02e8:

#include "Sampling.h"
#include "mbed.h"

//Thread Sync Tools
Mutex tempReadingsLock;
Mutex presReadingsLock;
Mutex LDRReadingsLock;
Mutex timeReadingsLock;

//Buffers
float tempReadings[BUFFERSIZE];
float presReadings[BUFFERSIZE];
float LDRReadings[BUFFERSIZE];
float timeReadings[BUFFERSIZE];

//Index
unsigned short newestIndex = BUFFERSIZE-1;
unsigned short oldestIndex = BUFFERSIZE-1;

bool firstSample = true;

//Hardware
#ifdef BME
BME280 sensor(D14, D15);
#else
BMP280 sensor(D14, D15);
#endif
AnalogIn LDRSensor(PA_1); //Check this is the correct pin

void SampleTimerISR(void)
{
    //Flag Threads
    t1.signal_set(1);
    t2.signal_set(1);
}

void ConfigThreadsAndIR(void)
{
    NewEnvSample = false;  //Reset
    NewLDRSample = false;  //Reset

    t1.start(ThreadSampleEnvSensor);
    t2.start(ThreadSampleLDR);

    sampleRate.attach(SampleTimerISR, 15); //15 second interval
}

void AddTempSample(float temp)
{
    tempReadingsLock.lock(); //Take the key
    tempReadings[newestIndex+1] = temp; //Add the sample after the most recent
    tempReadingsLock.unlock(); // Release the key
}

void AddPresSample(float pres)
{
    presReadingsLock.lock();    //Take the key
    presReadings[newestIndex+1] = pres; //Add to register
    presReadingsLock.unclock(); //Release the key
}

void ThreadSampleEnvSensor(void)
{
    while (true) {
        Thread::signal_wait(1); //Wait for signal 1
        //Get readings
        float temp = sensor.getTemperature();
        float pres = sensor.getPressure();
        AddPresSample(pres);    //Add value to register
        AddTempSample(temp);    //Add value to register
        NewEnvSample = true;    //Signal to main thread
    }
}

void AddLDRSample(float LDRval)
{
    LDRReadingsLock.lock(); //Take the key
    LDRReadings[newestIndex+1] = LDR; //Add the sample after the most recent
    LDRReadingsLock.unlock(); // Release the key
}

void ThreadSampleLDR(void)
{
    while (true) {
        Thread::signal_wait(1); //Wait for signal 1
        //get readings
        float LDRval = LDRSensor.value(); //Read the analogue pin value
        //get time function
        AddLDRSample(LDRval);
        //add time sample
        NewLDRSample = true;    //signal to main thread
    }
}

void IncrementIndex(void)
{
    newestIndex++; //Move the index forward one
    if (newestIndex == oldestIndex) {
        //If this is true then the memory is full and has looped back around and overwritten the oldest sample
        //Therefore, we need to move the oldest index pointer
        if (firstSample)
        {
            //this prevents the initial error
            oldestIndex++;
            firstSample = false;
        }
    }
}