In this article we will show you how to create an IoT Hub and connect your IoT Device.

Pre-requisites

  • Required Hardware:
    • Windows 10 PC
    • IoT Hardware kit: https://www.adafruit.com/product/3605 or similar hardware.
    • Access to a WiFi network 
  • Required Operating System:
    • Windows 10
  • Other Requirements:
    • Azure Subscription
  • Required Software:
    •  IoT Device Explorer, download: https://github.com/Azure/azure-iot-sdk-csharp/releases/download/2017-1023/SetupDeviceExplorer.msi

Steps:

Verify you properly setup your IoT Device Connectivity

please refer to https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide

Create an IoT Hub

Now you will create an IoT Hub in the Azure Portal. Go to the Azure Portal, click Create new and type “iot hub”:

Create IoT Hub

Now provide the following parameters to create your IoT Hub: 

IoT Hub Parameters

Verify the IoT Hub is successfully created: 

IoT Hub created

NG the Shared Access Policies  

IoT Shared Access Policies

Click Shared Access Policies,

Select “iothubowner” and enable “registry write” and copy the Shared access keys:

 Go back to your desktop and open the Device Explorer Twin,

If not already installed, install (https://github.com/Azure/azure-iot-sdkcsharp/releases/download/2017-10-23/SetupDeviceExplorer.msi ) and run the Device Explorer: 

IoT Device Explorer Twin - wikiazure

Provide a name for your IoT Device

Select the Management label and Click on Create Device, provide a name for your IoT Device and then paste the Shared Access Credentials you previously copied:

Create IoT Device on Device Explorer Twin - wikiazure

You will see a notification when the device is successfully created: 

Iot Device created - wikiazure

Copy connection string for the selected device

  9. In the Management label, right-click the device you just created and click “Copy connection string for the selected device” 

Device Explorer copy connection - wikiazure

 Launch Arduino.

You can download it from here:

https://www.arduino.cc/download_handler.php?f=/arduino-1.8.5-windows.exe .

 

Add the Microsoft IoT and Arduino libraries by clicking Sketch -> Include Library à-> Manage Libraries and search for “AzureIoT”. Install the library AzureIoTHub by Arduino, the AzureIoTProtocol_MQTT by Microsoft and AzureIoTUtility by Microsoft, as shown below.

Starting with a new sketch, copy the following code:

#include <ESP8266WiFi.h>
#include <ESP8266WiFiAP.h>
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiScan.h>
#include <ESP8266WiFiSTA.h>
#include <ESP8266WiFiType.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
  
#include <AzureIoTUtility.h>
#include <AzureIoTHub.h>
#include <AzureIoTProtocol_MQTT.h>
  
#include <DHT.h>
  
String ssid                         = "iot";        // your network SSID (name)
String pass                         = "microsoft" // your network password (use for WPA, or use as key for WEP)
static const char* connectionString = "HostName=daveiotdemo1.azure-devices.net;DeviceId=daveie;SharedAccessKey=1298128GASJDA12=";
#define DHTPIN 2                                   // what digital pin we're connected to
#define DHTTYPE DHT22                               // DHT11 or DHT22
  
IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
IOTHUB_CLIENT_STATUS status;
  
WiFiClientSecure espClient;
  
DHT dht(DHTPIN, DHTTYPE);
  
void initWifi() {
    if (WiFi.status() != WL_CONNECTED)
    {
        WiFi.stopSmartConfig();
        WiFi.enableAP(false);
  
        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        WiFi.begin(ssid.c_str(), pass.c_str());
      
        Serial.print("Waiting for Wifi connection.");
        while (WiFi.status() != WL_CONNECTED) {
            Serial.print(".");
            delay(500);
        }
      
        Serial.println("Connected to wifi");
  
        initTime();
        initIoTHub();
    }
}
  
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.print("Fetched NTP epoch time is: ");
            Serial.println(epochTime);
            break;
        }
    }
}
  
static void sendMessage(const char* message)
{
    static unsigned int messageTrackingId;
    IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromString(message);
  
    if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendMessageCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK)
    {
        Serial.println(" ERROR: Failed to hand over the message to IoTHubClient");
    }
    else
    {
      (void)printf(" Message Id: %u Sent.\r\n", messageTrackingId);
    }
  
    IoTHubMessage_Destroy(messageHandle);
    messageTrackingId++;
}
  
void sendMessageCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
{
    unsigned int messageTrackingId = (unsigned int)(uintptr_t)userContextCallback;
  
    (void)printf(" Message Id: %u Received.\r\n", messageTrackingId);
}
  
static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessageCallback(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
{
    IOTHUBMESSAGE_DISPOSITION_RESULT result = IOTHUBMESSAGE_ACCEPTED;
      
    const char* messageId = "UNKNOWN";      // in case there is not a messageId associated with the message -- not required
    messageId = IoTHubMessage_GetMessageId(message);
  
    const unsigned char* buffer;
    size_t size;
    if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK)
    {
        Serial.println(" Error: Unable to IoTHubMessage_GetByteArray");
        result = IOTHUBMESSAGE_ABANDONED;
    }
    else
    {
        char* tempBuffer = (char*)malloc(size + 1);
        if (tempBuffer == NULL)
        {
            Serial.println(" Error: failed to malloc");
            result = IOTHUBMESSAGE_ABANDONED;
        }
        else
        {
            result = IOTHUBMESSAGE_ACCEPTED;
            (void)memcpy(tempBuffer, buffer, size);
              
            String messageStringFull((char*)tempBuffer);
            String messageString = "UNKNOWN";
            messageString = messageStringFull.substring(0,size);
  
/*            if (messageString.startsWith("OTA")) {
                  String fullURL = messageString.substring(messageString.indexOf("://") - 4);;
                  // t_httpUpdate_return OTAStatus = OTA.update(fullURL.c_str());
                  // if we do OTA, then we never return the IOTHUBMESSAGE_ACCEPTED and we have issues
            }*/
              
            String messageProperties = "";
            MAP_HANDLE mapProperties = IoTHubMessage_Properties(message);
            if (mapProperties != NULL)
            {
            const char*const* keys;
            const char*const* values;
            size_t propertyCount = 0;
            if (Map_GetInternals(mapProperties, &keys, &values, &propertyCount) == MAP_OK)
                {
                if (propertyCount > 0)
                    {
                    size_t index;
                    for (index = 0; index < propertyCount; index++)
                        {
                            messageProperties += keys[index];
                            messageProperties += "=";
                            messageProperties += values[index];
                            messageProperties += ",";
                        }
                    }
                }
            }
  
            Serial.print(" Message Id: ");
            Serial.print(messageId);
            Serial.print(" Received. Message: \"");
            Serial.print(messageString);
            Serial.print("\", Properties: \"");
            Serial.print(messageProperties);
            Serial.println("\"");
        }
        free(tempBuffer);
    }
    return result;
}
  
void initIoTHub() {
  iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
  if (iotHubClientHandle == NULL)
  {
      (void)printf("ERROR: Failed on IoTHubClient_LL_Create\r\n");
  } else {
    IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessageCallback, NULL);
  }
}
  
void LEDOn() {
  digitalWrite(LED_BUILTIN, LOW);
}
  
void LEDOff() {
  digitalWrite(LED_BUILTIN, HIGH);
}
  
void setup() {
  Serial.begin(115200);
  dht.begin();
  initWifi();
  pinMode(LED_BUILTIN, OUTPUT);
  LEDOff();
}
  
void loop() {
  initWifi();         // always checking the WiFi connection
  LEDOn();
  
  // we will process every message in the Hub
  while ((IoTHubClient_LL_GetSendStatus(iotHubClientHandle, &status) == IOTHUB_CLIENT_OK) && (status == IOTHUB_CLIENT_SEND_STATUS_BUSY))
  {
      IoTHubClient_LL_DoWork(iotHubClientHandle);
      ThreadAPI_Sleep(1000);
  }
    
  String  JSONMessage = "{\'temperature\':";
          JSONMessage += dht.readTemperature();
          JSONMessage += "}";
  sendMessage(JSONMessage.c_str()); 
  
  LEDOff();
  delay(5000);
}
Modify the SSID, password, and connectionString on lines 18 – 20 as shown below and click “Compile and Upload”:
String ssid                         = "iot";        // your network SSID (name)
String pass                         = "microsoft" // your network password (use for WPA, or use as key for WEP)
static const char* connectionString = "HostName=daveiotdemo1.azure-devices.net;DeviceId=daveie;SharedAccessKey=1298128GASJDA12=";

Go back to the Device Explorer.

Click Message To Device. Type a message, add any desired properties and click Send, as shown below:

sensor-connected-IoT-Device-wikiazure

Tried to take a closer picture of the device in case you want to validate your sensor connectivity:

sensor IoT Device - wikiazure

Using Serial Monitor, you should be able to look the Humidity Percentage, temperature in °C and °F:

Monitoring-Temperature-IoT-Device-wikiazure

You should also be able to monitor the messages through Serial Monitor as shown below:

IoT Device Serial Monitor - wikiazure

This completes the article on how to Create an IoT Hub and connect your IoT Device. 

Conclusion: 

Azure provides a robust platform for IoT with seamless integration and a diversity of hardware providers certified to enable IoT solutions in a seamless way. 

Other Languages:

  - Azure: Crear IoT Hub y conectar un dispositivo IoT (es-MX)