Jeroen Swart

.NET Architect

NetDuino - Getting Started with PWM

PWM (or Pulse Width Modulation) is a technique that basically allows digital circuits to control analog circuits. One of the applications for this is to control the speed of a motor or, as I will show you in a second, the brightness of a LED.

A digital port is either on or off. This is very logical, but not very helpful when controlling an analog device like a motor. The speed of a motor is usually controlled by varying the voltage: if you set the voltage higher, more current will flow and the speed of the motor will increase.

With PWM, the digital port is switched on and off really fast. The effective voltage for analog (DC) use is the average of the on and off levels and depends on how fast the port is switched. The time the port has been switched both on and off is called the period, the time the port is on is called the pulse and the time the port is on, relative to the period, is called the duty-cycle and is expressed in percentage. By controlling the width of the pulse, you control the effective voltage on the output. Luckily, most microcontrollers have one or more PWM ports. You only need to set the period, pulse and/or duty-cycle, and the microcontroller takes care of the rest.


This image shows a PWM signal with a 50% duty-cycle. With a supply voltage of 3.3V, like on the Netduino, this will result in an average output of 1.65V.


This image shows a PWM signal with a 25% duty-cycle. This will result in an average output of 0.825V when using a supply voltage of 3.3V.

The Netduino has 4 ports that are capable of producing PWM signals: D5, D6, D9 and D10. The PWM class is used to control one of these ports. It provides two methods to configure the port. With the SetDutyCycle method, the duty-cycle is simply set as a percentage. Passing 0 sets the port off all the time, resulting in an effective 0V output. Passing 100 sets the port on all the time, resulting in an effective 3.3V output. Passing 50 results in an pulse that’s on during 50% of the period, resulting in a 1.65V output. The SetPulse method allows a little more control. The first argument is the length of the period and the second argument is the duration of the pulse, both in microseconds. So calling SetPulse(1000, 250), results in a pulse that starts every 1ms and lasts 0.25ms; the duty-cycle in this case is 25%.

In the simple example below, the LED is dimmed to a specific level. Since the on-board LED is not connected to a port that allows PWM, we need to connect a LED ourselves. This example will work with a LED & resistor connected directly as shown here, or using a transistor as shown here. The only difference is that you need to use one of the PWM ports. The code below is using port D5. Please note that for controlling anything other than a LED, you will need a transistor to provide a decent amount of current.

public class Program
{
    public static void Main()
    {
        // initialize one of the digital pins (that support PWM!) for PWM
        PWM pwm = new PWM(Pins.GPIO_PIN_D5);

        // set the duty-cycle to a specific value
        pwm.SetDutyCycle(50);

        // wait forever...
        Thread.Sleep(Timeout.Infinite);
    }
}

In the example below, the LED is dimmed repeatedly from totally off to totally on and back again. It uses the same port and components as in the previous example.

public class Program
{
    public static void Main()
    {
        // initialize one of the digital pins (that support PWM!) for PWM
        PWM pwm = new PWM(Pins.GPIO_PIN_D5);

        // we start with the LED off
        int dutyCycle = 0;
        // we start with making the LED brighter
        bool up = true;

        // do forever...
        while (true)
        {
            // if making the LED more bright
            if (up)
            {
                // increase duty-cycle
                dutyCycle++;

                // if we're at 100%, start making the LED less bright
                if (dutyCycle >= 100)
                {
                    up = false;
                }
            }
            else
            {
                // decrease duty-cycle
                dutyCycle--;

                // if we're at 0%, start making the LED more bright
                if (dutyCycle

Another application for PWM is controlling servos, as are used in remote controlled cars and small robots. In this case the duration of the pulse controls the angle of the servo. The period is 20ms and a pulse of 1.5ms (duty-cycle 7.5%) puts the servo in the center or zero position. A pulse of 1ms (duty-cycle 5%) turns the servo completely to one side and a pulse of 2ms (duty-cycle 10%) turns the servo completely to the other side.

Next: using the ADC.

NetDuino - Getting Started with transistors

Controlling a LED directly using a port is fine in most cases, because a LED only requires a small current that can be supplied by the Netduino. But when controlling components that require more current (like high-power LED’s, motors, relays, etc.) a transistor is needed. The transistor is controlled by a small current from the MCU and the transistor controls the heavy load. While transistors actually work as amplifiers, they can also be used as switches.

Transistors exist in a few main types, like bipolar (either NPN or PNP) or FET. For our purpose almost any popular bipolar transistor will work. For each main type, there are many different types to select from. Examples for NPN types are: BC547, BC548 or 2N222. Examples for PNP are: BC557, BC558 or 2N2907. I picked the BC547, a NPN type, and will use it in my example which will simply control a LED. You can use the source code from the blink example in the Netduino Getting Started document.

The schematic shows a LED, again with a resistor to restrict the current through the LED. They are connected to the collector of the transistor, while the emitter is connected to ground (or common or 0V). When the transistor is switched on, current will flow through the transistor from the collector to the emitter. This current will also flow through the resistor and LED, so the LED lights up. When the transistor is switched off, no current will flow and the LED remains off. Switching the transistor is controlled by a current through the base. The base is connected to a NetDuino port through a resistor. And yes, the resistor is there to restrict the current. Since the current is only needed to switch the transistor and not to light up the LED a small current will suffice. A high level (true) on the NetDuino port will cause a current at the base, which will switch the transistor on and the LED will light up.

The above is of course a simple (but working) example. Each specific transistor type (BC547, BC548, etc.) has its own specifications, although many can be used in a similar way or even as a replacement in a situation as simple as this.

Since the Netduino ports are at 3.3V, when set high and the base-emitter voltage is 0.7V (which is the case for most transistors), the voltage-span over the resistor is 2.6V. This gives a 0.5 mA current (I = V/R => 2.6V / 5.6KΩ = 0.46 mA) through the resistor and at the base.

A PNP transistor, like the BC557 below, can replace the BC547 in the schematic above. Although, because of the different behavior of the PNP transistor, the LED will be off when the port is high and the LED will be on when the port is low.

On a PNP transistor the collector is drawn with an arrow inwards. On a NPN transistor the arrow is outwards on the emitter.

Connecting the transistor

A transistor is almost always part of a larger circuit, as it is not much use by itself. The easiest way of putting such a circuit together with the Netduino is using a breadboard or a breadboard shield. If you want to know more about using a breadboard, there are lots of online breadboard tutorials.

To connect any transistor in the right way, you'll need to know which pin is which. The datasheet for the transistor of your choice will help you out. Just google/bing the type and 'datasheet'. Below is a part from the datasheet of the BC547.

 

Next: dimming a LED.

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 Scrumboard

One of the things I'm missing in Team Foundation, is an easy way to prioritize and plan workitems (user stories, tasks, bugs, etc.). The easiest way right now, is to open a workitem query in excel and edit the priority of each workitem. But that's not really easy. You need to change the priority field, making sure to provide a correct value that will put the workitem in the right position priority-wise. If you managed to pick the correct values, you need to sort the workitems; which is a manual action.

I would like to be able to drag & drop workitems in the correct position in the list. I don't care about the exact value of the priority field. I only care about the order in which the workitems show when they are sorted by priority. I would also like to be able to easily plan workitems, by moving workitems into (or out of) a specific iteration path. In my case that would be the product backlog and several sprint backlogs, but the functionality should be applicable to all process templates. Finally, I would like to have some sort of status- or scrumboard. Each possible status for workitems is a column on the board and each workitem is represented by some form of card. By moving a workitem card into a specific column, the status of that workitems changes accordingly. We use physical (white)boards, with a recent print-out of the sprint burndown in some corner, but they are of course not connected to TFS.

I did some research on how to build such functionality and, especially, on how to integrate it into TFS Web Access and/or Sharepoint. I quickly found that TFS Web Access would be the easiest way, for me at least :-P. Last month I started a project on codeplex: TFS Scrumboard. Below is a short description and a screenshot.

Project Description
TFS Scrumboard is an extension to TFS 2010 Web Access, providing easy planning and managing of workitem progress.

TFS Scrumboard is build (in C#) as an extension to TFS 2010 Web Access. It is designed to be used in scrum projects, using one of the many scrum process templates available. I use my own custom scrum process template, to support the way we do scrum projects, but no dependency on any kind of process template is assumed.

When installed, TFS Scrumboard provides two extra tabs in TFS Web Access: Planning and Tasks.

The Planning tab is meant for planning and prioritizing workitems. It shows the product backlog and each sprint backlog on the left side, and the workitems in a selected (product/sprint) backlog on the right side. A workitem can be planned by moving it to (dropping it on) a specific sprint backlog or removed from planning by moving it to the product backlog. A workitem can be prioritized by dragging-and-dropping it in the desired position inside a (product/sprint) backlog.

The Tasks tab is meant for managing the progress of workitems during a sprint. It shows vertical swimminglanes which represents one or more statusses of the workitems in a specific sprint. The status of a workitem can be changed by dragging-and-dropping it in the desired swimminglane. A workitem can be prioritized by dragging-and-dropping it in the desired position (vertically).

Goals

  • Planning work items, by dragging-and-dropping them into a specific (product or sprint) backlog
  • Prioritizing work items, by dragging-and-dropping them into the desired order
  • Manage sprint progress, by dragging-and-dropping them into the corresponding swimminglane
  • Print workitem cards, to be used on a RL scrumboard (if possible with a link back to TFS, using a camera, some form of (RFID?) tags or (2D?) barcodes)

 

TFS 2010 - Moving Sharepoint to another server

The last few months, we used a single server for our first TFS installation to host both TFS 2010 and Sharepoint 2010. We started with the single server because of lack of resources on the virtual hosts, and I couldn't wait for the new hardware to arrive :-P.

Today I moved the Sharepoint server to a new dedicated virtual machine. Only a few team projects with a team portal exist yet and since most portals don't have any content except the dashboards, I decided to simply recreate the team portals on the new machine and copy any content manually.

The installation and configuration of the new Sharepoint 2010 server was quick and without problems. We also changed the NAT of the firewall to point our external IP & domainname to the new server, again without any problems.

Then it was time to install & configure the Sharepoint extensions as well as reconfigure the integration with Sharepoint for TFS 2010. I encountered some errors during this part that we quickly fixed, but learned a few lessons that might be usefull for others.

TF250049 & TF25006

The first error happened during the configuration of the TFS Sharepoint extensions on the new Sharepoint machine. Error TF250049 (the URL for Team Foundation Server could not be verified), which in turn was caused by error TF250067 (No connection could be made). This error was solved by first changing the 'Sharepoint Web Applications' configuration on the TFS machine. By adding the new Sharepoint web application (or changing the existing one) the service accounts used by Sharepoint are granted access to TFS.

TF250067 and not associated project portals

Before (re)creating the site collection and project portal sites, you need to add the TFS service account to the farm administrators group in Sharepoint. This will prevent TF250067 errors during the creation of the project portals. The project portal will be created, but without a working association with TFS.

If this happened to you, delete the project portal site before recreating it, again.

Team Project Site collection

To recreate the site collection, navigate to the team project collection in the 'Team Project Collections' node in the TFS admin console and select the SharePoint Site tab. Select 'Edit Default Site Location' (, make any changes to the Default Site Location if you want) and click OK. Since the Sharepoint is a fresh install, you will be prompted to create a new site. This is the site(-collection) for the team project collection, that will contain all the project portals within the team project collection.

Project Portals

The easiest way to recreate the project portals, is to use the tfpt command-line tool that is part of the Team Foundation Power Tools (which can be downloaded from the Visual Studio Gallery). You can easily see what arguments must and can be provided by executing: tfpt addprojectportal /?, but here is some extra information.

The collection argument is the uri of the TFS server, as you configured them e.g. in the Team Explorer. Examples:
/collection:http://tfs.domain.local:8080/tfs
/collection:https://tfs.domain.com/tfs

The teamproject argument specifies the name of the team project. Of course, you need to put the name between quotes if it contains spaces. Examples:
/teamproject:MyProject
/teamproject:"My Other Project"

The processtemplate argument specifies the name of the process template. Again, use quotes if it contains spaces. Examples:
/processtemplate:"MSF for Agile Software Development v5.0"
/
processtemplate:"Quintor Scrum 0.8"

If you want to create the portal on a different url, e.g. team project name contains spaces and you do not want those in the url of the project portal, provide both the webapplication and the relativepath arguments.

The webapplication argument specifies the url of the web application (and not the name as the usage help says). Examples:
/webapplication:http://sharepoint.domain.local
/webapplication:https://projects.domain.com

The relativepath specifies the path to the project portal. Examples:
/relativepath:/sites/DefaultCollection/MyProject
/relativepath:/sites/Quintor/MyOtherProject

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.

Hello 2011

Welcome in the new year. I wish you all the health, success, luck and happiness.

Although I did write content for my blog as I set out to do at the beginning of last year, I didn’t write as much as I’d liked. This year I will try to write more and more interesting content.

A big change for me this year is a change of employer. Next month I’m starting at Quintor. Quintor specializes in Agile software development using the Scrum methodology, Java technology and a software factory based on Java technology, tools, frameworks and best practices. And, as you might have guessed, we will be adding Microsoft .NET technology and a software factory based on .NET specific tools, frameworks and best practices.

VMware Player and bridged network adapter

For a current project I needed a 64 bits virtual environment and decided to use VMware Player (3.1.2). All went well untill I tried to access the web from the VM while working at home using my wireless LAN. I had no problem accessing the internet during the first part of the install, but that was at the office and probably hardwired to the LAN.

So I had to tell my VM not to use the wireless adapter, not the wired adapter. I've used VMware workstation before so I thought no problem. But, VMware player is missing the Virtual Network Editor. Fortunately, this tool is part of the installer, it's just not installed. To get the Virtual Network Editor do the following:

  1. Run the installer with the extract (/e) option to extract all it's contents to a local folder:
    VMware-player-3.1.2-301548.exe /e .\extract[/code]
  2. In the created 'extract' folder, locate the 'network.cab' file and open it.
  3. From the 'network.cab' file, copy the 'vmnetcfg.exe' file to the VMware Player installation folder (in my case: C:\Program Files (x86)\VMware\VMware Player).
  4. Start the Virtual Network Editor (vmnetcfg.exe) from the installation folder; you could add a shortcut to the start menu for easy access.
  5. Now you can select or restrict the network adapters to be used by the bridged adapter from within your VM.