Jeroen Swart

.NET Architect

Netduino - Getting Started with switches

After getting the blinking LED, the next thing to do is experiment with a switch. Besides an on-board LED, the Netduino also comes with an on-board switch, so we can work without extra components.

There are two ways to use a digital input-port. As an InputPort, which requires us to constantly check for an input-value ourselves, or as an InterruptPort, which will provide an event when the value changes. I will show code for each.

For this example, the program will turn the LED on when the button is pressed. When using the on-board switch, the program may look like this:

public class Program
{
    public static void Main()
    {
        // initialize the onboard LED
        OutputPort ledPort = new OutputPort(Pins.ONBOARD_LED, false);
        // initialize the onboard switch
        InputPort switchPort = new InputPort(Pins.ONBOARD_SW1, false,
                                             Port.ResistorMode.Disabled);

        // do forever...
        while (true)
        {
            // turn the LED on
            //, if the switch is pressed (== false, because switch is inverted)
            ledPort.Write(switchPort.Read() == false);
        }
    }
}

After the output port for the LED is created as in the blink example, the input port is created for the on-board switch. In this case the glitch-filter is turned off, since bouncing of the switch contacts is not an issue here. The pull-up resistor inside the port of the MCU is disabled, since the on-board switch already has a pull-up resistor. More on this later. Important note: since the switch has a pull-up resistor, the value on the port is low/false when the switch is pressed; the value is high/true when it is released.

Using an InputPort, as shown above, the code is required to regularly read the input port to check if the switch has been pressed and act accordingly. An easier way is to use an InterruptPort, as shown below.

public class Program
{
    // initialize the onboard LED
    private static OutputPort ledPort = new OutputPort(Pins.ONBOARD_LED, false);
 
    public static void Main()
    {
        // initialize the onboard switch
        InterruptPort switchPort = new InterruptPort(Pins.ONBOARD_SW1, false,
                                                     Port.ResistorMode.Disabled,
                                                     Port.InterruptMode.InterruptEdgeBoth);
        // add an event-handler for the switch
        switchPort.OnInterrupt += new NativeEventHandler(switchPort_OnInterrupt);
 
        // wait forever...
        Thread.Sleep(Timeout.Infinite);
    }
 
    ///
    /// Event handler for the onboard switch.
    ///
    ///The port for which the event occurs.
    ///The state of the switch.
    ///Time of the event.
    private static void switchPort_OnInterrupt(uint port, uint data, DateTime time)
    {
        // turn the LED on, if the button is pressed (== 0, because switch is inverted)
        ledPort.Write(data == 0);
    }
}

In this version, an InterruptPort is created for the on-board switch, again with the glitch filter and the internal resistor disabled. The interrupt mode is set to both edges, meaning that an event is raised when the value on the port changes from low to high and when it changes from high to low. This allows us to respond when the switch is pressed and when it is released. In both cases, the OnInterrupt event is raised, for which a handler is registered. The handler turns the LED on or off depending on whether the switch is pressed or released.

In this example, the program enters sleep-mode as soon as the initialization of the ports is done. When an event is raised, the program wakes up, the handler is called and goes back to sleep again.

If you want to use your own switch, there are several ways to connect a switch to the Netduino (or a MCU in general), but a common way is shown in the schematic below.

As with the LED, you need to combine the switch with a resistor. Not only to restrict the current, but also to prevent a shortcut when the button is pressed. As with the on-board switch, because a pull-up resistor is used, the value at the port is high when the button is not pressed, and the value is low while the button is pressed.

You can connect the switch & resistor to any of the available ports A0-5 or D0-D13 , as long as you change the first argument of the InputPort or InterruptPort constructor to correspond with the selected port. E.g. when connected to the D0 port, the port should be constructed as follows:

InterruptPort switchPort = new InterruptPort(Pins.GPIO_PIN_D0, false,
                                             Port.ResistorMode.Disabled,
                                             Port.InterruptMode.InterruptEdgeBoth); 

Next: getting started with transistors.

Netduino - Getting Started

Last week I finally received my Netduino, after it had spent almost a week at customs :-(. I didn’t have much time last weekend, but luckily it doesn’t take much time to get started with the Netduino.

I also ordered a breadboard shield and a motor shield. The breadboard shield is very handy for experimenting small projects, but a separate breadboard is even better. And with some wiring you can use them together, of course.

How to install, connect, start coding, deploy and debug your Netduino projects is very well described in this document on the Netduino website. So there is no point in repeating that here. One tip though: use a separate solution for each project. You can add libraries to the solution of course. I started with a single solution with several projects, each representing a different hardware project. Even though I set a specific project as the ‘Startup Project’, Visual Studio still started the first project I added to the solution when I hit F5. A workaround is to select the correct project in the Solution Explorer, open it’s context-menu and select ‘Debug’, then ‘Start new instance’.

Blink a LED

The first program to run is of course the mandatory blinking of a LED. It is the ‘Hello World’ of the microcontrollers. Since the NetDuino has an on-board LED, this program can be run without any extra components. You can use the code from the Getting Started document mentioned before.

If you want to try to blink your own LED, don’t forget to combine it with a resistor (of about 1K) to restrict the current that will flow through the LED. Forgetting the resistor could ruin the LED, or worse, the port on your Netduino. Also, mind the polarity of the LED. The longest wire is the positive one. There are several ways you can connect the LED and resistor to any microcontroller, but usually it is done as shown below. This way the LED will be on when the port is high (true).

You can connect the LED & resistor to any of the available ports A0-5 or D0-D13 (the analog ports can be used for digital I/O as well), as long as you change the first argument of the OutputPort constructor to correspond with the selected port. E.g. when connected to the D0 port, the OutputPort should be constructed as follows:

OutputPort led = new OutputPort(Pins.GPIO_PIN_D0, false);

Next: getting started with switches.

TFS 2010 Customization - Version Control

Process template

The version control part of our process template is the same as both the MSF for Agile and the Microsoft Scrum templates.

Multiple check-out is enabled, because there is no reason to disabled it. Any conflicts can easily be resolved using the tools available in Visual Studio, most of the time even automatically. In some instances however, like when refactoring a lot of code, you may consider checking out the affected files with a check out lock. This is still possible with multiple checkouts enabled, but you need to check-out the file(s) manually and select the ‘Check Out’ Lock type.

Get latest on check-out is disabled, because I want control over when the latest version is downloaded. I get the latest version before I start changing any code, but I don’t want any changes on the server to interfere with my coding work while I’m coding. I’d rather resolve any issues once, during check-in, instead of every time I check out a file. Of course, if I need changes made by others, I will get the latest changes, but I’ll decide when.

I didn’t define any check-in policies. Of course everybody should provide comments, associate with work items, run code analysis and make sure the code builds before check-in. But we’ve decided not to make them policies and let them prevent from checking in. One reason is that, although a policy can check if certain information (like comments or a work item) is provided, a policy can’t check if it is meaningful. So these things will be monitored and if a team member is not providing the required information, we will explain why it is important and help to provide the right and meaningful information.

I also didn’t change the check-in notes. I’ve not used them yet and don’t expect to use them in a scrum project, but decided to leave them in.

The above mentioned settings are the default in the process template, but can of course be changed in a specific team project if there is a need to do so. And if there is a very good reason to do so, we can even change the process template :-).

Branching and merging

Branching and merging is an important part of version control, but not a part of the process template. Based on the Branching guide from the ALM Rangers (http://tfsbranchingguideiii.codeplex.com/), we have decided upon a strategy that will allow us to start simple, grow as we need and even take different approaches if required. Below are the basic choices, where the simplest workable solution is the best.

Always start with a Main folder and make it a branch. For very small projects, this could be the branch where development takes place. Only if maintenance is needed on a released version, a new release branch is created using the label that was created during the build of that particular version.

Create separate development branches for multiple teams, or small projects if working in the Main branch is making that branch unstable. Always create a container folder that holds all the development branches, even if there is (currently) only one development branch. Forward and reverse integration with the Main branch is done as much as possible, to minimize the amount and complexity of conflicts.

Release branches, as already mentioned, but also branches for hotfixes, service packs and other maintenance work are only created when necessary. Such branches can easily be created using the label of the build related to the version requiring maintenance. The complexity of the total branch structure really depends on the project and we use the branching guide as a guideline.

TFS 2010 Customization

It has been a while since my last post, but I’ve been very busy. I’ve setup a fresh TFS 2010 environment at Quintor and customized it to our needs. I created a custom process template, a custom SharePoint site definition and custom build activities, to name a few. In this and some following posts, I would like to share what I’ve done.

Of course, to be able to edit the process template, I’ve installed the TFS Power Tools. The latest version (now March 2011) can be downloaded from the Visual Studio Gallery.

Since we use Scrum for all our projects, I decided to start with the Microsoft Scrum template (also available in the Visual Studio Gallery). Some parts I left as it is, other parts I’ve changed to fit our process and needs. And I’m sure some more things will change (or change back) once we have more projects done using this template.

I will take a look at the following subjects, and any changes and customizations I've made, in upcoming posts and provide links to them here:

  • Version control
  • Build automation (including continuous integration)
  • Code quality
  • Work items
  • Reports
  • Project Portal
  • Security

Test and Lab management are missing because I haven’t touched them yet. As soon as I do, and I will :-), I will add those to the list.

HttpWebRequest, HttpWebResponse and cookies

For one of my projects I'm working with HttpWebRequest and HttpWebResponse to retrieve data from a webserver. The code on the server is in PHP which uses cookies to keep track of sessions.

After some research I found the CookieContainer is to be created once and set on each request. My code initially looked something like this:

CookieContainer cookieContainer = new CookieContainer();

HttpWebRequest firstRequest = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

HttpWebResponse firstResponse = (HttpWebResponse)firstRequest.GetResponse();

HttpWebRequest secondRequest = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

HttpWebResponse secondResponse = (HttpWebResponse)secondRequest .GetResponse();

At first it appeared to work. After the first request, the cookies came back in both the response and the CookieContainer. But the second request didn't work, at least the server responded as if no cookies were sent.

With the aid of wireshark, I discovered that the cookies simply weren't sent. And after some debugging I found that the CookieContainer stores the cookies per domain in a domaintable. Although the domainname on each cookie is correct, the domainname in the table is prefixed with a dot ('.'). I'm assuming that the cookies aren't sent, because the prefixed domainname doesn't match the domain I'm sending the next request to.

If I add the cookies to the CookieContainer myself, after getting the response, the cookies are sent as they should and all he requests work fine. With some checks added, the code looks as follows:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.Cookies != null && response.Cookies.Count > 0)
{
    _cookieContainer.Add(response.Cookies);
}

I still feel I must have missed something because, according to each example I've found, just setting the CookieContainer should be enough for all to work. If anyone has a suggestion, please leave a comment. For now, I'm sticking with my workaround.