Michael Duerinckx

 

Kicad: Creating schematic components and libraries

I’ve had some trouble piecing together how to deal with custom schematic components in my PCB design package of choice, Kicad. It took too much searching and trial and error to get to grips with the process, so I’ve decided to write my own detailed article about it. This guide applies as of version 4.0.4-stable. I’m using the Windows build.

Please do note, this article will only cover schematic components; I will not touch on the actual PCB footprints here. In Kicad, the two are very distinct; they are only connected when you finish designing your schematic, and you assign footprints to each of the components in it.


Library structure

In Kicad, all files are essentially plain text files, meaning you could edit them with a simple text editor like Notepad or TextEdit. A library (.lbr) file is one such plain text file, in which a series of schematic components are defined by name, a set of pins, and a drawing. In addition, there is a .dcm file for every library file, which contains any documentation and description for the components contained within the library.

Kicad comes with a set of libraries of its own, which are typically stored in a read-only location. As a result, if you want to customize or create new components, they should be saved in a library within your documents, or your project directory. You can choose to maintain your own main set of libraries that all your kicad projects can access, or you can save libraries in project folders, making them local to just that project.

The location you save your libraries is a matter of personal preference, so don’t dwell on it too much.

Read more »

Using Async and Await in C# (Part 1)

In programming, there are many use cases for doing things in an asynchronous way. In almost all cases, it comes down to executing an operation that may take a while, without blocking user interaction or other program execution. Perhaps the most common example of this is making a web request, waiting for its response, then doing something with said response. While you are waiting for the response, the user interface shouldn’t freeze.

This is where asynchronous operations come in. In essence, you tell the computer to “do X, and whenever that’s done, do Y. In the meantime, let me go about my business”. A real life analogy would be heating food in a microwave oven: You put your food in there, tell the oven what to do and to notify you when it’s done. While the oven is doing its thing, you can get on with setting the table. When it’s done, it gives you hot food, which you can then serve.

Callbacks: The Old, Ugly Way

If you are used to Java, you would often implement asynchronous operations by supplying a callback: a function that gets invoked once the operation is completed. You either instantiate and override a class that implements the required callback functions, or implement the interface directly in your class. The code to execute once the operation completes is nested at least two levels deep, or lives in some other method. Your options are to do some cumbersome nesting, or to artificially split up code that is part of the same action.

C# allows you to do both of those, but offers a much tidier approach. Out with the loads of extra classes and interfaces, in with async, await, and Task.

C#;s async Modifier and await Keyword

In C#, if you want to do asynchronous work, start by adding the async modifier to the method where you’ll be doing it.

private async void MyMethod()

In this method, you can now use the await keyword, for example, like the following:

var itemPrice = await api.getPrice(itemId);

The code in this method will execute up to this point, and not go any further until api.getPrice has finished its work and retrieved a value. Once in it has retrieved the item’s price from wherever, execution of our method continues at the next line, like regular program flow.

At this point you may object, since nothing but a few keywords distinguish the example from a normal synchronous program. The difference lies in the fact that other code is free to run while the awaited call is ongoing. The user interface will not become unresponsive.

This async method behaves exactly like a callback would. In contrast to a callback, all our related code gets to stay in one method, and remains easy to follow, much like a normal procedural program.

In this post I will explain how you can implement your own asynchronous methods for a few common use cases:

Read more »

Adding stereo VU meters to a turntable

My fiancée got me a great gift for my last birthday: a turntable. Being a classic trance lover, I’ve since been collecting a bunch of records. The thing has really been a source of joy thus far.

About a month ago I started itching to do a little electronics project again as it had been a while. Long story short, I figured it’d be neat to open up this relatively simple device and add a nice aesthetic feature to it: VU meters.

Since this is a rather involved hack, (as opposed to my line-in addition to a boombox), it gave me a good reason to finally check out Southampton’s maker/hackerspace, SoMakeIt.

Turntable with lit LEDs along the diameter of the record it's playing

Read more »

Hacking a line-in socket into an 80s radio and cassette player

A few years ago, my grandmother gave me one of the old radios she had lying around the house. My late grandfather’s hobby was participating in radio quizzes, which led him to win a lot of radios; I assume this was one of them. The radio was manufactured in the early 80s, so the guts are relatively easy to tinker with; everything is on single-layer PCBs.

Frontal photo of the radio before any alterations were made, showing buttons on top, speakers on either side of a cassette deck, slider buttons, a radio tuning dial across the top, and sound volume indicator lights
The radio, as it looked before opening it up

I realised that the audio quality of this old boy was really decent, so it would be a waste to just let it sit in a cupboard. I don’t generally listen to the radio that much, and I don’t exactly have a big collection of music on cassettes either (and if I did, I’d digitize it anyway). To really get some use out of it, the most logical thing would be to have a line-in, letting me hook up a phone or whichever external audio source.

So, I set to work, opening the machine up.

Photo of the radio laying down on its back, the front part of the case taken off. Revealed is the mechanism of the cassette player, various sliders, PCBs with various components on the left and right, and the transformer on the far left.
The front part of the case taken off, which removes the speakers

Read more »

Embedding a player on Facebook: A guide

Last weekend I had a mission: to build a player component for instaud.io that could play audio people linked to, right in Facebook news feeds. I found that there are plenty of excerpts on how to go about this, but most of them are based on outdated links to Facebook developer documentation. It bugged me greatly that Facebook didn’t bother setting up redirects to relevant pages after restructuring their docs.

Anyway, I think this would work best as a step by step guide. I’ll go through the steps I’ve had to learn about; you may want to skip over some if you’re already know what you’re doing in them.

1. Build your player in Flash

I downloaded the Adobe Flash trial for this. You’ll want to create a stage that is not much wider than 500 pixels. I went with 504px. What you’re going to be playing depends entirely on you. My purpose was simply to play audio files (MP3s), so I used Sound and SoundChannel to control that. The audio file to be played was requested with an URLRequest object.

If you want a more thorough introduction on how to set up a simple sound player, this video from 2008 is still a good starting point, even with the latest version of Flash (12, CS6): Build Simple Sound Player: Flash Tutorial AS 3.0

Using parameters

The important part about the ActionScript is using parameters. Parameters will be passed to the eventual SWF through the querystring, that is, the bold part in this URL: https://example.com/my-player.swf?param=value&otherparam=value

In ActionScript (3), you can access these variables the following way:

loaderInfo.parameters.parameterName

To check if a parameter is actually present:

loaderInfo.parameters.hasOwnProperty('parameterName')

This way you can use default values for parameters:

var myParam = loaderInfo.parameters.hasOwnProperty('myParam') ?
    loaderInfo.parameters.myParam :
    'defaultValue';

Since hasOwnProperty returns a boolean value (true or false), this statement assigns either the value of myParam from the querystring, or 'defaultValue' if no such parameter was specified, to the myParam variable. It uses a ternary operator.

2. Export the SWF file and include it in your website’s assets

This is fairly straightforward. You’ll want the swf to live someplace where it’s directly accessible. I let mine live in the document root directory.

3. Add Open Graph meta tags to the page

This is where the Facebook magic happens.

Read more »

Event-driven JavaScript: a simple event dispatcher

One of the more valuable lessons that I’ve learned in the years I’ve been programming is that loose coupling will make your life better. A very good way to achieve loose coupling in your projects is by dividing functionality in self-sufficient modules that communicate merely by subscribing to and triggering events. To work with these events, you need one component that is relatively tightly coupled with all your modules. This little bit of coupling is definitely worth it though.

Before diving into specifics, let’s talk about just what I mean.

Loose coupling

When the code base for a project gets sizeable, one thing that can make it a nightmare to work with is tight coupling. When modules are tightly coupled in a project, it means that changing one method in module A may require you to change the way certain things are implemented in module D, F and G. In order to make any modifications, you need to be well aware of how other modules rely on the module you wish to modify.

Since having a single module in your head can be taxing enough for the mind, considering basically the whole project when making a local change is awful; oversights are bound to occur.

To ensure you do not need to wrap your head around the entire code base at all time, you’ll want to make sure your modules are loosely coupled. You can safely change the modules’ internals without having to worry about how other modules have to interact with this module. You need to consciously engineer your modules to be entirely agnostic of the inner workings of others.

You’ll find that employing this method makes it much less of a daunting task to change some functionality around.

Bring on event-driven programming

Event-driven programming is a fairly simple pattern where component subscribe to events and trigger them. A variant of the pattern is the observer pattern; the difference however lies in where the event dispatching happens.

In an observer pattern, you can register observers (subscribers) to event a certain module emits. This way you can subscribe to, for example, an after-save event, which is emitted every time an object’s data is saved. The observer subscribing to this event will be triggered every time that happens, and a function can then be run.

In this case, we move the subscribing facilities away from the modules to a dedicated event dispatcher module. This provides one central location where modules sign up to be notified when a certain event occurs, as well as where modules go to broadcast an event they want to make the application aware of.

Doing this, all each module is concerned with if it comes to communicating with the rest of the application is 2 uniform things: Emitting events and responding to events emitted elsewhere. The modules do their thing, throw out some information whenever there is something that may concern the rest of the application, and they remain alert for external events pertaining to the module in question.

Responsibilities of the event dispatcher

The event dispatcher module that drives this whole pattern has only few responsibilities:

Read more »

Organize your life with Trello

We’re all leading very busy lives nowadays. There are people communicating with us from everywhere all the time, and there are always things you need to remember doing or need to get organized. Personally, with the little spare time a full time job and a household leaves me, I have a hard time keeping track of the side projects and creative things I want to be doing, which ultimately causes me to waste more of that spare time than I’d like.

I intended to do something about this whole problem, in the form of a side project: a todo-list managing web application where you could label todo items for priority, assign people, and so forth. I was pretty far into the website design and initial front-end coding when I first heard about Trello. It took me only a few days to realize that the people behind Trello had done a much better job of it than I ever would. I abandoned my own project shortly after.

So what is Trello?

Trello lets you organize “cards” in “lists”, on “boards”; that may sound a little bit abstract, so let’s expand a bit on that.

A board on Trello consists of one or more named lists. It is an environment where you keep track of a certain thing, collect information on a certain thing, or simply where you manage something. Where you keep something organized.

A “list” is no more than a named column where you keep a bunch of cards. Such a list can indicate the progress status of the items within, or it can be treated as a category. The purpose of a list depends entirely on what you are organizing.

A “card” can be anything you want it to be: a feature for a piece of software you’re working on, a book you want to read, a holiday destination you’re considering, you can come up with plenty more, I’m sure.

This screenshot gives a bit of an overview (full size):

Trello screenshot

Read more »

Music to listen to loudly with eyes closed

While I listen to music more or less all day while work and whatnot, I infrequently like to pick out some of my favourite songs, turn up the volume and just sit back and close my eyes, focussing only on the music.

There are some tracks which have the amazing quality to completely take over your awareness as you really get into them. Here are some that do that for me. They range from old hits to obscure stuff, from chill-out to hard rock, and are in no particular order.

1. The Extreme – Daydream

This wonderful chill-out tune has a deep bass-line that instantly drew me in the first time I heard it on Digitally Imported’s Chillout channel. The lush instrumentation accompanied by a perfectly fitting break beat later on takes you through a dreamland of relaxation. It is all over the place in a big mess of harmony.

Read more »

JavaScript forEach Object, Array, and String

In many programming languages, you have a simple for each construct available to quickly go over the contents of just about anything iterable. In JavaScript it isn’t so straightforward. To rectify this, I’ve written up a function that provides a single interface to iterate over the elements of an array, the values in an object, and “even” the characters in a string.

It works with a callback function that takes index/key and value as parameters. This callback function is executed for every item in the collection passed.

The benefit of using this is that you have very readable code; most programmers will intuitively know how it works because of the familiar collection, index and value interface.

To the code!

(function () {
    "use strict";

    /**
     * Iterate over an Object, Array of String with a given callBack function
     *
     * @param {Object|Array|String} collection
     * @param {Function} callBack
     * @return {Null}
     */
    function forEach(collection, callBack) {
        var i = 0, // Array and string iteration
            iMax = 0, // Collection length storage for loop initialisation
            key = '', // Object iteration
            collectionType = '';

        // Verify that callBack is a function
        if (typeof callBack !== "function") {
            throw new TypeError("forEach: callBack should be function, " +
              typeof callBack + " given.");
        }

        // Find out whether collection is array, string or object
        switch (Object.prototype.toString.call(collection)) {
          case "[object Array]":
              collectionType = "array";
              break;

          case "[object Object]":
              collectionType = "object";
              break;

          case "[object String]":
              collectionType = "string";
              break;

          default:
              collectionType = Object.prototype.toString.call(collection);
              throw new TypeError(
                "forEach: collection should be array, object or string, " +
                collectionType + " given.");
        }

        switch (collectionType) {
          case "array":
              for (i = 0, iMax = collection.length; i < iMax; i += 1) {
                  callBack(collection[i], i);
              }

              break;

          case "string":
              for (i = 0, iMax = collection.length; i < iMax; i += 1) {
                  callBack(collection.charAt(i), i);
              }

              break;

          case "object":
              for (key in collection) {
                  // Omit prototype chain properties and methods
                  if (collection.hasOwnProperty(key)) {
                      callBack(collection[key], key);
                  }
              }

              break;

          default:
              throw new Error(
              "Continuity error in forEach, this should not be possible.");
              break;
        }

        return null;
    }

    //Example uses

    // Array example
    forEach(["a", "b", "c"], function (value, index) {
        console.log(index + ": " + value);
    });

    // Object example
    forEach({"foo": "bar", "barfoo": "foobar"}, function (value, key) {
        console.log(key + ": " + value);
    });

    // String example
    forEach("Hello, world!", function (character, index) {
        console.log(index + ": " + character);
    });
}());

Read more »

Selectbox / dropdown replacements

The &lt;select&gt; element is hard to style properly and is something that easily ruins sleek designs. Many people have already realised this, which is why there are a couple of JavaScript replacements out there.

Here’s a quick list of those that I’m aware of—in no particular order.

This post is mostly as a reference, so I don’t need to look up all the options (no pun intended) every time this situation arises. I hope it can help you quickly select (pun definitely intended this time) which one’s best for you.

Update 05 April 2014: Removed “jQuery SelectBox plugin” as both links had died.