init

Dependencies:   aconno_I2C Lis2dh12 WatchdogTimer

Files at this revision

API Documentation at this revision

Comitter:
pathfindr
Date:
Thu Feb 13 00:57:06 2020 +0000
Parent:
56:efd9f5613549
Child:
58:8d4a354816b1
Commit message:
init

Changed in this revision

LED.cpp Show annotated file Show diff for this revision Revisions of this file
LED.h Show annotated file Show diff for this revision Revisions of this file
LIS3DH.h Show diff for this revision Revisions of this file
LISD3H.cpp Show diff for this revision Revisions of this file
SI7060.cpp Show diff for this revision Revisions of this file
SI7060.h Show diff for this revision Revisions of this file
board.h Show annotated file Show diff for this revision Revisions of this file
common.cpp Show diff for this revision Revisions of this file
common.h Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
main.h Show annotated file Show diff for this revision Revisions of this file
mbed_app.json Show annotated file Show diff for this revision Revisions of this file
modem.cpp Show diff for this revision Revisions of this file
modem.h Show diff for this revision Revisions of this file
sensors.cpp Show diff for this revision Revisions of this file
sensors.h Show diff for this revision Revisions of this file
states.h Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LED.cpp	Thu Feb 13 00:57:06 2020 +0000
@@ -0,0 +1,45 @@
+#include "LED.h"
+
+//------------------------------------------------------------------------------
+// LED
+//------------------------------------------------------------------------------ 
+DigitalOut led1(PN_LED);
+
+void LED1on(long milliseconds = 0) {
+    led1 = 0;
+    if (milliseconds > 0) {
+        ThisThread::sleep_for(milliseconds);
+        //Thread::wait(milliseconds);
+        led1 = 1;
+    }
+}
+void LED1blink(int count = 2, long milliseconds = 100) {
+    for (int i = 0; i < (count*2); i++) {
+        led1 = !led1;
+        if (milliseconds > 0) {
+            //Thread::wait(milliseconds);
+            ThisThread::sleep_for(milliseconds);
+        } else { 
+            //Thread::wait(100);
+            ThisThread::sleep_for(100); //default if 0 provided
+        }
+    }
+    led1 = 1;
+}
+void LED1errorCode(int pattern, int count) {
+    for (int i = 0; i < count; i++) {
+        for (int p = 0; p < pattern; p++) {
+            led1 = 0;
+            //Thread::wait(200);
+            ThisThread::sleep_for(200);
+            led1 = 1;
+            //Thread::wait(300);
+            ThisThread::sleep_for(300);
+        }
+        ThisThread::sleep_for(1000);
+    }
+    led1 = 1;
+}
+void LED1off() {
+    led1 = 1;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LED.h	Thu Feb 13 00:57:06 2020 +0000
@@ -0,0 +1,13 @@
+#ifndef COMMON_H_
+#define COMMON_H_
+
+#include "main.h"
+
+extern DigitalOut led1;
+extern void LED1on(long milliseconds);
+extern void LED1blink(int count, long milliseconds);
+extern void LED1blinkRTC(int count);
+extern void LED1errorCode(int pattern, int count);
+extern void LED1off(void);
+
+#endif
\ No newline at end of file
--- a/LIS3DH.h	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,527 +0,0 @@
-#ifndef LIS3DH_H
-#define LIS3DH_H
-
-#include "mbed.h"
-
-namespace mbed {
-
-#ifndef __ARCHDEP__TYPES
-#define __ARCHDEP__TYPES
-
-typedef unsigned char u8_t;
-typedef unsigned short int u16_t;
-typedef short int i16_t;
-typedef signed char i8_t;
-
-#endif /*__ARCHDEP__TYPES*/
-
-typedef u8_t LIS3DH_IntPinConf_t;
-typedef u8_t LIS3DH_Axis_t;
-typedef u8_t LIS3DH_Int1Conf_t;
-
-
-//define structure
-#ifndef __SHARED__TYPES
-#define __SHARED__TYPES
-
-typedef enum {
-  MEMS_SUCCESS              =       0x01,
-  MEMS_ERROR                =       0x00    
-} status_t;
-
-typedef enum {
-  MEMS_ENABLE               =       0x01,
-  MEMS_DISABLE              =       0x00    
-} State_t;
-
-typedef __packed struct {
-  i16_t AXIS_X;
-  i16_t AXIS_Y;
-  i16_t AXIS_Z;
-} AxesRaw_t;
-
-#endif /*__SHARED__TYPES*/
-
-typedef enum {  
-  LIS3DH_ODR_1Hz                =       0x01,       
-  LIS3DH_ODR_10Hz                      =        0x02,
-  LIS3DH_ODR_25Hz               =       0x03,
-  LIS3DH_ODR_50Hz               =       0x04,
-  LIS3DH_ODR_100Hz              =       0x05,   
-  LIS3DH_ODR_200Hz              =       0x06,
-  LIS3DH_ODR_400Hz              =       0x07,
-  LIS3DH_ODR_1620Hz_LP              =       0x08,
-  LIS3DH_ODR_1344Hz_NP_5367HZ_LP       =        0x09    
-} LIS3DH_ODR_t;
-
-typedef enum {
-  LIS3DH_POWER_DOWN                    =        0x00,
-  LIS3DH_LOW_POWER          =       0x01,
-  LIS3DH_NORMAL         =       0x02
-} LIS3DH_Mode_t;
-
-typedef enum {
-  LIS3DH_HPM_NORMAL_MODE_RES           =               0x00,
-  LIS3DH_HPM_REF_SIGNAL                =               0x01,
-  LIS3DH_HPM_NORMAL_MODE               =               0x02,
-  LIS3DH_HPM_AUTORESET_INT             =               0x03
-} LIS3DH_HPFMode_t;
-
-typedef enum {
-  LIS3DH_HPFCF_0                       =               0x00,
-  LIS3DH_HPFCF_1                       =               0x01,
-  LIS3DH_HPFCF_2                       =        0x02,
-  LIS3DH_HPFCF_3                       =               0x03
-} LIS3DH_HPFCutOffFreq_t;
-
-typedef struct {
-  u16_t AUX_1;
-  u16_t AUX_2;
-  u16_t AUX_3;
-} LIS3DH_Aux123Raw_t;
-
-typedef enum {
-  LIS3DH_FULLSCALE_2                   =               0x00,
-  LIS3DH_FULLSCALE_4                   =               0x01,
-  LIS3DH_FULLSCALE_8                   =               0x02,
-  LIS3DH_FULLSCALE_16                  =               0x03
-} LIS3DH_Fullscale_t;
-
-typedef enum {
-  LIS3DH_BLE_LSB            =       0x00,
-  LIS3DH_BLE_MSB            =       0x01
-} LIS3DH_Endianess_t;
-
-typedef enum {
-  LIS3DH_SELF_TEST_DISABLE             =               0x00,
-  LIS3DH_SELF_TEST_0                   =               0x01,
-  LIS3DH_SELF_TEST_1                   =               0x02
-} LIS3DH_SelfTest_t;
-
-typedef enum {
-  LIS3DH_FIFO_BYPASS_MODE              =               0x00,
-  LIS3DH_FIFO_MODE                     =               0x01,
-  LIS3DH_FIFO_STREAM_MODE              =               0x02,
-  LIS3DH_FIFO_TRIGGER_MODE             =               0x03,
-  LIS3DH_FIFO_DISABLE                  =               0x04
-} LIS3DH_FifoMode_t;
-
-typedef enum {
-  LIS3DH_TRIG_INT1                     =        0x00,
-  LIS3DH_TRIG_INT2          =       0x01
-} LIS3DH_TrigInt_t;
-
-typedef enum {
-  LIS3DH_SPI_4_WIRE                    =               0x00,
-  LIS3DH_SPI_3_WIRE                    =               0x01
-} LIS3DH_SPIMode_t;
-
-typedef enum {
-  LIS3DH_X_ENABLE                      =               0x01,
-  LIS3DH_X_DISABLE                     =               0x00,
-  LIS3DH_Y_ENABLE                      =               0x02,
-  LIS3DH_Y_DISABLE                     =               0x00,
-  LIS3DH_Z_ENABLE                      =               0x04,
-  LIS3DH_Z_DISABLE                     =               0x00    
-} LIS3DH_AXISenable_t;
-
-typedef enum {
-  LIS3DH_INT1_6D_4D_DISABLE            =               0x00,
-  LIS3DH_INT1_6D_ENABLE                =               0x01,
-  LIS3DH_INT1_4D_ENABLE                =               0x02 
-} LIS3DH_INT_6D_4D_t;
-
-typedef enum {
-  LIS3DH_UP_SX                         =               0x44,
-  LIS3DH_UP_DX                         =               0x42,
-  LIS3DH_DW_SX                         =               0x41,
-  LIS3DH_DW_DX                         =               0x48,
-  LIS3DH_TOP                           =               0x60,
-  LIS3DH_BOTTOM                        =               0x50
-} LIS3DH_POSITION_6D_t;
-
-typedef enum {
-  LIS3DH_INT_MODE_OR                   =               0x00,
-  LIS3DH_INT_MODE_6D_MOVEMENT          =               0x01,
-  LIS3DH_INT_MODE_AND                  =               0x02,
-  LIS3DH_INT_MODE_6D_POSITION          =               0x03  
-} LIS3DH_Int1Mode_t;
-
-
-//interrupt click response
-//  b7 = don't care   b6 = IA  b5 = DClick  b4 = Sclick  b3 = Sign  
-//  b2 = z      b1 = y     b0 = x
-typedef enum {
-LIS3DH_DCLICK_Z_P                      =               0x24,
-LIS3DH_DCLICK_Z_N                      =               0x2C,
-LIS3DH_SCLICK_Z_P                      =               0x14,
-LIS3DH_SCLICK_Z_N                      =               0x1C,
-LIS3DH_DCLICK_Y_P                      =               0x22,
-LIS3DH_DCLICK_Y_N                      =               0x2A,
-LIS3DH_SCLICK_Y_P                      =               0x12,
-LIS3DH_SCLICK_Y_N           =       0x1A,
-LIS3DH_DCLICK_X_P                      =               0x21,
-LIS3DH_DCLICK_X_N                      =               0x29,
-LIS3DH_SCLICK_X_P                      =               0x11,
-LIS3DH_SCLICK_X_N                      =               0x19,
-LIS3DH_NO_CLICK                        =               0x00
-} LIS3DH_Click_Response; 
-
-//TODO: start from here and manage the shared macros etc before this
-
-/* Exported constants --------------------------------------------------------*/
-
-#ifndef __SHARED__CONSTANTS
-#define __SHARED__CONSTANTS
-
-#define MEMS_SET                                        0x01
-#define MEMS_RESET                                      0x00
-
-#endif /*__SHARED__CONSTANTS*/
-
-
-//Register Definition
-#define LIS3DH_WHO_AM_I             0x0F  // device identification register (00110011 default value=0x33)
-
-// CONTROL REGISTER 1
-#define LIS3DH_CTRL_REG1                0x20
-#define LIS3DH_ODR_BIT                      BIT(4)
-#define LIS3DH_LPEN                 BIT(3)
-#define LIS3DH_ZEN                  BIT(2)
-#define LIS3DH_YEN                  BIT(1)
-#define LIS3DH_XEN                  BIT(0)
-
-//CONTROL REGISTER 2
-#define LIS3DH_CTRL_REG2                0x21
-#define LIS3DH_HPM                  BIT(6)
-#define LIS3DH_HPCF                 BIT(4)
-#define LIS3DH_FDS                  BIT(3)
-#define LIS3DH_HPCLICK                  BIT(2)
-#define LIS3DH_HPIS2                    BIT(1)
-#define LIS3DH_HPIS1                    BIT(0)
-
-//CONTROL REGISTER 3
-#define LIS3DH_CTRL_REG3                0x22
-#define LIS3DH_I1_CLICK             BIT(7)
-#define LIS3DH_I1_AOI1                  BIT(6)
-#define LIS3DH_I1_AOI2                      BIT(5)
-#define LIS3DH_I1_DRDY1             BIT(4)
-#define LIS3DH_I1_DRDY2             BIT(3)
-#define LIS3DH_I1_WTM                   BIT(2)
-#define LIS3DH_I1_ORUN                  BIT(1)
-
-//CONTROL REGISTER 6
-#define LIS3DH_CTRL_REG6                0x25
-#define LIS3DH_I2_CLICK             BIT(7)
-#define LIS3DH_I2_INT1                  BIT(6)
-#define LIS3DH_I2_BOOT                  BIT(4)
-#define LIS3DH_H_LACTIVE                BIT(1)
-
-//TEMPERATURE CONFIG REGISTER
-#define LIS3DH_TEMP_CFG_REG             0x1F
-#define LIS3DH_ADC_PD                       BIT(7)
-#define LIS3DH_TEMP_EN                  BIT(6)
-
-//CONTROL REGISTER 4
-#define LIS3DH_CTRL_REG4                0x23
-#define LIS3DH_BDU                  BIT(7)
-#define LIS3DH_BLE                  BIT(6)
-#define LIS3DH_FS                   BIT(4)
-#define LIS3DH_HR                   BIT(3)
-#define LIS3DH_ST                       BIT(1)
-#define LIS3DH_SIM                  BIT(0)
-
-//CONTROL REGISTER 5
-#define LIS3DH_CTRL_REG5                0x24
-#define LIS3DH_BOOT                                    BIT(7)
-#define LIS3DH_FIFO_EN                                 BIT(6)
-#define LIS3DH_LIR_INT1                                BIT(3)
-#define LIS3DH_D4D_INT1                                BIT(2)
-
-//REFERENCE/DATA_CAPTURE
-#define LIS3DH_REFERENCE_REG                        0x26
-#define LIS3DH_REF                          BIT(0)
-
-//STATUS_REG_AXIES
-#define LIS3DH_STATUS_REG               0x27
-#define LIS3DH_ZYXOR                                   BIT(7)
-#define LIS3DH_ZOR                                     BIT(6)
-#define LIS3DH_YOR                                     BIT(5)
-#define LIS3DH_XOR                                     BIT(4)
-#define LIS3DH_ZYXDA                                   BIT(3)
-#define LIS3DH_ZDA                                     BIT(2)
-#define LIS3DH_YDA                                     BIT(1)
-#define LIS3DH_XDA                                     BIT(0)
-
-//STATUS_REG_AUX
-#define LIS3DH_STATUS_AUX               0x07
-
-//INTERRUPT 1 CONFIGURATION
-#define LIS3DH_INT1_CFG                                 0x30
-#define LIS3DH_ANDOR                                   BIT(7)
-#define LIS3DH_INT_6D                                  BIT(6)
-#define LIS3DH_ZHIE                                    BIT(5)
-#define LIS3DH_ZLIE                                    BIT(4)
-#define LIS3DH_YHIE                                    BIT(3)
-#define LIS3DH_YLIE                                    BIT(2)
-#define LIS3DH_XHIE                                    BIT(1)
-#define LIS3DH_XLIE                                    BIT(0)
-
-//INTERRUPT 2 CONFIGURATION
-#define LIS3DH_INT2_CFG                                 0x34
-
-//FIFO CONTROL REGISTER
-#define LIS3DH_FIFO_CTRL_REG                           0x2E
-#define LIS3DH_FM                                      BIT(6)
-#define LIS3DH_TR                                      BIT(5)
-#define LIS3DH_FTH                                     BIT(0)
-
-//CONTROL REG3 bit mask
-#define LIS3DH_CLICK_ON_PIN_INT1_ENABLE                0x80
-#define LIS3DH_CLICK_ON_PIN_INT1_DISABLE               0x00
-#define LIS3DH_I1_INT1_ON_PIN_INT1_ENABLE              0x40
-#define LIS3DH_I1_INT1_ON_PIN_INT1_DISABLE             0x00
-#define LIS3DH_I1_INT2_ON_PIN_INT1_ENABLE              0x20
-#define LIS3DH_I1_INT2_ON_PIN_INT1_DISABLE             0x00
-#define LIS3DH_I1_DRDY1_ON_INT1_ENABLE                 0x10
-#define LIS3DH_I1_DRDY1_ON_INT1_DISABLE                0x00
-#define LIS3DH_I1_DRDY2_ON_INT1_ENABLE                 0x08
-#define LIS3DH_I1_DRDY2_ON_INT1_DISABLE                0x00
-#define LIS3DH_WTM_ON_INT1_ENABLE                      0x04
-#define LIS3DH_WTM_ON_INT1_DISABLE                     0x00
-#define LIS3DH_INT1_OVERRUN_ENABLE                     0x02
-#define LIS3DH_INT1_OVERRUN_DISABLE                    0x00
-
-//CONTROL REG6 bit mask
-#define LIS3DH_CLICK_ON_PIN_INT2_ENABLE                0x80
-#define LIS3DH_CLICK_ON_PIN_INT2_DISABLE               0x00
-#define LIS3DH_I2_INT1_ON_PIN_INT2_ENABLE              0x40
-#define LIS3DH_I2_INT1_ON_PIN_INT2_DISABLE             0x00
-#define LIS3DH_I2_INT2_ON_PIN_INT2_ENABLE              0x20
-#define LIS3DH_I2_INT2_ON_PIN_INT2_DISABLE             0x00
-#define LIS3DH_I2_BOOT_ON_INT2_ENABLE                  0x10
-#define LIS3DH_I2_BOOT_ON_INT2_DISABLE                 0x00
-#define LIS3DH_INT_ACTIVE_HIGH                         0x00
-#define LIS3DH_INT_ACTIVE_LOW                          0x02
-
-//INT1_CFG bit mask
-#define LIS3DH_INT1_AND                                0x80
-#define LIS3DH_INT1_OR                                 0x00
-#define LIS3DH_INT1_ZHIE_ENABLE                        0x20
-#define LIS3DH_INT1_ZHIE_DISABLE                       0x00
-#define LIS3DH_INT1_ZLIE_ENABLE                        0x10
-#define LIS3DH_INT1_ZLIE_DISABLE                       0x00
-#define LIS3DH_INT1_YHIE_ENABLE                        0x08
-#define LIS3DH_INT1_YHIE_DISABLE                       0x00
-#define LIS3DH_INT1_YLIE_ENABLE                        0x04
-#define LIS3DH_INT1_YLIE_DISABLE                       0x00
-#define LIS3DH_INT1_XHIE_ENABLE                        0x02
-#define LIS3DH_INT1_XHIE_DISABLE                       0x00
-#define LIS3DH_INT1_XLIE_ENABLE                        0x01
-#define LIS3DH_INT1_XLIE_DISABLE                       0x00
-
-//INT1_SRC bit mask
-#define LIS3DH_INT1_SRC_IA                             0x40
-#define LIS3DH_INT1_SRC_ZH                             0x20
-#define LIS3DH_INT1_SRC_ZL                             0x10
-#define LIS3DH_INT1_SRC_YH                             0x08
-#define LIS3DH_INT1_SRC_YL                             0x04
-#define LIS3DH_INT1_SRC_XH                             0x02
-#define LIS3DH_INT1_SRC_XL                             0x01
-
-//INT1 REGISTERS
-#define LIS3DH_INT1_THS                                0x32
-#define LIS3DH_INT1_DURATION                           0x33
-
-//INT2 REGISTERS
-#define LIS3DH_INT2_THS                                0x36
-#define LIS3DH_INT2_DURATION                           0x37
-
-//INTERRUPT 1 SOURCE REGISTER
-#define LIS3DH_INT1_SRC                                 0x31
-#define LIS3DH_INT2_SRC                                 0x35
-
-//FIFO Source Register bit Mask
-#define LIS3DH_FIFO_SRC_WTM                            0x80
-#define LIS3DH_FIFO_SRC_OVRUN                          0x40
-#define LIS3DH_FIFO_SRC_EMPTY                          0x20
-  
-//INTERRUPT CLICK REGISTER
-#define LIS3DH_CLICK_CFG                0x38
-//INTERRUPT CLICK CONFIGURATION bit mask
-#define LIS3DH_ZD_ENABLE                               0x20
-#define LIS3DH_ZD_DISABLE                              0x00
-#define LIS3DH_ZS_ENABLE                               0x10
-#define LIS3DH_ZS_DISABLE                              0x00
-#define LIS3DH_YD_ENABLE                               0x08
-#define LIS3DH_YD_DISABLE                              0x00
-#define LIS3DH_YS_ENABLE                               0x04
-#define LIS3DH_YS_DISABLE                              0x00
-#define LIS3DH_XD_ENABLE                               0x02
-#define LIS3DH_XD_DISABLE                              0x00
-#define LIS3DH_XS_ENABLE                               0x01
-#define LIS3DH_XS_DISABLE                              0x00
-
-//INTERRUPT CLICK SOURCE REGISTER
-#define LIS3DH_CLICK_SRC                               0x39
-//INTERRUPT CLICK SOURCE REGISTER bit mask
-#define LIS3DH_IA                                      0x40
-#define LIS3DH_DCLICK                                  0x20
-#define LIS3DH_SCLICK                                  0x10
-#define LIS3DH_CLICK_SIGN                              0x08
-#define LIS3DH_CLICK_Z                                 0x04
-#define LIS3DH_CLICK_Y                                 0x02
-#define LIS3DH_CLICK_X                                 0x01
-
-//Click-click Register
-#define LIS3DH_CLICK_THS                               0x3A
-#define LIS3DH_TIME_LIMIT                              0x3B
-#define LIS3DH_TIME_LATENCY                            0x3C
-#define LIS3DH_TIME_WINDOW                             0x3D
-
-//OUTPUT REGISTER
-#define LIS3DH_OUT_X_L                  0x28
-#define LIS3DH_OUT_X_H                  0x29
-#define LIS3DH_OUT_Y_L                  0x2A
-#define LIS3DH_OUT_Y_H                  0x2B
-#define LIS3DH_OUT_Z_L                  0x2C
-#define LIS3DH_OUT_Z_H                  0x2D
-
-//AUX REGISTER
-#define LIS3DH_OUT_1_L                  0x08
-#define LIS3DH_OUT_1_H                  0x09
-#define LIS3DH_OUT_2_L                  0x0A
-#define LIS3DH_OUT_2_H                  0x0B
-#define LIS3DH_OUT_3_L                  0x0C
-#define LIS3DH_OUT_3_H                  0x0D
-
-//STATUS REGISTER bit mask
-#define LIS3DH_STATUS_REG_ZYXOR                        0x80    // 1 :   new data set has over written the previous one
-                            // 0    :   no overrun has occurred (default)   
-#define LIS3DH_STATUS_REG_ZOR                          0x40    // 0 :   no overrun has occurred (default)
-                            // 1    :   new Z-axis data has over written the previous one
-#define LIS3DH_STATUS_REG_YOR                          0x20    // 0 :   no overrun has occurred (default)
-                            // 1    :   new Y-axis data has over written the previous one
-#define LIS3DH_STATUS_REG_XOR                          0x10    // 0 :   no overrun has occurred (default)
-                            // 1    :   new X-axis data has over written the previous one
-#define LIS3DH_STATUS_REG_ZYXDA                        0x08    // 0 :   a new set of data is not yet avvious one
-                                                        // 1    :   a new set of data is available 
-#define LIS3DH_STATUS_REG_ZDA                          0x04    // 0 :   a new data for the Z-Axis is not availvious one
-                                                        // 1    :   a new data for the Z-Axis is available
-#define LIS3DH_STATUS_REG_YDA                          0x02    // 0 :   a new data for the Y-Axis is not available
-                                                        // 1    :   a new data for the Y-Axis is available
-#define LIS3DH_STATUS_REG_XDA                          0x01    // 0 :   a new data for the X-Axis is not available
-
-#define LIS3DH_DATAREADY_BIT                           LIS3DH_STATUS_REG_ZYXDA
-
-
-//STATUS AUX REGISTER bit mask
-#define LIS3DH_STATUS_AUX_321OR                         0x80
-#define LIS3DH_STATUS_AUX_3OR                           0x40
-#define LIS3DH_STATUS_AUX_2OR                           0x20
-#define LIS3DH_STATUS_AUX_1OR                           0x10
-#define LIS3DH_STATUS_AUX_321DA                         0x08
-#define LIS3DH_STATUS_AUX_3DA                           0x04
-#define LIS3DH_STATUS_AUX_2DA                           0x02
-#define LIS3DH_STATUS_AUX_1DA                           0x01
-
-#define LIS3DH_MEMS_I2C_ADDRESS                 0x33
-
-//FIFO REGISTERS
-#define LIS3DH_FIFO_CTRL_REG                    0x2E
-#define LIS3DH_FIFO_SRC_REG                 0x2F
-
-
-/* Exported macro ------------------------------------------------------------*/
-
-#ifndef __SHARED__MACROS
-
-#define __SHARED__MACROS
-#define ValBit(VAR,Place)         (VAR & (1<<Place))
-#define BIT(x) ( (x) )
-
-#endif /*__SHARED__MACROS*/
-
-class LIS3DH
-{
-public:  
-    LIS3DH(PinName mosi, PinName miso, PinName ss, PinName sck);
-    ~LIS3DH();
-    
-    //own functions 
-    u8_t InitLIS3DH(LIS3DH_Mode_t Mode, LIS3DH_ODR_t Odr, LIS3DH_Fullscale_t Grange);
-    //u8_t SetLIS3DHActivityDetection(uint8_t Th, LIS3DH_Int1Mode_t Mode, uint8_t OnOff);
-    
-    //Sensor Configuration Functions
-    //status_t LIS3DH_SetODR(LIS3DH_ODR_t ov);
-    //status_t LIS3DH_SetMode(LIS3DH_Mode_t md);
-    //status_t LIS3DH_SetAxis(LIS3DH_Axis_t axis);
-    //status_t LIS3DH_SetFullScale(LIS3DH_Fullscale_t fs);
-    //status_t LIS3DH_SetBDU(State_t bdu);
-    //status_t LIS3DH_SetBLE(LIS3DH_Endianess_t ble);
-    status_t LIS3DH_SetSelfTest(LIS3DH_SelfTest_t st);
-    status_t LIS3DH_SetTemperature(State_t state);
-    //status_t LIS3DH_SetADCAux(State_t state);
-
-    //Filtering Functions
-    //status_t LIS3DH_HPFClickEnable(State_t hpfe);
-    //status_t LIS3DH_HPFAOI1Enable(State_t hpfe);
-    //status_t LIS3DH_HPFAOI2Enable(State_t hpfe);
-    //status_t LIS3DH_SetHPFMode(LIS3DH_HPFMode_t hpf);
-    //status_t LIS3DH_SetHPFCutOFF(LIS3DH_HPFCutOffFreq_t hpf);
-    //status_t LIS3DH_SetFilterDataSel(State_t state);
-
-    //Interrupt Functions
-    //status_t LIS3DH_SetInt1Pin(LIS3DH_IntPinConf_t pinConf);
-    //status_t LIS3DH_SetInt2Pin(LIS3DH_IntPinConf_t pinConf);
-    status_t LIS3DH_IntLatchEnable(State_t latch);
-    status_t LIS3DH_ResetInt1Latch(void);
-    status_t LIS3DH_ResetInt2Latch(void);
-    //status_t LIS3DH_SetIntConfiguration(LIS3DH_Int1Conf_t ic);
-    //status_t LIS3DH_SetInt1Threshold(u8_t ths);
-    //status_t LIS3DH_SetInt1Duration(LIS3DH_Int1Conf_t id);
-    //status_t LIS3DH_SetIntMode(LIS3DH_Int1Mode_t ic);
-    //status_t LIS3DH_SetClickCFG(u8_t status);
-    //status_t LIS3DH_SetClickTHS(u8_t ths);
-    //status_t LIS3DH_SetClickLIMIT(u8_t t_limit);
-    //status_t LIS3DH_SetClickLATENCY(u8_t t_latency);
-    //status_t LIS3DH_SetClickWINDOW(u8_t t_window);
-    //status_t LIS3DH_SetInt6D4DConfiguration(LIS3DH_INT_6D_4D_t ic);
-    status_t LIS3DH_GetInt1Src(u8_t* val);
-    status_t LIS3DH_GetInt2Src(u8_t* val);
-    //status_t LIS3DH_GetInt1SrcBit(u8_t statusBIT, u8_t* val);
-
-    //FIFO Functions
-    //status_t LIS3DH_FIFOModeEnable(LIS3DH_FifoMode_t fm);
-    //status_t LIS3DH_SetWaterMark(u8_t wtm);
-    //status_t LIS3DH_SetTriggerInt(LIS3DH_TrigInt_t tr);
-    //status_t LIS3DH_GetFifoSourceReg(u8_t* val);
-    //status_t LIS3DH_GetFifoSourceBit(u8_t statusBIT, u8_t* val);
-    //status_t LIS3DH_GetFifoSourceFSS(u8_t* val);
-
-    //Other Reading Functions   
-    //status_t LIS3DH_GetStatusReg(u8_t* val);
-    //status_t LIS3DH_GetStatusBit(u8_t statusBIT, u8_t* val);
-    //status_t LIS3DH_GetStatusAUXBit(u8_t statusBIT, u8_t* val);
-    //status_t LIS3DH_GetStatusAUX(u8_t* val);
-
-    status_t LIS3DH_GetAccAxesRaw(AxesRaw_t* buff);
-    status_t LIS3DH_GetAuxRaw(LIS3DH_Aux123Raw_t* buff);
-    //status_t LIS3DH_GetClickResponse(u8_t* val);
-    status_t LIS3DH_GetTempRaw(i8_t* val);
-    status_t LIS3DH_GetWHO_AM_I(u8_t* val);
-    status_t LIS3DH_Get6DPosition(u8_t* val);
-  
-    u8_t LIS3DH_ReadReg(u8_t Reg, u8_t* Data);
-    u8_t LIS3DH_WriteReg(u8_t WriteAddr, u8_t Data);
-  
-private:
-
-        
-protected:
-    SPI _spi;
-    DigitalOut _ss;
-    
-};
-} //Namespace
-#endif
--- a/LISD3H.cpp	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1674 +0,0 @@
-#include "LIS3DH.h"
-
-LIS3DH::LIS3DH(PinName mosi, PinName miso, PinName ss, PinName sck):  _spi(mosi,miso,sck), _ss(ss){    
-        
-    // Make sure CS is high
-    _ss = 1; 
-    // Setup the spi for 8 bit data, high steady state clock,
-    // second edge capture, with a 1MHz clock rate
-    _spi.format(8,3);
-    _spi.frequency(4000000);
-}
-
-/*
-u8_t LIS3DH::InitLIS3DH(LIS3DH_Mode_t Mode, LIS3DH_ODR_t Odr, LIS3DH_Fullscale_t Grange)
-{
-    uint8_t response;
-    uint8_t Tmp;
-    
-    LIS3DH_GetWHO_AM_I(&Tmp);
-    
-    response = LIS3DH_SetODR(Odr);
-    
-    //set PowerMode 
-    response = LIS3DH_SetMode(Mode);
-    
-    //set Fullscale
-    response = LIS3DH_SetFullScale(Grange);
-    
-    //set axis Enable
-    response = LIS3DH_SetAxis(LIS3DH_X_ENABLE | LIS3DH_Y_ENABLE | LIS3DH_Z_ENABLE);
-    
-    return response;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetStatusAUX
-* Description    : Read the AUX status register
-* Input          : Char to empty by status register buffer
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetStatusAUX(u8_t* val) {
-  
-  if( !LIS3DH_ReadReg(LIS3DH_STATUS_AUX, val) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;  
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetStatusAUXBIT
-* Description    : Read the AUX status register BIT
-* Input          : LIS3DH_STATUS_AUX_321OR, LIS3DH_STATUS_AUX_3OR, LIS3DH_STATUS_AUX_2OR, LIS3DH_STATUS_AUX_1OR,
-                   LIS3DH_STATUS_AUX_321DA, LIS3DH_STATUS_AUX_3DA, LIS3DH_STATUS_AUX_2DA, LIS3DH_STATUS_AUX_1DA
-* Output         : None
-* Return         : Status of BIT [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetStatusAUXBit(u8_t statusBIT, u8_t* val) {
-  u8_t value;  
-  
-  if( !LIS3DH_ReadReg(LIS3DH_STATUS_AUX, &value) )
-    return MEMS_ERROR;
-  
-  if(statusBIT == LIS3DH_STATUS_AUX_321OR){
-    if(value &= LIS3DH_STATUS_AUX_321OR){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }   
-  }
-  
-  if(statusBIT == LIS3DH_STATUS_AUX_3OR){
-    if(value &= LIS3DH_STATUS_AUX_3OR){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }     
-  }
-  
-  if(statusBIT == LIS3DH_STATUS_AUX_2OR){
-    if(value &= LIS3DH_STATUS_AUX_2OR){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }    
-  }
-  
-  if(statusBIT == LIS3DH_STATUS_AUX_1OR){
-    if(value &= LIS3DH_STATUS_AUX_1OR){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }   
-  }
-  
-  if(statusBIT == LIS3DH_STATUS_AUX_321DA){
-    if(value &= LIS3DH_STATUS_AUX_321DA) {     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }   
-  }
-  
-  if(statusBIT == LIS3DH_STATUS_AUX_3DA){
-    if(value &= LIS3DH_STATUS_AUX_3DA){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }   
-  }
-  
-  if(statusBIT == LIS3DH_STATUS_AUX_2DA){
-    if(value &= LIS3DH_STATUS_AUX_2DA){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  
-  if(statusBIT == LIS3DH_STATUS_AUX_1DA){
-    if(value &= LIS3DH_STATUS_AUX_1DA){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }  
-  return MEMS_ERROR;
-}
-*/
-
-/*
-u8_t LIS3DH::SetLIS3DHActivityDetection(uint8_t Th, LIS3DH_Int1Mode_t Mode, uint8_t OnOff)
-{
-    uint8_t response;
-    
-    response = LIS3DH_SetInt1Pin(LIS3DH_CLICK_ON_PIN_INT1_DISABLE | LIS3DH_I1_INT1_ON_PIN_INT1_ENABLE |              
-                    LIS3DH_I1_INT2_ON_PIN_INT1_DISABLE | LIS3DH_I1_DRDY1_ON_INT1_DISABLE | LIS3DH_I1_DRDY2_ON_INT1_DISABLE |
-                    LIS3DH_WTM_ON_INT1_DISABLE | LIS3DH_INT1_OVERRUN_DISABLE );
-    
-    //set Interrupt Threshold   
-    response = LIS3DH_SetInt1Threshold(Th);
-        
-    //set Interrupt configuration (all enabled)
-    if(OnOff)
-    {
-        response = LIS3DH_SetIntConfiguration(LIS3DH_INT1_ZHIE_ENABLE | LIS3DH_INT1_ZLIE_ENABLE |
-                                       LIS3DH_INT1_YHIE_ENABLE | LIS3DH_INT1_YLIE_ENABLE |
-                                       LIS3DH_INT1_XHIE_ENABLE | LIS3DH_INT1_XLIE_ENABLE ); 
-    }
-    else
-    {
-        response = LIS3DH_SetIntConfiguration(LIS3DH_INT1_ZHIE_DISABLE | LIS3DH_INT1_ZLIE_DISABLE |
-                                       LIS3DH_INT1_YHIE_DISABLE | LIS3DH_INT1_YLIE_DISABLE |
-                                       LIS3DH_INT1_XHIE_DISABLE | LIS3DH_INT1_XLIE_DISABLE ); 
-    }
-    
-    //set Interrupt Mode
-    response = LIS3DH_SetIntMode(Mode);
-    
-    return response;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetODR
-* Description    : Sets LIS3DH Output Data Rate
-* Input          : Output Data Rate
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetODR(LIS3DH_ODR_t ov){
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG1, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x0f;
-  value |= ov<<LIS3DH_ODR_BIT;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG1, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetMode
-* Description    : Sets LIS3DH Operating Mode
-* Input          : Modality (LIS3DH_NORMAL, LIS3DH_LOW_POWER, LIS3DH_POWER_DOWN)
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetMode(LIS3DH_Mode_t md) {
-  u8_t value;
-  u8_t value2;
-  static   u8_t ODR_old_value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG1, &value) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG4, &value2) )
-    return MEMS_ERROR;
-  
-  if((value & 0xF0)==0) 
-    value = value | (ODR_old_value & 0xF0); //if it comes from POWERDOWN  
-  
-  switch(md) {
-    
-  case LIS3DH_POWER_DOWN:
-    ODR_old_value = value;
-    value &= 0x0F;
-    break;
-    
-  case LIS3DH_NORMAL:
-    value &= 0xF7;
-    value |= (MEMS_RESET<<LIS3DH_LPEN);
-    value2 &= 0xF7;
-    value2 |= (MEMS_SET<<LIS3DH_HR);   //set HighResolution_BIT
-    break;
-    
-  case LIS3DH_LOW_POWER:        
-    value &= 0xF7;
-    value |=  (MEMS_SET<<LIS3DH_LPEN);
-    value2 &= 0xF7;
-    value2 |= (MEMS_RESET<<LIS3DH_HR); //reset HighResolution_BIT
-    break;
-    
-  default:
-    return MEMS_ERROR;
-  }
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG1, value) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG4, value2) )
-    return MEMS_ERROR;  
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetAxis
-* Description    : Enable/Disable LIS3DH Axis
-* Input          : LIS3DH_X_ENABLE/DISABLE | LIS3DH_Y_ENABLE/DISABLE | LIS3DH_Z_ENABLE/DISABLE
-* Output         : None
-* Note           : You MUST use all input variable in the argument, as example
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetAxis(LIS3DH_Axis_t axis) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG1, &value) )
-    return MEMS_ERROR;
-  value &= 0xF8;
-  value |= (0x07 & axis);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG1, value) )
-    return MEMS_ERROR;   
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetFullScale
-* Description    : Sets the LIS3DH FullScale
-* Input          : LIS3DH_FULLSCALE_2/LIS3DH_FULLSCALE_4/LIS3DH_FULLSCALE_8/LIS3DH_FULLSCALE_16
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetFullScale(LIS3DH_Fullscale_t fs) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG4, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xCF;    
-  value |= (fs<<LIS3DH_FS);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG4, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetBDU
-* Description    : Enable/Disable Block Data Update Functionality
-* Input          : ENABLE/DISABLE
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetBDU(State_t bdu) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG4, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x7F;
-  value |= (bdu<<LIS3DH_BDU);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG4, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetBLE
-* Description    : Set Endianess (MSB/LSB)
-* Input          : BLE_LSB / BLE_MSB
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetBLE(LIS3DH_Endianess_t ble) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG4, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xBF;  
-  value |= (ble<<LIS3DH_BLE);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG4, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetSelfTest
-* Description    : Set Self Test Modality
-* Input          : LIS3DH_SELF_TEST_DISABLE/ST_0/ST_1
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_SetSelfTest(LIS3DH_SelfTest_t st) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG4, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xF9;
-  value |= (st<<LIS3DH_ST);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG4, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-
-/*******************************************************************************
-* Function Name  : LIS3DH_HPFClick
-* Description    : Enable/Disable High Pass Filter for click
-* Input          : MEMS_ENABLE/MEMS_DISABLE
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_HPFClickEnable(State_t hpfe) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG2, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xFB;
-  value |= (hpfe<<LIS3DH_HPCLICK);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG2, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_HPFAOI1
-* Description    : Enable/Disable High Pass Filter for AOI on INT_1
-* Input          : MEMS_ENABLE/MEMS_DISABLE
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_HPFAOI1Enable(State_t hpfe) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG2, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xFE;
-  value |= (hpfe<<LIS3DH_HPIS1);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG2, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_HPFAOI2
-* Description    : Enable/Disable High Pass Filter for AOI on INT_2
-* Input          : MEMS_ENABLE/MEMS_DISABLE
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_HPFAOI2Enable(State_t hpfe) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG2, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xFD;
-  value |= (hpfe<<LIS3DH_HPIS2);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG2, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetHPFMode
-* Description    : Set High Pass Filter Modality
-* Input          : LIS3DH_HPM_NORMAL_MODE_RES/LIS3DH_HPM_REF_SIGNAL/
-           LIS3DH_HPM_NORMAL_MODE/LIS3DH_HPM_AUTORESET_INT
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetHPFMode(LIS3DH_HPFMode_t hpm) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG2, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x3F;
-  value |= (hpm<<LIS3DH_HPM);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG2, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetHPFCutOFF
-* Description    : Set High Pass CUT OFF Freq
-* Input          : HPFCF [0,3]
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetHPFCutOFF(LIS3DH_HPFCutOffFreq_t hpf) {
-  u8_t value;
-  
-  if (hpf > 3)
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG2, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xCF;
-  value |= (hpf<<LIS3DH_HPCF);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG2, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetFilterDataSel
-* Description    : Set Filter Data Selection bypassed or sent to FIFO OUT register
-* Input          : MEMS_SET, MEMS_RESET
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetFilterDataSel(State_t state) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG2, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xF7;
-  value |= (state<<LIS3DH_FDS);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG2, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetTemperature
-* Description    : Sets LIS3DH Output Temperature
-* Input          : MEMS_ENABLE, MEMS_DISABLE
-* Output         : None
-* Note           : For Read Temperature by LIS3DH_OUT_AUX_3, LIS3DH_SetADCAux and LIS3DH_SetBDU 
-                   functions must be ENABLE
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_SetTemperature(State_t state){
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_TEMP_CFG_REG, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xBF;
-  value |= state<<LIS3DH_TEMP_EN;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_TEMP_CFG_REG, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetADCAux
-* Description    : Sets LIS3DH Output ADC
-* Input          : MEMS_ENABLE, MEMS_DISABLE
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetADCAux(State_t state){
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_TEMP_CFG_REG, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x7F;
-  value |= state<<LIS3DH_ADC_PD;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_TEMP_CFG_REG, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetAuxRaw
-* Description    : Read the Aux Values Output Registers
-* Input          : Buffer to empty
-* Output         : Aux Values Registers buffer
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetAuxRaw(LIS3DH_Aux123Raw_t* buff) {
-  u8_t valueL;
-  u8_t valueH;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_1_L, &valueL) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_1_H, &valueH) )
-    return MEMS_ERROR;
-  
-  buff->AUX_1 = (u16_t)( (valueH << 8) | valueL )/16;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_2_L, &valueL) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_2_H, &valueH) )
-    return MEMS_ERROR;
-  
-  buff->AUX_2 = (u16_t)( (valueH << 8) | valueL )/16;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_3_L, &valueL) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_3_H, &valueH) )
-    return MEMS_ERROR;
-  
-  buff->AUX_3 = (u16_t)( (valueH << 8) | valueL )/16;
-  
-  return MEMS_SUCCESS;  
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetInt1Pin
-* Description    : Set Interrupt1 pin Function
-* Input          :  LIS3DH_CLICK_ON_PIN_INT1_ENABLE/DISABLE    | LIS3DH_I1_INT1_ON_PIN_INT1_ENABLE/DISABLE |              
-                    LIS3DH_I1_INT2_ON_PIN_INT1_ENABLE/DISABLE  | LIS3DH_I1_DRDY1_ON_INT1_ENABLE/DISABLE    |              
-                    LIS3DH_I1_DRDY2_ON_INT1_ENABLE/DISABLE     | LIS3DH_WTM_ON_INT1_ENABLE/DISABLE         |           
-                    LIS3DH_INT1_OVERRUN_ENABLE/DISABLE  
-* example        : SetInt1Pin(LIS3DH_CLICK_ON_PIN_INT1_ENABLE | LIS3DH_I1_INT1_ON_PIN_INT1_ENABLE |              
-                    LIS3DH_I1_INT2_ON_PIN_INT1_DISABLE | LIS3DH_I1_DRDY1_ON_INT1_ENABLE | LIS3DH_I1_DRDY2_ON_INT1_ENABLE |
-                    LIS3DH_WTM_ON_INT1_DISABLE | LIS3DH_INT1_OVERRUN_DISABLE   ) 
-* Note           : To enable Interrupt signals on INT1 Pad (You MUST use all input variable in the argument, as example)
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetInt1Pin(LIS3DH_IntPinConf_t pinConf) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG3, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x00;
-  value |= pinConf;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG3, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetInt2Pin
-* Description    : Set Interrupt2 pin Function
-* Input          : LIS3DH_CLICK_ON_PIN_INT2_ENABLE/DISABLE   | LIS3DH_I2_INT1_ON_PIN_INT2_ENABLE/DISABLE |               
-                   LIS3DH_I2_INT2_ON_PIN_INT2_ENABLE/DISABLE | LIS3DH_I2_BOOT_ON_INT2_ENABLE/DISABLE |                   
-                   LIS3DH_INT_ACTIVE_HIGH/LOW
-* example        : LIS3DH_SetInt2Pin(LIS3DH_CLICK_ON_PIN_INT2_ENABLE/DISABLE | LIS3DH_I2_INT1_ON_PIN_INT2_ENABLE/DISABLE |               
-                   LIS3DH_I2_INT2_ON_PIN_INT2_ENABLE/DISABLE | LIS3DH_I2_BOOT_ON_INT2_ENABLE/DISABLE |                   
-                   LIS3DH_INT_ACTIVE_HIGH/LOW)
-* Note           : To enable Interrupt signals on INT2 Pad (You MUST use all input variable in the argument, as example)
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetInt2Pin(LIS3DH_IntPinConf_t pinConf) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG6, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x00;
-  value |= pinConf;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG6, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetClickCFG
-* Description    : Set Click Interrupt config Function
-* Input          : LIS3DH_ZD_ENABLE/DISABLE | LIS3DH_ZS_ENABLE/DISABLE  | LIS3DH_YD_ENABLE/DISABLE  | 
-                   LIS3DH_YS_ENABLE/DISABLE | LIS3DH_XD_ENABLE/DISABLE  | LIS3DH_XS_ENABLE/DISABLE 
-* example        : LIS3DH_SetClickCFG( LIS3DH_ZD_ENABLE | LIS3DH_ZS_DISABLE | LIS3DH_YD_ENABLE | 
-                               LIS3DH_YS_DISABLE | LIS3DH_XD_ENABLE | LIS3DH_XS_ENABLE)
-* Note           : You MUST use all input variable in the argument, as example
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetClickCFG(u8_t status) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CLICK_CFG, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xC0;
-  value |= status;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CLICK_CFG, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetClickTHS
-* Description    : Set Click Interrupt threshold
-* Input          : Click-click Threshold value [0-127]
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetClickTHS(u8_t ths) {
-  
-  if(ths>127)     
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CLICK_THS, ths) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetClickLIMIT
-* Description    : Set Click Interrupt Time Limit
-* Input          : Click-click Time Limit value [0-127]
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetClickLIMIT(u8_t t_limit) {
-  
-  if(t_limit>127)     
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_TIME_LIMIT, t_limit) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetClickLATENCY
-* Description    : Set Click Interrupt Time Latency
-* Input          : Click-click Time Latency value [0-255]
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetClickLATENCY(u8_t t_latency) {
-  
-  if( !LIS3DH_WriteReg(LIS3DH_TIME_LATENCY, t_latency) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-} 
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetClickWINDOW
-* Description    : Set Click Interrupt Time Window
-* Input          : Click-click Time Window value [0-255]
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetClickWINDOW(u8_t t_window) {
-  
-  if( !LIS3DH_WriteReg(LIS3DH_TIME_WINDOW, t_window) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetClickResponse
-* Description    : Get Click Interrupt Response by CLICK_SRC REGISTER
-* Input          : char to empty by Click Response Typedef
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetClickResponse(u8_t* res) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CLICK_SRC, &value) ) 
-    return MEMS_ERROR;
-  
-  value &= 0x7F;
-  
-  if((value & LIS3DH_IA)==0) {        
-    *res = LIS3DH_NO_CLICK;     
-    return MEMS_SUCCESS;
-  }
-  else {
-    if (value & LIS3DH_DCLICK){
-      if (value & LIS3DH_CLICK_SIGN){
-        if (value & LIS3DH_CLICK_Z) {
-          *res = LIS3DH_DCLICK_Z_N;   
-          return MEMS_SUCCESS;
-        }
-        if (value & LIS3DH_CLICK_Y) {
-          *res = LIS3DH_DCLICK_Y_N;   
-          return MEMS_SUCCESS;
-        }
-        if (value & LIS3DH_CLICK_X) {
-          *res = LIS3DH_DCLICK_X_N;   
-          return MEMS_SUCCESS;
-        }
-      }
-      else{
-        if (value & LIS3DH_CLICK_Z) {
-          *res = LIS3DH_DCLICK_Z_P;   
-          return MEMS_SUCCESS;
-        }
-        if (value & LIS3DH_CLICK_Y) {
-          *res = LIS3DH_DCLICK_Y_P;   
-          return MEMS_SUCCESS;
-        }
-        if (value & LIS3DH_CLICK_X) {
-          *res = LIS3DH_DCLICK_X_P;   
-          return MEMS_SUCCESS;
-        }
-      }       
-    }
-    else{
-      if (value & LIS3DH_CLICK_SIGN){
-        if (value & LIS3DH_CLICK_Z) {
-          *res = LIS3DH_SCLICK_Z_N;   
-          return MEMS_SUCCESS;
-        }
-        if (value & LIS3DH_CLICK_Y) {
-          *res = LIS3DH_SCLICK_Y_N;   
-          return MEMS_SUCCESS;
-        }
-        if (value & LIS3DH_CLICK_X) {
-          *res = LIS3DH_SCLICK_X_N;   
-          return MEMS_SUCCESS;
-        }
-      }
-      else{
-        if (value & LIS3DH_CLICK_Z) {
-          *res = LIS3DH_SCLICK_Z_P;   
-          return MEMS_SUCCESS;
-        }
-        if (value & LIS3DH_CLICK_Y) {
-          *res = LIS3DH_SCLICK_Y_P;   
-          return MEMS_SUCCESS;
-        }
-        if (value & LIS3DH_CLICK_X) {
-          *res = LIS3DH_SCLICK_X_P;   
-          return MEMS_SUCCESS;
-        }
-      }
-    }
-  }
-  return MEMS_ERROR;
-} 
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_Int1LatchEnable
-* Description    : Enable Interrupt 1 Latching function
-* Input          : ENABLE/DISABLE
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_IntLatchEnable(State_t latch) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG5, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0b00001010; //Latch 1 and 2
-  
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG5, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-
-status_t LIS3DH::LIS3DH_ResetInt1Latch(void) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_INT1_SRC, &value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-
-status_t LIS3DH::LIS3DH_ResetInt2Latch(void) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_INT2_SRC, &value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetIntConfiguration
-* Description    : Interrupt 1 Configuration (without LIS3DH_6D_INT)
-* Input          : LIS3DH_INT1_AND/OR | LIS3DH_INT1_ZHIE_ENABLE/DISABLE | LIS3DH_INT1_ZLIE_ENABLE/DISABLE...
-* Output         : None
-* Note           : You MUST use all input variable in the argument, as example
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetIntConfiguration(LIS3DH_Int1Conf_t ic) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_INT1_CFG, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x40; 
-  value |= ic;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_INT1_CFG, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-} 
-*/
-
-     
-/*******************************************************************************
-* Function Name  : LIS3DH_SetIntMode
-* Description    : Interrupt 1 Configuration mode (OR, 6D Movement, AND, 6D Position)
-* Input          : LIS3DH_INT_MODE_OR, LIS3DH_INT_MODE_6D_MOVEMENT, LIS3DH_INT_MODE_AND, 
-                   LIS3DH_INT_MODE_6D_POSITION
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetIntMode(LIS3DH_Int1Mode_t int_mode) {
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_INT1_CFG, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x3F; 
-  value |= (int_mode<<LIS3DH_INT_6D);
-  
-  if( !LIS3DH_WriteReg(LIS3DH_INT1_CFG, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetInt6D4DConfiguration
-* Description    : 6D, 4D Interrupt Configuration
-* Input          : LIS3DH_INT1_6D_ENABLE, LIS3DH_INT1_4D_ENABLE, LIS3DH_INT1_6D_4D_DISABLE
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetInt6D4DConfiguration(LIS3DH_INT_6D_4D_t ic) {
-  u8_t value;
-  u8_t value2;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_INT1_CFG, &value) )
-    return MEMS_ERROR;
-  if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG5, &value2) )
-    return MEMS_ERROR;
-  
-  if(ic == LIS3DH_INT1_6D_ENABLE){
-    value &= 0xBF; 
-    value |= (MEMS_ENABLE<<LIS3DH_INT_6D);
-    value2 &= 0xFB; 
-    value2 |= (MEMS_DISABLE<<LIS3DH_D4D_INT1);
-  }
-  
-  if(ic == LIS3DH_INT1_4D_ENABLE){
-    value &= 0xBF; 
-    value |= (MEMS_ENABLE<<LIS3DH_INT_6D);
-    value2 &= 0xFB; 
-    value2 |= (MEMS_ENABLE<<LIS3DH_D4D_INT1);
-  }
-  
-  if(ic == LIS3DH_INT1_6D_4D_DISABLE){
-    value &= 0xBF; 
-    value |= (MEMS_DISABLE<<LIS3DH_INT_6D);
-    value2 &= 0xFB; 
-    value2 |= (MEMS_DISABLE<<LIS3DH_D4D_INT1);
-  }
-  
-  if( !LIS3DH_WriteReg(LIS3DH_INT1_CFG, value) )
-    return MEMS_ERROR;
-  if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG5, value2) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_Get6DPosition
-* Description    : 6D, 4D Interrupt Position Detect
-* Input          : Byte to empty by POSITION_6D_t Typedef
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_Get6DPosition(u8_t* val){
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_INT1_SRC, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x7F;
-  
-  switch (value){
-  case LIS3DH_UP_SX:   
-    *val = LIS3DH_UP_SX;    
-    break;
-  case LIS3DH_UP_DX:   
-    *val = LIS3DH_UP_DX;    
-    break;
-  case LIS3DH_DW_SX:   
-    *val = LIS3DH_DW_SX;    
-    break;
-  case LIS3DH_DW_DX:   
-    *val = LIS3DH_DW_DX;    
-    break;
-  case LIS3DH_TOP:     
-    *val = LIS3DH_TOP;      
-    break;
-  case LIS3DH_BOTTOM:  
-    *val = LIS3DH_BOTTOM;   
-    break;
-  }
-  
-  return MEMS_SUCCESS;  
-}
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetInt1Threshold
-* Description    : Sets Interrupt 1 Threshold
-* Input          : Threshold = [0,31]
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetInt1Threshold(u8_t ths) {
-  if (ths > 127)
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_INT1_THS, ths) )
-    return MEMS_ERROR;    
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetInt1Duration
-* Description    : Sets Interrupt 1 Duration
-* Input          : Duration value
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetInt1Duration(LIS3DH_Int1Conf_t id) {
-  
-  if (id > 127)
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_WriteReg(LIS3DH_INT1_DURATION, id) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_FIFOModeEnable
-* Description    : Sets Fifo Modality
-* Input          : LIS3DH_FIFO_DISABLE, LIS3DH_FIFO_BYPASS_MODE, LIS3DH_FIFO_MODE, 
-           LIS3DH_FIFO_STREAM_MODE, LIS3DH_FIFO_TRIGGER_MODE
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_FIFOModeEnable(LIS3DH_FifoMode_t fm) {
-  u8_t value;  
-  
-  if(fm == LIS3DH_FIFO_DISABLE) { 
-    if( !LIS3DH_ReadReg(LIS3DH_FIFO_CTRL_REG, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0x1F;
-    value |= (LIS3DH_FIFO_BYPASS_MODE<<LIS3DH_FM);                     
-    
-    if( !LIS3DH_WriteReg(LIS3DH_FIFO_CTRL_REG, value) )           //fifo mode bypass
-      return MEMS_ERROR;   
-    if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG5, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0xBF;    
-    
-    if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG5, value) )               //fifo disable
-      return MEMS_ERROR;   
-  }
-  
-  if(fm == LIS3DH_FIFO_BYPASS_MODE)   {  
-    if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG5, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0xBF;
-    value |= MEMS_SET<<LIS3DH_FIFO_EN;
-    
-    if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG5, value) )               //fifo enable
-      return MEMS_ERROR;  
-    if( !LIS3DH_ReadReg(LIS3DH_FIFO_CTRL_REG, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0x1f;
-    value |= (fm<<LIS3DH_FM);                     //fifo mode configuration
-    
-    if( !LIS3DH_WriteReg(LIS3DH_FIFO_CTRL_REG, value) )
-      return MEMS_ERROR;
-  }
-  
-  if(fm == LIS3DH_FIFO_MODE)   {
-    if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG5, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0xBF;
-    value |= MEMS_SET<<LIS3DH_FIFO_EN;
-    
-    if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG5, value) )               //fifo enable
-      return MEMS_ERROR;  
-    if( !LIS3DH_ReadReg(LIS3DH_FIFO_CTRL_REG, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0x1f;
-    value |= (fm<<LIS3DH_FM);                      //fifo mode configuration
-    
-    if( !LIS3DH_WriteReg(LIS3DH_FIFO_CTRL_REG, value) )
-      return MEMS_ERROR;
-  }
-  
-  if(fm == LIS3DH_FIFO_STREAM_MODE)   {  
-    if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG5, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0xBF;
-    value |= MEMS_SET<<LIS3DH_FIFO_EN;
-    
-    if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG5, value) )               //fifo enable
-      return MEMS_ERROR;   
-    if( !LIS3DH_ReadReg(LIS3DH_FIFO_CTRL_REG, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0x1f;
-    value |= (fm<<LIS3DH_FM);                      //fifo mode configuration
-    
-    if( !LIS3DH_WriteReg(LIS3DH_FIFO_CTRL_REG, value) )
-      return MEMS_ERROR;
-  }
-  
-  if(fm == LIS3DH_FIFO_TRIGGER_MODE)   {  
-    if( !LIS3DH_ReadReg(LIS3DH_CTRL_REG5, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0xBF;
-    value |= MEMS_SET<<LIS3DH_FIFO_EN;
-    
-    if( !LIS3DH_WriteReg(LIS3DH_CTRL_REG5, value) )               //fifo enable
-      return MEMS_ERROR;    
-    if( !LIS3DH_ReadReg(LIS3DH_FIFO_CTRL_REG, &value) )
-      return MEMS_ERROR;
-    
-    value &= 0x1f;
-    value |= (fm<<LIS3DH_FM);                      //fifo mode configuration
-    
-    if( !LIS3DH_WriteReg(LIS3DH_FIFO_CTRL_REG, value) )
-      return MEMS_ERROR;
-  }
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetTriggerInt
-* Description    : Trigger event liked to trigger signal INT1/INT2
-* Input          : LIS3DH_TRIG_INT1/LIS3DH_TRIG_INT2
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetTriggerInt(LIS3DH_TrigInt_t tr) {
-  u8_t value;  
-  
-  if( !LIS3DH_ReadReg(LIS3DH_FIFO_CTRL_REG, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xDF;
-  value |= (tr<<LIS3DH_TR); 
-  
-  if( !LIS3DH_WriteReg(LIS3DH_FIFO_CTRL_REG, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_SetWaterMark
-* Description    : Sets Watermark Value
-* Input          : Watermark = [0,31]
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_SetWaterMark(u8_t wtm) {
-  u8_t value;
-  
-  if(wtm > 31)
-    return MEMS_ERROR;  
-  
-  if( !LIS3DH_ReadReg(LIS3DH_FIFO_CTRL_REG, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0xE0;
-  value |= wtm; 
-  
-  if( !LIS3DH_WriteReg(LIS3DH_FIFO_CTRL_REG, value) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetStatusReg
-* Description    : Read the status register
-* Input          : char to empty by Status Reg Value
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetStatusReg(u8_t* val) {
-  if( !LIS3DH_ReadReg(LIS3DH_STATUS_REG, val) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;  
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetStatusBIT
-* Description    : Read the status register BIT
-* Input          : LIS3DH_STATUS_REG_ZYXOR, LIS3DH_STATUS_REG_ZOR, LIS3DH_STATUS_REG_YOR, LIS3DH_STATUS_REG_XOR,
-                   LIS3DH_STATUS_REG_ZYXDA, LIS3DH_STATUS_REG_ZDA, LIS3DH_STATUS_REG_YDA, LIS3DH_STATUS_REG_XDA, 
-           LIS3DH_DATAREADY_BIT
-           val: Byte to be filled with the status bit 
-* Output         : status register BIT
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetStatusBit(u8_t statusBIT, u8_t* val) {
-  u8_t value;  
-  
-  if( !LIS3DH_ReadReg(LIS3DH_STATUS_REG, &value) )
-    return MEMS_ERROR;
-  
-  switch (statusBIT){
-  case LIS3DH_STATUS_REG_ZYXOR:     
-    if(value &= LIS3DH_STATUS_REG_ZYXOR){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  case LIS3DH_STATUS_REG_ZOR:       
-    if(value &= LIS3DH_STATUS_REG_ZOR){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  case LIS3DH_STATUS_REG_YOR:       
-    if(value &= LIS3DH_STATUS_REG_YOR){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }                                 
-  case LIS3DH_STATUS_REG_XOR:       
-    if(value &= LIS3DH_STATUS_REG_XOR){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }     
-  case LIS3DH_STATUS_REG_ZYXDA:     
-    if(value &= LIS3DH_STATUS_REG_ZYXDA){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }   
-  case LIS3DH_STATUS_REG_ZDA:       
-    if(value &= LIS3DH_STATUS_REG_ZDA){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }   
-  case LIS3DH_STATUS_REG_YDA:       
-    if(value &= LIS3DH_STATUS_REG_YDA){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }   
-  case LIS3DH_STATUS_REG_XDA:       
-    if(value &= LIS3DH_STATUS_REG_XDA){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }                                  
-    
-  }
-  return MEMS_ERROR;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetAccAxesRaw
-* Description    : Read the Acceleration Values Output Registers
-* Input          : buffer to empity by AxesRaw_t Typedef
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_GetAccAxesRaw(AxesRaw_t* buff) {
-  i16_t value;
-  u8_t *valueL = (u8_t *)(&value);
-  u8_t *valueH = ((u8_t *)(&value)+1);
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_X_L, valueL) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_X_H, valueH) )
-    return MEMS_ERROR;
-  
-  buff->AXIS_X = value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_Y_L, valueL) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_Y_H, valueH) )
-    return MEMS_ERROR;
-  
-  buff->AXIS_Y = value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_Z_L, valueL) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_Z_H, valueH) )
-    return MEMS_ERROR;
-  
-  buff->AXIS_Z = value;
-  
-  return MEMS_SUCCESS; 
-}
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetInt1Src
-* Description    : Reset Interrupt 1 Latching function
-* Input          : Char to empty by Int1 source value
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_GetInt1Src(u8_t* val) {
-  
-  if( !LIS3DH_ReadReg(LIS3DH_INT1_SRC, val) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetInt2Src
-* Description    : Reset Interrupt 2 Latching function
-* Input          : Char to empty by Int2 source value
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_GetInt2Src(u8_t* val) {
-  
-  if( !LIS3DH_ReadReg(LIS3DH_INT2_SRC, val) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetInt1SrcBit
-* Description    : Reset Interrupt 1 Latching function
-* Input          : statusBIT: LIS3DH_INT_SRC_IA, LIS3DH_INT_SRC_ZH, LIS3DH_INT_SRC_ZL.....
-*                  val: Byte to be filled with the status bit
-* Output         : None
-* Return         : Status of BIT [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetInt1SrcBit(u8_t statusBIT, u8_t* val) {
-  u8_t value;  
-   
-  if( !LIS3DH_ReadReg(LIS3DH_INT1_SRC, &value) )
-      return MEMS_ERROR;
-   
-  if(statusBIT == LIS3DH_INT1_SRC_IA){
-    if(value &= LIS3DH_INT1_SRC_IA){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  
-  if(statusBIT == LIS3DH_INT1_SRC_ZH){
-    if(value &= LIS3DH_INT1_SRC_ZH){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  
-  if(statusBIT == LIS3DH_INT1_SRC_ZL){
-    if(value &= LIS3DH_INT1_SRC_ZL){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  
-  if(statusBIT == LIS3DH_INT1_SRC_YH){
-    if(value &= LIS3DH_INT1_SRC_YH){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  
-  if(statusBIT == LIS3DH_INT1_SRC_YL){
-    if(value &= LIS3DH_INT1_SRC_YL){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  if(statusBIT == LIS3DH_INT1_SRC_XH){
-    if(value &= LIS3DH_INT1_SRC_XH){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  
-  if(statusBIT == LIS3DH_INT1_SRC_XL){
-    if(value &= LIS3DH_INT1_SRC_XL){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  return MEMS_ERROR;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetFifoSourceReg
-* Description    : Read Fifo source Register
-* Input          : Byte to empty by FIFO source register value
-* Output         : None
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetFifoSourceReg(u8_t* val) {
-  
-  if( !LIS3DH_ReadReg(LIS3DH_FIFO_SRC_REG, val) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetFifoSourceBit
-* Description    : Read Fifo WaterMark source bit
-* Input          : statusBIT: LIS3DH_FIFO_SRC_WTM, LIS3DH_FIFO_SRC_OVRUN, LIS3DH_FIFO_SRC_EMPTY
-*          val: Byte to fill  with the bit value
-* Output         : None
-* Return         : Status of BIT [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetFifoSourceBit(u8_t statusBIT,  u8_t* val){
-  u8_t value;  
-  
-  if( !LIS3DH_ReadReg(LIS3DH_FIFO_SRC_REG, &value) )
-    return MEMS_ERROR;
-  
-  
-  if(statusBIT == LIS3DH_FIFO_SRC_WTM){
-    if(value &= LIS3DH_FIFO_SRC_WTM){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  
-  if(statusBIT == LIS3DH_FIFO_SRC_OVRUN){
-    if(value &= LIS3DH_FIFO_SRC_OVRUN){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  if(statusBIT == LIS3DH_FIFO_SRC_EMPTY){
-    if(value &= statusBIT == LIS3DH_FIFO_SRC_EMPTY){     
-      *val = MEMS_SET;
-      return MEMS_SUCCESS;
-    }
-    else{  
-      *val = MEMS_RESET;
-      return MEMS_SUCCESS;
-    }  
-  }
-  return MEMS_ERROR;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetFifoSourceFSS
-* Description    : Read current number of unread samples stored in FIFO
-* Input          : Byte to empty by FIFO unread sample value
-* Output         : None
-* Return         : Status [value of FSS]
-*******************************************************************************
-status_t LIS3DH::LIS3DH_GetFifoSourceFSS(u8_t* val){
-  u8_t value;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_FIFO_SRC_REG, &value) )
-    return MEMS_ERROR;
-  
-  value &= 0x1F;
-  
-  *val = value;
-  
-  return MEMS_SUCCESS;
-}
-*/
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetTempRaw
-* Description    : Read the Temperature Values by AUX Output Registers OUT_3_H
-* Input          : Buffer to empty
-* Output         : Temperature Values Registers buffer
-* Return         : Status [MEMS_ERROR, MEMS_SUCCESS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_GetTempRaw(i8_t* buff) {
-  u8_t valueL;
-  u8_t valueH;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_3_L, &valueL) )
-    return MEMS_ERROR;
-  
-  if( !LIS3DH_ReadReg(LIS3DH_OUT_3_H, &valueH) )
-    return MEMS_ERROR;
-  
-  *buff = (i8_t)( valueH );
-  
-  return MEMS_SUCCESS;  
-}
-
-/*******************************************************************************
-* Function Name  : LIS3DH_GetWHO_AM_I
-* Description    : Read identification code by WHO_AM_I register
-* Input          : Char to empty by Device identification Value
-* Output         : None
-* Return         : Status [value of FSS]
-*******************************************************************************/
-status_t LIS3DH::LIS3DH_GetWHO_AM_I(u8_t* val){
-  
-  if( !LIS3DH_ReadReg(LIS3DH_WHO_AM_I, val) )
-    return MEMS_ERROR;
-  
-  return MEMS_SUCCESS;
-}
-
-/*******************************************************************************
-* Function Name     : LIS3DH_ReadReg
-* Description       : Generic Reading function. It must be fullfilled with either
-*           : I2C or SPI reading functions                  
-* Input         : Register Address
-* Output        : Data REad
-* Return        : None
-*******************************************************************************/
-u8_t LIS3DH::LIS3DH_ReadReg(u8_t Reg, u8_t* Data) {
-  
-  //To be completed with either I2c or SPI reading function
-  //i.e. *Data = SPI_Mems_Read_Reg( Reg );  
-    
-    _ss = 0;
-    _spi.write(0x80 | Reg);
-    signed char raw = _spi.write(0x00); 
-    _ss = 1;
-    
-    *Data=raw;
-    
-  return 1;
-}
-
-/*******************************************************************************
-* Function Name     : LIS3DH_WriteReg
-* Description       : Generic Writing function. It must be fullfilled with either
-*           : I2C or SPI writing function
-* Input         : Register Address, Data to be written
-* Output        : None
-* Return        : None
-*******************************************************************************/
-u8_t LIS3DH::LIS3DH_WriteReg(u8_t WriteAddr, u8_t Data) {
-  
-  //To be completed with either I2c or SPI writing function
-  //i.e. SPI_Mems_Write_Reg(WriteAddr, Data);  
-    
-    _ss = 0;
-    _spi.write(0x00 | WriteAddr);
-    _spi.write (Data);
-    _ss = 1;  
-    
-  return 1;
-}
-
-LIS3DH::~LIS3DH(){};
\ No newline at end of file
--- a/SI7060.cpp	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-#include "SI7060.h"
-
-uint8_t _address = I2C_ADDRESS_SI7060_01 << 1;
-
-SI7060::SI7060(PinName sda, PinName scl):  _i2c(sda,scl)
-{
-}
-
-char SI7060::readValue(uint8_t registerAdd) {
-    char _ret[1];
-    char cmd[1];
-    cmd[0] = registerAdd;
-    _i2c.write(_address, cmd, 1);
-    _i2c.read(_address, _ret, 1);
-    return _ret[0];
-};
-
-void SI7060::writeValue(uint8_t registerAdd, uint8_t value) {
-    char cmd[2];
-    cmd[0] = registerAdd;
-    cmd[1] = value;
-    _i2c.write(_address, cmd, 2);
-};
-
-void SI7060::sleep() {
-    writeValue(CMD_SI7060_meas,0x01);
-};
-
-void SI7060::prepare() {
-    uint8_t _ret;
-    _ret = readValue(CMD_SI7060_ID);
-    _ret = readValue(CMD_SI7060_meas);
-    writeValue(CMD_SI7060_meas,0x04);
-    _ret = readValue(CMD_SI7060_meas);
-    writeValue(CMD_SI7060_sw_op,0x4E);
-    writeValue(CMD_SI7060_sw_hyst,0x1C);
-};
-
-float SI7060::getTemperature(void) 
-{
-    prepare();
-    
-    float _temp;
-    uint8_t _Dspsigm;
-    uint8_t _Dspsigl;
-    uint8_t _ret;
-    _ret = readValue(CMD_SI7060_Dspsigm);
-    _Dspsigm = (_ret&0x7F);
-    _ret = readValue(CMD_SI7060_Dspsigl);
-    _Dspsigl = _ret;
-    _temp = 55+ ((float)(256*_Dspsigm)+(float)(_Dspsigl-16384))/160;
-    
-    sleep();
-    return _temp;
-}
-
-SI7060::~SI7060(){};
\ No newline at end of file
--- a/SI7060.h	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-#ifndef SI7060_H
-#define SI7060_H
-
-#include "mbed.h"
-
-namespace mbed {
-
-    #define I2C_ADDRESS_SI7060_00 0x30
-    #define I2C_ADDRESS_SI7060_01 0x31
-    #define I2C_ADDRESS_SI7060_02 0x32
-    #define I2C_ADDRESS_SI7060_03 0x33
-    #define CMD_SI7060_ID 0xC0
-    #define CMD_SI7060_Dspsigm 0xC1 
-    #define CMD_SI7060_Dspsigl 0xC2 
-    #define CMD_SI7060_meas 0xC4 
-    #define CMD_SI7060_sw_op 0xC6 
-    #define CMD_SI7060_sw_hyst 0xC7 
-    #define CMD_SI7060_slTimeena 0xC9
-    
-    class SI7060
-    {
-        public:  
-            SI7060(PinName sda, PinName scl);
-            ~SI7060();
-            
-            //funcs
-            char readValue(uint8_t registerAdd);
-            void writeValue(uint8_t registerAdd, uint8_t value);
-            void prepare(void);
-            void sleep(void);
-            float getTemperature(void);
-            
-        private:
-        
-        protected:
-            I2C _i2c;
-    };
-
-} //Namespace
-#endif
--- a/board.h	Fri Aug 09 14:22:21 2019 +0000
+++ b/board.h	Thu Feb 13 00:57:06 2020 +0000
@@ -4,32 +4,26 @@
 #define PN_SWDIO                SWDIO
 #define PN_SWCLK                SWCLK
 #define PN_RESET                P0_21
-#define PN_IO1                  P0_20
-#define PN_IO2                  P0_18
-#define PN_IO3                  P0_2
-#define PN_IO4                  P0_3
-#define PN_IN_BUTTON            P0_13
-#define PN_LED                  P0_11
-#define PN_GSM_WAKEUP_IN        P0_14
-#define PN_GSM_WAKE_DISABLE     P0_16
-#define PN_GSM_STATUS           P0_15
-#define PN_GSM_RESET            P0_25
-#define PN_GSM_PWR_KEY          P0_28
+#define PN_IN_BUTTON            P0_2
+
+#define PN_LED                  P0_30   // Green
+#define PN_LED_BLUE             P0_31   // Blue
+
 #define PN_SPI_MOSI             P0_23
 #define PN_SPI_MISO             P0_19
 #define PN_SPI_CLK              P0_24
 #define PN_SPI_CS0              P0_22
 #define PN_SPI_CS1              P0_17
-#define PN_UART_RX              P0_8
-#define PN_UART_TX              P0_6
+#define PN_UART_RX              P0_11
+#define PN_UART_TX              P0_5
 #define PN_UART_CTS             P0_30
 #define PN_UART_RTS             P0_31
 #define PN_OUT_BUZZER           P0_7
-#define PN_ACC_INT1             P0_5
-#define PN_ACC_INT2             P0_4
-#define PN_VREG_EN              P0_29
-#define PN_I2C_SDA              P0_26
-#define PN_I2C_SCL              P0_27
+#define PN_ACC_INT1             P0_25
+//#define PN_ACC_INT2             P0_25
+#define PN_I2C_SDA              P0_29
+#define PN_I2C_SCL              P0_28
+
 
 //MEMORY FOR DISK
 //#define BD_PAGE_SIZE    4096
@@ -38,5 +32,5 @@
 
 #define USERDATA_START          0x7E000 // - 8k for user data
 
-//#define APPDATA_START           0x40000 // - 4k for app data - DEVELOPMENT
-#define APPDATA_START           0x3D000 // - 4k for app data - PRODUCTION
\ No newline at end of file
+#define APPDATA_START           0x40000 // - 4k for app data - DEVELOPMENT
+//#define APPDATA_START           0x3D000 // - 4k for app data - PRODUCTION
\ No newline at end of file
--- a/common.cpp	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-#include "common.h"
-
-//------------------------------------------------------------------------------
-// LED
-//------------------------------------------------------------------------------ 
-DigitalOut led1(PN_LED);
-
-void LED1on(long milliseconds = 0) {
-    GLOBAL_LEDSequenceinProgress = true;
-    led1 = 0;
-    if (milliseconds > 0) {
-        //ThisThread::sleep_for(milliseconds);
-        Thread::wait(milliseconds);
-        led1 = 1;
-        GLOBAL_LEDSequenceinProgress = false;
-    }
-}
-void LED1blink(int count = 2, long milliseconds = 100) {
-    GLOBAL_LEDSequenceinProgress = true;
-    for (int i = 0; i < (count*2); i++) {
-        led1 = !led1;
-        if (milliseconds > 0) {
-            Thread::wait(milliseconds);
-            //ThisThread::sleep_for(milliseconds);
-        } else { 
-            Thread::wait(100);
-            //ThisThread::sleep_for(100); //default if 0 provided
-        }
-    }
-    led1 = 1;
-    GLOBAL_LEDSequenceinProgress = false;
-}
-void LED1errorCode(int pattern, int count) {
-    GLOBAL_LEDSequenceinProgress = true;
-    for (int i = 0; i < count; i++) {
-        for (int p = 0; p < pattern; p++) {
-            led1 = 0;
-            Thread::wait(200);
-            led1 = 1;
-            Thread::wait(300);
-        }
-        Thread::wait(1000);
-    }
-    led1 = 1;
-    GLOBAL_LEDSequenceinProgress = false;
-}
-void LED1off() {
-    led1 = 1;
-    GLOBAL_LEDSequenceinProgress = false;
-}
\ No newline at end of file
--- a/common.h	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-#ifndef COMMON_H_
-#define COMMON_H_
-
-#include "main.h"
-
-extern DigitalOut led1;
-extern void LED1on(long milliseconds);
-extern void LED1blink(int count, long milliseconds);
-extern void LED1blinkRTC(int count);
-extern void LED1errorCode(int pattern, int count);
-extern void LED1off(void);
-
-#endif
\ No newline at end of file
--- a/main.cpp	Fri Aug 09 14:22:21 2019 +0000
+++ b/main.cpp	Thu Feb 13 00:57:06 2020 +0000
@@ -6,127 +6,88 @@
 • Ensure APP DATA address is correct
 */
 
-/*
-TO DO
-STOP FRASH WRITE FROM CRASHING IF THERE IS A PROBLEM
-*/
-
 //------------------------------------------------------------------------------
 //FUNCTION PROTOTYPES - NEED TO ADD ALL OF THE MISSING ONES
 //------------------------------------------------------------------------------ 
 //should really add these - will just add as and when needed for now
-void event_activity_tx();
-void event_location_tx(bool failsafe);
-#if BLE_ENABLED
-    void bleShutdown();
-#endif
+void bleShutdown();
 
 //------------------------------------------------------------------------------
-// GLOBALS
+// VARS
 //------------------------------------------------------------------------------
-char*            GLOBAL_defaultApi                                  = "b:gps2";
-bool             GLOBAL_accel_healthy                               = false;
-bool             GLOBAL_motionStopFlagTriggered                     = false;
-bool             GLOBAL_needToConfigureLis3dh                       = false;
-bool             GLOBAL_registeredOnNetwork                         = false;
-bool             GLOBAL_modemOn                                     = false;
-bool             GLOBAL_LEDSequenceinProgress                       = false;
-time_t           GLOBAL_wakeTime                                    = 0;
-char             GLOBAL_exceptionString[30];
-char             GLOBAL_exceptionStringRetainedUntilSuccess[10];
+char             RET_pf_identifier[6];
+time_t           RET_RTCunixtime                                    = 0;
+bool             RET_debug                                          = true;
+time_t           RET_debug_offat                                    = 0;
 char             GLOBAL_debug_buffer[DEBUG_BUFFERSIZE];
-char             GLOBAL_failed_broadcasts[5][160];
-bool             GLOBAL_failed_broadcast_slots[5];
-char             GLOBAL_GPSlocString_prev[70];
-bool             GLOBAL_have_GPSlocString_prev                      = false;
 
-//SETTINGS
-int              RET_setting_firmware                               = 0;
-uint32_t         RET_setting_minimumupdate_hrs                      = 0;
-uint8_t          RET_setting_location_mode                          = DEFAULT_LOCATION_MODE;
-uint8_t          RET_setting_location_accuracy                      = DEFAULT_LOCATION_ACCURACY;
-uint32_t         RET_setting_location_tx_interval_mins              = DEFAULT_LOCATION_TX_INTERVAL_MINS;
-uint32_t         RET_setting_location_tx_failsafe_hrs               = DEFAULT_LOCATION_TX_FAILSAFE_HRS;
-uint32_t         RET_location_failsafe_seconds_max                  = (DEFAULT_LOCATION_TX_FAILSAFE_HRS * 3600);
-uint16_t         RET_setting_location_timeout                       = DEFAULT_LOCATION_TIMEOUT;
-uint32_t         RET_setting_activity_tx_interval_hrs               = 0;
-uint8_t          RET_setting_activity_mode                          = 1;
-uint32_t         RET_setting_environmental_tx_interval_mins         = 0;
-uint16_t         RET_setting_motion_g                               = DEFAULT_MOTION_G;
-time_t           RET_setting_motion_start_seconds                   = DEFAULT_MOTION_START_SECONDS;
-time_t           RET_setting_motion_stop_seconds                    = DEFAULT_MOTION_STOP_SECONDS;
-uint16_t         RET_setting_impact_g                               = 0;
-uint8_t          RET_setting_impact_alert                           = 0;
-uint16_t         RET_setting_connection_timeout                     = DEFAULT_CONNECTION_TIMEOUT;
-uint16_t         RET_setting_beacon_interval_seconds                = 0;
-uint8_t          RET_setting_beacon_scan                            = 0;
+//SENSORS
+float            RET_voltage                                        = 0.0;
+float            RET_temperature                                    = 0.0;
+float            RET_humidity                                       = 0.0;
+bool             RET_motionState                                    = false;
+bool             RET_impactState                                    = false;
+
 //STATE
-char             RET_pf_identifier[7];
-uint8_t          RET_coldBoot                                       = 1;
-bool             RET_asleep                                         = false;
 bool             RET_busy                                           = false;
-time_t           RET_RTCunixtime                                    = 0;
-bool             RET_haveSettings                                   = false;
 uint8_t          RET_state                                          = STATE_SETUP;
 uint8_t          RET_state_prev                                     = RET_state;
+bool             RET_asleep                                         = false;
+bool             RET_coldBoot                                       = true;
+
+//BUTTON
+bool             RET_buttonPressed                                  = false;
 uint8_t          RET_buttonPressCount                               = 0;
 time_t           RET_buttonPressTime                                = 0;
 time_t           RET_buttonReleaseTime                              = 0;
 time_t           RET_buttonReleaseTime_prev                         = 0;
 time_t           RET_buttonHoldTime                                 = 0;
-time_t           RET_SetupRunAt                                     = 0;
-time_t           RET_SettingsGotAt                                  = 0;
-bool             RET_setupInProgress                                = false;
-bool             RET_force2G                                        = DEFAULT_FORCE2G;
-bool             RET_watchdogfired                                  = false;
-bool             RET_receivedNewSettings                            = false;
-uint32_t         RET_GPSFailCount                                   = 0;
-uint32_t         RET_NetworkFailCount                               = 0;
-bool             RET_NetworkFailFlag                                = false;
-bool             RET_debug                                          = true;
-time_t           RET_debug_offat                                    = 0;
-float            RET_voltage                                        = 0.0;
-float            RET_temperature                                    = 0.0;
-float            RET_humidity                                       = 0.0;
-float            RET_temperature_max                                = -999.0; //Within broadcast frame. Set inital value to low
-float            RET_temperature_min                                = 999.0; //Within broadcase frame. Set inital value to high
-uint32_t         RET_modemBrownOutCountInSession                    = 0;
-time_t           RET_lastTxTime                                     = 0;
-//MOTION STATE
-bool             RET_motionTriggeredinFrame                         = false;
-bool             RET_motionStateOnInLocTXInterval                   = false;
-time_t           RET_motionStartTime                                = 0;
-time_t           RET_motionStopTime                                 = 0;
-bool             RET_motionPendingOnState                           = false;
-bool             RET_motionPendingOffState                          = false;
-bool             RET_motionState                                    = false;
-float            RET_motionTotalActivityHours                       = 0.0f;
-float            RET_motionTotalActivityHoursSincePost              = 0.0f;
-time_t           RET_motionFrameStart                               = 0;
-char             RET_activityData[ACTIVITY_BUFFERSIZE];
-//IMPACT
-bool             RET_impactTriggered                                = 0;
-//EVENTS LOGGING
-time_t           RET_eventTime_location_log                         = 0;
-time_t           RET_eventTime_environmental_log                    = 0;
-//EVENTS TX
-time_t           RET_eventTime_location_tx                          = 0;
-time_t           RET_eventTime_location_failsafe_tx                 = 0;
-time_t           RET_location_failsafe_seconds_count                = 0;
-time_t           RET_eventTime_environmental_tx                     = 0;
-time_t           RET_eventTime_activity_tx                          = 0;
-time_t           RET_eventTime_wakeFromDormant                      = 0;
+
+//EVENTS
+bool             RET_haveEventsToRun                                = false;
+
+bool             EVENT_buttonPress                                  = false;
+
+bool             EVENT_battery                                      = false;
+time_t           EVENT_battery_interval                             = DEFAULT_INTERVAL_BATTERY;
+time_t           EVENT_battery_time                                 = 0;
+
+bool             EVENT_motionClear                                  = false;
+time_t           EVENT_motionClear_interval                         = DEFAULT_INTERVAL_MOTIONCLEAR;
+time_t           EVENT_motionClear_time                             = 0;
+
+bool             EVENT_buttonClear                                  = false;
+time_t           EVENT_buttonClear_interval                         = DEFAULT_INTERVAL_BUTTONCLEAR;
+time_t           EVENT_buttonClear_time                             = 0;
+
+bool             EVENT_temperature                                  = false;
+time_t           EVENT_temperature_interval                         = DEFAULT_INTERVAL_TEMPERATURE;
+time_t           EVENT_temperature_time                             = 0;
+
+bool             EVENT_humidity                                     = false;
+time_t           EVENT_humidity_interval                            = DEFAULT_INTERVAL_HUMIDITY;
+time_t           EVENT_humidity_time                                = 0;
+
+bool             EVENT_settingsScan                                 = false;
+time_t           EVENT_settingsScan_interval                        = DEFAULT_INTERVAL_SETTINGSSCAN;
+time_t           EVENT_settingsScan_time                            = 0;
+
+bool             EVENT_uwbScan                                      = false;
+time_t           EVENT_uwbScan_interval                        = 60;
+time_t           EVENT_uwbScan_time                                 = 0;
+
 //BLE
+uint16_t         RET_setting_beacon_interval_ms                     = DEFAULT_BEACON_INTERVAL_MS;
+uint16_t         RET_setting_beacon_interval_ms_active              = DEFAULT_BEACON_INTERVAL_MS;
 bool             RET_bleBroadcasting                                = false;
 uint8_t          RET_bleAdv_flags                                   = 0;
-char             RET_closestLocationTag_id[17];
-int              RET_closestLocationTag_rssi                        = 999;
-int              RET_closestBT04Tag_rssi                            = 999;
-bool             RET_locationTag_present                            = false;
-bool             RET_detector_present                               = false;
-const uint8_t    bleAdv_motionTriggeredinFrame_flag                 = 0b01000000;
-const uint8_t    bleAdv_motionState_flag                            = 0b00100000;
-const uint8_t    bleAdv_impact_flag                                 = 0b00010000;
+bool             RET_UWBdetector_present                            = true; //BEN should be false
+bool             RET_BLEpacketUpdate                                = false;
+bool             RET_settingsReceived                               = false;
+const uint8_t    bleAdv_motion_flag                                 = 0x01; //motion detected
+const uint8_t    bleAdv_impact_flag                                 = 0x02; //impact detected
+const uint8_t    bleAdv_button_pressed_flag                         = 0x08; //button press detected
+const uint8_t    bleAdv_gap_connected_flag                          = 0x40; //device is connected
 #pragma pack(1)
 struct bleData_t {
     uint16_t applicationSpecificId;
@@ -140,14 +101,9 @@
     int8_t accel_x;
     int8_t accel_y;
     int8_t accel_z;
-    /*char id_1; //cant use this and local name as it pushes us over size limit
-    char id_2;
-    char id_3;
-    char id_4;
-    char id_5;
-    char id_6;*/
 };
 #pragma pack()
+    
 //------------------------------------------------------------------------------
 //GPIO
 //------------------------------------------------------------------------------ 
@@ -156,13 +112,8 @@
 //------------------------------------------------------------------------------
 //PERIPHERALS
 //------------------------------------------------------------------------------ 
-#if BLE_ENABLED 
-    BLE myble;
-#endif
+BLE myble;
 WatchdogTimer watchdog;
-LIS3DH lis3dh(PN_SPI_MOSI, PN_SPI_MISO, PN_SPI_CS0, PN_SPI_CLK);
-SI7060 si7060(PN_I2C_SDA, PN_I2C_SCL);
-Modem modem(PN_GSM_PWR_KEY, PN_VREG_EN, PN_GSM_WAKE_DISABLE);
 LowPowerTicker RTCticker;
 LowPowerTimer LPtimer;
 
@@ -192,10 +143,6 @@
     //nrf_gpio_cfg_input(PN_SPI_MOSI, NRF_GPIO_PIN_NOPULL);  //Don't need this one
     nrf_gpio_cfg_input(PN_SPI_MISO, NRF_GPIO_PIN_NOPULL);
     
-    //disable modem control lines
-    nrf_gpio_cfg_input(PN_GSM_PWR_KEY, NRF_GPIO_PIN_NOPULL);
-    nrf_gpio_cfg_input(PN_GSM_WAKE_DISABLE, NRF_GPIO_PIN_NOPULL);
-    
     //TWI0
     NRF_TWI0->ENABLE = TWI_ENABLE_ENABLE_Disabled << TWI_ENABLE_ENABLE_Pos;
     *(volatile uint32_t *)0x40003FFC = 0;
@@ -207,40 +154,9 @@
     *(volatile uint32_t *)0x40004FFC;
     *(volatile uint32_t *)0x40004FFC = 1;
 }
-void setState(uint8_t state) {
-    RET_state_prev = RET_state;
-    RET_state = state;
-}
-void dumpSettings() {  
-    if(RET_debug){
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_RTCunixtime:%u", RET_RTCunixtime);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_firmware:%d", RET_setting_firmware);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_minimumupdate_hrs:%d", RET_setting_minimumupdate_hrs);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_state:%d", RET_state);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_mode:%d", RET_setting_location_mode);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_accuracy:%d", RET_setting_location_accuracy);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_tx_interval_mins:%d", RET_setting_location_tx_interval_mins);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_location_failsafe_seconds_max:%d", RET_location_failsafe_seconds_max);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_timeout:%d", RET_setting_location_timeout);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_activity_tx_interval_hrs:%d", RET_setting_activity_tx_interval_hrs);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_activity_mode:%d", RET_setting_activity_mode);debug_exe();        
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_environmental_tx_interval_mins:%d", RET_setting_environmental_tx_interval_mins);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_motion_g:%d", RET_setting_motion_g);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_motion_start_seconds:%d", RET_setting_motion_start_seconds);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_motion_stop_seconds:%d", RET_setting_motion_stop_seconds);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_impact_g:%d", RET_setting_impact_g);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_impact_alert:%d", RET_setting_impact_alert);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_connection_timeout:%d", RET_setting_connection_timeout);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_beacon_interval_seconds:%d", RET_setting_beacon_interval_seconds);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_beacon_scan:%d", RET_setting_beacon_scan);debug_exe();
-        debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_pf_identifier:%s", RET_pf_identifier);debug_exe();
-    }
-}
+
 void recordFirmwareAsValid() {
-    #if BLE_ENABLED
-        bleShutdown();
-    #endif
-    debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RECORD FW %d AS VALID...", FW_VERSION);debug_exe();
+    bleShutdown();
     read_app_data_from_flash(&app_data);
     bool write_app_data_to_flash_execute = false;
     if(get_flag(&app_data, app_execution_flag) == true) {
@@ -280,33 +196,9 @@
     }
     RET_voltage = (voltage_accumulator / (float)readings);
 }
-//------------------------------------------------------------------------------
-// TEMPERATURE
-//------------------------------------------------------------------------------ 
-float getTemperature() {
-    return si7060.getTemperature();
-}
-void updateTemperatures() {
-    if (RET_temperature == 0.0) {RET_temperature = getTemperature();}
-    RET_temperature = (RET_temperature + (getTemperature() - RET_temperature) * 0.25f); //smoothed
-    if (RET_temperature < RET_temperature_min) {RET_temperature_min = RET_temperature;}
-    if (RET_temperature > RET_temperature_max) {RET_temperature_max = RET_temperature;}
-    if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "Temp:%.1f  Min:%.1f  Max:%.1f",RET_temperature,RET_temperature_min,RET_temperature_max);debug_exe();}
-}
-void addToExceptionString(char* value) {
-    if(strstr(GLOBAL_exceptionString, value) == false){
-        snprintf(GLOBAL_exceptionString+strlen(GLOBAL_exceptionString),sizeof(GLOBAL_exceptionString),".%s",value);
-    }
-}
-void addToExceptionStringRetainedUntilSuccess(char* value) {
-    if(strstr(GLOBAL_exceptionStringRetainedUntilSuccess, value) == false){
-        snprintf(GLOBAL_exceptionStringRetainedUntilSuccess+strlen(GLOBAL_exceptionStringRetainedUntilSuccess),sizeof(GLOBAL_exceptionStringRetainedUntilSuccess),".%s",value);
-    }
-}
-void resetTemperatures() {
-    RET_temperature_max = -999.0; //Within broadcast frame. Set inital value to low
-    RET_temperature_min = 999.0; //Within broadcase frame. Set inital value to high   
-}
+
+
+
 //------------------------------------------------------------------------------
 // USER BUTTON HANDLING
 //------------------------------------------------------------------------------ 
@@ -316,15 +208,20 @@
 void buttonRelease() {
     //debounce catch
     RET_buttonReleaseTime = LPtimer.read_ms();
-    if ((RET_buttonReleaseTime - RET_buttonReleaseTime_prev) > 75) { 
+    if ((RET_buttonReleaseTime - RET_buttonReleaseTime_prev) > 100) { 
         RET_buttonPressCount ++;
         RET_buttonHoldTime = (RET_buttonReleaseTime - RET_buttonPressTime);
-        //temporarily enable debugging and dump settings
+        //temporarily enable debugging
         RET_debug = true;
         RET_debug_offat = (RET_RTCunixtime + 3600); //debug on for 1hr
+        EVENT_buttonPress = true;
+        mainthread.release();
     }
     RET_buttonReleaseTime_prev = RET_buttonReleaseTime;
 }
+
+
+
 //------------------------------------------------------------------------------
 // RTC TICKER
 //------------------------------------------------------------------------------
@@ -333,199 +230,86 @@
     //YOU MUST NOT CALL ANY OTHER FUNCTIONS OR DEBUG FROM INSIDE HERE!!! OR IT LOCKS UP THE DEVICE, just change vars & comparisons etc
     RET_RTCunixtime += 1;
     
-    //button logic
-    if (RET_buttonHoldTime >= 4000 && RET_buttonHoldTime <= 10000) {
-        RET_buttonHoldTime = 0;
-        RET_buttonPressCount = 0;
-        if (RET_state != STATE_DORMANT) {
-            RET_state_prev = RET_state;
-            RET_state = STATE_TURNOFF;
-        } else {
-            RET_state = STATE_TURNON;
+    //CHECK FOR EVENTS
+    if (RET_haveEventsToRun == false) {
+        if (EVENT_motionClear_time > 0 && RET_RTCunixtime >= EVENT_motionClear_time) {
+            RET_haveEventsToRun = true; EVENT_motionClear = true;
+        }
+        if (EVENT_buttonClear_time > 0 && RET_RTCunixtime >= EVENT_buttonClear_time) {
+            RET_haveEventsToRun = true; EVENT_buttonClear = true;
+        }
+        if (EVENT_battery_time > 0 && RET_RTCunixtime >= EVENT_battery_time) {
+            RET_haveEventsToRun = true; EVENT_battery = true;
         }
-        mainthread.release();
-    } else if (RET_buttonHoldTime >= 14000 && RET_buttonHoldTime <= 30000) {
-        RET_buttonHoldTime = 0;
-        RET_buttonPressCount = 0;
-        RET_state = STATE_SCORCHEDEARTH;
-        mainthread.release();
-    } else {
-        if((LPtimer.read_ms() - RET_buttonReleaseTime) > 1500 && RET_buttonPressCount > 0) {
-            if(RET_busy == true) { 
-                //RTCtick_ledflash_count = 4;// 2 flashes
-                RET_flash_busy = true;
-            } else {
-                RET_SetupRunAt = 0; //allow setup to run again
-                switch (RET_buttonPressCount) {   //double catches to help with debounce
-                    case 1 :
-                        if(RET_state_prev != RET_state) {RET_state_prev = RET_state;}
-                        RET_state = STATE_BUTTONPRESS1;
-                        RET_buttonPressCount = 0;
-                        mainthread.release();
-                        break;
-                    case 3 :
-                        if(RET_state_prev != RET_state) {RET_state_prev = RET_state;}
-                        RET_state = STATE_BUTTONPRESS3;
-                        RET_buttonPressCount = 0;
-                        mainthread.release();
-                        break;
-                    case 5 :
-                        if(RET_state_prev != RET_state) {RET_state_prev = RET_state;}
-                        RET_state = STATE_BUTTONPRESS5;
-                        RET_buttonPressCount = 0;
-                        mainthread.release();
-                        break;
-                    default :
-                        //do nothing
-                        break;
-                }
-            }
-            RET_buttonPressCount = 0;
+        if (EVENT_temperature_time > 0 && RET_RTCunixtime >= EVENT_temperature_time) {
+            RET_haveEventsToRun = true; EVENT_temperature = true;
+        }
+        if (EVENT_humidity_time > 0 && RET_RTCunixtime >= EVENT_humidity_time) {
+            RET_haveEventsToRun = true; EVENT_humidity = true;
+        }
+        if (EVENT_settingsScan_time > 0 && RET_RTCunixtime >= EVENT_settingsScan_time) {
+            RET_haveEventsToRun = true; EVENT_settingsScan = true;
+        }
+        if (EVENT_uwbScan_time > 0 && RET_RTCunixtime >= EVENT_uwbScan_time) {
+            RET_haveEventsToRun = true; EVENT_uwbScan = true;
         }
     }
     
-    if (RET_busy && RET_flash_busy) {
-        led1 = !led1;
-    } else {
-        RET_flash_busy = false;   
-    }
-    /*
-    if(RET_debug && GLOBAL_LEDSequenceinProgress == false){
-        if (RET_motionState) {
-            led1 = 0;   
-        } else {
-            led1 = 1;   
-        }
-    }
-    */
-}
-//------------------------------------------------------------------------------
-// GLOBALS
-//------------------------------------------------------------------------------ 
-void resetSessionVars() {
-    GLOBAL_accel_healthy = false;
-    RET_motionTriggeredinFrame = false;
-    RET_modemBrownOutCountInSession = 0;
-    RET_humidity = 99.0f;
-}
-void healthCheck() {
-    //check for watchdog fire
-    if (RET_watchdogfired == true) {
-        addToExceptionString("WD");
-        RET_watchdogfired = false;
-        RET_haveSettings = false;
-    }
-    //check clock
-    if(RET_haveSettings == true) {
-        if (RET_RTCunixtime < 1547678732 || RET_RTCunixtime > 1900000000) {
-            RET_haveSettings = false; 
-            addToExceptionString("CI");
-        }
-    }
-    //check that we have a reasonable time to loc
-    if(RET_haveSettings == true) {
-        //check location tx delta is set
-        if (RET_eventTime_location_tx == 0) {
-            //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "ERR:eventTime_location_tx is 0");debug_exe();}
-            RET_haveSettings = false;
-            addToExceptionString("E3");
-        }
-        //check location failsafe tx is less than 2 weeks
-        if (RET_location_failsafe_seconds_max > (336 * 3600)) {
-            //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "ERR:RET_location_failsafe_seconds_max too big");debug_exe();}
-            RET_haveSettings = false;
-            addToExceptionString("E2");
-        }
-    }
-    //check that we have had an attempted post within 2x failsafe time
-    long long unixtime = RET_RTCunixtime;
-    long long lasttxtime = RET_lastTxTime;
-    long long timeSinceTX = (unixtime - lasttxtime);
-    if (RET_lastTxTime > 0 && RET_location_failsafe_seconds_max > 0 && timeSinceTX > (RET_location_failsafe_seconds_max * 2)) {
-        RET_haveSettings = false;
-        addToExceptionString("E1");
-    }
-    //if have settings false then rerun setup
-    if (RET_haveSettings == false) {
-        setState(STATE_SETUP);
+    if (RET_haveEventsToRun) {
+        mainthread.release();
     }
 }
 
-bool selfTest() {
-    int test_count = 0;
-    int test_pass = 0;
-    
-    //Accelerometer
-    test_count ++;
-    uint8_t lis3dh_id; 
-    lis3dh.LIS3DH_GetWHO_AM_I(&lis3dh_id);
-    if (lis3dh_id == 51) {
-        GLOBAL_accel_healthy = true;
-        test_pass ++;
-    } else {
-        GLOBAL_accel_healthy = false;
-        addToExceptionString("AF");   
-    }
-    
-    //Result
-    if (test_count == test_pass) {
-        return true;
-    } else {
-        return false;   
-    }
-}
+
 //------------------------------------------------------------------------------
 // BLE FUNCS
 //------------------------------------------------------------------------------
-#if BLE_ENABLED
 void bleBuildData(bleData_t &bleData)
 {
-    bleData.applicationSpecificId = BLE_SERVICEID_GPSPLUS;
+    bleData.applicationSpecificId = BLE_SERVICEID_UWBBEACON;
     bleData.firmware = FW_VERSION;
     //set flags
-    if (RET_motionTriggeredinFrame) {
-        set_8bit_flag(RET_bleAdv_flags, bleAdv_motionTriggeredinFrame_flag);
+    if (RET_motionState) {
+        set_8bit_flag(RET_bleAdv_flags, bleAdv_motion_flag);
     } else {
-        clr_8bit_flag(RET_bleAdv_flags, bleAdv_motionTriggeredinFrame_flag);
+        clr_8bit_flag(RET_bleAdv_flags, bleAdv_motion_flag);
+    }
+    
+    if (RET_impactState) {
+        set_8bit_flag(RET_bleAdv_flags, bleAdv_impact_flag);
+    } else {
+        clr_8bit_flag(RET_bleAdv_flags, bleAdv_impact_flag);
     }
-    if (RET_motionState) {
-        set_8bit_flag(RET_bleAdv_flags, bleAdv_motionState_flag);
+    
+    if(RET_buttonPressed) {
+        set_8bit_flag(RET_bleAdv_flags, bleAdv_button_pressed_flag);
     } else {
-        clr_8bit_flag(RET_bleAdv_flags, bleAdv_motionState_flag);
+        clr_8bit_flag(RET_bleAdv_flags, bleAdv_button_pressed_flag);
     }
-    clr_8bit_flag(RET_bleAdv_flags, bleAdv_impact_flag);
+    
     bleData.flags = RET_bleAdv_flags;
-    bleData.voltage = uint16_t(RET_voltage * 100);
-    bleData.temperature = uint16_t(getTemperature() * 10);
+    bleData.voltage = RET_voltage;
+    bleData.buttonpresses = RET_buttonPressCount;
+    bleData.temperature = RET_temperature;
     bleData.humidity = 0xFF;
     bleData.lux = 0xFF;
     bleData.accel_x = 0xFF;
     bleData.accel_y = 0xFF;
     bleData.accel_z = 0xFF;
-    /*
-    bleData.id_1 = RET_pf_identifier[0]; //dont use this just stick it in the local name
-    bleData.id_2 = RET_pf_identifier[1];
-    bleData.id_3 = RET_pf_identifier[2];
-    bleData.id_4 = RET_pf_identifier[3];
-    bleData.id_5 = RET_pf_identifier[4];
-    bleData.id_6 = RET_pf_identifier[5];
-    */
 }
-void bleUpdateAndAdvertise(void)
+void bleUpdateAndAdvertise(void) 
 {
-    if (RET_setting_beacon_interval_seconds < 2) {RET_setting_beacon_interval_seconds = 2;}
-    int AdvertisingInterval = (RET_setting_beacon_interval_seconds * 1000);
     bleData_t bleData;
     bleBuildData(bleData);
     myble.gap().stopAdvertising();
     myble.gap().setTxPower(DEFAULT_BEACON_POWER); // set tx power,valid values are -40, -20, -16, -12, -8, -4, 0, 4
     myble.gap().accumulateAdvertisingPayloadTxPower(DEFAULT_BEACON_POWER); // (accepted values are -40, -30, -20, -16, -12, -8, -4, 0, and 4 dBm)
-    myble.gap().setAdvertisingInterval(AdvertisingInterval);
+    myble.gap().setAdvertisingInterval(RET_setting_beacon_interval_ms_active);
     myble.gap().updateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
     //myble.gap().updateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
     myble.gap().startAdvertising();
     RET_bleBroadcasting = true;
-    if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE Adv Start");debug_exe();}
+    RET_BLEpacketUpdate = false;
 }
 void bleSetupAdvertising(BLE::InitializationCompleteCallbackContext *params)
 {
@@ -537,9 +321,8 @@
         myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE );
         myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)localname, sizeof(localname));
         myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
-        //myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
+        ////myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
         myble.gap().setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED);
-        if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE Setup...");debug_exe();}  
     }
 }
 void bleStopAdvertising(void)
@@ -548,7 +331,6 @@
     RET_bleBroadcasting = false;
     if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE Adv Stop");debug_exe();}
 }
-int blecount = 0;
 void bleAdvertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
     struct AdvertisingData_t {
         uint8_t                        length;
@@ -559,135 +341,15 @@
         uint16_t applicationSpecificId;
     } PACKED;
     
-    //LOOKING FOR (SIAEC BETA)
-    //14f64b977c250854
-    //442ce31996801546
-    
-    char beta_location_tag_0[17] = {'4','1','1','7','6','9','0','5','6','4','6','8','3','f','6','8',0x00}; //bens
-    char beta_location_tag_1[17] = {'1','4','f','6','4','b','9','7','7','c','2','5','0','8','5','4',0x00}; //singapore
-    char beta_location_tag_2[17] = {'4','4','2','c','e','3','1','9','9','6','8','0','1','5','4','6',0x00}; //singapore
-    
-    //Portal demos
-    char beta_location_tag_3[17] = {'1','5','f','c','6','d','d','5','c','3','7','f','1','f','4','a',0x00};
-    char beta_location_tag_4[17] = {'b','a','a','e','c','d','6','8','b','d','7','e','e','a','6','5',0x00};
-    char beta_location_tag_5[17] = {'7','e','4','b','7','8','e','0','f','a','3','3','0','8','a','0',0x00};
-    char beta_location_tag_6[17] = {'e','1','1','3','c','d','e','a','a','e','f','f','1','4','d','9',0x00};
-    char beta_location_tag_7[17] = {'8','c','9','2','4','5','f','f','0','c','f','a','b','9','2','f',0x00};
-    char beta_location_tag_8[17] = {'0','7','e','9','9','1','d','3','b','e','b','6','4','0','4','8',0x00};
-    char beta_location_tag_9[17] = {'9','5','6','3','a','0','8','6','2','1','e','8','e','c','1','4',0x00};
-    
-    //RR demos
-    char beta_location_tag_10[17] = {'3','3','0','2','2','c','9','f','0','b','1','8','5','3','a','c',0x00};
-    char beta_location_tag_11[17] = {'2','5','6','c','4','0','2','b','d','c','1','4','2','5','2','7',0x00};
-    char beta_location_tag_12[17] = {'8','e','9','f','0','e','c','1','4','0','e','1','2','e','e','9',0x00};
-    char beta_location_tag_13[17] = {'8','d','6','b','8','5','e','b','8','4','6','e','e','0','0','e',0x00};
-    char beta_location_tag_14[17] = {'9','3','2','7','4','c','b','9','e','4','6','d','b','6','7','6',0x00};
-    char beta_location_tag_15[17] = {'1','a','e','3','0','7','7','f','8','f','3','a','f','7','c','1',0x00};
-    char beta_location_tag_16[17] = {'f','f','d','5','a','2','e','a','4','4','9','2','e','d','a','c',0x00};
-    char beta_location_tag_17[17] = {'f','0','e','f','2','d','8','b','f','7','6','1','3','a','1','d',0x00};
-    char beta_location_tag_18[17] = {'e','e','7','6','4','c','8','5','3','4','6','b','9','5','f','2',0x00};
-    char beta_location_tag_19[17] = {'b','b','0','3','6','7','d','b','d','a','5','b','a','5','a','5',0x00};
-    
-    blecount ++;
-    
     //Search for the manufacturer specific data with matching application-ID
     AdvertisingData_t *pAdvData;
     for (size_t index = 0; index < params->advertisingDataLen; index += (pAdvData->length + 1)) {
         pAdvData = (AdvertisingData_t *)&params->advertisingData[index];
         const bleData_t *pbleData = (const bleData_t *)pAdvData->data;
         
-        //ESTIMOTE BEACON
-        //example data 020104 0303 9afe1716 9afe 22 02c887042a33f9f0 00efebc60146f8ffffffff    //spaces just to show identifier
-        
         //BLE TYPE SWITCH
         switch(pbleData->applicationSpecificId) {
-            case BLE_SERVICEID_PFBEACON1 :
-            {
-                char beacon_identifier[17];
-                snprintf(beacon_identifier, sizeof(beacon_identifier), "%02x%02x%02x%02x%02x%02x%02x%02x",
-                params->advertisingData[12],
-                params->advertisingData[13],
-                params->advertisingData[14],
-                params->advertisingData[15],
-                params->advertisingData[16],
-                params->advertisingData[17],
-                params->advertisingData[18],
-                params->advertisingData[19]);
-                //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), " Mac: [%02x%02x%02x%02x%02x%02x], rssi: %d, AType: %u, S: %04x, Id: %s",params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],params->rssi, params->type, pbleData->applicationSpecificId, beacon_identifier);debug_exe();}
-                //check to see if its one of the two location beta beacons we are looking for...
-                if (strcmp(beacon_identifier, beta_location_tag_0) == 0 
-                    || strcmp(beacon_identifier, beta_location_tag_1) == 0 
-                    || strcmp(beacon_identifier, beta_location_tag_2) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_3) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_4) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_5) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_6) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_7) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_8) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_9) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_10) == 0 
-                    || strcmp(beacon_identifier, beta_location_tag_11) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_12) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_13) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_14) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_15) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_16) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_17) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_18) == 0
-                    || strcmp(beacon_identifier, beta_location_tag_19) == 0
-                    ) {
-                    //dump advertising data
-                    //for (unsigned index = 0; index < params->advertisingDataLen; index++) { if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "%02x",params->advertisingData[index]);debug_exe(false);}}
-                    //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), " MATCH");debug_exe();}
-                    int tag_rssi = params->rssi * -1; //to convert to positive number
-                    if (tag_rssi < RET_closestLocationTag_rssi) {
-                         RET_closestLocationTag_rssi = tag_rssi;
-                         memcpy(RET_closestLocationTag_id, beacon_identifier, sizeof(RET_closestLocationTag_id));
-                         RET_locationTag_present = true;
-                         //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "Location Tag: %s, rssi: %d",RET_closestLocationTag_id, RET_closestLocationTag_rssi);debug_exe();}
-                    }
-                }
-                break;
-            }
-            case BLE_SERVICEID_BT04 :
-            {  
-                //get serial
-                //char serial[9];
-                //snprintf(serial, sizeof(serial), "%02x%02x%02x%02x", params->advertisingData[11], params->advertisingData[12], params->advertisingData[13], params->advertisingData[14]);
-                //if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Serial: %s", serial);debug_exe();}
-    
-                //get battery
-                //int battery = params->advertisingData[15];
-                //if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Battery: %i", battery);debug_exe();}
-                
-                //get temperature positive
-                /*
-                bool temppositive = !(params->advertisingData[17] & 0b01000000);            
-                float temperature =
-                        (
-                            ((params->advertisingData[17] & 0b00111111) << 8) |
-                            ((params->advertisingData[18] & 0b11111111))
-                        ) / 100.0;
-                if (!temppositive) temperature = -temperature;
-                //if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Temp: %f", temperature);debug_exe();}
-                */
-                
-                //get humidity
-                int tag_rssi = params->rssi * -1; //to convert to positive number
-                if (tag_rssi < RET_closestBT04Tag_rssi) {
-                     RET_humidity =
-                        (
-                            ((params->advertisingData[19] & 0b01111111) << 8) |
-                            ((params->advertisingData[20] & 0b11111111))
-                        ) / 100.0;
-                     //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "Humidity Tag Present: %f",RET_humidity);debug_exe();}
-                }
-                //rssi
-                //if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Rssi: %i", params->rssi);debug_exe();}
-
-                break;
-            }
-            case BLE_SERVICEID_PFDETECTOR1 :
+            case BLE_SERVICEID_PFDETECTOR2 :
             {
                 char ble_advdata[100];
                 snprintf(ble_advdata, sizeof(ble_advdata), "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
@@ -715,8 +377,9 @@
                 //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), " Mac: [%02x%02x%02x%02x%02x%02x], rssi: %d, AType: %u, Id: %s",params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],params->rssi, pAdvData->dataType, ble_advdata);debug_exe();}
                 //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "Detector @rssi: %d",params->rssi);debug_exe();}
                 if (params->rssi >= -75) {
-                    RET_detector_present = true;
+                    
                 }
+                RET_settingsReceived = true;
                 break;
             }
         }
@@ -724,7 +387,6 @@
 }
 void bleConfigureScan(void)
 {
-    //configure scan
     myble.gap().setScanParams(200,200); //scan interval //scan window
     myble.gap().startScan(bleAdvertisementCallback);
 }
@@ -738,762 +400,146 @@
     bleStopAdvertising();
     myble.shutdown();
 }
-#endif
-
-//------------------------------------------------------------------------------
-// MOTION FUNCS
-//------------------------------------------------------------------------------ 
-bool checkMotion() {
-    if (RET_haveSettings) { //NEED THIS AS THINGS GO FUNKY WITHOUT RTC TIME SET CORRECTLY
-        if (lis3dh_int2) {
-            RET_motionTriggeredinFrame = true;
-            GLOBAL_needToConfigureLis3dh = true; //interrupt has fire so need to clear it
-            if(RET_debug) {
-                LED1on(100);
-            }
-            if (!RET_motionPendingOnState) {
-                RET_motionPendingOnState = true;
-                RET_motionPendingOffState = false;
-                // Log start motion time
-                RET_motionStartTime = RET_RTCunixtime;
-            }
-        } else {
-            RET_motionTriggeredinFrame = false;
-            RET_motionPendingOnState = false;
-            if (!RET_motionPendingOffState) {
-                RET_motionPendingOffState = true;
-                //log stop motion time
-                RET_motionStopTime = RET_RTCunixtime;
-            }
-        }
-        //calculate motion state
-        if (RET_motionFrameStart == 0) {RET_motionFrameStart = RET_RTCunixtime;}
-        if (RET_motionPendingOnState) {
-            //check if above threshold
-            time_t inMotionForSeconds = ((RET_RTCunixtime - RET_motionStartTime) + (DEFAULT_SLEEP_FRAME / 1000)); //Plus DEFAULT_SLEEP_FRAME as it should include frame time
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "M:%u",inMotionForSeconds);debug_exe();}
-            if (inMotionForSeconds >= RET_setting_motion_start_seconds) {
-                //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "MotionOn");debug_exe();}
-                RET_motionState = true;
-                RET_motionStateOnInLocTXInterval = true;
-                GLOBAL_have_GPSlocString_prev = false;
-                if (RET_motionState == false) { //If this is first after motionState 0
-                    if (RET_setting_activity_mode == 2 && RET_setting_activity_tx_interval_hrs > 0) {
-                        time_t epochOffsetMins = ((RET_RTCunixtime - RET_motionFrameStart) / 60);
-                        sprintf(RET_activityData+strlen(RET_activityData),"1.%u!",epochOffsetMins);
-                    }
-                }
-            }
-        }
-        if (RET_motionPendingOffState) {
-            time_t noMotionForSeconds = ((RET_RTCunixtime - RET_motionStopTime) + (DEFAULT_SLEEP_FRAME / 1000)); //Plus DEFAULT_SLEEP_FRAME as it should include frame time
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "NM:%u",noMotionForSeconds);debug_exe();}
-            if (noMotionForSeconds >= RET_setting_motion_stop_seconds) {
-                if (RET_motionState == true) {
-                    RET_motionPendingOffState = false;
-                    RET_motionState = false;
-                    GLOBAL_motionStopFlagTriggered = true;
-                    //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "MotionStop");debug_exe();}
-                    if (RET_setting_activity_mode > 0 && RET_setting_activity_tx_interval_hrs > 0) {
-                        RET_motionTotalActivityHoursSincePost += ((float(RET_motionStopTime)-float(RET_motionStartTime)) / 3600.0f);
-                        RET_motionTotalActivityHours += RET_motionTotalActivityHoursSincePost;
-                        if (RET_setting_activity_mode == 2) {
-                            time_t epochOffsetMins = ((RET_RTCunixtime - RET_motionFrameStart) / 60);
-                            sprintf(RET_activityData+strlen(RET_activityData),"0.%u!",epochOffsetMins);
-                        }
-                    }
-                }
-            }
-        }
-    }
-    return RET_motionState;
-}
 
 //------------------------------------------------------------------------------
-// UPDATE OPERATING SETTINGS
+// FIRST RUN
 //------------------------------------------------------------------------------ 
-bool saveSettings(char* settingsBuffer) {
-    int matchCount = 0;
-    int critical_fail_count = 0;
-    int TEMP_a = -1; time_t TEMP_b = 0; int TEMP_c = -1; int TEMP_d = -1; int TEMP_e = -1; int TEMP_f = -1; int TEMP_g = -1; int TEMP_h = -1; int TEMP_i = -1; int TEMP_j = -1; 
-    int TEMP_k = -1; int TEMP_l = -1; int TEMP_m = -1; int TEMP_n = -1; int TEMP_o = -1; int TEMP_p = -1; int TEMP_q = -1; int TEMP_r = -1; int TEMP_s = -1; int TEMP_t = -1; char TEMP_u[7];
-    
-    if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RESP: %s",settingsBuffer);debug_exe();}
-    
-    //exampple
-    //+CUSD: 0,”1#a:12,b:1558020598,c:-1,d:-1,e:1,f:2,g:5,h:168,i:90,j:168,k:0,l:8,m:60,n:60,o:0,p:0,q:120,r:0,s:0,t:1,u:F859C1#”,15    
+void firstRun() {
+    //Set Serial Number
+    RET_pf_identifier[0] = 'U';
+    RET_pf_identifier[1] = 'W';
+    RET_pf_identifier[2] = 'B';
+    RET_pf_identifier[3] = '0';
+    RET_pf_identifier[4] = '1';
+    RET_pf_identifier[5] = 0x00;
     
-    if ( (matchCount = sscanf(settingsBuffer,"a:%d,b:%u,c:%d,d:%d,e:%d,f:%d,g:%d,h:%d,i:%d,j:%d,k:%d,l:%d,m:%d,n:%d,o:%d,p:%d,q:%d,r:%d,s:%d,t:%d,u:%s",
-    &TEMP_a,&TEMP_b,&TEMP_c,&TEMP_d,&TEMP_e,&TEMP_f,&TEMP_g,&TEMP_h,&TEMP_i,&TEMP_j,&TEMP_k,&TEMP_l,&TEMP_m,&TEMP_n,&TEMP_o,&TEMP_p,&TEMP_q,&TEMP_r,&TEMP_s,&TEMP_t,&TEMP_u) ) > 0 ) {
-        
-        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "PARAMS: a:%d,b:%u,c:%d,d:%d,e:%d,f:%d,g:%d,h:%d,i:%d,j:%d,k:%d,l:%d,m:%d,n:%d,o:%d,p:%d,q:%d,r:%d,s:%d,t:%d,u:%s\n",
-        TEMP_a,TEMP_b,TEMP_c,TEMP_d,TEMP_e,TEMP_f,TEMP_g,TEMP_h,TEMP_i,TEMP_j,TEMP_k,TEMP_l,TEMP_m,TEMP_n,TEMP_o,TEMP_p,TEMP_q,TEMP_r,TEMP_s,TEMP_t,TEMP_u);debug_exe();}
-        
-        if(TEMP_a > 0) { RET_setting_minimumupdate_hrs = TEMP_a;                      }
-        if(TEMP_b > 1552915630 && TEMP_b < 1900000000) {
-            if (RET_RTCunixtime < 1552915630) {
-                //assume this is first proper unixtime and set
-                RET_RTCunixtime = TEMP_b;
-            } else {
-                //this is not a first unixtime, so check within safe range, convert to long long first to avoid -1 rollover issue
-                long long unixtime_in = TEMP_b;
-                long long unixtime_current = RET_RTCunixtime;
-                if ((unixtime_in - unixtime_current) < 604800) { //allow 1 week difference
-                    RET_RTCunixtime = TEMP_b;
-                } else {
-                    critical_fail_count++;
-                    if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "unixtime too far ahead. C:%u  N:%u",RET_RTCunixtime,TEMP_b);debug_exe();}
-                }
-            }
-        } else { 
-            critical_fail_count++;
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "unixtime too low");debug_exe();}
-        }
-        if(TEMP_c > 0) { RET_setting_firmware = TEMP_c;                               } else { RET_setting_firmware = -1;}
-        if(TEMP_d > -1) { setState(TEMP_d);                                           } else { setState(STATE_NORMAL);}
-        if(TEMP_e > 0) { RET_setting_location_mode = TEMP_e;                          }
-            if(RET_setting_location_mode > 4) {RET_setting_location_mode = DEFAULT_LOCATION_MODE;}
-        if(TEMP_f > 0) { RET_setting_location_accuracy = TEMP_f;                      }
-            if(RET_setting_location_accuracy > 3) {RET_setting_location_accuracy = DEFAULT_LOCATION_ACCURACY;}
-        if(TEMP_g > 0) { RET_setting_location_tx_interval_mins = TEMP_g;              }
-        if(TEMP_h > 0) { RET_setting_location_tx_failsafe_hrs = TEMP_h;               }
-            if(RET_setting_location_tx_failsafe_hrs > 504) {RET_setting_location_tx_failsafe_hrs = DEFAULT_LOCATION_TX_FAILSAFE_HRS;}
-        if(TEMP_i > 0) { RET_setting_location_timeout = TEMP_i;                       }
-            if(RET_setting_location_timeout < 60 || RET_setting_location_timeout > 300) {RET_setting_location_timeout = DEFAULT_LOCATION_TIMEOUT;}
-        if(TEMP_j > -1) { RET_setting_activity_tx_interval_hrs = TEMP_j;               }
-        if(TEMP_k > -1) { RET_setting_environmental_tx_interval_mins = TEMP_k;         }
-        if(TEMP_l > 0) { RET_setting_motion_g = TEMP_l;                               }
-            if(RET_setting_motion_g < 4 || RET_setting_motion_g > 127) {RET_setting_motion_g = DEFAULT_MOTION_G;}
-        if(TEMP_m > -1) { RET_setting_motion_start_seconds = TEMP_m;                   }
-        if(TEMP_n > -1) { RET_setting_motion_stop_seconds = TEMP_n;                    }
-        if(TEMP_o > -1) { RET_setting_impact_g = TEMP_o;                               }
-        if(TEMP_p > -1) { RET_setting_impact_alert = TEMP_p;                           }
-        if(TEMP_q > -1) { RET_setting_connection_timeout = TEMP_q;                     }
-            if(RET_setting_connection_timeout < 60 || RET_setting_connection_timeout > 240) { RET_setting_connection_timeout = DEFAULT_CONNECTION_TIMEOUT; }
-        if(TEMP_r > -1) { RET_setting_beacon_interval_seconds = TEMP_r;                }
-        if(TEMP_s > -1) { RET_setting_beacon_scan = TEMP_s;                            }
-        if(TEMP_t > -1) { RET_setting_activity_mode = TEMP_t;                          }
-        if(TEMP_u[0] != 0x00 && TEMP_u[1] != 0x00 && TEMP_u[2] != 0x00) { strcpy(RET_pf_identifier,TEMP_u);                      }
+    //GET INITITAL SENSORS
+    updateBatteryV();
+    //updateTemperature
+    //updateHumidity
 
-        if (critical_fail_count == 0) { 
-            RET_receivedNewSettings = true;
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "NEW SETTINGS");debug_exe();}
-            dumpSettings();
-            RET_haveSettings = true;
-            GLOBAL_needToConfigureLis3dh = true;
-            RET_SettingsGotAt = RET_RTCunixtime;
-            //check for firmware update
-            if (RET_setting_firmware > 0 && RET_setting_firmware != FW_VERSION) {
-                //Broadcast any activity data we have before fw update
-                event_activity_tx();
-                //prep for FW update
-                #if BLE_ENABLED
-                    bleShutdown();
-                #endif
-                read_app_data_from_flash(&app_data);
-                clr_flag(&app_data, app_execution_flag);
-                clr_flag(&app_data, first_run_flag);
-                app_data.current_firmware_version = FW_VERSION;
-                app_data.target_firmware_version = RET_setting_firmware;
-                write_app_data_to_flash(&app_data);
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "OTA\n");debug_exe();}
-                ThisThread::sleep_for(200);
-                system_reset();
-            }
-            return true;
-        } else {
-            addToExceptionString("SCF");
-            return false;
-        }
-    } else {
-        addToExceptionString("SPE");
-        return false;
-    }
-}
-
-//------------------------------------------------------------------------------
-// SET EVENT TIMES
-//------------------------------------------------------------------------------ 
-void setEventTime_Location() {
-    if(RET_setting_location_tx_interval_mins > 0) { 
-        RET_eventTime_location_tx = (RET_RTCunixtime + (RET_setting_location_tx_interval_mins * 60));
-        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVTSET - LOC TX @ %u, MODE %d",RET_eventTime_location_tx, RET_setting_location_mode);debug_exe();}
-    }
-    if(RET_setting_location_tx_failsafe_hrs > 0 && RET_setting_location_tx_failsafe_hrs <= 168) { 
-        RET_location_failsafe_seconds_max = (RET_setting_location_tx_failsafe_hrs * 3600);
-        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVTSET - LOC FS TX %u s",RET_location_failsafe_seconds_max);debug_exe();}
-    } else {
-        RET_location_failsafe_seconds_max = (DEFAULT_LOCATION_TX_FAILSAFE_HRS * 3600);
-    }
-    RET_eventTime_location_failsafe_tx = (RET_RTCunixtime + RET_location_failsafe_seconds_max);
-}
-void setEventTime_Activity() {
-    if(RET_setting_activity_tx_interval_hrs > 0) { 
-        RET_eventTime_activity_tx = (RET_RTCunixtime + (RET_setting_activity_tx_interval_hrs * 3600));
-        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVTSET - ACT TX @ %u",RET_eventTime_activity_tx);debug_exe();}
-    }
-}
-void setEventTime_Environmental() {
-    if(RET_eventTime_environmental_tx > 0) { 
-        RET_eventTime_environmental_tx = (RET_RTCunixtime + (RET_setting_environmental_tx_interval_mins * 60));
-        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVTSET - ENV TX @ %u",RET_eventTime_environmental_tx);debug_exe();}
-    }
-}
-void setEventTimes() {
-    //SET ALL EVENT TIMES
-    setEventTime_Location();
-    setEventTime_Activity();
-    setEventTime_Environmental();
-}
-
-//------------------------------------------------------------------------------
-// ERROR LOG
-//------------------------------------------------------------------------------ 
-void sendErrorLog(char* error) {
-    updateBatteryV();
-    int timetaken = (RET_RTCunixtime - GLOBAL_wakeTime);
-    char bytestosend[100];
-    memset(bytestosend,0x00,sizeof(bytestosend));
-    snprintf(bytestosend,sizeof(bytestosend),"(%s,a:log,f:%d,v:%.2f,e:%d,z:%s.%s,s:0)\0",GLOBAL_defaultApi,FW_VERSION,RET_voltage,timetaken,error,GLOBAL_exceptionString);
-    if (modem.on(RET_force2G)) {
-        if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,RET_setting_connection_timeout,RET_NetworkFailCount)) {
-            modem.USSDmessage(bytestosend, false, 2, GLOBAL_defaultApi);
-        }
-    }
-    ThisThread::sleep_for(250);
+    //SET EVENT TIMES
+    EVENT_battery_time = (RET_RTCunixtime + EVENT_battery_interval);
+    EVENT_temperature_time = (RET_RTCunixtime + EVENT_temperature_interval);
+    EVENT_humidity_time = (RET_RTCunixtime + EVENT_humidity_interval);
+    EVENT_settingsScan_time = (RET_RTCunixtime + EVENT_settingsScan_interval);
+    EVENT_uwbScan_time = (RET_RTCunixtime + EVENT_uwbScan_interval);
 }
 
 //------------------------------------------------------------------------------
-// EVENTS
+// BLE SETTINGS SCAN
 //------------------------------------------------------------------------------ 
-void failed_broadcast_log(char* eventstring) {
-    //First available free slot
-    bool saved = false;
-    for(int i = 0; i < sizeof(GLOBAL_failed_broadcast_slots); i++) {
-        if (GLOBAL_failed_broadcast_slots[i] == false) {
-            memset(GLOBAL_failed_broadcasts[i],0x00,sizeof(GLOBAL_failed_broadcasts[i])); //clear row
-            snprintf(GLOBAL_failed_broadcasts[i],sizeof(GLOBAL_failed_broadcasts[i]),"%s",eventstring); //save new row
-            GLOBAL_failed_broadcast_slots[i] = true;
-            saved = true;
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Failed Broadcast saved: %s",eventstring);debug_exe();}
-            break;
-        }
-    }
-    if (!saved) {
-        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Failed Broadcast save fail");debug_exe();}
-    }
-    return;
-}
-void failed_broadcasts_tx() {
-    #if BLE_ENABLED
-        bleStopAdvertising();
-    #endif
-    //check we have something to send...
-    int numbertosend = 0;
-    for(int i = 0; i < sizeof(GLOBAL_failed_broadcast_slots); i++) {
-        if (GLOBAL_failed_broadcast_slots[i] == true) {
-            numbertosend ++;
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Retry:%s",GLOBAL_failed_broadcasts[i]);debug_exe();}
-        }
-    }
-    if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Failed Broadcasts to send:%d",numbertosend);debug_exe();}
-    for(int i = 0; i < sizeof(GLOBAL_failed_broadcast_slots); i++) {
-        if (GLOBAL_failed_broadcast_slots[i] == true) {
-            if (RET_NetworkFailCount <= DEFAULT_MAX_FAILED_CONNECTIONS) {
-                if (modem.on(RET_force2G)) {
-                    if (modem.registerOnNetwork(2,RET_setting_connection_timeout,RET_NetworkFailCount)) {
-                        char result[100];
-                        bool getResponse = false;
-                        snprintf(result,sizeof(result),"%s",modem.USSDmessage(GLOBAL_failed_broadcasts[i], getResponse, 2, GLOBAL_defaultApi));
-                        if (strcmp(result, "sendok") == 0) {
-                            //clear row
-                            memset(GLOBAL_failed_broadcasts[i],0x00,sizeof(GLOBAL_failed_broadcasts[i]));
-                            GLOBAL_failed_broadcast_slots[i] = false;
-                        }
-                    }
-                }
-            }
-        }
-    }
-}
-bool event_setup(bool manualrun) {
-    #if BLE_ENABLED
-        bleStopAdvertising();
-    #endif
-    bool pass = false;
+void settingsScan() {
     LED1on(0);
-    if (RET_NetworkFailCount > DEFAULT_MAX_FAILED_CONNECTIONS) addToExceptionString("NF");
-    if (RET_GPSFailCount > DEFAULT_MAX_FAILED_GPS) addToExceptionString("GF");
-    RET_setupInProgress = true;
-    GLOBAL_have_GPSlocString_prev = false;
-    RET_lastTxTime = RET_RTCunixtime;
-    RET_NetworkFailCount = 0;
-    RET_GPSFailCount = 0;
-    RET_setting_connection_timeout = 180; //reset to longer value to setup run to help with connection
-    bool selftestresult = selfTest();
-    int connectionStartTime = RET_RTCunixtime;
-    if (modem.on(RET_force2G)) {
-        if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,RET_setting_connection_timeout,RET_NetworkFailCount)) {
-            int timetaken_total = (RET_RTCunixtime - GLOBAL_wakeTime) + 10; //add 10 for ussd response time.
-            int timetaken_connection = (RET_RTCunixtime - connectionStartTime);
-            if (manualrun) addToExceptionString("MAN");
-            char bytestosend[160];
-            snprintf(bytestosend,sizeof(bytestosend),"(%s,a:setup,f:%d,v:%.2f,t:%.1f,e:%d,y:%d,z:SETUP-%s,k:%s,m:%s,s:1)\0",GLOBAL_defaultApi,FW_VERSION,RET_voltage,RET_temperature,timetaken_total,timetaken_connection,GLOBAL_exceptionString,SKU,HW_MAJORREVISION);
-            char result[200];
-            snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytestosend, true, 2, GLOBAL_defaultApi));
-            RET_setupInProgress = false; //this turns off the flashing led
-            if (strcmp(result, "sendokrecfail") == 0) {
-                //send ok but receive fail
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"USSD Send Ok but Rec fail");debug_exe();}
-                sendErrorLog("ERR-SU-NR");
-            } else if (strcmp(result, "sendfail") == 0) {
-                //do nothing
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"USSD Send Fail");debug_exe();}
-            } else {
-                if (saveSettings(result) == true) {
-                    pass = true;
-                } else {
-                    //something went critically wrong getting settings 
-                    sendErrorLog("ERR-SU-IR");
-                }
-            }
-        }
-    } else {
-        //FAILUREMODE Modem failed to turn on  
-        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Modem Fail");debug_exe();}
-    }
-    
-    //IF WE PASSED THEN LETS DO OTHER POSTS
-    if (pass == true) {
-        GLOBAL_wakeTime = RET_RTCunixtime; //lets reset this here so that the following loc and act function have sensible values for total time
-        //GET LOC DATA
-        //uint8_t previous_location_accuracy = RET_setting_location_accuracy;
-        //RET_setting_location_accuracy = 1; //set location mode to CL only
-        event_location_tx(false);
-        //RET_setting_location_accuracy = previous_location_accuracy; //set location mode back to previous
-        //SEND ANY ACTIVITY DATA
-        event_activity_tx();
-        LED1blink(4,500); //PASS AND END
-    }
-    
-    //TIDY UP = LOG RUN TIME - THIS MUST GO AT END AFTER WE HAVE GOT SERVER TIMESTAMP
-    RET_SetupRunAt = RET_RTCunixtime;
-    RET_GPSFailCount = 0;
-    RET_NetworkFailCount = 0;
-    setEventTimes();
-    //RESULT
-    return pass;
-}
-void event_turnonofflog_tx(bool turnon) {
-    #if BLE_ENABLED
-        bleStopAdvertising();
-    #endif
-    RET_NetworkFailCount = 0; //reset network blocker
-    RET_GPSFailCount = 0;
-    updateBatteryV();
-    int connectionStartTime = RET_RTCunixtime;
-    if (modem.on(RET_force2G)) {
-        char locString[70];
-        int gpsStartTime = RET_RTCunixtime;
-        memcpy(locString, modem.getLocation(1, RET_setting_location_timeout, RET_GPSFailCount, RET_NetworkFailCount), sizeof(locString));
-        int timetaken_gps = (RET_RTCunixtime - gpsStartTime);
-        if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,RET_setting_connection_timeout,RET_NetworkFailCount)) {
-            int timetaken_total = (RET_RTCunixtime - GLOBAL_wakeTime);
-            int timetaken_connection = (RET_RTCunixtime - connectionStartTime);
-            char bytestosend[160];
-            if (turnon) {
-                snprintf(bytestosend,sizeof(bytestosend),"(%s,a:log,f:%d,t:%.1f,v:%.2f,z:TURNON,e:%d,y:%d,x:%d,s:1%s)\0",GLOBAL_defaultApi,FW_VERSION,RET_temperature,RET_voltage,timetaken_total,timetaken_connection,timetaken_gps,locString);
-            } else {
-                snprintf(bytestosend,sizeof(bytestosend),"(%s,a:log,f:%d,t:%.1f,v:%.2f,z:TURNOFF,e:%d,y:%d,x:%d,s:1%s)\0",GLOBAL_defaultApi,FW_VERSION,RET_temperature,RET_voltage,timetaken_total,timetaken_connection,timetaken_gps,locString);
-            }
-            char result[180];
-            snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytestosend, false, 2, GLOBAL_defaultApi));
+    bleStopAdvertising();
+    LowPowerTimer bleScan_t;
+    bleScan_t.start();
+    RET_settingsReceived = false;
+    uint32_t bleScan_startmillis = bleScan_t.read_ms(); uint32_t bleScan_runtime = 0;
+    if (!myble.hasInitialized()) {
+        myble.init();
+        while (!myble.hasInitialized() && bleScan_runtime < 1000) { 
+            bleScan_runtime = (bleScan_t.read_ms() - bleScan_startmillis);
         }
     }
-}
-void event_location_tx(bool failsafe) {
-    #if BLE_ENABLED
-        bleStopAdvertising();
-    #endif
-    RET_location_failsafe_seconds_count = 0; //reset failsafe count
-    RET_lastTxTime = RET_RTCunixtime;
-    //check if we have any outstanding to send
-    failed_broadcasts_tx();
-    bool selfTestResult = selfTest();
-    bool skipTX = false;
-    char bytesToSend[160];
-    
-    //Check for Nearby Location Beacons
-    memset(RET_closestLocationTag_id, 0x00, sizeof(RET_closestLocationTag_id));
-    RET_closestLocationTag_rssi = 999;
-    RET_locationTag_present = false;
-    RET_detector_present = false;
-    #if BLE_ENABLED
-        blecount = 0;
-        if (RET_setting_beacon_scan == 1 && RET_setting_location_mode != LOCATION_MODE_REALTIME) {
-            LowPowerTimer bleScan_t;
-            bleScan_t.start();
-            uint32_t bleScan_startmillis = bleScan_t.read_ms(); uint32_t bleScan_runtime = 0;
-            if (!myble.hasInitialized()) {
-                myble.init();
-                while (!myble.hasInitialized() && bleScan_runtime < 1000) { 
-                    bleScan_runtime = (bleScan_t.read_ms() - bleScan_startmillis);
-                }
-            }
-            if (myble.hasInitialized()) {
-                //Scan for 10 seconds
-                bleConfigureScan();
-                bleScan_startmillis = bleScan_t.read_ms();
-                while (bleScan_runtime < 20000 && RET_detector_present == false) {
-                    bleScan_runtime = (bleScan_t.read_ms() - bleScan_startmillis);
-                    myble.waitForEvent(); // low power wait for event
-                }
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLECount: %d",blecount);debug_exe();}
-                if (RET_locationTag_present && RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "LocationTag: %s, rssi: %d",RET_closestLocationTag_id, RET_closestLocationTag_rssi);debug_exe();}
-            }
-            bleScan_t.stop();
-            myble.gap().stopScan();
-        }
-        //see if we are in range of ble detector, if so, no need to get gps and broadcast
-        if (RET_detector_present == true && RET_setting_beacon_interval_seconds > 0) {
-            skipTX = true;
-        }
-    #endif
-    
-    if (skipTX == false || failsafe == true) {
-        //Set any network or GPS fail flags
-        if (RET_NetworkFailCount > DEFAULT_MAX_FAILED_CONNECTIONS) {RET_NetworkFailFlag = true;}
-        if (RET_GPSFailCount > DEFAULT_MAX_FAILED_GPS) {addToExceptionString("GF");}
-        //lets check to see if we've had repeated comms failings in this location, if so dont bother trying. reset by movment and failsafe
-        if (RET_NetworkFailCount <= DEFAULT_MAX_FAILED_CONNECTIONS) {
-            if (RET_NetworkFailFlag) {RET_NetworkFailFlag = false; addToExceptionString("NF");}
-            if (RET_receivedNewSettings) {RET_receivedNewSettings = false; addToExceptionString("SR");}
-            if (modem.on(RET_force2G)) {
-                char locString[70];
-                memset(locString,0x00,sizeof(locString));
-                int gpsStartTime = RET_RTCunixtime;
-                if (RET_locationTag_present) {
-                    snprintf(locString, sizeof(locString), ",l:%s.%d\0",RET_closestLocationTag_id,RET_closestLocationTag_rssi);
-                    addToExceptionString("BL");
-                } else {
-                    //check if we have moved since last post, if not use same valid gps fix if exists
-                    if (RET_motionStateOnInLocTXInterval == false && GLOBAL_have_GPSlocString_prev == true) {
-                        memcpy(locString, GLOBAL_GPSlocString_prev, sizeof(locString));
-                        addToExceptionString("P");
-                    } else {
-                        GLOBAL_have_GPSlocString_prev = false;
-                        memcpy(locString, modem.getLocation(RET_setting_location_accuracy, RET_setting_location_timeout, RET_GPSFailCount, RET_NetworkFailCount), sizeof(locString));
-                    }
-                }
-                int timetaken_gps = (RET_RTCunixtime - gpsStartTime);
-                
-                //SEND DATA
-                int connectionStartTime = RET_RTCunixtime;
-                
-                if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,RET_setting_connection_timeout,RET_NetworkFailCount)) {
-                    int timetaken_total = (RET_RTCunixtime - GLOBAL_wakeTime) + 10; //add 10 for avg ussd response time.
-                    int timetaken_connection = (RET_RTCunixtime - connectionStartTime);
-                    //Check if we should wait for settings back
-                    bool getSettings = true;
-                    //work out if we need to get settings back
-                    if (  ((RET_RTCunixtime - RET_SettingsGotAt)/3600) < RET_setting_minimumupdate_hrs  ) { getSettings = false; timetaken_total -= 10;} //remove the extra 10 seconds from times
-                    char bytesToSend[160];
-                    //snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:loc,f:%d,t:%.1f,v:%.2f,z:LOC-%s,e:%d,y:%d,x:%d,c:1,s:%d%s)\0",GLOBAL_defaultApi,FW_VERSION,temperature,voltage,GLOBAL_exceptionString,timetaken_total,timetaken_connection,timetaken_gps,getSettings,locString);
-                    snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:loc,f:%d,t:%.0f,n:%.0f,q:%.0f,w:%.0f,v:%.1f,z:L%s,e:%d,y:%d,x:%d,j:%d,s:%d%s)\0",GLOBAL_defaultApi,FW_VERSION,RET_temperature,RET_temperature_min,RET_temperature_max,RET_humidity,RET_voltage,GLOBAL_exceptionString,timetaken_total,timetaken_connection,timetaken_gps,RET_motionStateOnInLocTXInterval,getSettings,locString);
-                    char result[180];
-                    snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytesToSend, getSettings, 2, GLOBAL_defaultApi));
-                    //if (result != "err") {
-                    if (strcmp(result, "err") != 0) {
-                        if (getSettings) {
-                            if (saveSettings(result) == false){sendErrorLog("ERR-LOC-IR");}
-                        }
-                    } else {
-                        sendErrorLog("ERR-LOC-NR");
-                    }
-                }
-                
-                /*
-                if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,RET_setting_connection_timeout,RET_NetworkFailCount)) {
-                    int timetaken_total = (RET_RTCunixtime - GLOBAL_wakeTime) + 10; //add 10 for avg ussd response time.
-                    int timetaken_connection = (RET_RTCunixtime - connectionStartTime);
-                    //Check if we should wait for settings back
-                    bool getSettings = true;
-                    //work out if we need to get settings back
-                    if (  ((RET_RTCunixtime - RET_SettingsGotAt)/3600) < RET_setting_minimumupdate_hrs  ) { getSettings = false; timetaken_total -= 10;} //remove the extra 10 seconds from times
-                    snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:loc,f:%d,t:%.0f,n:%.0f,q:%.0f,w:%.0f,v:%.1f,z:L%s,e:%d,y:%d,x:%d,j:%d,s:%d%s)\0",GLOBAL_defaultApi,FW_VERSION,RET_temperature,RET_temperature_min,RET_temperature_max,RET_humidity,RET_voltage,GLOBAL_exceptionString,timetaken_total,timetaken_connection,timetaken_gps,RET_motionStateOnInLocTXInterval,getSettings,locString);
-                    //snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:loc,f:%d,t:%.0f,v:%.1f,z:L-%s,e:%d,y:%d,x:%d,j:%d,s:%d%s)\0",GLOBAL_defaultApi,FW_VERSION,RET_temperature,RET_voltage,GLOBAL_exceptionString,timetaken_total,timetaken_connection,timetaken_gps,RET_motionStateOnInLocTXInterval,getSettings,locString);
-                    char result[180];
-                    snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytesToSend, getSettings, GLOBAL_defaultApi));
-                    if (getSettings == true && strcmp(result, "sendokrecfail") == 0) {
-                        //send ok but receive fail
-                        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"USSD Send Ok but Rec fail");debug_exe();}
-                        sendErrorLog("ERR-LOC-NR");
-                    } else if (strcmp(result, "sendok") == 0) {
-                        //do nothing
-                    } else if (strcmp(result, "sendfail") == 0) {
-                        if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"USSD Send Fail");debug_exe();}
-                        //need to log for retry
-                    } else {
-                        if (getSettings) {
-                            if (saveSettings(result) == false){sendErrorLog("ERR-LOC-IR");}
-                        }
-                    }
-                }
-                */
-            }
+    if (myble.hasInitialized()) {
+        bleConfigureScan();
+        bleScan_startmillis = bleScan_t.read_ms();
+        while (bleScan_runtime < DEFAULT_SETTINGSSCANTIME_MS && RET_settingsReceived == false) {
+            bleScan_runtime = (bleScan_t.read_ms() - bleScan_startmillis);
+            myble.waitForEvent(); // low power wait for event
         }
     }
-    //RESETS
-    RET_motionStateOnInLocTXInterval = false;
-    setEventTime_Location();
-}
-void event_activity_tx() {
-    #if BLE_ENABLED
-        bleStopAdvertising();
-    #endif
-    //check if we have any outstanding to send
-    failed_broadcasts_tx();
-    //check we have something to send...
-    bool sendok = false;
-    if (RET_motionTotalActivityHoursSincePost > 0.0f && RET_setting_activity_mode > 0) {
-        //Build data to send
-        char bytesToSend[160];
-        if (RET_setting_activity_mode == 1) {
-            snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:act,t:%u,r:%.2f,h:%.2f)\0",GLOBAL_defaultApi,RET_motionFrameStart,RET_motionTotalActivityHoursSincePost,RET_motionTotalActivityHours);
-        } else if (RET_setting_activity_mode == 2) {
-            snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:act,e:%s,t:%u,r:%.2f)\0",GLOBAL_defaultApi,RET_activityData,RET_motionFrameStart,RET_motionTotalActivityHoursSincePost);
-        }
-        if (RET_NetworkFailCount <= DEFAULT_MAX_FAILED_CONNECTIONS) {
-            if (modem.on(RET_force2G)) {
-                //SEND DATA
-                if (modem.registerOnNetwork(2,RET_setting_connection_timeout,RET_NetworkFailCount)) {
-                    char result[100];
-                    bool getResponse = false;
-                    snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytesToSend, getResponse, 2, GLOBAL_defaultApi));
-                    if (strcmp(result, "sendok") == 0) {
-                        sendok = true;
-                        //if(!RET_debug) {sendok = true;} //FOR TESTING
-                    }
-                }
-            }
-        }
-        //If send failed then log it for retry - only need to do this for mode 2, for mode the time just increments
-        if (sendok == true) {
-            if (RET_setting_activity_mode == 1) {
-                RET_motionTotalActivityHoursSincePost = 0.0f;
-                if (RET_haveSettings) { RET_motionFrameStart = RET_RTCunixtime; }
-            } else if (RET_setting_activity_mode == 2) {
-                RET_motionTotalActivityHoursSincePost = 0.0f;
-                if (RET_haveSettings) { RET_motionFrameStart = RET_RTCunixtime; }
-            }
-        } else if (sendok == false) {
-            if (RET_setting_activity_mode == 1) {
-                //do nothing
-            } else if (RET_setting_activity_mode == 2) {
-                failed_broadcast_log(bytesToSend);
-                RET_motionTotalActivityHoursSincePost = 0.0f;
-                if (RET_haveSettings) { RET_motionFrameStart = RET_RTCunixtime; }
-            }
-        }
-    }
-    //RESETS
-    memset(RET_activityData,0x00,sizeof(RET_activityData));
-    setEventTime_Activity();
+    bleScan_t.stop();
+    myble.gap().stopScan();
+    LED1off();
 }
 
 //------------------------------------------------------------------------------
 // STATE ENGINE
 //------------------------------------------------------------------------------ 
 void mainStateEngine() {
-    switch(RET_state) {
-        case STATE_SETUP :
-        { //need the curlies to avoid "transfer of control bypass init error warning"
-            RET_busy = true;
-            //check that we havent run setup too recently
-            time_t setupRunAt_delta = (RET_RTCunixtime - RET_SetupRunAt);
-            if (RET_SetupRunAt == 0 || setupRunAt_delta >= ONEDAYINSECONDS) {
-                updateBatteryV();
-                if (event_setup(false)) {
-                    // All good
-                    setState(STATE_NORMAL);
-                } else {
-                    RET_eventTime_wakeFromDormant = (RET_RTCunixtime + ONEDAYINSECONDS);
-                    setState(STATE_DORMANT);
-                    if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"SETUP FAILED:DORMANT until %u\n",RET_eventTime_wakeFromDormant);debug_exe();}
-                }
-            } else {
-                time_t setupCanRunAt = (RET_RTCunixtime + (ONEDAYINSECONDS - setupRunAt_delta));
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"SETUP CAN RUN AGAIN @%u \n",setupCanRunAt);debug_exe();}
-            }
-            RET_busy = false;
-            break;
-        }
-        case STATE_NORMAL :
-        {   
-            RET_busy = true;
-            //LOCATION EVENT
-            bool run_location_tx = false;
-            switch (RET_setting_location_mode) {
-                case 1: //INTERVAL POST
-                    if(RET_RTCunixtime >= RET_eventTime_location_tx && RET_eventTime_location_tx > 0) { run_location_tx = true; }
-                    break;
-                case 2: //INTERVAL POST WITH MOTION CHECK
-                    if(RET_RTCunixtime >= RET_eventTime_location_tx && RET_eventTime_location_tx > 0) { 
-                        if (RET_motionStateOnInLocTXInterval == true || RET_motionState == true) {
-                            run_location_tx = true;
-                        } else {
-                            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "Skip TX no mot\n");debug_exe();}
-                        }
-                    }
-                    break;
-                case 3: //POST ON STOP MOTION
-                    if (GLOBAL_motionStopFlagTriggered) { GLOBAL_motionStopFlagTriggered = false; run_location_tx = true; }
-                    break;
-            }
-            if(run_location_tx == false && RET_location_failsafe_seconds_count >= RET_location_failsafe_seconds_max) { 
-                RET_NetworkFailCount = 0; //reset to ensure connection
-                RET_GPSFailCount = 0; // reset to ensure gps try
-                addToExceptionString("FS");
-                updateBatteryV();
-                event_location_tx(true);
-            } else {
-                if (run_location_tx) { 
-                    updateBatteryV(); 
-                    event_location_tx(false); 
-                }
-            }
-            
-            //ACTIVITY EVENT
-            bool run_activity_tx = false;
-            if(RET_RTCunixtime >= RET_eventTime_activity_tx && RET_eventTime_activity_tx > 0) {
-                if (RET_setting_activity_mode == 1 && RET_motionTotalActivityHoursSincePost > 0.0f) {
-                    run_activity_tx = true;
-                }
-                if (RET_setting_activity_mode == 2 && strlen(RET_activityData) > 1) {
-                    run_activity_tx = true;
-                }
-            }
-            //If in sendevent mode, check if buffer is close to full, if so send
-            if (RET_setting_activity_mode == 2 && strlen(RET_activityData) > (ACTIVITY_BUFFERSIZE-20)) { run_activity_tx = true; }
-            if (run_activity_tx) { event_activity_tx(); }
-            
-            RET_busy = false;
-            break;
-        }
-        case STATE_DORMANT :
-        {
-            RET_busy = true;
-            if (RET_RTCunixtime >= RET_eventTime_wakeFromDormant) {
-                if (RET_haveSettings) {
-                    setState(STATE_NORMAL); 
-                } else {
-                    setState(STATE_SETUP); 
-                }
-            }
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"STATE:DORMANT until %u  Prev S:%d\n",RET_eventTime_wakeFromDormant,RET_state_prev);debug_exe();}
-            RET_busy = false;
-            break;
-        }
-        case STATE_BUTTONPRESS1 :
-        {
-            RET_busy = true;
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON PRESS 1\n");debug_exe();}
-            updateBatteryV();
-            if (RET_voltage < 2.5f) {
-                LED1blink(3,500);
-            } else if (selfTest() == false){
-                LED1blink(4,500);
-            } else {
-                if(RET_state_prev == STATE_DORMANT) {
-                    LED1on(500);
-                } else if (RET_state_prev == STATE_NORMAL) {
-                    LED1blink(2,500);
-                }
-            }
-            if (RET_state_prev != STATE_NORMAL || RET_state_prev != STATE_DORMANT) {
-                setState(STATE_NORMAL);
-            } else {
-                setState(RET_state_prev);
-            }
-            dumpSettings();
-            RET_busy = false;
-            break;
-        }
-        case STATE_BUTTONPRESS3 :
-        {
-            RET_busy = true;
-            if(RET_state_prev == STATE_DORMANT || RET_state_prev == STATE_NORMAL) {
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON PRESS 3\n");debug_exe();}
-                LED1blink(3,500);
-                LED1on(0);
-                updateBatteryV();
-                event_setup(true);
-                LED1off();
-            }
-            setState(STATE_NORMAL); //turns device back on
-            RET_busy = false;
-            break;
-        }
-        case STATE_BUTTONPRESS5 :
-        {
-            RET_busy = true;
-            if(RET_state_prev == STATE_DORMANT || RET_state_prev == STATE_NORMAL) {
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON PRESS 5\n");debug_exe();}
-                LED1blink(5,500);
-                LED1on(0);
-                updateBatteryV();
-                event_location_tx(false);
-                LED1off();
-            }
-            setState(STATE_NORMAL); //turns device back on
-            RET_busy = false;
-            break;  
-        }
-        case STATE_TURNOFF :
-        {
-            RET_busy = true;
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON HOLD \n");debug_exe();}
-            RET_eventTime_wakeFromDormant = (RET_RTCunixtime + THREEDAYSINSECONDS);
-            setState(STATE_DORMANT);
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"TURNING OFF\n");debug_exe();}
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"STATE:DORMANT until %u\n",RET_eventTime_wakeFromDormant);debug_exe();}
-            LED1on(5000);
-            //event_turnonofflog_tx(false);
-            RET_busy = false;
-            break;
-        }
-        case STATE_TURNON :
-        {
-            RET_busy = true;
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON HOLD \n");debug_exe();}
-            if (RET_haveSettings) {
-                setState(STATE_NORMAL);
-            } else {
-                setState(STATE_SETUP);
-            }
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"TURNING ON\n");debug_exe();}
-            LED1blink(20,100);
-            RET_busy = false;
-            break;
-        }
-        case STATE_SCORCHEDEARTH :
-        {
-            RET_busy = true;
-            if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"SCORCHED EARTH - RESETTING");debug_exe();}
-            setState(STATE_SETUP); //this wont be used but just incase to kick it out of this state
-            read_app_data_from_flash(&app_data);
-            app_data.current_firmware_version = 0;
-            app_data.target_firmware_version = 0;
-            write_app_data_to_flash(&app_data);
-            system_reset();
-            RET_busy = false;
-            break;
-        }
-        default :
-        {
-            setState(STATE_SETUP);
+    if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "MainStateEngine");debug_exe();}
+    
+    if (EVENT_buttonPress) {
+        if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_ButtonPress");debug_exe();}
+        EVENT_buttonClear_time = (RET_RTCunixtime + EVENT_buttonClear_interval);
+        RET_setting_beacon_interval_ms_active = DEFAULT_BEACON_INTERVAL_FAST_MS;
+        RET_BLEpacketUpdate = true;
+        EVENT_buttonPress = false;
+    }
+    
+    if (EVENT_motionClear) {
+        if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_MotionClear");debug_exe();}
+        EVENT_motionClear_time = 0;
+        RET_motionState = false;
+        RET_impactState = false;
+        RET_BLEpacketUpdate = true;
+        EVENT_motionClear = false;
+    }
+    
+    if (EVENT_buttonClear) {
+        if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_ButtonClear");debug_exe();}
+        EVENT_buttonClear_time = 0;
+        RET_buttonPressed = false;
+        RET_buttonPressCount = 0;
+        RET_setting_beacon_interval_ms_active = RET_setting_beacon_interval_ms; //reset back to normal broadcast rate
+        RET_BLEpacketUpdate = true;
+        EVENT_buttonClear = false;
+    }
+    
+    if (EVENT_battery) {
+        if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_Battery");debug_exe();}
+        EVENT_battery_time = (RET_RTCunixtime + EVENT_battery_interval);
+        updateBatteryV();
+        RET_BLEpacketUpdate = true;
+        EVENT_battery = false;
+    }
+    
+    if (EVENT_temperature) {
+        if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_Temperature");debug_exe();}
+        EVENT_temperature_time = (RET_RTCunixtime + EVENT_temperature_interval);
+        RET_BLEpacketUpdate = true;
+        EVENT_temperature = false;
+        //get temperature TODO - only update ble if different to last
+    }
+    
+    if (EVENT_humidity) {
+        if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_Humidity");debug_exe();}
+        EVENT_humidity_time = (RET_RTCunixtime + EVENT_humidity_interval);
+        RET_BLEpacketUpdate = true;
+        EVENT_humidity = false;
+        //get humidity TODO - only update ble if different to last
+    }
+    
+    if (EVENT_settingsScan) {
+        if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_SettingsScan");debug_exe();}
+        EVENT_settingsScan_time = (RET_RTCunixtime + EVENT_settingsScan_interval);
+        EVENT_settingsScan = false;
+        settingsScan();
+    }
+    
+    if (EVENT_uwbScan) {
+        if(debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_uwbScan");debug_exe();}
+        EVENT_uwbScan_time = (RET_RTCunixtime + EVENT_uwbScan_interval);
+        EVENT_uwbScan = false;
+    }
+        
+    //BLE START OR UPDATE
+    if (RET_bleBroadcasting == false) {
+        myble.init(bleSetupAdvertising);
+        if (myble.hasInitialized()) {
+            if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE Start");debug_exe();}
+            bleUpdateAndAdvertise();
         }
     }
+    if (RET_BLEpacketUpdate == true) {
+        if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE Update only");debug_exe();}
+        bleUpdateAndAdvertise();
+    }    
+    
+    //END
+    RET_haveEventsToRun = false;
 }
 
 //------------------------------------------------------------------------------
@@ -1504,121 +550,43 @@
     LED1off();
     ThisThread::sleep_for(2000); //Initial pause, this is needed for softdevice to init, dont remove!! If we dont have this we get crashes
     watchdog.configure(400.0); //6.6 mins //Do not set to less than 4500ms or can cause issues with softdevice
-    modem.off(false);
     RTCticker.attach(&RTCtick, 1.0);
     LPtimer.start();
     button.fall(&buttonPress);
     button.rise(&buttonRelease);
-    read_app_data_from_flash(&app_data);
-    dumpSettings();
-    
-    //CHECK IF THIS IS RESET
-    //0x00000008 == lock up //0x00000004 == soft reset  //0x00000002 == watchdog  //0x00000001 == button/hardreset 
-    if (NRF_POWER->RESETREAS != 0xffffffff) {
-        RET_coldBoot = 1;
-        switch(NRF_POWER->RESETREAS) {
-            case 0x00000001  :
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"RR:HW\n");debug_exe();}
-                addToExceptionString("RH");
-            break;
-            case 0x00000002  :
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"RR:WD\n");debug_exe();}
-                addToExceptionString("WD");
-            break;
-            case 0x00000004  :
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"RR:SW\n");debug_exe();}
-                addToExceptionString("RS");
-            break;
-            case 0x00000008  :
-                if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"RR:LU\n");debug_exe();}
-                addToExceptionString("RL");
-            break;            
-        }
-        NRF_POWER->RESETREAS = 0xffffffff;
-    }
-    
-    //CHECK FOR FIRST BOOT
-    if (RET_coldBoot == 1) {  
-        memset(RET_activityData,0x00,sizeof(RET_activityData));
-        lis3dh_configureForSleep(DEFAULT_MOTION_G,DEFAULT_IMPACT_G);
-        updateBatteryV();
-        if (RET_voltage < 2.5f) { LED1errorCode(10,2);}
-        addToExceptionString("FR");
-    }
+    //read_app_data_from_flash(&app_data);
+    firstRun();
     
     //MAIN LOOP
     while(true) {
         RET_asleep = false;
-        watchdogKick();
-        updateTemperatures();
-        resetSessionVars();
-        healthCheck(); //this must be after resetGlobals
-        GLOBAL_wakeTime = RET_RTCunixtime;
-        
-        //check and log motion
-        if (RET_state == STATE_NORMAL || RET_state == STATE_SETUP) { 
-            if (checkMotion() == true) { //if motionstate is true, then reset network and gps fail counts, so that they are not skipped
-                RET_NetworkFailCount = 0;
-                RET_GPSFailCount = 0;
-            }
-        }
+        LED1on(20);
         
-        //MAIN LOGIC
-        if(RET_debug){
-            if (RET_state != 99) {
-                debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "F:%d, S:%d, SET:%d, MF:%d, MS:%d, MTX:%d, %u, L:%u, FSC:%u FSM:%u, FST:%u, A:%u", FW_VERSION, RET_state, RET_haveSettings, RET_motionTriggeredinFrame, RET_motionState, RET_motionStateOnInLocTXInterval, RET_RTCunixtime,RET_eventTime_location_tx,RET_location_failsafe_seconds_count,RET_location_failsafe_seconds_max,RET_eventTime_location_failsafe_tx,RET_eventTime_activity_tx);debug_exe();
-                debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "ACT M:%d, HsP:%.2f, Ht:%.2f, D:%s",RET_setting_activity_mode,RET_motionTotalActivityHoursSincePost,RET_motionTotalActivityHours,RET_activityData);debug_exe();
-            } else {
-                debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "F:%d, S:%d, WAKE@:%u\n", FW_VERSION, RET_state, RET_eventTime_wakeFromDormant);debug_exe();
-            }
-            if (RET_coldBoot == false && RET_RTCunixtime > RET_debug_offat) {
-                debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"DEBUGGING OFF\n");debug_exe();
-                RET_debug = false;
-            }
-        }
-
         //STATE ENGINE
         mainStateEngine();
         
         //LOG FIRST RUN - BOOTLOADER COMMS
         if (RET_coldBoot) {
-            recordFirmwareAsValid();
+            //recordFirmwareAsValid();
             RET_coldBoot = 0;
         }
         
-        //CONFIGURE BLE BEACON BROADCAST
-        #if BLE_ENABLED
-            //see if we are in range of ble detector, if so, no need to get gps and broadcast
-            if (RET_setting_beacon_interval_seconds > 0 && RET_pf_identifier[0] != 0x00 && RET_pf_identifier[1] != 0x00 && RET_pf_identifier[2] != 0x00) {
-                if (RET_bleBroadcasting == false) {
-                    if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE init...");debug_exe();}
-                    myble.init(bleSetupAdvertising);
-                    if (myble.hasInitialized()) {
-                        if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "OK");debug_exe();}
-                        bleUpdateAndAdvertise();
-                    } else {
-                        if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "FAIL");debug_exe();}
-                    }
-                } else {
-                    if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE update");debug_exe();}
-                    bleUpdateAndAdvertise();
-                }
-            } else {
-                if (RET_bleBroadcasting == true) bleStopAdvertising();
+        //DEBUGGING OFF TIMER
+        if(RET_debug){
+            if (RET_RTCunixtime > RET_debug_offat) {
+                debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"DEBUGGING OFF\n");debug_exe();
+                RET_debug = false;
             }
-        #endif
-        
+        }
+                
         //PRE-SLEEP ACTIONS
-        RET_location_failsafe_seconds_count += (DEFAULT_SLEEP_FRAME / 1000);
-        memset(GLOBAL_exceptionString,0x00,sizeof(GLOBAL_exceptionString));
-        LED1off();
-        modem.off(GLOBAL_modemOn); //HARD OR SOFT SHUT DOWN - DEPENDING ON modemOn state
-        if (GLOBAL_needToConfigureLis3dh) { lis3dh_configureForSleep(RET_setting_motion_g,RET_setting_impact_g); }
+        //if (GLOBAL_needToConfigureLis3dh) { lis3dh_configureForSleep(RET_setting_motion_g,RET_setting_impact_g); }
+        watchdogKick();
+        //SLEEP
         nrf_configureForSleep();
         NRFuart_uninit();
-        watchdogKick();
-        //SLEEP
         RET_asleep = true;
+        LED1off();
         mainthread.wait(DEFAULT_SLEEP_FRAME);
     }
 }
\ No newline at end of file
--- a/main.h	Fri Aug 09 14:22:21 2019 +0000
+++ b/main.h	Thu Feb 13 00:57:06 2020 +0000
@@ -16,34 +16,23 @@
 //------------------------------------------------------------------------------
 //FW DETAILS
 //------------------------------------------------------------------------------ 
-#define FW_VERSION          35
-//#define SKU                 "GPSPLUSDEV"
-#define SKU                 "GPSPLUS"
+#define FW_VERSION          1
+#define SKU                 "UWBBEACON"
 #define HW_MAJORREVISION    "001"
 
 //OPTIONS
 #define USE_NRF_TEMP_SENSOR                 false
-#define BLE_ENABLED                         true
 
 //DEFAULT VELUES
-#define DEFAULT_SLEEP_FRAME                 30000
-#define DEFAULT_FORCE2G                     false
-#define DEFAULT_LOCATION_MODE               1
-#define DEFAULT_LOCATION_ACCURACY           1  // 0 = no location, 1 = cl only, 2 = gps then cl
-#define DEFAULT_LOCATION_TX_INTERVAL_MINS   1440
-#define DEFAULT_LOCATION_TX_FAILSAFE_HRS    168
-#define DEFAULT_LOCATION_TIMEOUT            120
+#define DEFAULT_SLEEP_FRAME                 120000
 #define DEFAULT_MOTION_G                    7
 #define DEFAULT_MOTION_START_SECONDS        120
 #define DEFAULT_MOTION_STOP_SECONDS         120
 #define DEFAULT_IMPACT_G                    127
-#define DEFAULT_CONNECTION_ATTEMPTS         1
-#define DEFAULT_CONNECTION_TIMEOUT          140
-#define DEFAULT_MAX_FAILED_CONNECTIONS      3 //max number of failed connections before device stops broadcasting until movement detected
-#define DEFAULT_MAX_FAILED_GPS              3 //max number of failed gps searches before device stops trying gps until movement detected
-#define DEFAULT_MAX_MODEMBROWNOUTS          2
-#define DEFAULT_BEACON_INTERVAL_SECONDS     10
+#define DEFAULT_BEACON_INTERVAL_MS          3000
+#define DEFAULT_BEACON_INTERVAL_FAST_MS     100
 #define DEFAULT_BEACON_POWER                4 //(accepted values are -40, -30, -20, -16, -12, -8, -4, 0, and 4 dBm)
+#define DEFAULT_SETTINGSSCANTIME_MS         10000
 
 //CONSTS
 #define ONEDAYINSECONDS                     86400
@@ -51,11 +40,14 @@
 #define SEVENDAYSINSECONDS                  604800
 #define TENDAYSINSECONDS                    864000
 
-//MODES
-#define LOCATION_MODE_INTERVAL              1
-#define LOCATION_MODE_INTERVAL_MOTION       2
-#define LOCATION_MODE_INTELLIGENT           3
-#define LOCATION_MODE_REALTIME              4
+//DEFAULT EVENT TIMES IN SECONDS
+#define DEFAULT_INTERVAL_MOTIONCLEAR        120
+#define DEFAULT_INTERVAL_BUTTONCLEAR        20
+#define DEFAULT_INTERVAL_BATTERY            ONEDAYINSECONDS
+#define DEFAULT_INTERVAL_TEMPERATURE        60
+#define DEFAULT_INTERVAL_HUMIDITY           120
+#define DEFAULT_INTERVAL_SETTINGSSCAN       60
+
 
 //DEFINES
 #define ACTIVITY_BUFFERSIZE                 100
@@ -67,15 +59,12 @@
 #include "mbed.h"
 //#include "nrf_soc.h"
 #include "board.h"
-#if BLE_ENABLED 
-    #include "ble/BLE.h" 
-#endif
+#include "ble/BLE.h" 
+
 //------------------------------------------------------------------------------
 //peripheral Libraries
 //------------------------------------------------------------------------------
 #include "WatchdogTimer.h"
-#include "LIS3DH.h"
-#include "SI7060.h"
 #include "acd_nrf52_saadc.h"
 
 //------------------------------------------------------------------------------
@@ -84,16 +73,11 @@
 #include "NRFuart.h"
 #include "app_data.h"
 #include "states.h"
-#include "common.h"
-#include "sensors.h"
-#include "modem.h"
+#include "LED.h"
 
 //BLE SERVICE IDS
-#define BLE_SERVICEID_GPSPLUS               0xfb10
-#define BLE_SERVICEID_PFDETECTOR1           0x4e96
-#define BLE_SERVICEID_PFBEACON1             0xfe9a //ESTIMOTE
-#define BLE_SERVICEID_BT04                  0xcbff //TZBT04 Temp/humid
-#define BLE_SERVICEID_PFBEACON2             0xfb20
+#define BLE_SERVICEID_PFDETECTOR2           0xfb40
+#define BLE_SERVICEID_UWBBEACON             0xfb50
 
 //------------------------------------------------------------------------------
 //Global macros
@@ -110,16 +94,9 @@
 extern bool GLOBAL_motionFlagTriggered;
 extern bool GLOBAL_debugLED;
 extern bool GLOBAL_needToConfigureLis3dh;
-extern bool GLOBAL_registeredOnNetwork;
-extern bool GLOBAL_modemOn;
 extern bool GLOBAL_LEDSequenceinProgress;
 extern time_t GLOBAL_RTCunixtime;
-extern time_t GLOBAL_wakeTime;
 extern char GLOBAL_debug_buffer[DEBUG_BUFFERSIZE];
-extern char GLOBAL_GPSlocString_prev[70];
-extern bool GLOBAL_have_GPSlocString_prev;
-extern char GLOBAL_exceptionStringRetainedUntilSuccess[10];
 //FUNCS
 extern void watchdogKick();
-extern void addToExceptionString(char* value);
 #endif
\ No newline at end of file
--- a/mbed_app.json	Fri Aug 09 14:22:21 2019 +0000
+++ b/mbed_app.json	Thu Feb 13 00:57:06 2020 +0000
@@ -23,8 +23,6 @@
             "platform.sys-stats-enabled": false
         },
         "NRF52_DK": {
-            "target.mbed_app_start": "0x3E000",
-            "target.bootloader_img": null,
             "target.OUTPUT_EXT": "bin",
             "target.uart_hwfc": 0,
             "nordic.uart_0_fifo_size": 1024,
--- a/modem.cpp	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,765 +0,0 @@
-#include "modem.h"
-
-char ATinBuffer[200];
-
-Modem::Modem(PinName pwrkey, PinName vreg_en, PinName w_disable): _pwrkey(pwrkey), _vreg_en(vreg_en), _w_disable(w_disable)
-{
-    //initially setup control lines as no pull to reduce power consumption, they will be correctly configured by .on() and .off()
-    nrf_gpio_cfg_input(PN_GSM_PWR_KEY, NRF_GPIO_PIN_NOPULL);
-    nrf_gpio_cfg_input(PN_GSM_WAKE_DISABLE, NRF_GPIO_PIN_NOPULL);
-}
-
-void Modem::ATsendCMD(char* cmd) 
-{ 
-    NRFuart_flush();
-    NRFuart_puts(cmd);
-    NRFuart_puts("\r");
-}
-
-bool Modem::ATwaitForWord(char* word, uint32_t timeout) 
-{
-    int targetIndex = 0;
-    bool havefullmatch = false;
-    char captured[32];
-    memset(captured,0,sizeof(captured));
-    Timer t;
-    t.start();
-    uint32_t startmillis = t.read_ms();
-    uint32_t runtime = 0;
-    while(!havefullmatch && runtime < timeout) {
-        runtime = (t.read_ms() - startmillis);
-        if(NRFuart_readable()) { 
-            char c = NRFuart_getc();
-            if (c != word[targetIndex]) { //no match, reset
-                targetIndex = 0; 
-            }
-            if (c == word[targetIndex]) { //we have a match
-                captured[targetIndex] = c;
-                targetIndex ++;
-                //check for full match
-                if (  strcmp(word, captured) == 0  ) {
-                    havefullmatch = true;
-                }
-            }
-        }
-    }
-    t.stop();
-    t.reset();
-    if (havefullmatch) {
-        return true;
-    } else {
-        return false;
-    }
-}
-
-/*
-bool Modem::ATwaitForWordOrBO(char* word1, uint32_t timeout)
-{
-      char* word2 = "RDY\r";
-      int targetIndex1 = 0;
-      int targetIndex2 = 0;
-      bool havefullmatch1 = false;
-      bool havefullmatch2 = false;
-      char captured[32];
-      memset(captured,0,sizeof(captured));
-      Timer t;
-      t.start();
-      uint32_t startmillis = t.read_ms();
-      uint32_t runtime = 0;
-      while((!havefullmatch1 || !havefullmatch2) && runtime < timeout)
-      {
-          runtime = (t.read_ms() - startmillis);
-          if(NRFuart_readable())
-           {
-              char c = NRFuart_getc();
-              if (c != word1[targetIndex1])
-               { //no match, reset
-                  targetIndex1 = 0;
-              }
-              
-              if (c != word2[targetIndex2])
-               { //no match, reset
-                  targetIndex2 = 0;
-              }          
-              
-              if (c == word1[targetIndex1])
-               { //we have a match
-                  captured[targetIndex1] = c;
-                  targetIndex1 ++;
-                  //check for full match
-                  if (  strcmp(word1, captured) == 0  )
-                   {
-                      havefullmatch1 = true;
-                  }
-              }
-              
-               if (c == word2[targetIndex2])
-               { //we have a match
-                  captured[targetIndex2] = c;
-                  targetIndex2 ++;
-                  //check for full match
-                  if (  strcmp(word2, captured) == 0  )
-                   {
-                      havefullmatch2 = true;
-                  }
-              }
-          }
-      }
-      t.stop();
-      t.reset();
-      
-      //if bool response
-      if (havefullmatch1) {
-        return true;
-      }
-      else {
-        addToExceptionStringRetainedUntilSuccess("BO");
-        return false;
-      }
-      
-    
-      //if int response
-      if (havefullmatch1) {
-            return 1;
-      }
-      else if(havefullmatch2) {
-            return 2;
-      }
-      else {
-            return 0;
-      }
-}
-*/
-
-
-bool Modem::ATgetResponse(char terminator, uint32_t timeout) 
-{
-    memset(ATinBuffer,0x00,sizeof(ATinBuffer));
-    int charindex = 0;
-    bool gotTerminator = false;
-    Timer t;
-    t.start();
-    uint32_t startmillis = t.read_ms();
-    uint32_t runtime = 0;
-    while(!gotTerminator && runtime < timeout) {
-        runtime = (t.read_ms() - startmillis);
-        if(NRFuart_readable()) { 
-            char c = NRFuart_getc();
-            if (c == terminator) {
-                gotTerminator = true;
-            } else {
-                ATinBuffer[charindex] = c;
-                charindex++;
-            }
-        }
-    }
-    t.reset();
-    t.stop();
-    ATinBuffer[charindex] = '\n'; //make sure we end with whitespace lf
-    return gotTerminator;
-}
-
-
-bool Modem::on(bool force2G) 
-{
-    NRFuart_init_nohwfc();
-    
-    if (!GLOBAL_modemOn) {
-        _w_disable.input(); // this sets the modem to airplane mode
-        _vreg_en = 1;
-        ThisThread::sleep_for(200);
-        //set prwkey to output low
-        _pwrkey.output();
-        _pwrkey = 0;
-        ThisThread::sleep_for(200);
-        //set prwkey back to tri-state
-        _pwrkey.input(); 
-        
-        GLOBAL_modemOn = true;
-        
-        //CONFIGURE
-        if (ATwaitForWord("RDY",ATTIMEOUT_MED)) {
-            
-            //TURN OFF ECHO
-            ATsendCMD("ATE0");
-            ATwaitForWord("OK",ATTIMEOUT_SHORT);
-            
-            //DISABLE LOW POWER WARNING
-            //ATsendCMD("AT+QCFG=\"vbatt\",-2,3300,0");
-            //ATwaitForWord("OK",ATTIMEOUT_SHORT);
-        
-            //DISABLE LNA
-            ATsendCMD("AT+QGPSCFG=\"lnacontrol\",0");
-            ATwaitForWord("OK",ATTIMEOUT_SHORT);
-                         
-            //ENABLE AIRPLANE MODE CONTROL WITH PIN
-            ATsendCMD("AT+QCFG=\"airplanecontrol\",1");
-            ATwaitForWord("OK",ATTIMEOUT_SHORT);
-            _w_disable.output();
-            _w_disable = 0;
-                
-            if (force2G) {
-                ATsendCMD("AT+QCFG=\"nwscanseq\",1,1"); //2G priority
-                ATwaitForWord("OK",ATTIMEOUT_SHORT);
-                ATsendCMD("AT+QCFG=\"nwscanmode\",1,1"); //2G only connection
-                ATwaitForWord("OK",ATTIMEOUT_SHORT);
-            } else {
-                //PRIORITISE 2G connection (reason being uses less power in some instances and can get cell tower tri)
-                //ATsendCMD("AT+QCFG=\"nwscanseq\",1,1"); //2G priority
-                //ATsendCMD("AT+QCFG=\"nwscanseq\",2,1"); //3G priority
-                ATsendCMD("AT+QCFG=\"nwscanseq\",0,1"); //AUTO - default
-                ATwaitForWord("OK",ATTIMEOUT_SHORT);
-                ATsendCMD("AT+QCFG=\"nwscanmode\",0,1"); //AUTO
-                //ATsendCMD("AT+QCFG=\"nwscanmode\",1,1"); //2G only connection
-                //ATsendCMD("AT+QCFG=\"nwscanmode\",2,1"); //3G only connection
-                ATwaitForWord("OK",ATTIMEOUT_SHORT);
-            }
-            return true;
-        } else {
-            return false;   
-        }
-    } else {
-        return true;   
-    }
-}
-
-void Modem::off(bool soft) 
-{
-    if (GLOBAL_modemOn == true) {
-        if (soft) {
-            bool atok = false;
-            int  atoktries = 0;
-            while(atok == false && atoktries < 3) {
-                ATsendCMD("AT");
-                if (ATwaitForWord("OK\r\n",ATTIMEOUT_SHORT)) {
-                    atok = true;
-                }
-                atoktries ++;
-            }
-            if (atok == true) {
-                ATsendCMD("AT+QPOWD=0");
-                ATwaitForWord("POWERED DOWN",ATTIMEOUT_SHORT);
-            }
-        }
-        GLOBAL_modemOn = false;
-    }
-    ThisThread::sleep_for(250);
-    GLOBAL_registeredOnNetwork = false;
-    _w_disable.input(); //enable airplane mode
-    _pwrkey.input();
-    _vreg_en = 0;       //kill power to module
-    
-    //disable control pins, needed to get low power off state
-    nrf_gpio_cfg_input(PN_GSM_PWR_KEY, NRF_GPIO_PIN_NOPULL);
-    nrf_gpio_cfg_input(PN_GSM_WAKE_DISABLE, NRF_GPIO_PIN_NOPULL);
-}
-
-uint64_t Modem::getIMEI() 
-{
-    uint64_t imei = 0;
-    int tries = 0;
-    ThisThread::sleep_for(200); //needed
-    while(imei == 0 && tries < 3) { //try 3 times
-        tries ++;
-        ATsendCMD("AT+GSN");
-        if (ATwaitForWord("\r\n",ATTIMEOUT_SHORT)) {
-            if (ATgetResponse('\r',ATTIMEOUT_SHORT)) {
-                imei = atoll(ATinBuffer);
-            }
-        };
-        NRFuart_flush();
-    }
-    return imei;
-}
-
-uint64_t Modem::getCCID() 
-{
-    uint64_t ccid = 0;
-    int tries = 0;
-    ThisThread::sleep_for(200); //needed
-    while(ccid == 0 && tries < 3) { //try 3 times
-        tries ++;
-        ATsendCMD("AT+QCCID");
-        if (ATwaitForWord("+QCCID: ",ATTIMEOUT_SHORT)) {
-            if (ATgetResponse('\r',ATTIMEOUT_SHORT)) {
-                ccid = atoll(ATinBuffer);
-            }
-        };
-        NRFuart_flush();
-    }
-    return ccid;
-}
-
-char* Modem::getModemModel() 
-{
-    char* modemModel;
-    ATsendCMD("AT+GMM");
-    if (ATwaitForWord("\r",ATTIMEOUT_SHORT)) {
-        if (ATgetResponse('\r',ATTIMEOUT_SHORT)) {
-            sscanf(ATinBuffer,"%s", modemModel);
-        }
-    };
-    NRFuart_flush();
-    return modemModel;
-}
-
-bool Modem::registerOnNetwork(int maxAttempts, uint32_t timeout, uint32_t &BYREF_NetworkFailCount) 
-{
-    //CHECK WE ARE NOT ALREADY ON NETOWRK
-    if (!GLOBAL_registeredOnNetwork) {
-        int attempt = 0;
-        Timer t;
-        t.start();
-        //DISABLE AIRPLANE MODE
-        _w_disable.input();
-        while (attempt < maxAttempts) {
-            t.reset();
-            uint32_t startseconds = t.read();
-            uint32_t runtime = 0;
-            while(GLOBAL_registeredOnNetwork == false && runtime < timeout) {
-                runtime = (t.read() - startseconds);
-                ThisThread::sleep_for(1000);
-                //TURN OFF ECHO //we need this again incase of modem brown out, as it means the modems starts echoing again
-                    ATsendCMD("ATE0");
-                    ATwaitForWord("OK",ATTIMEOUT_SHORT);
-                ATsendCMD("AT+CREG?");
-                if (ATwaitForWord("+CREG: 0,5",ATTIMEOUT_VERYSHORT)) {
-                    NRFuart_flush();
-                    GLOBAL_registeredOnNetwork = true;
-                };
-                
-            }
-            attempt ++;
-            //if there are more attempt potential, then reset the modem
-            if (GLOBAL_registeredOnNetwork == false && attempt < maxAttempts) {
-                off(false);
-                ThisThread::sleep_for(1000);
-                on(false);
-            }
-        }
-        t.reset();
-        t.stop();
-    }
-    NRFuart_flush();
-    if (GLOBAL_registeredOnNetwork == true) {        
-        BYREF_NetworkFailCount = 0;
-        ThisThread::sleep_for(1000); //wait 1 seconds for things to settle
-        return true;
-    } else {
-        BYREF_NetworkFailCount ++;
-        return false;   
-    }
-}
-
-char* Modem::HTTPpost(char* url, char* message, bool getResponse, int maxAttempts) 
-{
-    bool sent = false;
-    bool criticalfail = false;
-    int attempt = 0;
-    bool gotResponse = false;
-    
-    //TRY X NUMBER OF TIMES
-    while (!sent && attempt < maxAttempts) {
-        criticalfail = false;
-        
-        //TURN OFF ECHO //we need this again incase of modem brown out, as it means the modems starts echoing again
-            ATsendCMD("ATE0");
-            ATwaitForWord("OK",ATTIMEOUT_SHORT);
-        
-        if (!criticalfail) {
-            ATsendCMD("AT+QHTTPCFG=\"contextid\",1");    
-            if (!ATwaitForWord("OK\r",ATTIMEOUT_SHORT)) criticalfail = true;
-        }
-        
-        if (!criticalfail) {
-            ATsendCMD("AT+QICSGP=1,1,\"tsiot\",\"\",\"\",0");
-            if (!ATwaitForWord("OK\r",ATTIMEOUT_SHORT)) criticalfail = true;
-        }
-        
-        if (!criticalfail) {
-            ATsendCMD("AT+QIACT=1");    
-            if (!ATwaitForWord("OK\r",ATTIMEOUT_LONG)) criticalfail = true;
-        }
-        
-        /*if (!criticalfail) {
-            ATsendCMD("AT+QIACT?");    
-            if (!ATwaitForWord("OK\r",ATTIMEOUT_SHORT)) criticalfail = true;
-        }*/
-        
-        if (!criticalfail) {
-            char URLcmd[60];
-            snprintf(URLcmd, sizeof(URLcmd), "AT+QHTTPURL=%d,80", strlen(url));
-            ATsendCMD(URLcmd);
-            if (!ATwaitForWord("CONNECT\r",ATTIMEOUT_LONG)) criticalfail = true;
-        }
-        
-        if (!criticalfail) {
-            ATsendCMD(url);
-            if (!ATwaitForWord("OK\r",ATTIMEOUT_SHORT)) criticalfail = true;
-        }
-        
-        if (!criticalfail) {
-            char POSTparams[60];
-            snprintf(POSTparams, sizeof(POSTparams), "AT+QHTTPPOST=%d,80,80", strlen(message));
-            ATsendCMD(POSTparams);
-            if (!ATwaitForWord("CONNECT\r\n",ATTIMEOUT_LONG)) criticalfail = true;
-        }
-        
-        if (!criticalfail) {
-            ATsendCMD(message);
-            if (ATwaitForWord("+QHTTPPOST: 0",ATTIMEOUT_MED)) {
-                sent = true;
-            } else {
-                criticalfail = true;
-            }
-        }
-        
-        if (!criticalfail && getResponse) {
-            ATsendCMD("AT+QHTTPREAD=80");
-            ATwaitForWord("CONNECT\r\n",ATTIMEOUT_MED);
-            ATgetResponse('\r',ATTIMEOUT_SHORT);
-            
-            if (ATwaitForWord("+QHTTPREAD: 0",ATTIMEOUT_MED)) {
-                gotResponse = true;
-            }
-        }
-        
-        NRFuart_flush();
-        attempt ++;
-    }
-    if (sent) {
-        if (getResponse == false) {
-            return "sendonly";
-        } else {
-            if (gotResponse == true) {
-                return ATinBuffer;
-            } else {
-                return "noresp";
-            }
-        }
-    } else {
-        return "err";
-    }
-}
- 
-bool Modem::USSDsend(char* message, int maxAttempts) 
-{
-    bool sent = false;
-    int attempt = 0;
-    //TRY X NUMBER OF TIMES
-    while (!sent && attempt < maxAttempts) {
-        char bytestosend[160];
-        snprintf(bytestosend, sizeof(bytestosend), "AT+CUSD=1,\"#469*%s#\"", message);
-        ATsendCMD(bytestosend);
-        if (ATwaitForWord("+CUSD: 0",ATTIMEOUT_MED)) {
-            sent = true;
-        };
-        NRFuart_flush();
-        attempt ++;
-    }
-    if (sent) {
-        return true;
-    } else {
-        return false;   
-    }
-}
-
-char* Modem::USSDreceive(int messageIndex) 
-{
-    bool received = false;
-    uint32_t timeout = ATTIMEOUT_LONG;
-    int USSDmessageIndex = 0;
-    int matchCount = 0;
-    Timer t;
-    t.start();
-    //TRY UNTIL TIMEOUT
-    uint32_t startmillis = t.read_ms();
-    uint32_t runtime = 0;
-    while(!received && runtime < timeout) {
-        runtime = (t.read_ms() - startmillis);
-        if (ATwaitForWord("+CUSD: 0",ATTIMEOUT_SHORT)) {
-            if (ATgetResponse('\r',ATTIMEOUT_SHORT)) {  
-                if ( (matchCount = sscanf(ATinBuffer,",\"%d#%[^#]",USSDmessageIndex,ATinBuffer) ) > 0 ) {
-                    if (USSDmessageIndex == messageIndex) {
-                        //NEED TO GET THIS WORKING SO WE KNOW WE ARE DEALING WITH THE RIGHT MESSAGE
-                        //MOVE THE BELOW INTO THIS IF STAEMEBNTS WHEN DONE
-                    }
-                    received = true;
-                }
-            }
-        }
-    }
-    NRFuart_flush();
-    if (received) {
-        return ATinBuffer;
-    } else {
-        return "err";
-    }
-}
-
-char* Modem::USSDmessage(char* message, bool needResponse, int maxAttempts, char* api) 
-{  
-    uint8_t messageIndex = 1;
-    bool result;
-    int messageLength = strlen(message);
-    if (messageLength > USSD_MAXLENGTH) {
-        char message_failsafe[100];
-        snprintf(message_failsafe,sizeof(message_failsafe),"(%s,a:error,z:TOOBIG,s:1,c:%d)\0",api,messageIndex);
-        result = USSDsend(message_failsafe, maxAttempts);
-    } else {
-        result = USSDsend(message, maxAttempts);
-    }
-    if (result) {
-        if (needResponse) {
-            char* response = USSDreceive(messageIndex);
-            if (strcmp(response, "err") != 0) {
-                return response;
-            } else {
-                return "sendonly";
-            }
-        } else {
-            return "ok";   
-        } 
-    } else {
-        return "err";   
-    }
-}
-
-/*
-bool Modem::USSDsend(char* message) 
-{
-    bool sent = false;
-    int attempt = 0;
-    
-    //CHECK FOR AT OK
-    bool atok = false;
-    int  atoktries = 0;
-    while(atok == false && atoktries < 3) {
-        ATsendCMD("AT");
-        if (ATwaitForWord("OK\r\n",ATTIMEOUT_SHORT)) {
-            atok = true;
-        }
-        atoktries ++;
-    }
-    if (!atok) return false;
-    
-    char bytestosend[160];
-    snprintf(bytestosend, sizeof(bytestosend), "AT+CUSD=1,\"#469*%s#\"", message);
-        
-    //TRY X NUMBER OF TIMES
-    //maxAttempts
-    while (!sent && attempt < 10) { //20 seconds, 100*200ms
-        //TURN OFF ECHO //we need this again incase of modem brown out, as it means the modems starts echoing again
-        ATsendCMD("ATE0");
-        ATwaitForWord("OK",ATTIMEOUT_SHORT);
-        ATsendCMD(bytestosend);
-        if (!ATwaitForWord("+CME ERROR",200)) { 
-            if (ATwaitForWord("+CUSD: 0",ATTIMEOUT_SHORT)) {
-                sent = true;
-            };
-        }
-        if (sent == false) {
-            ThisThread::sleep_for(1000);   
-        }
-        NRFuart_flush();
-        attempt ++;
-    }
-    
-    if (sent) {
-        return true;
-    } else {
-        return false;   
-    }
-}
-
-char* Modem::USSDreceive(void) 
-{
-    bool received = false;
-    uint32_t timeout = ATTIMEOUT_LONG;
-    int USSDmessageIndex = 0;
-    int matchCount = 0;
-    Timer t;
-    t.start();
-    //TRY UNTIL TIMEOUT
-    uint32_t startmillis = t.read_ms();
-    uint32_t runtime = 0;
-    while(!received && runtime < timeout) {
-        runtime = (t.read_ms() - startmillis);
-        if (ATwaitForWord("+CUSD: 0",ATTIMEOUT_SHORT)) {
-            if (ATgetResponse('\r',ATTIMEOUT_SHORT)) {  
-                if ( (matchCount = sscanf(ATinBuffer,",\"%d#%[^#]",USSDmessageIndex,ATinBuffer) ) > 0 ) {
-                    received = true;
-                }
-            }
-        }
-    }
-    NRFuart_flush();
-    t.reset();
-    t.stop();
-    if (received) {
-        return ATinBuffer;
-    } else {
-        return "err";
-    }
-}
-
-
-char* Modem::USSDmessage(char* message, bool needResponse, char* api) 
-{  
-    bool result;
-    int messageLength = strlen(message);
-    if (messageLength >= USSD_MAXLENGTH) {
-        char message_failsafe[100];
-        snprintf(message_failsafe,sizeof(message_failsafe),"(%s,a:error,z:TOOBIG,s:1)\0",api);
-        result = USSDsend(message_failsafe);
-    } else {
-        result = USSDsend(message);
-    }
-    if (result) {
-        if (needResponse) {
-            char* response = USSDreceive();
-            if (strcmp(response, "err") != 0) {
-                return response;
-            } else {
-                return "sendokrecfail";
-            }
-        } else {
-            return "sendok";
-        } 
-    } else {
-        return "sendfail";   
-    }
-}
-*/
-
-char* Modem::getLocation(uint8_t accuracy, uint16_t timeout_seconds, uint32_t &BYREF_GPSFailCount, uint32_t &BYREF_NetworkFailCount) 
-{ 
-    NRFuart_flush();
-    bool haveGPSFix = false;
-    bool haveCellFix = false;
-    float utc; float lat; float lng; float hdp; float alt; uint8_t fix; float cog; float spkm; float spkn; uint32_t date; uint8_t sat;
-    static char locDataOut[70];
-    memset(locDataOut,0x00,sizeof(locDataOut));
-    Timer t;
-    t.start();
-    uint32_t startseconds;
-    uint32_t runtime;
-    
-    //TURN OFF ECHO //we need this again incase of modem brown out, as it means the modems starts echoing again
-    ATsendCMD("ATE0");
-    ATwaitForWord("OK",ATTIMEOUT_SHORT);
-    
-    if (accuracy >= 2 && BYREF_GPSFailCount <= DEFAULT_MAX_FAILED_GPS) {
-        //TURN ON GPS
-        ATsendCMD("AT+QGPS=1");
-        ATwaitForWord("OK",ATTIMEOUT_SHORT);
-        
-        //TRY UNTIL TIMEOUT
-        uint8_t GPS_fixstage = 0;
-        uint8_t GPS_fixloopcount = 0;
-        startseconds = t.read();
-        runtime = 0;
-        
-        while(GPS_fixstage < 2 && runtime < timeout_seconds) {
-            ThisThread::sleep_for(4000); //this goes first
-            runtime = (t.read() - startseconds);
-            //TURN OFF ECHO //we need this again incase of modem brown out, as it means the modems starts echoing again
-            ATsendCMD("ATE0");
-            ATwaitForWord("OK",ATTIMEOUT_SHORT);
-            ATsendCMD("AT+QGPSLOC=2");
-            if (ATwaitForWord("+QGPSLOC: ",ATTIMEOUT_SHORT)) {
-                int matchCount = 0;
-                if (ATgetResponse('\r',ATTIMEOUT_VERYSHORT)) { 
-                    if ((matchCount = sscanf(ATinBuffer,"%f,%f,%f,%f,%f,%d,%f,%f,%f,%d,%d",&utc,&lat,&lng,&hdp,&alt,&fix,&cog,&spkm,&spkn,&date,&sat)) == 11 ) {
-                        //{“fix”:“GPS”,“sat”:“9",“lat”:“52.913254",“lng”:“-1.455289",“hdp”:“2.0",“spd”:“0.0"}                    
-                        haveGPSFix = true;
-                        GPS_fixstage = 1;
-                        GPS_fixloopcount ++;
-                        if (accuracy > 2) {
-                            if (hdp <= 1.8f) {
-                                GPS_fixstage = 2;
-                            }
-                        } else {
-                            if (GPS_fixloopcount > 2) {
-                                GPS_fixstage = 2;
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        
-        if (haveGPSFix) {
-            sprintf(locDataOut,",g:(fix:GPS,sat:%d,lat:%.5f,lng:%.5f,hdp:%.0f,spd:%.0f)\0",sat,lat,lng,hdp,spkm);
-            memset(GLOBAL_GPSlocString_prev,0x00,sizeof(GLOBAL_GPSlocString_prev));
-            memcpy(GLOBAL_GPSlocString_prev,locDataOut,sizeof(GLOBAL_GPSlocString_prev)); //save for future recall
-            GLOBAL_have_GPSlocString_prev = true;
-            BYREF_GPSFailCount = 0;
-        } else {
-            BYREF_GPSFailCount ++; 
-        }
-        
-        //TURN OFF GPS
-        ATsendCMD("AT+QGPSEND");
-        ATwaitForWord("OK",ATTIMEOUT_SHORT);
-    }
-    
-    //SHALL WE GET CELL LOCATION
-    if (!haveGPSFix && accuracy >= 1) {
-        uint16_t cellLocateTimeout = timeout_seconds;
-        if (registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,cellLocateTimeout,BYREF_NetworkFailCount)) {
-            int matchCount; char type[6]; char cellID[6]; char lac[6]; int mcc; int mnc;
-            t.reset();
-            startseconds = t.read();
-            runtime = 0;
-            while(haveCellFix == false && runtime < 20) {
-                runtime = (t.read() - startseconds);
-                //TURN OFF ECHO //we need this again incase of modem brown out, as it means the modems starts echoing again
-                ATsendCMD("ATE0");
-                ATwaitForWord("OK",ATTIMEOUT_SHORT);
-                ATsendCMD("AT+QENG=\"servingcell\"");
-                if (ATwaitForWord("+QENG: \"servingcell\",\"NOCONN\",",ATTIMEOUT_VERYSHORT)) {
-                    if (ATgetResponse('\r',ATTIMEOUT_SHORT)) {
-                        if ((matchCount = sscanf(ATinBuffer,"\"%[^\"]\",%d,%d,%[^,],%[^,]",&type,&mcc,&mnc,&lac,&cellID)) == 5 ) {
-                            sprintf(locDataOut,",h:%s.%s.%d.%d\0",cellID,lac,mcc,mnc);
-                            //sprintf(locDataOut,",h:41806.2252.234.30\0");
-                            haveCellFix = true;
-                        }
-                    }
-                }
-                ATwaitForWord("OK",ATTIMEOUT_SHORT);
-            }
-                    
-            //example from mulbs
-            /*
-            2g
-            +QENG: "servingcell","NOCONN","2G",234,30,8CC,A34E,20,668,0,-80,0,5,4,26,26,1,-,-,-,-,-,-,-,-,-,"-"
-            3g
-            +QENG: "servingcell","NOCONN","3G",234,20,8A,CE735F,10588,52,-97,-99,11,25,16,128,-,-,-,-,-,"-",-
-            +QENG: "neighbourcell","2G",234,30,8CC,A34D,20,656,-89,17,17,0,0
-            +QENG: "neighbourcell","2G",234,30,8CC,678,61,686,-104,2,2,0,0
-            +QENG: "neighbourcell","2G",234,30,8CC,4303,32,676,-104,2,2,0,0
-            +QENG: "neighbourcell","2G",234,30,8CC,B2B2,16,692,-107,-1,-1,0,0
-            https://www.neilson.co.za/mobile-network-geolocation-obtaining-the-cell-ids-the-signal-strength-of-surrounding-towers-from-a-gsm-modem/
-            */
-            //ATsendCMD("AT+QENG=\"neighbourcell\"");
-            //ATwaitForWord("OK",ATTIMEOUT_LONG);
-        }
-    }
-    
-    t.reset();
-    t.stop();
-    
-    //debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "locdata: %s",locDataOut);debug_exe();
-
-    
-    //RETURN
-    if (accuracy == 0) {
-        sprintf(locDataOut,"\0");
-    } else if (!haveGPSFix && !haveCellFix) {
-        sprintf(locDataOut,"\0");
-    }
-    return locDataOut;
-}
-
-Modem::~Modem(){};
\ No newline at end of file
--- a/modem.h	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-#ifndef MODEM_H
-#define MODEM_H
-
-#include "main.h"
-
-namespace mbed {
-
-    #define UC20_BAUDRATE       115200
-    #define SIM7600_BAUDRATE    115200
-    #define USSD_MAXLENGTH      140
-    #define ATTIMEOUT_VERYSHORT 3000
-    #define ATTIMEOUT_SHORT     5000
-    #define ATTIMEOUT_MED       10000
-    #define ATTIMEOUT_LONG      20000
-    
-    class Modem
-    {
-        public:  
-            Modem(PinName pwrkey, PinName vreg_en, PinName w_disable);
-            ~Modem();
-            
-            //control
-            bool on(bool force2G);
-            void off(bool soft);
-             
-            //funcs
-            bool registerOnNetwork(int maxAttempts, uint32_t timeout, uint32_t &BYREF_NetworkFailCount);
-            char* HTTPpost(char* url, char* message, bool getResponse, int maxAttempts);
-            /*
-            bool USSDsend(char* message);
-            char* USSDreceive(void);
-            char* USSDmessage(char* message, bool needResponse, char* api);
-            */
-            bool USSDsend(char* message, int maxAttempts);
-            char* USSDreceive(int messageIndex);
-            char* USSDmessage(char* message, bool needResponse, int maxAttempts, char* api);
-            char* getLocation(uint8_t accuracy, uint16_t timeout_seconds, uint32_t &BYREF_GPSFailCount, uint32_t &BYREF_NetworkFailCount); //accuracy is 1,2
-            uint64_t getIMEI(void);
-            uint64_t getCCID(void);
-            char* getModemModel(void);
-            
-            //AT
-            void ATsendCMD(char* cmd);
-            bool ATwaitForWord(char* word, uint32_t timeout);
-            bool ATwaitForWordOrBO(char* word1, uint32_t timeout);
-            bool ATgetResponse(char terminator, uint32_t timeout);
-        private:
-
-            
-        protected:
-            DigitalOut _vreg_en;
-            DigitalInOut _pwrkey;
-            DigitalInOut _w_disable;
-    };
-
-} //Namespace
-#endif
\ No newline at end of file
--- a/sensors.cpp	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-#include "sensors.h"
-
-//------------------------------------------------------------------------------
-// ACCELEROMETER
-//------------------------------------------------------------------------------ 
-
-DigitalIn lis3dh_int1(PN_ACC_INT1, PullNone); //DISTUBANCE
-DigitalIn lis3dh_int2(PN_ACC_INT2, PullNone); //IMPACT
-
-void lis3dh_configureForSleep(uint8_t motion_threshold, uint8_t impact_threshold) {
-    //init
-    LIS3DH lis3dh(PN_SPI_MOSI, PN_SPI_MISO, PN_SPI_CS0, PN_SPI_CLK);
-     
-    //Mode
-    lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG1, 0b00111111); // 00111111 25hz low power mode all axis. 50hz = 6ua  /   25hz = 4ua  /   10hz = 3ua
-    lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG2, 0b11001011); // HP Filter with 0.2hz@25hz for both INT1 and INT2 and Data //http://www.st.com/content/ccc/resource/technical/document/application_note/77/ed/e7/e1/28/5a/45/d6/CD00290365.pdf/files/CD00290365.pdf/jcr:content/translations/en.CD00290365.pdf
-
-    //g and Resolution
-    //lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG4, 0b00110000); // disable highresoluton , set 16g
-    lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG4, 0b00100000); // disable highresoluton , set 8g
-    //lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG4, 0b00010000); // disable highresoluton , set 4g
-    //lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG4, 0b00000000); // disable highresoluton , set 2g
-    
-    //interrupt setup
-    lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG5, 0b00001010); // Latch INT1 and INT2
-    
-    //impact interrupt 
-    if (impact_threshold > 10) { //10 is a reasonable minimum value 
-        lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG3, 0b01000000); // IA1 on INT1
-        lis3dh.LIS3DH_WriteReg(LIS3DH_INT1_CFG, 0b00101010); // Enable X,Y,Z interrupt generation
-        lis3dh.LIS3DH_WriteReg(LIS3DH_INT1_THS, impact_threshold);
-        lis3dh.LIS3DH_WriteReg(LIS3DH_INT1_DURATION, 0x00); // Set duration to 0 cycle
-    } else {
-        lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG3, 0b00000000); // No IA1 on INT1
-        lis3dh.LIS3DH_WriteReg(LIS3DH_INT1_CFG, 0b00000000); // Enable X,Y,Z interrupt generation
-    }
-    
-    //awake interrupt
-    lis3dh.LIS3DH_WriteReg(LIS3DH_CTRL_REG6, 0b00100000); // IA2 on INT2
-    lis3dh.LIS3DH_WriteReg(LIS3DH_INT2_CFG, 0b00101010); // Enable X,Y,Z interrupt generation
-    lis3dh.LIS3DH_WriteReg(LIS3DH_INT2_THS, motion_threshold); // Set threshold
-    lis3dh.LIS3DH_WriteReg(LIS3DH_INT2_DURATION, 0x00); // Set duration to 0 cycle
-
-    //Clear interrupts
-    lis3dh.LIS3DH_ResetInt1Latch();
-    lis3dh.LIS3DH_ResetInt2Latch();
-    
-    GLOBAL_needToConfigureLis3dh = false;
-}
--- a/sensors.h	Fri Aug 09 14:22:21 2019 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-#ifndef SENSORS_H_
-#define SENSORS_H_
-
-#include "main.h"
-
-//------------------------------------------------------------------------------
-// ACCELEROMETER
-//------------------------------------------------------------------------------
-//PINS
-extern DigitalIn lis3dh_int1;
-extern DigitalIn lis3dh_int2;
-
-//FUNCS
-extern void lis3dh_configureForSleep(uint8_t motion_threshold, uint8_t impact_threshold);
-
-//------------------------------------------------------------------------------
-// TEMPERATURE
-//------------------------------------------------------------------------------
-
-#endif
\ No newline at end of file
--- a/states.h	Fri Aug 09 14:22:21 2019 +0000
+++ b/states.h	Thu Feb 13 00:57:06 2020 +0000
@@ -1,9 +1,7 @@
 #define STATE_SETUP              0
 #define STATE_NORMAL             1
-#define STATE_DORMANT            99
+#define STATE_LAUNCH             2
+#define STATE_ALARM              4
 #define STATE_BUTTONPRESS1       81
 #define STATE_BUTTONPRESS3       82
-#define STATE_BUTTONPRESS5       83
-#define STATE_TURNOFF            88
-#define STATE_TURNON             89
 #define STATE_SCORCHEDEARTH      90
\ No newline at end of file