Azure IoT with Arduino UNO board to turn on/off LED using a .NET core console application

Mohamed Ashiq Faleel
6 min readMar 22, 2021

This post is in continuation to my journey with IoT leveraging Microsoft cloud services & it’s technology and based out of few questions I have been asked in few of the events I’ve spoken on the Topic Controlling Devices using Power Apps. In this post let us see how to turn on/off a LED connected to an Arduino UNO board by sending a message from Azure IoT hub with the help of a .NET core console application created from Visual studio code.

What is Arduino UNO Board:

Arduino Uno is an open-source & low cost microcontroller board based on Microchip ATmega328P microcontroller. The board is equipped with digital and analog Input/Output pins that can be interfaced with other circuits. If there is a need to collect data from sensors (Temperature, Humidity etc) then the mode of the pin should be Input and for controlling devices or activating relays the pin mode must be Output. For this example since we will have to turn on/off a LED, the pin mode has to set as Output.

Arduino IDE:

The IDE is a cross platform application written using C++. If you have worked with an Arduino board already, you would have probably used the Arduino IDE to deploy code called as Sketch. The code written on the sketch is compiled to a HEX file (Machine language) which can be understood by the microcontroller once the sketch is uploaded. The hex file is then sent to the Arduino UNO board using the USB port.

Pre-Requisite:

Azure IoT Hub:

IoT hub is a managed service hosted in cloud that acts as a central message hub for bi-directional communication from the device to the cloud and the cloud to the device. There is an also a Free-Tier limited to one per subscription which can add up to 500 devices and 8000 msgs/day as of today based on the Pricing calculator. Create a IoT Hub for us to send a message to the Arduino UNO device as per the instruction given in the article. After the IoT hub is created.

  • A device must be registered with your IoT hub before it can connect. There are different ways to register a device like using Azure Cloud shell, in this case we will use portal. Click IoT Devices under the Explorers blade on the IoT hub and click on + New, enter the Device ID and click save.
  • Copy the Primary key of the registered device
  • Copy the Hostname from the IoT Hub Overview blade
  • These values will be used later in the .NET console application

Arduino Sketch:

Let us now create a simple Arduino project sketch from Visual studio code to send signal to Arduino Board using the serial port with the help of the Nuget package System.IO.Ports. Make sure the Arduino IDE and the Arduino extension for VS code is installed. The Arduino board can now be plugged in to the USB port of your laptop or computer with the provided cable. Follow the below mentioned steps to create an Arduino sketch template from VS Code

  1. Create a folder on the development machine for the Arduino project and then open the folder in Visual Studio code
  2. In VS Code, hit the key CTRL+Shift+P to open the command pallete
  3. Type the command Arduino: Initialize which will try to create a file with name app.ino. Change the name of the file relevant to your project. I have named it as ControlDevicesforCSharp.ino.
  4. You will now be prompted to select the name of the Arduino board. I have selected Arduino UNO. You can also select the board and port from the VS Code right bottom corner as shown below

The serial port will be visible if the board in plugged in and recognized by the computer. This is how it looks after the board and the port is selected.

Now update the code as shown below to receive signal from the console application. If it receives a value of A to the character variable inputValue from the console application, then the PIN 13 is set to HIGH which means it generates 5v as an output and if the inputValue is B the PIN 13 is set to LOW which means the Output of the pin will be zero as opposed to 5v when set to HIGH. If you want, you can connect a LED to the PIN 13 with a 220 ohm resistor bu the pin 13 has a in-built LED to test. You can also notice on the code the PIN mode for 13 is set to Output

#define BaudRate 9600
char inputValue;
int led1 = 13;
void setup()
{
// Initialize serial communication at 9600 bits per second Serial.begin(BaudRate);// Prepare the digital output pinspinMode(led1, OUTPUT);// Initially all are offdigitalWrite(led1, LOW);}// the loop function runs over and over again forever void loop()
{
// Reads the inputinputValue = Serial.read();if(inputValue == ‘A’){// Turn on the LEDdigitalWrite(led1, HIGH);}else if (inputValue == ‘B’){// Turn off the LEDdigitalWrite(led1, LOW);}}

Now you verify the sketch by pressing CTRL+AL+R if there is any compile error. If all is well, you can now upload the sketch by pressing the key CTRL+ALT+U. If the upload is successful, you will the following message on the VS output terminal

Now the sketch is ready, it is now time to create the console application to receive message from Azure IoT hub to control the LED from cloud applications like Power Apps.

.NET core console Application:

The package System.IO.Ports supports to control serial ports which will be used to send message to Arduino board (A or B) to turn on or off the LED. Follow the below given steps to create the console application

  1. Use the same directory you have used to create the Arduino sketch. On the VS Code terminal window, enter the command dotnet new console to create a new console application
  2. Add the package System.IO.Ports using the nuget package manager plugin by CTRL+SHIFT+P > NuGet Package Manager: Add Package or enter the command on the terminal window dotnet add package System.IO.Ports –version 6.0.0-preview.1.21102.12
  3. Add the package Microsoft.Azure.Devices.Client to connect to client devices to Azure IoT Hub
  4. Use the Hostname of Azure IoT Hub, Device ID, Primary key of the Device copied earlier during the setup
  • private const string IotHubUri = “YourIoTHub.azure-devices.net”;
  • private const string deviceKey = “Your Key”;
  • private const string deviceId = “Your device ID”;

In the code the

  • Method deviceClient.ReceiveAsync() receives a message from the IoT hub queue
  • Method Encoding.ASCII.GetString(receivedMessage.GetBytes()) reads the message
  • Method deviceClient.CompleteAsync(receivedMessage, _ct) deletes the message from the queue

The following code establishes the connection on the serial port COM4

// Initialises the serial port communication on COM4SerialPort = new SerialPort(“COM4”){BaudRate = 9600,Parity = Parity.None,StopBits = StopBits.One,DataBits = 8,Handshake = Handshake.None};// Subscribe to the event SerialPort.DataReceived += SerialPortDataReceived;// Now open the port.SerialPort.Open();

With the help of the following method to Subscribe

static void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
var serialPort = (SerialPort)sender;
// Read the data that’s in the serial buffer.
var serialdata = serialPort.ReadExisting();
}
  1. The code SerialPort.Write(“A”) send the message to the Arduino Sketch.
  2. Now run the dotnet application using the command dotnet run. Now send a message from the Azure IoT explorer or from Azure portal IoT device explorer ON1 or Off1 to turn On/Off the LED connected to PIN 13

The complete code is uploaded in my Github here.

Originally posted at https://ashiqf.com/2021/02/28/azure-iot-with-arduino-uno-board-to-turn-on-off-led-using-a-net-core-console-application-connected-to-power-apps/

--

--