Dependencies:   EthernetInterface ThingCloud mbed-rtos mbed

main.cpp

Committer:
gert_lauritsen
Date:
2017-06-09
Revision:
2:88dce59f9a99
Parent:
1:77bd7a299174

File content as of revision 2:88dce59f9a99:

#include "mbed.h"
#include "EthernetInterface.h"
#include "thingspeak.h"
#include "Config.h"

#define samplingTime 280
//#define apikey "EBQZGHVA0T7U04MZ"
#define apikey "SOMJ5VHIL690SNC8" //single sensor
#define readapikey "73DW768IEIMGF66B" //single sensor

#define apiID 133611
#define off 1
#define on 0
#define OldSensor 1
#define N 100

EthernetInterface eth;
char* thingSpeakKey = apikey;
char* thingSpeakReadKey = readapikey;

THINGSPEAK Channel;

Serial pc(USBTX, USBRX);     // serial comms over usb back to console
Serial nova(p13, p14);
char inbuff[25];
char pInbuff;

float PM10;
float PM25;
uint16_t pm10, pm25;
int stack;

float approxRollingAverage (float avg, float new_sample)
{
    avg -= avg / N;
    avg += new_sample / N;
    return avg;
}

void LogData()
{
    Channel.AddFloat(PM10/stack);
    Channel.AddFloat(PM25/stack);
  //  Channel.AddFloat(0);
  //  Channel.AddFloat(0);
    Channel.AddPosition(latitude[stationID],longitude[stationID]);
    stack=0;
    PM10=0;
    PM25=0;
    if (Channel.SendData(thingSpeakKey)) pc.printf("Upload Error                     \r");
    else pc.printf("Upload OK                    \r");
    //Channel.ReadData(thingSpeakReadKey,apiID);
}

int ReadNova()
{
    int res=0;
    uint16_t old_pm10, old_pm25;
    if (nova.readable()) {
        inbuff[pInbuff]=nova.getc();
        if (inbuff[pInbuff]==0xAA) {
            pInbuff=-1;
        }
        if (inbuff[pInbuff]==0xAB) {
            if (old_pm10!=0) old_pm10=pm10;
            else old_pm10=5000;
            if (old_pm25!=0) old_pm25=pm25;
            else old_pm25=5000;
            
            pm25=(inbuff[2]<<8)+inbuff[1];
            pm10=(inbuff[4]<<8)+inbuff[3];
            if ((pm25<(2*old_pm25)) && (pm10<(2*old_pm10))) { //Spike fra sortering
                PM10+=pm10/10.0;
                PM25+=pm25/10.0;
                stack++;
                pc.printf("PM10=%.1f PM2.5=%.1f Stack=%d       \r",pm10/10.0,pm25/10.0,stack);
                res=1;
            }
            pInbuff=-1;
        }
        pInbuff++;
    }
    return res;
}

DigitalOut myled(LED1);

int main()
{
    pInbuff=0;
    stack=0;
    pc.printf("\n\r---------------------------------------------------------------\n\r");
    eth.init(); //Use DHCP
    eth.connect();
    pc.printf("IP Address is %s\n\r", eth.getIPAddress());
    while (true) {
        ReadNova();
        if (stack>=60) {
            LogData();
        }
    }
}