Free eBook - Mastering Internet of Things

3.8 (4 reviews total)
By Peter Waher
  • A new free eBook every day on the latest in tech
  • 30 permanently free eBooks from our core tech library
  1. Preparing Our First Raspberry Pi Project

About this book

The Internet of Things (IoT) is the fastest growing technology market. Industries are embracing IoT technologies to improve operational expenses, product life, and people's well-being. Mastering Internet of Things starts by presenting IoT fundamentals and the smart city. You will learn the important technologies and protocols that are used for the Internet of Things, their features, corresponding security implications, and practical examples on how to use them. This book focuses on creating applications and services for the Internet of Things. Further, you will learn to create applications and services for the Internet of Things. You will be discover various interesting projects and understand how to publish sensor data, control devices, and react to asynchronous events using the XMPP protocol. The book also introduces chat, to interact with your devices. You will learn how to automate your tasks by using Internet of Things Service Platforms as the base for an application. You will understand the subject of privacy, requirements they should be familiar with, and how to avoid violating any of the important new regulations being introduced.

At the end of the book, you will have mastered creating open, interoperable and secure networks of things, protecting the privacy and integrity of your users and their information.

Publication date:
March 2018
Publisher
Packt
Pages
410
ISBN
9781788397483

 

Chapter 1. Preparing Our First Raspberry Pi Project

In this chapter, we'll start getting our hands dirty and create our first Raspberry Pi project. You are surely eager to get started. This chapter covers:

  • An introduction to the Raspberry Pi and peripherals
  • How to install Windows 10 on your device
  • How to start and administer your device
  • How to create a simple C# project for Raspberry Pi
  • How to download and run your application on your device
  • How to debug your application remotely on your device
 

Getting what you need


For the purposes of this chapter, you will need the following:

  • A Raspberry Pi 2 or 3 (you'll need three in total, throughout the book)
  • A micro SD memory card (16 GB or greater) for each Raspberry Pi
  • A shielded box, to avoid electrostatic damage to your device
  • A laptop or PC running Windows 10, where you can insert the memory card
  • An Ethernet network cable, if you use Raspberry Pi 2 or lack Wi-Fi
  • An internet connection

The Raspberry Pi 2 or 3 will allow us to run .NET applications and control peripherals using digital input and output easily. It's also a great platform for creating connected distributed services. One of its weaknesses, however, is its lack of simple out-of-the-box analog interfaces. To do analog input and output, you must connect additional chips or equipment using either synchronous or asynchronous serial communication interfaces that converts analog signals to digital ones. To simplify this task, you can also use an Arduino board that you connect to the Raspberry Pi via USB. This has the added benefit of allowing you to use a wide range of standard Arduino peripherals and devices in your Raspberry Pi projects. So, you need to add to your list:

  • Arduino shield for Raspberry Pi B+/2B/3B
  • Short serial USB cable to connect the Arduino board to the Raspberry Pi
  • Analog Arduino-compatible light sensor
  • Digital motion detection PIR sensor
  • Digital relay module

Most of the above equipment (and more) can be obtained in so-called Starter Kits. Such starter kits make for great fun, since they often include a wide variety of sensors and actuators for you to play with. For examples, refer to https://www.dfrobot.com/category-173.html.

Note

You can use the Arduino Uno board as well. The advantage of the Arduino shield for Raspberry Pi is that it mounts easier on top of the Raspberry Pi.

Downloading the IoT Dashboard

Installing Windows 10 on a Raspberry Pi is both free and very easy. Microsoft has developed a tool for this purpose: the IoT Dashboard. Apart from allowing you to download and install Windows 10 on your devices, it also helps you manage your devices in the network. It's a very handy tool, and does not require you to learn any command-line syntax:

Note

Download and install the IoT Dashboard from the following link: https://developer.microsoft.com/en-us/windows/iot/docs/iotdashboard

The IoT Dashboard is a Windows 10 app. Once running, you can choose to right-click on its icon and select Pin to taskbar, so that you can find it easier later.

If you don't want to use Windows 10, and want to use Linux instead, you can do so with the following modifications:

Note

You can run .NET Core on Linux as well. For more information, see: https://github.com/dotnet/core/blob/master/samples/RaspberryPiInstructions.md

Installing Windows 10 on your Raspberry Pi

When you've installed and run the IoT Dashboard, a window appears:

  1. Select Set up a new device in the left-hand menu. This will open a simple form. Select your device (Raspberry Pi 2 & 3) and the OS you want to download and install (Windows 10 IoT Core).
  1. Also, insert the memory card into the computer and select the Drive letter it is assigned to. Other relevant information you need to provide include the Device name and an Administrator password:

Setting up a new device

Note

Remember the password!

  1. If you have access to Wi-Fi (2.4 GHz), and are programming a device with access to Wi-Fi, make sure the correct Wi-Fi Network Connection is also assigned:

Configuring Wi-Fi connectivity

  1. Finally, accept the license agreement, and press the Download and install button:

Installing Windows 10

You need to confirm you really want to format the memory card, and install Windows 10 on it. All previous data on the card will be lost. The IoT Dashboard then goes on to download the operating system and preparing the memory chip for you, including configuring the device, according to the settings you provided. This process includes performing some command-line tasks, so you will see a terminal window appear temporarily.

 

Starting your Raspberry Pi


When the card is ready, an Explorer window might appear, and the IoT Desktop window gives you instructions to remove the card and insert it into your device. Do so, and make sure you connect your device correctly. Then power it on. Meanwhile, go to the My Devices view in the IoT Dashboard. It might take a short while to boot the device up the first time. Don't worry, after first-time initialization, your Raspberry Pi, with Windows 10, should appear. This process can take from a couple of minutes to a quarter of an hour, depending on the memory card used:

Device ready for use

Connecting to your Raspberry Pi

When the device appears in your list of devices, right-click on it, and select Open in Device Portal. Your browser should open and prompt you to login. The username is Administrator. Enter the password you provided when you prepared your memory chip.

The Device Portal is a very handy and powerful web portal for your device. In it you can:

  • Configure basic device settings (you should update your time zone at this point).
  • Update your password.
  • Remotely view what's on the screen. This will come in handy, especially for devices that are not connected to monitors. Press the Capture Screenshot button to try this out.
  • Control installed apps.
  • Access files.
  • View processes and system performance.
  • Access a command prompt.
  • Access debugging tools.
  • Control system devices.
  • Manage network connectivity.
  • Update Windows (make sure you have the latest version by clicking on the Check for updates button):

Windows 10 start screen

Note

Since the Device Portal is so powerful and only protected by a simple username and password, of which the username is known beforehand, you need to take extra care by protecting it from outside access. Always keep your devices protected by firewalls. Don't allow anybody on the outside to connect to your devices, unless you have full control of what happens, and can make appropriate security decisions. We will present methods in this book, allowing you to develop IoT applications that will allow outside access in a simple way, but not through connecting to the device directly. This is much more secure. Using these techniques avoids risking the device needlessly.

Downloading the Arduino IDE

In projects where you want to use the Arduino in conjunction with the Raspberry Pi, you typically use an Arduino board that is mounted on top of the Raspberry Pi. This board also needs to be prepared. You do this using the Arduino IDE software, which can be downloaded from this link: https://www.arduino.cc/en/Main/Software. There are setup applications for Windows, Linux, and MAC.

Installing Firmata on your Arduino board

To access analog sensors on a Raspberry Pi, you need to add circuitry supporting serial communication to your board since it's not supported by default. One way is to use I2C or SPI circuits with analog to digital converters. Another way, which we explore in this book, is to use an Arduino board. The Arduino is a programmable chip, and, as such, you can program your own firmware with your own serial protocol inside. A simpler method, is to use the well-used and battle-tested Firmata protocol. Software for this already exists, and is available in the Arduino IDE directly. Libraries for Firmata exist in many languages.

To install Firmata on your Arduino board, simply follow the following procedure:

  1. Connect your Arduino board to your PC using a short USB cable.
  2. Load the Firmata application into the IDE. This is done by selecting File, then Examples, Firmata and Standard Firmata from the menu in the Arduino IDE.
  3. Specify the serial port you connected the Arduino board to. This is done under Tools and Port in the Arduino IDE.
  1. Next you need to specify the type of Arduino you're using. If using an Arduino Starter Kit, the name should be listed in the specification. You select the board under Tools and Board in the Arduino IDE.
  2. Finally, you upload the firmware to the Arduino board. You do this by clicking on the Upload button, formed as an arrow.

Note

If unsure about what type of Arduino you've connected, try the Tools and Get Board Info command.

Your Arduino board is now prepared with the Firmata firmware. You can close the Arduino IDE. You will not use it any more in this book.

Testing your Arduino board

Without disconnecting your Arduino board from your PC, you can test that it works as it should. Since the Firmata protocol is well known, there exist a lot of applications on varying operating systems, that can read sensors and control devices connected to the Arduino. Since we demonstrate Windows 10 in this book, you can use the Windows Remote Arduino Experience App for this purpose. It can be downloaded at https://www.microsoft.com/sv-se/store/p/windows-remote-arduino-experience/9nblggh2041m.

To test this software, we also need to connect some devices to it for testing. Let's connect our light sensor, PIR sensor, and relay module to it to see if we can access them. Make sure to connect ground, power and signal correctly. Also make sure to differentiate between digital pins and analog pins on your Arduino board. For the purposes of our example, I connected the PIR sensor to digital pin 8, and the relay to digital pin 9. The light sensor was connected to the analog pin A0.

Note

In my Starter Kit, ground (GND or -) is always black, power (3.3V, 5V or +) is always red. Analog pins are colored blue, while digital are colored green.While digital pins 0 and 1 can be used on some Arduino boards for general purpose input and output, other boards use them for serial communication only. That's why we've selected pins 8 and 9 instead of 0 and 1.Also, consider using anantistatic wrist strapto protect your hardware from electrostatic discharges.

When opening the Windows Remote Arduino Experience App, you must first choose how the app will communicate with your Arduino board. Since it's connected to a USB port, select USB in the Connection box, and select a communication speed of 57600 baud. Next, the app makes a search, and a list of devices will be presented. The Arduino board should appear. Select it and click the Connect button.

You should now be able to interact with the hardware you connected. First go to the Analog tab. Set the A0 pin to Input, and then watch how the value changes as you cover or illuminate the sensor accordingly:

Analog peripherals

Similarly, on the Digital tab, set the 8 pin to Input. Move your hand in front of the PIR sensor to activate it, and watch how the value jumps to a high voltage level. Set the 9 pin to Output and control it by setting the value correspondingly. You should hear the relay clicking as it changes position:

Digital peripherals

Now that you know your Arduino is programmed correctly, and that values are reported as they should be over the USB serial cable, you're ready to start programming.

Choosing a development environment

You're now ready to start actual coding. The first step is to choose a development environment. Since this book focuses on C# and .NET, including .NET Core 2, an obvious choice is to use Visual Studio. But it's not your only option.

For .NET Core development, you can also choose to use Roslyn, which, apart from being open source, can also be run directly on Windows 10 IoT Core, including the version we use on the Raspberry Pi. For more information about Roslyn, see https://msdn.microsoft.com/magazine/mt808499.

Another option, is to use Xamarin Studio. It's a development tool focusing on cross platform development using C#. With Xamarin you can develop applications for IoT devices, smart phones and tablets, as well as PCs using the same code base. It runs on both Windows and MAC. The community-edition is free. For more information, see https://www.xamarin.com/studio.

Since Microsoft acquired Xamarin, its cross-platform capabilities are also available in Visual Studio. A free version also exists. And Visual Studio can be run on MACs. The examples published in this book have been developed using Visual Studio 2017. For more information, see https://www.visualstudio.com/.

Using the IoT Gateway project and libraries

The projects presented in this book are all available on GitHub at https://github.com/PeterWaher/MIoT. To simplify development and prototyping, these projects use several libraries. These are available as downloadable and updateable packages (NuGets), most of which are open source, available on GitHub in the IoT Gateway repository at https://github.com/PeterWaher/IoTGateway. The IoT Gateway repository is available free for personal or academic use, or for security analysis. Commercial use requires a commercial license. The repository includes communication libraries, an encrypted object database, event logging infrastructure, application hosting, web server, content management, scripting, runtime-tools, and so on. Things that are good to have, to prototype real-world embedded IoT applications easily and quickly.

 

Creating your first project


Let's begin. Since our Raspberry Pi now runs Windows 10 IoT Core, .NET Core applications will run on it, including Universal Windows Platform (UWP) applications. From a blank solution, let's create our first Raspberry Pi application. Choose Add and New Project. In the Visual C# category, select Blank App (Universal Windows). Let's call our project FirstApp. Visual Studio will ask us for target and minimum platform versions. Check the screenshot and make sure the version you select is lower than the version installed on your Raspberry Pi.

Note

In our case, the Raspberry Pi runs Build 15063. This is the March 2017 release. So, we accept Build 14393 (July 2016) as the target version and Build 10586 (November 2015) as the minimum version. If you want to target the Windows 10 Fall Creators Update, which supports .NET Core 2, you should select Build 16299 for both.

In the Solution Explorer, we should now see the files of our new UWP project:

New project

Adding NuGet packages

We proceed by adding functionality to our app from downloadable packages, or NuGets. From the References node, right-click and select Manage NuGet Packages. First, go to the Updates tab and make sure the packages that you already have are updated. Next, go to the Browse tab, type Firmata in the search box, and press Enter. You should see the Windows-Remote-Arduino package. Make sure to install it in your project. In the same way, search for the Waher.Events package and install it.

Aggregating capabilities

Since we're going to communicate with our Arduino using a USB serial port, we must make a declaration in the Package.appxmanifest file stating this. If we don't do this, the runtime environment will not allow the app to do it. Since this option is not available in the GUI by default, you need to edit the file using the XML editor. Make sure the serialCommunication device capability is added, as follows:

<Capabilities> 
   <Capability Name="internetClient" /> 
   <DeviceCapability Name="serialcommunication"> 
         <Device Id="any"> 
               <Function Type="name:serialPort" /> 
         </Device> 
   </DeviceCapability> 
</Capabilities> 

Initializing the application

Before we do any communication with the Arduino, we need to initialize the application. We do this by finding the OnLaunched method in the App.xml.cs file. After the Window.Current.Activate() call, we make a call to our Init() method where we set up the application.

   Window.Current.Activate(); 
   Task.Run((Action)this.Init); 

Note

We execute our initialization method from the thread pool, instead of the standard thread. This is done by calling Task.Run(), defined in the System.Threading.Tasks namespace. The reason for this is that we want to avoid locking the standard thread. Later, there will be a lot of asynchronous calls made during initialization. To avoid problems, we should execute all these from the thread pool, instead of from the standard thread.

We'll make the method asynchronous:

private async void Init() 
{ 
   try 
   { 
         Log.Informational("Starting application."); 
         ... 
   } 
   catch (Exception ex) 
   { 
         Log.Emergency(ex); 
          
         MessageDialog Dialog =  
new MessageDialog(ex.Message, "Error"); 
         await Dialog.ShowAsync(); 
} IoT Desktop  
} 

The static Log class is available in the Waher.Events namespace, belonging to the NuGet we included earlier. (MessageDialog is available in Windows.UI.Popups, which might be a new namespace if you're not familiar with UWP.)

Communicating with the Arduino

The Arduino is accessed using Firmata. To do that, we use the Windows.Devices.Enumeration, Microsoft.Maker.RemoteWiring, and Microsoft.Maker.Serial namespaces, available in the Windows-Remote-Arduino NuGet. We begin by enumerating all the devices it finds:

DeviceInformationCollection Devices =  
   await UsbSerial.listAvailableDevicesAsync(); 
foreach (DeviceInformationDeviceInfo in Devices) 
{ 

If our Arduino device is found, we will have to connect to it using USB:

if (DeviceInfo.IsEnabled&&DeviceInfo.Name.StartsWith("Arduino")) 
{ 
   Log.Informational("Connecting to " + DeviceInfo.Name); 
 
   this.arduinoUsb = new UsbSerial(DeviceInfo); 
   this.arduinoUsb.ConnectionEstablished += () => 
         Log.Informational("USB connection established."); 

Attach a remote device to the USB port class:

this.arduino = new RemoteDevice(this.arduinoUsb); 

We need to initialize our hardware, when the remote device is ready:

this.arduino.DeviceReady += () => 
{ 
   Log.Informational("Device ready."); 
 
   this.arduino.pinMode(13, PinMode.OUTPUT);    // Onboard LED. 
   this.arduino.digitalWrite(13, PinState.HIGH); 
 
   this.arduino.pinMode(8, PinMode.INPUT);      // PIR sensor. 
   MainPage.Instance.DigitalPinUpdated(8,
          this.arduino.digitalRead(8)); 
   this.arduino.pinMode(9, PinMode.OUTPUT);     // Relay. 
   this.arduino.digitalWrite(9, 0);             // Relay set to 0 
 
   this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. 
   MainPage.Instance.AnalogPinUpdated("A0",
          this.arduino.analogRead("A0")); 
}; 

Note

Important: the analog input must be set to PinMode.ANALOG, not PinMode.INPUT. The latter is for digital pins. If used for analog pins, the Arduino board and Firmata firmware may become unpredictable.

Our inputs are then reported automatically by the Firmata firmware. All we need to do to read the corresponding values is to assign the appropriate event handlers. In our case, we forward the values to our main page, for display:

this.arduino.AnalogPinUpdated += (pin, value) => 
{ 
   MainPage.Instance.AnalogPinUpdated(pin, value); 
}; 
 
this.arduino.DigitalPinUpdated += (pin, value) => 
{ 
   MainPage.Instance.DigitalPinUpdated(pin, value); 
}; 

Communication is now set up. If you want, you can trap communication errors, by providing event handlers for the ConnectionFailed and ConnectionLost events. All we need to do now is to initiate communication. We do this with a simple call:

this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); 

Testing the app

Make sure the Arduino is still connected to your PC via USB. If you run the application now (by pressing F5), it will communicate with the Arduino, and display any values read to the event log. In the GitHub project, I've added a couple of GUI components to our main window, that display the most recently read pin values on it. It also displays any event messages logged. We leave the relay for later chapters.

Note

For a more generic example, see the Waher.Service.GPIO project at https://github.com/PeterWaher/IoTGateway/tree/master/Services/Waher.Service.GPIO. This project allows the user to read and control all pins on the Arduino, as well as the GPIO pins available on the Raspberry Pi directly.

Deploying the app

You are now ready to test the app on the Raspberry Pi. You now need to disconnect the Arduino board from your PC, and install it on top of the Raspberry Pi. The power of the Raspberry Pi should be turned off when doing this. Also make sure the serial cable is connected to one of the USB ports of the Raspberry Pi. Begin by switching the target platform, from Local Machine to Remote Machine, and from x86 to ARM:

Run on a remote machine with an ARM processor

Your Raspberry Pi should appear automatically in the following dialog. You should check the address with the IoT Dashboard used earlier, to make sure you're selecting the correct machine:

Select your Raspberry Pi

You can now run or debug your app directly on the Raspberry Pi, using your local PC. The first deployment might take a while, since the target system needs to be properly prepared. Subsequent deployments will be much faster. Open the Device Portal from the IoT Dashboard, and take a Screenshot, to see the results. You can also go to the Apps Manager in the Device Portal, and configure the app to be started automatically at startup:

App running on the Raspberry Pi

 

Summary


In this chapter, you've been given an introduction on how to develop apps for the Raspberry Pi using C#. You've learned how to prepare the hardware and how to use the IoT Dashboard to install and configure Windows 10 IoT on the device. You've used the Device Portal to control the applications running on it. You've learned how to extend the functionality of the Raspberry Pi by using Arduino boards. You've configured these with Firmata using the Arduino IDE. You've learned how to create a Universal Windows Platform application to run on the Raspberry Pi, and how to use NuGet packages to add existing software components to your application. You also successfully tested and deployed your application. In the next chapter, you will learn the basics of creating a working sensor.

Note

There are many excellent blog posts on the internet that provide tutorials concerning C# development on the Raspberry Pi. One example of such an article is https://msdn.microsoft.com/magazine/mt808503.

About the Author

  • Peter Waher

    Peter Waher is the founder of Little Sister®, a standards-based distributed social network, based on the principles of edge computing, privacy & information ownership, for humans and machines. Currently, Peter advises companies on topics such as privacy, the IoT and Smart Cities. He has worked for 24 years with computers and device communication, including low-level development in assembler for resource-constrained devices to high-level system design and architecture. His award-winning applications has attracted global attention, and he has been invited to speak at prestigious events.

    Browse publications by this author

Latest Reviews

(4 reviews total)
It tooks 1 weeks to download my purchase ebook.
Porque cumplió con mis expectativas.
This book was an excellent resource for studying IoT and preparing for my exam.

Recommended For You

Internet of Things Programming Projects

A practical project-based guide to help you build and control your IoT projects

By Colin Dow
Hands-On Industrial Internet of Things

Build a strong and efficient IoT infrastructure at industrial and enterprise level by mastering Industrial IoT network

By Giacomo Veneri and 1 more
Internet of Things for Architects

Learn to Design, Implement and secure your IoT infrastructure

By Perry Lea
Python Machine Learning - Third Edition

Applied machine learning with a solid foundation in theory. Revised and expanded for TensorFlow 2, GANs, and reinforcement learning.

By Sebastian Raschka and 1 more