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


  • Required Hardware:
    • Windows 10 PC
    • IoT Hardware kit: or similar hardware.
    • Access to a WiFi network 
  • Required Operating System:
    • Windows 10
  • Other Requirements:
    • Azure Subscription
  • Required Software:
    •  IoT Device Explorer, download:


Verify you properly setup your IoT Device Connectivity

please refer to

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 ( ) 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: .


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 = ";DeviceId=daveie;SharedAccessKey=1298128GASJDA12=";
#define DHTPIN 2                                   // what digital pin we're connected to
#define DHTTYPE DHT22                               // DHT11 or DHT22
WiFiClientSecure espClient;
void initWifi() {
    if (WiFi.status() != WL_CONNECTED)
        // 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.println("Connected to wifi");
void initTime() {
    time_t epochTime;
    configTime(0, 0, "", "");
    while (true) {
        epochTime = time(NULL);
        if (epochTime == 0) {
            Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry.");
        } else {
            Serial.print("Fetched NTP epoch time is: ");
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");
      (void)printf(" Message Id: %u Sent.\r\n", 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)
    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");
        char* tempBuffer = (char*)malloc(size + 1);
        if (tempBuffer == NULL)
            Serial.println(" Error: failed to malloc");
            result = IOTHUBMESSAGE_ABANDONED;
            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(" Received. Message: \"");
            Serial.print("\", Properties: \"");
    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() {
void loop() {
  initWifi();         // always checking the WiFi connection
  // we will process every message in the Hub
  while ((IoTHubClient_LL_GetSendStatus(iotHubClientHandle, &status) == IOTHUB_CLIENT_OK) && (status == IOTHUB_CLIENT_SEND_STATUS_BUSY))
  String  JSONMessage = "{\'temperature\':";
          JSONMessage += dht.readTemperature();
          JSONMessage += "}";
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 = ";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:


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:


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. 


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)