Pinterest Stumbleupon Whatsapp
Ads by Google

Microsoft is going all in for Windows 10, finally realizing the dream of having apps that run cross-platform. Combined with official support for Arduino, you have a powerful new tool at your disposal: the ability to easily create universal Windows apps that have a hardware connection to the real world.

Here’s how to get started, even if you’ve never programmed a Windows app before.

Before you read on, check out the demo of what we’re going to make.

I should note, I haven’t used Visual Studio, or even touched C#, since about 10 years ago. I’m coming at this from the perspective of a fresh Visual Studio install, and having forgotten everything I know.

If you’re already quite experienced with Windows app programming, or even looking for a simple way to get started with programming in Windows without this Arduino stuff, try Ryan’s guide to making a simple Visual Basic app How You Can Make Your Own Simple App With VBA How You Can Make Your Own Simple App With VBA For those of you that would really love to be able to write your own application, but have never typed a single line of code before, I'm going to walk you through making your very... Read More . Absolute programming beginners may want to check out my Programming 101 The Basics Of Computer Programming 101 - Variables And DataTypes The Basics Of Computer Programming 101 - Variables And DataTypes Having introduced and talked a little about Object Oriented Programming before and where its namesake comes from, I thought it's time we go through the absolute basics of programming in a non-language specific way. This... Read More  (and part 2 The Absolute Basics Of Programming For Beginners (Part 2) The Absolute Basics Of Programming For Beginners (Part 2) In part 2 of our absolute beginners guide to programming, I'll be covering the basics of functions, return values, loops and conditionals. Make sure you’ve read part 1 before tackling this, where I explained the... Read More ) article first.

Ads by Google

You should be familiar with some beginner’s Arduino projects 10 Great Arduino Projects for Beginners 10 Great Arduino Projects for Beginners Completing an Arduino project gives you a sense of satisfaction like no other. Most beginners aren't sure where to start though, and even beginner's projects can seem rather daunting. Read More (and maybe even read our Arduino Guide Getting Started With Arduino: A Beginner's Guide Getting Started With Arduino: A Beginner's Guide Arduino is an open-source electronics prototyping platform based on flexible, easy-to use hardware and software. It's intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments. Read More ), but this will probably be the first time you’ve tried creating a real bit of computer software to interact with it.

Downloads

First: you need to join the Windows Insider Program to get the latest preview edition of Visual Studio 2015, and the latest build of Windows 10 Preview. Do that now – it’s free. Windows 10 is a developer preview, and should not be installed as your main operating system. It’s buggy as hell.

Visual Studio is Microsoft’s own development environment that we’ll be using to create a C# Windows application.

Why C#? With strong similarities to Java, it’s a relatively easy programming language for beginners to get a working app up and running, yet powerful enough that you can go on to create some stunning applications (even games: C# is the Unity scripting language of choice – check out our free eBook, Beginner’s Guide to Programming a Game with Unity Programming A Game With Unity: A Beginner's Guide Programming A Game With Unity: A Beginner's Guide In the evolving landscape of indie game development, Unity has emerged as something of a de-facto standard: its low cost, ease of use, and broad feature set make it ideal for rapid game development. Read More ).

If you haven’t already, download the Arduino IDE from the official Arduino.cc site, and install the standard firmata onto the board. You’ll find it under Examples -> Firmata -> Standard Firmata. This just turns it into a “dumb” serial device, which will do whatever our app tells it to – there will be no app logic on the board itself, just an interface between our app, and any sensors or output devices connected to the Arduino.

In terms of wiring, you can either stick an LED directly to pin 13 and GND as below, or use the onboard LED. You’ll also need a variable resistor (I’ve used a 10k linear potentiometer) going into A0 (with the appropriate legs on GND and +5v too, obviously).

arduino-windows10-demo

Finally, download the Remote Wiring package from GitHub. This is the layer we need to add that will enable our Windows app to talk to the Arduino.

Create an Application

Go ahead and open up Visual Studio. If this is the first time you’ve run it, you’ll be given the option to sign in. Ignore that if you like. Choose Visual C# as the development option and continue; either way, it takes a few minutes to prepare Visual Studio for first use.

Create a new project, using the template Visual C# -> Blank App (Windows Universal). I called mine “Arduino Test”, but it doesn’t matter.

new c sharp universal windows app

At this point, I encountered an error about having to switch Windows 10 into developer mode if I wanted to actually run the app. Go ahead and do this, though if you find your build of Windows 10 is crashing on that setting, it’s a known bug and you’ll need to use the group policy editor to enable developer mode.

Next, right click anywhere in the Solution Explorer (that’s the thing on right) and select Add -> Existing Project.

solution explorer add projects

Navigate to where you downloaded the Remote Wiring files from Github – if it’s been unzipped, it should be a folder called remote-wiring-develop. Inside there you’ll find Microsoft.Maker.win10; and inside of that you’ll find another 3 folders. In turn, add each one by navigating inside those three folders and finding the project file.

If you receive any errors about “XAML 8.2 file not found”, you have the wrong version of Visual Studio or don’t have the developer tools installed yet. Go back to the start of this article and ensure you’ve downloaded and installed both of the linked Visual Studio files.

These 3 projects you’ve just added are just different layers of the Arduino interface. From the solution explorer, if you right click and select Dependencies -> Build Dependencies, you can see which layers depend upon which (Serial doesn’t depend on anything; Firmata depends on Serial; RemoteWiring depends on both). The only change you need to make here is to select your project from the drop down, and check each box to indicate that your project depends on all these other projects.

check dependencies

One last step: from the solution explorer again, right click on the References item under your project, and select Add Reference. From the left, navigate to Windows Universal, then tick the box next to Microsoft Visual C++ AppLocal Runtime Package. Don’t close the dialog yet.

project references

Next navigate to Projects (also on the same dialog box, from the list on the left), and check the box next to each of the three Microsoft.Maker projects.

maker references

That was harder than it ought to be, but you only need to do it once; now we can have some fun with the programming – I promise it’s not that scary.

Programming

If you have trouble following along, the full code is available on Pastebin. I strongly suggest reading through the notes below anyway though, so I can explain what the code actually does.

First, we need add a bit of code that says we need a USB port to communicate with the Arduino. Find the Package.appxmanifest file from the solution explorer, and double click to edit it. We need to paste some code into here – technically, we will be “inserting a child node” because it’s an XML file, but just replace the entire <Capabilities> section with the code below so it looks like this: 

capabilities

The exact code will vary if you’re using Bluetooth, or if you’re targeting Win8.1 instead of 10, but the following is for a Windows 10, USB connection.

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

Go to the Build menu -> Rebuild Solution, and make sure you don’t get any errors.

From the solutions explorer, expand the MainPage.xaml node. Double clicking on that will load the form designer which we’ll come back to later, but for now open up MainPage.xaml.cs, which contains the main logic behind our application.

Add two lines in the first section, to indicate we’ll be “using” the Arduino bits.

using Microsoft.Maker.serial;
using Microsoft.Maker.RemoteWiring;

I also added a line to say we’ll be using System.Diagnostics; which enables us to use the Debug.WriteLine() function to output debug messages to the IDE.

First off, let’s define a few variables we’ll be using throughout. Add these lines just before the public MainPage() function declaration.

UsbSerial connection;
RemoteDevice arduino;
UInt16 lastvalue;

Next, jump into the MainPage() function – this is called the constructor, and it’s a function that gets called immediately when our app is created, so we use it to set everything up.

First, add a line to establish the USB serial connection to a specific USB device (the Arduino).

connection =new UsbSerial("VID_2341", "PID_0043");

Notice that the USB IDs of a standard Arduino Uno are coded into the block already, but you can verify this from Device Manager -> Ports (COM and LPT) -> Arduino Uno -> Details tab -> Hardware IDs.

check usb hid pid

Then add the following lines just after that.

arduino = new RemoteDevice(connection);
connection.ConnectionEstablished += OnConnectionEstablished;
connection.begin(57600, SerialConfig.SERIAL_8N1);

A few things are happening here. First, we’re creating a RemoteDevice object – remember, that’s the layer that gives us a bunch of Arduino commands – and giving it the variable name “arduino”. The next line is attaching to the ConnectionEstablished event, to say “once the USB connection has successfully been established, please run the function called OnConnectionEstablish()”. 

The final just tells the connection to start already, at a baud rate of 57600, using the 8N1 bit pattern.

You’ll also need to create that OnConnectionEstablished() function now, so move outside the MainPage() function and just make a blank function as follows.

private void OnConnectionEstablished()
{
// LOGIC HERE
}

Jump back to the form designer I mentioned earlier (if you’ve forgotten how: double click on MainPage.xaml from the solution explorer). Create two buttons. To do this, open up the Toolbox tab that you’ll find pinned vertically on the left side of the screen. Drag two buttons onto the page, then label one On and one Off.

form designer add buttons

Select the first button, then from the Properties box in the bottom right, name it  “OnButton”. Click the small lightning icon – this is the events and actions list which used to specify what happens when form elements are interacted with. Type “OnButtonClick” into the Click field.

When you press enter, it’ll automatically create the code for that particular button event and load the standard code view. Switch back to the form designer for now and do the same for the Off button, but this time call it “OffButton”, and “OffButtonClick”. While you’re there, go ahead and name the main window form behind it as “Page” – we’ll use that later. You should now have something resembling the screenshot below:

designer creates events

Switch back to the designer again for a moment, and again for each of the buttons, set the isEnabled property to False. You either do this by typing the property directly into the XAML code view, or you can find that checkbox in the Properties box (click the spanner if you’re still on the actions view) – it’s under the expanded Common category of properties.

This isn’t essential, but it’s good practice to disable the buttons until we’re sure the Arduino is plugged in and connected.

To re-enable them, add the following to the OnConnectionEstablished() function. Don’t worry too much about the exact meaning of the code for now, it’s just the way you’re supposed to handle form updates in modern Windows apps to ensure good performance. Once we’ve connected to the Arduino, we set the IsEnabled property of the buttons to true.

private void OnConnectionEstablished()
 {
 // enable the on off buttons
 var action = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => {
 OnButton.IsEnabled = true;
 OffButton.IsEnabled = true;
 }));
 arduino.pinMode(14, PinMode.ANALOG);
 arduino.AnalogPinUpdatedEvent += MyAnalogPinUpdateCallback;
 Debug.WriteLine(arduino.analogRead(14));
 }

You’ll also see a more familiar pinMode() statement, to say we have an analog input on pin 14 (there are 13 digital pins, so A0 start counting from 14). Then we’ve got another event declaration – when the analog pin value updates, call the function MyAnalogPinUpdateCallback.

Finally, we need to edit the button click events and decide what happens when the analog input changes. Let’s start with the buttons. We can interact with the Arduino using similar function names as regular Arduino code, as follows:

arduino.digitalWrite(13, PinState.HIGH);

Paste that for the onButton event, and this for the offButton:

arduino.digitalWrite(13, PinState.LOW);

Simple. The analog input from the Arduino is a little trickier, but here’s what I came up with.

public void MyAnalogPinUpdateCallback(byte pin, UInt16 value)
 {
 if(value-lastvalue >5 || lastvalue-value > 5){
Debug.WriteLine("Pin A" + pin + " is now " + value);
 var action = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => {
 byte num = Convert.ToByte(value / 4);
 Page.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, num, num, Convert.ToByte(255 -num)));
 }));
 }
 lastvalue = value;
 }

Note that I’m storing the previous value we received from the pin in a variable called lastValue; this enables us to check how much the value is changed, and only react if the difference is significant (a kind of signal smoothing). If it changes in either direction more than 5 (0-1024 is the full range of values), then we react by changing the RGB background color value of the Page element.

Since we only have one number to work with, and I was in a rush, I fudged things a bit here with the 3 numbers required to make R, G, and B. You can probably come up with something a lot prettier.

Finished

arduino windows 10 completed

That’s it – run the code, and you should see something similar to the screenshot above. The buttons will turn the LED on and off, and the variable resistor will change the background. If you had trouble, don’t forget the full code is here.

Now that you can write your own Windows 10 apps that interact with Arduino, what will you make? Perhaps a home automation controller Home Automation with Raspberry Pi and Arduino Home Automation with Raspberry Pi and Arduino The home automation market is flooded with expensive consumer systems, incompatible with one another and costly to install. If you have a Raspberry Pi and an Arduino, you can basically achieve the same thing at... Read More ? Let me know in the comments.

  1. Sam
    January 6, 2016 at 3:16 pm

    Hi James,

    I am also using VStudio 2015 Community Edition and having a few issues. There are quite a few differences between the two VStudio versions. Would it be possible for you to update and retest your codes?

    Thanks,
    Sam

  2. Ashok
    December 27, 2015 at 2:35 pm

    I am using visual studio 2015 community RC with update 1 and latest windows 10 pro..
    while using the code i get an error..
    i added the three solutions
    Microsoft.maker.Firmata
    Microsoft.maker.Serial
    Microsoft.maker.RemoteWring

    Error CS0234 The type or namespace name 'Maker' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) App1

  3. Christophe de Mey
    August 14, 2015 at 8:25 am

    Hi James

    Thanks for the tip, i usually use Mega's but they're all in use :-).
    I asked a colleague to lend me his UNO, will let you know if it works then.

  4. Christophe de Mey
    August 12, 2015 at 7:50 pm

    Thanks for the tip, but unfortunatly it didnt fix the problem.

    When i use standardFirmata which uses Serial and i launch the .NET app the RX on the board starts blinking for a while and then stops, this indicates to me that the app is trying to communicate with the board, but no TX is sent so it eventually stops trying.

    When i use Serial1, there is nothing , not even RX blinking on application boot.
    I also cant get the standard firmata test app to work.

    The OnConnectionEstablished event also is raised indicating a succesfull SerialPort.Open.

    Got anymore idea's ?

    Thanks!

  5. Christophe de Mey
    August 12, 2015 at 7:29 pm

    Hi

    I have an arduino Yun and i cant get it to work.
    There are no exceptions, so i dont have a clue.

    - I was required to make 2 changes to the tutorial :

    In void OnConnectionEstablished
    arduino.AnalogPinUpdated += MyAnalogPinUpdateCallback;

    In void MyAnalogPinUpdateCallback
    this.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, num, num, Convert.ToByte(255 - num)));

    Can i send you my solution so you can check if its working with your UNO?

    Thanks!

    • James Bruce
      August 12, 2015 at 7:35 pm

      I'm afraid I downgraded back to Windows 8.1 due to Oculus Rift incompatibilities, but did you check this: https://ms-iot.github.io/content/en-US/win10/SetupWRA.htm - Yun uses "Serial1" rather than "Serial", so that might be why you're just not getting it to work, there's technically no code error.

      • Christophe de Mey
        August 12, 2015 at 8:00 pm

        Thanks for the tip, but unfortunatly it didnt fix the problem.

        When i use standardFirmata which uses Serial and i launch the .NET app the RX on the board starts blinking for a while and then stops, this indicates to me that the app is trying to communicate with the board, but no TX is sent so it eventually stops trying.

        When i use Serial1, there is nothing , not even RX blinking on application boot.
        I also cant get the standard firmata test app to work.

        The OnConnectionEstablished event also is raised indicating a succesfull SerialPort.Open.

        Got anymore idea’s ?

        Thanks!

        • James Bruce
          August 13, 2015 at 8:56 am

          Sorry Christophe, I'd suggest posting to their Github issues trackers for specific help with that board. Generally I advise people to stay away from the Yun as it's not really like any other Arduino hardware, so a lot of libraries tend to be incompatible. I'd suggest buying a cheap $5 Uno clone for working with Windows 10, and keep the Yun for more advanced projects - you'd be wasting it's processor and features with the standard firmata, I think.

        • Christophe de Mey
          August 14, 2015 at 8:26 am

          Hi James

          Thanks for the tip, i usually use Mega’s but they’re all in use :-).
          I asked a colleague to lend me his UNO, will let you know if it works then.

        • Christophe de Mey
          August 15, 2015 at 2:27 pm

          Hi James

          I got my hands on an Arduino Micro and an Arduino Uno.
          Suprise suprise! The uno works fine!
          When i load same sketch (standardFirmata) to Micro and Yun, it doesnt work.
          I will do a test with a Mega also and let you know.

        • James Bruce
          August 15, 2015 at 3:18 pm

          Glad to hear it, though it's frustrating it isn't mentioned anywhere official.

Leave a Reply

Your email address will not be published. Required fields are marked *