I have this 8×8 LED screen which I picked up a while ago. I’m going to hook this up to a Raspberry Pi and a D-pad and write games for it. Until I have the correct parts, I’m emulating the screen using HTML5 canvas.


Last night I wrote an implementation of Snake. I have a few more I wrote today which I’ll put on github.

An introduction to digital computing

This article is an introduction the basic concepts of digital computers.  I’ll cover how to do arithmetic on any numbers with just 1s and 0s, what a logic gate is, how to combine logic gates to do arithmetic and store the results. I’ll also show how logic gates can be implemented with electrical circuits. Finally I’ll introduce instructions and show how computers execute them.

The most fundamental operation in arithmetic is addition. We learned how to do long hand arithmetic as students in elementary school. We can add the numbers 27 and 15 as follows.


In the ones column, add 7+5 = 12. We put the 2 from the 1s place in the result and carry the 1 from the 10s place above the 10s column. To get the 10s digit of the result we then sum the carry digit (1) with 2 and 1 to get 4. The result is 42.

The above is called base 10 arithmetic because each digit can have one of 10 values (0 through 9). For reasons that will become obvious later, modern computers do not represent numbers in base 10. Instead they use what is called base 2 (or binary) arithmetic. In base 2, each digit can only have the value 0 or 1. Instead of each number having a 1’s place, 10’s place, 100’s place, etc, we use powers of 2, so we have the 1’s place, 2’s place, 4’s place, 8’s place, etc.

Here are the same numbers from above written in expanded base 10 and base 2 forms. See how you can use the same pattern to form the same numbers in each base?


Now let’s look at what the arithmetic would look like using base 2 numbers. Note that when we add 1+1 in base 2, the result is not 2, but rather 10. We put the 0 in the result row and carry the 1 to the next column.

Using the rules 1+0=1, 1+1=10, and 1+1+1=11, we can solve the previous arithmetic in base 2.


We’ll see these rules again in a few minutes.

The next fundamental subject in computation is logic gates. Logic gates represent devices (either mechanical or electronic) which can be used to carry out simple logic. And I mean really simple. The three simplest logic operators are AND, OR, and NOT.

Logic operators operate on variables (inputs or outputs). We conventionally allow a variable to be in either the TRUE or FALSE state. When we implement an electronic logic gate we call these states HIGH and LOW. You might have already guessed, but when we combine logic gates to perform computations, we consider these states to be 1 (TRUE) and 0 (FALSE).

The NOT operator is the simplest. It has one input and one output. The output is always the negation of the input. We can write this in a truth table. A truth table shows all combinations of inputs and outputs. Each row forms a true statement.

1 0
0 1

So, the first row means “NOT TRUE is FALSE”. The second row means “NOT FALSE is TRUE”. Simple stuff.

The AND operator has two inputs (called A and B) and one output. The AND operator’s output is FALSE unless both inputs are TRUE. If one input is TRUE and one is FALSE, the output is FALSE.

0 0 0
1 0 0
0 1 0
1 1 1

The OR operator also has two inputs and one output. When either input is TRUE, the output is also TRUE. When both inputs are FALSE, the output is FALSE.

0 0 0
1 0 1
0 1 1
1 1 1

Did you notice that when both inputs of the OR operator are TRUE, the output is also TRUE? There is a second type of OR operator for which this is not the case. The exclusive OR (written XOR) is TRUE only when one input is TRUE and one input is FALSE. This is a very useful operator.

0 0 0
1 0 1
0 1 1
1 1 0


These gates can be combined to form a few additional commonly used gates.

The NAND gate is a combination of and AND gate with a NOT gate on the output. This negates the output of the AND operation.

0 0 1
1 0 1
0 1 1
1 1 0

The two remaining gates are NOR (OR + NOT) and XNOR (XOR + NOT).

We can combine logic gates to perform what is called Boolean arithmetic. For example, the following is a statement in logic.


Sometimes it can be helpful to visually express logic statements. Here are the symbols typically used for logic gates. Inputs are on the left and outputs on the right.

Screen Shot 2015-09-03 at 9.59.42 PM

So the above statement can be represented graphically as follows.

The A and B inputs go to the AND gate. The C input goes into a NOT gate. The outputs of the AND and NOT gates go into the OR gate and the output of the OR gate is the result.

Let’s look at how we can combine logic gates to form a system of equations.

Let S = A XOR B
Let C = A AND B

This can be expressed graphically as:

Half Adder

Since both statements have the same input variables (A and B), we can write them in a unified truth table.

0 0 0 0
1 0 0 1
0 1 0 1
1 1 1 0

This table is equivalent to the statement A + B = C*2^1 + S*2^0. The right hand side of the equation should look familiar.

A + B = C*2 + S
0 + 0 =  0
1 + 0 =  1
0 + 1 =  1
1 + 1 = 10

This is base 2 arithmetic implemented in logic!

Now we don’t quite have enough power to solve the original problem I gave you. The above system is called the Half Adder. The half adder accepts two input values and outputs a sum and a carry value. In order to sum numbers with multiple digits, we need to be able the accept three inputs: A, B, and a carry from the previous column. The output will be the sum plus a carry, for a total of five variables. The system that can do this is called a Full Adder. It is implemented as follows:

Let S = A XOR B XOR Cin
Let Cout = (A AND B) OR (Cin AND (A XOR B))

Which can be expressed graphically as:

Full Adder

The truth table for the full adder is repetitive, but can be simplified to the statements:

0 + 0 =  0
0 + 1 =  1
1 + 1 = 10
  1 + 1 + 1 = 11

By chaining a series of full adders together (taking Cout from the previous adder as Cin on the next), we can carry out multiple digit binary arithmetic.

4 bit adder

(Image credit: Wikipedia)

The full adder is one of the primary building blocks of computers. Though tricks of notation and clever combinations with other gates, binary logic can also be made to perform subtraction, multiplication, division, and comparing numbers.

Logic gates can also be used to control other circuits based on a fixed set of rules. A good introductory logic system is the 7 segment LED found in clocks, radios, DVD players, and many other places. The logic controlling these displays converts a binary encoded number into 7 output signals which are used to turn on or off each segment of the display. There are 4 inputs representing the 4 binary digits necessary to represent 0 through 9. So for example, when the inputs are 0110 (meaning 6), the output of the gates will turn on all the segments except the top right one.



The basic idea behind designing these circuits is to start by writing a truth table for all possible relationships between the input and output variables, and then combining logic gates to create those values. Here the inputs are labeled A-D and the outputs a-d. The decimal point above is not included.

7 segment table

(Source: Texas Instruments

It can get complicated very quickly, though several techniques exist to find simplified truth tables. Here is what the complete 7 segment control system looks like. The blanking input is used to turn off all the outputs no matter what the other 4 inputs are. It’s very useful if you’d like to show a flashing digit.

7 segment

(Source: ibid)

This concept can be extended to any system that needs to turn other circuits on and off based on an input value.

Now that you’ve become familiar with logic gates as abstract concepts, let’s look at how we can implement them using electronic components.

There are many unique ways to build logic gates from electrical components, but the component of choice for modern computers is the transistor. The transistor is a type of semiconductor discovered at Bell Labs in the 1940’s. They have properties which can be used to amplify signals (like an audio amplifier) or to switch circuits on and off very quickly. They can also be made extremely tiny. A modern CPU contains several billion transistors etched on a wafer of silicon.


A transistor has three pins called the collector, base, and emitter. The base acts as a switch to turn on a circuit connecting the collector to the emitter. When a LOW signal is sent to the base, the collector-emitter switch is off. But when a HIGH signal is sent to the base, the collector-emitter switch is on.

Transistor Switch

The other component used in these circuits is a resistor. The purpose of a resistor is to limit the flow of current so the circuit does not short out and burn up or catch fire! You must have a resistor between a HIGH point and a LOW point in a circuit, but just because a circuit has a resistor does not mean it changes a HIGH signal into a LOW one.


Each gate circuit has a HIGH source, LOW source, at least one input, and one output. We can understand how the input affects the output by looking at the complete or incomplete circuits made by the transistor switches.

Here is a resistor-transistor implementation of a NOT gate. You can ignore the resistor on the input line. It’s purpose is to protect the transistor from burning out.

NOT Gate

When the input is LOW, the transistor switch is off, breaking the connection between the resistor and the LOW source. The resulting circuit looks like this:


There is a complete circuit only from HIGH to output, so the output is HIGH. The LOW signal is disconnected from everything since no signal can pass through an open switch.

When the input is HIGH, the transistor switch is closed. In this case we have to consider the placement of the output pin relative to the resistor because one side of the resistor has a HIGH signal and the other side is LOW. The output pin is on the LOW side of the resistor so the output will be LOW.


Next let’s look at the AND gate.

AND Gate

When A or B (or both) are LOW, there is an open switch between HIGH and the resistor, thus the remaining circuit only connects output to LOW so the output is LOW. When both A and B are HIGH, then both switches are closed, connecting HIGH to the resistor. Since the output pin is on the HIGH side of the resistor, the output will be HIGH. This behavior matches the truth table shown earlier.

Similar circuits can be made for each gate. Here are schematics for the OR and NAND gates. Note that the crossed lines in the OR gate only indicate a connection if there is a dot. Doesn’t NAND look a lot like AND? Try tracing the signals through these circuits.

OR Gate

OR Gate



Everything we’ve looked at so far is called combinatorial logic. Combinatorial logic allows us to perform addition, multiplication, and turn circuit components on and off, but there is another critical function computers need. The logic gates demonstrated above only provide an output as long as an input state is provided. The input may correspond to a button press or to a value stored in the computer’s memory. But how can the computer remember a key was pressed after the key is released, and how can computers remember numbers at all? The key to computer memory is a special combination of logic gates called the flip flop.

A flip flop is a pair of coupled NOR gates which feed the output of each gate into an input of the other gate. The two remaining inputs are conventionally called Set (S) and Reset (R). Once a HIGH signal is sent to SET, the flip flop’s output will output HIGH continuously, even after the HIGH signal is removed from SET. This is called a bistable circuit because the output does not depend on an input signal being provided. When a HIGH signal is sent to the Reset input, the output state will go to the LOW state and remain there until a HIGH signal is received on the Set input.


Flip Flop

In a computer, flip flops (called registers in a CPU) sit in between groups of logic gates to act as a buffer for the results from each step of a computation. Setting and resetting of the flip flops occurs at a regular interval which is driven by a clock signal, a system-wide alternating pulse of HIGH and LOW signals. In a modern computer, the clock cycles more than a billion times per second!

So how do we get from gates and flip flops to a programmable computer?

Computers are different from fixed logic devices such as clocks because they can execute instructions written after the circuit is built. They can do this because internally they contain many separate circuits which can carry out fixed operations such as addition, multiplication, comparing numbers, and copying numbers between registers. These circuits are turned on and off by some control circuitry based on coded instructions stored in the instruction registers. The whole process is timed based on the computer’s central clock.

Here is a simple computer architecture. It’s called the Von Neumann architecture and it’s used by most computers today.

Von Neumann

  • Instructions: This is an array of registers which hold coded instructions for the computer to follow. Each instruction is coded as number.
  • Instruction pointer: This is a register which tells the CPU the address of the next instruction to execute. Each time the computer reads an instruction, it increments this value by 1 so it knows to read the next instruction on the next clock cycle.
  • Controller: This decodes the current instruction from the instruction registers and activates the other circuitry to execute the hardwired logic for that instruction, much like the LED logic shown earlier.
  • Arithmetic logic unit (ALU): This contains the logic circuits that can carry out mathematical operations.
  • Logic registers (AX, BX, CX, DX): These are registers which can be accessed by the ALU. It is much faster to access a register than main memory. Registers are referred to by their name when writing instructions.
  • Main memory/system bus: This lets the CPU talk to the main memory or other devices attached to the computer like a keyboard, mouse, monitor, or network port. Numbers stored in memory must be copied to a register before they can be used by the ALU. Only a few registers are available, but memory can hold up to billions of values.

The instructions that a computer can follow are very simple. Here are enough instructions (with arguments written in parentheses) to write simple programs.

  • INPUT (register, address)
    • Copies the value stored at address in the main memory and copies it to the named register.
  • OUTPUT (address, register)
    • Copies the value in the named register to the specified main memory address.
  • SET (register, value)
    • Sets the named register to the specified value.
  • ADD (register1, register2)
    • Adds the values of register1 and register2 and stores the result in register1.
  • JUMP (line_number)
    • Changes the instruction pointer’s value to line_number.
  • COMPARE-JUMP (register, value, line_number)
    • Compares the value in the named register with the specified value. If they are equal, it changes the instruction pointer’s value to line_number. This lets a program change the order of execution of instructions in response to input data.
  • HALT
    • Indicates that this is the last instruction. Stop. Early computers would ring a bell or beep to let the user know they were finished.

Let’s use these instructions to write a program that can add up a long series of numbers. I’ll make two assumptions about the input.

  1. The first number of the input will be the total number of items in the input.
  2. Some process which we don’t care about writes the numbers into the computer’s memory. This could be copying from a file, the internet, or a user manually typing them in.

Here is what the computer’s memory will look like before the program runs. I only included three numbers for brevity, but this could be anywhere from zero numbers to millions, limited only by how big the computer’s memory is.

Address Value
1000 3
1001 183
1002 492
1003 266

In the program, I use all four available registers. I use each register for a specific purpose.

  • AX = the running total of the list (called the “accumulator”)
  • BX = the next memory address to read
  • CX = counter for how many more memory address to read
  • DX = register to load the current list value into

The basic structure of the program is some setup code, followed by a loop which does the summing of the list, and finally writing the result to main memory. The main loop structure is created by using two COMPARE-JUMP and JUMP instructions. The COMPARE-JUMP decides when to leave the loop. The JUMP instruction restarts the loop at the end.

Here is the program code:

1 SET BX, 1000 Store the starting memory location in register BX
2 INPUT CX, BX Copy first memory location to counter register (CX)
3 ADD BX, 1 Increment BX to next memory address
4 INPUT AX, 0 Initialize an accumulator register (AX) to 0
5 COMPARE-JUMP CX, 0, 11 If the counter equals zero, jump to instruction 11
6 INPUT DX, BX Copy the number to add to register DX
7 ADD AX, DX Add DX to the accumulator register AX
8 ADD BX, 1 Increment BX to next memory address
9 ADD CX, -1 Decrement the counter register CX
10 JUMP 5 Go to instruction 5
11 OUTPUT BX, AX Copy the accumulator register to main memory

Raw computer instructions can be difficult to understand. Most programs are written in a more expressive format and then converted to computer instructions by another program called a compiler. In pseudocode the above instructions would look like:

int address = 1000;
int counter = list [ address ]; // read from list
address = address + 1;
int sum = 0;
while(counter > 0)
	int value = read [ address ];
	sum = sum + value;
	address = address + 1;
	counter = count - 1;
list [ address ] = sum; // write to list


I assembled the following table showing how the computer’s registers change with each instruction. Notice that only one register changes in each instruction. (With the exception of the instruction pointer which always increments unless there was a jump instruction.)

1 SET BX, 1000 1000 2
2 INPUT CX, BX 1000 3 3
3 ADD BX, 1 1001 3 4
4 INPUT AX, 0 0 1001 3 5
5 COMPARE-JUMP CX, 0, 11 0 1001 3 6 No jump
6 INPUT DX, BX 0 1001 3 183 7
7 ADD AX, DX 183 1001 3 183 8
8 ADD BX, 1 183 1002 3 183 9
9 ADD CX, -1 183 1002 2 183 10
10 JUMP 5 183 1002 2 183 5 Jump
5 COMPARE-JUMP CX, 0, 11 183 1002 2 183 6 No jump
6 INPUT DX, BX 183 1002 2 492 7
7 ADD AX, DX 675 1002 2 492 8
8 ADD BX, 1 675 1003 2 492 9
9 ADD CX, -1 675 1003 1 492 10
10 JUMP 5 675 1003 1 492 5 Jump
5 COMPARE-JUMP CX, 0, 11 675 1003 1 492 6 No jump
6 INPUT DX, BX 675 1003 1 266 7
7 ADD AX, DX 941 1003 1 266 8
8 ADD BX, 1 941 1004 1 266 9
9 ADD CX, -1 941 1004 0 266 10
10 JUMP 5 941 1004 0 266 5 Jump
5 COMPARE-JUMP CX, 0, 11 941 1004 0 266 11 Jump
11 OUTPUT BX, AX 941 1004 0 266 12 Write 941 to main memory at address 1004
12 HALT 941 1004 0 266 Done

The output of the program is 183 + 492 + 266 = 941.

So that’s it. I hope this gave you some insight to how computers work. Of course I brushed over many of the complexities. I did not cover how to do multiplication or division, or how to represent negative numbers (there’s a very elegant way to do this called two’s complement), or how to compare numbers with logic gates. The model of the transistor I presented is very simple and does not account for power consumption or chaining multiple gates together. Within the computer’s logic there are more complicated structures as well such as clocked flip flops, 3-state gates, counters, dividers, multiplexers, and comparators. These are all topics beyond an introductory post, but none are too difficult to understand.

If this is a topic that interests you and you’d like to learn more, check out this free online course from MIT.

Flipping a sprite in DirectX

I have a sprite which faces to the right. I wanted to make it face left when moving left. After reading a dozen-plus forum threads without finding an answer, I’m posting this for reference. I’m a DirectX noob so this may not be the best solution, but it worked for me.

D3DXVECTOR2 position(caveman.x, caveman.y);
D3DXVECTOR2 spriteCenter(caveman.width / 2.0f, caveman.height / 2.0f);
D3DXVECTOR2 scaling(caveman.faceLeft ? -1 : 1, 1);
D3DXMATRIX matrix;
D3DXMatrixTransformation2D(&matrix, &spriteCenter, 0, &scaling, NULL, 0, &position);

Also, you will need to turn off culling on your DirectX device object.

d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);

A DSL for testing cash registers

I’m kicking around an idea for a DSL for testing cash register transactions. My goal is for it to be simple enough that someone without a programming background could verify the test scenarios. To do that, I’m drawing inspiration from something that everyone at my employer is familiar with–receipts. The test input will look like a register receipt and the output will be another receipt with an expected and actual column.

test "Product at retail":
	item		"123"

	subtotal	50.00
	tax		 3.75
	total		53.75

This is just plain text in a file. You can also declare products, tender types, discounts, tax rates, etc in the same file to include them in a test. The entire DSL is declarative. For example, here I’m declaring an item before the discount it uses.

	sku		"234"
	retail		10.00
	discounts	"bogo"

	name		"bogo"
	buy		1
	getFree		1

test "Item with BOGO":
	item		"234", 2    // qty = 2
	subtotal	10.00
	tax		 0.75
	total		10.75

The output of these tests is intended to look like another receipt.

Passed “Item at retail”

SKU                         Qty      Total
-------------------- ---------- ----------
123                        1.00      50.00

                       Expected     Actual
                     ---------- ----------
            Subtotal      50.00      50.00
           Discounts       0.00       0.00
               Taxes       3.75       3.75
               Total      53.75      53.75

FAILED “Item with BOGO”

SKU                         Qty      Total
-------------------- ---------- ----------
234                        2.00      20.00 
   bogo                             -10.00

                       Expected     Actual
                     ---------- ----------
            Subtotal      10.00      10.00
           Discounts       0.00       0.00
               Taxes       0.75       1.50 ***  // bug: tax applied on retail price
               Total      10.75      11.50 ***

The ***s indicate lines which failed the expectations. A future extension to the DSL may allow you to set expectations on discounts individually.

To pull this off, I leveraged RhinoDSL from Ayende Rahien. RhinoDSL is a tool for creating DSLs in Boo, a minimalist and very flexible .NET language which plays nicely with C# applications. I started from the OrderDSL sample and added a method for each keyword. When compiled, the tests look more like the following C# code:

public class TestScenario : BaseOrderDSL
	public override void Prepare()
		Test("item with bogo", () => {
			Item(“123”, 2);

All the methods called are declared in BaseOrderDSL. The Execute() method provided by the base class transforms the test objects into domain objects and passes them to the application. The receipt output is generated by a bunch of string.Format() calls using the pad left/right string formatters (eg: {1,10:N2}). In all it’s only about 300 lines of code, and most of that is just ceremony for wiring up keywords.

If you’d like to learn more about writing DSLs in .NET applications, I’d recommend picking up a copy of Ayende’s book DSLs in Boo.

Rules for custom software

  1. Custom software should enable your core business. There are countless software packages on the market serving common business functions. It makes no sense to invest in expensive custom software if it is not driving your bottom line. Successful custom software projects will enable your business to do more of what it does best. A consultant should help you evaluate where using custom software makes sense and offer off-the-shelf alternatives if an appropriate solution already exists.
  2. Custom software pays for itself. You should be able to quantify your expected ROI before signing a development contract. In some cases this is easy to do: software that increases throughput, helps win additional business, or directly generates revenue in some other way can easily prove it’s worth. In some cases the payoff of software is less visible: reduction of employee time spent on overhead tasks, elimination of human error, or even increased employee morale can all result from better software. I believe a successful project should deliver at least 3X ROI in the first year after implementation.
  3. If you’re being charged by the hour, run like hell. There is an Ed Kless quote I really like: “If you aren’t good at what you do, charge by the hour.” A qualified developer who is genuinely interested in your business’s success will take the time to understand your situation, identify potential roadblocks, and design an effective solution that fits your budget. Based on their past experience they will be able to provide an accurate quote or fixed price agreement for the project.
  4. Custom software requires maintenance. Just like Microsoft regularly releases updates to Windows and Office, custom software also requires periodic care to address bug fixes, changes in business processes, and changes in 3rd party APIs. As part of a development contract, your software provider should provide a retainer to address issues such as bug fixes or user support questions. Information about future maintenance costs should be included as part of buyer education before you sign a contract.
  5. Custom software should be agile. It’s all too common that a consultant shows up, listens to your problems, and then disappears for months to code up a solution. When they return, it’s inevitable that somewhere there was a miscommunication and the software does not exactly fit your business. Efforts to modify the software result in expensive change orders. A reputable consultant should engage the buyer and end users regularly during the development cycle to discover misunderstandings as quickly as possible. Minor changes which do not affect the development schedule should not incur additional cost.

Installing Meteor

These instructions will assume you are running Mac OS.

Getting started with Meteor is very simple. Everything can be installed from the command line.

Install Node

You can download node by going to and clicking Install.

Launch Terminal

Find Terminal in your Applications folder and run it. You’ll use this a lot so pin it to the dock.

Install Meteor

At the terminal prompt, type

$ curl | sh

That’s it!

Install an editor

I’ll probably be trying out several different editors, but to get started I’m using Atom.

Install Git

I use git and GitHub for source control. You can get an installer from I won’t go into detail about Git. There are about 10,000 tutorials already. I recommend the GitHub tutorial.

In the next post we’ll create the default Meteor project and walk through each line of code.

Hello Meteor!

After 10 years in .NET land, I’m trying out something a bit different. I’ve been watching Meteor since the original announcement, but this is my first dive in. There are several things I’m really excited about in Meteor:

  • easy real-time collaborative UIs
  • reactive HTML templates
  • MongoDB
  • the active community

My background includes ASP.NET WebForms and about 5 years with ASP.NET MVC. I’ve been using REST/JSON APIs and Knockout extensively for the past several years, but never dove into real-time applications. I’m already quite familiar with MongoDB so when I started looking for a framework for quickly mocking up applications, Meteor jumped out as a great fit.

In this blog, I’ll be writing about my experience with Meteor, writing how-tos, and hopefully contributing something useful back to the community. I was inspired to start writing by Ciara’s intro post at Meteor Academy. I hope I can get some constructive feedback as I experiment with application architecture and become more familiar with the Meteor paradigm.

Let’s get started!