March 2015

Volume 30 Number 3


.NET Micro Framework - The Microsoft .NET Framework in Embedded Applications

By Colin Miller

The world has come a long way from the first context-­sensitive C code editor in the early 1980s. Tooling and languages developed initially for desktop apps have been extended to encompass server, cloud and other environments. The Microsoft .NET Framework and Visual Studio provide state-of-the-art tools that greatly increase programmer efficiency. The .NET Framework tools and languages provide rich libraries and collaboration tools, and protect programmers from the most common mistakes.

These advances have not, however, been made available to devel­opers working on embedded devices. The market for embedded tools has lacked the scale necessary to attract the kind of investments made in tools for PC, server and cloud applications. The emergence of “intelligent devices” of all descriptions is bringing about a change in this imbalance.

With the .NET Micro Framework, there has been a new stream of products, including small devices that used to require a different set of embedded skills to develop code. Instead these were developed by individuals and teams with .NET skills. If you’re a .NET developer and have thought about how to leverage small embedded devices in your applications, hopefully this article will convince you that you can use your skills to participate in the explosion of the Internet of Things (IoT) and intelligent devices.

Why should you care? One recent analysis estimated 94 percent of the processors expected to ship in 2017 won’t be of sufficient capacity to support a traditional .NET application environment. With the .NET Micro Framework, you can extend your reach.

The .NET Micro Framework was initially developed in the SPOT watch project. It has been part of the .NET family for the last seven years. It runs on 32-bit processors too small to support full OSes. It’s actually .NET running directly on the hardware with the execution engine and type system integrated into the executable image.

The goal of the .NET Micro Framework is to help .NET developers create an application that runs on a small 32-bit MCU-based device for embedded applications. At the Build conference in 2014, Microsoft described a range of OS platforms covering the IoT space with Windows Embedded Standard at the high end and the .NET Micro Framework for the small device end.

Embedded Development

Intelligent devices have local computing capability and can communicate with other devices and potentially the cloud. For this article, I’ve created a small mobile robot I can control from a smartphone running the Windows Phone OS. The objective is to show how .NET skills you use for the Windows Phone app are just as applicable on the robot side. The tools and language support are new in this environment, and the development environment for working back and forth between the two is seamless.

Meet Bert—Bert is a mobile robot with four powered wheels (see Figure 1). He includes a Netduino 2 board available for about $35 by Secret Labs. A simple controller lets you control the motors on each side of the robot to go forward and reverse. There’s no speed control, though.

Bert the Robot
Figure 1 Bert the Robot

For communication, Bert includes a Bluetooth module that communicates with the Netduino over a serial interface. To ensure you won’t crash Bert into anything or run him off a cliff, there are IR proximity sensors included in the front and rear. There are also headlights and turn signals just for fun.

The simple Windows Phone app is derived from a demo presented at the Build conference. It connects to the correct device and uses the onboard accelerometer to steer Bert around by sending commands over Bluetooth. You can see the interface in Figure 2, with the dropdown selection in Figure 3. Select Enumerate to pick the connected device to which you’ll send commands. The commands are reflected in the directional letters on the screen.             

Windows Phone App Interface
Figure 2 Windows Phone App Interface

Device Selection Dropdown
Figure 3 Device Selection Dropdown

You can port the .NET Micro Framework to another hardware platform with the .NET Micro Framework Porting Kit (bit.ly/1wp57qm). Use the kit to write the low-level interfaces to the specific hardware upon which you’re running. This is closer to classical embedded programming activities. The good news is vendors have already done this for you. The Netduino board used in this application is an example of having all you need to start coding to the board in the Netduino SDK (bit.ly/1CQygzz).

Netduino is a Cortex-M3 processor from STMicro, with 192KB to 384KB of Flash and 60KB to 100KB of RAM and is pin-compatible with Arduino shields. You can find other devices that support the .NET Micro Framework at GHI Electronics, Mountaineer, Sparkfun, Adafruit, Amazon and other stores.

The board is also open source hardware, so once you write your application and want to commercialize it, you have several options. You can just use the Netduino board for low-volume applications, but if you’re targeting a higher volume or have specific requirements such as wanting to integrate additional electronics on the same PCB, you can take the open source design files to a board manufacturer and go from there.

Because I started with the Netduino board, I installed the Netduino SDK. This includes the .NET Micro Framework SDK with Visual Studio templates and all the necessary library support. For other development boards, you might need to install the .NET Micro Framework SDK separately. The SDK comes with an emulator, so you don’t need to get any hardware to play with the .NET Micro Framework, although using hardware is more productive if you already know what sensors you want to use.

Create the Embedded Application

After you install the Netduino SDK (which contains the .NET Micro Framework SDK), starting a .NET Micro Framework embedded application is just like starting any other project within Visual Studio. You select New Project and the type of application you want to start. As shown in Figure 4, I’ve selected a Netduino 2 Application to match the board on Bert.

Start a .NET Micro Framework Embedded Application
Figure 4 Start a .NET Micro Framework Embedded Application

Once you’ve started the project, you can jump right into creating the communication link between the robot and the phone. 

Like many embedded applications, Bert runs on batteries. This means your code has to be written to conserve power usage. The good news is the .NET Framework and the .NET Micro Framework are perfectly suited for that. If there’s no thread to run, the .NET Micro Framework can automatically put the processor into a lower power state. It’s also becoming common to add a second efficient processor to monitor the interrupts and put the main processor into an even lower power state. You’ll soon see if the .NET Framework is well-suited for addressing this type of programming.

The code in this application runs in response to an external event and then only what’s needed to respond. So you’ll see all execution resides in an event handler or in a thread that’s suspended most of the time, like so:

public class Program
  {
    public static void Main()
    {
      RunRobot myRunRobot = new RunRobot();
      myRunRobot.Start();
      while (true)
      {
        Thread.Sleep(Timeout.Infinite);
      }
    }
  }

The RunRobot constructor initializes the IO instances that I’ll look at in more detail and the RunRobot.Start method initializes the interrupts that trigger the actual execution:

public void Start()
  {
  // Enable interrupts on BT input on the HC-06 radio
  hc06.DataReceived += hc06_DataReceived;
  // Use onboard button to turn on/off accepting commands
  button = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled,
    Port.InterruptMode.InterruptEdgeHigh);
  // Start monitoring for button presses
  button.OnInterrupt += new NativeEventHandler(button_OnInterrupt);
  }

Get Bluetooth Working 

There are three steps to getting the Bluetooth communication working between Bert and the Windows Phone app:

  1. Wire up the Bluetooth module on the robot
  2. Send commands from the phone app
  3. Receive those commands on Bert 

Because the Netduino is Arduino-compatible, for many of the connections, you might be able to find a shield you can plug in that makes all the necessary connections for you. The Arduino is a popular hobbyist platform that has a rich ecosystem of peripherals. You can craft a broad range of solutions from existing modules.

If you don’t want to spend time with wiring, look into the Gadgeteer products from GHI Electronics. With these boards and components, you can use a wizard to decide where to plug the components into standard connections (see Figure 5), so you don’t need any knowledge of wiring connections. The module interfaces are at a similarly high level. Like Arduino, Gadgeteer has a rich set of existing modules with which to create your solution. Once you have the modules connected, you’re still coding in the .NET Micro Framework. This is particularly useful for rapidly prototyping your ideas.

The Gadgeteer Wizard Showing Connections
Figure 5 The Gadgeteer Wizard Showing Connections

In the case of Bert, I’m not using Gadgeteer, but collecting my own modules.  The Bluetooth module (HC-06) uses a serial interface with four connections—VIN, GND, RX and TX. Connect the VIN (Voltage In) to either the 5V or 3.3V outputs from the Netduino, then connect GND to one of the GND connections. Looking at the I/O table for the Netduino in Figure 6, you’ll see to connect the BT module RX (Receive) to the Netduino TX (Transmit) and the BT Module TX to the Netduino RX of the COM1 serial port. If needed, there are a number of examples of connecting these modules to common microcontrollers on the Web.

Netduino IO Pins Defined
Figure 6 Netduino IO Pins Defined

With those connections made, you can power up the Netduino (which powers the BT module) and pair the device with the phone. The default name for the BT module is HC-06, so you can pair with that. I changed the name to Bert using AT commands. Send an array of bytes with the characters “AT+NAMEBert” to change the name of the BT module. You can also use this interface to configure the Bluetooth module, including things like the communication baud rate.

Now you can use the phone to connect to Bert as you would any other BT device and start sending commands. First, I access the onboard accelerometer and set up a reasonable reporting interval, so as not to swamp poor Bert:

accelerometer = Accelerometer.GetDefault();
if (accelerometer != null)
{
  uint minReportInterval = accelerometer.MinimumReportInterval;
  desiredReportInterval = minReportInterval > 250 ? minReportInterval : 250; 
    // Slowing this way down to prevent flooding with commands
  accelerometer.ReportInterval = desiredReportInterval;
    // Add event for accelerometer readings
  accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer,
    AccelerometerReadingChangedEventArgs>(ReadingChanged);
}

The ReadingChanged event handler sends commands, as shown in Figure 7.

Figure 7 The Event Handler for Sending Commands to Bert

AccelerometerReading reading = args.Reading;
if (reading.AccelerationX > .4)  // These are arbitrary levels
                                 // set to what seemed easy
{
                        // Send Right
  if( cmdSent != 'R')   // Don’t resend the same command over and over
  {
      // Update the phone display
    txtRight.Text = "On";
    txtLeft.Text = " L";
    txtForward.Text = " F";
    txtBack.Text = " B";
      // Send the command
    packet = Encoding.UTF8.GetBytes("R");
    cmdSent = 'R';
    SendData(packet);
  }

Receive and Execute Commands   

Now you can consider receiving a command on the robot side. The BT module is wired to the first serial port on the Netduino. Create a SerialPort instance and a message buffer, just as you would on other versions of the .NET Framework:

SerialPort hc06;                 // The BT radio
byte[] cmdBuffer = new byte[32]; // The input buffer for receiving commands

Then configure the serial port for communication with the Bluetooth module (9600 baud is the default; I could reset this using AT commands, but this will be a very sparse communication to simplify the program, so faster speeds are unnecessary): 

// Set up the Bluetooth radio communication
hc06 = new SerialPort(SerialPorts.COM1, 9600, 
  Parity.None, 8, StopBits.One);
hc06.ReadTimeout = 1000;
hc06.Open();

Then I set up a DataReceived event handler that triggers most of the processing within the app. In other words, Bert sleeps until he receives a command. The processor stays up long enough to set the motors in the right state and goes back to sleep: 

// Enable interrupts on BT input
hc06.DataReceived += hc06_DataReceived;

Incoming commands are processed in the event handler, as shown in Figure 8.

Figure 8 The Inbound Commands to Start Bert Moving

do
{
  try
  {
    count = hc06.Read(cmdBuffer, 0, 1);  // Should read one byte at a time
  }
  catch (Exception) { }        // Just eat exceptions
  if (count > 0)
  {
    cmd = (char)cmdBuffer[0];
    executeCmd(cmd);   // Execute command immediately
  }
} while (count > 0);

None of that code is any different than what you would write on the desktop.

Set Bert in Motion 

The motor controller I use simply requires me to set four inputs in some logical state to determine how the wheels turn. The logic is:

/*        
A2  A1  Motor 1         B2  B1  Motor 2
0   0   Shaft locked    0   0   Shaft locked
0   1   Clockwise       0   1   Clockwise
1   0   Anti-clockwise  1   0   Anti-clockwise
1   1   Shaft locked    1   1   Shaft locked 
*/

To write to these, I create an OutputPort and tie it to one of the Netduino digital pins shown in Figure 6. OutputPort is a unique class in the .NET Framework because devices that run the full .NET Framework typically can’t address individual digital I/O ports. There are a handful of new classes in the .NET Micro Framework to handle the additional I/O types and other issues unique to this application space like power management:

// Motor controller output
A1 = new OutputPort(Pins.GPIO_PIN_D2, false);  
  // A is the left tires when viewed from the front
A2 = new OutputPort(Pins.GPIO_PIN_D3, false);
B1 = new OutputPort(Pins.GPIO_PIN_D4, false);  
  // B is the right tires when viewed from the front
B2 = new OutputPort(Pins.GPIO_PIN_D5, false);
Setting them is as simple as writing true or false:
switch (cmd)
{
  case 'F':
  {
    Debug.Print("Forward");
    A1.Write(false);   // Left forward = false/true
    A2.Write(true);
    B1.Write(true);    // Right forward = true/false
    B2.Write(false);
    break;
  }

Drive Carefully

I don’t want Bert to run into things for his own sake and for the safety of things and people around him, so I installed InfraRed proximity sensors from Sharp in the front and back. These sensors return a value from 0.0 to 1.0 depending on the distance to the nearest object that reflects the projected IR light.

The front sensor is pointed diagonally down sensing the ground about 18 inches in front of Bert. This lets me use one sensor to detect objects, as well as the ground falling away if it’s approaching a set of stairs, for example. The values these sensors return are analog, which means I create an instance of another class unique in the .NET Framework to the .NET Micro Framework—the AnalogInput class:

AnalogInput foreRange;    // Forward range finder input
AnalogInput backRange;    // Rear range finder input
// Set up range finder for collision and edge avoidance
foreRange = new AnalogInput(Cpu.AnalogChannel.ANALOG_5, 100, 0, -1);
backRange = new AnalogInput(Cpu.AnalogChannel.ANALOG_4, 100, 0, -1);

This constructor identifies the specific analog port to which I’m connecting, a multiplier I can use to convert the output to a more convenient range, an offset to modify the output for convenience and the precision of the output with -1 meaning maximum precision. To make these measurements periodically and let the processor sleep as much as possible, the readings are triggered by a timer. I set this when I start accepting commands from the phone and dispose of it when I’m not:

// Start timer for rangeFinders
Timer rangeReader = new Timer(new TimerCallback(rangeTimerHandler), 
  null, 0, 100);

General Purpose Interrupt 

The last new class I need to introduce is the InterruptPort class. This lets me monitor changes in digital input and triggers on changes like the leading edge of a change from Low to High, for example. I’m using this for the button on the Netduino board that gets Bert to respond to commands from the phone. This means he ignores commands until this button is pressed and ignores them after pressing it again:

// Use onboard button to turn on/off accepting commands
button = new InterruptPort(Pins.ONBOARD_SW1, false,
  Port.ResistorMode.Disabled,
  Port.InterruptMode.InterruptEdgeHigh);

Pins.ONBOARD_SW1 is the internal connection for the switch on the Netduino board. You can connect a switch to any of the digital ports listed in Figure 6. The second argument is whether I need a glitch filter applied to this switch input to avoid multiple triggers for a single button press.

The next parameter is whether there’s a pull up or pull down resistor on the switch. This defines the default port position when the button isn’t pressed (High or Low). The next parameter is set to trigger the interrupt on the transition back to High so your finger is out of the way if Bert takes off immediately. With the InterruptPort instance created, I can assign the interrupt handler:

// Start monitoring for button presses
button.OnInterrupt += new NativeEventHandler(button_OnInterrupt);

The interrupt handler starts Bert monitoring any commands coming from the phone, as you can see in Figure 9.

Figure 9 Interrupt Handler Activating Command Monitoring

private void button_OnInterrupt(uint data1, uint data2, DateTime time)
{
  cmdListenState = !cmdListenState;
  if (cmdListenState)
  {
    // Set up timer for rangeFinders
    rangeReader = new Timer(new TimerCallback(rangeTimerHandler), 
      null, 0, 100);
  }
  else
  {
    rangeReader.Dispose(); // Drop the timer because Bert isn't processing
                          // commands so he shouldn't be moving
  }
  led.Write(cmdListenState);  // The onboard LED indicates whether
                               // Bert is accepting commands
}

Embedded Applications and the .NET Micro Framework

Embedded applications typically perform a targeted set of functions on hardware crafted to meet the minimum requirements. Crafting targeted and tuned embedded applications requires a higher initial investment. That investment is recouped over a longer product lifecycle.

One of the biggest challenges for traditional embedded development is the time it takes to complete projects. A large proportion of embed­­ded projects are abandoned because the cost becomes too large or the requirements change before the projects can get to market.

A number of things are affecting the dynamics of embedded appli­cations. When Microsoft first released the .NET Micro Framework seven years ago, most embedded applications were built on 8-bit processors to reduce cost, achieve needed performance requirements and meet power requirements (the ability to run on a battery for extended periods, for example). 

At the same time, most of the growth in the embedded space targeted 32-bit processors like the ARM7. These processors were continuing to come down in price and offered adequate performance for many applications and power consumption was improving. The newer Cortex processors are continuing to attract many new embedded applications to the 32-bit family.

Recently, there have been more devices that are integral parts of broader applications, including embedded devices, gateways, cloud connectivity, databases, business intelligence applications and so on. These new applications change the economics of embedded applications. 

It becomes more important to adhere to common communication protocols. More of these new devices are in the consumer realm, so expecting long development cycles means increased product risks. Time to market is even more important for these applications and during the coming explosion of “intelligent devices.”

The other impact of these new types of applications is their breadth alone. They potentially bring together the desktop developer and his expertise in high-scale communications, databases and business analytics, and cloud protocols with the embedded developer and her expertise in hardware and low-level programming. The tools and languages help same-skill sets to work across the entire applications for more efficient projects.

This was the background for which the .NET Micro Framework was developed. The beginnings of this platform were created as internal tools for developing Microsoft SPOT watch applications (only nine years ahead of the market). When the platform became useful for other internal projects, the product was rounded out as a general platform in 2007.

The embedded application drivers of cost, performance and power efficiency haven’t gone away. If anything, when you’re talking about applications where you want to deploy thousands of sensors in a building, cost becomes even more critical. Performance and power requirements vary with the application, as well. Continuing to improve the range of applications that can be reached with the .NET Micro Framework is an ongoing area of focus for Microsoft development efforts.

Deploy and Debug 

Deploying code to your device is as easy as connecting it and pressing F5, just as with the Windows Phone app. However, the setup is a little different. In the Project | Properties dialog, there’s a .NET Micro Framework tab where you can specify the transport (USB, serial or TCP/IP) and identify the device. The default is USB. It will automatically identify a .NET Micro Framework device, so unless you’re connected to several devices, you may never need to be in this dialog box. At this point, the solution is built and the assemblies deployed to the device. You can follow all this in the Output window in Visual Studio. Execution starts immediately and you can start debugging the code running on the device.

You can also deploy the app to an emulator running on a desktop PC. The difference is Windows Phone has a comparatively limited number of permutations, so you can select the closest emulator from a set provided in Visual Studio. For the .NET Micro Framework, there’s a generic Microsoft emulator. You’ll most likely have to create your own emulator to match your hardware. This is definitely worth looking into if you want to start coding before your hardware is available.

In the past, the scenario for debugging the communication between the robot and the Windows Phone app might have been done with a JTAG debugger. This is separate from the development environment and foreign to a .NET developer, so you might have one developer monitoring what’s happening on the phone and one monitoring (in separate tools) what’s happening on the embedded device. You can monitor both simultaneously in Visual Studio. You can step through the phone code and break in on command transmission, then step into what happens to that command on Bert.

Wrapping Up

The full picture of how to create any significant embedded application on the .NET Micro Framework would take an entire book. The objective of this article was to demonstrate the learning curve isn’t very steep to use your .NET skills for embedded applications and the .NET Micro Framework. 

This project requires a few classes that aren’t part of the full .NET libraries. There will also be some things you’re familiar with on the full .NET Framework that you couldn’t squeeze into the .NET Micro Framework, but the Visual Studio environment is completely supported with IntelliSense, breakpoints, watch points, call stack, and whatever else you’re used to. There are embedded applications out there for which the .NET Micro Framework isn’t the right solution. For many, though, it works quite well. Efforts continue to broaden the applicability of the platform to larger segments of this growing and increasingly critical part of computer science.

So now you’re ready to try a small project as an embedded programmer.

See Bert in Action

 Now you know how to put your development skills to good use for something fun. You’ve developed an app with which you can control a small robot using a smartphone running the Windows Phone OS. The .NET skills you used to develop the Windows Phone app are equally applicable for the robot. Working back and forth between the two is seamless. Your work is done—it’s time to see Bert in action: youtu.be/ypuqTju2w4c.


Colin Miller is a principal program manager on the Internet of Things team at Microsoft. Reach him at colin.miller@microsoft.com. He’s been at Microsoft for 20 years, and has worked on the Internet of Things, Embedded, Developer Tools, Research, MSN, Internet Explorer, Word and other projects.

Thanks to the following Microsoft technical expert for reviewing this article: Lorenzo Tessiore