- Click on the New menu option in the upper-left.
- Select Internet of Things.
- Select Azure IoT Hub.
- Give it a name. (e.g. your name followed by iot-labs).
- Select or create a new Resource Group.
- Select a location. Choose the one closest to your physical location.
Once the IoT Hub is created, we can then create a device. When I say ‘create a device’ its just a way of letting Azure IoT Hub know about devices which would connect. We can create a new device by clicking on the Add button.
Please proceed with entering a DeviceId and then select the Authentication Type that you want your device to use while connecting to the Hub. By default symmetrical key is selected which can be changed to X509 certificate if you intend to use a certificate while authenticating your devices. We would cover that later once we see how to use Device Provisioning Service (DPS) in Azure IoT. For now let’s select symmetric key and have the option Auto-generate-key checked which would generate the keys for us.
Click on the device created to see the details about keys and connection string.
This shows details about the device which we just created. It shows ConnectionString info as well. Please make sure you keep this information secure and don’t share it in public since this is the id which your device would use to connect to Azure IoT hub. You can see the options like Message to Device, Direct Method, Device twin etc., which can be ignored for now. We would cover these later in our next post.
- Navigate into the IoT Hub.
- Click on the key icon at the top of the blade.
- In the next blade, click on the iothubowner entry.
- Copy the Connection string-primary key to your clipboard.
Arduino Code
Header file “dht_temperature_AzureIotHub_config.h” has details about connection string and WiFi SSID and password. Please update these config and then flash your NodeMCU .Please make sure you are giving updated connection string in IOT_CONFIG_CONNECTION_STRING.
You can open Serial Monitor from Arduino IDE to view the details of data being send to Azure IoT Hub.
Source code:-
#include <ESP8266WiFi.h> | |
#include <AzureIoTHub.h> | |
#include <AzureIoTProtocol_MQTT.h> | |
#include <AzureIoTUtility.h> | |
#include <ArduinoJson.h> | |
#include "dht_temperature_AzureIotHub_config.h" | |
#include "DHT.h" | |
#define DHTPIN D1 // what digital pin we're connected to | |
#define DHTTYPE DHT11 // DHT 11 | |
DHT dht(DHTPIN, DHTTYPE); | |
const char* ssid = IOT_CONFIG_WIFI_SSID; | |
const char* password= IOT_CONFIG_WIFI_PASSWORD; | |
static bool messagePending = false; | |
static bool messageSending = true; | |
static int interval = INTERVAL; | |
static IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle; | |
static const char* connectionString = IOT_CONFIG_CONNECTION_STRING; | |
void setup() | |
{ | |
// put your setup code here, to run once: | |
Serial.begin(9600); | |
dht.begin(); | |
//Connect wifi | |
initWiFi(); | |
initTime(); | |
//Create AureIOtHubConnectionString | |
iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol); | |
if (iotHubClientHandle == NULL) | |
{ | |
Serial.println("Failed on IoTHubClient_CreateFromConnectionString."); | |
while (1); | |
} | |
else // added else block | |
{ | |
Serial.println(" IoTHubClient_CreateFromConnectionString Ceated"); | |
} | |
} | |
static int messageCount = 1; | |
void loop() { | |
// put your main code here, to run repeatedly: | |
delay(2000); | |
if (!messagePending && messageSending) | |
{ | |
char messagePayload[MESSAGE_MAX_LEN]; | |
readMessage(messageCount, messagePayload); | |
sendMessage(iotHubClientHandle, messagePayload); | |
messageCount++; | |
delay(interval); | |
} | |
IoTHubClient_LL_DoWork(iotHubClientHandle); | |
delay(10); | |
} | |
void initWiFi() | |
{ | |
Serial.print("Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid,password); | |
while (WiFi.status() != WL_CONNECTED) | |
{ | |
delay(500); | |
Serial.print("."); | |
} | |
if(WiFi.status() == WL_CONNECTED) | |
{ | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); | |
} | |
} | |
void readMessage(int messageId, char *payload) | |
{ | |
// get humidity reading | |
float h = dht.readHumidity(); | |
// get temperature reading in Celsius | |
float t = dht.readTemperature(); | |
// get temperature reading in Fahrenheit | |
//float f = dht.readTemperature(true); | |
// Check if any reads failed and exit early (to try again). | |
if (isnan(h) || isnan(t)) | |
{ | |
Serial.println("Failed to read from DHT sensor!"); | |
return; | |
} | |
StaticJsonBuffer<MESSAGE_MAX_LEN> jsonBuffer; | |
JsonObject &root = jsonBuffer.createObject(); | |
root["deviceId"] = DEVICE_ID; | |
root["messageId"] = messageId; | |
// NAN is not the valid json, change it to NULL | |
if (std::isnan(t)) | |
{ | |
root["temperatureC"] = NULL; | |
} | |
else | |
{ | |
root["temperatureC"] = t; | |
} | |
if (std::isnan(h)) | |
{ | |
root["humidity"] = NULL; | |
} | |
else | |
{ | |
root["humidity"] = h; | |
} | |
root.printTo(payload, MESSAGE_MAX_LEN); | |
} | |
void initTime() | |
{ | |
time_t epochTime; | |
configTime(0, 0, "pool.ntp.org", "time.nist.gov"); | |
while (true) | |
{ | |
epochTime = time(NULL); | |
if (epochTime == 0) | |
{ | |
Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry."); | |
delay(2000); | |
} | |
else | |
{ | |
Serial.printf("Fetched NTP epoch time is: %lu.\r\n", epochTime); | |
break; | |
} | |
} | |
} |
Callback function and sendmessage function file
Callback function and sendmessage function file | |
static void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *userContextCallback) | |
{ | |
if (IOTHUB_CLIENT_CONFIRMATION_OK == result) | |
{ | |
(void)printf("Message sent to Azure IoT Hub."); | |
} | |
else | |
{ | |
(void)printf("Failed to send message to Azure IoT Hub."); | |
} | |
messagePending = false; | |
} | |
static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, char *buffer) | |
{ | |
IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char *)buffer, strlen(buffer)); | |
if (messageHandle == NULL) | |
{ | |
(void)printf("Unable to create a new IoTHubMessage."); | |
} | |
else | |
{ | |
(void)printf("Sending message: %s.\r\n", buffer); | |
if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, NULL) != IOTHUB_CLIENT_OK) | |
{ | |
(void)printf("Failed to hand over the message to IoTHubClient."); | |
} | |
else | |
{ | |
messagePending = true; | |
(void)printf("IoTHubClient accepted the message for delivery."); | |
} | |
IoTHubMessage_Destroy(messageHandle); | |
} | |
} |
Azure Config file
// Copyright (c) Microsoft. All rights reserved. | |
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | |
#ifndef IOT_CONFIGS_H | |
#define IOT_CONFIGS_H | |
#define DEVICE_ID "<Give your Deviceid here>" | |
// Interval time(ms) for sending message to IoT Hub | |
#define INTERVAL 2000 | |
#define MESSAGE_MAX_LEN 256 | |
/** | |
* WiFi setup | |
*/ | |
#define IOT_CONFIG_WIFI_SSID "<Give your WIFI SSID here>" | |
#define IOT_CONFIG_WIFI_PASSWORD "<Give your WIFI password here" | |
#define IOT_CONFIG_CONNECTION_STRING "HostName=XXXX.azure-devices.net;DeviceId=XXXXX;SharedAccessKey=XXXXXXX" | |
#endif /* IOT_CONFIGS_H */ |