Monday, September 26, 2011

Digital Design

Web Based Digital Design


This is the first of what I hope to be several posts related to building a web-based digital design tool. Today I wrote some basic logic operation in terms of "nor" gates.



var logic = {
    nop: function (a) {
        return a;
    },
    nor: function (a, b) {
        return (a | b) ? 0 : 1;
    },
    not: function (a) {
        return this.nor(a, a);
    },
    or: function (a, b) {
        return this.not(this.nor(a, b));
    },
    nand: function (a, b) {
        return this.or(this.not(a), this.not(b));
    },
    and: function (a, b) {
        return this.nor(this.not(a), this.not(b));
    },
    xnor: function (a, b) {
        return this.or(this.and(a, b), this.and(this.not(a), this.not(b)));
    },
    xor: function (a, b) {
        return this.or(this.and(a, this.not(b)), this.and(this.not(a), b));
    }
};

I then defined a gate constructor



var gate = (function () {

    function tick(op, input) {
        this.value = this.next;
        var params = [];
        for (var i = 0; i < input.length; i++) {
            params[i] = input[i].value;
        }
        this.next = op.apply(logic, params);
    }

    return function (opName, input) {
        var that = this;
        clock.hook(function () { tick.call(that, logic[opName], input); });
    }

}).call();

I then created a small test



(function () {
    var zero = { value: 0 };
    var one = { value: 1 };
    var input = [zero, one];
    var g1 = new gate("xor", input);
    var g2 = new gate("and", [g1, input[1]]);
    clock.tick();
    clock.tick();
    assert(g1.value == 1, "0 xor 1");
    clock.tick();
    assert(g2.value == 1, "1 and 1");
    input[0] = one;
    clock.tick();
    clock.tick();
    assert(g1.value == 0, "1 xor 1");
    clock.tick();
    assert(g2.value == 0, "0 and 1");
}).call();

For the time being my clock looks like this



var clock = {
    tick: function () { },
    hook: function (callback) {
        var tick = this.tick;
        this.tick = function () {
            tick();
            callback();
        };
    }
};

Next step is to construct a more robust test by building a JK flip-flop circuit and then a counter.

No comments:

Post a Comment