Hello Ranger

Figure 1 Ultrasonic sensor, HC-SR504

HELLO RANGER
The ability to estimate the distance using a sensor enables several applications:
Length measurement
Obstacle detection
Linear travel range
Liquid level indicator
This application note uses an ultrasonic sensor, HC-SR504, to illustrate these applications.
Bill of Materials
The table below summarizes the key components to build the circuit for the initial round of tests:
Part type Description Quantity
LED LED with legs, assorted colors 3
Resistor Resistor, 220Ω ±5% 3
UNO Arduino UNO Rev 3 1
Sensor Ultrasonic sensor, HC-SR504 1
BBH Breadboard, half-size 1
Wires DuPont connection wire, male-to-male, assorted colors and length 14

Schematic diagram
The schematic diagram for the initial round of tests is shown below:

Figure 3 Green LED on

Assembly
The components may be assembled as shown in the figure below. Any unintentional obstruction of the signal path in front of the transmitter and receiver pair of the sensor (e.g. protruding wires) should be avoided.
Operation
The ultrasonic sensor, HC-SR504, has four pins. Viewing the sensor from front in elevation view, the pins are as follows from left to right:
VCC, +5V DC
Trigger for pulse, input
Echo detector, output
GND
Timing Diagram
The diagram below summarizes the operation of the sensor:
When the state of the trigger pin changes from LOW to HIGH and lasts for more than 40 microseconds, the module’s piezo element transmits a burst of 8 cycles at 40kHz (approximately 200 microseconds total)
The duration of the echo for this burst at the receiver represents the time taken for the signal to travel from the piezo element to the reflecting object and then back to the echo receiver

Figure 5 Yellow LED on

The echo width is converted to a distance measurement using the basic formula based on the speed of sound.
The maximum echo width for the sensor is approximately 30 milliseconds which varies nominally depending on the manufacturer’s specifications for the sensor. The corresponding timeout value for the echo detection is 38 milliseconds which represents the state that no echo was received.
The best practice recommendation for this sensor is to not issue another trigger request until 60 milliseconds have elapsed since the previous request. It is also prudent to reset the echo detection (see example code) in the event of a timeout.
Estimating Distance
The equation for the speed of sound is:
a= √γRT
a=speed of sound
γ,ratio of specific heats=1.4 for air at standard temperature and pressure
R,gas constant=286 m^2/(s^2 K)
T,absolute temperature=273.15+°C

A simpler derivation from the above equation is:
a=331.3+0.06t
a=speed of sound,
t,temperature,°C
This simpler derivation does not account for changes in the value of γ (heat capacity ratio) for barometric and hygrometric changes from the standard.
For the purposes of the current exercise, the speed of sound at 25°C and standard atmospheric conditions with no humidity is 346.3 meters/second. This value can be recast to 0.03463 centimeters per microsecond.
Distance= (〖time〗_pulse*〖speed〗_sound)/2
Since the pulse travels twice the distance between the sensor and sound reflecting object, the scale multiplier in effect is 0.01732.
Test case
There were two test cases for this assembly using:
The PulseIn method
The hardware external interrupt
PulseIn Method
This approach, as the name implies, relies on the Arduino library method called PulseIn to determine the duration of the pulse echo. Since there is no external trigger is applied, this approach relies on constant polling which may lead inefficient use of computing cycles in the general sense.
Hardware External Interrupt
This approach measures the elapsed time between the RISING and FALLING states of the echo signal on the assigned pin. While this approach is more efficient if nominal timeout considerations are built into the measurement.
Caution
Since the HC-SR504 may be sourced from a variety of sources, the quality of specific versions may not be exactly to the original specifications. For example, some models of this sensor require the echo pin to be reset if a timeout occurs. The unpredictability of this condition makes it prudent (a.k.a. defensive programming) to reset the echo pin through code as shown explicitly in the example for the PulseIn method.

CONCLUSION
This note examined two techniques to use an ultrasonic sensor to estimate the distance from the sensor to a sonar reflector. The success of the tests is manifested by the blinking of the LED devices in approximation to the estimated range. The references in the succeeding section provide further insight to the use of the ultrasonic sensor on Arduino boards.
REFERENCES
http://www.micropik.com/PDF/HCSR04.pdf
http://mc-computing.com/Hardware_Platforms/Arduino/HC-SR04_Ultrasonic_Sens
https://en.wikipedia.org/wiki/Speed_of_sound

APPENDIX

Advertisements
Posted in IoT | Tagged , | Leave a comment

Hello LED

Figure 1 Breakout Board on Breadboard

 

INTRODUCTION

The Raspberry Pi (RPi) relies on a set of pins for the exchange of electrical signals with external components. A set of these pins serve as General Purpose Input/Output (GPIO) interfaces as shown in Figure 2 Raspberry Pi pin cross-reference below:

Figure 2 Raspberry Pi pin cross-reference

 

General Purpose Input/Output

A very common exercise is to use the GPIO pins to drive LED devices. This note illustrates the basic example and then extends it for multiple LED devices.

Caution

Since working with GPIO pins is experimental, some precautions should be taken to avoid exceeding the recommended electrical settings for all pins on the board. The RPi does not have any feature like the Arduino UNO board where pin 13 is connected to an on-board LED.

Hardware Attached on Top

There are several accessory boards (i.e. Hardware Attached on Top – HAT) that insulate the RPi from accidental exposure to electrical overload conditions. Some of these boards will be examined in a subsequent note. The LED tests with GPIO pins do not require a HAT.

SINGLE LED

The single LED example serves as the equivalent of the traditional Hello World exercise. A bare minimum number of lines of code serve as the introduction to using a GPIO pin.

Solution

The principle to light an LED device for this exercise, as shown in Figure 3 Basic Circuit, leverages a resistor to ensure that the electrical requirements of the LED (i.e. voltage and current) are met.

The value of the resistor, R1, depends on the characteristics of the LED device. For this exercise, using commonly available LED devices, the characteristics of the chosen LED are:

  • LED voltage drop: 1.2V
  • LED max current: 20mA
  • GPIO max voltage: 5V

The estimated value of the resistor to support the tests in this note is derived using the equation shown below:

Using conventional standards for commonly available resistors (for hobbyists), the preferred value for R1 may be 220 ohms. The nominal tolerance value of 5% is perfectly adequate for the exercise. Similarly, the watt rating for the resistor can be as low as practical for handling while assembling the circuit on the breadboard.

Bill of Materials

The table below lists the materials for the first exercise:

Part Qty Description Label
RPi 1 Raspberry Pi B rev 2 RPi1
LED, red 1 LED, color red, 633 nm LED1
Resistor 1 Resistor, 220 ohms ±5% tol R1
Wire 2 Dupont connecting wires
Breadboard 1 Breadboard, half-size

 

Figure 4 Single LED Test

Assembly

The layout for the first example, as shown below in Figure 5 Hello LED 1, uses the physical pin number 7 which also referenced as BCM4. The reference section has links to more detailed information on the correspondence between the physical pins and the Broadcom

(BCM) pin numbers.

Since the use of a breakout board (also known as cobbler board in some circles), limits the interaction with the physical pins of the RPi by transferring the equivalent connections directly to the breadboard. The practical exercises in this note were conducted using the Sunfounder RPi-GPIO Extensions Board v3.0

This particular board, illustrated in Figure 6 Sunfounder RPi-GPIO Extensions Board, has been superseded with improved pin connectivity for the newer models of Raspberry Pi.

Figure 7 Hello LED 1 schematic

Pin P7 of the extensions board has the following associations:

Physical pin number Broadcom (BCM) number Sunfounder Extensions board pin WiringPi pin number
7 4 P7 7

 

A key advantage of the Sunfounder extensions board is that the GND and VDC (5V and 3.3V) are applied to the buses on the edges of the breadboard. The 5V DC supply is on the right (or upper) side and the 3.3V DC is on the left (or lower) side. This option is no longer available in the newer 40-pin model but there are other manufacturers who support the earlier concept.

Schematic

The figure in the left column illustrates the schematic diagram of the assembly with only two discrete components (i.e. LED and resistor) and the RPi board. This note uses the B Rev 2 board but the instructions apply equally to current succeeding RPi models including the Raspberry Pi 3 and Raspberry Pi Zero models.

Test

The following lines of code are sufficient to test the initial exercise.

The sample code above uses GPIO.BOARD conventions to reference the pin used to drive the LED. The alternate version of the code using the

GPIO.BCM convention is shown below:

 

Figure 10 Hello Five LEDs

MORE LIGHTS

The RPi boards have many GPIO pins, as shown in Figure 2 Raspberry Pi pin cross-reference, that are good candidates to extend the exercise to more than one LED device. The next test toggles the state of five LED devices in sequence. Each LED device blinks three times. The sequence is repeated five times.

Sunfounder RPi-GPIO Extension Board

Since the exercises on the remainder of this note rely on the Sunfounder RPI-GPIO Extension Board v3, the following table can serve as short but quick reference to the GPIO pins in the different access methods:

Sunfounder RPI-GPIO Extension Board v3
Left Right
Breakout Physical WiPi BCM Breakout Physical WiringPi BCM
CE1 26 7 P0 11 0 17
CE0 24 8 P1 12 1 18
SCLK 23 11 P2 13 2 27
MISO 21 9 P3 15 3 22
MOSI 19 10 12 P4 16 4 23
RXD 10 16 15 P5 18 5 24
TXD 8 15 14 P6 22 6 25
SCL 5 9 3 P7 7 7 4
SDA 3 8 2 GND

 

Assembly

The breadboard layout to blink five LED devices is shown below:

 

In order to keep the arrangement simple, the specifications of the LED devices and resistors are constant for all instances.

Part

Qty

LED, assorted colors

5

220Ω resistors

5

RPi

1

Wires

6

Breadboard

1

Figure 12 Shopping List for Five LED Test

Schematic

The schematic corresponding to the assembly in Figure 11 Hello LED with five devices is shown below:

Test

This test uses the BCM pin numbers instead of the BOARD pin numbers. The Appendix section in this note has the basic code for the test. A video of a test run is available at YouTube.

WiringPi

Gordon Henderson made available the WiringPi package that is currently installed with the standard Raspbian image. The original library was intended for C/C++ programming. Subsequently, the library was ported for use with Java, Perl, Python, Ruby and Tcl

Pin Table

The table headers are:

  • Board – physical pin on the Raspberry Pi
  • WiPi – WiringPi pin reference number
  • BCM – Broadcom (BCM chip) pin number
  • Name – mnemonic for reference purpose
Board WiPi BCM Name Board WiPi BCM Name
1 3.3V 2 5V
3 4 5V
5 6
7 7 4 8
9 GND 10
11 0 12
13 14 GND
15 16
17 18
19 20 GND
21 22
23 24
25 GND 26

Command Line Utility

The utility gpio is run without super user privileges from the command line. Detailed usage information on the utility is available from the corresponding man page by typing man gpio at the command line.

Blink one LED

The C++ source code to blink one LED using WiringPi pin number 7 (see table above for corresponding reference to other nomenclature) is shown below:

#include #define pinLED 7 int main(int argc, char **argv) { wiringPiSetup(); pinMode(pinLED, OUTPUT); for (;;) { digitalWrite(pinLED, HIGH); delay(1000); digitalWrite(pinLED, LOW); delay(1000); } return 0; } ” src=”file:///C:/Users/baqwa/AppData/Local/Temp/msohtmlclip1/01/clip_image035.png” v:shapes=”_x0000_s2052″>

 

CONCLUSION

This note examined the basic technique to access the GPIO pins on Raspberry Pi boards. The success of the test is manifested by the blinking of the LED device assigned to the pins under tests. The references in the succeeding section provide further insight to the use of GPIO pins on Raspberry Pi boards.

REFERENCES

GPIO: Raspberry Pi Models A and B

Introducing Raspberry Pi HATs

Simple Guide to the RPI GPIO Header and Pins

Sunfounder RPi-GPIO Extension Board

WiringPi, GPIO Interface library for the Raspberry Pi

 


APPENDIX

 

 

 

 

 

 

 

 

Posted in Uncategorized | Leave a comment

Hello Azure IoT Hub for .NET

References

Pre-Requisites

The following licensed program products serve as the foundation for this introductory tutorial on connecting to the Microsoft Azure IoT Hub with devices:

Some familiarity with Microsoft C# programming language constructs is desirable.

Introduction

This tutorial is a retrace of the excellent example provided by Dominic Betts at the Microsoft Azure site as noted in the reference section above. All credit is due to Dominic for sharing his work in a very informative manner.

The introductory work will emulate the steps published by Dominic using a C# client. A latter article will examine the Python and Node.js interfaces for the equivalent exercises.

Scope

This tutorial covers the following topics:

Limitations to Scope

The underlying assumption of this article is that the pre-requisites have been fulfilled prior to proceeding to the next steps. It is beyond the scope of this article to enable the pre-requisites.

Objectives

This tutorial accomplishes the following entry level applications a la “Hello World:”

  • CreateDeviceIdentity: to create a device identity to connect the device securely to an IoT hub
  • ReadDeviceMessages: to process data from a device to an IoT hub
  • SimulateDevice: to send telemetry from a device to an IoT hub

 

Create an IoT hub

This exercises uses an Azure IoT Hub for the transmission of data from IoT devices. The following steps illustrate the key steps to create a new Microsoft Azure IoT Hub.

  • Logon to the Microsoft Azure Portal. You will need to establish an account to proceed with the subsequent steps if you do not have an Microsoft account already.
  • On the Microsoft Azure portal page, drill down from the left pane to the right by clicking in the following sequence:

newiothub

Figure 1 New IoT Hub

+ New è Internet of Things è Azure IoT Hub

 

  • On the IoT hub blade:

o   Enter the data for the following fields as appropriate:

  • Name: must be unique across Azure IoT Hub or else an error message is flagged; a green check mark indicates that your entry is unique
  • Pricing and scale tier: choose F1-Free if available
  • IoT Hub units: retain the default
  • Device-to-cloud partitions: retain the default
  • Subscription: hopefully you have enabled a trial subscription for this exercise
  • Resource group: select as appropriate (if you have existing Azure resources)

createiothub

Figure 2 Create IoT Hub

Location: your preference should be fine for this exercise

o   Click the Create button at the bottom of the blade

It will take a few minutes for the hub to be created. Azure will post a notification when the deployment of the hub is successful.

  • On the portal page, click All Resources and then click the Name of the newly deployed IoT hub:
Figure 3 All Resources

 

  • Make a note of the fully qualified Hostname as highlighted in the preceding figure under the Essentials group of the blade for the named hub.
  • On the blade for the named hub, under General, drill down as follows:

Shared access policies è iothubowner

Figure 4 Connection String

On the iobhubowner pane, in Connection string – primary key, copy the string to the clipboard using the icon button adjacent to the right of the field. Paste the Connection string to a document for later use.

 

The Hostname and Connection string are the two key parameters used by IoT devices to exchange data.

Create a device identity

In order for a device to communicate with the IoT hub, it needs to identify itself uniquely. Azure IoT uses the term device identity for this purpose. There is yet another article by Dominic Betts that explains the background information in greater detail.

A basic Windows console app using the Microsoft Azure IoT Service SDK synthesizes the device identity for use in communications with the Azure IoT hub.

Build Windows Console App

The following steps build a basic Windows Console app:

  • Launch Visual Studio 2015
Figure 5 Launch Visual Studio

 

  • On the Start Page, drill down to Project:

File è New è Project

Figure 6 Start Page

 

  • On the New Project window:

o   Drill down to Console Application:

Installed è Classic Desktop è Console Application

o   Enter an appropriate Name for the app

o   Click the OK button

 

Figure 7 New Project

 

Figure 8 CreateDeviceIdentity Initial Panes

After the wizard completes its operations, the shell for the main program appears on the left-center pane and the Solution Explorer on the right pane as shown below:

 

Figure 9 Manage Nuget Packages

In the Solution Explorer pane, right-click the CreateDeviceIdentity project and on the context menu click Manage Nuget Packages:

 

  • In the Nuget Package Manager window, enter microsoft.azure.devices in the text box on the upper left and click the Browse button.
  • Select Microsoft.Azure.Devices in the results pane and click the Install button on the right pane

 

Figure 10 Install Nuget Package

 

  • In the Review Changes window, click the OK button
Figure 11 Review Changes

In the License Acceptance window, click the I Accept button

Figure 12 I Accept

 

Figure 13 New References

In the Solution Explorer pane, for the CreateDeviceIdentity project, the References node should have new entries for the Azure libraries

using Microsoft.Azure.Devices; using Microsoft.Azure.Devices.Common.Exceptions;
Figure 14 References to Azure SDK libraries

In the source code file, Program.cs, insert the references to the newly added libraries with C# language using statements as shown below:

1.  static RegistryManager registryManager;

static string connectionString = “<your iot hub connection string>”;

Figure 15 Program variables

In the source code file, Program.cs, insert the following statements to define the variables, registryManager and connectionString, for use in registering the device identity:

The connection string value should be the corresponding string for your newly created Azure IoT Hub as shown in Figure 4 Connection String.

 

  • The app requires a nominal set of instructions to create the device identity using a method, AddDeviceAsync, for the class that constitutes the app, Program:

 

 

private static async Task AddDeviceAsync()
{
  string deviceId = "raspbarin";
  Device device;
  try
  {
    device = await registryManager.AddDeviceAsync(new Device(deviceId));
  }
  catch (DeviceAlreadyExistsException)
  {
    device = await registryManager.GetDeviceAsync(deviceId);
  }
  Console.WriteLine("Generated device key is {0}", device.Authentication.SymmetricKey.PrimaryKey);
}
Figure 16 AddDeviceAsync Method

As explained in literature, async methods are now de rigueur for most operations especially when these methods communicate external to client environment. Also, for illustration purposes, a set of instructions for exception handling, used for simple illustration here, represent good practice towards the stepwise refinement of the solution for more robust operations.

 

The variable, deviceId, should be any identifier unique to the device. This example uses the host name of the client machine as the device identifier.

  • The last step for the code is to insert the instructions to connect to the Azure service, retrieve
1.  registryManager = RegistryManager.CreateFromConnectionString(connectionString);

2.  AddDeviceAsync().Wait();

Console.ReadLine();

Figure 17 Retrieving Device Identity

the assigned identity and echo it to the terminal window:

The final program should be similar to that shown below:

 

 

 

Figure 18 Full Program

 

  • Use the Debug mode to run the app: press the F5 key (or drill down)

 

The output from the program to the console is shown below:

 

Figure 19 Console Terminal Window

  • The console terminal window will display the device identity key. Save this key for use in subsequent message exchanges between the device (client machine) and the specific IoT hub that was created previously for this exercise.

 

 

 

LThe device key for raspbarin is G2r4dKhry0Xfy0gC7FEUMlbUciETVCFqtHqhbPMdryg=

Receive Device Messages

This project will use a basic Windows console app to read messages from a device client to an Azure IoT hub that was created using steps outlined earlier in this article.

Figure 20 Device to Cloud Messaging

 

 

Build the console app

The steps to build the console app are shown below. For this exercise, the corresponding project is added to the solution.

Figure 21 Add New Project

In the Solution Explorer pane, right-click the solution name and drill-down to Add è New
Project:

Figure 22 Add New Project

In the Add New Project window, enter the Name for the project (e.g. ReadMessages)

 

  • In the Solution Explorer pane, right-click the name of the newly created project and from the context menu select Manage Nuget Packages

 

  • In the NuGet Package Manager window, enter WindowsAzure.ServiceBus in the search field click Browse

 

  • In the results frame, select WindowsAzure.ServiceBus and click the Install button

 

Figure 23 Install Windows Azure Service Bus Package

In the Preview window, review the package name and click the OK button

 

Figure 24 Review Changes

 

Figure 25 Added Reference

In the License Acceptance window, click the I Accept button. The figure below illustrates the
added reference:

 

 

 

using Microsoft.ServiceBus.Messaging; using System.Threading;
Figure 26 Using Statements

In the Program.cs file, add the following two statements towards the top of the file:

static string myConnection = “<use IoT Hub connection string>”; static string device2cloudEndpoint = “messages/events”; static EventHubClient myEventHubClient;
Figure 27 Class Fields

In the Program class, add three fields as shown below:

private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct) {

var myEventHubReceiver = myEventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

while (true)

{

if (ct.IsCancellationRequested) break;

EventData myEventData = await myEventHubReceiver.ReceiveAsync();

if (myEventData == null) continue;

 

string data = Encoding.UTF8.GetString(myEventData.GetBytes());

Console.WriteLine(“Message received. Partition: {0} Data: ‘{1}'”, partition, data);

}

}

Figure 28 Method to Receive Messages

In the Program class, add a method, ReceiveMessagesFromClientAsync, as shown below:

  • In the Program class under the Main method, insert the lines of code shown below:
Console.WriteLine(“Receive messages. Ctrl-C to exit.\n”);

myEventHubClient = EventHubClient.CreateFromConnectionString(connectionString, device2cloudEndpoint);

 

var d2cPartitions = myEventHubClient.GetRuntimeInformation().PartitionIds;

 

CancellationTokenSource cts = new CancellationTokenSource();

 

System.Console.CancelKeyPress += (s, e) =>

{

e.Cancel = true;

cts.Cancel();

Console.WriteLine(“Exiting…”);

};

 

var tasks = new List<Task>();

foreach (string partition in d2cPartitions)

{

tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));

}

Task.WaitAll(tasks.ToArray());

Figure 29 Receive Message Operations

Create a simulated client

For the limited purposes of this exercise, using a simulated client to send messages to the IoT hub in the cloud is more expedient than configuring any IoT device. Opinions will differ on this rationalization. Examples of practical IoT devices (Raspberry Pi, Intel Edison, Freescale/NXP/Qualcomm et al.) are planned for later exercises.

Build the app

  • In Solution Explorer, right-click the current solution name and drill-down the context menus to add a new project:

New Project è Add

Figure 30 Add New Project for Simulated Client

In the Add New Project window:

o   Drill-down the left pane: Installed è Visual C# è Windows è Classic Desktop

o   In the middle pane, select Console Application

o   Enter a Name for the project

o   Click the OK button

Figure 31 Project Name for Simulated Client

 

  • In Solution Explorer, right-click the name of the newly created project (i.e. SimulatedClient in
Figure 32 Manage NuGet Packages for Simulated Client

this example) and from the ensuing context menu, click Manage NuGet Packages:

 

  • In the NuGet Package Manager window:

o   Enter a search string, e.g. Device SDK Azure IoT

o   Click the Browse button

o   Select Microsoft.Azure.Devices.Client in the left pane

o   Click the Install button

Figure 33 Install NuGet Package for Simulated Client

 

  • In the Preview window, click the OK button
  • In the License Acceptance, click the I Accept button
Figure 34 References Added for Simulated Client Project

The figure below lists the references added to the project:

  • In the file, Program.cs, add references to the packages using the statements shown below:

 

Figure 35 Package References for Simulated Client
using Microsoft.Azure.Devices.Client; using Newtonsoft.Json;

 

 

 

  • In the Program class, add the following fields using the actual values instead of the placeholder labels identified in the string definitions:

o   myDeviceClient

o   myIoTHub

o

static DeviceClient myDeviceClient;

static string myIoTHub = “{placeholder for IoT Hub host name}”;

static string myDeviceKey = “{placeholder for device key}”;

Figure 36 Add Fields to Program

myDeviceKey

 

  • In the Program class, add a method, SendFromClientToIoTHub, as shown below:
private static async void SendFromClientToIoTHubAsync()

{

double avgWindSpeed = 10; // m/s

Random rand = new Random();

 

while (true)

{

double currentWindSpeed = avgWindSpeed + rand.NextDouble() * 4 – 2;

 

var telemetryDataPoint = new

{

deviceId = “raspbari9”,

windSpeed = currentWindSpeed

};

var messageString = JsonConvert.SerializeObject(telemetryDataPoint);

var message = new Message(Encoding.ASCII.GetBytes(messageString));

 

await deviceClient.SendEventAsync(message);

Console.WriteLine(“{0} > Sending message: {1}”, DateTime.Now, messageString);

 

Task.Delay(1000).Wait();

}

}

Figure 38 Method for Simulated Client
Console.WriteLine(“Simulated client\n”);

myDeviceClient = DeviceClient.Create(myIoTHub, new DeviceAuthenticationWithRegistrySymmetricKey(“raspbari9”, myDeviceKey));

 

SendFromClientToIoTHubAsync();

Console.ReadLine();

Figure 37 Send Message from Client to IoT Hub

In the Program class, add the instructions to send the messages from the client to the IoT Hub:

  • Close the solution to save all the files that were modified.

The Create method for DeviceClient uses the AMQP protocol which is popular for IoT devices. There are other protocols (e.g. HTTP) for data exchanges with the IoT Hub. The corresponding packages for these protocols are available through NuGet.

For real-world scenarios, more robust messaging may be necessary. The Microsoft Patterns and Practices team provides examples as well as guidelines on Transient Fault Handling to retry when transmission errors arise.

Build the applications

This example build a solution file with three projects:

  • Create device identity
  • Send messages to hub
  • Read Messages at hub

The first project is run only once to obtain the identity key. The other two projects can be run concurrently to demonstrate the transmission from the client and the processing at the hub.

Startup Projects

The two projects that must run concurrently in the current example are:

  • ReadMessages
  • SimulatedClient
Figure 39 Current Solution

 

Visual Studio 2015 permits both projects to start-up concurrently.

  • In the Solution Explorer pane, right-click the solution name and from the context menu select
Figure 40 Set StartUp Projects

Set StartUp Projects:

 

  • In the Solution Property Pages window:

o   In the left pane, select Startup Project

o   In the middle pane, select Multiple startup projects

o   For the project ReadMessages, select the Action as Start

o   For the project SimulatedClient, select the Action as Start

o   Click the OK button

Run the projects

  • On the menu bar, click Debug and on the cascade menu click Start Debugging. Alternatively, press the F5 key:
Figure 41 Start Debugging

Two console terminal windows will launch as shown below with transactions logged based on the interval specified in the client app:

Figure 42 Sending and Receiving Messages

To stop the projects, click the Stop Debugging button. Alternatively, press [Shift+F5] keys:

Figure 43 Stop Debugging

Conclusion

This article illustrated the basic “Hello IoT World” exercise. Subsequent articles will extend the solution with some of the more popular boards and sensors.

Posted in IoT | Tagged , , , | Leave a comment

RPi in the Cloud

The popularity of the Open Source project, Nextcloud, has led to the inevitable porting of the solution to the ubiquitous Raspberry Pi platform with the rapid availability of Snappy Ubuntu Core.

Features

  • File access & sharing
  • Security & control
  • Mobile & desktop clients
  • External storage
  • Calendar & Contacts
  • Secure audio & video calls
  • Collabora Online Office

Technology

  • 1 TB USB3 hard drive (WDLabs)
  • Nextcloud case for IoT board and hard drive
  • microUSB charger, cables and adapters
  • microSD card with Snappy Ubuntu Core (for OS)
  • Pre-installed Apache, MySQL and Nextcloud
  • NOT included in box – compatible IoT board:
    • RPi 2 supported currently
    • RPi 3 support planned
    • oDroid support planned

Box Assembly

  • The chassis has the hard disk fastened with four screws
  • The RPi (presently limited to Model 2) is fastened adjacent to the hard disk with four supplied screws
  • The custom cable with three leads is connected to the hard disk
  • The microUSB male end of the custom cable is connected to the RPi power socked (female microUSB)
  • The male USB end of the custom cable is connected to an open USB port on the RPi
  • The PWR lead of the custom cable is connected to male microUSB of the power cable
  • The male USB end of the power connector is connected to power adapter which in turn is connected to a stable power supply
  • Use a suitable HDMI cable to connect the RPi video output to a display monitor
  • Use an Ethernet cable or a Wi-Fi adapter to connect the RPi to an existing network
  • Use an USB adapter to connect a keyboard to the RPi

The document illustrates the arrangement for the RPi version of the Nextcloud server.

Installation

Update

There are two ways to access the server for the update steps:

  • Attach a keyboard/mouse pair using the available USB ports and also plug a display monitor using the HDMI cable
  • Connect using the PuTTY application

The default hostname of the server is ubuntu-standard. The PuTTY application requires the IP address of the Nextcloud server. The arp command from another computer can assist in the determination of the IP address. The MAC address for all RPi 2 models have the hexadecimal prefix “B8:27.”

The default access credentials are ubuntu and ubuntu. The password should be changed as soon as practical using the passwd command.

Assuming that the login is successful, enter the following steps for the recommended software upgrade:

sudo apt update && sudo apt dist-upgrade
sudo snap refresh ubuntu-core
sudo snap refresh

Enter the letter “y” when prompted during these operations.

Setup

  • Launch a browser from a client machine and enter the IP address of the RPi Nextcloud server. You can use the hostname (or fully qualified domain name if your network subnet registers IP addresses using DNS). The server will proceed to finish the setup by requesting data to create an admin account.

create-an-admin-account

  • On the Create an admin account form, enter your preferred username for the admin account and the corresponding password. The system does check for the strength of the password. You may want to observe the guidance but as usual please remember to save the credentials securely.
  • Click the Finish setup button. The successful completion of the operation will result in the display of an updated page shown below:

a-safe-home-for-all-your-data

  • On the page entitled “a safe home for all your data,” click the Desktop app button.
  • On the Get Started page under the Sync your data section, click Desktop clients button.

desktop-clients

  • Click the Save button to download the file to the default location in the Downloads folder
  • Click the Run button to install the desktop client application
  • After confirming that you wish to install the desktop client, on the Welcome … Wizard window, click the Next button

welcome-wizard

  • On the Choose Components window, select (i.e. check) all the options and click the Next button:

choose-components

  • On the Choose Install Location window, update the Destination Folder if necessary and click the Install button

installing

  • Assuming that the installation proceeds without hiccups, on the Installation Complete window, click the Next button

installation-complete

  • On the Completing … Wizard window, click the Finish button.
  • On the Connect to Nextcloud window, in the Server Address text box, enter the IP address of the server (if you are not relying on DNS)

setup-nextcloud-server

  • Enter the credentials for the connection and click the Next button

enter-user-credentials

  • Connect your Local Folder for synchronization with the server

setup-folder-options

  • Click the Connect button

everything-set-up

  • Click the Finish button

The desktop will display a shortcut for routine use of the application.

short-cut

 

Posted in IoT | Tagged , , , , , | Leave a comment

Bash for Windows 10 and Microsoft R Open

Microsoft R Open
There are three variations of R for consideration currently:

• Microsoft R Server
• Microsoft R Open
• SQL Server R Services
• Microsoft R Client

This article derived from the narrative by David Salgado (see reference below) uses the bash environment in Windows 10 to examine the elementary steps for predictive modeling (a.k.a. machine learning) using Microsoft R Open. Another variation, Microsoft R Client, will be examined at a later date to illustrate ScaleR technology with suitable data sets.

Install the tools
The pre-requisite for this version of this exercise is the installation of bash on Windows. This environment provides the command-line utilities for a basic Ubuntu plug-in. Obviously, Microsoft R Open is not dependent on this environment. This exercise is merely an illustration of the portability of R and the new add-on feature to support Linux natively in Windows 10. The installation guide for this environment is noted in the References section below. After completing the installation, open a command prompt window and enter bash to launch the environment:

Obtain the installation file, microsoft-r-open-3.3.1.tar.gz, from the Microsoft site at mran.revolutionaryanalytics.com as illustrated below. You should change the current directory to a work folder as a practical measure.The version number of the archive shown below is 3.3.1; this version may be superseded by the time you read this note.

It is prudent to check that the download was successful by displaying the contents of the folder with the ls command that, in the figure below, illustrates the presence of the installation file, microsoft-r-open-3.3.1.tar.gz.

The command to extract the files from the installation archive is:

tar -xf microsoft-r-open-3.3.1.tar.gz

The example assumes that the installation archive resides in the current folder. After the command completes without any error messages, you can examine the contents of the folder once again by using the ls command. There will be a new file install.sh in the folder amongst a few other files.

Accept the Microsoft license agreement to continue with the installation:

Accept the request to install the Microsoft R Open package as well as the Intel Multithreading Kernel Library (MKL) package:

The following figure illustrates the messages that confirm the installation of the packages:

Launch Microsoft R Open using the standard command, R, as shown below. The preamble will be repeated every time the package is launched:

Frame the problem
This introductory exercise illustrates the development a very simple prediction to assist the business in demand estimation based on autonomous variables (e.g. snow condition, day of the week). There are many, many models to choose for the prediction but for the limited purpose of an introductory exercise only two basic models are shown. There are certainly other models that can provide more practical predictions.

Extract Transform and Load Data
Extract, Transform and Load (ETL) is the classic paradigm for analysis with structured data. Of course, the concepts have been applied to unstructured data too but that topic is beyond the scope of the current article. The sample data for this exercise is available at:

raw.githubusercontent.com/davidsalgado/BlogSamples/master/FirstPredictiveModelWithR/RentalFeatures.txt

The steps below illustrate the use of the conventional wget command to retrieve the dataset to a local folder named labs and then lists the files in the folder after the download. You can use any alternate method that you prefer to download the data set to the current folder.

The sample data set has been graciously made available here. I chose the word graciously here deliberately. Nearly ten years ago, I wanted to emulate a market basket analysis case study from a textbook using Microsoft SSAS 2005 with the Naïve Bayes model. I asked the author to clarify some key omissions in the textbook data. He declined stating that it would be unfair for me to audit his work!

Assign the dataset that resides in the current folder to a local variable, mydata, by loading it with the read.table method and specifying the presence of column names in the first row of the data set with the header parameter set to TRUE. You will have to use a fully qualified name with Linux conventions for the data set if it resides in another folder.

mydata = read.table(“RentalFeatures.txt”, header=TRUE)

Using the head command to list a few rows of data it is apparent that some of the column values ought to represent categories and not numerical values. The simplest way would be to append additional columns for category analysis by factorizing some of the numerical columns. The three key columns for this exercise are:

• Holiday
• Snow
• WeekDay

The command to represent the numerical values to categories for each of these columns is factor as shown below:

mydata$FHoliday = factor(mydata$Holiday)
mydata$FSnow = factor(mydata$Snow)
mydata$FWeekDay = factor(mydata$WeekDay)

You can view the levels for each factor assignment using the levels command as shown in the figure below:

levels(mydata$FHoliday)
levels(mydata$FSnow)
levels(mydata$FWeekDay)

Split the data into two subsets – one for training the model to estimate parameters and the other to validate it using your preferred nomenclature. In this exercise the names are train_data and test_data respectively:

train_data = mydata[mydata$Year < 2015]
test_data = mydata[mydata$Year == 2015]

The data in test_data is expressly omitted during the model training. It is limited to assessing the model only.

The application of a very simple selection criterion (e.g. Year) is sufficient for the purposes of an introductory illustration in this exercise. Practical uses of the splitting process require more complex filtering criteria to reduce intrinsic bias.

In this exercise, the data prior to year 2015 will serve as the training set for the model and the data for year 2015 will be used to test the model. It is also helpful to have a column to test the quality of the prediction as shown below:

Prepare the data
While ETL operations performed using a systematic workflow may be sufficient for introductory exercises, there is often a need for operations with the data before the analysis can start. You may encounter discussions on schemata or data normalization. This introductory exercise assumes that the ETL operations conducted so far are sufficient to proceed with the subsequent steps.

A summary of the data is available with the summary method as shown below:

The summary information provides a basic insight to the range of the data for subsequent analysis. You can list a few rows of the data set using the head command as shown below:

Exploratory Data Analysis
With the assumption that the current data set is ready for modeling exercises, data visualization is a key step to examine the key aspects for a data model. The simplest way to visualize is to plot two columns from the data set as follows:

plot(mydata$FSnow, mydata$RentalCount)
title(“Snow versus Rental Count”)

The plots are saved in the file, Rplots.pdf, in the current folder.

The title command illustrates the use of one of many options to embellish the plot. The snow values were factored into the FSnow category in a previous step. The corresponding chart illustrated higher demand for rentals during Snow days (x-axis: 0=no snow, 1=snow present) is shown below:

In order to visualize the rental trends on days of the week, the following command may be used:

plot(mydata$FWeekDay, mydata$RentalCount)
title(“Week Day versus Rental Count”)

The initial examination of the rental count for each week day (factored as FWeekDay in a previous step) clearly illustrates the perceptible higher demand for rentals during Sunday (i.e. factor category “1”) and Saturday (i.e. factor category “7”) over other days of the week in the chart below:

Another useful visual chart is the demand for rentals over a time period. Converting the calendar periods to an ISO date format while plotting is necessary for this purpose. Of course, there are many other parametric variations that you may want to consider for visualization purposes. The basic example is:

plot(ISOdate(mydata$Year, mydata$Month, mydata$Day), mydata$RentalCount)
title(“Rental Count for a time period”)

The seasonality of the rentals is evident in the corresponding chart is shown below:

Modeling
The simplest model to examine the relationship between the variables is linear regression. The commands below use the training data set to prepare the model and then use the test data set to validate the fit which is subsequently representing in chart format for quick visualization:

model1 = lm(RentalCount ~ Month + Day + FWeekDay + FSnow + FHoliday, train_data)
p1 = predict(model1, test_data)
plot(p1 – test_counts)
title(“Linear regression model”)

The explanation of the syntax for the model is thoroughly documented in R documentation which should be referenced for the details. For the purposes of this exercise, only the basic formulation is used for the linear regression model. The corresponding chart is shown below:

Viewing the chart it is readily apparent that there are noticeably large errors for many records. This observation should serve as a cue to evaluate alternate models. The basic approach in data mining is recursive partitioning that explores the structure of data sets. The rpart method will be used for the limited purposes of this exercise to illustrate the classification and regression trees that support the model through step-wise refinement. To install the rpart package, enter the following command when using rpart for the first time:

require(rpart)

The commands for the model using classification trees is as follow:

model2 = rpart(RentalCount ~ Month + Day + FWeekDay + FSnow + FHoliday, train_data)
p2 = predict(model2, test_data)
plot(p2 – test_counts)
title(“Rpart (Classification Tree) model”)

The ensuing chart illustrates a better model using classification trees than vanilla linear regression. The error residuals are much smaller in magnitude.

Forecasting
The preferred model can be used for predictions using the predict command as shown below:

predict(model2, data.frame(Month=1, Day=1, FWeekDay=factor(1), FSnow=factor(0), FHoliday=factor(0)))

Some examples are shown in the figure below with the clear manifestation that the rentals are higher during holidays:

For practical purposes the preferred usage would be to pass the independent parameters to a custom method that would return the computed value. Before committing to this approach it would be more prudent to refine the model for more robust performance.

References
• Data Science for Developers: Build your first predictive model with R, David Salgado
• Getting Started with R, MRAN
• An Introduction to R, W N Venables, D M Smith and the R Core Team
• Applied Predictive Modeling in R, Max Kuhn
• Bash on Windows Installation Guide, Jack Hammons

Posted in Data Science | Leave a comment

Hello UNO

Introduction

This app demonstrates the use of Arduino sketches on a Raspberry Pi under Windows 10 IoT Core. The key steps are:

  • Build the app
  • Configure the driver
  • Run the app

Build the app

The basic default Arduino app will suffice for this introductory exercise

  • Launch Visual Studio from the Start menu

Hello UNO - Launch Visual Studio

  • From the menu bar, click the File command and drill-down to New and then Project

Hello UNO - New Project

  • In the New Project dialog box, on the left-pane, drill-down as follows: Installed ® Templates ® Visual C++ ® Windows ® Windows IoT Core
  • In the middle name of the same dialog box, select Arduino Wiring Application for Windows IoT Core
  • Enter a name for the application (this example exercise uses HelloUNO)

Hello UNO - Arduino Wiring Application

The Solution Explorer pane should resemble that shown below.

Hello UNO - Solution Explorer

  • Close the solution from the File menu

 Configure the driver

The Lightning driver enables the Raspberry Pi to run Arduino sketches with minimal modifications.

  •  Launch the Windows IoT Core Dashboard

Hello UNO - Windows IoT Core Dashboard

  • In the IoT Dashboard window, click on Open Windows Device Portal in browser in the lower section of the window

Hello UNO - IoT Dashboard

  • In the Microsoft Edge window, enter the credential and corresponding password for the access to the remote machine and click the OK button

Hello UNO - Microsoft Edge

  • In the Device Manager window, select Devices on the left pane
  • In the Default Controller Driver drop-down list, select Direct Memory Mapped Driver and click the Update Driver button

Hello UNO - Update Driver

  • In the This site says modal dialog box, click the OK button

Hello UNO - Driver changed

  • In the Device Manager toolbar, click the Restart button

Hello UNO - Restart

  • In the This site says modal dialog box, click the OK button

Hello UNO - Are you sure

Run the app

Open the HelloUNO solution in Visual Studio; from the Debug menu click on HelloUNO Properties

Hello UNO - Debug Properties

  • In the Configuration Properties pane, click on Debugging
  • In main pane, enter the Machine Name and ensure that the Authentication Type is set to Universal
  • Click the OK button

Hello UNO - Debug Properties Debugging

  • On the toolbar, click on Remote Machine

Hello UNO - Remote machine

<Insert video>

  • On the toolbar, click on the Stop button that is outlined in red color below

Hello UNO - Stop debugging

 

 

 

 

 

 

 

 

Posted in IoT | Tagged , , , | Leave a comment

Hello Blinky

Introduction

This application toggles the state of a single LED at a fixed interval. The purpose of this application is to ensure that the core libraries have been installed for further application development in subsequent projects. The basic development of the application moves along the classic project phases:

  • Design
  • Construction
  • Testing
  • Deployment

Project phases

The two key phases for the project with respect to the limited purposes of this simple application are:

  • Construction
  • Testing
       txtStatus.Text = "No GPIO controller detected on device!";
                   }
               }
               else
               {
                   txtStatus.Text = "GPIO controller already initialized!";
               }
               return pinDetected;
           }

Construction

There are two parts to the construction phase:

  • Board assembly
  • Code development

Board assembly

The following information is presented in this section:

  • Layout
  • Schematic
  • Bill of Materials
Layout

The general layout of the breadboard for the application is shown in the header of this post. In practice, a cobbler board (see photo/video) was used to layout the RPi pins to the breadboard but you may choose to forgo this extra work for the limited purposes of this specific application.

GPIO 5 and 3.3V PWR pins are the only two pins(#1 and #29) used in this application.

Schematic

HelloBlinky2_schem

Bill of Materials

Label Description Quantity Reference
RpI1 Raspberry Pi 2 1
LED1 LED, red, 633 nm 1
R1 Resistor, 220, ±5% 1
Misc Connection wires, assorted colors 4

Code development

Code development consists of:

  • Prepare the project files
  • Place the user interface controls
  • Add the timer code

Prepare the project files

  • Launch Visual Studio
  • On the menu bar of the Start Page, click File and drill-down the cascade menu to New and then Project as shown below:

HelloBlinky - File New

  • In the left-pane of the New Project dialog box, drill-down as follows: Templates Visual C# Windows Universal
  • In the middle-pane of the same dialog box, select Blank App (Universal Windows)
  • In the bottom-pane of the same dialog box, enter HelloBlinky for the Name field as shown below and leave the other fields as the defaults unless you have a specific reason to override these entries.
  • Click the OK button to proceed as shown below:

HelloBlinky - New Project

Wait for the wizard to complete the initialization of the files for the solution. In the right-pane, select the Solution Explorer tab and drill-down the tree control to References as shown below:

HelloBlinky - References

  • Right click References and select Add Reference in the context menu as shown below:

HelloBlinky - Add Reference

  • In the Reference Manager dialog box, drill-down in the left-pane to Universal Windows Extensions. In the middle-pane select the SDK, Windows IoT Extensions for the UWP version 10.0.10586.0 or later as shown below:

HelloBlinky - Reference Manager

The selected SDK will now be displayed under References for the project in the Solution Explorer pane as shown below:

HelloBlinky - Added reference to IoT SDK

Place the user interface controls

Open the MainPage.xaml file; you will be presented with a blank screen on the Design page in the middle-pane of the IDE as shown below:

Hello Blinky - MainPage blank display

In the XAML code section, you will notice that the default Grid control is present:

   <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
   </Grid>
  • Insert a StackPanel control within the Grid element to facilitate the positioning of the subsequent controls. You can drag and drop the StackPanel control from the Toolbox:
Hello Blinky - StackPanel control

Alternatively, you can type the XAML code directly using your own preferences for the values for Alignment and Margin to override the default values:

       <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
       </StackPanel>

There are three controls that have to be placed within the StackPanel. You can use the Toolbox to drag-and-drop these controls (shown below) to the MainPage or you can type the XAML code shown further below:

  • Ellipse (i.e. circle) to display the current color of the LED

Hello Blinky - Ellipse control

  • TextBlock for the duration before the state reversal of the LED

Hello IoT World - Textbox control

  • TextBlock for status messages

If you drag-and-drop the controls to the canvas pay attention to the closing XAML element of the corresponding control which in the case of the StackPanel would have to edited. The XAML code, excluding the header section, after all the controls have been inserted should be similar to that shown below:

   <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
       <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
           <Ellipse x:Name="ellLED" HorizontalAlignment="Center" Height="100" VerticalAlignment="Center" Width="100" Margin="10"/>
           <TextBox x:Name="txtDelayPeriod" HorizontalAlignment="Center" TextWrapping="Wrap" Text="unknown" VerticalAlignment="Center" Margin="10" FontSize="32"/>
           <TextBox x:Name="txtStatus" HorizontalAlignment="Center" TextWrapping="Wrap" Text="Not ready" VerticalAlignment="Top" Margin="10" FontSize="24"/>
       </StackPanel>
   </Grid>

 

Add the timer code

Open the file, MainPage.xaml.cs

Untitled picture

  • Insert the following statement in the header section of the file to use the WinRT classes:
 using Windows.Devices.Gpio;

 

  • Insert variables for the class MainPage; insert the following lines before the MainPage constructor:
private const int GPIO_LED = 5;
	private const double blinkInterval = 1.0;              
	private GpioPin pinLED;                                
	private DispatcherTimer timer = new DispatcherTimer();
	private SolidColorBrush brushRed = new SolidColorBrush(Windows.UI.Colors.Red);
	private SolidColorBrush brushLightGray = new SolidColorBrush(Windows.UI.Colors.LightGray);
  •  Insert the following method in the class MainPage to initialize the GPIO controller and active pin:

 

private Boolean InitGPIO()
{
  Boolean pinDetected = false;
  if (gpio == null)
  {
    txtDelayPeriod.Text = blinkInterval.ToString() + " secs";
    gpio = GpioController.GetDefault();
    if (gpio != null)
    {
      try
      {
        pinLED = gpio.OpenPin(GPIO_LED);
        pinLED.SetDriveMode(GpioPinDriveMode.Output);
        txtStatus.Text = "GPIO pin " + GPIO_LED + " initialized";
        pinLED.Write(GpioPinValue.High);
        pinDetected = true;
      }
      catch (System.IO.FileLoadException fle)
      {
        txtStatus.Text = "GPIO pin " + (GPIO_LED).ToString() + " in incompatible sharing mode";
      }
    }
    else
    {
    }

 

  • Insert the following method to the class MainPage:

 

private void Timer_Tick(object sender, object e)
     {
       if (stateLED == GpioPinValue.High)
       {
         stateLED = GpioPinValue.Low;
         ellLED.Fill = brushRed;
         txtStatus.Text = "HIGH";
        }
        else
        {
          stateLED = GpioPinValue.High;
          ellLED.Fill = brushLightGray;
          txtStatus.Text = "LOW";
        }
           }
           pinLED.Write(stateLED);
       }

 

  • Insert the following code snippet after the this.InitializeComponent statement in the class MainPage:
	txtStatus.Text = "Loading...";
	timer.Interval = TimeSpan.FromSeconds(1.0);
	timer.Tick += Timer_Tick;
	if (InitGPIO() == true)
	{
	   timer.Start();
	}
	else
	{
	   txtStatus.Text = "Initialization failed!";
	}

The Output pane should display a message similar that shown below:

'HelloBlinky.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Data\Users\DefaultAccount\AppxLayouts\38416d93-771d-4180-882b-8015e481426eVS.Debug_ARM.User\System.Reflection.Extensions.dll'. Module was built without symbols.

The display attached to the Remote Machine will display the main page with the three visual controls:

  • Circle displaying the current state of the LED
  • Textbox for the toggle interval
  • Textbox for the status message

 

  • Stop the application using the Stop button on the toolbar as shown below:
Hello Blinky - Stop Debugging

References

Posted in IoT | Tagged , , | Leave a comment

Hello IoT World

Introduction

This application displays a text box and a button on a page displayed by the Internet of Things (IoT) board. There is a default text in the in text box that changes to an alternate text when the user clicks the button for the first time. It represents the proverbial “Hello World” example specific for the IoT board.

Key Steps

The key steps in the development of the application are:

  • Create a new project
  • Add a reference to the Windows IoT extension SDK
  • Add content to the Main Page
  • Build and test the app in a development environment
  • Deploy the app to the IoT board
  • Set the app to launch after IoT boots (optional)

Create a new project

  • Launch Visual Studio 2015 which you have installed previously in accordance with requirements for the development of IoT applications.
  • Create a new project by clicking File on the menu bar and cascading through New to Project: [Cntrl+Shift+N]
  • In the New Project dialog box on the left pane, drill down as follows:

Installed → Visual C# → Windows → Universal

  • In the middle pane, select Blank App (Universal Windows)
  • Enter values for the following fields in the bottom pane:
  1. Name
  2. Location
  3. Solution name

In the figure below, the illustrated app name is HelloWorld.

Hello IoT World - New Project

While Visual Studio will display the following progress bar while creating the initial set of files for the project. When the operation is complete, the Integrated Development Environment (IDE) will display a set of standard panes:

  • Solution Explorer
  • Properties
  • Output
  • Toolbox
  • Main window (for the display of the initial C# code)

Hello IoT World - project create progress bar

Add a reference to Windows IoT extension SDK

The app requires a reference to the IoT libraries. Expand the References folder in the Solution Explorer which is normally docked on the right side of the IDE.

  • Click the Solution ‘HelloWord’ and drill-down to References

Hello IoT World - Solution Explorer initial

  • Right-click Reference and click Add Reference in the context menu
  • In the left pane of the Reference Manager dialog box, drill-down Universal Windows IoT Extensions
  • In the middle pane, scroll down to check Windows IoT Extensions for the UWP as shown below

Hello IoT World - Add Reference

  • Click the OK button to dismiss the dialog box. The reference will now display under the References leaf in Solution Explorer as shown below. The namespaces for the IoT libraries can now be entered in the code for the app.

Hello IoT World - Solution Explorer with Reference

Add content to MainPage

The next step is add the following two user interface controls to the main (and only) page of the app:

  • Text box

Hello IoT World - Textbox control

  • Button

Hello IoT World - Button control

Hello IoT World - Solution Explorer MainPage selection

While there are several ways to add the two user interface controls to the main page of the app, the most expedient way for this HelloWorld app is to update the main body of the XAML code. Open the file, MainPage.xaml, by right clicking the filename in Solution Explorer under the HellowWorld project and clicking Open in the context menu. You may be prompted to permit elevated permissions which you should do without reservation for the current exercise. The main pane of the IDE will display two sections – the top for the rendered display of the page (i.e. Design) and the bottom for the equivalent code (i.e. XAML).

XAML markup

Although the following equivalent operations for the placement of the user interface can be performed in the Design pane, the following instructions apply to the XAML code. There is only one element in the body of the XAML code – Grid element as shown below.

   <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
   </Grid>

User interface controls

Insert the following code snippet between inside the Grid element block. While only two elements, TextBox and Button, are necessary for the exercise, the StackPanel control assists in simplifying the layout considerations for the user interface. The StackPanel control will be your friend when you start developing more advanced layouts.

       <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
           <TextBox x:Name="txtHello" Text="Hello IoT!" Margin="10" IsReadOnly="True"/>
           <Button x:Name="btnClick" Content="Click Me!" Margin="10" HorizontalAlignment="Center"/>
</StackPanel>
Your ensuing code for the page should be similar to that shown below.
   <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
       <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
           <TextBox x:Name="txtHello" Text="Hello IoT!" Margin="10" IsReadOnly="True"/>
           <Button x:Name="btnClick" Content="Click Me!" Margin="10" HorizontalAlignment="Center"/>
       </StackPanel>
   </Grid>

Event code

With the user interface elements now placed on the main page, the next step is to code the processing that will occur when the user clicks the Button when the program is running. The simplest way to generate the skeletal code for this event is to double-click the Button element in the Design section of the MainPage.xaml file that is currently in the middle pane of the IDE. Another way to accomplish the same effect is to add the event attribute, Click, to the corresponding XAML element as shown below with the property “btnClick_Click” as shown below:

   <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
       <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
           <TextBox x:Name="txtHello" Text="Hello IoT!" Margin="10" IsReadOnly="True"/>
           <Button x:Name="btnClick" Content="Click Me!" Margin="10" HorizontalAlignment="Center" Click="btnClick_Click"/>
       </StackPanel>
</Grid>

After the Click event attribute is added to the Button element in the XAML file,
a new method is placed in the corresponding C# file, MainPage.xaml.cs,
as shown below:

private void btnClick_Click(object sender, RoutedEventArgs e)
{
}

Open the code file, MainPage.xaml.cs, to insert the statement to assign a text to be displayed in the TextBox when the Button is clicked. An example illustrating the update to the Text property of the TextBox control is shown below:

private void btnClick_Click(object sender, RoutedEventArgs e) {
   this.txtHello.Text = "Hello, Windows IoT Core!";
}

Test the app locally

The app should be run in the development environment before deployment to the device. This process will reduce the potential for basic or inadvertent errors. The steps to test the app locally:

  • Build the app
  • Run the app

Build the app

To build the app, drill-down from the menu bar as follows: Build Build Solution as shown below: [Ctrl+SHIFT+B]

Hello IoT World - Build

Review the Output pane, as shown below, for the results of the build operation:

Hello IoT World - Build Output

In the example above, the build was successful. You can then proceed to run the app locally.

Run the app

The best process is to run the app:

  • Locally and then
  • Deploy to remote device

Run locally

To run the app, drill-down from the menu bar as follows: Debug ® Start Debugging as shown below: [F5]
Hello IoT World - Start Debugging locally
Accept the request for elevated privileges should the corresponding dialog box be displayed. Subsequently after the app has loaded, the following MainPage will display:

Hello IoT World - Main page initial local

Note that the default message in the Textbox control is “Hello, World!” Click the Button beneath the Textbox control. The TextBox message will be updated as shown below with the message “Hello, Windows IoT Core!”

Hello IoT World - Main page post-click local

This concludes the test. You dismiss the app by clicking the X button on the top right corner of the main page of the app.

Deploy the app to the IoT device

Deployment of the app to the IoT device requires the current configuration options to be changed.

  • Change the processor to ARM as shown below.

Hello IoT World - Remote device selection

The execution on Remote Machine will be selected by default:

Hello IoT World - Remote device selection confirmation

Configure the deployment options

Drill-down to the property page of the app from the menu bar: Debug → HelloWorld Properties as shown below:

Hello IoT World - Remote device properties

In the Start options group of the resulting Debug tab, enter or select the values for the following fields:

Target device will be set to Remote Machine. Do not change this selection.

Authentication Mode should be set to Universal if you are using Windows IoT Core build 10586 or later. This is a change from earlier versions of Windows IoT Core.

Remote machine may be entered clicking the Find button and then using the Remote Connections dialog box to establish either the IP address or the hostname.

Leave the other values to their default entries as shown below:

Hello IoT World - Remote device debug start options

Proceed to the deployment of the app on the remote machine by clicking the Remote Machine control as shown below:

Hello IoT World - Remote device run

The Output pane will scroll a few informational messages. The app will deploy on the remote machine and assuming that you have a suitable display monitor connected to the device you will see the Main Page displayed with the two user interface controls displayed in the center of the display monitor. If you have a pointing device connected to the remote machine, you can click the button on the display and witness the message in the text box change appropriately.

Conclude your test of the app on the remote machine by:

  • Either dismiss the app using the X button on the top right hand corner of the Main Page
  • Or stopping the app in Visual Studio using the Stop icon as shown below:

The app will terminate with the following message in the Output pane:

Hello IoT World - Remote device run exit output pane

Conclusion

The main purpose of this exercise, as in the classic HelloWorld exercise, is to ensure that your IoT device can run Windows 10 IoT Core natively without any teething issues.

Reference:

 

 

 

Posted in IoT | Tagged , | Leave a comment