Introduction to computers — theory with a photo of the whiteboard, the Von Neumann architecture, the instruction cycle and a hello world that goes down 7 floors (and the «zero» computers I was carrying)
First Computer Engineering I (IC1) class. The lecturer puts the chalk down, turns around and asks: «How many computers are you carrying right now?». Very sure of myself, I answer: «None, I left my laptop at home». Half the room laughs. In my pocket I had a phone (a computer), on my wrist a watch with a heart-rate sensor (another one), wireless earbuds with a chip inside (one more) and, in my wallet, the bus card with its microchip. That day I learnt that a computer is not «the box with a keyboard»: it is any machine that takes in data, processes it following a program stored inside it and gives back a result.
This is the first topic of the paper part of Computer Engineering I (IC1): what lies underneath everything you programmed in MIPS. We will see what a computer is, what parts it has, how those parts talk to each other (buses), how it runs an instruction step by step and how it represents information with electrical signals. So that it does not stay abstract, the whole topic revolves around something you do every day: taking a photo of the whiteboard with your phone at the end of class. Afterwards, in the practice we solve the typical problems step by step, and in the exercises it is your turn. If you have already done the MIPS topics (for example, MIPS program structure and data), many pieces will sound familiar.
Table of Contents
Before you start. You do not need anything beforehand for this topic. If you have already programmed in MIPS it will help, but it is not essential. Numbers like 1A20 or 0040 are in hexadecimal, which is explained in the next topic; whenever it matters, you will have their decimal value next to them. The topic has two halves, in this order: first, the computer on the inside (what it is, what kinds there are, the Von Neumann idea, its components, memory, buses and how it runs an instruction); then, how it stores information with electricity (analogue and digital, bits, logic levels, pulses and the clock). If you get lost at any point, go back to the photo of the whiteboard and ask yourself who is working at that moment: the whole topic can be told with it.
What a computer is
The definition from the course notes, in our own words, is this:
A computer is a machine able to accept input data, process it (perform arithmetic and logic operations on it) and deliver the resulting information through an output medium, autonomously or with little human intervention, under the control of a program of instructions previously stored in the computer itself.
Read it again slowly, because every piece matters:
- Accept input data: the light coming in through the camera lens.
- Process it: the phone adjusts brightness, focuses, compresses the image. All of that is additions, comparisons and bit operations.
- Deliver the result through an output medium: the photo appears on the screen and is saved in the gallery.
- Autonomously: you press a button and that is it; you do not tell it what to do pixel by pixel.
- Under the control of a stored program: the camera app is stored inside the phone before you press. Without that program, the phone would not know what to do with the light.
Why insist on the stored program? Because it is what separates a computer from an old calculator or a garage remote: those devices always do the same thing. A computer does whatever the program it has loaded says, and that program can be changed.
Spanish speakers say «ordenador» in Spain and «computadora» in Latin America; the course notes and the exam say «computador». It is all the same thing.
Hardware and software
A computer has two halves that are useless without each other:
- Hardware: the physical part, what you can touch. In the phone: the processor, the memory, the camera sensor, the screen, the battery.
- Software: the logical elements (programs and data) that give the hardware the ability to carry out a task automatically.
Software, in turn, splits into three groups. Look at the diagram:
- System software: what the hardware needs in order to work, plus utilities to use it and make the most of its resources. The operating system and the drivers (for example, the one that knows how to talk to the camera sensor).
- User applications: what you use to do tasks: the camera, the gallery, messaging, an office suite.
- Developer software: what is used to create new programs: editors, compilers, debuggers. Notepad++ and QtSpim from the MIPS labs go here.
Saying the operating system is an «application». No: it is system software. A user application needs the operating system to run; the operating system does not need the application.
Kinds of computers
By what they are used for (their requirements), the notes classify them into three:
| Kind | What it is designed for | Examples | In the whiteboard photo |
|---|---|---|---|
| Personal (PC) | Individual use | Desktop, laptop, tablet, phone | The phone taking the photo |
| Server | Heavy workload: many users, complex applications | Web and mail servers, supercomputers | The cloud server where the photo backup is stored |
| Embedded | One specific job, inside another device | Car, router, Internet of Things | The chip focusing the camera; the one in the fast charger |
The curious thing is that a single photo goes through all three kinds. And notice a detail in the notes: the phone appears as an example of a personal computer and of an embedded one. It is not a typo: the phone as a whole is a PC, but inside it carries several embedded computers (the modem’s, the camera’s…), each with its own program.
To classify, ask yourself who it works for and how many different things it can do. One person and many tasks: personal. Many people at once: server. A single task hidden inside another device: embedded.
The four functions and the Von Neumann architecture
Every computer does only four basic things:
- Process data: operate on it (raise the brightness of a pixel).
- Store data: keep it for a while or for good (the photo in RAM while you edit it; in the gallery afterwards).
- Transfer data: move it between the computer and its surroundings (light comes in, the image goes out to the screen or the cloud).
- Control: decide which of the other three happens at each moment and in what order.
Almost every computer today follows the Von Neumann architecture (after the mathematician John von Neumann, who described it in 1945). Its features are:
- A single memory with a linear structure: a row of numbered positions (addresses), one after another.
- Binary representation: everything inside memory is zeros and ones.
- No explicit distinction between instructions and data: both are binary words in the same memory. That is the stored program: instructions, data and partial and final results live together.
- Sequential execution: instructions run one after another, in the order they sit in memory.
- The sequence can be broken: with jump instructions, which change which instruction comes next.
Look at the memory in the diagram. At addresses 100 to 103 there are instructions; at A20 to A22, data (the brightness of a pixel of the photo, how much we raise it and the slot for the result). If I give you only the word 0040, is it an instruction or data? There is no way to tell by looking at it: it depends on whether the CPU reaches it while looking for the next instruction or because an instruction asked it for data. That is the beauty (and the danger) of Von Neumann.
You have already seen this in MIPS: in QtSpim, the text segment (instructions) and the data segment live in the same memory, just at different addresses (0x00400000 and 0x10010000). Review it in MIPS program structure and data.
The components of a computer
Structurally, a computer has five components:
| Component | What it does | Grouped into… |
|---|---|---|
| Control unit | Interprets instructions and tells the rest what to do at each moment | CPU (processor) |
| Datapath | Performs the operations on the data (additions, comparisons…) | CPU (processor) |
| Memory | Stores programs and data | — |
| Input | Brings data in from outside | I/O system |
| Output | Sends results out | I/O system |
And they are all connected through the interconnection bus, which we will see shortly.
The five components, in the whiteboard photo
Names on their own do not stick. Follow the whiteboard photo from the moment you tap the button until you see it on the screen, and ask yourself at each moment which component is working:
| Moment | Component | Why that one |
|---|---|---|
| You tap the shutter button | Input (the touchscreen) | It brings data in from outside: where you tapped |
| The camera sensor picks up the light | Input (the camera) | It turns the light from the whiteboard into data the computer can store |
| The camera app says what to do with that data | Control unit | It reads the app’s instructions, one by one, and gives the orders; it does not do any calculation itself |
| The brightness is raised and the photo is compressed | Datapath | It is the part that adds, compares and operates on the data |
| The app and the photo are stored in the meantime | Memory | It holds the program (the app) and the data (the photo) at the same time |
| The photo appears on the screen | Output (the screen) | It sends the result out |
The screen shows up twice, as input and as output: the same device can do both. And the control unit and the datapath always work together, but one decides what has to be done and the other does it; that is why the notes keep them apart even though both are inside the CPU. Every time something passes from one component to another, it travels over the bus.
Inside the CPU
The CPU (Central Processing Unit) or processor is what executes instructions. Inside it has:
- Datapath: the part that operates on data. It is like the kitchen: it has the utensils (the ALU that adds and compares) and the corridors along which the ingredients move.
- Control unit: the head chef. It does not cook, but it tells each unit what to do at every moment.
- Internal memory:
- Registers: the fastest and smallest level of memory. In MIPS there were 32 (
$t0,$s0…). - Cache memory (one or several levels): keeps copies of the data and instructions most likely to be used soon.
Saying the CPU has «three components: control unit, datapath and memory». Main memory is another component, outside the CPU. What the CPU has inside are registers and cache, which are internal memory.
The memory hierarchy
The ideal would be a huge, very fast and cheap memory. It does not exist: fast memory is expensive and small, big memory is slow. The solution is to organise memory in levels so that the user gets the impression of a memory that is big, fast and cheap at the same time.
| Level | Where it is | What it is like | In the whiteboard photo |
|---|---|---|---|
| Registers | Inside the CPU | Fastest and most expensive; very few | The value of the pixel being added right now |
| Cache | On the processor chip, in several levels | Slower than registers, bigger; faster than main memory | The row of the photo the filter is going through |
| Main memory (RAM) | Outside the CPU | Gigabytes; erased when powered off | The whole photo while you edit it |
| Secondary memory | Disks, flash memory, USB | Slowest, cheapest and biggest; not erased | The photo already saved in the gallery |
The times in the diagram are rough orders of magnitude, not exact values for a specific phone: what matters is that each level is quite a lot slower than the one above. In the cache topic we will measure it for real.
In the operating systems part of IC2 you already saw the hierarchy from the operating system’s point of view: interrupts and memory hierarchy. Here we look at it from the hardware side.
How the trick works: copies between levels
«Giving the impression of a memory that is big, fast and cheap» hides the trick behind the whole hierarchy: each level keeps a copy of a small piece of the level below, exactly the piece being used. Follow it with the photo:
- The photo is in the gallery, in secondary memory: it is not erased when powered off, but it is the slowest.
- When you open it in the editor, it is copied to main memory (RAM). Now there are two copies.
- The filter starts going through row 3. The pixels in that area are copied to the cache, because RAM is still slow for the CPU.
- To add a specific pixel, its value is copied to a register, which is the only place where the datapath operates.
- The result makes the journey back: from the register to the cache, from there to RAM and, when you tap save, to the gallery.
When the CPU needs a piece of data, it looks for it at the top first. If it is in the cache, it gets it straight away; if it is not, it has to go down to RAM for it and, while it is there, it brings up a copy of that piece of data and of the ones next to it, in case it asks for them later. And why is what it needs almost always at the top? Because of the principle of locality, the next section.
Check you’ve got it: why isn’t all of the phone’s memory built with the technology of the registers, which is the fastest?
For two reasons that are already in the table. Fast memory is expensive and small: with that technology, the gigabytes of the gallery would cost a fortune and would not fit on the chip. And registers, cache and RAM are erased when powered off, so the photo would still need secondary memory. The hierarchy is the way to get almost the speed of the top with almost the capacity and the price of the bottom.
The principle of locality
Why does having a little fast memory and a lot of slow memory work? Because of the principle of locality: at any given moment, programs tend to work with a small subset of all their data. If that subset is in the registers and the cache, most memory accesses avoid going all the way to main memory, which is slow.
Think of a filter that smooths the photo: it walks along row 3, pixel by pixel, and for each one it looks at its neighbours. During that time it only uses a few pieces of data (the yellow ones), it uses them several times and they are close together. Copying them to the cache pays off.
Those two ideas have names (we will use them in the cache topics):
- Temporal locality: what you have just used you will use again soon (the counter of a loop).
- Spatial locality: if you use a piece of data, you will soon use the ones next to it in memory (the elements of an array).
With both ideas at hand, go back to the filter on row 3: it goes through the pixels one by one and, for each one, looks at the one on its left and the one on its right.
Check you’ve got it: in that filter, which kind of locality is each of these three things? (a) moving from pixel 7 to pixel 8 you need pixel 9; (b) you already used pixel 8 as a neighbour of pixel 7 and now you use it again; (c) the loop counter that moves from one pixel to the next.
(a) It is spatial locality: pixel 9 is right next to pixel 8 in memory, and that is why, when the cache brings in pixel 8, it is worth bringing in the ones next to it too. (b) It is temporal locality: the same piece of data is used several times in a short time (as a neighbour of 7, as the center and then as a neighbour of 9). (c) It is also temporal: the counter is read and changed on every turn of the loop. If in doubt: the same data repeated, temporal; neighbouring data, spatial.
Input/output: devices and controllers
The input/output system is the devices that let the computer bring data in and send it out, plus the interfaces that allow talking to them, called controllers. The CPU does not talk directly to the camera sensor: it talks to its controller, which knows how that device works.
By function, devices are:
| Kind | What it does | On the phone |
|---|---|---|
| Input | Brings data in | Camera, microphone, touch screen (when touched) |
| Output | Sends data out | Screen, speaker, vibration |
| Storage | Keeps data permanently | The flash memory holding the gallery, a microSD card |
The touch screen is input and output at the same time: it shows you the photo (output) and picks up where you touch (input). In the exam, if a device does both, say so.
Buses: how the components talk
The components are connected through buses. A bus is nothing more than a set of electrical conductors (wires or circuit tracks) shared by several components. There are three groups of lines:
- Address lines: say where: which memory or I/O position is to be read or written.
- Data lines: carry what: the data or instruction travelling.
- Control lines: say what to do and when: read or write, the clock signal, notifications (interrupts).
An example: to read the brightness of the pixel at address A20, the CPU puts A20 on the address lines, activates «read» on the control lines, and memory answers by putting 0040 on the data lines.
The same bus is also used to bring in instructions and to write results; the only thing that changes is what goes on each group of lines and who puts it there. With the brightness program, which you will see in full further down:
| Lines | Fetching the instruction at 100 | Reading the data at A20 | Writing the result to A22 | Why |
|---|---|---|---|---|
| Address | 100 (put there by the CPU) | A20 (put there by the CPU) | A22 (put there by the CPU) | The one who decides where to read or write is always the CPU |
| Control | «read» | «read» | «write» | It tells memory what to do with that address |
| Data | 1A20 (put there by memory) | 0040 (put there by memory) | 0058 (put there by the CPU) | Data travels both ways: when reading it goes up to the CPU; when writing, down to memory |
Look at the first column: for the bus, fetching an instruction is exactly the same as reading data. Memory does not know whether what it hands over is one thing or the other; that is Von Neumann again.
One slide of the course notes says there are «memory, data and control buses»; the drawing on that same slide and on the next one says address, data and control. The right answer is address, data and control.
How an instruction is executed
You already know the program is in memory. How does the CPU run it? By repeating two phases non-stop, until an instruction halts it:
The registers involved
To understand the cycle you need four special CPU registers (plus the accumulator of our example machine):
| Register | Name | What it is for |
|---|---|---|
| PC | Program counter | Holds the address of the next instruction |
| IR | Instruction register | Holds the instruction being executed |
| MAR | Memory address register | The address the CPU puts on the bus to read or write |
| MBR | Memory buffer register | The data coming from memory or going to it |
| AC | Accumulator (in our example machine) | Where the arithmetic happens |
The drawing in the notes also shows I/O AR and I/O BR: they are the same as MAR and MBR, but for talking to an input/output module.
Phase 1: fetch
- The CPU copies PC into MAR:
MAR ← PC. - Memory returns what is at that address, which arrives in MBR:
MBR ← M[MAR]. - The instruction moves to IR:
IR ← MBR. - PC is updated to point to the next instruction:
PC ← PC + 1.
Fetch is always the same, whatever the instruction. Look at step 4: PC is incremented before executing. That is why, while an instruction is running, PC already points to the next one.
The same fetch, with numbers. At the start, PC holds 100, the address of the first instruction of the brightness program (you will see it in full in the complete example):
| Step | Operation | After the step | Why |
|---|---|---|---|
| 1 | MAR ← PC | MAR = 100 | Memory only pays attention to the address in MAR, which is the register connected to the address lines of the bus |
| 2 | MBR ← M[MAR] | MBR = 1A20 | What memory returns arrives over the data lines and goes into MBR |
| 3 | IR ← MBR | IR = 1A20 | MBR is going to be used again during execution; the instruction is kept in IR so the control unit has it at hand while it runs it |
| 4 | PC ← PC + 1 | PC = 101 | The instruction is already inside; PC moves on to point to the next one |
Why so many intermediate registers? Because during execution the bus is used for other addresses (the data address, A20), and PC cannot be touched for that: it has to keep holding where the next instruction is. MAR talks to the address lines and MBR to the data lines; PC and IR stay still, holding their own values.
In our toy machine PC adds 1 because each instruction takes up a single memory position. In MIPS it added 4 because there each address is one byte and each instruction takes up 4 bytes. The idea is the same: point to the next instruction.
Phase 2: execute
It depends on the instruction. The notes distinguish five kinds:
| Kind | What it does | Examples |
|---|---|---|
| Processor ↔ memory | Transfers data between CPU and memory (both ways) | load, store |
| Processor ↔ I/O | Transfers data with the outside world | read, write |
| Data processing | An arithmetic or logic operation | add, mul |
| Control | Alters the sequence of execution | jump |
| Combination | Several of the above in one instruction | an addition with an operand in memory |
A full example: raising the brightness of a pixel
Our toy machine has 16-bit words: the first 4 bits are the operation code and the other 12, an address. So 1A20 reads as 1 (LOAD) + A20 (address). The codes we will use: 1 LOAD (load into AC), 2 STORE (store AC), 5 ADD (add to AC), 6 SUB (subtract), 8 JUMP and F HALT.
The program in the Von Neumann diagram raises the brightness of a pixel from 64 (0040) by 24 (0018):
| Phase | PC | MAR | MBR | IR | AC | What happened |
|---|---|---|---|---|---|---|
| Fetch LOAD | 101 | 100 | 1A20 | 1A20 | — | The instruction at 100 is fetched and PC moves to 101 |
| Execute LOAD | 101 | A20 | 0040 | 1A20 | 0040 | The data at A20 is read and copied into AC |
| Fetch ADD | 102 | 101 | 5A21 | 5A21 | 0040 | |
| Execute ADD | 102 | A21 | 0018 | 5A21 | 0058 | 0040 + 0018 = 0058 (64 + 24 = 88) |
| Fetch STORE | 103 | 102 | 2A22 | 2A22 | 0058 | |
| Execute STORE | 103 | A22 | 0058 | 2A22 | 0058 | AC goes through MBR and is written to A22 |
| Fetch HALT | 104 | 103 | F000 | F000 | 0058 | The CPU halts |
How many times did the CPU go to memory? Once per fetch (4) and once per LOAD, ADD and STORE (3): 7 accesses. In the «Check it with Python» section you run it yourself.
The executions, on the inside
The table shows how the registers end up, but not what happens inside each execution:
- LOAD A20 (
1A20): the control unit sees in IR the code 1 (LOAD) and the addressA20. It puts it in MAR (MAR ← A20), memory returns the data to MBR (MBR ← M[MAR], which holds0040) and the data moves to the accumulator (AC ← MBR). One memory access. - ADD A21 (
5A21): the same as LOAD to bring in the data (MAR ← A21,MBR ← M[MAR], which holds0018), but instead of copying it to AC, the datapath adds it:AC ← AC + MBR, that is,0040 + 0018 = 0058. One memory access. - STORE A22 (
2A22): now the data goes the other way.MAR ← A22,MBR ← AC(the0058) and memory writes it:M[MAR] ← MBR. One memory access, but a write. - HALT (
F000): it asks for no data and writes nothing; the CPU halts. No access during execution.
With that, the count of accesses is plain to see:
| Instruction | Accesses to fetch it | Accesses to execute it | Total | Why |
|---|---|---|---|---|
| LOAD A20 | 1 | 1 | 2 | It reads the instruction and then reads the data |
| ADD A21 | 1 | 1 | 2 | It reads the instruction and then reads the second operand |
| STORE A22 | 1 | 1 | 2 | It reads the instruction and then writes the result |
| HALT | 1 | 0 | 1 | It reads the instruction and touches no data |
| Total | 4 | 3 | 7 | One fetch per instruction, plus one for each instruction that reads or writes data |
To check the addition in decimal, each hexadecimal digit is worth 16 times more than the one to its right: 0040 is 4 · 16 = 64, 0018 is 1 · 16 + 8 = 24 and 0058 is 5 · 16 + 8 = 88. And 64 + 24 = 88: the addition adds up. You will see it properly in number systems.
Check you’ve got it: after the STORE you want to undo the increase. You put SUB A21 (6A21) at 103, STORE A22 (2A22) at 104 and HALT moves to 105. How many memory accesses does the program make now, and what is left in A22?
11 accesses, and A22 is left holding 0040. There are now 6 instructions, so there are 6 fetches. Of those, LOAD, ADD, STORE, SUB and the second STORE read or write data: 5 more accesses. HALT still touches no data. 6 + 5 = 11. As for the value: after the ADD, AC holds 0058; the SUB subtracts what is in A21, 0018, leaving 0040 (88 − 24 = 64), which the second STORE writes to A22 over the 0058.
Incrementing PC at the end of execute instead of at the end of fetch. With a normal instruction it makes no difference, but with a jump it goes wrong: the jump puts a new value in PC and, if you then add 1, you skip an instruction.
A hello world going down 7 floors
All this seems very far from a print. Let us join the dots. Here is the same greeting, top to bottom:
- Floors 7, 6 and 5: Python, Java and C. Three high-level languages; each one writes the greeting in its own way.
- Floor 4, the operating system: none of the three knows how to write to the screen on its own. They all end up asking the operating system through a system call named
write. I checked it withstrace, a Linux tool that shows a program’s system calls:
$ strace -e trace=write ./hello write(1, "Hello, world\n", 13) = 13
The 1 is standard output, then comes the text, and 13 is the number of bytes (12 characters plus the newline). With java Hello you get exactly the same line. With Python, curiously, there were two write calls: one with "Hello, world" (12 bytes) and another with the "\n" (1 byte). Same result, different split.
- Floor 3, MIPS assembly: what you already know how to do:
li $v0, 4,la $a0, greetingandsyscall.syscallis the system call in MIPS. - Floor 2, machine code: each instruction is a 32-bit word.
li $v0, 4is reallyaddiu $v0, $zero, 4, which is encoded as0x24020004. That is how memory stores it (and how you will see it in the QtSpim text segment). How that number is worked out we will see in the instruction set topic. - Floor 1, logic gates: each of those bits is a high or low voltage going through logic gates (like the AND in the drawing: it outputs 1 only if two 1s come in).
When you do not understand why something is slow or fails «for no reason», go down a floor. A print inside a loop is one system call per iteration; data that is not in the cache is a trip to main memory.
Analogue and digital signals
So far, the computer from the inside. Now the other question of the topic: how is information stored? Computers run on electricity and represent information with the presence or absence of voltage.
- An analogue quantity takes continuous values: between any two values there are infinitely many in between. The light reaching a row of the camera sensor does not jump from «dark» to «bright»: it goes through every value in between.
- A digital quantity takes only a set of discrete values (separate, countable).
Nature is analogue; the computer, digital. To go from one to the other you have to digitise, which means coding the information of an analogue signal with a digital (binary) signal. It takes three steps:
- Sampling (or discretisation): taking samples of the signal at regular intervals.
- Quantisation: assigning each sample a value from a finite set.
- Coding: translating each value into a representation system; in a computer, into zeros and ones.
Let us do it with a row of the photo in «document» mode (black and white, like when you scan the whiteboard). We take 12 brightness samples (from 0 to 255) and decide: above 128, chalk (1); otherwise, board (0). It is the same thing the notes do with temperature (above 23 ºC, 1).
The same row, sample by sample. The threshold is «above 128»:
| Sample | Brightness | Bit | Why |
|---|---|---|---|
| 0 | 40 | 0 | Board: well below 128 |
| 1 | 40 | 0 | Board |
| 2 | 40 | 0 | Board |
| 3 | 51 | 0 | It starts to get lighter, but it is still far from 128 |
| 4 | 127 | 0 | Two points short: to be chalk it would have to go above 128 |
| 5 | 215 | 1 | Chalk: the center of the stroke |
| 6 | 127 | 0 | Again two points short of being chalk |
| 7 | 51 | 0 | Board |
| 8 | 45 | 0 | Board |
| 9 | 148 | 1 | Chalk: a wider stroke, two samples |
| 10 | 148 | 1 | Chalk |
| 11 | 45 | 0 | Board |
Look at what each step has done. Sampling has picked 12 points on a continuous line. Quantisation has left each point as a whole number from 0 to 255 (the real light can have decimals; the whole number cannot). And coding has turned each number into bits; here, with a single bit per sample, because document mode only wants to know whether it is chalk or board. If you wanted to keep the exact grey, you would need 8 bits per sample, because from 0 to 255 there are 256 values and 2⁸ = 256: the row would take up 12 · 8 = 96 bits instead of 12. More faithful, but eight times bigger.
The row becomes 000001000110. Look at the two samples worth 127: they were two points short of being chalk. A little noise (a shadow, the glare of the fluorescent light) and the bit changes. We come back to this with logic levels.
The separate samples (the dots) are not yet the digital representation: they are only a digitisable format. The digital signal appears when each sample is coded with bits.
Advantages of digital: storage is more compact, processing and transmission are more efficient and noise (unwanted voltage fluctuations) has less effect, because you only need to tell two levels apart.
Bits and logic levels
Digital circuits work with binary signals: only two states, normally two voltage levels (low and high). The digits of the binary system are 0 and 1, and each one is called a bit (binary digit). A set of bits forms a code, used to represent numbers, letters or symbols (we will see them in the next topics).
We will use positive logic: low voltage = 0 and high voltage = 1. The voltages that represent 0 and 1 are called logic levels.
Ideally an exact value (say, 3.3 V) would be 1 and another (0 V) would be 0. In practice that is impossible: voltage is never exact. So each logic level is a range between a minimum and a maximum, and between the two there is a forbidden zone:
With the example values in the drawing (typical of a 3.3 V family): 2.7 V is a 1, 0.3 V is a 0 and 1.4 V is nothing at all: a circuit does not know what to do with it. That is why designs make sure they never stay in the middle.
Here is what we promised with the samples worth 127. With a single threshold (128), two points of noise are enough for that 0 to be read as a 1. Logic levels avoid this by leaving a gap in the middle: with the values in the drawing, a 0 sent at 0 V would have to rise to 2.0 V to be read as a 1, and before that it would fall into the forbidden zone. That is why digital copes so well with noise.
Check you’ve got it: with the values in the drawing, what is each of these voltages: 0.5 V, 1.9 V and 3.0 V?
0.5 V is a 0, because it is inside the low range, between 0 V and 0.8 V. 1.9 V is neither 0 nor 1: it is above 0.8 V and below 2.0 V, in the forbidden zone, even though it is very close to the limit for 1. Being close does not count, only being inside. 3.0 V is a 1, because it is between 2.0 V and 3.3 V. If a question gives other limits (another logic family), you use the ones in the question.
In a logic-levels exercise, saying that a voltage in the forbidden zone «is a 0 because it is closer». No: it is neither 0 nor 1. The exact limits depend on the logic family, so they are always given in the exam question.
Pulses and edges
Digital signals are pulse trains: voltages that change between the low and the high level.
- Positive pulse: the signal is low, goes up and comes back down.
- Negative pulse: the signal is high, goes down and comes back up.
Each pulse has two edges: the positive one starts with a rising edge and ends with a falling one; the negative one, the other way round.
Ideal pulses change instantly (vertical edges) and are the ones we will use almost always. Real ones take a little time. To measure them:
- Rise time : how long it takes to go from 10 % to 90 % of the amplitude.
- Fall time : from 90 % to 10 %.
- Pulse width : the time between the two 50 % points.
Pulse trains can be:
- Periodic: they repeat at fixed intervals. That interval is the period and the number of repetitions per second is the frequency , measured in hertz (Hz):
- Non-periodic: pulses of different widths or separated by different intervals. Data travelling usually looks like this.
The clock and timing diagrams
A pulse train can be read as a sequence of bits: low level = 0, high level = 1. Each bit takes up a fixed time slot called the bit period.
In many digital systems all signals are synchronised with a periodic signal called the clock, in which each clock period equals one bit period. The way to draw it is a timing diagram: a chart with several waveforms, one above the other, showing how each signal changes relative to the others.
This is the timing diagram of our whiteboard row, 000001000110, sent one bit per clock period:
If each bit lasts 1 µs (one microsecond, a millionth of a second), the clock runs at:
and sending the 12 bits takes .
Memorise the prefix pairs: 1 ms ↔ 1 kHz, 1 µs ↔ 1 MHz, 1 ns ↔ 1 GHz. A 2 GHz processor has a period of ns. If the number does not get inverted when you go from frequency to period, something is wrong.
In a timing diagram, drawing the signal change in the middle of a clock period. Each bit takes up a whole period: the signal changes, if it changes, at the boundary between periods.
Common mistakes
Mixing up main memory and secondary memory. Main memory (RAM) is what the CPU uses while working and is erased when powered off; secondary memory (disk, flash) keeps things for good and is much slower.
Thinking that in Von Neumann instructions and data are in different memories. It is exactly the opposite: a single memory and nothing in the word says whether it is an instruction or data.
Mixing up MAR and MBR. MAR = address (where), MBR = data (what). Trick: the A in MAR stands for address.
Miscounting memory accesses. Every instruction is fetched (1 access) and, on top of that, the ones that read or write data make another. A jump or a HALT touches no data.
Forgetting to invert when going from frequency to period: 4 MHz is not 4 µs but .
Check it with Python
Two short simulators, with the fixed data from the article. I ran them once; the output is the real one.
A toy Von Neumann machine
It runs the brightness program and shows the registers after each phase:
# A toy Von Neumann machine: 16-bit words = operation code (4 bits) + address (12 bits)
OPS = {0x1: "LOAD", 0x2: "STORE", 0x5: "ADD", 0x6: "SUB", 0x8: "JUMP", 0xF: "HALT"}
# Program and data in THE SAME memory (stored program): raise the brightness of one pixel of the photo
mem = {0x100: 0x1A20, # LOAD A20 -> AC = brightness
0x101: 0x5A21, # ADD A21 -> AC = AC + increase
0x102: 0x2A22, # STORE A22 -> new brightness
0x103: 0xF000, # HALT
0xA20: 0x0040, # pixel brightness (64)
0xA21: 0x0018, # how much we raise it (24)
0xA22: 0x0000} # the result will go here
pc, ac, accesses, h = 0x100, 0, 0, lambda v, n=4: f"{v:0{n}X}"
while True:
# Fetch cycle: the address comes from PC, the instruction arrives through MBR and ends up in IR
mar = pc; mbr = mem[mar]; ir = mbr; pc += 1; accesses += 1
op, addr = ir >> 12, ir & 0xFFF
print(f"fetch PC={h(pc,3)} MAR={h(mar,3)} MBR={h(mbr)} IR={h(ir)} -> {OPS[op]} {h(addr,3)}")
# Execute cycle: depends on the operation code
if op == 0xF:
print("execute HALT: the CPU stops"); break
elif op == 0x8:
pc = addr # control: breaks the sequence
elif op == 0x2:
mar = addr; mbr = ac; mem[mar] = mbr; accesses += 1 # processor -> memory
else:
mar = addr; mbr = mem[mar]; accesses += 1 # memory -> processor
ac = mbr if op == 0x1 else (ac + mbr if op == 0x5 else ac - mbr)
print(f"execute MAR={h(mar,3)} MBR={h(mbr)} AC={h(ac)} PC={h(pc,3)}")
print(f"\nNew brightness at A22: {h(mem[0xA22])} = {mem[0xA22]}")
print("Memory accesses:", accesses, "(one per fetch and one per LOAD, ADD or STORE)")
Output:
fetch PC=101 MAR=100 MBR=1A20 IR=1A20 -> LOAD A20 execute MAR=A20 MBR=0040 AC=0040 PC=101 fetch PC=102 MAR=101 MBR=5A21 IR=5A21 -> ADD A21 execute MAR=A21 MBR=0018 AC=0058 PC=102 fetch PC=103 MAR=102 MBR=2A22 IR=2A22 -> STORE A22 execute MAR=A22 MBR=0058 AC=0058 PC=103 fetch PC=104 MAR=103 MBR=F000 IR=F000 -> HALT 000 execute HALT: the CPU stops New brightness at A22: 0058 = 88 Memory accesses: 7 (one per fetch and one per LOAD, ADD or STORE)
What to watch:
- Programs and data are in the same dictionary
mem: the machine only knows something is an instruction because PC pointed at it. - In every fetch, PC is already one more than MAR: it is incremented before executing.
- In the execution of STORE, MBR does not come from memory: it goes to it (
MBR ← AC). - The final count comes from counting accesses in the code, not by hand: 4 fetches + 3 data accesses = 7.
Digitising a row and sending it with a clock
It samples a row of the photo, quantises it, codes it with the threshold and draws the timing diagram as text:
import math
# The real light along one row of the whiteboard photo is continuous: dark board and two chalk strokes
def light(x): # x in millimetres of board; returns a brightness from 0 to 255
return 40 + 175 * math.exp(-((x - 5.0) / 1.2) ** 2) + 160 * math.exp(-((x - 9.5) / 0.8) ** 2)
N, STEP, THRESHOLD = 12, 1.0, 128 # 12 samples, one per millimetre; «document» mode threshold
T_BIT = 1e-6 # each bit lasts 1 microsecond when sent
samples = [light(i * STEP) for i in range(N)] # 1) sampling: separate values of something continuous
levels = [round(m) for m in samples] # 2) quantisation: each sample, to an integer 0-255
bits = "".join("1" if v > THRESHOLD else "0" for v in levels) # 3) coding with 1 bit (chalk = 1)
print("sample :", " ".join(f"{i:>3}" for i in range(N)))
print("light :", " ".join(f"{v:>3}" for v in levels))
print("bit :", " ".join(f"{b:>3}" for b in bits))
print("\nCoded signal:", bits)
# Timing diagram: one bit per clock period (positive logic: 1 = high level)
print("clock :", "|‾|_" * N)
print("S :", "".join("‾‾‾‾" if b == "1" else "____" for b in bits))
f = 1 / T_BIT
print(f"\nBit period = clock period = {T_BIT * 1e6:.0f} µs")
print(f"Clock frequency = 1 / T = {f:.0f} Hz = {f / 1e6:.0f} MHz")
print(f"Time to send the {N} bits = {N} x {T_BIT * 1e6:.0f} µs = {N * T_BIT * 1e6:.0f} µs")
print("Rising edges of S:", sum(1 for a, b in zip("0" + bits, bits) if a == "0" and b == "1"))
print("Bits at 1 (chalk):", bits.count("1"), "of", N)
Output:
sample : 0 1 2 3 4 5 6 7 8 9 10 11 light : 40 40 40 51 127 215 127 51 45 148 148 45 bit : 0 0 0 0 0 1 0 0 0 1 1 0 Coded signal: 000001000110 clock : |‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_ S : ____________________‾‾‾‾____________‾‾‾‾‾‾‾‾____ Bit period = clock period = 1 µs Clock frequency = 1 / T = 1000000 Hz = 1 MHz Time to send the 12 bits = 12 x 1 µs = 12 µs Rising edges of S: 2 Bits at 1 (chalk): 3 of 12
What to watch:
- The function
light(x)is continuous (you can give itx = 4.37): it is the analogue signal. - Each step of digitisation is one line:
samples(sampling),levels(quantisation) andbits(coding). - Samples 4 and 6 are 127 and stay at 0. Change
THRESHOLDto 120 and you will see the row change: the threshold decides. - The frequency comes from : with
T_BIT = 1e-6it gives 1 MHz. TryT_BIT = 250e-9.
Summary
| Concept | The essentials |
|---|---|
| Computer | Takes data, processes it and gives results, under the control of a stored program |
| Hardware / software | The physical part / programs and data; system, user and developer software |
| Kinds | Personal, server and embedded |
| Von Neumann | A single linear binary memory with instructions and data together, sequential execution and jumps |
| Components | Control unit + datapath (CPU), memory, input and output (I/O) |
| Hierarchy | Registers → cache → main → secondary: faster and dearer at the top, bigger at the bottom |
| Locality | Programs use few data at any moment; those are copied to the cache |
| Buses | Address lines (where), data (what) and control (what to do and when) |
| Instruction cycle | Fetch (MAR ← PC, MBR ← M[MAR], IR ← MBR, PC ← PC + 1) and execute |
| Kinds of execution | Processor-memory, processor-I/O, processing, control and combinations |
| Digitising | Sampling, quantisation and coding |
| Logic levels | Voltage ranges; positive logic; forbidden zone in between |
| Clock | Periodic signal; one bit per period; |
Three ideas to take away
- A computer is a stored program in motion: instructions and data in the same memory, and a CPU that fetches and executes non-stop.
- Fetch is always the same; what changes is execute. If you can move PC, MAR, MBR and IR, you can trace any program.
- Inside, everything is high or low voltages to the beat of a clock: and one bit per period.
Now it is time to practice. In the introduction to computers practice we solve three problems step by step: a full trace of the instruction cycle, a clock and timing-diagram problem and one with the format of the written exam.
And when you finish the exercises, the next paper topic is number systems: you will learn to read and write those bits in binary, octal and hexadecimal and to convert from one base to another.
Next step: practiceIntroduction to computers — practice with guided problems step by step: tracing the instruction cycle, the clock and a question in the exam format (and the counter that ended up with 226 photos)Did this article help you? Here is how you can support SergioLearns →



