   Serial.print(F("Disconnected event, central: "));
   Serial.println(central.address());
 }
+

// TimerOne library: https://code.google.com/p/arduino-timerone/
#include <TimerOne.h> 
#include <SPI.h>
#include <BLEPeripheral.h>


#endif

  blePeripheral.setLocalName("Temperature");
  
  blePeripheral.setAdvertisedServiceUuid(tempService.uuid());
  blePeripheral.addAttribute(tempService);
  blePeripheral.addAttribute(tempCharacteristic);
  blePeripheral.addAttribute(tempDescriptor);
  
  blePeripheral.setAdvertisedServiceUuid(humidityService.uuid());
  blePeripheral.addAttribute(humidityService);
  blePeripheral.addAttribute(humidityCharacteristic);
  blePeripheral.addAttribute(humidityDescriptor);

  blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler);
  blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);

  blePeripheral.begin();
  
  Timer1.initialize(2 * 1000000); // in milliseconds
  Timer1.attachInterrupt(timerHandler);
  
  Serial.println(F("BLE Temperature Sensor Peripheral"));
}

void loop() {
  blePeripheral.poll();
  
  if (readFromSensor) {
    setTempCharacteristicValue();
    setHumidityCharacteristicValue();
    readFromSensor = false;
  }
}

void timerHandler() {
  readFromSensor = true;
}

void setTempCharacteristicValue() {
  float reading = dht.readTemperature();
//  float reading = random(100);
  
  if (!isnan(reading) && significantChange(lastTempReading, reading, 0.5)) {
    char formatted[7];
    dtostrf(reading, 3, 1, formatted);
    tempCharacteristic.setValue(formatted);
    
    Serial.print(F("Temperature: ")); Serial.print(reading); Serial.println(F("C"));
    
    lastTempReading = reading;
  }
}

void setHumidityCharacteristicValue() {
  float reading = dht.readHumidity();
//  float reading = random(100);

  if (!isnan(reading) && significantChange(lastHumidityReading, reading, 1.0)) {
    char formatted[6];
    dtostrf(reading, 3, 1, formatted);
    humidityCharacteristic.setValue(formatted);
    
    Serial.print(F("Humidity: ")); Serial.print(reading); Serial.println(F("%"));
    
    lastHumidityReading = reading;
  }
}

boolean significantChange(float val1, float val2, float threshold) {
  return (abs(val1 - val2) >= threshold);
}

void blePeripheralConnectHandler(BLECentral& central) {
