MKR1000 and time

The MKR1000 has a real time clock (RTC) which keeps track of the current time. Every time the board is powered, the RTC is reset and starts from a standard date and time. The RTC can be kept alive even when the CPU is in sleep mode.

To interact with the RTC, you can use the RTC library, which can be found on GitHub. In the Arduino IDE, the library can easily be installed from the Library Manager. Just search for rtc and then install the RTCZero library, which can be used with the MKR1000, the MKRZero and the Arduino Zero.

To use the library, include it in your code and define a variable of type RTCZero:

#include <RTCZero.h>

RTCZero rtc;

In setup(), call rtc.begin() and then get the current epoch which is just a Unix timestamp. A Unix timestamp is the number of seconds since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. The WiFi library that we use has a handy function called getTime() which retrieves the epoch from NTP servers on the Internet.

The complete code to retrieve the current time as a Unix timestamp is shown below (taken from the Arduino website).

rtc.begin();

unsigned long epoch;
int numberOfTries = 0, maxTries = 6;
do {
  epoch = WiFi.getTime();
  numberOfTries++;
}
while ((epoch == 0) || (numberOfTries > maxTries));

if (numberOfTries > maxTries) {
  Serial.print("NTP unreachable!!");
  while (1);
}
else {
  Serial.print("Epoch received: ");
  Serial.println(epoch);
  rtc.setEpoch(epoch);

  Serial.println();
}

The code above just halts when WiFi.getTime() cannot retrieve the time. Otherwise the retrieved time, stored in the epoch variable, is printed and set as the RTC's current time with rtc.setEpoch().

You can now use the getEpoch() method of the RTCZero class to retrieve the current time as Unix time. In Chapter 3, in the Connect with MQTT section, getEpoch() is used during the creation of a SAS token which requires a Unix timestamp to determine when the token should become invalid:

String generateSAS(String url, char* key, long expire) {
  // if expire is 0 then default to January 1, 2030 for now
  if( expire==0 ) {
    expire = 1893456000;
  } else {
    expire = rtc.getEpoch() + expire;
  }

...

Above, the expire parameter is set to the number of seconds the token should remain valid.

You now have enough knowledge about device programming and interacting with HTTP and MQTT servers securely to proceed to the next chapters. In the next chapter, we will connect to Azure IoT Hub using HTTPS and MQTT over TLS!

results matching ""

    No results matching ""