Build a CPU from virtual transistors – Part 2 – Relay

Nevertoooldtocode implements the first actual component, an electrically controlled switch, or relay
A relay is simply a switch – like a light switch – that you can turn on and off using electricity. This concept is the building block of all digital electronics. In actual electronics relays aren’t used anymore, but rather transistors, which basically are the same, except much smaller, faster, and cheaper.

Here is a relay that is “off”:

The “control” input determines whether the electro-magnet attracts the moving slanted line or not. In this case the magnet gets nu current from “control” and therefore the current coming in at “in” gets directed to the bottom output interface “Q-bar”.

Now we put a current on “control” thereby switching the relay on:

The truth table will look like this:

In Control Q Q-bar
1 0 0 1
1 1 1 0
0 0 0 0
0 1 0 0

Here’s the code:

Note that the relay% class is a subclass of basic-element% . Also note that the (process) method overrides the dummy method in the basic-element% parent class. cond is the Racket/LISP conditional statement.

It is convenient to initialize the input and output interfaces to standard values anytime an object is created. Rather than have four lines (one for each interface), I’ve condensed them into two lines, using two initialization functions from the parent class. These look like this:

Unit Testing

We also want to include automatic unit testing. Suppose we want to change something in the implementation later on, we will know immediately if it breaks something that worked before.

Racket has a module Rackunit, that is written for this. It is convenient to use this in a
(module+ test ... statement for two reasons:

  • All (module+ test ... statements are treated together as a whole, even if they are spread throughout the program
  • If the file is included in a larger program, the (module+ test ... statements are not included

The test function we are using looks like this:

Notice we require the rackunit module:

The test function spends some time setting up for the key statement:

which only generates output if something’s wrong, i.e. if the predicted values are *not* equal to the claculated values.

The test function is called like this:

We have tested for all four possible combinations of input!

Now we have set this testing infrastructure up, it is easy to extend it for each newly added component, as we will see in the following episodes!

Leave a Reply

Your email address will not be published. Required fields are marked *