Getting Started With Windows IoT On Raspberry Pi

Starting with Windows IoT On Raspberry Pi

In this article, you you will learn how to connect Raspberry Pi on your laptop and how to install Windows IoT on Raspberry Pi. Before you continue, you need to have the following.

  1. A Raspberry Pi board ( I am using Raspberry pi 2) with an SD Card of at least 8 GB.
  2. Windows IoT dashboard in your laptop. You can download Windows IoT dashboard from this link.
  3. An ethernet cable to connect Raspberry Pi to your laptop and to connect your Pi to the internet. (You can alternatively connect your Pi with a Wi-Fi dongle).

Open the Windows IoT dashboard after completing the installation. Connect your SD card to your laptop. Click "Create new device" on IoT dashboard .You will see your SD card detected by dashboard. Enter the fields and remember the username (will be administrator by default) and password which you will be needing later.


Click "Download and install". It will take few minutes (depending on your internet speed) to install the Windows IoT on the SD card.

After completing the installation, insert the SD card to Raspberry Pi. Connect the Raspberry Pi to the laptop with an ethernet cable. Power up the Raspberry Pi with the power adapter (or you can use a USB data cable to power the Pi). It will take a few seconds for Pi to boot and the green light in the Raspberry Pi will stop blinking if everything goes fine. (If green light stays on, reinsert the SD card and Restart the Pi).

If Pi is successfully booted, you will see your Pi in IoT dashboard under "My devices". I have renamed my Pi  Groovepi.


Now, to connect your Raspberry Pi to the internet go to Network Settings> Ethernet > Change Adapter Settings. Now, select your WiFi connection + Ethernet together > right click > create bridge connection > done.

//(for now, you need to share internet through your laptop. After you have completed your work with Pi, you can simply connect it to the router directly) //


After completion, go back to IoT Dashboard (reopen). You will notice that the Pi IP has changed.

Right click on Pi and select "Open in device portal". Username is administrator and enter the password you created earlier. You will be logged into the Windows IoT device.


Now, you have connected the Raspberry Pi to the laptop and enabled internet access to Pi.

In coming parts, I will be talking about connecting Pi with grove starter kit and sending sensor values to Azure IoT Hub. Later, we will discuss how to put these sensor values to Azure SQLdb and displaying these data in a website.

Creating an Azure IoT Hub and creating a device Id 

In this part, you will learn how to create an Azure IoT Hub and how to create a device identity in Azure to connect your device.

To complete this article, you need to have the following

  1. Azure account. (if you don’t have, you can create a free trial account).
  2. Visual Studio 2015.

    After successful login to Azure, follow these steps to create an IoT Hub.

    Click +(NEW) > Internet of Things > IoT Hub.


    Enter necessary details to complete the process.

    Name  Give a name to your Hub

    Pricing  Select Free basic

     Your Azure subscription

    Resource group  Create a resource group named Pi.

    Location  Where you want to put your IoT Hub (I selected Southeast Asia)

Click "Create".

This will create a new IoT Hub in your Azure account.
Now click the IoT Hub you created. Copy the IoT Hub hostname and note it somewhere.
Click "Shared Access Policy" under General section.
Click on IoT Hub Owner Policy. A side window will open showing primary key and connection string.
Copy the primary connection string and note it somewhere.
Now, you need to create a device id to connect your device to IoT HUB. For that, follow the steps below.

1. Open Visual Studio> New project > create a new console application> write the following code in program.cs.
This code is available on // https// //
  1. using System;  
  2. using System.Threading.Tasks;  
  3. using Microsoft.Azure.Devices;  
  4. using Microsoft.Azure.Devices.Common.Exceptions;  
  5. namespace CreateDeviceIdentity {  
  6.     class Program {  
  7.         static RegistryManagerregistryManager;  
  8.         static string connectionString = ”The connection string you copied earlier from iotHUB“;  
  9.         private static async Task AddDeviceAsync() {  
  10.             string deviceId = “myFirstDevice”;  
  11.             Device device;  
  12.             try {  
  13.                 device = await registryManager.AddDeviceAsync(new Device(deviceId));  
  14.             } catch (DeviceAlreadyExistsException) {  
  15.                 device = await registryManager.GetDeviceAsync(deviceId);  
  16.             }  
  17.             Console.WriteLine(“Generated device key {  
  18.                 0  
  19.             }”, device.Authentication.SymmetricKey.PrimaryKey);  
  20.         }  
  21.         static void Main(string[] args) {  
  22.             registryManager = RegistryManager.CreateFromConnectionString(connectionString);  
  23.             AddDeviceAsync().Wait();  
  24.             Console.ReadLine();  
  25.         }  
  26.     }  
  27. }  
2. Install reference package using NuGet Package Manager> install package
Run the application.


This will register your device id (here myFirstDevice) in Azure and also generate a device key in console output . You need to note down this device key which will be needed later.

After completing this article, you will have the following with you. 
  1. IoT Hub Host name.
  2. Device id .
  3. Device Key.

Sending sensor values to Azure IoT Hub

I will be using the following to complete this article
  1. Raspberry Pi 2 with Windows IoT.
  2. Grove starter kit with grove sensors. (Temperature and humidity sensor, Light Sensor).


    Connect a grove LED to digital pin 2. Temperature sensor to digital pin 4 .Light sensor to analog pin 0.

  3. Visual Studio 2015.

    You will need to update Visual Studio. Install Update 3 from the Extensions and Update dialog in Visual Studio. Also you need to install Universal Windows App Development Tools in Visual Studio if not already installed. Download and install Windows IoT Core Project Templates from the following link .// https// //.

  4. Enable developer mode on your laptop. Follow the link 

  5. Install Device explorer.(This tool can be used to see the messages we send to iot hub . Also it can be used to create a new device id and device key. Connect device explorer with iot hub connection string which we created in previous article)

    Now open Visual Studio > Create new project > Windows > Blank App(Universal).

    Add references using nuget package manager. Right click on references in solution explorer>Manage Nuget Packages >Online tab> add the 3 highlighted packages shown in the image below .


    The code for the mainpage.xaml.cs is given below
    1. using System;  
    2. using Windows.UI.Xaml.Controls;  
    3. using System.Threading;  
    4. using System.Text;  
    5. using Microsoft.Azure.Devices.Client;  
    6. using GrovePi;  
    7. using GrovePi.Sensors;  
    8. namespaceiotApp {  
    9.     public sealed partial class MainPage Page {  
    10.         privateconst string IOT_HUB_CONN_STRING = “HostName = your iot hub hostname;  
    11.         DeviceId = yourdeviceid;  
    12.         SharedAccessKey = the device key you generated”;  
    13.         /*( 
    14.         all three of these where created in previous article.Paste it here.)*/  
    15.         privateconst string IOT_HUB_DEVICE = “myFirstDevice”;  
    16.         ILed led = DeviceFactory.Build.Led(Pin.DigitalPin2);  
    17.         IDHTTemperatureAndHumiditySensor sensor = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin4, DHTModel.Dht11);  
    18.         ILightSensor intensity = DeviceFactory.Build.LightSensor(Pin.AnalogPin0);  
    19.         private DeviceClientdeviceClient;  
    20.         private Timer readSensorTimer;  
    21.         publicMainPage() {  
    22.             this.InitializeComponent();  
    23.             InitAllAsync();  
    24.         }  
    25.         private void InitAllAsync() {  
    26.             readSensorTimer = new Timer(this.SensorTimer_Tick, null, 0, 5000);  
    27.             deviceClient = DeviceClient.CreateFromConnectionString(IOT_HUB_CONN_STRING);  
    28.             StatusText.Text = “Status Running”;  
    29.         }  
    30.         private void SensorTimer_Tick(object state) {  
    31.             if (led.CurrentState == SensorStatus.Off) {  
    32.                 led.ChangeState(SensorStatus.On);  
    33.             } else {  
    34.                 led.ChangeState(SensorStatus.Off);  
    35.             }  
    36.             string Light = intensity.SensorValue().ToString();  
    37.             sensor.Measure();  
    38.             string temparuture = sensor.TemperatureInCelsius.ToString();  
    39.             string humidity = sensor.Humidity.ToString();  
    40.             SendMessageToIoTHubAsync(temparuture, humidity, Light);  
    41.         }  
    42.         privateasync void SendMessageToIoTHubAsync(string temperature, stringhumidity, string Light) {  
    43.             try {  
    44.                 var payload = “ {\”  
    45.                     deviceId\” \””+IOT_HUB_DEVICE + “\”,  
    46.                     \”humidity\” \””+humidity + “\”,  
    47.                     \”Light\” \””+Light + “\”,  
    48.                     \”messurementValue\” ”+temperature + “,  
    49.                     \”messurementType\” \”Temperature\”,  
    50.                     \”localTimestamp\”: \””+DateTime.Now.ToLocalTime().ToString() + “\”  
    51.                 }”;  
    52.                 var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {  
    53.                     MessageLog.Text = “Sending message ”+payload + “\n” + MessageLog.Text;  
    54.                 });  
    55.                 varmsg = new Message(Encoding.UTF8.GetBytes(payload));  
    56.                 await deviceClient.SendEventAsync(msg);  
    57.             } catch (Exception ex) {  
    58.                 var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {  
    59.                     MessageLog.Text = “Sending message ”+ex.Message + “\n” + MessageLog.Text;  
    60.                 });  
    61.             }  
    62.         }  
    63.     }  
    64. }  

If you have gone through the first article you will have a pi running with internet access now. Now we are going to deploy the app we created into the pi. Go to solution explorer right click on properties > open >


Under the debug option select target option as remote machine and click find .This will open a new window.


If your pi is auto detected click select and save. If pi is not detected automatically copy the pi IP address from IoT dashboard and paste it in address tab. Select and save. Run the application. This will deploy app to pi and start sending sensor values to iothub. If you go to monitor option in device explorer you will see messages send to Azure iot.

In the next part I will show how to create a stream analytics and put the sensor values into a Azure SQL data base.

Stream analytics in azure Part four

In this you will create a stream analytics to send data from iothub to a azure sqldatabase.

First we have to create a azure >databases>sql database.

Give your db any name(grovedb) and select your subscription. Select basic in pricing. Create a new server and select the location (if you have chosen Southeast Asia in iothub select the same here). While creating the SQL server save the username and password you are  using somewhere (this will be needed later ). After creating the server click create sqldb.


Now you have created a SQL database in Azure and we are going to create a table in this db. For that open Visual Studio and connect Visual Studio to Azure using your Azure login credentials. In the server explorer you will see your Azure data server.


Click on sqldatabases,after few seconds your database will come up. Right click on your database and select open in SQL server object explorer. (You will be asked for login credentials you used when you created Azure SQL server).After a few seconds a SQL server object explorer will be opened.


Select your db> right click > create new table.Here is my table(Sensor) code.


After table design click on update option top left corner. This will update the table you created to Azure.

Now go to your azure portal >+(NEW) > Internet of Things >Stream Analytics Job>


Enter required fields

  • job name iotStream(give any name).
  • subscription your subscription.

Select same resource group and location as when you created your iothub.Click create.

Go to the stream analytics you created and under the job topology click on input. Select add an input. Give a name (sensorip). Select your IoT hub and follow as in image below. Choose event serialization format as JSON and encoding as UTF-8.Click create.


Now create a output
Output aliassensorop


sql database > subscription > use sqldb from current subscription.>select db you created.
enterservername,username, password, and table you created.

Click create output

Now add a new query. Look at the following code of query

AVG(messurementValue) as Temp,
AVG(humidity) as Humidity,
AVG(Light) as Light,
MAX(CAST([localTimestamp] AS datetime)) as Time
[sensorop]//(urstreamanalytic o/p you created)
[sensorip] // uri/p
TumblingWindow(minute, 1)

Click save and start the stream analytic job. Start your pi and run the app we created earlier to send sensor values to IoT hub. After a couple minutes check the table you created by switching to Visual Studio and click view data to see the table contents inserted by stream.The following image data in table is created.


Displaying Data in a web application from Azure SQLdb 

Now, we have our data in Azure SQLdb.

To display this data in a web application, open VS >> New Project >> New Web Application >> Empty >> Add a new webform to your project.

To connect to your database, go to "Tools" tab and click "Connect to a database" or you can connect to Azuredb by copying the database connection string from Azure, by selecting the database you created.
Change the Authentication to SQL Server.


In the Design section of the page, add a GridView to connect to your table. Add a new SQL data source to the GridView Controller (use the connection string you created earlier).


Add a timer and a panel if you want to automatically refresh your page.

Here is the code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data.SqlClient;  
  8. namespace tempWeb {  
  9.     public partial class Sensor System.Web.UI.Page {  
  10.         SqlConnection con = new SqlConnection(“Server = tcp, 1433; Initial Catalog = grovedb; Persist Security Info = False; User ID = joseph; Password = ** ** * ; MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = False; Connection Timeout = 30;”);  
  11.         protected void Page_Load(object sender, EventArgs e) {  
  12.             con.Open();  
  13.             SqlCommanddataCommand = new SqlCommand();  
  14.             dataCommand.Connection = con;  
  15.             dataCommand.CommandText = (“SELECT TOP(1) Temp FROM[dbo].[Sensor] ORDER BY ID DESC”);  
  16.             int temperature = Convert.ToInt32(dataCommand.ExecuteScalar());  
  17.             Label1.Text = “Current Temperature = ”+temperature.ToString() + “°C”;  
  18.             dataCommand.CommandText = (“SELECT TOP(1) Humidity FROM[dbo].[Sensor] ORDER BY ID DESC”);  
  19.             int Humidity = Convert.ToInt32(dataCommand.ExecuteScalar());  
  20.             Label2.Text = “Current Humidity = ”+Humidity.ToString() + “ % ”;  
  21.             dataCommand.CommandText = (“SELECT TOP(1) Light FROM[dbo].[Sensor] ORDER BY ID DESC”);  
  22.             int Light = Convert.ToInt32(dataCommand.ExecuteScalar());  
  23.             Label3.Text = “Current Light Intensity = ”+Light.ToString() + ”lx”;  
  24.             GridView1.DataBind();  
  25.             con.Close();  
  26.         }  
  27.     }  
  28. }  
Save and Run.