 /*
- * Author: NC Thompson
+ * Authors: NC Thompson, JP Meijers
  * Date: 2017-02-15
  *
  */
 #include <rn2xx3.h>
 #include <SHT1x.h>
-#include "LowPower.h"
+#include <avr/wdt.h>
+#include <avr/power.h>
+#include <avr/sleep.h>
+
+// The interval at which the sensors should be read and the values transmitted
+#define SAMPLE_INTERVAL_MS 60000UL
+
+// after this amount of time, if the rn2483 did not wake us up, reset the system
+#define WDT_INTERVAL_MS 600000UL
 
 //create an instance of the rn2483 library, using the given Serial port
 rn2xx3 myLora(Serial1);
 #define dataPin  SDA
 #define clockPin SCL
-#define PIN_SERIAL1_TX PIN1
+#define SELF_RESET_PIN 12
 
 SHT1x sht1x(dataPin, clockPin);
-
-uint8_t count = 0;
 
 uint8_t txBuffer[7];
 int batVoltPin = A5;    // select the input pin for the battery voltage
 
-// the setup routine runs once when you press reset:
+unsigned long startTime = 0;
+unsigned long sleepTime = 0;
+unsigned int wdtCount = 0;
+
+
+/*
+ * Define Timer4 labels
+ */
+#if defined __AVR_ATmega32U4__
+  // Timer 4 PRR bit is currently not defined in iom32u4.h
+  #ifndef PRTIM4
+    #define PRTIM4 4
+  #endif
+
+  // Timer 4 power reduction macro is not defined currently in power.h
+  #ifndef power_timer4_disable
+    #define power_timer4_disable()  (PRR1 |= (uint8_t)(1 << PRTIM4))
+  #endif
+
+  #ifndef power_timer4_enable
+    #define power_timer4_enable()   (PRR1 &= (uint8_t)~(1 << PRTIM4))
+  #endif
+#endif
+
+
+
 void setup()
 {
+  digitalWrite(SELF_RESET_PIN, HIGH);
+  wdt_disable();
+
   //output LED pin
   pinMode(13, OUTPUT);
   led_on();
 
-  // Open serial communications and wait for port to open:
   Serial.begin(57600); //serial port to computer
 
-  Serial1.begin(57600); //serial port to radio
-  //wakeUP_RN2483();
   // make sure usb serial connection is available,
-  // or after 10s go on anyway for 'headless' use of the
-  // node.
+  // or after 10s go on anyway for 'headless' use of the node.
   while ((!Serial) && (millis() < 10000));
 
   Serial.println("Startup");
 
   initialize_radio();
 
-  //transmit a startup message
-  myLora.tx("TTN Mapper on TTN Uno node");
+  // set up interrupt on Serial1 RX
+  // RXD1 = INT2 - enable interrupt on rising and falling edge
+  EICRA = 0b01010101;
+  EIMSK = 0b00000100;
+
   Serial.end();
   led_off();
-  delay(2000);
 }
 
 void initialize_radio()
 {
+  Serial1.begin(57600); //serial port to radio
+
+  //reset rn2483
+  pinMode(4, OUTPUT);
+  digitalWrite(4, LOW);
+  delay(100);
+  digitalWrite(4, HIGH);
+
   delay(100); //wait for the RN2xx3's startup message
   Serial1.flush();
 

  digitalWrite(13, 0);
}


  }
  Serial.println("Successfully joined TTN");
  okSeq();
}

void okSeq () {
    led_on();
    delay(100);
