In this guest post, Peter Waher, the author of the book, Mastering Internet of Things, shows how you can build your first Raspberry Pi project using a step by step practical guide
For the purposes of this article, you will need the following:
- A Raspberry Pi 2 or 3
- 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 convert analog signals to digital ones. To simplify this task, you can also use an Arduino board, which you can 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 the following 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 the 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.
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. You can download and install the IoT Dashboard from https://developer.microsoft.com/en-us/windows/iot/docs/iotdashboard.
The IoT Dashboard is a Windows 10 app. Once it’s running, you can choose to right-click on its icon and select Pin to taskbar, so that you can easily find it later.
If you don’t want to use Windows 10 but want to use Linux instead, you can do so with the following modifications:
- You can use the Raspbian operating system instead. It’s based on Debian. Follow the instructions given in https://www.raspberrypi.org/documentation/installation/installing-images/ to know how to download and install.
- Instead of compiling your project as a .NET Core application, compile it as a standard .NET Framework application instead.
- Run the application using Mono; refer to http://www.raspberry-sharp.org/eric-bezine/2012/10/mono-framework/installing-mono-raspberry-pi/.
Installing Windows 10 on your Raspberry Pi
When you’ve installed and run the IoT Dashboard, a window appears:
- 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).
- 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:
- If you have access to Wi-Fi (2.4 GHz) and are programming a device with access to Wi-Fi, make sure that the correct Wi-Fi Network Connection is also assigned:
- Finally, accept the license agreement, and press the Download and install button:
You need to confirm whether you really want to format the memory card and install Windows 10 on it. All the previous data on the card will be lost. The IoT Dashboard then goes on to download the operating system and prepare the memory chip for you, including configuring the device according to the settings you’ve 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’ve connected 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 the 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:
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):
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 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 is to use an Arduino board. 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 these steps:
- Connect your Arduino board to your PC using a short USB cable.
- 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.
- Specify the serial port you connected the Arduino board to. This is done under Tools and Port in the Arduino IDE.
- Next, you need to specify the type of Arduino you’re using. If you’re using an Arduino Starter Kit, the name should be listed in the specification. You’ve to select the board under Tools and Board in the Arduino IDE.
- Finally, upload the firmware to the Arduino board. You can do this by clicking on the Upload button.
Your Arduino board is now prepared with the Firmata firmware.
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 Arduino. For the current purpose of building a Raspberry Pi project, you can use the Windows Remote Arduino Experience App. It can be downloaded from https://www.microsoft.com/sv-se/store/p/windows-remote-arduino-experience/9nblggh2041m.
To test this software, you also need to connect some devices to it for testing. Connect the light sensor, PIR sensor, and relay module to it to see if you can access them. Make sure that you connect ground, power and signal correctly. Also make sure that you differentiate between digital pins and analog pins on your Arduino board. For the purpose of this article, I’ve connected the PIR sensor to digital pin 8, and the relay to digital pin 9. The light sensor is connected to the analog pin A0.
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 presents a list of devices. 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:
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:
Now that you know your Arduino is programmed correctly and that the 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 the actual coding. The first step is to choose a development environment. 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, tablets, and 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. In this article, we’ll be developing using Visual Studio 2017. For more information, see https://www.visualstudio.com/.
Creating your first project
Since our Raspberry Pi now runs Windows 10 IoT Core, .NET Core applications will run on it, including the 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 this project FirstApp. Visual Studio will ask you 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.
In the Solution Explorer, you should now see the files of your new UWP project:
Adding NuGet packages
Proceed by adding functionalities to the 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. Ensure that you’ve installed it in your project. In the same way, search for the Waher.Events package and install it.
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:
<Capability Name=”internetClient” />
<Function Type=”name:serialPort” />
Initializing the application
Before you establish any communication with Arduino, you need to initialize the application by finding the
OnLaunched method in the
App.xml.cs file. After the
Window.Current.Activate() call, make a call to the
Init() method to set up the application.
We’ll make the method asynchronous:[c] private async void Init()
catch (Exception ex)
MessageDialog Dialog = new MessageDialog(ex.Message, “Error”);
} 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 so, use
Microsoft.Maker.Serial namespaces, available in the Windows-Remote-Arduino NuGet. Begin by enumerating all the devices it finds:
foreach (DeviceInformationDeviceInfo in Devices)
If the Arduino device is found, connect to it using USB:[c] 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:[c] this.arduino = new RemoteDevice(this.arduinoUsb);
Initialize the hardware when the remote device is ready:
this.arduino.DeviceReady += () =>
this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED.
this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor.
this.arduino.pinMode(9, PinMode.OUTPUT); // Relay.
this.arduino.digitalWrite(9, 0); // Relay set to 0
this.arduino.pinMode(“A0”, PinMode.ANALOG); // Light sensor.
The inputs are then reported automatically by the Firmata firmware. All you need to do to read the corresponding values is to assign the appropriate event handlers. In this case, forward the values to the main page for display:[c]this.arduino.AnalogPinUpdated += (pin, value) =>
this.arduino.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 you need to do now is to initiate the communication with a simple call:[c] this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
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 that 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:
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:
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:
If you enjoyed this post and want to learn more about Internet of Things, you can read Mastering Internet of Things by Peter Waher, a hands-on book that will guide you through the advanced concepts of IoT in a lucid manner.