# Easily Send JSON to IoT Hub with C#

I recently needed to send JSON that an IoT Hub could receive and display on an AZ3166 device. Once the AZ3166 device receives the message, then it could do a number of things with the data such as open an door.

Part 1:

  • Create an IoT Hub and provision the MX Chip (AZ3166) as a device. While we could go into the Azure Portal and create a new IoT Hub and walk through the setup of our device, etc. There is an easier way.
  • Download the tools (opens new window)
  • Open VS Code, look under Arduino Examples and open the GetStarted sample and run task cloud-provision in the VS Code terminal..
  • If you switch over to the Azure Portal, and look under your new IoT, then Devices - you should see your new device.

Part 2:

  • I took the code from the “GetStarted” sample found in VS Code and tweaked the Screen.print(0, "Unlock Door"); lines in the GetStarted.ino file in the Setup method.
  • Now on my deivce it prints the “Unlock Door” message in fancy yellow and displays the IP Address and waits for a message to be sent to IoT Hub.

Part 3:

  • Open Visual Studio and create a console application.
  • Add NuGet package : Microsoft.Azure.Devices (Service SDK for Azure IoT Hub)
  • I hardcoded my connection string (found in IoT Hub) and mocked the JSON data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices;

namespace SendMessageToIoTHub
{
    class Program
    {
        static ServiceClient serviceClient;
        static string connectionString = "mykey";

        static void Main(string[] args)

        {
            serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
            SendCloudToDeviceMessageAsync().Wait();
            Console.ReadLine();
        }

        private async static Task SendCloudToDeviceMessageAsync()
        {
            string mockedJsonData =

                "{ \"Locked\":true}";

            var commandMessage = new Message(Encoding.ASCII.GetBytes(mockedJsonData));
            await serviceClient.SendAsync("AZ3166", commandMessage);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

Part 4:

  • The MX Board receives the message from IoT Hub
  • It prints the JSON message from the serviceClient code above to the board display.