 
 // =============================================================================
 void loop() {
-  static int ntp_last = 0;
-
-  // keep time somewhat synced
-  ntp_epoch_in_seconds += (millis() / 1000);
-  
+  static unsigned long display_last = 0;
+  static unsigned long ntp_last = 0;
+
+  // get humidity and temp
+  dht_read(); 
+   
+  // check for motion
+  pir_chk_motion();
+  
+  // update display and serial every 5 seconds
+  if (millis() - display_last > 5000) {
+      display_last = millis();
+
+      counter++;
+      oled_roost();
+      serial_roost();
+  }
+
+  // check for ntp response if not received
+  if (! ntp_packet_received){ ntp_read_response(); };
+  
+  // keep time updated, last epoch received plus usec since last epoch received / 1000
+  ntp_epoch_in_seconds = ntp_received_epoch + floor((millis() - ntp_received_millis) / 1000);
+  ntp_hms = ntp_epoch2hms(ntp_epoch_in_seconds);
+
   // update time every 60 seconds or when the last request is incomplete
   if ((millis() - ntp_last) > 60000 || (! ntp_packet_received)){
     ntp_last = millis();
     ntp_send_request();
   }
 
-  // clear the roost
-  dht_clear();
-
-  // get humidity and temp
-  dht_read();
-  
-  // check for motion
-  pir_chk_motion();
-  
-  led_blink(LED_DEFAULT, 500);
-  delay(500);
-
-  led_blink(LED_EXTRA, 500);
-  delay(500);
-
-  led_blink(LED_BOTH, 500);
-  delay(500);
-
-  // update the OLED
-  counter++;
-  oled_roost();
-  
   // let the web server do its thing every iteration
   web_server.handleClient();
 }


  // maximum blink is 5 seconds
  if (d>5000) { d=5000; }

  // blink on
  if (l == LED_BOTH) {
    digitalWrite(LED_DEFAULT, HIGH);
    digitalWrite(LED_EXTRA, HIGH);
  } else {
    digitalWrite(l, HIGH);
  }

  // pause ...
  delay(d);

  // blink off
  if (l == LED_BOTH) {
    digitalWrite(LED_DEFAULT, LOW);
    digitalWrite(LED_EXTRA, LOW);
  } else {

// =============================================================================
// File: Roost_lab7.ino LEDs, serial, Wifi, web, OLED, NTP, temp, motion
// Desc: Roost! An open source implementaion of a temperature and motion 
//       monitoring station based on an ESP8266 with temperature, humidity,
//       motion and distance sensors.
//
//       This code is in the public domain
// =============================================================================

// -----------------------------------------------------------------------------
// LED control:  code for dealing with the LEDs for the "Roost!" project
//

// default led on pin 5 (also onboard led)
#define LED_DEFAULT 5
