The IoT Journey: Additional Peripheral Protocols

In the last post of this series, I discussed digital signaling and hardware interrupts. The purpose of these posts is to educate on the basics of IoT technologies so that you will have a foundation to work from in order to build new IoT projects. In this post, we will discuss the concept of Pulse-Width Modulation (PWM) and how to use PWM to drive a tri-color LED with code on the Raspberry Pi.

Pulse Width Modulation

When controlling physical “things” from electronics, you have to be able to do more than simply power on and off a device, or react to the press of a button. The challenge there is that digital signals are either “on” or “off”, and buttons are either pressed or not. When working with electronic circuitry, one technique used to encode a message into a digital signal is called Pulse Width Modulation, or PWM. Basically what this means is that you define a “width” of the “on” signal (the amount of time that the signal is on) as equal to a binary value, and then you define the amount of time that you will “read” the total signal to obtain the message.

Probably the most common use of PWM in electronics is controlling the speed of a motor. Instead of using an analog circuit and adjustable resistor (which can generate a lot of heat and wasted energy), PWM is used to control the “duty cycle” of the motor (the amount of time that full power is applied versus the amount of time power is off). A simplistic example would be if we wanted to run a motor at 50% of it’s maximum speed, we could set the duty cycle to 50%, meaning that the PWM signal would be on 50% of the time and off 50% of the time.

There are many other examples of using PWM in electronics, and one of the easiest to work with is the multi-color LED light. A multi-color LED, or RGB LED, has a common cathode (or anode, depending on type) and then 3 inputs representing each of the primary colors. By using PWM and controlling the amount of time power is applied to each of the primary color inputs, we can create virtually unlimited output colors on the LED.

The Raspberry Pi 3 has 2 available PWM hardware outputs, but one of those is shared with the audio out, so in practice there is only a single channel available. Given this, projects that require more than a single PWM channel (such as the example above of an RGB LED) utilize a software library that “bit bangs” the output of a GPIO pin to create the PWM signal. This works well for LEDs and servo motors, where the use of the PWM signal is limited, but it’s much harder to implement when controlling a motor that requires a more constant PWM signal ( this is because for the duration of the PWM signal, the CPU is effectively latched performing that task).

For the purposes of this example, we’ll control an RGB LED from the Raspberry Pi, using the SoftPWM capabilities exposed in the WiringPi library that we’ve used in previous examples…

Step One – Wire the Circuit

Since we will require 3 GPIO channels, we’ll choose GPIO Pins 23, 24 and 25 (physical pins 16, 18 and 22) since they are convenient and aren’t used in the ISR solution that we created in the previous post. The Red pin will connect to GPIO 23, the Green pin to GPIO 24 and the Blue pin to GPIO 25. Connect the ground (-) pin to GND on the breadboard.

If you purchased the Sunfounder Sensor kit mentioned in previous posts, you’ll have an RGB LED that is already mounted to a circuit board with headers, otherwise you’ll need to obtain one and connect wires to the leads in order to plug it into the breadboard properly. The LED assembly looks like this:

20160428_164001105_iOS

 

The breadboard configuration will look like this:

20160428_165115470_iOS

Once the circuit is wired, we’re ready to extend the previous code solution to include the RGB LED.

Step Two – Develop the Solution

For the sake of simplicity, we’ll simply extend the previous button solution that we created and add the RGB LED. We will write code that will toggle the state of the LED between Red, Green and Blue as the button is pressed.

The flow of the program is basically:

  • Initialize the SoftPWM library and connect each of the GPIO outputs to the appropriate color pin on the LED
  • Initialize the ISR and set the callback method used
  • Ensure that the RGB LED is off
  • Wait for either a button press or a keyboard press
    • If a button press is detected, toggle the solitary LED, and then check the current state of the RGB LED and then toggle through the color choices
    • If a keyboard press is detected, close the PWM library and exit the program

Open the ISR solution in Visual Studio that we previously created (See the previous post in this series) and add the supporting constants:

image

Then add code to initialize the SoftPWM Library. We will use the default of 100 microseconds for the pulse width to balance CPU utilization with PWM functionality.

image

Then add a method to the class that sets the RGB LED saturation values:

image

Once that is done, add a method that detects the current state of the RGB LED and toggles it appropriately. (In this example we’re just using Red, Green and Blue as colors, however you can mix/match the RGB values to create any color combination that you want).

image

Finally, add code to the ISR method that invokes the SetRGB() method.

image

This will ensure that the LED switches through the RGB colors (or colors that you define) with a button press. Keep in mind that we are not debouncing the switch, so you will likely see some spurious color changes when you press the button.

The complete program.cs code is as follows:

using System;
using System.Threading.Tasks;
using WiringPi;

namespace ISR
{
class Program
{
const int redLedPin = 29; // GPIO 5, physical pin 29
const int buttonPin = 31; // GPIO 6, physical pin 31

        const int rgbLedR = 16; // GPIO 23, physical pin 16
const int rgbLedG = 18; // GPIO 24, physical pin 18
const int rgbLedB = 22; // GPIO 25, physical pin 22

        static string LedColor = “None”; // This is just a string variable that tells us what color the RGB LED is currently

        // The color saturation value is how “on” that particular color is. So when the redvalue is 255 and green and blue are 0, the
// Led will be Red. If the RedValue is 255 and GreenValue is 255, then the resulting color will be Red+Green or Yellow
// If Red is 0 and Green and Blue are both 255, then the resulting color will be Blue + Green or Cyan.
// See the RGB Model Wikipedia for more info:
https://en.wikipedia.org/wiki/RGB_color_model

        static void buttonPress()
{
if (GPIO.digitalRead(redLedPin) == (int)GPIO.GPIOpinvalue.Low) // Check to see if LED is on
GPIO.digitalWrite(redLedPin, (int)GPIO.GPIOpinvalue.High); // If so, turn it off
else
GPIO.digitalWrite(redLedPin, (int)GPIO.GPIOpinvalue.Low); // Otherwise turn it on

            SetRGB(); // Light the RGB LED with the appropriate color
}
static void Main(string[] args)
{
Console.WriteLine(“Initializing GPIO Interface”);
if (Init.WiringPiSetupPhys() < 0) //Initialize the GPIO Interface with physical pin numbering
{
throw new Exception(“Unable to Initialize GPIO Interface”); // Any value less than 0 represents a failure
}
GPIO.pinMode(redLedPin, (int)GPIO.GPIOpinmode.Output); // Tell the Pi we will be writing to the GPIO
GPIO.digitalWrite(redLedPin, (int)GPIO.GPIOpinvalue.Low); // Turn LED On

            GPIO.SoftPwm.Create(rgbLedR, 0, 100); // Setup the RGB LED pins as PWM Output and set the Pulse Max duration of 100 microseconds.
GPIO.SoftPwm.Create(rgbLedG, 0, 100); // This is software-based PWM since the Pi only has a single PWM hardware channel
GPIO.SoftPwm.Create(rgbLedB, 0, 100);

            Console.WriteLine(“Initializing Interrupt Service Routine”);
// We will fire the interrupt on the falling edge of the button press. Note that we are not “debouncing” the switch, so we will likely
// see some extra button presses during operation
if (GPIO.PiThreadInterrupts.wiringPiISR(buttonPin, (int)GPIO.PiThreadInterrupts.InterruptLevels.INT_EDGE_FALLING, buttonPress) < 0) // Initialize the Interrupt and set the callback to our method above
{
throw new Exception(“Unable to Initialize ISR”);
}
Console.WriteLine(“Press the button to toggle LED or press any key (and then press button) to exit”);
Console.ReadKey(); // Wait for a key to be pressed
GPIO.digitalWrite(redLedPin, (int)GPIO.GPIOpinvalue.High); // Turn off the static LED

            GPIO.SoftPwm.Stop(rgbLedR); // Turn off the RGB LED
GPIO.SoftPwm.Stop(rgbLedG);
GPIO.SoftPwm.Stop(rgbLedB);
}

        private static void SetRGB()
{
switch(LedColor) // Remember that we aren’t debouncing the switch, so the color changes may not be as elegant as the code would show
{
case “None”: // This will be the value when we first execute the code and the button is pressed
SetLedColor(255, 0, 0); // Turn the LED On Red
LedColor = “Red”; // Set the variable to Red so we know what color is showing
break;
case “Red”: // This will happen after the second button press
SetLedColor(0, 255, 0); // Set the color to Green
LedColor = “Green”;
break;
case “Green”: // This will happen after the third button press
SetLedColor(0, 0, 255); // Set the color to Blue
LedColor = “Blue”;
break;
case “Blue”: // This will happen after the fourth button press
SetLedColor(255, 0, 0); // Set the color to Red
LedColor = “Red”;
break;
default: // We should never reach this point, but if we do, handle it
LedColor = “None”;
break;
}

        }
private static void SetLedColor(int r, int g, int b) // Pulse the RGB pins with the appropriate saturation values
{
GPIO.SoftPwm.Write(rgbLedR, r);
GPIO.SoftPwm.Write(rgbLedG, g);
GPIO.SoftPwm.Write(rgbLedB, b);
}
}
}

Now that the code is developed, build it and fix any errors that you find. Once it is built without error, we can deploy it to the Pi and test.

Step Three Deploy and Execute the Code

Using a file transfer program (as mentioned before, I use FileZilla) connect to the Pi and copy the ISR.exe and WiringPi.dll files to the Pi. Overwrite the files that you previously copied.

image

Once the files are copied, you can execute the ISR.exe program by typing the command sudo mono ISR.exe:

image

Press the button several times and then note that the RGB LED switches through the colors.

20160428_174018231_iOS20160428_174024557_iOS20160428_174031228_iOS

Congrats! You now have developed and deployed a solution that utilizes Pulse Wide Modulation to control an LED!!

The IoT Journey : Interacting with the Physical World

In the first two posts of this series (See Post One and Post Two) I detailed the process of configuring a Raspberry Pi 3 to enable development and testing of Internet of Things (IoT) projects. The first post covered the basics of the Raspberry Pi, and the second detailed the basics of the GPIO interface and demonstrated how to turn an LED on and off with code. In this post, we will extend the project that we created earlier and add interaction with the physical world through the use of a mechanical button press.

When interacting with sensors and devices, one of the more important things to understand is how interrupts work, and how you code interrupt service routines.

Understanding Hardware Interrupts

This is a topic that you could spend many hours on and not understand all of the nuances, yet it’s very important to understand the basics of how interrupts work if you’re going to develop IoT applications that utilize sensors or other electronic components that work with the Raspberry Pi.

If you have an electronic circuit that contains a pushbutton switch, and you want the activity of the switch to cause action in your program, you need to write code that will read the state of the switch and then react based on the state of the switch. There are many different ways that you can approach this problem, but probably the two most common ways are polling and interrupt-driven. In a polling solution, you simply write code that reads the state of the switch, and call it on a regular basis. This works well if you can anticipate the pressing of the switch (i.e, the flow of your application is such that the user would press the switch at known points in the code), or if you use an asynchronous method to create a timer that reads the switch at defined intervals (of course this could be a problem if the switch is pressed and released outside of the defined interval, it would go unnoticed).

An interrupt is a signal to the processor to tell it to stop whatever it’s currently doing and do something else. In the switch example above, if we connected the switch to a GPIO and then defined that pin as an interrupt, whenever the pin detected a change in state (if the button were pressed, for example), it would activate the interrupt, and our code would simply have to handle that interrupt.

Because the Raspberry Pi GPIO interface is a digital interface, we have to understand the concept of Signal Edge when working with interrupts. Digital signals are either on or off and are represented by a square wave:

image

The normal HIGH (or current is not flowing) signal on the Raspberry Pi GPIO is 3.3v. This is why, in the previous post, we set the pin to LOW in order to light the LED. If you look at the above chart, you will notice that there are transitions between zero and 3.3v represented at the edge of the square. For example, if you look at 10 on the x axis, you’ll see the transition from 3.3v to 0v. This is known as a Falling Edge. Conversely, if you look at 15, you’ll notice the transition from 0v to 3.3v. This is known as the Rising Edge. If we construct our circuit such that the button press allows current to flow, then we will want to ensure the interrupt is generated only on the Falling Edge, otherwise we would trigger two interrupts for every button press. The simplified circuit diagram would look like this:

image

When the button is pressed, the GPIO pin is “Pulled Low”, meaning that current will flow between the pin and ground. One issue that might arise in this configuration is the fact that the mechanical switch isn’t precise and can possibly generate false signals as the contacts travel close during the push or release of the switch. Sometimes this “bouncing” effect can generate multiple signal transitions and must be considered when coding routines that deal with switch presses. This concept is known as de-bouncing. (As this series of posts is meant to be instructional and not production-quality, we will not de-bounce our switch inputs)

With this basic understanding out of the way, let’s move on to creating a simple circuit and writing some code to react to the button press.

Step One – Construct the Simple Circuit

In the previous post, we created a simple circuit that included an LED and a resistor that connected to the GPIO interface and allowed us to control the LED in code. The circuit diagram looks like:

image

and the resulting breadboard configuration looks like:

This circuit allowed current to flow through the LED when the GPIO pin was set (or “pulled”) LOW. We wrote code that simply set the GPIO interface to LOW whenever a key was pressed on the keyboard.

For this example, we will add the switch to the breadboard and connect one side to ground, and the other side to GPIO 6 (physical pin 31). The circuit will look like this:

image

And the resulting breadboard configuration will be (ignore the additional LEDs and Resistors at the top, we will discuss those later):

20160424_173812624_iOS

(note that even though the same breadboard is used, the switch circuit is not connected to the LED in any way)

Once the circuit is constructed, we’re ready to move on to coding the solution.

Step Two – Develop the Code

For this exercise, we will create a new solution in Visual Studio that uses interrupts to detect when the button is pressed. We will then toggle the LED every time the button is pressed.  In Visual Studio, create a new C# Windows Console application named ISR.

image

Once the solution is created, add a reference to WiringPi.dll (Because you have previously referenced this .dll, it should be present in the Reference Manager dialog and you should just have to select it).

image

Once the reference is complete, add a using statement for the WiringPi library:

image

The basic flow the application we are about to create is:

  1. Initialize the GPIO Library and tell it how we will reference the GPIO pins
  2. Instruct the GPIO that we will be writing to the pin with the LED connected
  3. Turn the LED On
  4. Initialize the WiringPi Interrupt Service Routine and tell it which signal edge will trigger an interrupt
  5. Wait for a button press, and if one is detected toggle the state of the LED
  6. Check if a key is pressed, and if so, exit the program

The completed code, with comments is below:

using System;
using System.Threading.Tasks;
using WiringPi;

namespace ISR
{
class Program
{
const int redLedPin = 29; // GPIO 5, physical pin 29
const int buttonPin = 31; // GPIO 6, physical pin 31
static void buttonPress()
{
if (GPIO.digitalRead(redLedPin) == (int)GPIO.GPIOpinvalue.Low) // Check to see if LED is on
GPIO.digitalWrite(redLedPin, (int)GPIO.GPIOpinvalue.High); // If so, turn it off
else
GPIO.digitalWrite(redLedPin, (int)GPIO.GPIOpinvalue.Low); // Otherwise turn it on

        }
static void Main(string[] args)
{
Console.WriteLine(“Initializing GPIO Interface”);
if (Init.WiringPiSetupPhys() < 0) //Initialize the GPIO Interface with physical pin numbering
{
throw new Exception(“Unable to Initialize GPIO Interface”); // Any value less than 0 represents a failure
}
GPIO.pinMode(redLedPin, (int)GPIO.GPIOpinmode.Output); // Tell the Pi we will be writing to the GPIO
GPIO.digitalWrite(redLedPin, (int)GPIO.GPIOpinvalue.Low); // Turn LED On
Console.WriteLine(“Initializing Interrupt Service Routine”);
// We will fire the interrupt on the falling edge of the button press. Note that we are not “debouncing” the switch, so we will likely
// see some extra button presses during operation
if (GPIO.PiThreadInterrupts.wiringPiISR(buttonPin, (int)GPIO.PiThreadInterrupts.InterruptLevels.INT_EDGE_FALLING, buttonPress) < 0) // Initialize the Interrupt and set the callback to our method above
{
throw new Exception(“Unable to Initialize ISR”);
}
Console.WriteLine(“Press the button to toggle LED or press any key (and then press button) to exit”);
Console.ReadKey(); // Wait for a key to be pressed
GPIO.digitalWrite(redLedPin, (int)GPIO.GPIOpinvalue.High);
}
}
}

 

Once you have the application coded, build it and prepare to deploy it to the Raspberry Pi.

Deploying and Executing the ISR Application

Use a file transfer program (I use FileZilla) to copy the ISR.exe and WiringPi.dll files to a folder on the Raspberry Pi. (I used ~/DevOps/ISR)

image

 

Once the files are copied, you can execute the application with the command sudo mono ISR.exe:

image

The LED will light, and when you press the button it should toggle state. You will likely very quickly see the result of our not de-bouncing the switch, as some presses will likely result in multiple toggles of the LED. There are many patterns for de-bouncing in software, but the most reliable solutions are hardware-based.  You will also note that when you press a key, the application does not exit until you press the button as well. This is a byproduct of the ISR Routine needing to execute in order to capture the keypress.

Congrats! You’ve now developed an application that bridges the gap between code and the physical world. This is an extremely important concept for developing any IoT Application.

In the next post in this series, we will discuss the concept of digital signaling and will develop an application that interacts with an RGB LED that requires Pulse Width Modulation in order to work properly.

The IoT Journey: Introducing the Raspberry Pi Expansion Capabilities

In my previous post in this series, I introduced the Raspberry Pi3 and provided the steps necessary to build and configure it to run C# applications that were developed using Visual Studio on Windows. Obviously you need to know the basics in order to proceed to more IoT-relevant projects, so if you’re just getting started in the IoT world with the Raspberry Pi, please make sure you understand the concepts discussed in the first post.

In any IoT project, you’ll likely want some external sensor capability beyond what is provided by the Raspberry Pi itself. Examples of relevant sensors could be temperature and humidity sensors, barometric sensors, altimeter sensors, etc.. The list is limited only by your creativity and imagination.

The Raspberry Pi is very versatile in that it has expansion capabilities that allow us to both read data and write data using several common interface protocols.

In this post, I’ll discuss the Raspberry Pi’s expansion header and how to write data as well as read data from externally-connected “things”. Admittedly this post is going to enter into “uber geek” territory quickly, and if you’re the type of person that is easily intimidated by “raw electronics”, I’d suggest to you that even though it might look intimidating and complicated, working with electronic components and circuitry is not all that difficult and can be extremely rewarding, so please, read on and give it a go. You won’t be disappointed.

Step One – Obtaining the Necessary Components

When I was much younger, one of my favorite things to do was to grab my allowance savings and free battery card (ah, the memories) and run down to the local Radio Shack store to see what cool things I could afford. Although the stores have declined in popularity and capability somewhat, they have seen a resurgence due to the popularity of the “maker” community, and many stores do stock the components necessary to experiment with IoT. With that said, I have found that there are some very comprehensive kits available from Sunfounder that put all of the parts into a single kit. While there are many different kits available, I found that for my experimentation the following two kits were the most useful:

Super Starter Kit – This kit has pretty much everything you’ll want, although it is a little light on some of the more useful sensors.

Sensor Kit – This kit makes up for the missing sensors above and then some.

For the purposes of this post, you’ll need the following components (which are available in the Super Starter Kit):

  • Breadboard – The breadboard allows you to place the components together in a circuit without the need to solder anything
  • Raspberry Pi GPIO Expansion Board – This simply plugs into the breadboard and makes it easy to connect the components to the Pi
  • Expansion Cable – The Raspberry Pi expansion header is 40 pins and the cable will connect the header on the Pi to the Breadboard
  • 220 Ohm resistor – You’ll need this to ensure the circuit we build is properly configured
  • Led – We will write code to turn the LED Light on and off
  • Switch – We will use code to read the state of the switch and take action

20160421_165941558_iOS

Once you have the components, you’ll want to connect everything to the expansion header in the Raspberry Pi (pay close attention to the pin layout – if you use the rainbow cables from the sunfounder kit mentioned above, you’ll want to connect it with the black wire (pin 1) closest to the end of the Raspberry Pi that contains the SD card. This can be confusing because the cable will fit in either direction, but it’s extremely important to connect the correct pin #s to the breadboard, otherwise you could find yourself applying the wrong signal or voltage to a sensor and at best destroying your sensor, and worst destroying the Pi….

20160421_175849764_iOS

Just make sure that the cable is correctly connected, and you’ll be OK.

Step Two – Prepare the Raspberry Pi

Once you’ve obtained the components and have plugged the expansion cable into the Pi, we need to make sure we have the appropriate development libraries installed in order to take advantage of the capabilities of the Pi.

The primary expansion capability on the Raspberry Pi is accessed through a series of General Purpose Input-Output (GPIO) pins. In short, the GPIO interface allows you to connect external devices directly to the Raspberry and then interact with that device. The “General Purpose” nature of this interface is exactly what makes the Raspberry Pi so popular with “makers”, and is what allows us to connect so many different devices to the Pi. This is the good news, the bad news, of course, is that because it is “General Purpose”, we need to actually write all of the code necessary to interact with the device. Fortunately, there are a number of very good libraries that already exist in the public domain that are designed to do exactly that.

Arguably the most popular and useful library is called Wiring Pi and is made available by Gordon Henderson. Gordon has made his library available using various methods and he is very good about reacting quickly to community feedback and requests for enhancement. This really does demonstrate the power of the Open Source community and is one reason that I’ve chosen to use open source tools for all of my IoT work.

The easiest way to install the WiringPi library is to use git (git is a tool that allows you to interact directly with source code repositories) and install it directly on the Pi. To do this, you’ll first need to make sure you have the current version of the git command installed connect to your Pi via SSH (see the first post in this series for a refresher on how to do this) and then run the following command, sudo apt-get install git-core . (Git is usually preinstalled on the Raspbian image, but you want to install the latest version, which this command will do)

image

Once Git is installed, change directories to the DevOps folder that you created for the Hello application (created in the first post in this series) and then execute the following command: git clone git://git.drogon.net/wiringPi . This will install the git source code onto your Pi.

image

Once the source code is installed, you’ll need to compile the code that will be used by your applications. Fortunately Gordon makes this simple and has provided a build script to do all of this. Change directories to the wiringPi directory and execute the script by typing ./build to start the script.

image

You are now ready to start developing applications for the Pi that interact directly with the GPIO interface.

Step Three – Preparing your Development Environment

Now that your Pi is configured and ready to receive your IoT applications, you need to prepare your development environment to ensure that you can properly develop code that will run on the Pi and interact with the wiringPi library. This can get tricky, because we’re going to be developing our code in C# on windows, but the wiringPi library is written on C for Linux. The first step in preparing for this is to create shared libraries from the code we just complied on the Pi. For our purposes, there are 3 specific libraries that we will create. Change to the wiringPi folder (inside the wiringPi folder that you created) and execute the following commands to create the libraries:

  • cc -shared wiringPi.o -o libwiringPi.so This command uses the compiler to create the basic library – this is the core library that we will use
  • cc -shared wiringPiI2C.o -o libwiringPiI2C.so – This command creates the library specific to the I2C protocol – more on this in later posts
  • cc -shared wiringPiSPI.o -o libwiringPiSPI.so – This command create the library specific to the SPI protocol – more on this in later posts

image

The next step in utilizing the wiringPi library is to build a C# wrapper that will encapsulate the functionality of the C libraries and allow you to use the C-on-Linux library as just another reference in your project. This is done in C# / Visual Studio by using an External Reference in a code file which tells the C# code where to “enter” the C code and what the specific interface looks like. As you might imagine, it can get fairly complex trying to read through the C source code to locate the routines that you want to use and then generate the appropriate wrapper. Fortunately for us, a gentleman by the name of Daniel Riches has taken the time to do just that and made his work available via open source. (yet another reason to love the open source community!)

In order to take advantage of the work Daniel has done, you’ll need to clone his git repository on your Windows development environment. You should already have git for windows installed, but if not, download it and install it, and then start the command line utility (which is PowerShell-based), switch to the root of the folder that you want to install the library in, and then issue the command git clone https://github.com/danriches/WiringPi.Net.git

image

This will install the source code and test harness for the WiringPi.Net library, which you will use for all of the code that you develop moving forward.

Once the library is installed, open Visual Studio and load the WiringPi.sln file that is included in the library. Right-click on the WiringPi project and then select Build.

image

This will create a .dll that you will reference in all of your other projects. Alternatively you can simply add the WiringPi code directly to each of your new solutions moving forward, but I personally find it easier to just add the .dll reference. (note, the default is to build the .dll in Debug mode, which is fine for our experiments, but if you are going to build production applications you’ll probably want to build it in Release mode)

Once your development environment is setup, you’re ready to develop  the “Hello World” equivalent in the IoT world…

Step Four – Create a Simple IoT Application

In any IoT application, the basic components are a device or sensor that collects information and a repository for that information. For the purposes of this post, we will focus on the sensor aspect of IoT. In most cases, the sensor that you would work with in a real world application would collect data in an analog form, and then convert that data to a digital signal in order to communicate that to the host (in our case via the GPIO pins on the Raspberry Pi). The process of converting the analog information into a digital signal is a non-trivial process, so when you are beginning to learn to develop IoT applications, you want to start with the most basic and work your way up to the more complex tasks, learning along the way. One of the more basic tasks that you can perform is using code to light an LED light. (It may sound like a very simple and easy task, but even though it really is a basic task, there is a lot to be learned by performing this simple task).

For this step, you’ll need an LED (any color will do), a 220 ohm resistor (color code Red,Red,Black) and the wires necessary to connect them on the breadboard.

Wire the Breadboard

If you are using the same GPIO expansion header that I am from the Sunfounder kit, this will be relatively easy for you since the GPIO signals are marked on the header and it’s easy to understand what you are connecting to. If you aren’t using that, you will definitely want to pay attention to the Raspberry Pi pinout diagram below:

RP2_Pinout

There is a fair amount of confusion around how the pins are referenced by both documentation and code, and this pinout diagram is one of the best available that shows the translation between the physical pin number, and the pin number as referenced by code. Due to the fact that hardware does occasionally change, most software libraries will reference the pin by function as opposed to location.

In our case, we are going to use GPIO 5 (physical pin 29) to drive the LED, and will use the 3.3v power (physical pins 1 or 17) as our power source. On the breadboard, plug the LED into an open space, and then connect the shorter leg (This is very important, the LED has 2 legs, one is longer than the other and must be installed in the correct direction to work correctly) to GPIO 5 and the longer leg to the resistor. Connect the other side of the resistor to the 3.3v supply. The circuit might look like this:

20160422_013956739_iOS

Note that I am using a header board that automatically connects the power to the edges of the breadboard, so I simply ran the 3.3v from that instead of to pin 1 or 17.

Once the circuit is complete, you can build a very simple application to turn the light on and off.

Developing the Hello World Application

In Visual Studio, create a new C# Windows Console Application and name it PiLED.

image

Once Visual Studio creates the project, right-click on the references node and select Add Reference. Select Browse, and browse to the location where you compiled the wiringPi library earlier. Select wiringPi.dll and then Add it to the project references.

image

This will ensure that the appropriate references are present for the code we’re about to write.

The basic process that we need to follow in order to instruct the Raspberry Pi to turn the LED on and off is:

  1. Initialize the GPIO Interface and tell it how we will reference the pins.
  2. Tell the GPIO Interface that we are planning to write to it
  3. Instruct the appropriate GPIO pin to turn LOW (which enables current to flow from the 3.3v power through the resistor and LED, thus lighting the LED)
  4. Pause (so that we can witness the LED in an ON state
  5. Instruct the appropriate GPIO pin to turn HIGH (and thus disable current flow through the LED)
  6. Wait for a key press
  7. Exit the program

The completed code (in the file program.cs in your project) looks like this:

using System;
using WiringPi;
namespace PiLED
{
class Program
{
// ENUM to represent various Pin Mode settings
public enum PinMode{
HIGH = 1,
LOW = 0,
READ = 0,
WRITE = 1
}
const int RedLedPin = 29; // LED is on GPIO 5 (Physical Pin 29)

        //This is a console application with no GUI interface. Everything that happens will be in the shell
static void Main(string[] args)
{
Console.WriteLine(“Initializing GPIO Interface”); // Tell the user that we are attempting to start the GPIO
if (Init.WiringPiSetupPhys() != -1) // The WiringPiSetup method is static and returns either true or false. Calling it in this fashion
//ensures that it initializes the GPIO interface and reports ready to work. We will use Physical Pin Numbers
{
GPIO.pinMode(RedLedPin, (int)PinMode.WRITE); // Set the mode of the GPIO Pin to WRITE (The method requires an integer, so CAST it)
GPIO.digitalWrite(RedLedPin, (int)PinMode.HIGH); //Ensure that the LED is OFF
Console.WriteLine(“GPIO Initialization Complete”);
Console.WriteLine(“Press Any Key to Turn LED On”);
Console.ReadKey(); // Pause and wait for user to press a key
GPIO.digitalWrite(RedLedPin, (int)PinMode.LOW); // Turn the LED On
Console.WriteLine(“Led should be on”);
Console.WriteLine(“Press Any Key to turn the LED Off and Exit”);
Console.ReadKey();
GPIO.digitalWrite(RedLedPin, (int)PinMode.HIGH); //Turn LED Off
}
else
{
Console.WriteLine(“GPIO Init Failed!”); //If we reach this point, the GPIO Interface did not successfully initialize
}
}
}
}

 

Deploying the HelloWorld Application

Once you have the code in Visual Studio, Compile it by using the Build option. Once the code is compiled, you will need to use a file transfer program to copy the .exe as well as the wiringPi.dll file to a directory on the Pi. (I use FileZilla, and created a new folder in the /DevOps folder called PiLED.

image

Once the file is copied you will need to execute the application on the Raspberry Pi.

Executing the HelloWorld Application

Connect to the Raspberry Pi and then change to the directory where you copied the files (in my case ~/DevOps/PiLED) and execute the application by using the mono command. In this case, since we are interfacing directly with the hardware, we must run the application as root by using the sudo command. The command is sudo mono PiLED.exe

image

Once  you start the application you will see the “Initializing” message. Press a key and the LED will turn on. Press another key and the LED will turn off and the program will exit.

Congratulations! You’ve just written your first application that will become the foundation for further IoT application development.

Future posts in this series will build on what you’ve created here and will demonstrate some of the other protocols as well as how to send data “to the cloud” to truly experience IoT development.

The IoT Journey : Getting Started with the Raspberry Pi 3

If you are involved with “Big Data”, “Advanced Analytics” or “Cloud Computing”, you’ve likely heard all the hype around the “Internet of Things” or “IoT”. It used to be that IoT meant things like the connected refrigerator, or networked thermostats. Now it seems like IoT is being applied to just about anything that can connect and share information, be it “wearables” that track fitness information, RFID tags that track objects, or more complex ideas like Smart Meters and connected buildings. In short, IoT is currently in the midst of a major hype cycle, and as such everyone seems to be talking about it, or wondering what it’s all about.

Simply put, IoT at it core is a connected device (it doesn’t have to be connected to the Internet) that shares some data about itself somewhere with something.

One of the most talked about devices over the last couple of years has been the credit-card sized computer, Raspberry Pi. The Raspberry Pi was originally designed to be used in the classroom to teach kids about programming and electronics, but due to its capability (there are those who use the Pi as their primary computer!) and price (you can buy a new Raspberry Pi for $35 in the US), an entire community of hobbyists and professionals use the Raspberry Pi for their work and play.

I have been working with a Raspberry Pi2 for the last year, but I had never gotten the WiFi adapter that I purchased to work properly, so I was really excited to hear that not only was the Raspberry Pi3 faster, it also had onboard WiFi. I want to utilize WiFi so that the device can be portable and used wherever I might be working.

If you want to learn how to develop IoT applications, there is no better place to start than with a Raspberry Pi and the Pi community. Be warned though, this community will suck you in, and you will find yourself immersed in a world of code, wires, sensors and frameworks before you know it!

The First Steps

One of the major announcements that Microsoft made with Windows 10 is that there is a version that will run on the Raspberry Pi. This version of Windows is called “Windows IoT Core” and is designed to be the OS layer for IoT devices. If you are a developer that focuses on Windows technologies, this is a natural platform for you to gravitate towards. Of course the “New Microsoft” embraces Open Source platforms as well as our own, so I thought it would be interesting to see how far I could extend my Windows development skills into the IoT world using the popular open source Linux Operating System. This post marks the beginning of that journey…

Step One – Obtain the Hardware

There are many places that you can buy a Raspberry Pi3, including Amazon, Fry’s Electronics (in the US) and RS-Online (in the UK). For this project, I decided to buy the kit offered by the Microsoft Store (I was already there, and had other things to buy, so why not?). The specific items I purchased are:

  • Raspberry Pi3 – This kit comes complete with an SD-Card with the NOOBS installer already configured. In my case though, the SD Card was NOT a class 10 card, meaning it did not actually work properly with Windows. It was fine for Linux, which is what I ended up using for reasons stated above, but it is something to look out for. The Microsoft store has subsequently fixed that issue so any new orders will have the correct card.
  • Raspberry Enclosure – I wanted to make sure that the little computer was properly protected and looked good, so I decided to buy the official enclosure. There are plenty of different cases available for the Pi, but this is the “official” one with the proper logo.
  • Power Adapter – This is an important piece! It’s important to note that power is supplied to the Raspberry Pi via the ubiquitous micro-USB port. Most of us have tons of these just laying around. I wanted to make sure though that I had a proper adapter that supplied the full 2.5A that the Pi will demand.

Once I returned home and unpacked everything, it all looked like this:

 

20160418_175839687_iOS

Once assembled (a very simple process, just drop the computer onto the posts in the case bottom, and then snap the rest of the pieces together around it:

20160418_175940941_iOS

Once everything is assembled, you simply plug the SD card into the Pi, then attach a USB keyboard and mouse along with an HDMI cable to connect to the TV/monitor and you’re ready to go. You should also plug in a regular network cable if you can, it will give the setup utility the ability to download the latest OS.

20160418_181545787_iOS

There is no power switch on the Pi, so to boot it you simply plug the power adaper into your AC power.

Step Two – Boot and Configure

If you purchased a version of the Raspberry Pi with NOOBs included on the SD-card, you simply have to insert the SD card and boot. If not, you’ll need to first download a copy of the NOOBS installer and follow the instructions on how to set it up. It really is a simple process (you just format a new SD card and then copy the contents of the NOOBS archive onto the card), so nothing to be concerned about. Once the Pi boots, you’ll see the configuration page:

20160418_182055424_iOS

Once NOOBS has started and displayed the available OS images to install, make sure you select the appropriate region and keyboard settings at the bottom of the page, and then select the Raspbian image (should be the first one on the menu) and then select Install. This will start the installer (which will take about 10-15 minutes).

20160418_182209714_iOS

Once the installer completes, the Pi will reboot and then start Raspbian Linux and will then automatically login as the user “Pi”.

20160418_185014682_iOS

Once the Pi has restarted properly and Raspbian is up and running, you can configure the WiFi connection by clicking the network icon (upper-right of the screen, just to the left of the speaker icon) and joining an available WiFi network.

image

Once you are connected to the WiFi network, you’re ready to configure the remote access capabilities of the Pi, as well as changing the password of the Pi user.

Step Three – Configure for Remote Access

If you are a Windows-only person and haven’t spent much time using Linux, this is where things are going to get a little confusing. If you’re used to the Linux world, then most of what I put here is going to be extremely basic for you.

Linux was designed first and foremost to be a Server Operating System platform, and as such much of the work that you will do will be from a command line shell. The shell is accessed via the Terminal program, which is started by double-clicking on the icon (It looks like a monitor and is located to the right of the menu button in the GUI).

image

Once in the shell, execute the command (by the way, in Linux it’s important to note that case matters when typing commands. “Sudo” and “sudo” for example are not equal) sudo raspi-config which will start the configuration manager. The “sudo” command basically tells the OS that you want to execute the command as an administrator (“root” in linux terms).

image

Use the arrow keys to navigate to Advanced Options, and then select the SSH option. Enable the SSH Server. (SSH is the remote access tool used to enable a secure shell from one computer to another)

image

Once the SSH Server is enabled, you will also want to change the time zone (located in the “Internationalisation settings” as well as the password for the Pi user. You can select the finish option at this point and then type “exit” to exit the terminal program/ shell.

Note: There is a very good guide located here that explains how to enable the remote GUI access as well, along with instructions on how to obtain and download appropriate programs for Windows to access the Pi remotely. For me, I don’t use the GUI that often, but when I do I use a program called Ultra VNC Viewer which is very lightweight and simple. For my remote shell, I’m using the Insider Preview of Windows 10, which includes the Bash Shell. For those not in the insider program, you can use the PuTTY tool mentioned in the article or any remote SSH tool. For file transfer, I’ve found that FileZilla is probably the easiest to use.

Configuring SSH to use Certificate Authentication

I hate having to type passwords, and tend to do the extra up-front work to enable any remote machine that I’m working with to enable certificate authentication instead of passwords. If you don’t mind typing passwords, you can skip this section, but if you’re like me and hate typing the passwords, then start your preferred shell on the remote machine, and execute the ssh-keygen command. Do not enter a passphrase for the key. This will create a new key pair and install it into the ~/.ssh folder.

image

Once the key is generated, execute the ssh-copy-id command, using the IP address of the Raspberry Pi (either WiFi or Cabled, depending on which method you’re using to connect) as the destination and the user “pi” as the user. You will be prompted for the password of the Pi user, but after that you will not be prompted again.

image

Once this is done you are ready to test the ssh command to see if you can connect without password authentication. Type ssh pi@<ip address or name of remote machine> to connect:

image

Congrats! You now have a remote connection to the Raspberry Pi without using a password.

 

Step Four – Preparing the Development and Test Environment

Once remote access is configured and working, you are ready to prepare the Pi for Iot Development and testing. I am a big fan of Microsoft Visual Studio (which you can download for free)and since most of the development work that I do is related to the various demos and proof of concept projects that I build for customer presentations, I didn’t really want to learn a new environment to play with the Raspberry Pi, plus I thought that it would be an interesting test to continue to write code in C# on Windows, then deploy and execute that code on the Raspberry Pi. As you will see, this turns out to be an almost trivial task (for the simple applications, as later posts in this series will show, it does present some serious challenges as well).

The first step to enabling the execution of C# code on the Raspberry Pi is to download and install the Mono framework.  The Mono project is an open source implementation of the Microsoft .NET Framework that allows developers to easily build cross-platform applications. It is very easy to install on the Pi, and uses built-in linux commands to implement.

To install the Mono framework on the Raspberry Pi, first update all of the application repositories by using the apt-get update command. (remember to execute the command as root by using the sudo command)

image

Once the update is complete (depending on the version of Raspbian and the speed of your Internet connection, it can take as little as a minute or as long as 10 minutes) you can then install the complete Mono framework by executing the apt-get install mono-complete command. (again, don’t forget to run it as root by using the sudo command)

image

Once Mono is installed (This will likely take several minutes to complete) you are ready to develop and deploy your first simple application.

Step Five – Hello Raspberry Pi!

No “how to” article would be complete without a “Hello World” application, and I certainly don’t want to disappoint. To start, on your Windows PC, launch Visual Studio and create a new C# Windows Console Application. Title it “PiHelloWorld”.

image

Then in the Program.cs file, add the following code. Note that you are targeting any CPU and using the .NET 4.5 framework.

image

Then once you are happy with the code, select Build to build the application. Once the application builds without errors, copy the PiHelloWorld.exe file to the Raspberry Pi using a file transfer utility as discussed above. (I use FileZilla)

image

Once the file is copied, switch back to the Raspberry Pi and execute the code with the mono command. Remember that Linux is case-sensitive!

image

This will execute the application and prove that the app is actually running on Linux on the Pi, even though it was developed on Windows in C#.

Conclusion

This blog post details the start of a journey, and explains how to get a Raspberry Pi3 ready to develop and deploy IoT applications written in C#. Following posts in this series will explore some of the sensors available that can be connected to the expansion port of the Pi, and will also explain the process of connecting the Pi to Microsoft Azure and the Microsoft IoT Suite of tools available in Azure.