This small projects aims at using ready-to-eat hardware in an energy self-sufficient setup to record environmental data which are then stored in a azure cloud storage cotainer.
Things

Unfortunately, this project is not exactly low cost. The hardware components sum up to 170 € and the azure services add some costs as well. However, this is pay-as-you go and will only add a few cents each month. All in all, aside the fun building this thing, you get a decent IoT device for your buck.
Step 1: Set up Azure IoT Hub
Create a new ressource

Chose „pas as you go“, add a ressurce group, your region and select a name. Click on „Review + Create“ at the bottom of the page, it will take a few minutes to set up your IoT Hub

Once the IoT Hub is set up, go to „IoT devices“ and select „New“ at the very top.

Step 2: Set up MKR 1500 NB
Follow the „Getting Started with the Arduino MKR NB 1500“ section at arduino.cc. You will also need some libraries: ArduinoECCX08 , ArduinoBearSSL , MKRNB , ArduinoMqttClient , Arduino Low Power , ArduinoJson

First, you will need to set up the crypto chip of the MKR 1500 NB:
Go to File -> Examples -> Arduino ECCX08 -> Tools -> ECX08SelfSignedCert.

Upload the sketch to your board, open a serial monitor and follow the instructions. Select slot 0 for your private key and slot 8 for storage. Confirm with Y. The console will show the certificate and a hash – in the form of SHA1: 2834754747w2bjhpr234hp23482482948438 . This hash is what you need to copy.

Step 3: Add MKR 1500 NB to Azure IoT Hub
Back to the Azure IoT Hub. In the „Create a device“ section we opened at the end of step 1, enter a unique device id, select X.509 Self-Signed and add the hash as primary and secondary thumbprint. Cklick on „Save“ at the very bottom and we are good to go. Your MKR is now known by your IoT Hub and can start to communicate.
Step 4: Prepare MKR
Now it is time to get your MKR 1500 NB up and running. First things first:
Put in your SIM Card. Make sure it is a NB-IoT SIM. A normal SIM will not work.
It will not work without a battery. Period. It will work unreliably with a battery with a smaller capacity than 1000 mAh. Period.
I have made this mistake more often than never, so just make sure the battery is charged and plug it into the JST connector. Connect the Antenna as well as the MKR ENV Shield and connect the MKR to your computer.
#include <Arduino_MKRENV.h>
#include <ArduinoJson.h>
#include "ArduinoLowPower.h"
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
#include <MKRNB.h>
#include "arduino_secrets.h"
/////// Enter your sensitive data in arduino_secrets.h
const char pinnumber[] = SECRET_PINNUMBER;
const char ssid[] = SECRET_SSID;
const char pass[] = SECRET_PASS;
const char broker[] = SECRET_BROKER;
String deviceId = SECRET_DEVICE_ID;
//Stuff for timekeeping
unsigned int localPort = 2390; // local port to listen for UDP packets
IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
unsigned long ntptime;
// initialize the library instance
NBClient nbClient;
NBScanner scannerNetworks;
BearSSLClient sslClient(nbClient);
MqttClient mqttClient(sslClient);
NB nbAccess(false);
GPRS gprs;
// Start UDP instance
NBUDP Udp;
unsigned long lastMillis = 0;
boolean dataSent = 0;
void setup() {
//Serial port for debugging
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
analogReference(AR_DEFAULT); // 3.3V
LowPower.attachInterruptWakeup(RTC_ALARM_WAKEUP, wakeUp, CHANGE);
if (!ENV.begin()) {
Serial.println("Failed to initialize MKR ENV shield!");
while (1);
}
if (!ECCX08.begin()) {
Serial.println("No ECCX08 present!");
while (1);
}
//Optional: Set deviceId form serial Number automatically
//deviceId = ECCX08.serialNumber();
// reconstruct the self signed cert
ECCX08SelfSignedCert.beginReconstruction(0, 8);
ECCX08SelfSignedCert.setCommonName(ECCX08.serialNumber());
ECCX08SelfSignedCert.endReconstruction();
// Set a callback to get the current time
// used to validate the servers certificate
ArduinoBearSSL.onGetTime(refreshTime);
// Set the ECCX08 slot to use for the private key
// and the accompanying public certificate for it
sslClient.setEccSlot(0, ECCX08SelfSignedCert.bytes(), ECCX08SelfSignedCert.length());
// Set the client id used for MQTT as the device id
mqttClient.setId(deviceId);
// Set the username to "<broker>/<device id>/api-version=2018-06-30" and empty password
String username;
username += broker;
username += "/";
username += deviceId;
username += "/api-version=2018-06-30";
mqttClient.setUsernamePassword(username, "");
// Set the message callback, this function is
// called when the MQTTClient receives a message
mqttClient.onMessage(onMessageReceived);
//Connect to the network
if (nbAccess.status() != NB_READY || gprs.status() != GPRS_READY) {
connectNB();
}
//Start Udp protocol
Udp.begin(localPort);
refreshTime();
}
void loop() {
//Make sure a connection to the mobile network is established
if (nbAccess.status() != NB_READY || gprs.status() != GPRS_READY) {
connectNB();
}
//Makre sure a connection to the mqtt service is established
if (!mqttClient.connected()) {
connectMQTT();
}
//A variable to check whether data have been sent an a call to void sendData()
if (dataSent == 0){
sendData();
lastMillis = millis();
}
//A poll for messages that might be sent to us by ther server. Not used in this example.
// mqttClient.poll();
//Conditions for entering low power sleep - will only happen 0.5s after data have been sent
if (dataSent == 1) {
if (millis() - lastMillis > 500) {
LowPower.sleep(1000*60);
Udp.begin(localPort);
}
}
}
// Connect to the network
void connectNB() {
Serial.print("Connecting to NB IoT network");
digitalWrite(LED_BUILTIN, HIGH);
while ((nbAccess.begin(pinnumber) != NB_READY) ||
(gprs.attachGPRS() != GPRS_READY)) {
// failed, retry
Serial.print(".");
delay(1000);
}
Serial.println("Connected.");
digitalWrite(LED_BUILTIN, LOW);
Serial.println();
}
//Connect to the mqtt service
void connectMQTT() {
Serial.print("Connecting to mqtt service ");
Serial.print(broker);
while (!mqttClient.connect(broker, 8883)) {
// failed, retry
Serial.print(".");
Serial.println(mqttClient.connectError());
delay(5000);
refreshTime();
}
Serial.println();
Serial.println("Connected.");
Serial.println();
// subscribe to a topic
mqttClient.subscribe("devices/" + deviceId + "/messages/devicebound/#");
}
//Handling of messages sent to use - not used in this example
void onMessageReceived(int messageSize) {
// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available()) {
Serial.print((char)mqttClient.read());
}
Serial.println();
Serial.println();
}
//Get time directly from an NTP server - example from: https://www.arduino.cc/en/Tutorial/MKRNBExamplesGPRSUdpNtpClient
unsigned long refreshTime() {
sendNTPpacket(timeServer); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
if ( Udp.parsePacket() ) {
// We've received a packet, read the data from it
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
// now convert NTP time into everyday time:
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
return epoch;
} else {
return 0;
}
}
unsigned long sendNTPpacket(IPAddress& address)
{
//Serial.println("1");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
//Serial.println("2");
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
//Serial.println("3");
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
//Serial.println("4");
Udp.write(packetBuffer, NTP_PACKET_SIZE);
//Serial.println("5");
Udp.endPacket();
//Serial.println("6");
}
//Function after wakeUp - Only use for small changes of variables! Never call larger functions from here.
void wakeUp() {
dataSent = 0;
}
//Read data from the ENV Shield, construct a json holding the data and send to mqtt broker
void sendData() {
//Step 1: Collect data
//read battery level
int sensorValue = analogRead(ADC_BATTERY);
float voltage = sensorValue * 3.3f / 1023.0f / 1.2f * (1.2f+0.33f);
// read all the sensor values
float temperature = ENV.readTemperature();
float humidity = ENV.readHumidity();
float pressure = ENV.readPressure();
float illuminance = ENV.readIlluminance();
float uva = ENV.readUVA();
float uvb = ENV.readUVB();
float uvIndex = ENV.readUVIndex();
String Signal = scannerNetworks.getSignalStrength();
const size_t CAPACITY = JSON_OBJECT_SIZE(12);
StaticJsonDocument<CAPACITY> doc;
JsonObject object = doc.to<JsonObject>();
object["id"] = deviceId;
object["battery"] = voltage;
object["signal"] = Signal;
object["temperature"] = temperature;
object["humidity"] = humidity;
object["pressure"] = pressure;
object["illuminance"] = illuminance;
object["uva"] = uva;
object["uvb"] = uvb;
object["uvIndex"] = uvIndex;
//Send message to mqqt broker
serializeJson(doc, Serial);
Serial.println();
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage("devices/" + deviceId + "/messages/events/");
serializeJson(doc, mqttClient);
mqttClient.endMessage();
dataSent = 1;
lastMillis = millis();
// signal strength in 0-31 scale. 31 means power > 51dBm
}
You will also have to add a arduino_secrets.h. The SECRET_DEVICE_ID must be the device Id you assigend in Step 2, the SECRET_BROKER is the name of your IoT hub followed by .azure-devices.net.
// NB settings - mostly not needed for NB IoT
#define SECRET_PINNUMBER ""
// Fill in the hostname of your Azure IoT Hub broker
#define SECRET_BROKER ".azure-devices.net"
// Fill in the device id
#define SECRET_DEVICE_ID ""
Step 5: Get everything up and running!
Upload your code and open a serial monitor. This is what you want to see:

If this is your console outpur: Congatulations. You are connected to to the Azure IoT Hub and you a sending environmental data.
If this is not what you are seeing – there is a long road of troubleshooting ahead I will not cover in this tutorial.
Step 6: Create Azure Function App
Next, we will need a Function App that follows a simple if-this-then-that logic. On the Azure portal, click on „Create a ressource“ and select „Function App“. Select „Pay-as-you-go“ for subscription, add the same resource group as before, name the function, select „Node.js“ as runtime stack and „12“ as the version. Make sure, the region matches the region you have set before. Go to tab „Monitoring“ and select „No“ for Apllication Insights. Continue by a click on „Review + Create“

Navigate to the newly created ressource and selecte „New function“. Chose „In-portal“ as your editor, then chose „More templates“.


Select the IoT Hub (Event Hub) template. In the side drawer that opens, chose „new“

Azure is absolutely straight forward with different functions that are hosted on azure, so you will be able to make the connection to your IoT Hub from here without any further hassles. In the pop-up, chose „IoT Hub“, select the IoT hub you have created in step 1 and also chose „Events (build-in endpoint)“. Create the function by a click on „Create“.


In the newly created function, click on „Integrate“ and then on „Outputs“ to make a connection to a table storage, in which the data that is received via the IoT Hub can be stored.

Again, this is hassle free, since we stay on the Azure platform, however, a new storage ressource will be created. Select Azure Table Storage, leave the Table parameter name as „outputTable“ and the Table name as „outTable“. Click on „Save“ and you are good to go for the last piece of code.

Step 7: Route IoT Hub events to table storage
The code is quite simple and mainly taken from another example. We write the values from each Json object we have received in a variable which is then routed to our table storage.
module.exports = function (context, IoTHubMessages) {
//context.log(`JavaScript eventhub trigger function called for message array: ${IoTHubMessages}`);
var count = 0;
var totalTemperature = 0.0;
var totalHumidity = 0.0;
var totalPressure = 0.0;
var totalIlluminance = 0.0;
var totalUva = 0.0;
var totalUvb = 0.0;
var totalUvIndex = 0.0;
var totalBattery = 0.0;
var totalSignal = 0.0;
var deviceId = "";
var messageId = 0;
var timestamp = new Date();
IoTHubMessages.forEach(message => {
var tmp = JSON.parse(message);
//context.log(`json: ${tmp}`);
count++;
totalTemperature += tmp.temperature;
totalHumidity += tmp.humidity;
totalPressure += tmp.pressure;
totalIlluminance += tmp.illuminance;
totalUva += tmp.uva;
totalUvb += tmp.uvb;
totalUvIndex += tmp.uvIndex;
totalBattery += tmp.battery;
totalSignal += tmp.signal;
deviceId = tmp.id;
messageId = tmp.id;
//context.log(`json data: ${tmp.messageId}`);
});
var output = {
"PartitionKey": deviceId,
"RowKey": timestamp.toString(),
// "timestamp": timestamp,
"deviceId": deviceId,
"measurementsCount": count,
"battery": totalBattery/count,
"signal": totalSignal/count,
"temperature": totalTemperature/count,
"humidity": totalHumidity/count,
"pressure": totalPressure/count,
"illuminance": totalIlluminance/count,
"uva": totalUva/count,
"uvb": totalUvb/count,
"uvIndex": totalUvIndex/count
};
context.log(`Output content: ${output.PartitionKey}`);
context.bindings.outputTable = output;
context.done();
};
Under „View files“ in the right hand drawer, select „function.json“, we need to modify this file a bit before we are there. Make sure, the file matches to the file below but replace the asterisk in „*_events_IOTHUB“ by your actual IoT Hub name
{
"bindings": [
{
"type": "eventHubTrigger",
"name": "IoTHubMessages",
"direction": "in",
"eventHubName": "samples-workitems",
"connection": *_events_IOTHUB",
"cardinality": "many",
"consumerGroup": "$Default",
"dataType": "string"
},
{
"type": "table",
"name": "outputTable",
"tableName": "outTable",
"connection": "AzureWebJobsStorage",
"direction": "out"
}
],
"disabled": false
}
Click on „Run“ and make sure the Logs does not throw an error. If you see something alike the log below: Congratulations. You did it.

Step 8: View your data in Azure Storage explorer
Open the Azure Storage Explorer (This is a program that needs to be installed first), log in and navigate to the storage ressource that was created during step 6. Click on query generator, select Field „Timestamp“, Value „Last Hour“ and click on Play. Y

You will now see the amazing environmental readings your MKR just sent to the cloud!