Starting with Windows IoT On Raspberry Pi
In this article, 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.
- A Raspberry Pi board ( I am using Raspberry pi 2) with an SD Card of at least 8 GB.
- Windows IoT dashboard in your laptop. You can download the Windows IoT dashboard from this link.
- 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 the IoT dashboard. You will see your SD card detected by the dashboard. Enter the fields and remember the username (will be an 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 the 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 the coming parts, I will be talking about connecting Pi with a 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 on 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
- Azure account. (if you don’t have, you can create a free trial account).
- Visual Studio 2015.
After successful login to Azure, follow these steps to create an IoT Hub.
Click +(NEW) > Internet of Things > IoT Hub.
Enter the necessary details to complete the process.
-
Name Give a name to your Hub
- Pricing Select Free basic
- Subscription Your Azure subscription
- Resource group Creates 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 the 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 the 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//docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-getstarted //
- using System;
- using System.Threading.Tasks;
- using Microsoft.Azure.Devices;
- using Microsoft.Azure.Devices.Common.Exceptions;
- namespace CreateDeviceIdentity {
- class Program {
- static RegistryManagerregistryManager;
- static string connectionString = ”The connection string you copied earlier from iotHUB“;
- private static async Task AddDeviceAsync() {
- string deviceId = “myFirstDevice”;
- Device device;
- try {
- device = await registryManager.AddDeviceAsync(new Device(deviceId));
- } catch (DeviceAlreadyExistsException) {
- device = await registryManager.GetDeviceAsync(deviceId);
- }
- Console.WriteLine(“Generated device key {
- 0
- }”, device.Authentication.SymmetricKey.PrimaryKey);
- }
- static void Main(string[] args) {
- registryManager = RegistryManager.CreateFromConnectionString(connectionString);
- AddDeviceAsync().Wait();
- Console.ReadLine();
- }
- }
- }
2. Install reference package using NuGet Package Manager> install microsoft.azure.devices 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.
- IoT Hub Host name.
- Device id.
- Device Key.
Sending sensor values to Azure IoT Hub
I will be using the following to complete this article
- Raspberry Pi 2 with Windows IoT.
- 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.
- 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//marketplace.visualstudio.com/items?itemName=MicrosoftIoT.WindowsIoTCoreProjectTemplates //.
- Enable developer mode on your laptop. Follow the link
- 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 the previous article)
Now open Visual Studio > Create new project > Windows > Blank App(Universal).
Add references using the 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
- using System;
- using Windows.UI.Xaml.Controls;
- using System.Threading;
- using System.Text;
- using Microsoft.Azure.Devices.Client;
- using GrovePi;
- using GrovePi.Sensors;
- namespaceiotApp {
- public sealed partial class MainPage Page {
- privateconst string IOT_HUB_CONN_STRING = “HostName = your iot hub hostname;
- DeviceId = yourdeviceid;
- SharedAccessKey = the device key you generated”;
-
-
- privateconst string IOT_HUB_DEVICE = “myFirstDevice”;
- ILed led = DeviceFactory.Build.Led(Pin.DigitalPin2);
- IDHTTemperatureAndHumiditySensor sensor = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin4, DHTModel.Dht11);
- ILightSensor intensity = DeviceFactory.Build.LightSensor(Pin.AnalogPin0);
- private DeviceClientdeviceClient;
- private Timer readSensorTimer;
- publicMainPage() {
- this.InitializeComponent();
- InitAllAsync();
- }
- private void InitAllAsync() {
- readSensorTimer = new Timer(this.SensorTimer_Tick, null, 0, 5000);
- deviceClient = DeviceClient.CreateFromConnectionString(IOT_HUB_CONN_STRING);
- StatusText.Text = “Status Running”;
- }
- private void SensorTimer_Tick(object state) {
- if (led.CurrentState == SensorStatus.Off) {
- led.ChangeState(SensorStatus.On);
- } else {
- led.ChangeState(SensorStatus.Off);
- }
- string Light = intensity.SensorValue().ToString();
- sensor.Measure();
- string temparuture = sensor.TemperatureInCelsius.ToString();
- string humidity = sensor.Humidity.ToString();
- SendMessageToIoTHubAsync(temparuture, humidity, Light);
- }
- privateasync void SendMessageToIoTHubAsync(string temperature, stringhumidity, string Light) {
- try {
- var payload = “ {\”
- deviceId\” \””+IOT_HUB_DEVICE + “\”,
- \”humidity\” \””+humidity + “\”,
- \”Light\” \””+Light + “\”,
- \”messurementValue\” ”+temperature + “,
- \”messurementType\” \”Temperature\”,
- \”localTimestamp\”: \””+DateTime.Now.ToLocalTime().ToString() + “\”
- }”;
- var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
- MessageLog.Text = “Sending message ”+payload + “\n” + MessageLog.Text;
- });
- varmsg = new Message(Encoding.UTF8.GetBytes(payload));
- await deviceClient.SendEventAsync(msg);
- } catch (Exception ex) {
- var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
- MessageLog.Text = “Sending message ”+ex.Message + “\n” + MessageLog.Text;
- });
- }
- }
- }
- }
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 the IoT dashboard and paste it in the address tab. Select and save. Run the application. This will deploy the app to pi and start sending sensor values to iothub. If you go to monitor option in device explorer you will see messages sent to Azure IoT.
In the next part, I will show how to create stream analytics and put the sensor values into an Azure SQL data base.
Stream analytics in azure Part four
In this, you will create stream analytics to send data from iothub to an azure sqldatabase.
First we have to create a azure db.click+(NEW) >databases>sql database.
Give your db any name(grovedb) and select your subscription. Select basic 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 for 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 the 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 the image below. Choose event serialization format as JSON and encoding as UTF-8. Click create.
Now create an output
Output aliassensorop
Sink
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
- SELECT
- AVG(messurementValue) as Temp,
- AVG(humidity) as Humidity,
- AVG(Light) as Light,
- MAX(CAST([localTimestamp] AS datetime)) as Time
- INTO
- [sensorop]//(urstreamanalytic o/p you created)
- FROM
- [sensorip] // uri/p
- GROUP BY
- deviceId,
- 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 the IoT hub. After a couple of minutes check the table you created by switching to Visual Studio and click view data to see the table contents inserted by the stream. The following image data in the 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 the "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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data.SqlClient;
- namespace tempWeb {
- public partial class Sensor System.Web.UI.Page {
- SqlConnection con = new SqlConnection(“Server = tcp grovepi.database.windows.net, 1433; Initial Catalog = grovedb; Persist Security Info = False; User ID = joseph; Password = ** ** * ; MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = False; Connection Timeout = 30;”);
- protected void Page_Load(object sender, EventArgs e) {
- con.Open();
- SqlCommanddataCommand = new SqlCommand();
- dataCommand.Connection = con;
- dataCommand.CommandText = (“SELECT TOP(1) Temp FROM[dbo].[Sensor] ORDER BY ID DESC”);
- int temperature = Convert.ToInt32(dataCommand.ExecuteScalar());
- Label1.Text = “Current Temperature = ”+temperature.ToString() + “°C”;
- dataCommand.CommandText = (“SELECT TOP(1) Humidity FROM[dbo].[Sensor] ORDER BY ID DESC”);
- int Humidity = Convert.ToInt32(dataCommand.ExecuteScalar());
- Label2.Text = “Current Humidity = ”+Humidity.ToString() + “ % ”;
- dataCommand.CommandText = (“SELECT TOP(1) Light FROM[dbo].[Sensor] ORDER BY ID DESC”);
- int Light = Convert.ToInt32(dataCommand.ExecuteScalar());
- Label3.Text = “Current Light Intensity = ”+Light.ToString() + ”lx”;
- GridView1.DataBind();
- con.Close();
- }
- }
- }
Save and Run.