Tales from the Evil Empire

Bertrand Le Roy's blog

News


Bertrand Le Roy

BoudinFatal's Gamercard

Tales from the Evil Empire - Blogged

Blogs I read

My other stuff

Archives

November 2010 - Posts

Doh! Use the right constants when you talk to a Netduino

(c) Bertrand Le Roy 2010When programming a Netduino microcontroller, you are going to use constants from the SecretLabs.NETMF.Hardware.Netduino namespace. In particular, there are constants defined for each of the microcontroller’s output and input ports, enabling you to write for example:

var button = new InputPort(
Pins.ONBOARD_SW1,
false,
Port.ResistorMode.Disabled);

The type of those constants is Microsoft.Spot.Hardware.Cpu.Pin. Here is the definition of that enumeration:

public enum Pin {
    GPIO_NONE = -1,
    GPIO_Pin0 = 0,
    GPIO_Pin1 = 1,
    GPIO_Pin2 = 2,
    GPIO_Pin3 = 3,
    GPIO_Pin4 = 4,
    GPIO_Pin5 = 5,
    GPIO_Pin6 = 6,
    GPIO_Pin7 = 7,
    GPIO_Pin8 = 8,
    GPIO_Pin9 = 9,
    GPIO_Pin10 = 10,
    GPIO_Pin11 = 11,
    GPIO_Pin12 = 12,
    GPIO_Pin13 = 13,
    GPIO_Pin14 = 14,
    GPIO_Pin15 = 15,
}

Now it’s easy to confuse those constants from the Microsoft.Spot.Hardware namespace for the following, which are defined in the Netduino library:

namespace SecretLabs.NETMF.Hardware.Netduino {
    public static class Pins {
        public const Cpu.Pin GPIO_PIN_D2 = Pin.GPIO_Pin0;
        public const Cpu.Pin GPIO_PIN_D3 = Pin.GPIO_Pin1;
        public const Cpu.Pin GPIO_PIN_D7 = Pin.GPIO_Pin3;
        public const Cpu.Pin GPIO_PIN_D8 = Pin.GPIO_Pin4;
        public const Cpu.Pin GPIO_PIN_A4 = Pin.GPIO_Pin10;
        public const Cpu.Pin GPIO_PIN_A5 = Pin.GPIO_Pin11;
        public const Cpu.Pin GPIO_PIN_D4 = Pin.GPIO_Pin12;
        public const Cpu.Pin GPIO_PIN_D12 = 16;
        public const Cpu.Pin GPIO_PIN_D11 = 17;
        public const Cpu.Pin GPIO_PIN_D13 = 18;
        public const Cpu.Pin GPIO_PIN_D0 = 27;
        public const Cpu.Pin GPIO_PIN_D1 = 28;
        public const Cpu.Pin ONBOARD_SW1 = 29;
        public const Cpu.Pin GPIO_PIN_D5 = 51;
        public const Cpu.Pin GPIO_PIN_D6 = 52;
        public const Cpu.Pin GPIO_PIN_D9 = 53;
        public const Cpu.Pin GPIO_PIN_D10 = 54;
        public const Cpu.Pin ONBOARD_LED = 55;
        public const Cpu.Pin GPIO_PIN_A0 = 59;
        public const Cpu.Pin GPIO_PIN_A1 = 60;
        public const Cpu.Pin GPIO_PIN_A2 = 61;
        public const Cpu.Pin GPIO_PIN_A3 = 62;
        public const Cpu.Pin GPIO_NONE = Pin.GPIO_NONE;
    }
}

See the big difference? If you use the first ones, thinking that the numbers are mapped to your ports, then you are going to get the signal for D0 on D2, D1 on D3 and so on.

As the type is Cpu.Pin, the confusion is very easy and you won’t even see the real constants you should be using if you didn’t include the SecretLabs.NETMF.Hardware.Netduino namespace.

I’ve seen it happen, and Fabien and I scratched our heads for a while before we understood that basic mistake.

Moral of the story:

Include the SecretLabs.NETMF.Hardware.Netduino namespace in all the classes you write against the Netduino, always use the Pins.* constants from that namespace, and never use the ones from Microsoft.SPOT.Hardware.

Checking that the pin number is not just a number but rather a letter (A or D for analog or digital) and a number is a good way to make sure you have the right ones.

Improving the Netduino Knight Rider effect with a shift register

(c) Bertrand Le Roy 2010In my last Netduino post, I showed how to create a simple Knight Rider effect. One of the problems of that implementation was that we were occupying one digital port of the Netduino for each light in the ramp. It’s fine for that simple effect, but in future posts we’ll look at controlling our whole 8x8 LED matrix, which has 16 pins whereas the Netduino has only 14 digital ports.

In order to address all the matrix pins, we will need to do some multiplexing. Multiplexing means trading some time for some space. In our case, instead of using 8 parallel ports for each of the LEDs that we want to address, we’ll stream the 8 bits onto a single port serially in time and have a special component spread that onto the matrix’s pins.

This can be very simply done using a SN74HC595 shift register. These little chips come for less than a dollar and are fairly easy to use.

Sending a byte to the shift register

As you can see from the diagram above, you need to send the bits in sync with the clock, and once you’re done, trigger the latch to tell the shift register you’re done transmitting. The output pins then reflect spatially the sequence of bits that was serially input.

Here is the code that would produce that result on the shift register:

byte value = 0x97; // 10010111 
Latch.Write(false);
// Lower Clock
Clock.Write(false);

for (var i = 0; i < 8; i++) {
    byte mask = 1;
    mask <<= 7 - i;

    var pinState = (mask & value) != 0;

    // Write data bit
    Data.Write(pinState);

    // Pulse Clock
    Clock.Write(true);

    // Raise Data to prevent IO conflict 
    Data.Write(true);

    Clock.Write(false);
}

// Set the latch high to indicate that
// we're done transmitting
Latch.Write(true); Latch.Write(false);

This time, the data we have to feed into the shift register will be very simple: we just want one bit at a time that we’re going to shift back and forth.

var button = new InputPort(
Pins.ONBOARD_SW1, false,
Port.ResistorMode.Disabled); var sr = new ShiftRegister74HC595(
1, DataPin, Clock, Latch,
Pins.GPIO_NONE); var dir = 1; var i = 0; while (button.Read()) { for (; i >= 0 && i < 8; i += dir) { sr.Write((byte)(1 << i)); Thread.Sleep(50); } dir *= -1; i += dir; }

We are using a little abstraction class around the shift register here (written by Fabien) that has a Write method that takes a byte and sends it to the SN74HC595.

The wiring for this is pretty straightforward.The wiring for the project

The first row of the LED matrix is wired to the ground so that the sequence displays on that row only. The outputs of the shift register go to the columns of the LED matrix through 8 150Ω resistors.

Here’s a video of the result:

The Knight Rider effect

Next time, we’ll get a full 8x8 image to display on the LED matrix.

You can download the code for this project here:
NetduinoKnightRiderShiftRegister.zip

Oh, and one last thing… I’ve been promising a shopping list for beginners, and Fabien was kind and patient enough to write this great post:
http://fabienroyer.wordpress.com/2010/11/11/where-to-find-parts-for-your-netduino/

FluentPath 1.0

(c) Bertrand Le Roy 2010Last Sunday, I published version 1.0 of my little FluentPath library.

This library, which is a fluent wrapper around System.IO, started as a little experiment / code sample and has been met with some enthusiasm from some of you so I spent quite a bit of time over the last few months polishing it and trying to raise it to a level of quality where it can safely be used in real applications (although my lawyer is telling me that it’s still at your own risk, as specified in the license).

I’ve started using it myself on a few projects and it’s now my default way of accessing the file system.

So what’s in there and why should you use it?

It’s small!

36kB dll, no dependencies.

It’s a NuGet!

You can now install FluentPath with NuGet:Installing FluentPath with NuGet

It’s robust!

Since the first release of FluentPath, I’ve spent the most time on writing unit and functional tests for the library. At 143 tests and more than 80% coverage, I’m pretty confident that this can be safely used in real projects (even if my lawyer isn’t).

Kind of.

Well, it’s still really designed for the manipulation of relatively light files: it does not always use buffered streams and doesn’t do asynchrony. I think that’s all right for most uses but if you’re in a case where you can’t afford that, just continue to use System.IO instead.

Of course, if someone wants to contribute patches, that’s fine too.

It’s fun!

Consider the following piece of code:

Path.Current
    .Files(
        p => new[] {
            ".avi", ".m4v", ".wmv",
            ".mp4", ".dvr-ms", ".mpg", ".mkv"
        }.Contains(p.Extension))
    .CreateDirectories(
        p => p.Parent()
              .Combine(p.FileNameWithoutExtension))
    .End()
    .Move(
        p => p.Parent()
              .Combine(p.FileNameWithoutExtension)
              .Combine(p.FileName));

This selects all video files in the current directory and then moves them into their own directory. So for example if you have a WingsOfDesire.avi file, it will create a WingsOfDesire folder and move the file in there. And it will do so for each of the files in there.

It is left as an exercise to the reader to write the same code with just System.IO and to compare with this.

It’s extensible!

Now that’s nice but there is so much more you can do with files. Zipping and unzipping for example. There are good libraries for that, such as SharpZipLib. But SharpZipLib is rather low-level and it’s not fluent. Not that everything has to be, but wouldn’t it be neat to have a fluent API for zipping and unzipping, one that integrates well with FluentPath?

Well, as an experiment, I built exactly that around SharpZipLib, enabling that sort of thing:

Path.Current
    .Files("*.txt", true)
    .Zip((Path) "textfiles.zip", p => (Path) p.FileName);

Those extra methods are just extension methods for Fluent.IO.Path that can be imported by referencing the new Fluent.Zip.dll assembly and using the Fluent.Zip namespace. For example, here’s the code for that particular Zip overload:

/// <summary>
/// Zips all files in the path to the target.
/// </summary>
/// <param name="path">The files to compress.</param>
/// <param name="target">
/// The path of the target zip file.
/// If target has more than one file, only the first
/// one is used.
</param> /// <param name="fileSystemToZip"> /// A function that maps the paths of the files and
/// directories to zip into relative paths inside the zip.
/// </param> /// <returns>The zipped path.</returns> public static Path Zip(this Path path, Path target,
Func<Path, Path> fileSystemToZip) {
var files = path.AllFiles() .ToDictionary( fileSystemToZip, p => p); Zip(target, new Path(files.Keys), p => files[p].ReadBytes()); return target; }

This shows how it’s very easy to add your own extensions to FluentPath and for example capture in an easy method a specific process that you happen to repeat a lot in your code.

What’s new?

The main change in this new version is that instead of having one Path class to represent a single path, and a PathCollection class to represent a collection of Path objects, I’ve coalesced both classes, jQuery-style and now there is only Path, which behaves both like a single path and like a collection of paths. This makes it really natural to work with sets as if they were single items, which is where fluent APIs really shine.

Another important and breaking change is that Path and string are no longer implicitly cast to each other. Now you need to be explicit about switching from string to Path and back. It’s a little less convenient but the previous ambiguity actually wasn’t sustainable. This way, things are a lot clearer.

And of course, I’ve added lots of nice methods such as Grep. And lots and lots of bug fixes, which is what happens when you start writing tests…

What’s next?

The next big change I want to bring to FluentPath is an additional layer of abstraction in the form of a pluggable file system. This should enable you to test code that is using FluentPath without having to physically write to the file system but instead to write to a stub or a mock. Potentially, it also opens a few interesting scenarios where you manipulate a file-system-like structure using these same APIs and switch from one abstraction to the other without code modifications.

I also want smaller changes such as exposing all file attributes and metadata directly on Path, or change monitoring.

Where is it?

Some links and previous posts about FluentPath:

The original post:
http://weblogs.asp.net/bleroy/archive/2010/03/10/fluentpath-a-fluent-wrapper-around-system-io.aspx

Writing the tests:
http://weblogs.asp.net/bleroy/archive/2010/05/28/writing-the-tests-for-fluentpath.aspx

The project:
http://fluentpath.codeplex.com/

More Netduino fun

(c) Bertrand Le roy 2010Last time, we ran a very simple program on the Netduino. This time around, we’ll actually connect some real hardware to that microcontroller and blink some lights! You know what? Let’s go crazy! Let’s go for Knight Rider lights! Woohoo!

Ahem.

Yeah. Well, you’ve got to start small. Anyway, I have this LED array that I’m going to build a little something on soon. This time, we’ll just use a single line for that simple effect.

The LED array can be found here: http://futurlec.com/LEDMatrix.shtml for $1.80, which is ridiculous. It’s the LEDMS88R. A LED array is a very simple piece of hardware: it’s just LEDs at each intersection of line and column wires:LEDMS88R Circuit

To turn on one of the LEDs, just send some juice between the right line and column. You can even turn on an arbitrary combination of lights on any line or any column. But of course if you try to do any more than that, you’ll have extra pixels lit in most cases. What you do instead is use persistence of vision and scan the matrix line by line very fast. This way you can display any 8x8 image at all. But today, we only need a single line.

Before we connect the controller to the matrix though, we need to deal with a small problem that will be very common as we build more hardware prototypes. Before you use any component at all, you need to RTFM. Let me repeat that:

You need to READ THE EFFING MANUAL.

For real. I know you’re a super geek and make a point of never ever doing that. Well, hardware is not like software. The equivalent of an API, for hardware, is the pin repartition but it doesn’t have names, it doesn’t have comments, and it’s not designed to be logical.

Just take another look at that LED matrix schema above. Notice anything? Yes, pin number 1 is for row 5, pin 2 is for row 7, pin 3 is for column 2, and so on until your sanity’s just a confused and fading memory. You don’t want to have to figure this out by trial and error. Just read the damn thing.

In order to get halfway back from that dark pit of madness, we’ll have to build a rational façade of sorts before that matrix. That façade can be either software on the microcontroller or it can be hardware. I opted for hardware, which I think deals with the problem once and for all and allows for more flexibility in design going forward. I went ahead and mapped the pins of the matrix to the rows 1 to 8 of two columns on my breadboard, one for rows and one for columns:Mapping the pins

One thing I might do eventually is to order a custom circuit that hosts the matrix, does the mapping and is easy to plug into the breadboard: those wires are ugly.

Another thing to keep in mind is that the consequences of a hardware mistake is not going to be a nice exception. There will be smoke. You’re going to fry a chip, or your microcontroller, or both. All the more reason to READ THE EFFING MANUAL. And check everything ten times before you switch on the power. Oh wait, make it twelve.

For example, when getting current flowing through LEDs like those in that matrix, remember a passing LED is like a wire, so it’ll short-circuit if you don’t put a resistor in front of it. If the LED doesn't fry before, which it will. But you don't want to use LED matrices as fuses.

For our Knight Rider effect, we only need one line, so I connected the 3V power line of the Netduino to one of the + columns of the breadboard. I then pulled a 150 Ohms resistor between that and the column 1 of the matrix. Then I pulled a wire between the pins for each row and the digital ports 0 to 7 of the Netduino:The knight rider effect connections

Now all we have to do is write the small bit of code that will turn the LEDs on and off in the right order:

using System.Threading;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;

namespace HelloNetduino {
    public class Program {
        private static readonly OutputPort[]
ColPorts = new [] { new OutputPort(Pins.GPIO_PIN_D0, false), new OutputPort(Pins.GPIO_PIN_D1, false), new OutputPort(Pins.GPIO_PIN_D2, false), new OutputPort(Pins.GPIO_PIN_D3, false), new OutputPort(Pins.GPIO_PIN_D4, false), new OutputPort(Pins.GPIO_PIN_D5, false), new OutputPort(Pins.GPIO_PIN_D6, false), new OutputPort(Pins.GPIO_PIN_D7, false) }; public static void Main() { var switchPort = new InputPort(
Pins.ONBOARD_SW1,
false,
Port.ResistorMode.Disabled); var dir = 1; var i = 0; while (switchPort.Read()) { for (; i >= 0 && i < 8 &&
switchPort.Read(); i+= dir) { ColPorts[i].Write(false); Thread.Sleep(50); ColPorts[i].Write(true); } dir *= -1; i += dir; } } } }

Now that wasn’t too hard. Here’s the result:

Next time, I’ll really give that shopping list I promised last time, and we’re going to see how to address any of the 8 rows and 8 columns on the matrix even though the Netduino only has 14 digital ports.

More Posts