Code supports writing to the SD card as well as working with the Volckens group smartphone apps for the mbed HRM1017

Dependencies:   ADS1115 BLE_API BME280 Calibration CronoDot EEPROM LSM303 MCP40D17 NCP5623BMUTBG SDFileSystem SI1145 STC3100 mbed nRF51822

Fork of UPAS_BLE_and_USB by Volckens Group Sensors

main.cpp

Committer:
jelord
Date:
2016-03-05
Revision:
123:2765e75fd0a6
Parent:
122:f26474cc223a
Child:
124:15466d0f04ab

File content as of revision 123:2765e75fd0a6:

#include "mbed.h"
#include "SDFileSystem.h"
#include "Adafruit_ADS1015.h"
#include "MCP40D17.h"
#include "STC3100.h"
#include "LSM303.h"
#include "BME280.h"
#include "SI1145.h"
#include "NCP5623BMUTBG.h"
#include "CronoDot.h"
#include "EEPROM.h"
#include "BLEDevice.h"
#include "Calibration.h"
#include "UPAS_Service.h"

#define SERIAL_BAUD_RATE    9600
#define SCL         20
#define SDA         22





uint8_t startAndEndTime[12] = {0,};
uint8_t logIntervalReadOut[1] = {0,}; 
static const uint16_t uuid16_list[] = {UPAS_Service::UPAS_SERVICE_UUID}; //Currently a custom 16-bit representation of 128-bit UUID
BLEDevice   ble;
UPAS_Service *upasServicePtr;
//BLE_Menu    bleMenu(ble, txPayload, rxPayload, uart_base_uuid_rev, uart_base_uuid, uartService);

I2C                 i2c(p22, p20);
Adafruit_ADS1115    ads(&i2c);
MCP40D17            DigPot(&i2c);
BME280              bmesensor(p22, p20);
STC3100             gasG(p22, p20);
Serial              pc(USBTX, USBRX);
DigitalOut          blower(p29, 0);
DigitalOut          pbKill(p18, 1);
LSM303              movementsensor(p22, p20);
SI1145              lightsensor(p22, p20);
NCP5623BMUTBG       RGB_LED(p22, p20);
CronoDot            RTC(p22, p20);
EEPROM              E2PROM(p22, p20);
DigitalOut          GPS_EN(p4,0);       //pin 4 is used to enable and disable the GPS, in order to recive serial communications
Calibration         calibrations(1);     //Default serial/calibration if there are no values for the selected option

//Timeout         stop;   //This is the stop call back object
//Timeout         logg;   //This is the logging call back object



uint16_t serial_num = 1;                // Default serial/calibration number
int RunReady =0;


float press;
float temp;
float rh;

int uv;
int vis;
int ir;


float compass;
float accel_x;
float accel_y;
float accel_z;
float accel_comp;
float angle_x;
float angle_y;
float angle_z;
float mag_x;
float mag_y;
float mag_z;


int vInReading;
int vBlowerReading;
int omronDiff;
float omronVolt; //V
int omronReading;
float atmoRho; //g/L

float massflow; //g/min
float volflow; //L/min
float volflowSet = 1.0; //L/min
int   logInerval = 10; //seconds
double secondsD = 0;
double lastsecondD = 0;
float massflowSet;
float deltaVflow = 0.0;
float deltaMflow = 0.0;
float gainFlow;
float sampledVol; //L, total sampled volume

int digital_pot_setpoint; //min = 0x7F, max = 0x00
int digital_pot_set;
int digital_pot_change;
int digitalpotMax = 127;
int digitalpotMin = 5;

int dutyUp;
int dutyDown;

// variables are only place holders for the US_Menu //
int refreshtime;
float home_lat, home_lon, work_lat, work_lon;
//*************************************************//

//int refresh_Time = 10;   // refresh time in s, note calling read_GPS()(or similar) will still take how ever long it needs(hopefully < 1s)

char filename[] = "/sd/XXXX0000LOG000000000000---------------.txt";
SDFileSystem sd(SPIS_PSELMOSI, SPIS_PSELMISO, SPIS_PSELSCK, SPIS_PSELSS, "sd"); // I believe this matches Todd's pinout, let me know if this doesn't work. (p12, p13, p15, p14)


void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
{
    ble.startAdvertising();
}

void WrittenHandler(const GattCharacteristicWriteCBParams *Handler) // called any time the phone sends a message
{
   uint8_t *writeData =  const_cast<uint8_t*>(Handler->data);
    // check to see what characteristic was written, by handle
    if(Handler->charHandle == upasServicePtr->rtcCharacteristic.getValueAttribute().getHandle()) {


        
        //E2PROM.write(0x00015, writeData+6, 12); This line needs to be omitted for android app to function. Should not have stuck around 
        RTC.set_time(writeData[0],writeData[1],writeData[2],writeData[3],writeData[3],writeData[4],writeData[5]);
   
    }else if(Handler->charHandle == upasServicePtr->sampleTimeCharacteristic.getValueAttribute().getHandle()){
        
        E2PROM.write(0x00015, writeData, 12);
    
    }else if(Handler->charHandle == upasServicePtr->subjectLabelCharacteristic.getValueAttribute().getHandle()){
        E2PROM.write(0x00001,writeData,15);
    
    }else if(Handler->charHandle == upasServicePtr->runReadyCharacteristic.getValueAttribute().getHandle()){
        
        uint8_t runData = writeData[0];
        E2PROM.write(0x00033,writeData,1);
        
        if(runData == 0x0A){
            RunReady = 10;
        }else{
            RunReady = 12;
        }       
    
    }else if(Handler->charHandle == upasServicePtr->logIntevalCharacteristic.getValueAttribute().getHandle()){
        /* Trigger demo mode*/
        //RGB_LED.set_led(3,1,0);
        E2PROM.write(0x00014,writeData,1);
    
    }else if(Handler->charHandle == upasServicePtr->flowRateCharacteristic.getValueAttribute().getHandle()){
    //RGB_LED.set_led(3,1,0);
        E2PROM.write(0x00010,writeData,4);
    
        //float volFlowTester = 0.0;
        //uint8_t flowRateTestBytes[4] = {0,};
        //E2PROM.read(0x00010,flowRateTestBytes,4);
        //E2PROM.byteToFloat(flowRateTestBytes, &volFlowTester);
        
    }else if(Handler->charHandle == upasServicePtr->serialNumCharacteristic.getValueAttribute().getHandle()){
        E2PROM.write(0x00034,writeData,2);    
    }

}



/*EEPROM ADDRESSING:
    0:Status bit-Unused
    1-15:Device Name
    16-19:Flow Rate
    20: Data Log Interval
    21-26: Start Time: ssmmHHddMMyy
    27-32: Stop Time: ssmmHHddMMyy
    33: Duty Up
    34: Duty Down
    35-38: Home Latitude
    39-42: Home Longitude
    43-46: Work Latitude
    47-50: Work Longitude
    51: Runready: Currently useless, should be 0
    52-53: Device Calibration
    54: Consider RunReady
    55-56: Menu Options
    57+ Nothing*/
int main()
{
    RGB_LED.set_led(1,1,1);
// Setup and Initialization
//---------------------------------------------------------------------------------------------//
    //**************//BLE initialization//**************//
    RTC.get_time();
    uint8_t rtcPassValues[6] = {RTC.seconds, RTC.minutes,RTC.hour,RTC.date,RTC.month,RTC.year};
    
    uint8_t sampleTimePassValues[12] = {0x00,0x00,0x0A,0x01,0x01,0x10,0x00,0x00,0x0A,0x01,0x01,0x10}; //Start 1/1/16 12:00:00 End 1/1/16 12:00:00
    uint8_t subjectLabelOriginal[8] = {0x52,0x45,0x53,0x45,0x54,0x5F,0x5F,0x5f}; // RESET___
    uint8_t dataLogOriginal[1] = {0x0A,}; //10 seconds
    uint8_t flowRateOriginal[4] = {0x00,0x00,0x80,0x3F}; //1.0 LPM
    
    uint8_t serialNumberAndType[6] = {0x50,0x53};
   
    //Code/conditional set up to prevent bad values in the EEPROM.  Does not set serial number currently
    uint8_t eepromFlag[1] = {0,}; 
    E2PROM.read(0x00071,eepromFlag,1); 
    if(eepromFlag[0]!= 0x0B){  
        E2PROM.write(0x00015, sampleTimePassValues, 12);
        E2PROM.write(0x00001, subjectLabelOriginal,8);
        E2PROM.write(0x00014,dataLogOriginal,1);
        E2PROM.write(0x00010,flowRateOriginal,4);
        
        eepromFlag[0] = 0x0B;
        E2PROM.write(0x00071,eepromFlag,1);
    }
    
    
    //Retrieve current eeprom values
    E2PROM.read(0x00015, sampleTimePassValues, 12);
    E2PROM.read(0x00001, subjectLabelOriginal,8);
    E2PROM.read(0x00014,dataLogOriginal,1);
    E2PROM.read(0x00010,flowRateOriginal,4);
    
    
    //Following 12 lines of code parses the serial number from a byte id to a readable set of characters for the app user to see
    E2PROM.read(0x00034,serialNumberAndType+2,2);
    int tempSerialNum = serialNumberAndType[2]+serialNumberAndType[3];
    int serialNumDigits[4];
    serialNumDigits[0] = tempSerialNum / 1000 % 10;
    serialNumDigits[1] = tempSerialNum / 100 % 10;
    serialNumDigits[2] = tempSerialNum / 10 % 10;
    serialNumDigits[3] = tempSerialNum  % 10;
    
    serialNumberAndType[2] = serialNumDigits[0]+48;
    serialNumberAndType[3] = serialNumDigits[1]+48;
    serialNumberAndType[4] = serialNumDigits[2]+48;
    serialNumberAndType[5] = serialNumDigits[3]+48;
    
    uint8_t bleControlByte[1] = {0,};
    E2PROM.read(0x00072,bleControlByte,1);
    if(bleControlByte[0] == 0x01){
        bleControlByte[0] = 0x02; 
        ble.init();
        ble.onDisconnection(disconnectionCallback);
        ble.onDataWritten(WrittenHandler); //add writeCharCallback (custom function) to whenever data is being written to device
        UPAS_Service upasService(ble, false,rtcPassValues,sampleTimePassValues,subjectLabelOriginal,dataLogOriginal,flowRateOriginal); //Create a GattService that is defined in UPAS_Service.h
        upasServicePtr = &upasService; //Create a pointer to the service (Allows advertisement without specifically adding the service
    
        /* setup advertising 
        Following lines do the follow:
            1:Declare the device as Bluetooth Smart(Low-Energy)
            2.Advertise the UPAS service that will send and receive the 113+ bits of settable values in the UPAS EEPROM
            3.Advertise the name that will be associated with the UPAS
            4.Allow the UPAS to advertise unrestricted (this might change) */
            
        ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
        ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
        ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)serialNumberAndType, sizeof(serialNumberAndType));
        ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
        ble.setAdvertisingInterval(160); /* 160ms. */
        ble.startAdvertising();
    
        //**************//BLE initialization//**************//
       
       //Logic Loop waiting for responses from the BLE iPhone App.
       //Will not break loop without response from the app
        
        
        //Loop waits for response from app. When set to start, UPAS is turned off, but BLE is disabled once UPAS is turned on   
        while (1) {
            ble.waitForEvent();
             
            if(RunReady==10){ //Check to see if app is done with configurations         
               ble.stopAdvertising();
               E2PROM.write(0x00072,bleControlByte,1);
               NVIC_SystemReset();
               //pbKill = 0;
           }
           
        }
    }
    bleControlByte[0] = 0x01;
    E2PROM.write(0x00072,bleControlByte,1);
    
    E2PROM.read(0x00015, startAndEndTime, 12); //Grab start and end times from EEPROM
    RGB_LED.set_led(1,0,1);
    while(!RTC.compare(startAndEndTime[0], startAndEndTime[1], startAndEndTime[2], startAndEndTime[3], startAndEndTime[4], startAndEndTime[5])) {  // this while waits for the start time by looping until the start time
            wait(0.5);
            
            RTC.get_time(); 

    }
    
    
    RGB_LED.set_led(0,1,0);
    
    //Get the proper serial number
    E2PROM.read(0x00034, flowRateOriginal,2);    
    serial_num = ((uint16_t)flowRateOriginal[1] << 8) | flowRateOriginal[0];
    //----------------------------------------------
    calibrations.initialize(serial_num);
    pc.printf("%f\n",calibrations.MF4);
    //----------------------------------------------
    wait(1);
    blower=1;
    E2PROM.read(0x00014,logIntervalReadOut,1);
    logInerval = logIntervalReadOut[0];
     
    pc.printf("You're done, you can now disconect the USB cable.\r\n");
    RunReady = 0;


    //stop.attach(&check_stop, 30);    // check if we should shut down every 30 seconds, starting 60s after the start.

    //Use the flow rate value stored in eeprom
    E2PROM.read(0x00010,flowRateOriginal,4);
    E2PROM.byteToFloat(flowRateOriginal, &volflowSet);
    
    if(volflowSet<=1.0) {
        gainFlow = 100;
    } else if(volflowSet>=2.0) {
        gainFlow = 25;
    } else {
        gainFlow = 25;
    }

    RGB_LED.set_led(1,0,0);
    press = bmesensor.getPressure();
    temp = bmesensor.getTemperature();
    rh = bmesensor.getHumidity();

    atmoRho = ((press-((6.1078*pow((float)10,(float)((7.5*temp)/(237.3+temp))))*(rh/100)))*100)/(287.0531*(temp+273.15))+((6.1078*pow((float)10,(float)((7.5*temp)/(237.3+temp))))*(rh/100)*100)/(461.4964*(temp+273.15));
    massflowSet = volflowSet*atmoRho;
    //Digtal pot tf from file: UPAS v2 OSU-PrimaryFlowData FullSet 2015-05-29 CQ mods.xlsx


    digital_pot_setpoint = (int)floor(calibrations.DP4*pow(massflowSet,4)+calibrations.DP3*pow(massflowSet,3)+calibrations.DP2*pow(massflowSet,2)+calibrations.DP1*massflowSet+calibrations.DP0); //min = 0x7F, max = 0x00

    if(digital_pot_setpoint>=digitalpotMax) {
        digital_pot_setpoint = digitalpotMax;
    } else if(digital_pot_setpoint<=digitalpotMin) {
        digital_pot_setpoint = digitalpotMin;
    }

    DigPot.writeRegister(digital_pot_setpoint);
    wait(1);
    blower = 1;

    
    E2PROM.read(0x00001, subjectLabelOriginal,8);        
    //sprintf(filename, "/sd/%c%c%c%c%c%c%c%cLOG_%02d-%02d-%02d_%02d=%02d=%02d.txt",subjectLabelOriginal[0],subjectLabelOriginal[1],subjectLabelOriginal[2],subjectLabelOriginal[3],subjectLabelOriginal[4],subjectLabelOriginal[5],subjectLabelOriginal[6],subjectLabelOriginal[7],RTC.year,RTC.month,RTC.date,RTC.hour,RTC.minutes,RTC.seconds);
    sprintf(filename, "/sd/UPAS%04dLOG_%02d-%02d-%02d_%02d=%02d=%02d_%c%c%c%c%c%c%c%c.txt",serial_num,RTC.year,RTC.month,RTC.date,RTC.hour,RTC.minutes,RTC.seconds,subjectLabelOriginal[0],subjectLabelOriginal[1],subjectLabelOriginal[2],subjectLabelOriginal[3],subjectLabelOriginal[4],subjectLabelOriginal[5],subjectLabelOriginal[6],subjectLabelOriginal[7]);
    FILE *fp = fopen(filename, "w");
    fclose(fp);

    //---------------------------------------------------------------------------------------------//
    //Following lines are needed to enter into the initiallization flow control loop

    wait(10);

    omronReading = ads.readADC_SingleEnded(0, 0xC583); // read channel 0 PGA = 2 : Full Scale Range = 2.048V
    omronVolt = (omronReading*4.096)/(32768*2);
    if(omronVolt<=calibrations.omronVMin) {
        massflow = calibrations.omronMFMin;
    } else if(omronVolt>=calibrations.omronVMax) {
        massflow = calibrations.omronMFMax;
    } else {
        massflow = calibrations.MF4*pow(omronVolt,(float)4)+calibrations.MF3*pow(omronVolt,(float)3)+calibrations.MF2*pow(omronVolt,(float)2)+calibrations.MF1*omronVolt+calibrations.MF0;
    }
    deltaMflow = massflow-massflowSet;
    digital_pot_set = digital_pot_setpoint;
    wait(5);

    //---------------------------------------------------------------------------------------------//
    //Sets the flow withen +-1.5% of the desired flow rate based on mass flow

    while(abs(deltaMflow)>.015) {

        omronReading = ads.readADC_SingleEnded(0, 0xC583); // read channel 0 PGA = 2 : Full Scale Range = 2.048V
        omronVolt = (omronReading*4.096)/(32768*2);
        //Mass Flow tf from file: UPAS v2 OSU-PrimaryFlowData FullSet 2015-05-29 CQ mods.xlsx
        if(omronVolt<=calibrations.omronVMin) {
            massflow = calibrations.omronMFMin;
        } else if(omronVolt>=calibrations.omronVMax) {
            massflow = calibrations.omronMFMax;
        } else {
            massflow = calibrations.MF4*pow(omronVolt,(float)4)+calibrations.MF3*pow(omronVolt,(float)3)+calibrations.MF2*pow(omronVolt,(float)2)+calibrations.MF1*omronVolt+calibrations.MF0;
        }

        atmoRho = ((press-((6.1078*pow((float)10,(float)((7.5*temp)/(237.3+temp))))*(rh/100)))*100)/(287.0531*(temp+273.15))+((6.1078*pow((float)10,(float)((7.5*temp)/(237.3+temp))))*(rh/100)*100)/(461.4964*(temp+273.15));
        volflow = massflow/atmoRho;
        massflowSet = volflowSet*atmoRho;
        deltaMflow = massflow-massflowSet;

        digital_pot_set = (int)(digital_pot_set+(int)((gainFlow*deltaMflow)));
        if(digital_pot_set>=digitalpotMax) {
            digital_pot_set = digitalpotMax;
        } else if(digital_pot_set<=digitalpotMin) {
            digital_pot_set = digitalpotMin;
        }

        wait(2);
        DigPot.writeRegister(digital_pot_set);
        wait(1);


    }

    sampledVol = 0.0;
    RGB_LED.set_led(0,1,0);
    
  //  logg.attach(&log_data, logInerval); // uses callbacks or block Interrupts for anything that uses i2c


    while(1){
        if(RTC.compare(startAndEndTime[6], startAndEndTime[7], startAndEndTime[8], startAndEndTime[9], startAndEndTime[10], startAndEndTime[11])) 
            pbKill = 0; // this is were we shut everything down
            
        wait(logInerval);
//        if(r==0) r=1;
//        else r=0;
//        RGB_LED.set_led(r,g,b);
//        wait(0.5);
        
        RTC.get_time();
        
        secondsD = RTC.seconds;
    
        while(fmod(secondsD,logInerval)!=0 || floor(secondsD)==floor(lastsecondD)) {
           //pc.printf("%f, %f\r\n", floor(secondsD), floor(lastsecondD)); 
            RTC.get_time();
            secondsD = RTC.seconds;
            wait_ms(100);
        }
        lastsecondD = secondsD;
            
        omronReading = ads.readADC_SingleEnded(0, 0xC583); // read channel 0 PGA = 2 : Full Scale Range = 2.048V
        omronVolt = (omronReading*4.096)/(32768*2);
    
        if(omronVolt<=calibrations.omronVMin) {
            massflow = calibrations.omronMFMin;
        } else if(omronVolt>=calibrations.omronVMax) {
            massflow = calibrations.omronMFMax;
        } else {
            massflow = calibrations.MF4*pow(omronVolt,(float)4)+calibrations.MF3*pow(omronVolt,(float)3)+calibrations.MF2*pow(omronVolt,(float)2)+calibrations.MF1*omronVolt+calibrations.MF0;
        }
    
        atmoRho = ((press-((6.1078*pow((float)10,(float)((7.5*temp)/(237.3+temp))))*(rh/100)))*100)/(287.0531*(temp+273.15))+((6.1078*pow((float)10,(float)((7.5*temp)/(237.3+temp))))*(rh/100)*100)/(461.4964*(temp+273.15));
        volflow = massflow/atmoRho;
        sampledVol = sampledVol + ((((float)logInerval)/60.0)*volflow);
        deltaVflow = volflow-volflowSet;
        massflowSet = volflowSet*atmoRho;
        deltaMflow = massflow-massflowSet;
        if(abs(deltaMflow)>.025) {
            digital_pot_change = (int)(gainFlow*deltaMflow);
    
    
            if(abs(digital_pot_change)>=50) {
                digital_pot_set = (int)(digital_pot_set+(int)((10.0*deltaMflow)));
                RGB_LED.set_led(1,0,0);
            }   else {
                digital_pot_set = (digital_pot_set+ digital_pot_change);
                RGB_LED.set_led(1,1,0);
            }
            
                    if(digital_pot_set>=digitalpotMax) {
                        digital_pot_set = digitalpotMax;
                        RGB_LED.set_led(1,0,0);
                    } else if(digital_pot_set<=digitalpotMin) {
                        digital_pot_set = digitalpotMin;
                        RGB_LED.set_led(1,0,0);
                    }
    
    
            DigPot.writeRegister(digital_pot_set);
    
        } else {
            RGB_LED.set_led(0,1,0);
        }
        
        
        movementsensor.getACCEL();
        movementsensor.getCOMPASS();
        compass = movementsensor.getCOMPASS_HEADING();
        accel_x = movementsensor.AccelData.x;
        accel_y = movementsensor.AccelData.y;
        accel_z = movementsensor.AccelData.z;
        accel_comp = pow(accel_x,(float)2)+pow(accel_y,(float)2)+pow(accel_z,(float)2)-1.0;
        mag_x = movementsensor.MagData.x;
        mag_y = movementsensor.MagData.y;
        mag_z = movementsensor.MagData.z;
        
        vInReading = ads.readADC_SingleEnded(1, 0xD583); // read channel 0
        vBlowerReading = ads.readADC_SingleEnded(2, 0xE783); // read channel 0
        omronDiff = ads.readADC_Differential(0x8583); // differential channel 2-3
        press = bmesensor.getPressure();
        temp = bmesensor.getTemperature()-5.0;
        rh = bmesensor.getHumidity();
        uv =  lightsensor.getUV();
        vis = lightsensor.getVIS();
        ir = lightsensor.getIR();
       
        
        FILE *fp = fopen(filename, "a");
        fprintf(fp, "%02d,%02d,%02d,%02d,%02d,%02d,",RTC.year, RTC.month,RTC.date,RTC.hour,RTC.minutes,RTC.seconds);
        fprintf(fp, "%1.3f,%1.3f,%2.2f,%4.2f,%2.1f,%1.3f,", omronVolt,massflow,temp,press,rh,atmoRho);
        fprintf(fp, "%1.3f,%5.1f,%1.1f,%1.1f,%1.1f,%1.1f,", volflow, sampledVol, accel_x, accel_y, accel_z, accel_comp);
        fprintf(fp, "%.1f,%.1f,%.1f,%.3f,%.3f,%.3f,%.1f,", angle_x,angle_y,angle_z,mag_x, mag_y, mag_z,compass);
        fprintf(fp, "%d,%d,%d,%d,%d,%d," ,uv,omronReading, vInReading, vBlowerReading, omronDiff,gasG.getAmps());
        fprintf(fp, "%d,%d,%d,%1.3f,%1.3f\r\n", gasG.getVolts(), gasG.getCharge(),digital_pot_set, deltaMflow, deltaVflow);
        fclose(fp);
        //free(fp);
        
    }
    


}