p2p-pingpong-clickbutton

Dependencies:   PingPong-P2P-ClickButtonToWork-SX1272 Lora_SX1272_Coragem

Revision:
3:cbe3f441353e
Parent:
2:4eef0eca4d26
Child:
4:05d5aa4d3f2d
Child:
5:ef21a65a3450
diff -r 4eef0eca4d26 -r cbe3f441353e main.cpp
--- a/main.cpp	Tue Feb 06 10:04:55 2018 +0000
+++ b/main.cpp	Tue Sep 03 21:25:05 2019 +0000
@@ -31,15 +31,22 @@
   
 #include "mbed.h"
 #include "SX1272.h"
+
+
 #define BAND868
 #define MAX_DBM 14
+#define DATA 0
+#define PING 1
+#define PONG 2
 
-const uint32_t DEFAULT_CHANNEL=CH_10_868;  // for BAND868
+#define ADDRESS 10
+
+const uint32_t DEFAULT_CHANNEL=CH_12_900;//915Mhz CH_12_900 =>0xE4C000
 
 //#define WITH_EEPROM            //  TO DO ON STM32
 #define WITH_APPKEY
 #define NEW_DATA_FIELD
-#define WITH_ACK
+//#define WITH_ACK
 
 ///////////////////////////////////////////////////////////////////
 // CHANGE HERE THE LORA MODE, NODE ADDRESS 
@@ -53,16 +60,11 @@
 ///////////////////////////////////////////////////////////////////
 
 ///////////////////////////////////////////////////////////////////
-// CHANGE HERE THE READ PIN AND THE POWER PIN FOR THE TEMP. SENSOR
-#define TEMP_PIN_READ  PA_4
-// use digital 9 to power the temperature sensor if needed
-#define TEMP_PIN_POWER PB_0
-///////////////////////////////////////////////////////////////////
-
-///////////////////////////////////////////////////////////////////
 // CHANGE HERE THE TIME IN SECONDS BETWEEN 2 READING & TRANSMISSION
-#define minTime 120 // 2 minutes
-#define maxTime 600 // 10 minutes
+//#define minTime 120 // 2 minutes
+//#define maxTime 600 // 10 minutes
+#define minTime 5 // seconds
+#define maxTime 25 // seconds
 ///////////////////////////////////////////////////////////////////
 
 #ifdef WITH_APPKEY
@@ -77,7 +79,7 @@
 #include <EEPROM.h>
 #endif
 
-#define DEFAULT_DEST_ADDR 1
+#define DEFAULT_DEST_ADDR 6
 
 #ifdef WITH_ACK
 #define NB_RETRIES 2
@@ -86,10 +88,10 @@
 #ifdef WITH_EEPROM
 struct sx1272config {
 
-  uint8_t flag1;
-  uint8_t flag2;
-  uint8_t seq;
-  // can add other fields such as LoRa mode,...
+    uint8_t flag1;
+    uint8_t flag2;
+    uint8_t seq;
+    // can add other fields such as LoRa mode,...
 };
 
 sx1272config my_sx1272config;
@@ -98,212 +100,459 @@
 ///////////////////////////////////////
 // Globals variables
 ///////////////////////////////////////
+
+//______________BME_280________________
+char cmd_bme[18];
+uint32_t hum_raw;
+float humf;
+uint32_t temp_raw;
+float tempf;
+uint32_t press_raw;
+float pressf;
+//char cmd[4];
+
+//___________SX1272____________________
+int e;
+
+//___________mensagem_____________________
+uint8_t message[100];
+uint8_t buffer[100];
+uint8_t message_pong[]="Pong";
+uint8_t message_ping[]="Ping";
+uint8_t r_size;
+char float_temp[10];
+char float_press[10];
+char float_hum[10];
+int cont =0;
+
+
+DigitalOut led1(P1_13);
+DigitalOut led2(P1_14);
+InterruptIn dio0(P0_12);
+DigitalIn button1(P1_11);
+DigitalIn button2(P1_12);
+DigitalIn button3(P0_30);
+
+EventQueue queue;
+
 int loraMode=LORAMODE;
-// added by C.Dupaty
-// For test with LM35DZ temperature captor
-DigitalOut temp_pin_power(TEMP_PIN_POWER);
-AnalogIn temp_pin_read(TEMP_PIN_READ);
+
+//_________BME 280___
+
+I2C sensor(p13, p15);
+const int BME280_ADDR = (0x77 << 1);
+
+uint16_t dig_T1,dig_P1,dig_H1, dig_H3;
+int16_t dig_T2, dig_T3,dig_P2, dig_P3, dig_P4, dig_P5, dig_P6, dig_P7, dig_P8, dig_P9,dig_H2, dig_H4, dig_H5, dig_H6;
+int32_t t_fine;
+
+ //============= internet of turtles =============
+Timer time_breathing;
+Timer time_diving;
+bool beathing = false;
+float last_breathing_time = 0.0;
+float last_diving_time = 0.0;
+
+char float_breathing_time[10];
+char float_diving_time[10];
+
+Timer seconds;
+
+//================================================
+void bme_init() { //bme initialization
+
+
+    sensor.frequency(1000000);
+
+    cmd_bme[0] = 0xf2; // ctrl_hum
+    cmd_bme[1] = 0x01;
+    sensor.write(BME280_ADDR, cmd_bme, 2);
+
+    cmd_bme[0] = 0xf4; // ctrl_meas
+    cmd_bme[1] = 0x27;
+    sensor.write(BME280_ADDR, cmd_bme, 2);
+
+    cmd_bme[0] = 0xf5; // config
+    cmd_bme[1] = 0xa0;
+    sensor.write(BME280_ADDR, cmd_bme, 2);
+
+    cmd_bme[0] = 0x88; // read dig_T regs
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, cmd_bme, 6);
+
+    dig_T1 = (cmd_bme[1] << 8) | cmd_bme[0];
+    dig_T2 = (cmd_bme[3] << 8) | cmd_bme[2];
+    dig_T3 = (cmd_bme[5] << 8) | cmd_bme[4];
+
+//    DEBUG_PRINT("dig_T = 0x%x, 0x%x, 0x%x\n", dig_T1, dig_T2, dig_T3);
+
+    cmd_bme[0] = 0x8E; // read dig_P regs
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, cmd_bme, 18);
+
+    dig_P1 = (cmd_bme[ 1] << 8) | cmd_bme[ 0];
+    dig_P2 = (cmd_bme[ 3] << 8) | cmd_bme[ 2];
+    dig_P3 = (cmd_bme[ 5] << 8) | cmd_bme[ 4];
+    dig_P4 = (cmd_bme[ 7] << 8) | cmd_bme[ 6];
+    dig_P5 = (cmd_bme[ 9] << 8) | cmd_bme[ 8];
+    dig_P6 = (cmd_bme[11] << 8) | cmd_bme[10];
+    dig_P7 = (cmd_bme[13] << 8) | cmd_bme[12];
+    dig_P8 = (cmd_bme[15] << 8) | cmd_bme[14];
+    dig_P9 = (cmd_bme[17] << 8) | cmd_bme[16];
+
+//    DEBUG_PRINT("dig_P = 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x\n", dig_P1, dig_P2, dig_P3, dig_P4, dig_P5, dig_P6, dig_P7, dig_P8, dig_P9);
+
+    cmd_bme[0] = 0xA1; // read dig_H regs
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, cmd_bme, 9);
+
+    dig_H1 = cmd_bme[0];
+    dig_H2 = (cmd_bme[2] << 8) | cmd_bme[1];
+    dig_H3 = cmd_bme[3];
+    dig_H4 = (cmd_bme[4] << 4) | (cmd_bme[5] & 0x0f);
+    dig_H5 = (cmd_bme[7] << 4) | ((cmd_bme[6]>>4) & 0x0f);
+    dig_H6 = cmd_bme[8];
+
+//    DEBUG_PRINT("dig_H = 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x\n", dig_H1, dig_H2, dig_H3, dig_H4, dig_H5, dig_H6);
+}
+
+float getTemperature(){
+
+    
+    cmd_bme[0] = 0xfa; // temp_msb
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, &cmd_bme[1], 1);
+    
+    cmd_bme[0] = 0xfb; // temp_lsb
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, &cmd_bme[2], 1);
+    
+    cmd_bme[0] = 0xfc; // temp_xlsb
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, &cmd_bme[3], 1);
+    
+    temp_raw = (cmd_bme[1] << 12) | (cmd_bme[2] << 4) | (cmd_bme[3] >> 4);
+    
+    int32_t temp;
+    
+    temp =
+        (((((temp_raw >> 3) - (dig_T1 << 1))) * dig_T2) >> 11) +
+        ((((((temp_raw >> 4) - dig_T1) * ((temp_raw >> 4) - dig_T1)) >> 12) * dig_T3) >> 14);
+    
+    t_fine = temp;
+    temp = (temp * 5 + 128) >> 8;
+    tempf = (float)temp;
+    
+    return (tempf/100.0f);
+}
+
+float getPressure(){
+
+    cmd_bme[0] = 0xf7; // press_msb
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, &cmd_bme[1], 1);
+
+    cmd_bme[0] = 0xf8; // press_lsb
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, &cmd_bme[2], 1);
+
+    cmd_bme[0] = 0xf9; // press_xlsb
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, &cmd_bme[3], 1);
+
+    press_raw = (cmd_bme[1] << 12) | (cmd_bme[2] << 4) | (cmd_bme[3] >> 4);
+
+    int32_t var1, var2;
+    uint32_t press;
+
+    var1 = (t_fine >> 1) - 64000;
+    var2 = (((var1 >> 2) * (var1 >> 2)) >> 11) * dig_P6;
+    var2 = var2 + ((var1 * dig_P5) << 1);
+    var2 = (var2 >> 2) + (dig_P4 << 16);
+    var1 = (((dig_P3 * (((var1 >> 2)*(var1 >> 2)) >> 13)) >> 3) + ((dig_P2 * var1) >> 1)) >> 18;
+    var1 = ((32768 + var1) * dig_P1) >> 15;
+    if (var1 == 0) {
+        return 0;
+    }
+    press = (((1048576 - press_raw) - (var2 >> 12))) * 3125;
+    if(press < 0x80000000) {
+        press = (press << 1) / var1;
+    }
+    else {
+        press = (press / var1) * 2;
+    }
+    var1 = ((int32_t)dig_P9 * ((int32_t)(((press >> 3) * (press >> 3)) >> 13))) >> 12;
+    var2 = (((int32_t)(press >> 2)) * (int32_t)dig_P8) >> 13;
+    press = (press + ((var1 + var2 + dig_P7) >> 4));
+
+    pressf = (float)press;
+    return (pressf/100.0f);
+}
+
+float getHumidity(){
+
+
+    cmd_bme[0] = 0xfd; // hum_msb
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, &cmd_bme[1], 1);
+
+    cmd_bme[0] = 0xfd; // hum_lsb
+    sensor.write(BME280_ADDR, cmd_bme, 1);
+    sensor.read(BME280_ADDR, &cmd_bme[2], 1);
+
+    hum_raw = (cmd_bme[1] << 8) | cmd_bme[2];
+
+    int32_t v_x1;
+
+    v_x1 = t_fine - 76800;
+    v_x1 =  (((((hum_raw << 14) -(((int32_t)dig_H4) << 20) - (((int32_t)dig_H5) * v_x1)) +
+               ((int32_t)16384)) >> 15) * (((((((v_x1 * (int32_t)dig_H6) >> 10) *
+                                            (((v_x1 * ((int32_t)dig_H3)) >> 11) + 32768)) >> 10) + 2097152) *
+                                            (int32_t)dig_H2 + 8192) >> 14));
+    v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * (int32_t)dig_H1) >> 4));
+    v_x1 = (v_x1 < 0 ? 0 : v_x1);
+    v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1);
+
+    humf = (float)(v_x1 >> 12);
+
+    return (humf/1024.0f);
+}
 
 /////////////////////////////////////////
 // SETUP SX1272 initialisation
 ////////////////////////////////////////
-void setup()
-{
-  int e;
-  // Print welcome message
-  printf("-------------------------------------------------\n");
-  printf("------Simple LoRa temperature sensor-------------\n");
-  printf("--P.Pharm, adaptation NUCELO STM32 C.Dupaty------\n");
-  printf("-------------------------------------------------\n\n");
-  printf("!!!!!!!!! During configuration, all states numbers must read at 0\n");
- 
-#ifdef TARGET_NUCLEO_L073RZ
-  printf("NUCLEO L073RZ detected\n");
-#else
-  printf("WARNING, this software has been tested on NUCLEO L073RZ only !!!\n"); 
-#endif
-
-  // Power ON the module
-  sx1272.ON();
-
-#ifdef WITH_EEPROM
-  // get config from EEPROM
-  EEPROM.get(0, my_sx1272config);
-
-  // found a valid config?
-  if (my_sx1272config.flag1==0x12 && my_sx1272config.flag2==0x34) {
-    printf("Get back previous sx1272 config\n");
+void setup(){
+      
+    
+      printf("------Coragem LoRa temperature sensor-------------\n");
+      //sx1272.ON();  // Power ON the module
 
-    // set sequence number for SX1272 library
-    sx1272._packetNumber=my_sx1272config.seq;
-    printf("Using packet sequence number of %d\n",sx1272._packetNumber);
-  }
-  else {
-    // otherwise, write config and start over
-    my_sx1272config.flag1=0x12;
-    my_sx1272config.flag2=0x34;
-    my_sx1272config.seq=sx1272._packetNumber;
-  }
-#endif
-  
-  int error_config_sx1272=0;
-  
-  // Set transmission mode and print the result
-  e = sx1272.setMode(loraMode);
-  if (e) error_config_sx1272=1;
-  printf("Setting Mode: state %d\n",e);
-  
-  // enable carrier sense
-  sx1272._enableCarrierSense=true;
-
-  // for LOW POWER
-  sx1272._RSSIonSend=false;
-
+    int error_config_sx1272=0;
+    
+    // Set transmission mode and print the result
+    e = sx1272.setMode(loraMode);
+    printf("Mode: %d\n",loraMode);
+    if (e) error_config_sx1272=1;
+    printf("Setting Mode: state %d\n",e);
+    
+    // enable carrier sense
+    sx1272._enableCarrierSense=true;
+    
+    // for LOW POWER
+    sx1272._RSSIonSend=false;
+    
+    
+    // Select frequency channel
+    e = sx1272.setChannel(DEFAULT_CHANNEL);
+    if (e) error_config_sx1272=1;
+    printf("Setting Channel: state %d\n",e);
     
-  // Select frequency channel
-  e = sx1272.setChannel(DEFAULT_CHANNEL);
-  if (e) error_config_sx1272=1;
-  printf("Setting Channel: state %d\n",e);
-  
-  // Select amplifier line; PABOOST or RFO
-#ifdef PABOOST
-  sx1272._needPABOOST=true;
-  // previous way for setting output power
-  // powerLevel='x';
-#else
-  // previous way for setting output power
-  // powerLevel='M';  
-#endif
-
-  // previous way for setting output power
-  // e = sx1272.setPower(powerLevel); 
-
-  e = sx1272.setPowerDBM((uint8_t)MAX_DBM);
-  if (e) error_config_sx1272=1;
-  printf("Setting Power: state %d\n",e);
-  
-  // Set the node address and print the result
-  e = sx1272.setNodeAddress(node_addr);
-  if (e) error_config_sx1272=1;
-  printf("Setting node addr: state %d\n",e);
-  
-  // Print a success message
-  if (!error_config_sx1272) printf("SX1272 successfully configured\n");
-  else printf("ERREUR DE CONFIGURATION DU SX1272\n");
-
-  wait_ms(500);
+    // Select amplifier line; PABOOST or RFO
+//    #ifdef PABOOST
+//        printf("pabboost\n");
+//        sx1272._needPABOOST=true;
+//    // previous way for setting output power
+//    // powerLevel='x';
+//    #else
+//    // previous way for setting output power
+//    // powerLevel='M';  
+//    #endif
+    
+    // previous way for setting output power
+    // e = sx1272.setPower(powerLevel); 
+    
+    e = sx1272.setPowerDBM((uint8_t)MAX_DBM);
+    if (e) error_config_sx1272=1;
+    printf("Setting Power: state %d\n",e);
+    
+    // Set the node address and print the result
+    e = sx1272.setNodeAddress(node_addr);
+    if (e) error_config_sx1272=1;
+    printf("Setting node addr: state %d\n",e);
+    
+    // Print a success message
+    if (!error_config_sx1272) printf("SX1272 successfully configured\n");
+    else printf("ERROR CONFIGURATION SX1272\n");
+    
+    wait_ms(400);
 }
 
-//////////////////////////////////////////////////////////////
-//  main was named loop on Arduino
-//////////////////////////////////////////////////////////////
-int main(void)      // return int for cpp compatibility but never ending the program
-{
-long startSend;
-long endSend;
-uint8_t app_key_offset=0;
-int e;
-double temp;            // variable temperature in this demo 
-char float_str[20];
-uint8_t message[100];   // the message that will be send to the gateway
-
-setup();
- 
- // main loop start here 
-while(1)  {  
 
-// this demo use a LM35DZ temerature captor
-      temp_pin_power=1;         // LM35DZ is powering by a simple GPIO
-      wait_ms(200);   
-      temp = 0;
-      int value;
-      for (int i=0; i<10; i++) {
-          // compute temperature for LM35DZ captor
-          value = temp_pin_read.read_u16();
-          temp += ((double)value*50.0/8192.0)/10;
-          printf("Reading ADC temperature %d/10 -> %d\n",i,value);
-          wait_ms(100);
-      } 
-      temp_pin_power=0;         // LM35DZ power off
-      printf("Mean temp is %f Cent\n",temp);
-// we have now temperature in the variable temp      
+void send_packet(int mode){
+    led1=1;
+    sx1272.writeRegister(0x01,129);//standby    
+    sx1272.setPacketType(PKT_TYPE_DATA);
+    
+    printf ("sendpacket1\n");
+    if (mode == DATA ) {
+       // uint8_t message[100];    
+        sprintf(float_temp,"%2.2f",getTemperature());
+        sprintf(float_press,"%04.2f",getPressure());
+        sprintf(float_hum,"%2.2f",getHumidity());
+        
+        printf ("sendpacket2\n");
+        //============= internet of turtles =============
+        sprintf(float_breathing_time,"%2.2f", last_breathing_time);
+        sprintf(float_diving_time,"%2.2f", last_diving_time);
+        r_size=sprintf((char*)message,"\\!#%s°C_%shPa_%s_Dt%s_Bt%s%%",float_temp,float_press,float_hum,float_diving_time,float_breathing_time);
+        // ==============================================
+        
+            printf ("sendpacket3\n");
+        //size=sprintf((char*)message,"\\!#%s°C_%shPa_%s%%",float_temp,float_press,float_hum);
+        sx1272.sendPacketTimeout(DEFAULT_DEST_ADDR, message, r_size);
+        printf ("sendpacket4\n");
+        printf("packet send :\n%s\n",message);
+       
+    }
+    else if (mode == PING ){   
+    
+       // uint8_t message[]="Ping";
+        //strcpy( message, "Ping");
 
-#ifdef WITH_APPKEY
-      app_key_offset = sizeof(my_appKey);
-      // set the app key in the payload
-      memcpy(message,my_appKey,app_key_offset);
-#endif
+        sx1272.sendPacketTimeout(DEFAULT_DEST_ADDR, message_ping, sizeof(message_ping));
+        printf("packet send :\n%s\n",message_ping);
+        
+        //sx1272.sendPacketTimeout(DEFAULT_DEST_ADDR, message, sizeof(message));
+//        sx1272.writeRegister(REG_OP_MODE, LORA_STANDBY_MODE);  // Stdby LoRa mode to write in FIFO
+        
+//        sx1272.writeRegister(0x0E,0x00);
+//        sx1272.writeRegister(0x0D,0x00);
+        
+//        sx1272.writeRegister(REG_PAYLOAD_LENGTH_LORA, sizeof(message));
+//        for(unsigned int i = 0; i < sizeof(message); i++)
+//        {
+//            sx1272.writeRegister(REG_FIFO, message[i]);  // Writing the payload in FIFO
+//        }
+//        sx1272.writeRegister(REG_OP_MODE, LORA_TX_MODE);  // LORA mode - Tx
+        
+//        int exitTime = millis()+2000;//2 segundos para sair do for
+        
+//        char value = sx1272.readRegister(REG_IRQ_FLAGS);
+//        while (( value && 8 == 0) && (millis() < exitTime))
+//        {
+//            value = sx1272.readRegister(REG_IRQ_FLAGS);
+//        }
+             
 
-      uint8_t r_size;
-      
-        // convert float temp to string ASCII
-        sprintf(float_str,"%2.2f",temp);
-        #ifdef NEW_DATA_FIELD
-              // this is for testing, uncomment if you just want to test, without a real temp sensor plugged
-              //strcpy(float_str, "21.55567");
-              r_size=sprintf((char*)message+app_key_offset,"\\!#%d#TC/%s",field_index,float_str);
-        #else
-              // this is for testing, uncomment if you just want to test, without a real temp sensor plugged
-              //strcpy(float_str, "21.55567");
-              r_size=sprintf((char*)message+app_key_offset,"\\!#%d#%s",field_index,float_str);
-        #endif
-          
-      printf("Sending %s\n",message+app_key_offset);
-      printf("Real payload size is %d\n",r_size);
-     
-      int pl=r_size+app_key_offset;
-      sx1272.CarrierSense();
-      startSend=millis();
+ //       printf("packet send :\n%s\n",message);
+ //       wait_ms(500); 
+ //       sx1272.writeRegister(0x12,255);//clean flags
+ //       sx1272.writeRegister(REG_OP_MODE, LORA_STANDBY_MODE);  // Stdby LoRa mode to write in FIFO
+        
+    }    
+    else if (mode == PONG )  {   
+       // uint8_t message_pong[]="Pong";
+        //strcpy( message, "Pong");
+
+        sx1272.sendPacketTimeout(DEFAULT_DEST_ADDR, message_pong, sizeof(message_pong));
+        printf("packet send :\n%s\n",message_pong);
+        
+    }
+    
+    cont++;
+    led1=0;    
+    sx1272.writeRegister(0x01,133); //leitura continua
+    printf("number=%d\n",cont);
+}
+
+
+void print_packet(){
+
+   led2=1;
+   sx1272.writeRegister(0x01,129);//standby    
 
-#ifdef WITH_APPKEY
-      // indicate that we have an appkey
-      sx1272.setPacketType(PKT_TYPE_DATA | PKT_FLAG_DATA_WAPPKEY);
-#else
-      // just a simple data packet
-      sx1272.setPacketType(PKT_TYPE_DATA);
-#endif
-      
-      // Send message to the gateway and print the result
-      // with the app key if this feature is enabled
-#ifdef WITH_ACK
-      int n_retry=NB_RETRIES;
-      do {
-        e = sx1272.sendPacketTimeoutACK(DEFAULT_DEST_ADDR, message, pl);
-        if (e==3) printf("No ACK");
-        n_retry--;
-        if (n_retry) printf("Retry");
-        else printf("Abort"); 
-      } while (e && n_retry);          
-#else      
-      e = sx1272.sendPacketTimeout(DEFAULT_DEST_ADDR, message, pl);
-#endif  
-      endSend=millis();
-#ifdef WITH_EEPROM
-      // save packet number for next packet in case of reboot
-      my_sx1272config.seq=sx1272._packetNumber;
-      EEPROM.put(0, my_sx1272config);
-#endif
+    uint8_t pac_size;
+
+    sx1272.writeRegister(0x0D,sx1272.readRegister(0x10));//set fifo pointer to read packet
+    pac_size = sx1272.readRegister(0x13);//read size of packet
+    for(int i =0 ; i<pac_size ; i++){ //print packet
+        buffer[i]=sx1272.readRegister(REG_FIFO);
+        printf("%c",buffer[i]);//print packet
+    }
+    printf("\n");
 
-      printf("LoRa pkt size %d\n",pl);
-      printf("LoRa pkt seq %d\n",sx1272.packet_sent.packnum);
-      printf("LoRa Sent in %ld\n",endSend-startSend);
-      printf("LoRa Sent w/CAD in %ld\n", endSend-sx1272._startDoCad);
-      printf("Packet sent, state %d\n",e);
-      printf("Remaining ToA is %d\n",sx1272.getRemainingToA());
-      
- // compute next time transmission in seconds
-      int waitting = rand()%maxTime+minTime;   // waitting in Sec
-      printf("Switch to power saving mode\n");
-      e = sx1272.setSleepMode();
-      if (!e)
-        printf("Successfully switch LoRa module in sleep mode\n");
-      else  
-        printf("Could not switch LoRa module in sleep mode\n");
-      // Deep sleep 
-      printf("Deep sleep allowed: %i for %d seconds\n", sleep_manager_can_deep_sleep(), waitting);
-      wait(waitting);
-}//  end loop
-
-//return (0);  useless here, the program never ends
+    for(int i =0 ; i<pac_size ; i++){ //look for Ping in packet
+        if ((buffer[i] =='P') && (buffer[i+1] =='i') ){
+                wait(1);
+                sx1272.writeRegister(0x12,255);//clean flags
+                send_packet(PONG);
+                i=pac_size;
+        }
+    } 
+    
+    for(int i =0 ; i<pac_size ; i++){ //look for Ping in packet
+        if ((buffer[i] =='R') && (buffer[i+1] =='e') && (buffer[i+2] =='s') && (buffer[i+3] =='e')  ){
+             NVIC_SystemReset();
+        }
+    }
+    
+    wait_ms(300);
+    sx1272.writeRegister(0x12,255);//clean flags
+    
+    led2=0; 
 
 }
+
+
+int main(void) {     
+    led1=1;//on leds
+    led2=1;
+
+    Thread eventThread;
+    eventThread.start(callback(&queue, &EventQueue::dispatch_forever));
+ 
+    dio0.rise(queue.event(&print_packet)); //configura rotina de interrupçao para quando receber pacote
+    seconds.start();
+
+    bme_init();//configura sensor bme280
+    setup(); //configura sx1272
+    
+    //TESTE_COMUNICAÇAO LABRADOR
+    //sx1272.writeRegister(0x0B,0x3B);
+    //sx1272.writeRegister(0x18,0x10);
+    //sx1272.writeRegister(0x33,0x26);
+    //sx1272.writeRegister(0x1D,0x08);
+    //sx1272.writeRegister(0x1E,0xC4); 
+    
+    
+    sx1272.writeRegister(REG_OP_MODE,133); //leitura continua
+    sx1272.writeRegister(0x11,187);//configure interrupt mask to interrupt only when a packet receive and packet envied 
+    
+    led1=0;//off leds
+    led2=0;
+    
+//    for (int i=2 ; i<255;i++){
+//        int value = sx1272.readRegister(i);
+//        if (value !=0 )
+//            printf("reg 0x%02x= 0x%02x\n",i,value);
+//    }
+    
+    //long int time_start = seconds.read();
+    //printf ("timestart=%d  leitura = %d\n",time_start,seconds.read());
+    while(1){
+
+         if (button3 != beathing) {
+            beathing = !beathing;
+            if(button3){
+                send_packet(DATA);
+                
+                time_breathing.reset();
+                time_breathing.start();
+                
+                time_diving.stop();
+                last_diving_time = time_diving.read();
+            }else{
+                time_diving.reset();
+                time_diving.start();
+                
+                time_breathing.stop();
+                last_breathing_time = time_breathing.read();
+
+            }
+                
+        }
+        
+        wait_ms(50);
+    }
+
+}