CSSE2010 — Full Course Notes

Week 1

Lecture 1 — Course Introduction; Bits, Bytes and Binary

See csse2010 for staff, assessment, and course logistics. The technical content of Lecture 1 is below.

Outline

  • Course intro, organisation and admin
  • Assessment details
  • Technical content — binary numbers

What the course is about

Computers, in several different aspects — from a desktop PC down to the microcontrollers embedded in a car, a washing machine or an Arduino board. The semester climbs the stack in three blocks:

Weeks Block
W01–W05 Hardware
W06–W08 Low-level software
W09–W13 High-level software

Levels of abstraction

A computer can be described at six numbered levels, each built on the one below it. Level 0 is where this course starts.

Figure 1: The six levels of abstraction. Each level is implemented in terms of the one below it, so the same machine can be discussed as gates, as an instruction set, or as a C program. In blue: C sits at Level 5, and there is an unnamed level \(-1\) underneath the digital logic level, below the bottom of the numbered stack.

The course works up this stack across the semester, starting at the bottom: Lecture 2 is already at the digital logic level. The three course blocks are not tied to particular numbered levels, only ordered along the stack, but the named levels reappear later as topics in their own right (see instruction-set-architecture for Level 2, and assembly-process and compilation-and-linking for how Levels 4 and 5 are turned into machine code).

Computers and binary numbers

A computer — general purpose or embedded — takes inputs and instructions and produces outputs. All three are binary inside the machine.

Figure 2: The computer as a black box. Inputs, instructions and outputs are all just bit patterns; nothing inside the machine holds a decimal digit, a letter or a sign. Everything from here on is about what a given bit pattern is agreed to mean.

Bits, bytes, nibbles and words

  • Bit = binary digit (0 or 1).
  • Nibble = 4 bits, the unit that makes hexadecimal convenient.
  • Byte = 8 bits, e.g. 01010111.
  • Word = the natural unit a machine works on, usually a power-of-2 number of bytes: 1, 2, 4 or 8 bytes = 8, 16, 32 or 64 bits. At the two ends of that list, the AVR used in this course has an 8-bit word and modern CPUs are 32- or 64-bit.

Larger amounts are counted in kilobytes, megabytes and gigabytes, which mean powers of 2 for memory but usually powers of 10 for disks (memory-technologies).

Binary numbers

Unsigned binary is covered in full (with diagrams and worked examples) in binary-number-representations. In outline:

  • each bit position is worth a power of 2, and binary → decimal is just adding the positions where the bit is 1 — e.g. 10010001 = 145;
  • MSB and LSB — the positions worth the most and least; for an \(n\)-bit unsigned word the MSB is worth \(2^{n-1}\);
  • two methods for decimal → binary (sum of powers of 2; repeated division by 2), both worked on 53;
  • the unsigned range: all 0’s = 0, all 1’s = \(2^n - 1\);
  • other radices — octal (radix 8, 3 bits per digit) and hexadecimal (radix 16, 4 bits per digit);
  • how a radix is indicated in code (0x, $, leading 0, 0b, subscripts).

Signed numbers are Lab 1’s material; see week1-lab-number-representations.

Worked exercise — convert \(26_{10}\) to octal and hexadecimal

Divide repeatedly by the target radix, exactly as Method 2 does for binary, and read the remainders back.

Figure 3: Converting \(26_{10}\) by repeated division. Dividing 26 by 16 leaves quotient 1 and remainder 10, which is the hex digit A, so \(26_{10}=1\mathrm{A}_{16}\); dividing by 8 leaves quotient 3 and remainder 2, so \(26_{10}=32_{8}\). The check underneath expands each result back out as digit \(\times\) radix\(^{\text{position}}\).

The same answer falls out of the bit pattern directly: \(26_{10} = 00011010_2\), which groups into nibbles as 0001 1010 = 1 A, and into triples as 00 011 010 = 0 3 2 — see the bit-grouping figure in binary-number-representations.

Which radix notations this course uses

Of the ten ways of marking a radix in the full table, five are the ones this course mostly uses:

  • a subscript, e.g. \(101_2\) or \(101_{16}\);
  • leading 0x for hex (C, Atmel AVR);
  • leading $ for hex (Atmel AVR assembly);
  • leading 0 for octal (C, Atmel AVR) — so 0101 is not one hundred and one;
  • leading 0b for binary (Atmel AVR assembly, some C).

The rest (h/q/b suffixes, @ and % prefixes) appear in various assembly languages but not here. Full table in binary-number-representations.

Reminders

  • Sign up to a pair of lab sessions (P2, P1).
  • Labs start from Thursday of week 1 (P1 sessions only — no P2 sessions in week 1).
  • From week 2, both P2 and P1 sessions run.
  • Lab 1 covers different binary representation formats for signed numbers (two’s complement etc.).
  • A summary recording on binary numbers will be posted by the end of week 1.
  • Lab sign-on issues: email eait.mytimetable@uq.edu.au.

Practice: binary-conversion-drill.

Lecture 2 — Intro to Logic Gates

See logic-gates and boolean-algebra for the reference definitions/tables.

Outline

  • Introduction to Logic Gates
  • Logic Diagrams
  • Boolean Algebra and Logic Expressions

Digital logic

This is level 0, the Digital Logic level, of the abstraction stack from Lecture 1 (see 2026-07-27-course-intro-bits-bytes-binary) — the bottom of the stack, and where the course starts.

  • Digital circuits only have two logical levels present (binary):
    • logic ‘0’ — usually a small voltage (e.g. around 0 volts);
    • logic ‘1’ — usually a larger voltage (e.g. 0.8 to 5 volts, depending on the logic family, i.e. the type/size of the transistors).
  • Logic gates are the building blocks of computers. Each gate has one or more inputs and exactly one output, and performs a logic operation (or function). Inputs and outputs can only be in two states, 1 & 0 — also called “true” & “false”.
  • 7 basic gate types: NOT, AND, OR, NAND, NOR, XOR, XNOR — see logic-gates for symbols and truth tables.
  • Every gate (and every logic function) can be described four equivalent ways: logic symbol, truth table, Boolean expression, timing diagram.

Filling in truth tables

Two habits:

  • A 2-input gate’s table has \(2 \times 2 = 4\) rows; \(n\) inputs give \(2^n\) rows.
  • Don’t memorise NAND/NOR/XNOR. Write the AND / OR / XOR column first, then invert it row by row — that is all the “N” prefix means. (Both worked questions below are done this way.)

Worked: 3-input NAND truth table

Which truth table is the 3-input NAND?

Write the 3-input AND column first — 0 everywhere except the last row — then invert it. The NAND is the table where \(X = 1\) for every combination except \(A=B=C=1\):

\(A\) \(B\) \(C\) AND NAND
0 0 0 0 1
0 0 1 0 1
0 1 0 0 1
0 1 1 0 1
1 0 0 0 1
1 0 1 0 1
1 1 0 0 1
1 1 1 1 0

The “output is HIGH when at least one input is LOW” wording carries over unchanged from two inputs to three.

Worked: 3-input XOR truth table

XOR is the odd function — the 2-input wording “exactly one input is HIGH” does not generalise; the correct statement is that the output is HIGH when an odd number of inputs are HIGH.

So the rows that are 1 are those with one or three 1s — \(001, 010, 100, 111\):

\(A\) \(B\) \(C\) XOR
0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0
1 1 1 1

Correspondingly XNOR is the even function.

Boolean logic functions

A logic function is written as an expression of variables (literals, e.g. \(A\), \(B\), \(X\)) combined by functions — \(+\) (OR), \(\cdot\) (AND), \(\oplus\) (XOR), \(\bar{\ }\) (NOT) — with the output given as a function of the inputs, \(X = f(A,B)\). Variables and functions can only take on the values 0 or 1, and the rules for manipulating such expressions are Boolean algebra.

See boolean-algebra for the full notation conventions, the laws/identities table, De Morgan’s law and its gate equivalents, and the worked simplification example.

Four representations of a logic function

For a function of \(n\) inputs:

  1. Truth table — lists the output for all \(2^n\) combinations of the inputs. Best to list the input combinations in a systematic way (i.e. counting up in binary).
  2. Boolean function (or equation) — describes the conditions under which the function output is 1.
  3. Logic diagram — a combination of logic symbols joined by wires.
  4. Timing diagram — see timing-diagrams.

Logic diagram conventions

Figure 4: The drawing conventions for a logic diagram, on a two-input example. The two junction dots and the dot-free crossing next to them are the point: A branches down to the lower AND gate and crosses B’s wire on the way, and only the dots say which wires are actually joined.

  • Inputs are conventionally drawn on the left, outputs on the right.
  • Lines represent electrical wires. A wire can be at high or low potential — logic 1 or logic 0 respectively.
  • A filled dot at a junction indicates an electrical connection; wires that cross without a dot are not connected.

Reading Figure 4 off the page as practice: the top AND gets \(\bar A\) and \(\bar B\), the bottom AND gets \(A\) and \(B\), so \(M = \bar A \bar B + AB\) — which is 1 exactly when \(A\) and \(B\) are equal, i.e. XNOR.

Gates on ICs

  • Example: the 74HCT00 IC has four 2-input NAND gates in a single 14-pin DIP package — drawn out, with its pin numbers, in logic-gates.
  • Vcc = power (e.g. 5V), GND = ground (0V). Pin spacing 0.1”×0.3”; chip ~15mm long.
  • The internal drawing of the chip is a schematic; the black plastic part on the bench is the IC. See circuit-schematics for the difference and for how chips get labelled on a buildable drawing.

Logic function implementation (sum of products)

Any logic function can be implemented as the OR of AND combinations of its inputs — called sum of products. From the truth table:

  1. For each ‘1’ in the output column, write down the AND combination of inputs that gives that 1 (complementing each input that is 0 in that row).
  2. OR these together.

Worked example — truth table for \(M\):

A B C M
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 1

Four rows are 1, so there are four product terms:

\[M = \bar A BC + A\bar B C + AB\bar C + ABC\]

which simplifies to

\[M = AB + BC + AC\]

This is the majority function: \(M = 1\) whenever at least two of the three inputs are 1. (It comes back as the design task in week2-lab-majority-function-circuit-design.)

The route is to duplicate \(ABC\) using the idempotent law \(A + A = A\), then pair it with each of the other three terms and use the distributive and inverse laws (all in boolean-algebra):

\[\bar A BC + ABC = BC(\bar A + A) = BC\] \[A\bar B C + ABC = AC(\bar B + B) = AC\] \[AB\bar C + ABC = AB(\bar C + C) = AB\]

The equivalent logic diagram

Figure 5: The sum-of-products expression built directly as a circuit. Gates 1-3 generate the complements; the six vertical rails carry A, B, C and their complements past every gate; gates 4-7 form one product term per ‘1’ row of the truth table; gate 8 ORs them into M. Only the dots are connections - every other crossing is just two wires passing.

This is the unsimplified \(\bar A BC + A\bar B C + AB\bar C + ABC\) drawn literally — three inverters, four 3-input ANDs and a 4-input OR. It is what sum of products gives you before any algebra.

Equivalent functions (simplification)

Sum of products does not necessarily produce the circuit with the minimum number of gates. The Boolean function can be manipulated into an equivalent function using the rules of Boolean algebra (see boolean-algebra).

Example: \(Z = AB + AC = A(B+C)\) by the distributive law.

Figure 6: The same function drawn twice. The left circuit is the sum-of-products form AB + AC and needs three gates; factoring A out with the distributive law gives A(B+C), which needs two. Both have identical truth tables - the algebra is what buys the saving.

A second worked simplification, \(\text{CODE} = C + CD + \overline{(D + \bar D)}\), collapses all the way down to \(\text{CODE} = C\) — the steps are in boolean-algebra.

De Morgan’s law and equivalent circuits

AND and OR can be interchanged if you invert the inputs and the output — the four gate equivalences are drawn in boolean-algebra. Exercise: use truth tables to check that they are valid.

Universal (complete) gates

All circuits can be built from NAND-only or NOR-only gates (called complete gates), because NOT, AND, and OR can each be constructed purely from NAND gates, or purely from NOR gates — the six constructions are drawn in logic-gates. The reason this matters in practice: it is easier to build NAND and NOR gates from transistors than AND/OR directly.

Reminders

  • Attend Learning Lab sessions for the second half of this week — only the session you’re signed up to. (Sign-on issues: email eait.mytimetable@uq.edu.au.)
  • The slides used in a Learning Lab are released after the last session that week.
  • If specific preparation is needed for a lab you will be told; by default, review the previous lectures.
  • From week 2, you’ll have both P2 (Mon-Tue) and P1 (Thu-Fri) lab sessions.

Week 1 Exercises — Bits, Bytes & Binary; Intro to Logic Gates

Practice exercises for week 1, covering 2026-07-27-course-intro-bits-bytes-binary and 2026-07-30-intro-to-logic-gates. Many are taken from or based on Tanenbaum, Structured Computer Organisation, 5th edition, Appendix A and Appendix B. See binary-number-representations and logic-gates for the reference material needed to solve these, and week1-lab-number-representations for the Learning Lab 1 session that works the same conversions and the same four signed formats.

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "1010"), then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).

Q1 — Decimal to binary conversion

Convert the following decimal numbers to binary (unsigned representation): 1984, 4000, 8192.

1984 →

4000 →

8192 →

Repeatedly divide by 2, reading the remainders bottom-to-top (or subtract the largest power of 2 not exceeding the remaining value) — see binary-number-representations#converting-decimal-to-binary.

  • \(1984 = 1024+512+256+128+64 = 2^{10}+2^9+2^8+2^7+2^6 \Rightarrow\) 11111000000
  • \(4000 = 2048+1024+512+256+128+32 = 2^{11}+2^{10}+2^9+2^8+2^7+2^5 \Rightarrow\) 111110100000
  • \(8192 = 2^{13} \Rightarrow\) 10000000000000 (a 1 followed by 13 zeros)

Q2 — Binary to decimal, octal, hexadecimal

What is \(1001101001\) (binary, unsigned) in decimal? In octal? In hexadecimal?

Decimal →

Octal →

Hexadecimal →

Sum the powers of 2 where a bit is set: \(1001101001_2 = 2^9+2^6+2^5+2^3+2^0 = 512+64+32+8+1 = 617_{10}\).

  • Octal: \(617 \div 8 = 77\) r\(1\); \(77 \div 8 = 9\) r\(5\); \(9 \div 8 = 1\) r\(1\); \(1 \div 8 = 0\) r\(1\) → 1151 (check: \(1\cdot512+1\cdot64+5\cdot8+1\cdot1=617\)).
  • Hex: \(617 \div 16 = 38\) r\(9\); \(38 \div 16 = 2\) r\(6\); \(2 \div 16 = 0\) r\(2\) → 269 (check: \(2\cdot256+6\cdot16+9=617\)).

Q3 — Counting \(k\)-digit radix-\(r\) numbers

How many different positive integers can be expressed in \(k\) digits using radix \(r\) numbers?

With \(k\) digits in radix \(r\), every combination from all-zeros to all-\((r-1)\)s is representable, giving \(r^k\) distinct values total (including 0). Excluding 0 leaves \(r^k - 1\) positive integers.

Q4 — Radix-32 (Manchester Mark 1)

One of the earliest computers (the Manchester Mark 1, 1949) was programmed with a radix-32 number system, with digits \(0, 1, \dots 9, A, B, \dots U, V\) (10 numerals + 22 letters = 32 symbols).

  1. Describe how a binary number can be converted into a radix-32 number.
  2. Describe how a decimal number can be converted into a radix-32 number.
  3. Convert the decimal numbers 1300 and 2300 to radix-32 representations.

1300 →

2300 →

  • (a) Binary → radix-32: since \(32=2^5\), group the binary digits into 5-bit groups starting from the least significant bit (pad the leftmost group with leading zeros if needed), then convert each 5-bit group (a value 0–31) to the corresponding single radix-32 digit (0–9, then A=10 … V=31).
  • (b) Decimal → radix-32: repeatedly divide by 32, recording each remainder (converting remainders 10–31 to A–V); the radix-32 digits are the remainders read in reverse (last remainder computed = most significant digit) — the same repeated-division method used for decimal → binary/octal/hex.
  • (c):
    • \(1300 \div 32 = 40\) r\(20\); \(40 \div 32 = 1\) r\(8\); \(1 \div 32 = 0\) r\(1\) → digits \(1, 8, 20\)(=K) → 18K. Check: \(1\cdot1024+8\cdot32+20=1300\).
    • \(2300 \div 32 = 71\) r\(28\); \(71 \div 32 = 2\) r\(7\); \(2 \div 32 = 0\) r\(2\) → digits \(2,7,28\)(=S) → 27S. Check: \(2\cdot1024+7\cdot32+28=2300\).

Q5 — Largest unsigned integer

What’s the largest unsigned integer that can be represented in:

  1. 10 bits
  2. 9 decimal digits
  3. 8 hexadecimal digits

(a) 10 bits →

(b) 9 decimal digits →

(c) 8 hexadecimal digits →

The largest value in \(n\) digits of radix \(r\) is \(r^n - 1\) (all digits at their maximum):

    1. \(2^{10}-1 = 1023\)
    1. \(10^9-1 = 999{,}999{,}999\)
    1. \(16^8-1 = 4{,}294{,}967{,}295\) (note: 8 hex digits = 32 bits, so this equals \(2^{32}-1\))

Q6 — Finger counting

What’s the largest number that can be counted to on ten fingers, if each finger can be considered to have two positions? Compare your answer to that in 5(a).

Ten fingers, each with 2 possible positions, is exactly 10 bits of information: \(2^{10}-1 = 1023\) — identical to 5(a), since “10 things each with 2 states” is a 10-bit binary number.

Q7 — Signed number formats

For each of the following decimal numbers, write down the 8-bit binary representation using signed magnitude, one’s complement, two’s complement, and excess-128 formats:

  1. \(-1\)
  2. \(-16\)
  3. \(-99\)

Answer as four comma-separated 8-bit codes, in the order signed-magnitude,ones-complement,twos-complement,excess-128 (e.g. "10000000,11111111,00000000,10000000" for 0).

(a) −1 →

(b) −16 →

(c) −99 →

Formats (see binary-number-representations): signed magnitude = sign bit + 7-bit \(|n|\); one’s complement (negative) = invert every bit of \(|n|\)’s 8-bit form; two’s complement (negative) = \(128+n\) as a 7-bit value, prefixed with a 1; excess-128 = \(n+128\) as a plain 8-bit unsigned value.

\(n\) Signed magnitude One’s complement Two’s complement Excess-128
−1 10000001 11111110 11111111 01111111
−16 10010000 11101111 11110000 01110000
−99 11100011 10011100 10011101 00011101

Q8 — Signed format ranges

What are the smallest and largest integers that can be represented in the following binary representations:

  1. 16-bit two’s complement
  2. \(n\)-bit one’s complement
  3. excess \(2^{m-1}\)
  • (a) 16-bit two’s complement: smallest \(=-2^{15}=-32768\), largest \(=2^{15}-1=32767\).
  • (b) \(n\)-bit one’s complement: symmetric about zero (it has two representations of 0), so smallest \(=-(2^{n-1}-1)\), largest \(=2^{n-1}-1\).
  • (c) excess \(2^{m-1}\) (\(m\)-bit field, bias \(2^{m-1}\)): stored value ranges \(0\) to \(2^m-1\), actual value = stored \(-\) bias. Smallest (stored \(=0\)): \(-2^{m-1}\). Largest (stored \(=2^m-1\)): \(2^{m-1}-1\) — the same numeric range as \(m\)-bit two’s complement, just a different (biased) encoding of it.

All five ranges at a width small enough to see whole, which is where the asymmetry in (a) and (c) and the symmetry in (b) come from:

Figure 7: The five formats at 4 bits, each bar spanning the values it can represent. Every bar is drawn from the same 16 bit patterns, so a bar that is one value short has spent a pattern twice — and the two that do are exactly the two with a second zero, marked in red with the pair of patterns that share it. That is the whole of why ones’ complement and signed magnitude are symmetric about zero while two’s complement and excess-8 reach one further down than up.

Q9 — Logic gates: NOR and XOR

Draw the logic symbol, write the Boolean function, and write down the truth table for:

  1. a 4-input NOR gate
  2. a 3-input XOR gate (i.e. the odd function)

Figure 8: The two symbols the question asks for. The shapes are distinctive-shape (not IEC rectangle), with inputs left and output right, an open bubble at the boundary for inversion, and XOR’s second concave arc set back from the input edge. Every gate symbol in the Device Pinouts sheet is two-input (or the hex inverter), and the kit contains no 3-or-more-input part, so nothing there shows how to draw a gate with more inputs. The extra input leads are stacked on the same gate body here, as a reasonable extension of the two-input symbols.

(a) 4-input NOR — symbol: an OR-gate body (curved input side, pointed output) with 4 input lines and a small bubble on the output denoting inversion. Boolean function (De Morgan’s): \(X = \overline{A+B+C+D} = \bar A \cdot \bar B \cdot \bar C \cdot \bar D\) — \(X=1\) only when every input is 0.

A B C D X
0 0 0 0 1
all other 15 combinations 0

(b) 3-input XOR (odd function) — symbol: an XOR-gate body (OR-gate shape with an extra curved line just behind the inputs), no bubble. Boolean function: \(X = A \oplus B \oplus C\) — \(X=1\) iff an odd number of inputs are 1.

A B C X
0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0
1 1 1 1

Number Representations

Learning Lab 1. There is no hands-on prac this week; the prac activities start in week 2. See binary-number-representations for the reference version of everything below.

Worked: two unsigned conversions

Two plain unsigned conversions of the kind in 2026-07-27-course-intro-bits-bytes-binary. The format plays no part yet.

Question Answer Working
Decimal 37 in 8-bit binary (unsigned) 00100101 \(37 = 32 + 4 + 1 = 2^5 + 2^2 + 2^0\)
Unsigned binary 01000110 in decimal 70 \(64 + 4 + 2 = 70\)

Wrong answers to recognise: 00110101 is \(53\), which is what you get by mis-decomposing 37 as \(32+16+4+1\). 67, 71 and 72 are all one or two off 70, which is what a slipped bit position costs.

The bare metal

A computer stores everything with high and low voltages, or some other two-state signal: magnetic fields, switches, flash memory. That goes for all of these alike:

  • unsigned numbers
  • signed numbers
  • decimal numbers, characters, images, sounds

You cannot know what data is just by looking at it.

This comes back at the end as “format matters”.

Radices

A radix-\(k\) number system has \(k\) symbols for the digits \(0\) to \(k-1\), and digit values (from the right) \(k^0, k^1, k^2, \dots\)

  • Octal (radix-8): symbols 0–7; one octal digit = 3 bits.
  • Hexadecimal (radix-16): symbols 0–9 A–F; one hex digit = 4 bits (useful).

Worked: the maximum value in \(n\) radix-\(k\) digits

Answer: \(k^n - 1\).

Two ways to see it:

  1. The smallest number you can’t represent is a one followed by \(n\) zeroes, whose value is \(k^n\). The largest you can is one less.
  2. The biggest number is \(n\) copies of the largest digit \(k-1\), i.e. \(\sum_{i=0}^{n-1} k^i (k-1) = k^n - 1\) by the geometric series.

Conversion facts

  • A hex digit represents 16 values; so do 4 bits (\(2^4 = 16\)).
  • An octal digit represents 8 values; so do 3 bits.
  • A base-10 digit represents 10 values; so do \(3.321928\ldots\) bits [citation needed].
  • Hex and octal convert to binary digit-by-digit; base-10 does not.
  • Three hex digits represent 4096 values; so do four octal digits.
  • \(123 = 0123\), but \(456 \neq 4560\) — pad zeroes on the left.

The conversion map

Binary is the hub of the conversions. Only two conversions are digit-by-digit, and both of them have binary at one end.

Figure 9: The conversions between decimal, binary, hexadecimal and octal, drawn as one map. Binary sits in the middle because hexadecimal and octal are both powers of two and so convert to it by regrouping bits, four at a time and three at a time respectively. Decimal is not a power of two, so its two arrows are arithmetic (repeated division, summation of powers) rather than regrouping. There is no direct hex-octal arrow: converting 0xC55E7201 to octal goes the long way, through 32 bits of binary. The box colours carry no meaning.

Worked conversions

Group binary into 4s for hex, 3s for octal, padding on the left:

From To Working Result
001001101001 hex 0010 0110 1001 0x269
01001101001 octal 001 001 101 001 \(1151_8\)
0xA1E binary 1010 0001 1110 101000011110
\(703_8\) binary 111 000 011 111000011
0xC55E7201 octal regroup 32 bits into 3s (pad one zero): 011 000 101 010 111 100 111 001 000 000 001 \(30527471001_8\)

Hex → octal has no shortcut: go via binary.

Negative numbers

Computers don’t store \(+\) and \(-\); four formats have been used. Two’s complement is what is practically used.

All four — and unsigned — use the same representation for positive numbers.

Signed magnitude

Leftmost bit is the sign (0 positive, 1 negative) and does not contribute to the magnitude. Negate by inverting the sign bit alone.

Ones’ complement

The sign bit now also contributes to the magnitude: its position value is \(-(2^{N-1}-1)\). Negate by inverting all the bits.

Two’s complement

The sign bit’s position value is \(-2^{N-1}\). Negate by inverting all the bits and adding 1.

Excess-\(2^{N-1}\)

For 8 bits, “excess 128”: the number is stored as its true value plus 128. So \(-3\) is stored as \(125\), and \(3\) as \(131\).

It is the same as two’s complement with the sign bit reversed — a 0 in the MSB means bit value \(-128\), a 1 means 0. Practical use: comparing two signed numbers becomes simple in hardware.

All of it in one picture

Write each format as a row of bit weights and stack the rows. They differ in one column only.

Figure 10: The four signed formats and unsigned, as stacked strips of bit weights. Every format gives bits 6 down to 0 exactly the same weights; the only thing any of them changes is what bit 7 is worth. Signed magnitude and excess-128 do not give bit 7 a weight at all — they give it a meaning, which is why those two boxes say what a 0 and a 1 mean rather than give a number. In signed magnitude the sign bit is not a magnitude position: only bits 6 to 0 carry magnitude.

The shaded column is the only one that differs. The reason two’s complement wins is not that it is cleverer at representing negatives; it is that \(-128\) is the only choice of bit-7 weight that leaves the whole row a plain sum of place values, with no special rule attached to the top bit. That is exactly what makes its addition ordinary binary addition, with no case analysis and no end-around carry. Limitations below says the same in words.

The ±47 example, 8-bit

\(+47 = \texttt{00101111}\) in all four formats.

Format \(-47\)
Signed magnitude 10101111
Ones’ complement 11010000
Two’s complement 11010001
Excess-128 01010001

And the 4-bit \(-3\) examples: ones’ complement 1100, two’s complement 1101.

Ranges

Format Range
8-bit signed magnitude \(-127\) to \(127\)
\(n\)-bit signed magnitude \(-(2^{n-1}-1)\) to \(2^{n-1}-1\)
8-bit ones’ complement \(-127\) to \(127\)
8-bit two’s complement \(-128\) to \(127\)
\(n\)-bit two’s complement \(-2^{n-1}\) to \(2^{n-1}-1\)
8-bit excess-128 \(-128\) to \(127\)

Why “complement”

In the loose mathematical sense, a thing and its complement together make a whole. An angle and its complement make a right angle; a graph and its complement a complete graph; a set and its complement a universal set.

  • In ones’ complement, a number plus its negative gives a string of ones (11111111 in 8 bits).
  • In two’s complement, a number plus its negative gives a power of two, with overflow (1 00000000). It would more correctly be called power-of-two’s complement.
  • Base 10 has the equivalent nines’ and ten’s complements, used on some early mechanical adding machines to do subtraction.

Limitations

Two representations of zero — undesirable, because it wastes a bit pattern that could have extended the range:

  • Signed magnitude: 00000000 and 10000000
  • Ones’ complement: 00000000 and 11111111

Asymmetric range: two’s complement and excess-\(2^{m-1}\).

Arithmetic: signed-magnitude addition requires taking cases; ones’ complement addition requires an extra addition step; sign extension and comparisons are non-trivial in both.

Two’s complement has one zero, and its addition is just binary addition — which is why it wins.

Format matters

“What is 10010010 converted to decimal?” cannot be answered as asked. It depends on the format:

Read as Value
8-bit unsigned 146
Two’s complement \(-110\)
Ones’ complement \(-109\)
Signed magnitude \(-18\)
Excess-128 18

In the same way, 01010101 could be 85 (8-bit unsigned), \(-43\) (excess-128), 'U' (ASCII), or 10.625 (8-bit fixed point, 5 bits before the point and 3 after).

Binary data is meaningless unless you know the format. The format is not encoded in the data — it has to be known separately, by a human, a program, or the hardware.

Exercise — the five-format table

Write the decimal interpretation of every 4-bit pattern under each format:

Pattern Unsigned Sign-mag Ones’ comp Two’s comp Excess-8
0000 0 0 0 0 \(-8\)
0001 1 1 1 1 \(-7\)
0010 2 2 2 2 \(-6\)
0011 3 3 3 3 \(-5\)
0100 4 4 4 4 \(-4\)
0101 5 5 5 5 \(-3\)
0110 6 6 6 6 \(-2\)
0111 7 7 7 7 \(-1\)
1000 8 \(-0\) \(-7\) \(-8\) 0
1001 9 \(-1\) \(-6\) \(-7\) 1
1010 10 \(-2\) \(-5\) \(-6\) 2
1011 11 \(-3\) \(-4\) \(-5\) 3
1100 12 \(-4\) \(-3\) \(-4\) 4
1101 13 \(-5\) \(-2\) \(-3\) 5
1110 14 \(-6\) \(-1\) \(-2\) 6
1111 15 \(-7\) \(-0\) \(-1\) 7

The two \(-0\) entries are the wasted patterns. Excess-8 is the two’s complement column with the sign bit flipped.

Esoteric formats

Not examinable: binary coded decimal with sign pattern; negabinary (base \(-2\)); zig-zag encoding; LEB128; quarter-imaginary base (base \(2i\)) and the Davis–Knuth “twindragon” base (base \(i-1\)) for Gaussian integers; and “integers don’t exist” — JavaScript.

Admin

Lab kits are used during the lab from week 2 and loaned out later (see week3-lab-logisim-and-flip-flops). If you’re on your own laptop you’ll need two USB-A connections from week 11, and one from week 8 — get a dongle early if you need one. Prac activities start in week 2. Catch up on the lecture content before attending a lab.

There is a summary recording on Blackboard covering the signed binary formats, to be watched before week 2.

See also

Week 2

Binary Arithmetic

See binary-number-representations for signed-format background (signed magnitude, two’s complement) and logic-gates/boolean-algebra for the gate-level building blocks used below. The matching lab is week2-lab-binary-arithmetic.

Worked: -32 in 8-bit signed magnitude

Signed magnitude splits the word into a sign bit (the MSB, 1 = negative) and a magnitude in the remaining \(N-1\) bits. Here \(32 = 0100000\) in the seven magnitude bits, and the sign bit is 1:

\[\underbrace{1}_{\text{sign}}\ \underbrace{0100000}_{\text{magnitude}} \;=\; \texttt{10100000}\]

Answer: 10100000.

Worked: -32 in 8-bit two’s complement

To negate a two’s complement number: invert every bit, then add 1.

Figure 11: Negating \(+32\) in 8 bits. Left: invert all eight bits of \(00100000\) and add one. Right: the answer checked against the place values — in two’s complement the MSB is the only column with a negative weight, \(-2^{N-1}\), which is what makes \(11100000\) come to \(-32\) rather than \(224\).

Answer: 11100000.

Two rules to carry forward:

  • The MSB alone tells you the sign. \(x \geq 0\) looks like \(\texttt{0}xx\ldots x\); \(x < 0\) looks like \(\texttt{1}xx\ldots x\).
  • The MSB is not just a flag — it is a place value of \(-2^{N-1}\). Every other column keeps its usual positive weight, so \(\texttt{11100000} = -128 + 64 + 32 = -32\).

The number -32 is 10100000 in signed magnitude and 11100000 in two’s complement. The same number has different bit patterns in different formats, so a bit pattern on its own means nothing until you know which format it is in.

Universal (complete) gates

Everything below is built out of gates. All circuits can be constructed from NAND gates only, or from NOR gates only — these are called complete (or universal) gates. The reason is practical: NAND and NOR are easier to build from transistors than AND and OR are.

Figure 12: NOT, AND and OR built two ways: from NAND gates only (top row) and from NOR gates only (bottom row). The two building tricks are the ones to remember — a NAND or NOR with its inputs tied together is an inverter, and De Morgan turns an inverted-input NAND into an OR (and an inverted-input NOR into an AND).

The two moves that generate the whole table:

  • Tie the inputs together to get an inverter. \(\overline{A \cdot A} = \overline{A}\) for a NAND, and \(\overline{A + A} = \overline{A}\) for a NOR.
  • Invert the inputs and apply De Morgan. For the NAND-OR cell: \[\overline{\overline{A} \cdot \overline{B}} \;=\; \overline{\overline{A}} + \overline{\overline{B}} \;=\; A + B\] and the mirror image for the NOR-AND cell, \(\overline{\overline{A} + \overline{B}} = A \cdot B\).

Everything else is one of these two composed with a plain NAND/NOR: AND from NAND is a NAND followed by an inverter, and OR from NOR is a NOR followed by an inverter.

Worked: a NOR-only implementation

Implement \(AB + CD\) using NOR gates only.

Figure 13: The circuit to implement (left) and its NOR-only version (right). Read it as three blocks: each AND becomes ‘invert both inputs, then NOR’, and the OR becomes ‘NOR, then invert’. The tempting wrong answer is the same circuit with that last inverting NOR left off, which computes the complement of the right answer.

Answer: the right-hand circuit. The quick way to read a circuit like this is to chunk it — mark off which gates form the two ANDs and which form the OR, rather than tracing signals gate by gate. The same circuit with the final inverting NOR missing produces \(\overline{AB + CD}\). Other wrong answers use the wrong gate type or too few gates.

Binary addition

Addition is simple in binary. Adding a single addend bit \(A\) to a single augend bit \(B\) gives a sum bit \(S\) and a carry:

Addend 0 0 1 1
Augend +0 +1 +0 +1
Sum 0 1 1 0
Carry 0 0 0 1

This table ignores carry-in — it is only correct for the least significant column. The full adder, below, handles carry-in.

Adding whole words

  Decimal   8-bit Unsigned      Decimal   8-bit 2's complement
  10        00001010            10        00001010
+ 243     + 11110011          +(-13)    + 11110011
--------- ------------        -------   --------------------
  253       11111101            -3        11111101

The two sums use exactly the same bit pattern and exactly the same procedure — only the reading of the operands and the result differs.

  • Format matters when you interpret the numbers, not when you add them. Whatever the format, the bit-wise addition is the same, which is why one adder circuit serves both.
  • Two’s complement: you do not need to do anything with the carry-out from the MSB to get the correct result — just drop it. A 4-bit check:
   111         <- carries
   1111   (-1)
 + 1111   (-1)
--------
 1 1110         carry-out discarded; the 4-bit result 1110 = -2
  • One’s complement: you do have to take the carry-out from the MSB and add it back into the result (an “end-around carry”) to get the right answer. That extra step is one of the practical drawbacks of one’s complement compared to two’s complement.

To check the two’s complement result above, negate it: \(\texttt{11111101} \to \texttt{00000010} \to +1 \to \texttt{00000011} = 3\), so the pattern is \(-3\).

Overflow

Overflow: there are not enough bits to represent the answer, so the result goes out of range and you get a wrong answer.

Figure 14: The two overflow cases worked with their carry rows exposed, because the carries are what the detection rules are stated in terms of. Left: unsigned, where a carry-out of the MSB alone means overflow. Right: two’s complement, where the carry into the MSB and the carry out of it disagree — and, below, what that looks like on the number line: \(125+4\) walks off the top of the range and wraps round to the bottom.

How overflow is detected:

  • Unsigned: a carry-out from the MSB means overflow.
  • Two’s complement: overflow if the carry-in to the MSB and the carry-out from the MSB differ, i.e. \[\text{Overflow} = C_{in} \oplus C_{out}\]
  • Equivalently in two’s complement: overflow happens when two negatives added together give a positive, or two positives added together give a negative. (Adding a positive to a negative can never overflow — the result is between the two operands.)

The two rules differ because in two’s complement the carry-out is meaningless on its own and is simply discarded, as above; it only says something about overflow when compared against the carry-in.

Worked: adding two 6-bit two’s complement numbers

\(110101 + 001111\), with the answer constrained to 6 bits:

  11111     <- carries
  110101
+ 001111
---------
1 000100    the 7th bit is outside the 6-bit word, so drop it

Answer: 000100.

Check in decimal: \(110101 = -32 + 16 + 4 + 1 = -11\) and \(001111 = 15\), so the answer should be \(4 = 000100\). And there is no overflow: the carry into the MSB is 1 and the carry out is 1, so \(C_{in} \oplus C_{out} = 0\).

Half-adder

A device that adds two bits has inputs \(A\), \(B\) and outputs \(S\) (sum) and \(C\) (carry). Its truth table is the single-bit table from earlier:

A B C S
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 0

\[S = A \oplus B \qquad C = AB\]

A device which adds 2 bits with no carry-in is called a half-adder. The sum column is exactly XOR and the carry column is exactly AND, so a half-adder is one XOR gate and one AND gate.

Dealing with carry-in: the full adder

A half-adder is not enough for a real column of an addition, because there may be a carry-in from the previous stage. A device with three inputs \(A\), \(B\), \(C_{in}\) and two outputs \(S\), \(C_{out}\) is a full adder.

Figure 15: Half-adder versus full adder as blocks, and (right) why the third input exists: in a multi-bit addition each column is one full adder, taking its carry-in from the column on its right and passing its carry-out to the column on its left. Only the least significant column can get away with a half-adder.

The full adder’s truth table:

A B \(C_{in}\) \(C_{out}\) Sum
0 0 0 0 0
0 0 1 0 1
0 1 0 0 1
0 1 1 1 0
1 0 0 0 1
1 0 1 1 0
1 1 0 1 0
1 1 1 1 1

\[S = A \oplus B \oplus C_{in}\] \[C_{out} = AB + C_{in}(A \oplus B)\]

\(S\) is 1 whenever an odd number of the three inputs is 1, which is the three-input XOR. \(C_{out}\) is 1 when \(A\) and \(B\) both carry, or when exactly one of \(A\), \(B\) is 1 and there was a carry-in to push the column over.

Those two expressions say the circuit is two half-adders and an OR gate: the first half-adder adds \(A\) and \(B\); the second adds its sum to \(C_{in}\); and the two half-adders’ carry outputs are OR’d to give \(C_{out}\) (they can never both be 1, so an OR is enough).

Figure 16: The full adder at gate level, with the two half-adders outlined. The left half-adder adds A and B; the right one adds that sum to the carry in; the OR at the bottom collects the two carries. At the crossing near the top right, the carry-in line passes over the first half-adder’s sum line without a junction dot, so they are not connected.

Ripple-carry adder

Cascading full adders — each stage’s \(C_{out}\) wired into the next stage’s \(C_{in}\) — builds a multi-bit binary adder. Four of them give a 4-bit adder.

Figure 17: A 4-bit ripple-carry adder: one full adder per bit position, with the carry chained from the least significant stage (right) to the most significant (left). Since stage \(i\) cannot produce its final sum until stage \(i-1\) has settled, the carry has to propagate through all four stages before any of the outputs can be trusted — which is what makes this structure simple but slow.

  • For plain addition the initial carry-in \(C_0\) is 0. (It is there because it is useful for other things — chaining adders, and subtraction, which comes later.)
  • This structure is called a ripple-carry adder, because the carry has to propagate (“ripple”) through every stage before the final sum is valid.
  • \(C_4\) and \(C_3\) are exactly the \(C_{out}\) and \(C_{in}\) of the MSB stage, so the overflow test above is available straight off this diagram.

See combinational-logic-blocks for the adder as a standard block, and arithmetic-logic-unit for the same ripple structure reused inside an ALU.

Admin and reminders

  • Contact eait.mytimetable@uq.edu.au if not yet signed up for a lab, or unable to attend the labs you are signed on to.
  • Two lab sessions per week from this week; refer to the week-by-week teaching outline on Blackboard.
  • Weekly exercises and quizzes (not assessed) are on Blackboard.
  • Week 2 labs: P2 sessions (Mon-Tue) run Lab 2 (Logic Gates); P1 sessions (Thu-Fri) run Lab 3 (Binary Arithmetic) — see week2-lab-binary-arithmetic.
  • Complete the week 1 exercises folder and ask if unclear.
  • Watch the summary video on Signed Binary Formats.

Lecture 4 — Combinational Logic

See combinational-logic-blocks for the reference definitions/tables of the adder-subtractor, multiplexer and decoder introduced here, and timing-diagrams for the timing-diagram representation and real-gate timing parameters.

Outline

  • Admin
  • Binary subtractors
  • More combinational logic circuits
    • Multiplexers
    • Decoders
    • Timing diagram representations

Recap — binary adder

Picking up from 2026-08-04-binary-arithmetic: full adders can be cascaded to make a multi-bit binary adder. For 4 bits, four full adders take \(A_3B_3 \ldots A_0B_0\) and produce \(S_3 \ldots S_0\) plus \(C_4\), with each stage’s carry-out \(C_{i+1}\) wired to the next stage’s carry-in. For addition the initial carry-in \(C_0\) is 0. This arrangement is a ripple-carry adder.

Figure 18: The 4-bit ripple-carry adder. Each full adder handles one bit position: it takes A and B for that position plus the carry coming in from the position to its right, and produces that position’s sum bit plus a carry out to the left. Nothing but the carry crosses between stages.

Binary subtractors

\(A - B\) is implemented as \(A + (-B)\), with \(-B\) the two’s complement of \(B\). Three things to keep straight:

  • \(A\) and \(B\) are multi-bit quantities.
  • The “+” means addition, not OR.
  • \(-B\) is the two’s complement of \(B\): flip the bits and add 1, i.e. \(-B = \bar B + 1\).

Take \(5 - 3\), first as an ordinary subtraction and then as the addition the hardware actually performs.

Figure 19: 5 - 3 worked as a subtraction and as the addition the hardware performs. Negating 3 takes two steps — invert 0011 to 1100, then add 1 to get 1101 — and 1101 is the four-bit two’s complement pattern for -3. Adding it to 0101 gives the same 0010 the subtraction gives, so a machine that can only add can subtract.

The two pieces needed on top of a plain adder are a controlled inverter (an XOR gate per bit, with the mode select \(M\) as the second input) and the extra \(+1\), which is supplied via the adder’s carry-in. Full derivation and the adder-subtractor circuit are in combinational-logic-blocks.

Two questions settle the design:

  • Which gate flips a bit, but only sometimes? The gate needs \(Z = \bar B\) when \(M=1\) and \(Z = B\) when \(M=0\). The three-column \(M\), \(B\), \(Z\) truth table gives a 2-input XOR, \(Z = B \oplus M\). The general identities behind it are \(X \oplus 0 = X\) and \(X \oplus 1 = \bar X\) for any signal \(X\).
  • What should carry-in be? \(C_0 = M\) — the same mode-select line that drives the XOR gates, so subtract mode automatically contributes the \(+1\) that two’s complement needs. \(M = 0\) gives \(S = A + B\), and \(M = 1\) gives \(S = A + (-B) = A + \bar B + 1\).

Combinational circuits in general

A combinational circuit is a combination of logic gates with \(n\) inputs and \(m\) outputs; each output is a function of the \(n\) inputs, the output depends on current inputs only, and it can be written as a truth table with \(n\) input columns, \(m\) output columns and \(2^n\) rows. See combinational-logic-blocks.

Multiplexers

\(2^n\) data inputs, 1 output, \(n\) select inputs that steer one data input to the output — a data selector. The two sizes used here are the 4-to-1 mux (logic symbol, function table, and the AND-OR sum-of-products implementation with inverted select literals) and the 2-to-1 mux. Tables and circuit descriptions: combinational-logic-blocks. Off-the-shelf part: the 74HCT157 quad 2-input mux, see device-pinouts.

The 4-to-1 function table has four rows, one per select combination, with \(F\) holding a data input name rather than a 0 or 1. That is deliberate: the full truth table over all six inputs would need \(2^6 = 64\) rows.

Worked: 2-to-1 multiplexer truth table

A 2-to-1 multiplexer has data inputs \(D_0\) and \(D_1\), control input \(S_0\), and output \(F\), with function table \(F = D_0\) when \(S_0 = 0\) and \(F = D_1\) when \(S_0 = 1\). Which of three candidate truth tables (columns \(S_0, D_0, D_1, F\)) goes with this circuit?

Three inputs means \(2^3 = 8\) rows, which all three candidates have. Reasoning from the function table, row by row in the order \(S_0 D_0 D_1 = 000, 001, 010, 011, 100, 101, 110, 111\):

  • The first four rows have \(S_0 = 0\), so \(F\) must copy \(D_0\) and ignore \(D_1\): \(F = 0, 0, 1, 1\).
  • The last four rows have \(S_0 = 1\), so \(F\) must copy \(D_1\) and ignore \(D_0\): \(F = 0, 1, 0, 1\).

\[F = 0,\,0,\,1,\,1,\,0,\,1,\,0,\,1\]

That is option 2. Option 1 has \(F\) following \(D_1\) when \(S_0=0\) and \(D_0\) when \(S_0=1\) — the two data inputs swapped. Option 3 is \(F = 0,0,0,0,1,1,1,1\), i.e. \(F = S_0\): it ignores the data inputs completely.

Equivalently: \(F = D_0 \bar S_0 + D_1 S_0\).

Worked: choosing mux inputs to realise \(X = \bar S_0 + S_1\)

A 4-to-1 multiplexer has \(A\) on data input 0, \(B\) on 1, \(C\) on 2, \(D\) on 3, selects \(S_1 S_0\), and output \(X\). What must \(A, B, C, D\) be so that

\[X = \bar S_0 + S_1\]

Options: (1) \(A{=}0, B{=}1, C{=}0, D{=}0\); (2) \(A{=}0, B{=}1, C{=}1, D{=}1\); (3) \(A{=}1, B{=}0, C{=}1, D{=}1\); (4) \(A{=}1, B{=}1, C{=}0, D{=}1\).

Reasoning: the mux steers data input \(i\) to the output when \(S_1S_0\) equals \(i\) in binary, so each data input must simply be the value the desired function takes for that select combination. Evaluate \(\bar S_0 + S_1\) for all four:

Figure 20: The 4-to-1 mux and the function it has to realise. Each select combination picks one data input, so the value that input must carry is just the function evaluated at that combination — the four evaluations are 1+0, 0+0, 1+1, 0+1.

\(S_1\) \(S_0\) \(\bar S_0\) \(X = \bar S_0 + S_1\) Selected input
0 0 1 1 \(A\) (input 0)
0 1 0 0 \(B\) (input 1)
1 0 1 1 \(C\) (input 2)
1 1 0 1 \(D\) (input 3)

So \(A = 1, B = 0, C = 1, D = 1\) — option 3.

This is the general trick: tying a mux’s data inputs to constants turns it into a lookup table for any function of the select variables.

Decoders

A decoder converts an \(n\)-bit input to a logic 1 on exactly one of \(2^n\) outputs. The 3-to-8 decoder (inputs \(A, B, C\); outputs \(D_0 \ldots D_7\)) is implemented with eight AND gates. Each row of its truth table corresponds to one minterm — \(\bar A \bar B \bar C\) at the top down to \(ABC\) at the bottom.

Because a decoder puts every minterm on its own wire, an arbitrary function is just an OR of the right outputs. For example

\[F = \bar A \bar B \bar C + ABC = D_0 + D_7\]

one OR gate on two decoder outputs. Circuit and diagram: combinational-logic-blocks.

Timing diagram representations

The timing diagram is another logic representation — like a truth table but graphical. timing-diagrams has the inverter as the worked example, the convention for drawing 2-input waveforms so all input combinations are covered, and the reality that gates aren’t perfect (propagation delay, fall time, rise time).

Worked: timing diagram for an XOR gate

Given input waveforms where \(A\) is low for the first half of the diagram then high for the second half, and \(B\) toggles at twice that rate (low, high, low, high) — so the four intervals are \(AB = 00, 01, 10, 11\) — which of three candidate output waveforms represents an XOR gate?

Reasoning from the XOR truth table (\(X = 1\) iff exactly one input is 1):

Interval \(A\) \(B\) \(A \oplus B\)
1 0 0 0
2 0 1 1
3 1 0 1
4 1 1 0

So the output must be low, high, high, low — a single pulse spanning the middle two intervals.

Figure 21: The inputs A and B and the three candidate outputs. Candidate 2 is the only one that goes high and comes back down, which is what a pulse over the middle two intervals requires. Candidate 1 rises once and stays high, so it can never be XOR; candidate 3 is candidate 2 inverted, i.e. XNOR.

That is option 2 — the only candidate with a pulse that goes high and comes back low again. Option 1 has a single rising edge and then stays high to the end, so it can never be XOR. Option 3 is the exact complement of option 2 (high, low, low, high), i.e. XNOR.

Reminders

  • Lab 4 preparation task — next week (week 3). It will be available on Blackboard under Learning Resources; it involves drawing some circuit schematic diagrams (see circuit-schematics), and you must bring it to Lab 4 (P2 Mon-Tue sessions in week 3). Complete it before Lab 4. Worked answers: week3-lab-lab-4-pre-work.
  • Supporting material for the labs is now on Blackboard.
  • Attempt the posted exercises and quiz (not assessed).
  • Any doubts: use course consultation, ask after the lecture, or use the Ed forum.

Binary Arithmetic Lab

Learning Lab 3 — binary arithmetic revision, then circuits that do arithmetic, simulated in Logisim and built with ICs. Pairs with 2026-08-04-binary-arithmetic.

Worked: \(-16_{10}\) in 8-bit two’s complement

11110000.

\(16 = \texttt{00010000}\); invert to 11101111; add 1 to get 11110000. Check: \(-128 + 64 + 32 + 16 = -16\). ✓

The wrong answers to watch for: 11101111 is the ones’ complement — the answer if you forget the \(+1\). 10010000 and 10010001 are the signed-magnitude and signed-magnitude-off-by-one answers, and 00010000 is \(+16\), i.e. the magnitude with the negation left out altogether.

Worked: 001110 + 110100 in 6-bit two’s complement

000010, with no overflow.

\(001110_2 = 14\) and \(110100_2 = -32 + 16 + 4 = -12\), so the true answer is \(2 = \texttt{000010}\). ✓

Overflow check, with the carry row written out:

\(c_5\) \(c_4\) \(c_3\) \(c_2\) \(c_1\) \(c_0\)
carry in 1 1 1 0 0 0 ← carry into each column
0 0 1 1 1 0 \(= 14\)
1 1 0 1 0 0 \(= -12\)
sum 0 0 0 0 1 0 \(= 2\)

The carry into the MSB is 1 and the carry out is also 1, so \(C_{in} \oplus C_{out} = 0\) — no overflow. The carry-out of 1 would signal overflow if these were unsigned. Getting the sum right is not enough: the answer has to say whether it overflows as well; see 2026-08-04-binary-arithmetic.

Worked: which operation overflows in 4-bit two’s complement?

4-bit two’s complement covers \(-8\) to \(7\).

Operation Result Overflow?
A 0100 − 0101 \(4 - 5 = -1\) no
B 1001 − 0001 \(-7 - 1 = -8\) no (just fits)
C 0100 + 0101 \(4 + 5 = 9\) yes — 9 > 7
D 1001 + 0001 \(-7 + 1 = -6\) no

Answer: C. B is the near-miss: \(-8\) is exactly representable, so it does not overflow.

Task 1 — 1-bit full adder

Turn the full-adder logic diagram (two XORs, two ANDs and an OR) into a circuit schematic, using switches for the three inputs (\(A\), \(B\), carry-in) and LEDs for the two outputs (sum, carry-out). Have it checked by a tutor, then simulate, build and test it — systematically, against the full-adder truth table. The gate-level diagram itself is in 2026-08-04-binary-arithmetic; the equations it implements are

\[S = A \oplus B \oplus C_{in} \qquad C_{out} = AB + C_{in}(A \oplus B)\]

The two-chip challenge

The challenge: build the full adder using only two chips.

The literal reading of the diagram needs three chips — a 74HCT86 for the two XORs, a 74HCT08 for the two ANDs and a 74HCT32 for the OR. Going all-NAND does not help: a full adder in NAND alone takes nine 2-input NAND gates, and a 74HCT00 holds four, so that route needs three chips too.

The two-chip answer is to convert only the carry expression to NAND and leave the sum as XORs. De Morgan on \(C_{out}\):

\[C_{out} = AB + C_{in}(A\oplus B) = \overline{\overline{AB}\cdot\overline{C_{in}(A\oplus B)}} = \text{NAND}\big(\text{NAND}(A,B),\ \text{NAND}(C_{in}, A\oplus B)\big)\]

That is two XOR gates and three NAND gates — two of the four gates on a 74HCT86 and three of the four on a 74HCT00. Two chips, with one spare gate in each.

Figure 22: The Task 1 circuit schematic in its two-chip form: a 74HCT86 supplies the two XOR gates of the sum path and a 74HCT00 the three NAND gates of the carry path. Drawn to the rules in circuit-schematics — device ID and type on every gate, a pin number on every terminal, IO board inputs attached at the point of the pentagon and outputs at its flat back, and one power block because both chips are 14-pin parts with Vcc on 14 and GND on 7. The four junction dots — one at each fan-out of A, B, CIN and A-xor-B — are the only connections; where CIN’s branch to U1:B crosses the A-xor-B drop, and where the switch wires cross CIN’s run, the wires pass without a dot.

The stages of completion, in order: schematic done / simulated / partially working / fully working with 3 ICs / fully working with 2 ICs. The two-chip build is the top rung, not an optional extra. (Completion is self-reported, not marked.)

See combinational-logic-blocks for the adder structure and circuit-schematics for the drawing rules.

Task 2 — 4-bit adder with the 74HCT283

The 74HCT283 is a single-chip 4-bit adder. Draw a schematic that adds two 4-bit numbers set on switches, showing the 4-bit result and the carry-out on LEDs, with the carry-in on a push button.

  • Use the Device Pinouts and Symbols symbol: a trapezoid with \(A_0\)–\(A_3\) on the upper left (pins 5, 3, 14, 12), \(B_0\)–\(B_3\) on the lower left (pins 6, 2, 15, 11), \(C_0\) entering the top (pin 7), \(S_0\)–\(S_3\) on the right (pins 4, 1, 13, 10) and \(C_4\) leaving the bottom (pin 9). See device-pinouts.
  • Don’t forget the power connections. It’s a 16-pin chip: Vcc is pin 16 and GND pin 8, not 14/7 as on every gate chip you have used so far.
  • Have the schematic checked, then wire it up, test it and simulate it. Try both unsigned and two’s complement test cases and check the results are what you expect. (They are the same four bits either way; only your reading of them changes, and only \(C_4\) versus the overflow rule tells you whether that reading is valid.)

Figure 23: The Task 2 schematic. Eight switches supply the two operands, a push button supplies the carry-in, and five LEDs show the sum and the carry-out. The one thing this figure exists to make unmissable is the power block: the 74HCT283 is a 16-pin package, so its supply pins are 16 and 8, and a schematic that reuses 14/7 out of habit is wrong. The switch, button and LED pin assignments are chosen from the IO board pin list in device-pinouts.

Extension — overflow detector

Add a two’s-complement overflow detector driving an LED. The catch:

There is no access to \(C_3\), which is an internal signal. The overflow output has to be expressed in terms of available information — i.e. \(A_3\), \(B_3\), \(S_3\), \(C_4\).

The usual formula \(V = C_3 \oplus C_4\) is therefore unavailable: the 74HCT283 chains \(C_1\), \(C_2\) and \(C_3\) inside the package and only brings out \(C_0\) and \(C_4\).

The rule that uses only the pins you can reach is: overflow happens exactly when both operands share a sign and the result’s sign differs from it. Adding two negatives can’t give a positive; adding two positives can’t give a negative. As an expression,

\[V = A_3 B_3 \overline{S_3} + \overline{A_3}\,\overline{B_3} S_3\]

\(C_4\) is available but not needed — the sign bits alone settle it.

Figure 24: Two ways to build the overflow LED, both using only the pins the 74HCT283 brings out. (a) is the sum-of-products form read straight off the rule, and costs three chips because the kit has no gate with more than two inputs, so each three-literal product needs two ANDs. (b) is the same function factored as a product of two XORs: A3 differs from S3 and B3 differs from S3 exactly when the two operands agree in sign and the sum does not. Its two XORs are exactly the pair left spare on Task 1’s 74HCT86, though the AND still needs a chip of its own: Task 1’s 74HCT00 has only one gate free, and an AND built from NANDs takes two.

The stages of completion for Task 2: schematic done / partially working / fully working 4-bit adder / fully working with overflow detection. Again, the extension is the top rung.

Next

Lab 4 has a preparation task to be done before the session — see week3-lab-lab-4-pre-work.

Majority Function Circuit Design

Learning Lab 2’s task, following on from revision of gate truth tables and Boolean identities (see logic-gates and boolean-algebra) and the introduction of circuit-schematics/device-pinouts conventions. Main lab objective: verify the functionality of a logic circuit either as a hardware circuit built from logic ICs, or as a Logisim simulation.

Question 1 — 3-input majority function

The 3-input majority function \(Z\) is true if at least two of the inputs \(A, B, C\) are true. Already simplified in 2026-07-30-intro-to-logic-gates (the \(M\) truth table/sum-of-products example there is this same function):

\[Z = AB + AC + BC\]

  1. Convert \(Z\) to a NAND-only circuit (using Boolean algebra or a logic diagram).

  2. Draw a circuit schematic for the NAND-only circuit — inputs are switches, output is an LED.

  3. Wire up the circuit (or simulate in Logisim) and determine the truth table.

(a) NAND-only conversion. The standard sum-of-products → NAND-only technique (double negation + De Morgan’s law, see boolean-algebra): double-invert the whole expression, then push one inversion inside with De Morgan’s law, turning each AND term into a NAND and the outer OR into a NAND of those NAND outputs:

\[Z = AB+AC+BC = \overline{\overline{AB+AC+BC}} = \overline{\overline{AB}\cdot\overline{AC}\cdot\overline{BC}}\]

i.e. \(Z = \text{NAND}\big(\text{NAND}(A,B),\ \text{NAND}(A,C),\ \text{NAND}(B,C)\big)\) — each first-level AND gate becomes a NAND gate, and the second-level OR gate becomes a NAND gate combining the (already-inverted) first-level outputs.

The catch: that final combining gate is a 3-input NAND, and the kit has none. Every gate chip in Device Pinouts and Symbols is 2-input (plus the hex inverter) — see device-pinouts — so the 3-input NAND has to be built from 2-input ones. Writing \(N_1 = \overline{AB}\), \(N_2 = \overline{AC}\), \(N_3 = \overline{BC}\):

\[Z = \overline{N_1 N_2 N_3} = \text{NAND}\big(\overline{\overline{N_1 N_2}},\ N_3\big)\]

which is three more 2-input NANDs: one for \(\overline{N_1 N_2}\), one wired as an inverter (both inputs tied together) to undo that inversion, and one to combine the result with \(N_3\).

Six 2-input NAND gates in total, so two 74HCT00 packages — four gates on the first and two on the second.

(b) Circuit schematic.

Figure 25: The NAND-only majority circuit as a circuit schematic. U1:A to U1:C are the three product terms; U1:D, U2:A and U2:B are the 3-input NAND built out of 2-input ones — combine, invert, combine again. U2:A is the NAND-as-inverter trick: both its inputs are tied to the same signal, which is what the junction dot on its input pair means. Six gates do not fit in one quad package, so the last two need a second chip, which is why U2 exists at all. The partitioning into packages, the pin assignment and the IO board pin choices follow the device pinouts.

(c) Truth table. Reading it off the definition (at least two inputs true) — and this is what the built circuit should reproduce:

\(A\) \(B\) \(C\) \(Z\)
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 1

Test the built circuit against all eight rows in this order, not at random — the systematic sweep is what catches a swapped pin. Lab 4 asks for the same habit: decide the test procedure and the truth table you are expecting (see week3-lab-lab-4-pre-work).

See also

  • circuit-schematics — the labelling rules the schematic above follows, and the seven common errors it is checked against
  • device-pinouts — the 74HCT00 gate/pin pairs and the IO board switch and LED pin numbers
  • week2-lab-binary-arithmetic — the next lab, which reuses the same NAND-conversion move on a full adder’s carry expression

Week 3

Lecture 5 — Introduction to Sequential Circuits

See flip-flops-and-latches and sequential-circuits for the reference definitions, characteristic tables and symbols.

Outline

  • Recap of combinational logic
  • Circuits that remember values
  • The D flip-flop: symbol, operation, characteristic table, waveforms
  • The SR latch built from NOR gates
  • Flip-flops vs latches; a real D flip-flop and its chips
  • Combinational vs sequential circuits; synchronous sequential circuits

Recap

The course so far stacks up in three layers, each built on the one below:

  1. Binary representations — unsigned, sign-magnitude, 1’s complement, 2’s complement, excess-\(2^{N-1}\) (see binary-number-representations, 2026-08-04-binary-arithmetic).
  2. Logic gates — NOT, AND, OR, NAND, NOR, XOR, XNOR — and Boolean algebra (see logic-gates, boolean-algebra).
  3. Combinational logic circuits — adder, adder/subtractor, multiplexer, decoder (see combinational-logic-blocks).

The circuits built so far are the 4-bit ripple carry adder (four full adders chained by their carries), the 4-bit adder/subtractor with its mode select \(M\) (\(M=0\) add, \(M=1\) subtract), the 4:1 MUX with selects \(S_1 S_0\), and the 3:8 decoder with inputs \(A,B,C\) and outputs \(D_0 \dots D_7\). All of them are combinational. Sequential circuits start here.

Worked: multiplexer implementing a given function

Consider a 4:1 multiplexer with data inputs \(A, B, C, D\) on lines 0, 1, 2, 3 respectively and select inputs \(S_1 S_0\). What must \(A, B, C, D\) be so that the multiplexer output is

\[X = S_1 . S_0 + \bar S_1 . G\]

The options: (1) \(A=0, B=0, C=0, D=1\); (2) \(A=G, B=G, C=0, D=1\); (3) \(A=G, B=0, C=0, D=1\); (4) \(A=0, B=G, C=0, D=1\); (5) none of the above.

By select code. Walk the four select codes and ask what the multiplexer has to be passing in each case. A 4:1 MUX passes exactly one data input per select code, so whatever \(X\) evaluates to for a given \(S_1 S_0\) is the value that must be sitting on the addressed input.

Figure 26: The multiplexer with the answer wired on, and the working beside it. Each row substitutes one select code into the target expression and reads off the value the addressed data input must carry; the four results down the right-hand column are the answer. Rows 1 and 2 both give G — the term S1-bar . G says nothing about S0, so both of the S1 = 0 inputs have to carry G.

The same thing algebraically. A 4:1 MUX passes whichever data input its select code addresses, so in general

\[X = \bar S_1 \bar S_0 . A + \bar S_1 S_0 . B + S_1 \bar S_0 . C + S_1 S_0 . D\]

Expand the target into the same four select terms. The \(\bar S_1 . G\) term covers both \(\bar S_1 \bar S_0\) and \(\bar S_1 S_0\), and the \(S_1 . S_0\) term is 1 for that one select code only:

\[X = \bar S_1 \bar S_0 . G + \bar S_1 S_0 . G + S_1 \bar S_0 . 0 + S_1 S_0 . 1\]

Matching term by term against the MUX expression: \(A = G\), \(B = G\), \(C = 0\), \(D = 1\).

Answer: option 2.

The trap: it’s tempting to put \(G\) on only one of the two \(\bar S_1\) lines, but \(\bar S_1 . G\) says nothing about \(S_0\), so both \(\bar S_1\) inputs must carry \(G\). That is what separates option 2 from options 3 and 4.

Two wider points:

  • Each of the four data inputs is one of \(\{1, 0, G, \bar G\}\). Those are the only four things a data input can ever need to be when a multiplexer is used to implement a function of its select variables plus one extra variable \(G\) — a constant, that variable, or its complement.
  • Using lookup/selection hardware to realise arbitrary logic is the idea programmable logic (FPGAs) is built on.

Circuits that remember values

  • The output of any logic gate or combinational circuit depends on the current value of the inputs only. A two-input adder block is an example: \(x\) and \(y\) in, \(S\) out.
  • If an input changes, the output can change too — and the previous value is lost forever.
  • In a sequential circuit, the current output depends not only on the current inputs but also on the past outputs.
  • Circuits with memory can remember values even when the input changes.

That motivates the whole rest of the course: to build anything that accumulates, counts, or holds a result, you need a storage element.

The D flip-flop

The first memory element is the D flip-flop: D is the data input, Q the output, and CLK the control input — the clock. Q copies the value of D — and remembers it — whenever CLK goes from 0 to 1 (the rising edge). A D flip-flop stores 1 bit of information.

Everything below depends on telling the two kinds of clock edge apart.

Figure 27: A clock waveform with an up-arrow on every 0-to-1 transition and a down-arrow on every 1-to-0 transition, beside the flip-flop symbols that trigger on each. Colour is only to keep the two edge types apart; it carries no other meaning. A D flip-flop responds to exactly one of these two events, and which one is settled by whether its clock pin carries a bubble.

The full symbol set, the characteristic table and a first worked waveform are in flip-flops-and-latches.

The characteristic table is the tabular definition of a flip-flop’s operation. Its right-hand column \(Q(t+1)\) is the next output: what the output will be on the next clock edge.

A D flip-flop remembers a single bit, so \(n\) D flip-flops remember \(n\) bits and an \(n\)-bit register is by definition \(n\) D flip-flops. JK and T flip-flops also exist but are not covered in this course. Flip-flops can be made out of logic gates.

Worked: D flip-flop output waveform

For the rising-edge D flip-flop above, what is the output waveform for Q, given the D and CLK waveforms in the figure?

Reading the figure. The clock has four rising edges, each marked with an arrow. D is low across the first clock pulse, rises after that pulse has ended, stays high across the second and third clock pulses, and falls again after the third rising edge but before the fourth.

Figure 28: The D and CLK waveforms with the answer, option 3, drawn in as Q. The dashed verticals are the four rising clock edges, each also marked with a blue arrow. Everything about Q is decided at those four instants and nowhere else — which is why Q’s edges never line up with D’s.

Rising clock edge D at that edge Q after the edge
1st 0 0
2nd 1 1
3rd 1 1 (no change)
4th 0 0

So Q goes high at the 2nd rising clock edge and stays high until the 4th rising clock edge, where it returns to 0. Q is not a copy of D: it lags D’s rise (waiting for the next clock edge) and lags D’s fall (holding the 1 until the next clock edge).

Answer: option 3 — the trace that rises at the second rising clock edge and falls at the fourth rising clock edge.

Why the others are wrong:

  • Option 1 rises and falls exactly with D — that’s D itself, i.e. no clocking at all.
  • Option 2 rises correctly at the second rising edge but falls at the falling edge of the third clock pulse — reacting to the wrong edge, as a negative-edge-triggered device would.
  • Option 4 goes high and low several times inside the window where D is high, dropping back to 0 between clock pulses instead of holding — it is following the clock rather than storing anything, so nothing is being remembered at all.

The general check, worth applying to any question of this shape: a rising-edge flip-flop’s output can only change at a marked rising edge. Any candidate trace with a transition anywhere else is wrong on sight, whatever D is doing there.

SR latch from NOR gates

Two cross-coupled NOR gates make a storage element: \(S\) into the top gate (output \(\bar Q\)), \(R\) into the bottom gate (output \(Q\)), each gate’s output fed back into the other gate’s spare input. This circuit is the active high SR latch.

The truth table: \(SR=00\) holds (\(Q\) unchanged, \(Q = Q_{n-1}\) — the storage, or remember, row), \(01\) resets to 0, \(10\) sets to 1, and \(11\) is invalid. With \(S=R=1\) the outputs are \(Q = \bar Q = 0\), and the two outputs coming out equal is what makes the combination invalid.

The analysis turns on the identity \(\overline{0+x} = 1 \cdot \bar x = \bar x\) — a NOR with a 0 on one input is an inverter for the other. Its companion is \(\overline{1+x} = 0\) (a NOR with a 1 on one input is pinned to 0); it is the same De Morgan step and the other half of the analysis, and flip-flops-and-latches carries both.

Circuit, both identities and the full row-by-row derivation are in flip-flops-and-latches.

Homework: re-analyse the same S-R latch with the NOR gates replaced by NAND gates, and complete the truth table. The result is the active low SR latch: the inputs become \(\bar S\) and \(\bar R\) and, importantly, the gate outputs swap over so that the top gate now carries \(Q\). That relabelling is what keeps “set” meaning set. Drawn and worked through in flip-flops-and-latches.

Flip-flops vs latches

Latches are level triggered — they respond to changes of logic level on their inputs. Modify a latch so it responds instead to an edge (a momentary transition) of a control input, and you have a flip-flop: it stores 1 bit while being sensitive only to a clock edge, so it changes its output only at the edges and holds the value in between.

A clock has a positive edge (0→1) and a negative edge (1→0), so a D flip-flop can be positive- or negative-edge triggered — see Figure 27 above. In a positive edge triggered D flip-flop, input D is copied to output Q at the positive edge of the clock. In between clock edges the flip-flop is not responsive, so it stores the value.

JK and T flip-flops exist but are not covered in this course. The state of a flip-flop is the value it is storing. Flip-flops are more useful than latches.

The four schematic symbols (plain / bubble / wedge / bubble-and-wedge on the clock pin, with the wedge meaning edge-triggered and the bubble meaning falling edge) are drawn and tabulated in flip-flops-and-latches.

A real D flip-flop’s internal schematic is six NAND gates in three cross-coupled pairs. Its \(\overline{\text{PRE}}\) and \(\overline{\text{CLR}}\) inputs are active low and asynchronous: they reach into the latches directly and do not wait for a clock edge. The symbol is in flip-flops-and-latches.

The chips that package them: the 74HCT74 (dual D flip-flop) and the 74HCT273 (eight flip-flops, i.e. one byte). See device-pinouts for the 74HCT74 pinout — the 74HCT273 is not in the course’s device-symbols document, so there is no pinout for it in the vault.

Combinational vs sequential circuits

The formal contrast:

Combinational Sequential
Contents Logic gates only, no flip-flops Includes flip-flops
Output Uniquely determined by the inputs — the same inputs always give the same output Determined by the current inputs and the current state (the values in the flip-flops)
When it can change Whenever an input changes Only when the clock ‘ticks’
Blocks met so far Adders, multiplexers, decoders, demultiplexers, encoders Counters, registers

A combinational example, first met in Lecture 2: \(A\) into an AND gate whose other input is \(B + C\), giving \(A(B+C)\) — a circuit with no memory at all.

The general block diagram (combinational logic + flip-flops + feedback path, with the clock entering the flip-flops only) and the definition of a synchronous sequential circuit — storage elements can only change at discrete instants of time, namely the clock edges — are drawn in sequential-circuits.

Reminders

Coming up:

  • Lab 4 (Mon–Tue this week) — combinational logic. Make sure you attempt the preparation task. Use logic ICs or Logisim software to test your circuits.
  • Lab 5 (Thu–Fri this week) — flip-flops. Use Logisim software to test the circuits. Kit loaning happens in Lab 5.

See also

Lecture 6 — Sequential Circuits 1: Shift Registers

See shift-registers for the reference material, and sequential-circuits and flip-flops-and-latches for the material recapped at the start.

Outline

  • Admin
  • Sequential circuits
  • Shift registers

Recap: flip-flops and sequential circuits

First met in Lecture 5; the full detail is in the concept notes.

  • D flip-flop — \(D\) input, \(Q\) output, \(CLK\) control input; \(Q\) copies (and remembers) \(D\) on the rising edge of \(CLK\). Only D flip-flops are used in this course. Optional asynchronous SET and CLR inputs set/clear \(Q\) outside clock edges and are typically active-low. D flip-flops are what you build sequential circuits from — e.g. [counters]. Full detail in flip-flops-and-latches.
  • Combinational vs sequential circuits — combinational = logic gates only, output uniquely determined by the inputs, so you always get the same output for a given set of inputs. An example is the pair \(AB + AC\) and \(A(B+C)\) — two ANDs into an OR beside an OR into an AND, with truth tables that agree; see logic-gates. Sequential = includes flip-flops, output determined by current inputs and current state, and can change when the clock ticks. See sequential-circuits.
  • Sequential circuits — state = values in the flip-flops; present state vs next state; the output depends on input and state (or sometimes just the state), and the next state depends on inputs and state. Mano’s block diagram is a combinational circuit feeding flip-flops, with the flip-flop outputs routed back round to the combinational circuit’s inputs and Clock pulses entering the flip-flops directly. See sequential-circuits, and the counter-structure figure in [counters] for the same diagram with its external inputs removed.
  • Synchronous sequential circuit — storage elements can only change at discrete instants. The clock is a train of narrow pulses, and those instants are its rising edges. Outputs of storage elements change only on the edges of the control signal, unlike logic gates whose output changes whenever the input does. The rule: in a synchronous sequential circuit, all the sequential elements share a common clock signal.

Registers

A register is a group of flip-flops: an \(n\)-bit register is \(n\) flip-flops storing \(n\) bits. Two points:

  • a register is a sequential circuit without any combinational logic — unlike the general sequential-circuit block diagram above, which has a combinational block in the loop;
  • registers store binary information (data/instructions) inside a processor.

An example is a 4-bit register with parallel inputs \(I_0..I_3\), parallel outputs \(A_0..A_3\), and common Clock and (active-low) Clear lines. It is drawn as the register figure in the shift-registers note.

Shift registers

A shift register is a register capable of shifting its binary information in one or both directions. The example is Mano’s Fig. 6-3: serial input \(SI\) → four D flip-flops in series → serial output \(SO\), all on a common \(CLK\). It is drawn, with a clock-by-clock trace, in the shift-registers note.

Two applications:

  • Serial ↔︎ parallel conversion — shift registers can do serial-to-parallel conversion and vice-versa. The starting point is the plain chain of four D flip-flops on a common clk: a lead into the first \(D\) on the left, each stage’s output running straight into the next stage’s \(D\). The conversion adds parallel taps to that chain.
  • Parallel load and serial shift — four D flip-flops on a common clk again, with a multiplexer in front of each flip-flop’s \(D\) input to choose between the shift source and the parallel input. See combinational-logic-blocks for the mux, and the shift-registers note for the construction, drawn out.

Exercise: bidirectional shift register

Using the same multiplexer concept, draw a 3-bit shift register which allows data to be shifted in either direction.

Hint: build it from the element below, where DIRN is 0 for left shift, 1 for right shift.

Figure 29: The hint element: a 2-to-1 multiplexer whose data inputs are labelled only 0 and 1, whose select input DIRN enters through the bottom sloping edge, and whose output drives the D input of one edge-triggered D flip-flop. The mux inputs have no names and the clock input no label. One mux plus one flip-flop is a stage, and DIRN picks which neighbour that stage listens to.

Answer. Instantiate three copies of the element, share one DIRN line and one clock across all three, and for each stage wire

  • mux input 0 (selected when DIRN = 0, left shift) to the neighbouring stage on the left-shift source side, and
  • mux input 1 (selected when DIRN = 1, right shift) to the neighbouring stage on the right-shift source side,

with an external serial input supplying whichever end of the register has no neighbour in that direction. Writing the bits as \(Q_2 Q_1 Q_0\) with \(Q_2\) most significant, and taking “left shift” to move bits towards the more-significant end:

Stage Mux input 0 (DIRN=0, left) Mux input 1 (DIRN=1, right)
\(Q_2\) \(Q_1\) \(SI_R\)
\(Q_1\) \(Q_0\) \(Q_2\)
\(Q_0\) \(SI_L\) \(Q_1\)

Sanity check on \(Q_2Q_1Q_0 = 110\) with both serial inputs at 0: one edge with DIRN = 0 gives \(100\); one edge with DIRN = 1 gives \(011\). The full wired-up register is drawn in the shift-registers note.

The point of the exercise: a bidirectional shift register is just a unidirectional one with a mux per flip-flop, and the direction control is a single line shared by every mux, so the whole register commits to one direction per clock edge.

Universal shift register

A universal shift register does hold / shift left / shift right / parallel load in one device, selected by control inputs. See the shift-registers note.

Wide shift registers

Shift registers can shift multiple bits at a time. An example is a 4-stage, 8-bit queue: four 8-bit registers in a row (inputs \(A..H\), outputs \(Q_1..Q_8\), each with an ENB enable), each register’s outputs feeding the next register’s inputs as an 8-bit bus, all on a common clock. A byte at Input emerges at Output four clock edges later. It is drawn in the shift-registers note.

This is also the shape the lab preparation task takes, two stages deep and four bits wide instead of four stages of eight.

Lab 06 preparation task

2-digit lock/unlock circuit: the user inputs two decimal digits (4 bits each) AB in serial. The circuit matches the two input digits with a code (say CD) and unlocks if the input matches the code (i.e. AB = CD).

The preparation-task handout specifies the architecture precisely, and it is not what “in serial” might suggest:

  • A two-stage, 4-bit-wide shift register — 8 flip-flops. The register is digit-serial, not bit-serial: each shift moves a whole 4-bit digit from stage 1 to stage 2.
  • Four switches set a digit value in parallel (\(0_{10}\)–\(15_{10}\), i.e. \(0000_2\)–\(1111_2\)); a push button clocks that digit into stage 1, pushing stage 1’s previous contents into stage 2.
  • Two LEDs — one for unlocked, one for locked — plus a reset push button. After reset both stages hold 0000; at all times other than a match, “locked” is on and “unlocked” is off.
  • The lock remembers the last two digits entered, so it opens on any sequence ending in the code. If the code is 34 and you enter 5, 3, 4, it unlocks on the third digit.

Figure 30: The combination lock at block level. Inputs on the left feed flip-flops in the centre, which feed flip-flops on the right, so the older digit ends up on the right. Hence the match condition shown: the first code digit C is compared against stage 2 and the second digit D against stage 1, not the other way round. Bus widths are lettered beside the heavy lines.

Your code is the last two digits of your student number, with any zeroes changed to \(10_{10} = 1010_2\); and if the two digits are identical, replace the second with \(11_{10} = 1011_2\). Enter the left digit first. (E.g. 40123456 → 5 then 6; 46543210 → 1 then 10; 44444444 → 4 then 11.)

The ordering trap, from the handout’s closing NB:

NB: The natural and eminently reasonable way to begin laying out the logic diagram and/or circuit schematic is to have the inputs on the left, feeding into a set of flipflops in the centre, which in turn feed into a set of flipflops on the right. In this case, the entered code moves left to right, such that the older of the two values is stored in the flipflops on the right and the newer on the left. Ensure that your code checking logic reflects this ordering.

Since you enter the left code digit first, that digit is the older one by the time the lock should open, so it is the one sitting in stage 2. That is the asymmetry Figure 30 spells out; getting it backwards is a lock that opens on the code reversed.

Deliverables: a logic diagram and a circuit schematic, using the device pinouts from Blackboard (see device-pinouts and circuit-schematics). The handout offers Logisim as an option, not a requirement — “You may also simulate your logic diagram in Logisim before coming to lab sessions” — and says the circuit is built during the practical session, along with variations on it. The comparison itself is combinational — see combinational-logic-blocks. The lab session this feeds is week4-lab-sequential-circuits-shift-registers.

The handout recommends watching the week 3, Lecture 6 recording before attempting this task.

Reminders

  • Labs 6 and 7 (next week, week 4) have preparation tasks which should be attempted before coming to the labs.
  • Attempt the weekly exercise and quizzes.

Lab 4 Pre-Work

Lab 4 is the combinational-logic lab, and almost all of its work happens before the session. The preparation sheet asks for three circuit schematics; the session itself is spent peer-checking them, getting them signed off by a tutor, and building the third one. Pairs with 2026-08-06-combinational-logic and combinational-logic-blocks.

The device pinout information is on Blackboard (learning resources → lab resources → digital logic) and in device-pinouts. The drawing rules every one of the three schematics is marked against are in circuit-schematics.

Warm-up: three recall questions from Lecture 4

Three multiple-choice questions on combinational logic. They are worth doing before you look at the circuits, because all three are about reading a block symbol correctly, which is exactly what Circuit 3 needs.

What does this symbol represent?

A trapezoid with the short edge on the left carrying three inputs \(A\), \(B\), \(C\) and the long edge on the right carrying eight outputs \(D_0 \ldots D_7\).

Answer: a 3:8 decoder. The flare direction is the whole tell — see csse2010-diagram-notation: a multiplexer’s wide edge is on the left (many data inputs funnelling to one output, selects entering the bottom), a decoder’s wide edge is on the right (\(n\) inputs fanning out to \(2^n\) outputs).

The distractors are worth naming:

  • 3:8 multiplexer / 8:3 multiplexer — a multiplexer has exactly one output whatever its size, so eight output stubs rule it out immediately.
  • 3:8 de-multiplexer — the near-miss. A demultiplexer routes a separate data input to one of \(2^n\) outputs under \(n\) selects; this symbol has only the three address lines and no data input, and no select stubs on the bottom edge.
  • 8:3 encoder — that would be eight in, three out; this is the other way round.

See combinational-logic-blocks for what each block actually does.

Which diagram implements \(Z = \overline{S}\cdot X + S\cdot Y\)?

Five 2-to-1 multiplexers, differing only in what is wired to the 0 and 1 data inputs.

Figure 31: The five candidate multiplexers, lettered A to E. The data input labelled 0 is the one selected when S = 0, so the expression S-bar.X + S.Y is read straight off: X on input 0, Y on input 1, and nothing complemented. Option A is the only one that matches; every other option either swaps X and Y or complements a data input that the expression does not complement.

Answer: A. The mux’s data input labels are the value of the select that picks them, so \(\overline{S}X + SY\) means “X on 0, Y on 1”. No complement appears in the expression, so any option with a bar on a data input is out (B, C, E), and D has \(X\) and \(Y\) the wrong way round.

What should be connected to \(A, B, C, D\) so that \(X = \overline{S_1 \oplus S_0}\)?

A 4-to-1 multiplexer with data inputs \(A, B, C, D\) on 0–3, selects \(S_1 S_0\), output \(X\).

Figure 32: The 4-to-1 multiplexer with the answer written onto its data inputs in red, and the table that produces it. Using a mux as a function generator is mechanical: the select pair addresses each data input by its binary index, so tabulate the function against every select combination and the output column is literally the list of constants to tie the data inputs to. Here the function is the complement of XOR, so the constants are 1, 0, 0, 1. The 0/1 written at the end of a data input is the course’s logic-diagram notation for tying that input to logic low or logic high (device-pinouts); on a real schematic they become the ground and Vcc symbols.

Answer: (d) \(A=1\), \(B=0\), \(C=0\), \(D=1\) — the XNOR column. This is the technique of using a mux to implement a logic function; see combinational-logic-blocks.

Circuit 1 — a 2-to-1 multiplexer from 2-input NAND gates only

Draw a circuit schematic diagram for a 2-to-1 multiplexer that uses only 2-input NAND gates. The data inputs should be connected to push buttons. The select input should be connected to a switch. The output should be connected to an LED.

Hint: do the truth table (or a function table) for a 2-to-1 multiplexer, obtain the logic expression, then draw a logic circuit and convert it to the NAND equivalent circuit by replacing each gate with its NAND version. If you use Logisim, do not use the MUX module.

1. Function table

\(S_0\) \(D_0\) \(D_1\) \(F\)
0 0 0 0
0 0 1 0
0 1 0 1
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1

2. Sum of products and simplification

Deriving the unsimplified sum of products from the true outputs in the table:

  • \(S_0 = 0\), \(D_0 = 1\), \(D_1 = 0 \rightarrow \bar{S_0} \cdot D_0 \cdot \bar{D_1}\)
  • \(S_0 = 0\), \(D_0 = 1\), \(D_1 = 1 \rightarrow \bar{S_0} \cdot D_0 \cdot D_1\)
  • \(S_0 = 1\), \(D_0 = 0\), \(D_1 = 1 \rightarrow S_0 \cdot \bar{D_0} \cdot D_1\)
  • \(S_0 = 1\), \(D_0 = 1\), \(D_1 = 1 \rightarrow S_0 \cdot D_0 \cdot D_1\)

Using Boolean algebra, we can simplify this expression:

\[ \begin{aligned} F &= \bar{S_0} D_0 \bar{D_1} + \bar{S_0} D_0 D_1 + S_0 \bar{D_0} D_1 + S_0 D_0 D_1 \\ &= \bar{S_0} D_0 (\bar{D_1} + D_1) + S_0 D_1 (\bar{D_0} + D_0) \\ &= \bar{S_0} D_0 (1) + S_0 D_1 (1) \\ &= \bar{S_0} D_0 + S_0 D_1 \end{aligned} \]

3. NAND equivalent conversion

To implement this circuit using only 2-input NAND gates, convert the simplified AND-OR expression into a NAND-NAND expression by applying double negation and De Morgan’s laws:

\[ \begin{aligned} F &= \overline{\overline{\bar{S_0} D_0 + S_0 D_1}} \\ &= \overline{(\overline{\bar{S_0} D_0}) \cdot (\overline{S_0 D_1})} \end{aligned} \]

4. Circuit schematic

Exactly four 2-input NAND gates are needed, so the whole circuit fits on one 74HCT00. Using circuit-schematics labelling conventions they become U1:A–U1:D:

  1. One NAND acting as an inverter for \(S_0\) (both inputs tied to \(S_0\)) to make \(\bar{S_0}\).
  2. One NAND computing \(\overline{\bar{S_0} D_0}\).
  3. One NAND computing \(\overline{S_0 D_1}\).
  4. One final NAND combining the outputs of 2 and 3.

Figure 33: Circuit 1 as a schematic. The one thing to look at is U1:A: its two inputs are tied together by the wire carrying the junction dot, which is what turns a NAND into an inverter and is the move that keeps the whole design inside one package. Note also that S0 fans out twice - to U1:A and to U1:C - so the switch wire carries a second dot. The four gates use the 74HCT00’s pin sets 1,2 to 3; 4,5 to 6; 9,10 to 8; 12,13 to 11, and one power block covers the single chip type. The task only says switch, push buttons and LED, so the pin assignments for the switch, the two buttons and the LED are chosen from the IO board list in device-pinouts.

Circuit 2 — a 2-to-4 decoder

Draw a circuit schematic diagram for a 2-to-4 decoder, using whichever logic gates you prefer (from those available in the CSSE2010/CSSE7201 lab). The two inputs should be connected to switches. The outputs should be connected to LEDs.

The truth table (inputs \(A_1\), \(A_0\); outputs \(X_0 \ldots X_3\)):

A1 A0   X0 X1 X2 X3
0 0 1 0 0 0
0 1 0 1 0 0
1 0 0 0 1 0
1 1 0 0 0 1

1. Boolean expressions

Since \(A_1, A_0\) can only take four combinations, each output’s truth-table row is already a single minterm — no Boolean simplification is needed, just one 2-input AND term per output:

  • \(X_0 = \bar{A_1} \cdot \bar{A_0}\)
  • \(X_1 = \bar{A_1} \cdot A_0\)
  • \(X_2 = A_1 \cdot \bar{A_0}\)
  • \(X_3 = A_1 \cdot A_0\)

2. Circuit schematic

Because every term is exactly two literals, this is the only one of the three circuits that needs no gate-building tricks at all: a 74HCT04 to make the two complements once each, and a 74HCT08 for the four products.

Figure 34: Circuit 2 as a schematic. Four vertical rails carry A1, A0 and their complements past all four AND gates, and each gate taps the one pair of rails that spells its minterm - the same rail idiom as the 3-to-8 decoder. Only the dots are connections: every other place a tap crosses a rail it is two wires passing. Exactly one AND gate can be high at a time, which is the decoder’s defining property and the thing to check when testing. The 74HCT04’s second half runs backwards (pin 9 in, pin 8 out), but this circuit only needs the first two inverters, so it is not exercised here.

Circuit 3 — a 4-bit two’s complement adder/subtractor

Using a 74HCT04, 74HCT157 and a 74HCT283, draw a circuit schematic diagram for a circuit which can act as a 4-bit two’s complement adder or subtractor. The output (4 bits from the 74HCT283, shown on LEDs) will have the value \(A+B\) or \(A-B\), where \(A\) and \(B\) are the 4-bit inputs taken from switches.

A push button input (\(M\), mode) determines whether the circuit adds or subtracts — if the value is 0, addition is performed; if the value is 1, subtraction is performed by calculating \(A+(-B)\).

The circuit is similar to the adder-subtractor in Lecture 4, except that the selection of the \(B\) input bits as \(B\) or \(\overline{B}\) is to be performed using multiplexers instead of XOR gates. (The 74HCT157 is a quad 2-to-1 multiplexer with a shared select input.) The carry output should be shown on an LED also.

The multiplexer IC in the kit, and its active-low ENABLE

Pin 15 of the 74HCT157 is its active-low ENABLE input. Two questions about it:

  • What does active low mean? The pin performs its function when it is driven low, not high. That is why the device sheet writes the name overlined, \(\overline{\text{ENABLE}}\), and draws a bubble on that pin in the schematic symbol — the bubble is the notation for “inverted here” (see logic-gates).
  • What should be connected to pin 15 for the IC to work? Logic 0 — tie it to GND. Left floating it is undriven and can read as either level at random, so the multiplexer intermittently stops passing its inputs through. This is the same failure mode the flip-flop lab returns to; see week3-lab-logisim-and-flip-flops.

Design reasoning

In two’s complement, \(-B = \bar{B} + 1\), so subtraction can be built from the same adder used for addition: \(A - B = A + \bar{B} + 1\). This means mode input \(M\) needs to do two things at once:

  • Select whether the adder’s \(B\) input is \(B\) (add) or \(\bar{B}\) (subtract) — done with the 74HCT157.
  • Inject the “\(+1\)” that turns one’s complement into two’s complement — done by wiring \(M\) straight into the adder’s carry-in, since \(C_0 = 0\) for addition (no extra bit needed) and \(C_0 = 1\) for subtraction (adds the required 1).

So \(M\) is wired to both the 74HCT157’s select line and the 74HCT283’s \(C_0\) pin — no separate control logic at all. That single fan-out is the whole idea of the circuit; everything else is bit-plumbing. Compare the XOR version of the same trick in combinational-logic-blocks — the multiplexer is doing exactly the job the controlled inverter did there, and the mode line still doubles as the carry-in either way.

Note also what the 74HCT157 being a quad mux with a shared select buys you: one chip conditions all four bits of \(B\) together, which is what you want, because a per-bit select would let the operand be half-complemented.

Select polarity. Wiring \(M\) straight to SEL (rather than through an inverter) assumes SEL low selects the A channel and SEL high selects B. That is the 74HCT157’s actual behaviour, but it comes from the part’s datasheet — the Device Pinouts and Symbols sheet (device-pinouts) names both channels and the select line without saying which level picks which. So put the raw \(B\) switches on the A inputs and the inverted ones on B, and check the polarity on the bench before you trust it: if the modes come out swapped, that one assumption is why.

Figure 35: Circuit 3 as a schematic. Follow the mode line M along the bottom: it forks once, at the junction dot, into the 74HCT157’s SEL (pin 1) and the 74HCT283’s carry-in C0 (pin 7) - one push button doing both halves of A + not(B) + 1. Channel A of the multiplexer takes the raw B switches and channel B takes them inverted by the 74HCT04, so SEL = 0 passes B and SEL = 1 passes B-bar. ENABLE (pin 15) is tied to ground because it is active low. The power block is split in two because the 74HCT04 is a 14-pin part while the 157 and the 283 are 16-pin. The task only names the three chips and the input and output devices, so the pin assignments for the switches, button and LEDs are chosen from the IO board list in device-pinouts.

The wiring, chip by chip

  • U1 (74HCT04, hex inverter) — generates \(\bar{B_0}\)–\(\bar{B_3}\) for the multiplexer’s B channel:
    • U1:A (1→2): \(B_0\) → \(\bar{B_0}\)
    • U1:B (3→4): \(B_1\) → \(\bar{B_1}\)
    • U1:C (5→6): \(B_2\) → \(\bar{B_2}\)
    • U1:D (9→8): \(B_3\) → \(\bar{B_3}\) — note the direction reversal in the second half of the package
  • U2 (74HCT157, quad 2-to-1 MUX) — selects \(B_i\) (channel A, \(M=0\)) or \(\bar{B_i}\) (channel B, \(M=1\)) per bit. SEL (pin 1) \(= M\); ENABLE (pin 15) tied to GND:
    • A0–A3 = pins 2, 5, 11, 14 = the \(B\) switches
    • B0–B3 = pins 3, 6, 10, 13 = U1’s inverted outputs
    • Y0–Y3 = pins 4, 7, 9, 12 → the adder’s B inputs
  • U3 (74HCT283, 4-bit adder):
    • A0–A3 (pins 5, 3, 14, 12) = the \(A\) switches (unchanged by mode)
    • B0–B3 (pins 6, 2, 15, 11) = U2’s Y0–Y3
    • C0 (pin 7, carry-in) = \(M\) (the same signal as U2’s SEL)
    • S0–S3 (pins 4, 1, 13, 10) → LEDs
    • C4 (pin 9, carry-out) → LED

Power supply connections are shown once per chip type, and this circuit has two different pin pairs: the 74HCT04 is a 14-pin package (Vcc 14, GND 7), while the 74HCT157 and 74HCT283 are 16-pin (Vcc 16, GND 8). Do not group all three together.

In the session

The session is spent working on the three schematics above:

  • Complete the preparation tasks, and make sure the three schematics are correctly drawn, not just roughly right.
  • Exchange your solutions with others at your table for peer evaluation.
  • Get a tutor to verify your schematic diagrams.
  • Construct the Circuit 3 (adder/subtractor) circuit on the breadboard and verify the functionality. Logisim simulation is allowed as well.

Construction advice

  • Keep circuits neat — use the shortest wires you can.
  • Turn the power off before you change the circuit.
  • Debugging: use the logic probe (the PR pin on the IO board — pin 16, see io-board), and be systematic: check power and ground connections first, then start at the inputs and work towards the outputs.

For each circuit

  1. Make sure you have a correct schematic before you build.
  2. Decide your test procedure — what truth table are you expecting?
  3. Build or simulate.
  4. Test systematically.

Don’t expect things to always work in the first instance. If things don’t work, troubleshoot systematically. Troubleshooting is also a part of your learning. A neatly drawn circuit schematic will always help when troubleshooting.

Stages of completion for the build: logic diagram only / schematic only / simulation only / attempted construction with incorrect output / fully working circuit with functionality verified.

Next

Lab 5 is the Logisim and flip-flops session, and the one where kits are loaned out — see week3-lab-logisim-and-flip-flops.

Logisim and Flip-Flops

Learning Lab 5 — verify the operation of latches and the D flip-flop in Logisim, then build one. It is also the session where kits are loaned out. Pairs with 2026-08-10-introduction-to-sequential-circuits and flip-flops-and-latches.

Recall

There are two types of logic circuit: combinational and sequential. The basic building block of sequential circuits is the flip-flop, which stores 1 bit of information. See flip-flops-and-latches and sequential-circuits.

Worked: which is NOT a combinational circuit?

A counter. Adders, multiplexers, decoders and adder/subtractors are all combinational — their output is a function of the current inputs alone, and every one of them appeared in Lab 4 (see week3-lab-lab-4-pre-work). A counter has to remember where it is, so it is sequential. See [counters].

Worked: which waveform captures the behaviour of this circuit?

The circuit is a rising-edge-triggered D flip-flop (a wedge on the clock input with no bubble in front of it) with \(A\) on \(D\), \(CLK\) on the clock, and \(Q\) taken out. SET and CLR are lettered inside the box but not driven.

Figure 36: The circuit, its two input waveforms CLK and A, and the four candidate outputs. The answer is (d). The dashed verticals through the four rising clock edges, and the A = 1/1/0/1 labels above them, are what makes the answer mechanical, since a rising-edge flip-flop copies D to Q at those four instants and nowhere else.

Answer: (d). Sample \(A\) at each rising edge of \(CLK\) and nowhere else: the values are 1, 1, 0, 1, so \(Q\) goes high at the first edge, holds through the second, drops at the third and rises again at the fourth. Between edges \(Q\) does nothing at all, however much \(A\) moves.

The three wrong waveforms each fail in a different, recognisable way:

  • (a) agrees with (d) from the second clock edge onwards but misses the first. \(A\) is already high when the first edge arrives, so the flip-flop does capture it — this is the answer you get by mentally starting one edge late.
  • (b) changes exactly once, at the moment \(A\) last rises. That is a wire, not a flip-flop: no clock edge is involved.
  • (c) changes at instants where the clock is falling as well as where it is rising, which no single-edge-triggered device does.

Worked: which of these is FALSE about a negative-edge-triggered D flip-flop?

“Changes on the D input affect the output when the clock signal is at logic 0.”

That describes a level-triggered latch — the thing an edge-triggered flip-flop is defined in contrast to. An edge-triggered device responds only at the transition; for a negative-edge part, when the clock goes 1 → 0. The other three statements (stores 1 bit, is a sequential circuit, changes when the clock goes from 1 to 0) are all true.

Contrast the previous question: the symbol there had a bare wedge (rising edge), and this question is about a bubbled wedge (falling edge). The wedge and the bubble read independently — the wedge says edge-triggered, the bubble says inverted; see the symbol table in flip-flops-and-latches.

Floating pins

If a pin isn’t being driven it is floating, and a floating pin can act as 0 or 1 at random.

The question is whether it matters that a pin is left disconnected, in three cases on one specific wired-up 74HCT74 (pinout in device-pinouts). The answers differ sharply.

Figure 37: The wired-up 74HCT74: the 14-pin package with both flip-flops inside, the three highlighted pin groups, and the only three external connections the circuit actually makes. The fill colours mark the three cases, one colour each - magenta for pins 11 and 12, yellow for pins 1 and 4, cyan for pin 6 - and mean nothing beyond that grouping; red and blue mark the supply stubs. The three connections are switch S0 to D1 (pin 2), push button B0 to CLK1 (pin 3) and LED L0 to Q1 (pin 5). The signal names outside each pin box are from the device sheet’s pin table (device-pinouts).

Reading the figure: the circuit uses only the first flip-flop. The second one (pins 8–13) is wired to nothing at all, and of the first flip-flop’s six pins only three are driven or read.

Disconnected Matters?
Pins 11 and 12 — CLK2 and D2, the clock and data of the second, entirely unused flip-flop No. That half’s outputs (pins 8 and 9) go nowhere, so whatever its flip-flop does is invisible. Untidy rather than wrong; good practice is to tie unused inputs to a fixed level so the chip isn’t switching at random and drawing current.
Pin 6 — \(\overline{Q1}\), the complement output of the flip-flop you are using No. It is an output. Leaving an output unconnected is always safe; it is only ever a problem to leave an input undriven.
Pins 1 and 4 — CLR1 and SET1 of the flip-flop you are using Yes, badly. These are active-low asynchronous inputs. Floating, they can assert at random and clear or set the flip-flop behind your back, so \(Q\) changes with no clock edge in sight. They must be tied high.

The distinction to take away: a floating input on a device you are using is a real fault; a floating output is harmless; a floating input on a section you are not using is merely untidy.

A naming clash worth knowing about. The device sheet calls pins 4 and 1 SET and CLR; Task 3 below calls the same two pins PRE and CLR; flip-flops-and-latches writes them \(\overline{\text{PRE}}\) and \(\overline{\text{CLR}}\). The course is inconsistent about this (see csse2010-diagram-notation). The pinout figure uses the device sheet’s names, and the Task 3 section below uses PRE/CLR for the two push buttons while the chip symbol inside its schematic keeps the device sheet’s SET/CLR on pins 4 and 1. Same two pins, two names, one figure.

The same trap comes back in Lab 4 as the 74HCT157’s active-low ENABLE, which must be tied low for the chip to work at all — see week3-lab-lab-4-pre-work — and again in Lab 7, see week4-lab-lab-7-exercises.

Tasks 1 and 2 — simulate the S-R latches

  1. Simulate the active-high S-R latch (cross-coupled NOR gates) in Logisim and verify its operation.
  2. Simulate the active-low S-R latch (cross-coupled NAND gates) and verify its operation.

Both circuits, both truth tables, and why the NAND version’s set/reset roles invert and its inputs are drawn overlined, are in flip-flops-and-latches.

The thing to actually verify in the simulator is the part a truth table hides: the hold row, where both inputs are inactive and the latch keeps whatever it had. Drive it into set, return the inputs to their inactive values, and check the output stays put — that is the memory, and it is the only behaviour that distinguishes a latch from a gate.

Task 3 — build a 74HCT74 circuit

The circuit to implement is a 2-input AND gate fed by \(A\) and \(B\), whose output drives the \(D\) input of a rising-edge-triggered D flip-flop.

Figure 38: The Task 3 circuit - two switch inputs ANDed into D, one clock input on a wedge (so edge-triggered), Q out. The clock is labelled CK, which is one of the four spellings this course uses for that pin. Nothing else is drawn: the asynchronous inputs and Q-bar are left off, even though the task requires both to be wired.

So \(Q\) takes the value of \(A \cdot B\) on each rising clock edge and holds it until the next one. Drawing the schematic means adding what this logic diagram leaves out. The task asks for a schematic that:

  • uses a 74HCT74 (and other chips as needed) — the AND gate needs a second chip;
  • uses push buttons for the CLK (CK), PRE and CLR inputs;
  • uses switches for the A and B inputs;
  • uses LEDs for the \(Q\) and \(\overline{Q}\) outputs.

Have it checked by a tutor, then build and test it.

Why put inverters between the buttons and the PRE/CLR inputs?

Because \(\overline{\text{PRE}}\) and \(\overline{\text{CLR}}\) are active low, and a push button is the wrong shape for an active-low input. What the flip-flop needs is a pin that sits reliably high whenever you are not asking for a preset or clear, and goes low only while you press — otherwise the asynchronous input is asserted at rest and the clocked behaviour you are trying to test never happens. Putting an inverter between the button and the pin turns the button’s natural “pressed = high” into the “pressed = low” the pin wants, and holds the pin high the rest of the time. (Asserting \(\overline{\text{PRE}}\) and \(\overline{\text{CLR}}\) at once is an illegal input; see flip-flops-and-latches.)

This is the same problem as the floating-pin question above. Pins 1 and 4 must be held high and only pulsed low, and neither leaving them floating nor wiring a bare button to them achieves that.

Figure 39: The Task 3 schematic. Three chips: U1 for the AND gate, U2 for the flip-flop, U3 for the two inverters that make the active-low PRE and CLR usable from push buttons. All three are 14-pin parts sharing Vcc 14 and GND 7, so one power block covers them. The pin assignments and the IO board pin numbers are from device-pinouts.

Test it the way Lab 4 asks you to test everything (see week3-lab-lab-4-pre-work): decide the expected behaviour first. Here that is four rows of \(A \cdot B\) crossed with “did a clock edge happen”, plus two asynchronous checks — press PRE with \(A\cdot B = 0\) and confirm \(Q\) goes high without a clock edge, then press CLR and confirm it goes low the same way.

Kit borrowing

  • Fill in, sign and submit the kit borrowing agreement (also on Blackboard), then collect your kit. Wait at your table; don’t queue.
  • Check all the parts are there and write your student number on the kit.
  • Don’t use the kit until advised — some parts break easily, especially the USB connector on the I/O board (see io-board).
  • You’ll start with the logic chips and breadboard, and will be advised how to use them. The AVR microcontroller is only needed in the second half of the course — leave those parts alone until then.
  • Drop the course after borrowing? Return the kit within 3 business days to the EECS school office, building 78 room 425. (If you’re thinking of dropping, don’t borrow one.)
  • The kit must be returned by the end of semester in working order.

Dongles

By the end of semester you’ll be using two USB-A cables for data — one for programming, one for serial communication — and one of them from about halfway through. On your own laptop you may need a dongle. There are workarounds but they all have downsides, so get one sooner rather than later.

Next

Lab 6 has a preparation task — the combination lock, spelled out in 2026-08-13-shift-registers — to be done before the session. See week4-lab-sequential-circuits-shift-registers.

Week 4

Lecture 7 — Counters

See [counters] for the reference material on counters, and shift-registers, sequential-circuits and flip-flops-and-latches for the background.

Counter design is a procedure: write the sequence down as a state table, read each \(D\) column off as a Boolean function of the \(Q\)s, then build it. Three circuits carry that idea — the one-bit toggle, the 2-bit binary up counter, and a 2-bit counter for a non-binary sequence with a don’t-care state.

Outline

  • A worked question on the mux-per-stage shift register
  • Shift register types
  • Counters, and binary counters
  • A digital system application built around a counter
  • State: current state, next state, and the \(D\) inputs
  • Worked counter examples
  • Next: state machines

Schedule

From the course teaching outline:

  • Week 4, Mon-Tue 17-18 Aug — this lecture, Lecture 7: Counters (17 Aug).
  • Week 4, Thu-Fri 20-21 Aug — Lecture 8: Finite State Machines (20 Aug).
  • Learning labs this week: Lab 6 Shift Registers (P2, Mon-Tue) and Lab 7 Counters (P1, Thu-Fri).
  • Week 5: Lecture 9 ALU and Control Unit (24 Aug), Lecture 10 Introduction to AVR and Assembly Language (27 Aug), with labs 8 (Finite State Machines) and 9 (AVR Assembly Programming 1).

Later in the schedule: the week 6 Thu-Fri revision and help sessions for the lab exam, and the week 7 Lab Exam (Digital Logic), held during the scheduled lab sessions. Everything from this lecture onwards is lab-exam material three weeks later.

Worked: shift direction control

Which of the following statements about the circuit below is true?

A. When A is 1, flip-flop values are shifted to the right B. When A is 0, flip-flop values are shifted to the right C. When A is 0, flip-flop values stay the same D. When FN is 1, flip-flop values are shifted to the left E. When FN is 0, flip-flop values stay the same F. When FN is 0, flip-flop values are shifted to the left

The circuit is the mux-per-stage construction from last lecture, two stages deep.

Figure 40: A two-stage shift register with a 2-to-1 mux in front of every flip-flop. Each mux’s 0 input is fed back from its own flip-flop’s \(Q\) — that is the hold path — and its 1 input takes the value from the stage before it (\(A\) from outside, for stage 1). One line, \(FN\), selects both muxes, so \(FN\) enables the shift rather than choosing a direction; there is no left-shift path anywhere in the circuit. Each mux is drawn wide-edge-left with the select entering the bottom sloping edge (see csse2010-diagram-notation). The one crossing, the \(CLK\) riser over the \(FN\) rail, carries no junction dot and so is not a connection.

Reading Figure 40 off, with \(Q_a\) = stage 1 and \(Q_b\) = stage 2:

\[D_a = \begin{cases} A & FN = 1 \\ Q_a & FN = 0\end{cases} \qquad D_b = \begin{cases} Q_a & FN = 1 \\ Q_b & FN = 0\end{cases}\]

  • When \(FN = 1\), \(A\) is loaded into stage 1 and stage 1’s value moves into stage 2 — data shifts left-to-right along the diagram, one stage per clock.
  • When \(FN = 0\), each flip-flop’s \(D\) input is its own \(Q\), so every flip-flop reloads the value it already had — nothing changes.

\(FN\) is therefore a shift enable, not a direction control, so every option mentioning “shifted to the left” is out; and \(A\) is plain data rather than a control signal, so A/B/C are out too.

Answer: E — when FN is 0, flip-flop values stay the same.

Shift register types

There are seven shift-register configurations: serial in/shift right/serial out, serial in/shift left/serial out, parallel in/serial out (PISO), serial in/parallel out, parallel in/parallel out, rotate right and rotate left. Rotate right is a right shift with a wrap-around path.

Getting 0101 into a 4-bit register takes four clocks when it is shifted in serially (a serial load) and a single clock when it is loaded in parallel: \(n\) clocks versus one. The configurations and the clock-by-clock trace are in shift-registers.

Counters

An \(n\)-bit binary counter has \(n\) flip-flops and \(2^n\) states, and counts \(0\) to \(2^n-1\). The definition of a counter and the 4-bit binary counting sequence table are in [counters]. The sequence runs 000…0, 000…1, ⋮, 111…1 and then back to 000…0, which is \(2^n\) states. The state count is the length of the cycle, not just the width of the register.

Digital system application

Where a counter sits in a real system — an automated tablet-bottling line (the example is from Floyd’s Digital Fundamentals):

  • A keypad for the number of tablets per bottle feeds an encoder, which feeds Register A. Register A drives Decoder A and a 7-segment display showing the tablets-per-bottle setting, and also a code converter producing the binary code for the preset number.
  • On the conveyor, a sensor emits one pulse per tablet passing the valve. Those pulses are the clock of a counter, so the counter holds the binary code for the actual number of tablets in the bottle. A separate pulse resets the counter to zero when the next bottle is in place.
  • A comparator tests the counter value against the preset value. Its output goes HIGH when \(A = B\): HIGH closes the valve and advances the conveyor, LOW keeps the valve open.
  • The counter value also feeds an adder, whose other input is the running total held in Register B; the comparator’s HIGH also causes the new sum to be stored back into Register B. Register B drives Decoder B (total display) and a MUX/DEMUX path that sends the accumulated total on to a computer for storage.

The counter, adder, register, decoder, comparator, encoder, mux and demux blocks covered so far in the course compose into a complete system — see combinational-logic-blocks for the mux/decoder blocks and 2026-08-04-binary-arithmetic for the adder.

One-bit counter

The circuit is a single D flip-flop, clocked on \(CLK\), with a wire from its \(\overline{Q}\) output looped back around to its \(D\) input.

Figure 41: Left: one D flip-flop with \(\overline{Q}\) looped back to \(D\), so the next state is always the complement of the present state. The \(Q\) output line crosses the feedback wire with no junction dot, i.e. no connection. Right: the waveform, with an arrow on each rising clock edge and the value of \(Q\), 0 or 1, written on each segment. \(Q\) toggles on every rising edge, so the flip-flop divides the clock frequency by two.

The derivation takes three steps. First the equation: \(D = \overline{Q}\). Then the roles: \(Q\), the flip-flop’s stored value, is the present state; \(D\), what is sitting on the input at the clock edge, is the next state. Then those two written out as columns give the state table:

present state \(Q\) next state \(D\)
0 1
1 0

Since \(D\) is the next state and \(D = \overline{Q}\), the value inverts on every clock edge and the counter counts

\[0 \to 1 \to 0 \to 1 \to \ldots\]

which is exactly the \(n = 1\) binary counter (\(2^1 = 2\) states, counting \(0\) to \(2^1 - 1 = 1\)). This is the standard toggle configuration, and the two-row table above is the smallest possible instance of the method the larger counters below use.

NotePresent state or current state?

Current state and present state are synonyms. The course uses both and settles neither; see csse2010-diagram-notation.

State

Three statements make counter design mechanical. Take two D flip-flops on a common \(CLK\), with inputs \(D_1\) and \(D_0\) still to be worked out:

  • the values stored in the flip-flops are the current state of the circuit;
  • the \(D\) inputs are the next state;
  • the \(D\) inputs are some (combinational) function of the current state and the inputs.

So each \(D\) input is driven by its own combinational circuit, and each of those circuits is fed from the \(Q\) outputs. That is the whole architecture — flip-flops hold the state, a block of combinational logic computes the next one, and the clock steps between them. The design method that follows is written up as a recipe in [counters]; the underlying state terminology is in sequential-circuits.

Counter example — the 2-bit binary up counter

The problem is to design a 2-bit counter for \(00 \to 01 \to 10 \to 11 \to 00\). Design means a sequence is given and the circuit has to be found; the worked question after this one is analysis, where a circuit is given and the sequence has to be found.

Start from two D flip-flops on a common \(CLK\) with nothing connected to their \(D\) inputs, and a current-state/next-state table with columns \(Q_1, Q_0 \mid D_1, D_0\) and a row for each of the four states. Filling in the next state for each row gives the state table:

\(Q_1\) \(Q_0\) \(D_1\) \(D_0\)
0 0 0 1
0 1 1 0
1 0 1 1
1 1 0 0

Reading the two next-state columns as Boolean functions of \(Q_1\) and \(Q_0\) gives two equations:

\[D_0 = \overline{Q_0} \qquad\qquad D_1 = Q_1 \oplus Q_0\]

\(D_0\) is 1 exactly when \(Q_0\) is 0, so bit 0 toggles every clock — it is the one-bit counter of Figure 41, unchanged. \(D_1 = Q_1 \oplus Q_0\) means bit 1 takes its own value flipped whenever \(Q_0 = 1\) and keeps it whenever \(Q_0 = 0\) — which is the carry rule for binary counting: bit 1 flips exactly on the clocks where bit 0 rolls over from 1 to 0.

Figure 42: The 2-bit synchronous binary up counter for \(00 \to 01 \to 10 \to 11 \to 00\). \(\overline{Q_0}\) loops back to \(D_0\) (bit 0 toggles every clock); an XOR of \(Q_1\) and \(Q_0\) drives \(D_1\). Both flip-flops share one clock, which is what makes the counter synchronous. The gate is drawn the conventional way round — inputs on the left, output on the right — a rule the course schematics guide states and that holds without exception (see csse2010-diagram-notation). The feedback to \(D_0\) is taken from the \(\overline{Q}\) pin at the lower right of the flip-flop.

As a check, step the circuit through a clock train and write down the state at each rising edge: \(00\), \(01\), \(10\), \(11\), \(00\). The circuit walks the sequence it was designed from. This is the direct model for the 3-bit design in Lab 7.

Worked: what sequence does this counter count through?

What sequence does the counter below count through? (Assume \(Q_1Q_0\) starts at \(00\).)

A. \(00 \to 11 \to 10 \to 01 \to 00\) B. \(00 \to 10 \to 11 \to 01 \to 00\) C. \(00 \to 11 \to 01 \to 10 \to 00\) D. \(00 \to 01 \to 11 \to 10 \to 00\) E. \(00 \to 01 \to 10 \to 11 \to 00\) F. \(00 \to 10 \to 01 \to 11 \to 00\)

This is the design problem run backwards: the circuit is given, the sequence has to be recovered.

Figure 43: The counter to analyse. The left flip-flop’s \(\overline{Q}\) is wired back to its own \(D\), so \(D_1 = \overline{Q_1}\) and \(Q_1\) toggles every clock. The right flip-flop’s \(D\) is driven by a two-input XNOR — an OR body with the extra input-side arc and an inversion bubble on the output — whose inputs are \(Q_1\) and \(Q_0\), so \(D_0 = \overline{Q_1 \oplus Q_0}\). Everything in the answer turns on that gate symbol. SET and CLR are lettered inside the boxes and are unused.

Tabulating from Figure 43:

\(Q_1\) \(Q_0\) \(D_1 = \overline{Q_1}\) \(D_0 = \overline{Q_1 \oplus Q_0}\) next state
0 0 1 1 11
1 1 0 1 01
0 1 1 0 10
1 0 0 0 00

Starting from \(00\): \(00 \to 11 \to 01 \to 10 \to 00 \to \ldots\)

Answer: C.

The gate reading rests entirely on the symbol — the extra input-side arc plus the output bubble is an XNOR, not a NOR. Don’t try to settle it by elimination: an XOR reading gives \(D_0 = Q_1 \oplus Q_0\), \(D_1 = \overline{Q_1}\) and the sequence \(00 \to 10 \to 01 \to 11 \to 00\), which is one of the listed options (F).

This counter is not a binary counter. Its sequence is a legitimate four-state cycle that simply isn’t the binary count — exactly the case the second key point below covers.

Key points

Four key points, all recorded in [counters]:

  • the next state is a function of the previous state (and possibly of external inputs);
  • the count sequence can be the binary numbers but does not have to be — if it is, the counter is a binary counter;
  • these circuits are synchronous: all flip-flops share the same clock;
  • asynchronous counters exist as well, but the course does not discuss them.

Worked example — a non-binary sequence with a don’t-care

The problem:

Design a 2-bit counter that counts \(00 \to 10 \to 01 \to 00 \to\)

Step 1 — the state table. Present state on the left, next state on the right. The fourth row, present state \(11\), is an unused state. Its next-state entries are written \(X_1 X_0\), where an \(X\) is a don’t care term:

\(Q_1\) \(Q_0\) \(D_1\) \(D_0\)
0 0 1 0 \(00 \to 10\)
1 0 0 1 \(10 \to 01\)
0 1 0 0 \(01 \to 00\)
1 1 \(X_1\) \(X_0\) unused state

Step 2 — spend the don’t-cares. Write down both choices for each column, then pick:

\[ \begin{aligned} D_0:\quad & X_0 = 0 \;\Rightarrow\; D_0 = Q_1\overline{Q_0} &\qquad& X_0 = 1 \;\Rightarrow\; D_0 = Q_1 \quad\checkmark\\ D_1:\quad & X_1 = 0 \;\Rightarrow\; D_1 = \overline{Q_1}\,\overline{Q_0} \quad\checkmark &\qquad& X_1 = 1 \;\Rightarrow\; D_1 = \overline{Q_1 \oplus Q_0} \quad\times \end{aligned} \]

\(X_0 = 1\) is chosen because it is strictly simpler: adding the \(11\) row to the single \(10\) row lets \(Q_0\) drop out entirely and leaves \(D_0 = Q_1\), a bare wire. \(X_1 = 1\) is rejected even though it also looks tidy — an XNOR is one gate, same as an AND. The reason is the next step.

Step 3 — check the unused state. With \(X_1X_0 = 01\) the transitions are

\[00 \to 10 \to 01 \to 00, \qquad 11 \to 01\]

This is a robust design: the unused state falls straight back into the cycle, so a power-up glitch into \(11\) costs one clock and nothing more. Taking \(X_1 = 1\) instead would have given \(11 \to 11\) and the counter would have hung there forever — which is why that option is rejected. The final equations are

\[D_1 = \overline{Q_1}\,\overline{Q_0} \qquad\qquad D_0 = Q_1\]

Figure 44: The implementation of \(D_1 = \overline{Q_1},\overline{Q_0}\) and \(D_0 = Q_1\) for \(00 \to 10 \to 01 \to 00\). One AND gate over the two complement outputs is the whole of the combinational logic; \(D_0\) needs no gate at all, being \(Q_1\) wired straight across. As in Figure 42 the gate is drawn inputs-left/output-right. The clock is lettered clk here and CLK in the other figures; the course uses both and settles neither (see csse2010-diagram-notation).

As a check, step the circuit through a clock train again: the state at each rising edge is \(00\), \(10\), \(01\), \(00\), and from \(11\) it drops into \(01\). The full write-up of this example, including the sum-of-products working, is in [counters]; week4-lab-lab-7-exercises is the same procedure at \(n = 3\).

Next: state machines

More sequential circuits come next: state machines. In the general synchronous sequential circuit, inputs and fed-back state go into a combinational circuit, whose outputs are both the circuit outputs and the flip-flop inputs; the flip-flops are driven by clock pulses and their outputs are fed back (see sequential-circuits).

A counter may or may not have external inputs. This is the link between the two: a counter is the special case of a state machine whose transition logic reads nothing but the state itself, which is why none of the four counter circuits above has an input other than the clock. See state-machines and 2026-08-20-state-machines.

Reminders

  • Lab 7 (Counters) runs in the P1 sessions this week (Thu-Fri) — the pre-lab schematic for the 3-bit synchronous counter must be drawn beforehand. See week4-lab-lab-7-exercises, and device-pinouts for the flip-flop packages.
  • Lab 6 (Shift Registers) runs in the P2 sessions (Mon-Tue) this week.
  • The centrally scheduled 90-minute in-semester theory exam is on Saturday 5 September, and the Digital Logic lab exam is during the scheduled lab sessions in week 7.

Lecture 8 — State Machines

See state-machines for the reference material — Moore vs Mealy, the diagram and table notation, encoding schemes and the design procedure — and sequential-circuits, flip-flops-and-latches and [counters] for the background. The drawing conventions for state diagrams and state tables are catalogued in csse2010-diagram-notation.

Outline

  1. State diagrams
  2. State tables
  3. State encoding

Sequential circuits

  • State = the value stored in the flip-flops.
  • Output depends on the input and the state.
  • Next state depends on the inputs and the state.

In the block diagram, the combinational circuit is the logic gates:

Figure 45: The sequential-circuit block diagram (from Mano, Digital Design, 3rd ed.). Flow is left to right with the state fed back around the outside, and the clock enters on its own stub reaching only the flip-flops — never the gates. The red arrow and the blue Logic Gates label mark the combinational circuit as the logic gates. D and Q name the two feedback-side wires, which is what makes the two functions below readable off the picture.

Writing \(Q\) for the present state (PS) and \(D\) for the next state (NS), the one box marked Combinational circuit is really two functions computed side by side:

\[\underbrace{\text{OUT} = g(\text{IN}, Q)}_{\text{output logic}} \qquad\qquad \underbrace{D = f(\text{IN}, Q)}_{\text{transition logic}}\]

The clock pulses reach only the flip-flops, never the gates — see sequential-circuits.

“Output depends on input and state” is the general sequential-circuit statement, i.e. the Mealy form. A Moore machine is narrower: the output depends on the state alone. Every state machine drawn in this course from here on obeys the narrower rule.

State machines

Sequential circuits can also be called state machines, or finite state machines (FSMs). A state machine has a finite number of possible states, is in only one current state at a time, and can transition to other states based on the inputs and the current state.

\(N\) flip-flops give \(2^N\) states.

Defining the states from the problem

The first step in a design is not a circuit at all — it is deciding what the states are:

A vending machine accepts 5 cent and 10 cent coins, and dispenses a candy when it receives 15 cents in total. What can be the different states?

Tabulate the running total:

Coins inserted 0 5 10 15 20 50
Candy? ✗ ✗ ✗ ✓ ✓ + change —

So the states are the amounts accumulated so far. 15 dispenses; 20 dispenses and owes change (reachable by putting 10c on top of 10c). 50 is ruled out — with only 5c and 10c coins the machine dispenses long before it could accumulate that much, so it is not a reachable state.

The transferable move: ask what must the circuit remember?, and the answer is the state set.

Moore vs Mealy

  • Mealy — outputs depend on the current state and the inputs.
  • Moore — outputs depend only on the current state (the flip-flop values), so outputs can only change when the state changes.

A Moore machine is a special case of a Mealy machine, and this course sticks to Moore machines.

The two structures have the same three-block shape: combinational circuit → flip-flops → combinational circuit, with the state fed back to the first block. The only difference is one branch — in the Mealy machine the input line also runs forward into the second (output) combinational block; in the Moore machine it does not. Both are drawn in the “Moore and Mealy machines” section of state-machines.

State diagrams

The notation for a state diagram:

Figure 46: The state-diagram notation. A state is a circle split by a horizontal chord: state name above, output value(s) below. State names are free-form — a systematic S0 and an arbitrary word (Alex) are both allowed — and outputs are a bare bit string with no separators. A transition is a plain single-headed arrow labelled with a Boolean expression written above it; the red box marks the special case where a machine has exactly one input and the label degenerates to a bare 0 or 1. The bottom row gives example labels, including the unlabelled arrow, which means true.

Reading it off:

  • A state is a circle divided by a horizontal chord — state name above, output value(s) below. Nothing else goes inside.
  • Names are free-form. \(S_0\), \(S_1\), … is a convention, not a rule; Alex is just as legal.
  • A transition is an arrow labelled with a logic expression. If the expression is true, the transition is made. Label algebra is the ordinary Boolean notation of boolean-algebra: overbar for NOT, · or juxtaposition for AND, + for OR.
  • No label means “true” — i.e. always transition.
  • Exactly one input is a special case: the label may be written as a bare 0 or 1 rather than \(\overline{Z}\) or \(Z\). This is the red-boxed case in the figure.

The notation leaves two things unsettled — see csse2010-diagram-notation:

  • how to mark the start / reset state (the diagrams below mark none: no incoming stub, no double circle, no reset label), and
  • how to draw a self-loop (there is no set shape for one, although the completeness rule below guarantees most machines need them).

Worked: a two-state lock system

A lock with one input key and one output locked:

IN key OUT locked
0 1
1 0

Figure 47: The two-state lock. The state name sits above the chord and the output value below it, so OPEN is the state whose locked output is 0. With one input there are two arrows out of every state, and here they account for both values of key: present the key and the lock opens or stays open, remove it and it closes or stays closed. The self-loops are needed for completeness.

Example — binary counter with 2-bit output

A counter has no inputs at all beyond the clock, so every arrow is unlabelled — the machine advances one state per clock edge regardless.

Figure 48: A 2-bit binary counter as a state machine: the four states in a left-to-right row, forward transitions between neighbours, and the wrap-around drawn as a long arc below the row. Outputs 00, 01, 10, 11, and no transition labels because there is no input to test. No state is marked as the start state. Compare the gate-level construction of the same thing in the counters note.

Example — binary up/down counter, one input

One input \(U\): 1 means count up, 0 means count down. The two output sequences:

\(U = 1\) 00, 01, 10, 11, 00, 01, …
\(U = 0\) 11, 10, 01, 00, 11, 10, …

Figure 49: The up/down counter with a single input. Each state has exactly two arrows out — one for U and one for its complement — which is completeness for a one-input machine. The U arrows run clockwise through the ring and the U-bar arrows run anticlockwise. The states sit in a square ring because a straight row does not extend to a machine with arrows running both ways.

Because there is exactly one input, the one-input special case applies: these labels could equally be written as bare 1 and 0.

Example — binary up/down counter, two inputs

Two inputs \(U\) and \(D\), giving four commands:

\(U\) \(D\) Meaning
1 0 count up
0 1 count down
1 1 set to 11
0 0 reset to 00

With \(N\) inputs there are \(2^N\) transitions to account for out of each present state — here \(2^2 = 4\) arrows out of every state. Working the four commands through each state gives:

Current state \(U\overline{D}\) (up) \(\overline{U}D\) (down) \(UD\) (set 11) \(\overline{U}\,\overline{D}\) (reset 00)
\(S_0\) (00) \(S_1\) \(S_3\) \(S_3\) \(S_0\)
\(S_1\) (01) \(S_2\) \(S_0\) \(S_3\) \(S_0\)
\(S_2\) (10) \(S_3\) \(S_1\) \(S_3\) \(S_0\)
\(S_3\) (11) \(S_0\) \(S_2\) \(S_3\) \(S_0\)

Combinations sharing a destination merge onto one arrow, and the merged labels simplify:

Transition Merged label Simplifies to
\(S_0 \to S_3\) \(\overline{U}D + UD = D(\overline{U} + U)\) \(D\)
\(S_1 \to S_0\) \(\overline{U}D + \overline{U}\,\overline{D} = \overline{U}(D + \overline{D})\) \(\overline{U}\)
\(S_2 \to S_3\) \(U\overline{D} + UD = U(\overline{D} + D)\) \(U\)
\(S_3 \to S_0\) \(U\overline{D} + \overline{U}\,\overline{D} = \overline{D}(U + \overline{U})\) \(\overline{D}\)

Both steps are the complement law \(X + \overline{X} = 1\) used once each — see boolean-algebra.

Figure 50: The up/down counter with set and reset. Every state has four input combinations to account for, drawn here as three arrows each once the combinations sharing a destination are merged. S0 keeps its reset combination as a self-loop and S3 keeps its set combination as one; the labels are shown in merged form with the simplification after the equals sign.

Completeness

Each possible combination of inputs should be addressed exactly once for each state — i.e. transition arrows from each state must encompass all possibilities (exactly once).

The two-input counter above is the check in practice: four input combinations, four accounted for out of every state, none twice. Equivalently — the labels leaving a state must OR to 1 (no gap) and no two of them can be true at once (no ambiguity).

State tables

A state diagram can equivalently be written as a state table. There are two forms; both here are filled in for the up/down counter with the single input \(U\) (1 up, 0 down) — the machine of Figure 49.

One-dimensional — a row for every combination of state and inputs:

Current State Input \(U\) Next State \(Q_1\) \(Q_0\)
\(S_0\) 0 \(S_3\) 0 0
\(S_0\) 1 \(S_1\) 0 0
\(S_1\) 0 \(S_0\) 0 1
\(S_1\) 1 \(S_2\) 0 1
\(S_2\) 0 \(S_1\) 1 0
\(S_2\) 1 \(S_3\) 1 0
\(S_3\) 0 \(S_2\) 1 1
\(S_3\) 1 \(S_0\) 1 1

Two-dimensional — one row per state, with a next-state column for every combination of inputs:

Current State Next State (\(\overline{U}\)) Next State (\(U\)) \(Q_1\) \(Q_0\)
\(S_0\) \(S_3\) \(S_1\) 0 0
\(S_1\) \(S_0\) \(S_2\) 0 1
\(S_2\) \(S_1\) \(S_3\) 1 0
\(S_3\) \(S_2\) \(S_0\) 1 1

In the full layout the last two columns sit under a single spanning Outputs header, and the \(\overline{U}\) / \(U\) columns under a spanning Next State header; the tables above repeat the header text instead. Two smaller notational points, both unresolved in csse2010-diagram-notation: the output bits are written both unsubscripted (Q1, Q0) and subscripted (\(Q_1\), \(Q_0\)), and the first column is headed both Current State and Present State. Nothing in the course picks a winner, so the subscripted form is used here for consistency with the rest of these notes.

The output columns repeat in the 1D form (both rows for \(S_0\) output 00) because this is a Moore machine — the output is a property of the state alone, which is exactly why the 2D form can give it one column per state. In a Mealy machine the 2D form’s output would have to be split by input as well.

State encoding

Each state must be encoded into flip-flop values: choose the number of flip-flops and the bit patterns representing each state. Ideally, pick the encoding that makes the combinational logic simple — for both the output logic and the next-state logic.

Two encodings of the four-state binary counter:

State Binary One-hot
\(S_0\) 00 0001
\(S_1\) 01 0010
\(S_2\) 10 0100
\(S_3\) 11 1000

One-hot coding uses one flip-flop per state, with only one flip-flop holding 1 at any time — four flip-flops here instead of two. A third scheme, Gray coding, is in state-machines.

Worked: one-hot encoding of the binary counter with 2-bit output

Call the four flip-flops \(F_3 F_2 F_1 F_0\), one per state, with state \(S_k\) encoded by \(F_k = 1\). The counter’s cycle \(S_0 \to S_1 \to S_2 \to S_3 \to S_0\) becomes

\[D_1 = F_0, \qquad D_2 = F_1, \qquad D_3 = F_2, \qquad D_0 = F_3\]

— i.e. no next-state gates at all, just four wires. That circuit is a 4-bit shift register wired end to end, otherwise known as a ring counter (see shift-registers and [counters]).

The outputs are no longer free, though. \(Q_1\) is 1 in \(S_2\) and \(S_3\), and \(Q_0\) is 1 in \(S_1\) and \(S_3\):

\[Q_1 = F_2 + F_3, \qquad Q_0 = F_1 + F_3\]

so two OR gates. Under binary encoding the trade runs the other way: the outputs are the flip-flops (\(Q_1, Q_0\) straight out, no gates) but the next-state logic needs \(D_1 = Q_1 \oplus Q_0\) and \(D_0 = \overline{Q_0}\). That is the point of choosing an encoding, in miniature — the encoding decides where the gates end up, and how many flip-flops you pay for.

Sequence detector example

Design a state machine which detects the pattern 101 in an incoming bit stream and outputs a 1 whenever it detects this pattern. The output is 1 for one clock cycle after the third digit is clocked in.

Figure 51: A worked bit stream for the 101 detector. The numbers along the top are bit positions. The braces mark the three occurrences of 101 in the input; the third is drawn on its own level because it overlaps the second. The dashed arrows show which output bit each match raises, and those output bits are red.

Three detections: the 101 finishing at position 5, the one finishing at position 9, and the overlapping one finishing at position 11 — the 1 at position 9 serves as both the end of one match and the start of the next. That is the whole difficulty of the problem: after a successful detection the machine must not go back to “seen nothing”, because it has already seen the first 1 of a possible next match.

The machine itself is one of the two examples worked through in the Blackboard recordings.

Steps involved in FSM design

  1. Defining state based on the problem definition.
  2. Drawing the state diagram.
  3. Completing the state table (1D or 2D).
  4. State encoding and re-doing the state table with encoded states.
  5. Obtaining the Boolean expressions for next state logic (i.e. the \(D\)’s) and for outputs.
  6. Drawing the logic diagram.
  7. Simulating in Logisim to verify functionality. ⎫ the labs
  8. Building and testing the circuit in hardware. ⎭

Steps 1–6 are lecture material; 7 and 8 are what the learning labs do — see week5-lab-state-machines. Steps 5 and 6 are the same derivation used to build a counter by hand — see [counters] and circuit-schematics.

The examples above take the up/down counter to step 3 and the plain counter to step 4; steps 5 and 6 are exercised on the sequence detector in the recordings.

Two recordings on Blackboard work through further examples, and should be watched after this lecture.

See also

Lab 7 Exercises

NoteProvided task

Pre-Lab Preparation

You should complete a circuit schematic diagram as described below before your Lab 7 session in week 4 (Thu-Fri). You should consult the device pinout information on Blackboard (captured in device-pinouts; the drawing rules it has to satisfy are in circuit-schematics). You will be testing this circuit (or a similar circuit) during the prac session.

Design Requirements

Design and draw a circuit schematic diagram for a 3-bit synchronous counter which counts through your allocated sequence (see table below).

Hardware Specifications:

  • Clock: You must use a push button for the clock signal.
  • Preset: Use a single switch to allow your counter to be preset (i.e., to 111).
  • Clear: Use a single switch to allow your counter to be cleared (i.e., to 000).
  • Outputs: Your count output should be shown on three LEDs.
    • \(Q_2\): Most Significant Bit (MSB)
    • \(Q_1\): Middle bit
    • \(Q_0\): Least Significant Bit (LSB)

Note: Your allocated sequence has seven binary numbers; you may choose to do whatever you like with the missing number – i.e., if the counter ever has this value then we don’t care what the next count value is.

It is recommended that you simulate your circuit using Logisim to ensure it counts through the expected sequence.

Count Sequences

Find the sequence corresponding to the last digit of your 8-digit UQ student number:

Table 1: Count sequence by last digit of student ID
Last digit of UQ ID Count Sequence
0 111 -> 011 -> 101 -> 110 -> 001 -> 000 -> 010 -> 111 -> …
1 111 -> 010 -> 101 -> 110 -> 100 -> 000 -> 001 -> 111 -> …
2 000 -> 011 -> 010 -> 110 -> 100 -> 001 -> 111 -> 000 -> …
3 111 -> 100 -> 101 -> 000 -> 110 -> 001 -> 011 -> 111 -> …
4 000 -> 101 -> 011 -> 010 -> 001 -> 110 -> 100 -> 000 -> …
5 000 -> 110 -> 001 -> 100 -> 111 -> 011 -> 010 -> 000 -> …
6 111 -> 010 -> 000 -> 110 -> 001 -> 101 -> 100 -> 111 -> …
7 111 -> 001 -> 110 -> 101 -> 100 -> 000 -> 010 -> 111 -> …
8 111 -> 000 -> 001 -> 101 -> 011 -> 110 -> 100 -> 111 -> …
9 000 -> 100 -> 001 -> 110 -> 101 -> 011 -> 010 -> 000 -> …

In the lab session

The prep task above is only step one. The whole exercise is a seven-step procedure, modelled on the worked examples in lecture 7:

  1. Pick the counting sequence based on your student number.
  2. Draw the state table — present state and next state.
  3. Obtain Boolean expressions for the \(D\)’s in terms of the \(Q\)’s.
  4. Simplify the expressions if necessary.
  5. Obtain a logic diagram — and optionally simulate it.
  6. Convert the logic diagram to a schematic diagram.
  7. Build and test the circuit for correct operation.

Steps 1–4 are Table 2 through Equation 7 below, step 5 is Figure 52, step 6 is Figure 53, and step 7 is the bench work. The session runs as review of preparation task → design → build and test.

Don’t forget the preset/clear inputs on the flip-flops. The design requirements need both a preset (to 111) and a clear (to 000), and only a flip-flop with both asynchronous inputs can give you that — the 74HCT74 has a SET and a CLR on each half, so it can; the 74HCT175 used in task 2 has a single shared CLR and no set at all, so it cannot. See device-pinouts.

Working

My student number is ——6, so I will be sequencing: 111 -> 010 -> 000 -> 110 -> 001 -> 101 -> 100 -> 111 -> …

Let’s map the current and next states:

Table 2: Current and next state
Current State (\(Q_2 Q_1 Q_0\)) Next State (\(D_2 D_1 D_0\)) Comment
0 0 0 1 1 0 \(000 \to 110\)
0 0 1 1 0 1 \(001 \to 101\)
0 1 0 0 0 0 \(010 \to 000\)
0 1 1 X X X unused state
1 0 0 1 1 1 \(100 \to 111\)
1 0 1 1 0 0 \(101 \to 100\)
1 1 0 0 0 1 \(110 \to 001\)
1 1 1 0 1 0 \(111 \to 010\)

Deriving \(D_2\)

Rows where \(D_2 = 1\):

\(Q_2 Q_1 Q_0\) \(D_2\)
0 0 0 1
0 0 1 1
1 0 0 1
1 0 1 1

Each row gives one product term (1 for that row, 0 elsewhere):

\[ \begin{aligned} D_2 &= \bar{Q_2} \cdot \bar{Q_1} \cdot \bar{Q_0} + \bar{Q_2} \cdot \bar{Q_1} \cdot Q_0 + Q_2 \cdot \bar{Q_1} \cdot \bar{Q_0} + Q_2 \cdot \bar{Q_1} \cdot Q_0 \\ &= \bar{Q_2} \cdot \bar{Q_1} \left(\bar{Q_0} + Q_0\right) + Q_2 \cdot \bar{Q_1} \left(\bar{Q_0} + Q_0\right) & \text{(Distributive law)} \\ &= \bar{Q_2} \cdot \bar{Q_1} \cdot \mathbf{t} + Q_2 \cdot \bar{Q_1} \cdot \mathbf{t} & \text{(Negation law)} \\ &= \bar{Q_2} \cdot \bar{Q_1} + Q_2 \cdot \bar{Q_1} & \text{(Identity law)} \\ &= \bar{Q_1} \left(\bar{Q_2} + Q_2\right) & \text{(Distributive law)} \\ &= \bar{Q_1} \cdot \mathbf{t} & \text{(Negation law)} \\ &= \bar{Q_1} & \text{(Identity law)} \end{aligned} \tag{1}\]

\(D_2\) is just \(\bar{Q_1}\), so it needs no gate at all. FF1’s \(\overline{Q}\) output wires straight to FF2’s \(D\) input.

Deriving \(D_1\)

Sum of products where \(D_1 = 1\) (000, 100, 111):

\[ \begin{aligned} D_1 &= \bar{Q_2} \cdot \bar{Q_1} \cdot \bar{Q_0} + Q_2 \cdot \bar{Q_1} \cdot \bar{Q_0} + Q_2 \cdot Q_1 \cdot Q_0 & \\ &= \bar{Q_1} \cdot \bar{Q_0} \left(\bar{Q_2} + Q_2\right) + Q_2 \cdot Q_1 \cdot Q_0 & \text{(Distributive law)} \\ &= \bar{Q_1} \cdot \bar{Q_0} \cdot \mathbf{t} + Q_2 \cdot Q_1 \cdot Q_0 & \text{(Negation law)} \\ &= \bar{Q_1} \cdot \bar{Q_0} + Q_2 \cdot Q_1 \cdot Q_0 & \text{(Identity law)} \end{aligned} \tag{2}\]

Deriving \(D_0\)

Sum of products where \(D_0 = 1\) (001, 100, 110), plus the unused state 011 — its next state is a don’t care, so I am free to take \(D_0 = 1\) there, which lets \(Q_1\) cancel:

\[ \begin{aligned} D_0 &= \bar{Q_2} \cdot \bar{Q_1} \cdot Q_0 + \bar{Q_2} \cdot Q_1 \cdot Q_0 + Q_2 \cdot \bar{Q_1} \cdot \bar{Q_0} + Q_2 \cdot Q_1 \cdot \bar{Q_0} & \\ &= \bar{Q_2} \cdot Q_0 \left(\bar{Q_1} + Q_1\right) + Q_2 \cdot \bar{Q_0} \left(\bar{Q_1} + Q_1\right) & \text{(Distributive law)} \\ &= \bar{Q_2} \cdot Q_0 \cdot \mathbf{t} + Q_2 \cdot \bar{Q_0} \cdot \mathbf{t} & \text{(Negation law)} \\ &= \bar{Q_2} \cdot Q_0 + Q_2 \cdot \bar{Q_0} & \text{(Identity law)} \\ &= Q_2 \oplus Q_0 & \text{(definition of XOR)} \end{aligned} \tag{3}\]

\(\bar{Q_2} \cdot Q_0 + Q_2 \cdot \bar{Q_0}\) is exclusive-or, so \(D_0\) is a single XOR gate.

Checking Robustness

011 was left unused in Table 2, so its next state was treated as a don’t care when deriving Equation 1, Equation 2 and Equation 3. The circuit will still compute something for this state, so I need to check it doesn’t get stuck there. Substituting \(Q_2 Q_1 Q_0 = 011\) into each equation:

\[ \begin{aligned} D_2 &= \bar{Q_1} \\ &= \bar{1} \\ &= 0 \end{aligned} \tag{4}\]

\[ \begin{aligned} D_1 &= \bar{Q_1} \cdot \bar{Q_0} + Q_2 \cdot Q_1 \cdot Q_0 \\ &= \bar{1} \cdot \bar{1} + 0 \cdot 1 \cdot 1 \\ &= 0 \cdot 0 + 0 \\ &= 0 \end{aligned} \tag{5}\]

\[ \begin{aligned} D_0 &= Q_2 \oplus Q_0 \\ &= 0 \oplus 1 \\ &= 1 \end{aligned} \tag{6}\]

So \(D_2 D_1 D_0 = 001\), meaning 011 -> 001. This is not 011 itself, and 001 is already part of my sequence, so the counter does not lock up in the unused state: it self-corrects back into the main count sequence within one clock cycle.

Taking the don’t care as a 1 in \(D_1\) as well would have simplified it to \(\overline{Q_1 \oplus Q_0}\), but then 011 -> 011 and the counter would hang, so I only used it for \(D_0\).

Conclusion

As per Equation 1, Equation 2 and Equation 3, the excitation equations for the counter are:

\[ \begin{aligned} D_2 &= \bar{Q_1} \\ D_1 &= \bar{Q_1} \cdot \bar{Q_0} + Q_2 \cdot Q_1 \cdot Q_0 \\ D_0 &= Q_2 \oplus Q_0 \end{aligned} \tag{7}\]

and the robustness check in Equation 4, Equation 5 and Equation 6 confirms that the one unused state, 011, transitions to 001 rather than to itself. The counter is therefore self-correcting, and these three equations fully and safely implement my allocated count sequence.

That comes to five 2-input gates, which fit into three gate chips. No inverters are needed anywhere: the 74HCT74 gives \(\overline{Q}\) alongside \(Q\), so \(\overline{Q_1}\) and \(\overline{Q_0}\) are free.


Circuit Schematic

Figure 52: The complete counter: the gates of Equation 7 on the left, the three flip-flops on the right, and \(Q\)/\(\overline{Q}\) fed back to the input rails. \(D_2\) has no gate: it is FF1’s \(\overline{Q}\) wired straight across. CLOCK, PRESET and CLEAR come from the push button and the two switches; each \(Q\) drives one of the three LEDs.

Figure 52 is a logic diagram. Figure 53 is the same counter drawn as a circuit schematic (see circuit-schematics), with device IDs, chip types and pin numbers from device-pinouts.

It takes five chips: U1 and U2 are 74HCT74 dual flip-flops, U3 a 74HCT08 (the 3-input product is U3:B and U3:C cascaded, since the kit has no 3-input gate), U4:A a 74HCT32 and U5:A a 74HCT86. On the IO board, CLOCK is button B0, PRESET and CLEAR are switches S0 and S1, and \(Q_2 Q_1 Q_0\) drive LEDs L2, L1 and L0.

Figure 53: The counter as a circuit schematic, ready to build: device IDs and chip types on every gate, pin numbers on every connection, IO board symbols for the inputs and outputs, and the power connections given once for all four chip types. Inputs and outputs are the same right-pointing pentagon, the input’s wire leaving the point and the output’s arriving at the flat back edge, per circuit-schematics. A dot marks a joined connection; crossing wires are not connected.

Peer review of the schematic

Before building, everyone checks a neighbour’s schematic against a fixed list. It is worth running over Figure 53 as a self-check, because it is also the marking list:

  • naming of inputs and outputs;
  • identification of chips (U1, U2, …) and of the gate within a chip where it matters (:A, :B, …);
  • identification of chip types (74HCT00 etc.);
  • numbering of pins, including the IO board pins;
  • power supply connections;
  • circuit functionality — will it do what was asked?

The schematic guide and device pinouts on Blackboard have the detail (circuit-schematics and device-pinouts here). Ask a tutor if that is not enough. My schematic uses five 74-series chips.

Task 2 — a 4-bit up/down counter built from an adder

The second task drops the derive-the-equations method entirely. Instead of working out \(D_3 \ldots D_0\) by hand, put a 4-bit adder (74HCT283) in front of a 4-bit register (74HCT175) and let the adder compute the next count:

  • the current count — the flip-flop outputs \(Q_3 Q_2 Q_1 Q_0\) — goes back to one adder input, \(A\);
  • the adder’s sum outputs \(S_3 \ldots S_0\) drive the flip-flop inputs \(D_3 \ldots D_0\);
  • an external input \(U\) picks the direction:
    • \(U = 0\): \(0000 \to 0001 \to \ldots \to 1111 \to 0000\) (up);
    • \(U = 1\): \(1111 \to 1110 \to \ldots \to 0000 \to 1111\) (down).

That leaves the other adder input \(B\) and the carry-in \(C_{in}\) to work out for each mode:

Table 3: The table to fill in
Mode Adder B input \(C_{in}\)
Up-count (\(U=0\))
Down-count (\(U=1\))

Working out B and Cin

Note

Hint: \(-1\) in four-bit two’s complement is 1111, and that is exactly the thing task 2 needs.

The adder computes \(A + B + C_{in}\), and \(A\) is already the current count. So the question is only what to add.

Counting up means the next count is one more than this one, so \(B + C_{in}\) has to come to 1. The cheapest way is \(B = 0000\) with \(C_{in} = 1\) — the carry-in is a free +1, which is why it is the input being asked about at all.

Counting down means the next count is one less, i.e. \(Q + (-1)\). In four-bit two’s complement \(-1\) is 1111 (see binary-number-representations), so \(B = 1111\) with \(C_{in} = 0\).

Table 4: The completed table
Mode Adder B input \(C_{in}\)
Up-count (\(U=0\)) 0000 1
Down-count (\(U=1\)) 1111 0

Read Table 4 down the columns and the combinational logic falls out with no algebra at all:

\[B_3 = B_2 = B_1 = B_0 = U \qquad\qquad C_{in} = \overline{U}\]

Every bit of \(B\) is just \(U\) wired straight to it, and \(C_{in}\) is \(U\) through a single inverter. One gate for the whole direction control.

The wrap-around is free, and worth seeing why: the adder’s carry-out \(C_4\) goes nowhere, so the arithmetic is mod 16. Counting up from 1111 gives \(1111 + 0000 + 1 = 1\,0000\), and the discarded carry leaves 0000. Counting down from 0000 gives \(0000 + 1111 + 0 = 1111\) with no carry generated at all.

Figure 54: Task 2’s logic diagram with the two unknowns filled in. \(Q_3 \ldots Q_0\) feed back to the adder’s \(A\) input, the sum drives the register’s \(D\) inputs, and the direction input \(U\) does two jobs: tied to all four bits of \(B\) it supplies 0000 or 1111, and inverted into \(C_{in}\) it supplies the +1 that up-counting needs. The four nested feedback loops are drawn so no two cross. The task gives the two chips, the clock, the \(A\) feedback and the \(S\)-to-\(D\) connections; the \(B\) rail, the inverter and the \(C_{in}\) connection complete it, per the derivation above. The chips are plain rectangles rather than the notched arithmetic-block outline device-pinouts gives the 74HCT283, and the 74HCT175’s clock wedge sits on the bottom edge here rather than on the left edge as in the pinout sheet’s symbol. Either way it is one clock serving all four flip-flops.

Building it

The steps for task 2:

  1. Complete the given logic diagram, connecting \(U\) to the adder’s \(B\) input and \(C_{in}\) with appropriate combinational logic — that is Figure 54.
  2. Simulate the logic diagram in Logisim to check it behaves.
  3. Convert the logic diagram to a schematic diagram (the same treatment Figure 52 got in Figure 53).
  4. Build and test it: clock on a push button, \(U\) on a slide switch, the four counter outputs on four LEDs — see io-board for which pins those are.

Two things to watch on the hardware. The 74HCT175 shares one clock (pin 9) and one clear (pin 1) across all four flip-flops, so unlike the 74HCT74 pairs in Figure 53 there is nothing to fan out — but there is also no preset, so this counter can only be cleared, not loaded. And the register has no clock-enable: every push of the button counts, in whichever direction \(U\) happens to be selecting at that instant.

Sequential Circuits 1 — Shift Registers

Learning Lab 6 — the four-mode shift-register design exercise, then the combination lock from the preparation task. Pairs with 2026-08-13-shift-registers, which carries the full preparation-task spec, and with shift-registers for the mux-per-flip-flop construction the exercise turns on.

Lab plan

  • Sequential circuits — the shift register exercise
  • The combination lock preparation task — discuss with staff and others at your table
  • The combination-lock example is set up at the end of Week 3, Lecture 6 (see the lecture note); read it first
  • Modifying the combination lock
  • Make sure you can draw a circuit schematic and simulate in Logisim. If in doubt, ask.

Ed Lessons — C is starting

The Ed discussion board also hosts Ed Lessons, teaching the basics of C. The content is no more complex than CSSE1001, and C programming for the AVR starts in week eight. Staggered release:

Date Release
14 Aug Basics (out now)
28 Aug Next Steps #1
11 Sep Next Steps #2
25 Sep Extension Tasks
16 Oct Floating Point Workshop

Exercise — the four-mode shift register

The exercise is a half-drawn circuit to finish. What is already wired matters as much as what is missing.

Figure 55: The half-drawn circuit to complete. Three stages, not four: each is a 4-to-1 multiplexer (trapezoid, wide edge left, data inputs numbered 0-3 top to bottom, select inputs entering the bottom sloping edge) feeding one edge-triggered D flip-flop. Already wired for you are the mux outputs into the D inputs and the three shared rails - S1 and S0 into every mux’s select, CLK into every flip-flop. Left bare are the twelve mux data inputs and the A and B stubs at the top left: filling those in is the whole exercise. Junction dots mark connections; lines that cross without a dot are not connected.

Complete the design so that it implements this behaviour:

\(S_1 S_0\) Action when the circuit is clocked
00 Bits shifted to the right; the value on \(A\) is stored in the leftmost flip-flop
01 All bit values are toggled
10 If \(B\) is 1, the value from \(A\) is stored in all flip-flops; if \(B\) is 0, all flip-flops reset (i.e. 0 is stored in all flip-flops)
11 All bits are rotated to the left. (Bit in leftmost flip-flop is moved to rightmost flip-flop)

Hint: construct the truth table for \(f(A,B)\).

What the hint is for

Three of the four modes pick a source for each \(D\) input — some other flip-flop’s output, or that flip-flop’s own complement. Mode 10 is the only one that has to compute something from the primary inputs, and the hint says to nail it down as a truth table before wiring anything:

\(A\) \(B\) What the row asks for \(f\)
0 0 \(B=0\), so reset — store 0 0
0 1 \(B=1\), so store \(A\) — store 0 0
1 0 \(B=0\), so reset — store 0 0
1 1 \(B=1\), so store \(A\) — store 1 1

\[\boxed{f(A,B) = A \cdot B}\]

One AND gate, its output fanned out to input 2 of all three multiplexers. “Load \(A\)” and “reset” are not two behaviours needing two circuits — they are the same wire, because \(B\) gates \(A\) to zero.

Where each mux input comes from

Name the flip-flops \(Q_2 Q_1 Q_0\), leftmost first, matching the bit ordering used in shift-registers. Input \(n\) of every mux is the one selected by \(S_1S_0 = n\), so the mode table becomes a wiring table:

Mux input Mode Leftmost (\(D_2\)) Middle (\(D_1\)) Rightmost (\(D_0\))
0 00 shift right \(A\) \(Q_2\) \(Q_1\)
1 01 toggle \(\overline{Q_2}\) \(\overline{Q_1}\) \(\overline{Q_0}\)
2 10 load / reset \(f = A\cdot B\) \(f\) \(f\)
3 11 rotate left \(Q_1\) \(Q_0\) \(Q_2\)

Three things fall out of that table, and they are what the exercise is really testing:

  • The toggle mode needs no gates at all. Every D flip-flop already publishes \(\overline{Q}\), so input 1 of each mux is a wire back from the stage’s own complementary output. Feeding \(\overline{Q}\) into \(D\) is the standard way to make a flip-flop toggle — it is the same \(D = \overline{Q}\) wiring [counters] gives for a 1-bit counter.
  • The load/reset mode needs exactly one gate, shared, because \(f\) does not depend on the stage.
  • Rotate left is shift right’s column read backwards, plus a wrap. Input 0 always comes from the neighbour on the left, input 3 always from the neighbour on the right; the only asymmetry is at the ends — the leftmost stage takes \(A\) for input 0 (there is no neighbour, and the bit shifted out of \(Q_0\) is simply lost), and the rightmost stage takes \(Q_2\) for input 3.

Figure 56: The completed design. Each mux input takes the source its select code names: 0 shifts right (from the left-hand neighbour’s Q, or from A at the left end), 1 toggles (the stage’s own Qbar, which the flip-flop already provides, so no inverter is needed anywhere), 2 loads f = A.B (one AND gate shared by all three stages), 3 rotates left (from the right-hand neighbour’s Q, with Q2 wrapping round to the rightmost stage). The flip-flops are named Q2 Q1 Q0 left to right, matching the bit ordering used in shift-registers. Lines crossing without a junction dot are not connected - that rule is doing a lot of work in the band of return wires below the row.

A trace

A check of the wiring above. Start at \(Q_2Q_1Q_0 = 101\) and hold \(A = 1\), \(B = 1\) except where noted:

\(S_1S_0\) Mode Before After
00 shift right, \(A=1\) in at the left 101 110
01 toggle 110 001
11 rotate left 001 010
10 \(B=1\): load \(A=1\) everywhere 010 111
10 \(B=0\): reset 111 000

The rotate row is the one worth checking twice: \(Q_2 \leftarrow Q_1 = 0\), \(Q_1 \leftarrow Q_0 = 1\), and the bit that was in the leftmost flip-flop, \(Q_2 = 0\), wraps into the rightmost.

Discussing your diagrams

The lab runs a schematic review. The checklist:

Logic diagram — circuit functionality: will it do what was asked?

Circuit schematic —

  • naming of inputs and outputs
  • identification of chips (U1, U2, …) and gates within chips where applicable (:A, :B, …)
  • identification of types of chips (74HCT00 etc.)
  • numbering of pins
  • power supply connections

Check the schematic guide and device pinouts on Blackboard for more detail, and ask a staff member if necessary. Full rules in circuit-schematics; pinouts in device-pinouts.

Combination lock tasks

The preparation task itself — a two-stage 4-bit shift register, four switches, clock and reset buttons, locked/unlocked LEDs, and a code derived from your student number — is spelled out in 2026-08-13-shift-registers, which also carries the block diagram and the ordering trap (you enter the left code digit first, so it is the older one and ends up in the second stage).

Task 1 — test your combination lock design.

Task 2 — use fewer flip-flops. On paper, design something that detects the sequence AC in hex: switches set to A (1010), clock push-button pressed; switches set to C (1100), clock push-button pressed.

Can you do it with 3 flip-flops? Can you do it with 2? (Hint: can you move the registers towards the output side?)

Working — Task 2

The basic lock stores both digits and compares afterwards: two 4-bit stages, eight flip-flops, feeding a combinational code check. But the digits themselves are never needed downstream — only whether each was the expected one. So compare first, and register the verdict:

\[P = W_3\overline{W_2}W_1\overline{W_0} \quad (\text{switches show A} = 1010_2) \qquad C = W_3W_2\overline{W_1}\,\overline{W_0} \quad (\text{switches show C} = 1100_2)\]

  • Flip-flop 1: \(D_1 = P\). After a clock, \(Q_1 = 1\) means the digit just entered was A.
  • Flip-flop 0: \(D_0 = Q_1 \cdot C\). After the next clock, \(Q_0 = 1\) means the last two digits entered were A then C.
  • unlocked LED \(= Q_0\); locked LED \(= \overline{Q_0}\), taken straight off the flip-flop.

Two flip-flops, down from eight. The combinational cost barely moves — the original design also has to compare two 4-bit values against the code, so \(P\) and \(C\) are the same two equality checks moved to the other side of the flip-flops, plus one AND. The whole saving is in storage.

Figure 57: Task 2’s two-flip-flop AC detector. This is the hint ‘move the registers towards the output side’ drawn out: the four switches are compared against the two expected digits combinationally, and only the one-bit verdicts are clocked, so the eight flip-flops of the basic lock (compare after storing, see the block diagram in 2026-08-13-shift-registers) collapse to two. Q1 remembers ‘the digit just entered was A’; Q0 is the unlock verdict, and it is a registered output, so the LEDs change only when the enter button is pressed. The locked LED needs no inverter - the flip-flop’s Qbar is already the complement. Lines crossing without a junction dot are not connected. The comparators are drawn as plain blocks, and the four-switch bus is drawn heavy with its width lettered beside it, which is neither of the two ways the course marks bus width (a slash across the line with the width beside it, or the width lettered next to a plain line).

Why not one? With a single flip-flop holding “the last digit was A” and the LED driven combinationally by \(Q_1 \cdot C\), the lock would open the instant the switches were set to C — before the enter button was pressed. That is a Mealy output, and it is not what the original lock does. Registering the verdict is what keeps the LEDs changing only on a clock edge. Two is also the floor for a Moore machine here: the circuit must distinguish three situations — nothing useful yet, A just entered, AC just entered — and three states need two flip-flops. See state-machines.

Three flip-flops. Reading the question as a ladder, three flip-flops is what a one-hot encoding of those same three states costs — one flip-flop per state — and going to a binary encoding is what buys the drop to two. The compare-then-register construction lands on two directly, so three is a waypoint rather than a separate design.

Simulate and test.

Task 3 — challenge. Allow the unlock combination itself to be set and stored in flip-flops using switches and buttons, rather than hard-wired. Simulate and test.

The expected trajectory: for each of tasks 1 and 2, logic/schematic diagrams completed → partially working circuit → fully working circuit, with task 3 only at the diagram stage.

Next

Lab 7 has a preparation task, and it is to be done before you arrive for the practical session — see week4-lab-lab-7-exercises.

See also

Week 5

Lecture 9 — From Digital Logic to Processors: ALU and Control Unit

The first half of the course, assembled into a processor. See cpu-organisation for the blocks, arithmetic-logic-unit for the ALU and its control table, and fetch-decode-execute-cycle for the control unit’s job. The worked examples, and the thread joining them, are below.

Where this sits

Everything so far has been gates, flip-flops and state machines. They assemble into the three blocks of a CPU: a control unit, an ALU, and registers, joined by internal buses and connected to memory and IO over external buses. Full picture in cpu-organisation.

The control unit fetches instructions from memory and makes the ALU and registers carry them out. There is enough of it below to see why the ALU needs the control inputs it has. The AVR used later in the course is an 8-bit machine with 32 general purpose registers, R0–R31, and therefore an 8-bit ALU.

Registers

Registers are temporary storage inside the CPU, in two kinds:

  • General purpose registers — the data being operated on and the results. Collectively the register file; their width is the CPU word size.
  • Special purpose registers — used by the system. Two of them: the Program Counter (PC), holding the address of the next instruction to be fetched, and the Instruction Register (IR), holding the current instruction.

Scale varies: a small CPU might have 8 × 8-bit registers, a large one 64 × 32-bit. Drawn out in cpu-organisation.

The ALU

The ALU is versatile hardware which can perform various operations based on some control inputs. A function/control input selects between addition, increment, subtraction, bitwise AND, bitwise OR and so on, so the ALU does considerably more than adding.

Its connections are of two kinds. A, B and Output are data (each an \(n\)-bit bus), while Function/Control is control (\(m\) bits). The ALU is one piece of hardware whose behaviour is chosen by wires coming from somewhere else.

Like adders, ALUs can be made up from 1-bit slices, and an \(n\)-bit ALU is \(n\) identical slices with the carry rippling through. The bit-slice circuit, the cascade and the full table of control combinations are all in arithmetic-logic-unit.

Two levels of control

The slice’s control inputs work at two different levels, and separating them is what makes the whole combinations table make sense:

  1. Permutations of the data inputs — ENA, ENB, INVA condition A and B before any function sees them.
  2. Function select — \(F_1 F_0\) picks which operation’s result reaches the output:
\(F_1 F_0\) Function
00 A and B
01 invert B
10 A or B
11 A plus B

The first three are logical, the last arithmetic.

What the conditioning gates do

Call the two conditioned lines \(X\) (on the A path) and \(Y\) (on the B path). Three gates produce them, and those three gates are the entire front end of the ALU:

Figure 58: The input-conditioning gates of the bit slice. The two conditioned lines are X on the A path and Y on the B path. Nothing here selects an operation — these gates only decide what the four function blocks downstream get to see, which is why this is a separate level of control.

ENA INVA \(X\)
0 0 \(0\)
0 1 \(1\)
1 0 \(A\)
1 1 \(\overline{A}\)
ENB \(Y\)
0 \(0\)
1 \(B\)

Being able to force an operand to a constant 0 or a constant 1 (all ones across the word, which is \(-1\) in two’s complement) is what lets a single ALU produce \(0\), \(1\), \(-1\), \(A+1\), \(B-1\) and \(-A\) with no dedicated hardware for any of them.

The same ALU without a multiplexer

The four-function ALU can be drawn in two forms. The simplified form routes the four results (\(A\) and \(B\), \(\overline{B}\), \(A\) or \(B\), and the adder’s sum) into a multiplexer whose select is \(F_1F_0\) (arithmetic-logic-unit). The full internal diagram, from Tanenbaum’s Structured Computer Organization, has no multiplexer at all: it feeds \(F_1F_0\) into a decoder, and the decoder’s four outputs are enable lines, one per function.

Figure 59: Selecting a function with enable lines instead of a multiplexer: a decoder turns F1 F0 into four enable lines, each function’s result is ANDed with its own enable line, and the four gated results are OR’d together. Because a decoder raises exactly one output, three of the AND gates emit 0 and the OR simply passes the fourth through. The decoder block stands for inverters plus four AND gates. The logical results are labelled AB, B-bar and A+B, but the gates actually see the conditioned X and Y of the previous figure. The enable-to-function mapping is the F1 F0 table above.

Only one of the enable lines is 1 at a time. That is the defining property of a decoder (combinational-logic-blocks), and it is what makes the final OR gate safe: three of its four inputs are guaranteed to be 0, so the OR is not combining anything, just passing the selected result through. The two drawings are therefore the same machine. A multiplexer is a decoder driving enable gates into an OR, which is exactly how the mux of combinational-logic-blocks is built inside.

Two other things the full diagram makes visible that the simplified one hides:

  • the three logical functions form a logical unit and the adder is a separate full adder, so the slice is some logic, one adder, and a chooser;
  • the carry-in to the adder is Carryin (INC), which is where the INC control input of the combinations table physically enters.

Example — calculating \(B - A\) using this ALU

The question is which values of \(F_1\), \(F_0\), ENA, ENB, INVA and INC make the ALU output \(B - A\).

Via two’s complement negation:

\[B - A = B + (-A) = B + (\overline{A} + 1) = B + \overline{A} + 1\]

\[\boxed{F_1 = 1 \quad F_0 = 1 \quad \text{ENA} = 1 \quad \text{INVA} = 1 \quad \text{ENB} = 1 \quad \text{INC} = 1}\]

Select the adder (\(F_1F_0 = 11\)), let \(A\) through and invert it (\(\text{ENA} = \text{INVA} = 1\), giving \(X = \overline{A}\)), let \(B\) through (\(\text{ENB} = 1\)), and set the carry into the bottom slice (\(\text{INC} = 1\)). Written as a column addition across the word for \(n = 8\):

\[\begin{array}{cccccc} & B_7 & B_6 & \cdots & B_1 & B_0 \\ + & \overline{A_7} & \overline{A_6} & \cdots & \overline{A_1} & \overline{A_0} \\ + & 0 & 0 & \cdots & 0 & 1 \end{array}\]

The bottom row is INC entering the least significant slice — so the \(+1\) of the negation costs no extra hardware at all.

Useful combinations

The full table of useful combinations of ALU inputs is in arithmetic-logic-unit. Three of its rows, worked through:

  • \(B - 1\) — control input by control input: \(F_1F_0 = 11\) (adder), \(\text{ENA} = 0\) with \(\text{INVA} = 1\) so \(X\) is all ones, \(\text{ENB} = 1\) so \(Y = B\), \(\text{INC} = 0\). Across the word that is \(B_7 B_6 \dots B_0\) plus \(1\,1\,\dots\,1\), i.e. \(B + (-1)\).
  • \(-1\) — the pattern \(11\dots1\). Here the same all-ones \(X\) is combined by OR with \(Y\) forced to zero, so the all-ones pattern passes straight through to the output.
  • \(B + 1\) — by the same reasoning it is \(F_1F_0 = 11\), \(\text{ENA} = 0\), \(\text{ENB} = 1\), \(\text{INVA} = 0\), \(\text{INC} = 1\): force \(X\) to zero, pass \(B\), and add the carry.

The control unit

Fetch-decode-execute

The control unit operates in a continuous cycle on the datapath — fetch an instruction from memory into the CPU (PC and IR are the registers involved), decode it to resolve the opcode and operands, then execute, issuing control signals so the operation happens in the datapath. Written out as five steps, with the PC advancing before execution, and drawn as a loop, in fetch-decode-execute-cycle. The cycle is a three-stage pipeline.

Control signals

The datapath is a register file feeding two buses into the ALU, with the result returning on a destination bus. Controlling it means deciding four things:

  • what the ALU does;
  • which register values are placed on the A and B buses;
  • which register receives the result from the destination bus;
  • when to read or write memory.

Each is decided by a bundle of wires leaving the control unit, and their widths follow from the hardware they drive:

Signal Width Why that width
A register select 3 \(2^3 = 8\) registers in the file (r0–r7)
B register select 3 same
Destination select 3 same
ALU control 6 the six ALU control inputs — \(F_1\), \(F_0\), ENA, INVA, ENB, INC
Memory read/write 1 one bit chooses the direction

plus address and data lines to memory, and — coming back the other way — the ALU status lines feeding into the control unit. The whole figure is in fetch-decode-execute-cycle.

So r5 = r0 + r2 becomes: A select 0, B select 2, destination select 5, ALU control set to the \(A+B\) row of the combinations table.

Control signals come from the control unit, which must generate them in the right order for a given instruction — and the instruction is determined by the contents of the Instruction Register.

Data influencing control

The IR alone is not enough: the control unit can’t operate without knowing something about the data. If a for-loop variable is meant to run from 10 down to 0, the control unit has to know when it gets there.

That is what the status register is for. It is determined by ALU operations, stores the status of the last ALU operation, and is available to the control unit. if (x < 0) becomes, at this level, an ALU operation followed by the control unit reading a status bit.

ALU status flags

Flag Question
Z zero bit — was the last result 0?
V overflow bit — did the last addition/subtraction overflow, assuming a two’s complement operation?
C carry bit — was a carry out generated?
N negative bit — was the result negative as two’s complement, i.e. what is the sign bit?

Typically held in a special purpose STATUS register (SREG) available to the control unit. The register is wider than four bits, and these four flags occupy its right-hand end.

Example — the flags after \(8_{10} - 9_{10}\) on a 5-bit ALU

First negate 9 in 5 bits: \(9 = 01001\), invert to \(10110\), add one to get \(10111\). Then add, keeping the carries into and out of the sign column:

\[\begin{array}{crl} \text{carry into MSB} \rightarrow & 0\phantom{0000} & \\ & 01000 & \\ + & 10111 & \\ \hline \text{carry out} = 0 \rightarrow & 11111 & \end{array}\]

\[Z = 0 \qquad C = 0 \qquad V = 0 \qquad N = 1\]

  • \(Z = 0\) — the result is not zero.
  • \(C = 0\) — nothing carried out of the top bit.
  • \(V = 0\) — the carry into the sign column and the carry out of it are both 0, so they agree; equivalently, \(8 + (-9) = -1\) is well within 5-bit two’s complement range. See 2026-08-04-binary-arithmetic for the \(C_{in} \oplus C_{out}\) rule.
  • \(N = 1\) — the sign bit is set.

And \(11111\) read as two’s complement is \(-1\), which is indeed \(8 - 9\).

See also

Lecture 10 — AVR Introduction

See instruction-set-architecture for machine instructions, the ISA and assembly language, avr-architecture for the chip, and avr-instructions for the instruction set and its encodings.

Outline

  • Machine code
  • Introduction to AVR — hardware, then assembly language

Recap

Basic computer organisation — ALU, control unit, registers, primary memory (cpu-organisation) — with the fetch-decode-execute cycle running over it: the instruction comes out of primary memory (F), is decoded (D), and is executed against the registers and ALU (E). Everything here is that picture made concrete on a real chip.

Machine code

Machine instructions

An example of Atmel AVR machine code: 0000 1101 0111 0111.

Instructions typically consist of:

  • Opcode (operation code) — defines the operation, e.g. addition.
  • Operands — what is being operated on, e.g. particular registers or a memory address.

So add rd, rr, meaning rd ← rd + rr, is an opcode (add) plus two register operands. (That example word decodes to a real instruction, worked out below.)

Instruction Set Architecture

An ISA is a specification — i.e. a document. It specifies the interface between hardware and software: software above the line is compiled without knowing how the chip works, hardware below it is built without knowing what will run. Drawn out in instruction-set-architecture.

Microarchitecture

Microarchitecture = the architecture of the control unit — i.e. the state machine (gates and flip-flops etc.) that implements the control unit.

Which is exactly the state-machines material from Lecture 8, now at processor scale.

An ISA can be implemented by many different microarchitectures. The 8086 ISA has been implemented by many processors in different ways; the Pentium ISA by Pentium, Pentium IV, Core2Duo and i7 (each differently), by various AMD devices, and by other manufacturers.

Assembly language

Machine code is too hard to program in, so we use assembly language: human readable (just!), and converted into machine code by software called an assembler.

add r3,r4 r3 ← r3 + r4
inc r22 r22 ← r22 + 1

The structural point: a high-level language compiles one-to-many, whereas assembly assembles 1:1 — one assembly instruction is exactly one machine instruction.

Introduction to Atmel AVR

Hardware

Atmel AVR devices are microcontrollers, which include lots of components on one chip: CPU, memory (RAM), program memory, input/output devices. A microprocessor is the CPU alone: an ATmega324A is not a CPU; it contains one, plus everything else needed to make a working system.

Figure 60: Microcontroller versus microprocessor. The four boxes are the four kinds of component, all in one package. The whole chip is the microcontroller, and only the CPU block is what would be sold on its own as a microprocessor. What a real ATmega324A actually contains is the chip diagram in the AVR architecture note.

On the AVR architecture diagram, the three regions of the cycle fall out of the block layout:

Blocks
F Program Counter → Flash Program Memory → Instruction Register
D Instruction Decoder → Control Lines
E 32 × 8 general purpose registers → ALU → Status and Control

Since those are separate hardware, they run concurrently on successive instructions — a three-stage pipeline. Drawn out, with the sizes and volatility of each memory, in avr-architecture.

Numbers worth having: program memory is 32 kB flash and non-volatile; the register file is 32 registers, R0–R31, each 8 bits wide and made of flip-flops; the ALU is 8-bit, which is what makes AVR an 8-bit machine; data SRAM is 2 kB and volatile; the data bus is 8 bits.

The peripherals on the ATmega324A datasheet block diagram fall into groups: the four 8-bit ports A–D are GPIO; USART 0, USART 1, SPI and TWI are communication; 8-bit T/C 0, 16-bit T/C 1 and 8-bit T/C 2 are the timers/counters; and the A/D converter and analog comparator go together as a fourth group. The 16-bit T/C 3 box is not in the timers/counters group: it belongs to the ATmega1284/1284P rather than the 324A. The three memories are FLASH for the program, SRAM for data, and EEPROM for non-volatile data. Those groupings are drawn out, with the package boundary and internal bus, in avr-architecture.

The AVR status register

8 bits, all R/W, all reset to 0:

Bit 7 6 5 4 3 2 1 0
I T H S V N Z C

The five to know are the bottom five — S, V, N, Z, C. Four of them are the flags from Lecture 9 (fetch-decode-execute-cycle); I at bit 7 is the global interrupt enable.

AVR instructions

rd is the destination, rr the source. AVR is a two-operand machine — the destination is also an operand, so add rd, rr computes rd ← rd + rr. A three-operand ISA like ARM writes add rd, r1, r2 instead and leaves both sources alone.

Instruction Meaning Example
MOV rd, rr “move”, but actually copy: rd ← rr mov r3, r14
ADD rd, rr add rr to rd add r5, r6 → r5 ← r5 + r6
AND rd, rr bitwise AND into rd
OR rd, rr bitwise OR into rd
EOR rd, rr bitwise exclusive-OR into rd
LDI rd, number load immediate — put the number into rd ldi r16, 73

LDI works for registers r16 to r31 only, with 8-bit numbers (00000000 to 11111111) — in decimal, the range \(-128\) to \(255\). ldi r0, 5 is not valid: r0 is below r16, so no such instruction exists. The reason is in the encoding, further down.

More instructions in coming weeks.

AVR machine code

Formats and bit-field diagrams in avr-instructions. Three encodings, each with a worked example:

ADD — 0000 11rd dddd rrrr

The 0000 11 is the opcode, bits 15–10; the remaining ten bits are the two five-bit register numbers, each torn into a single top bit and a low nibble. Watch the order in the middle: r (bit 9) comes before d (bit 8), the reverse of how the mnemonic writes them.

add r23, r7. The register numbers in binary, each split across its two fields:

  • r23 \(= 16 + 4 + 2 + 1 = \texttt{10111}\), so d = 1 and dddd = 0111
  • r7 \(= 4 + 2 + 1 = \texttt{00111}\), so r = 0 and rrrr = 0111

\[\texttt{0000 1101 0111 0111}\]

— which is the example word from the machine instructions section above. Drawn out field by field in avr-instructions.

COM — 1001 010d dddd 0000

Flip all bits (one’s complement). For com r19: r19 \(= 16 + 2 + 1 = \texttt{10011}\), so d = 1 and dddd = 0011:

\[\texttt{1001 0101 0011 0000}\]

LDI — 1110 KKKK dddd KKKK

K is the 8-bit constant, split into two nibbles either side of the register field, and d = register number − 16.

That subtraction is exactly why LDI is restricted to r16–r31: \(2^4 = 16\) — four bits of dddd can only name sixteen registers, and the ISA spends them on the upper half of the file.

Coming up

Instruction Set Architecture — more examples of AVR instructions.

See also

Lab 9 — Microchip Studio and AVR Assembly Introduction

Learning Lab 9, the first assembly lab. See avr-instructions for the instruction set, bit-masking for the masking technique the exercises turn on, and avr-architecture for the status register.

What the lab covers

  • AVR assembly language — instruction intro, documentation, machine code equivalent
  • Microchip Studio (previously Atmel Studio) — assembling and simulating code

Objectives: you should know how to create a project for the ATmega324A, enter assembly language instructions, build the project, simulate instructions and examine register values.

Documentation

  • ATmega324A datasheet — have it open from the start of every remaining lab this semester.
  • AVR Instruction Set Manual and AVR Instruction Set Reference
  • On Blackboard: Learning resources → Atmel AVR resources
  • Follow the Microchip Studio tutorial (Intro_to_Microchip_Studio.pdf) for the lab tasks — see instruction-set-architecture.

Admin: by the end of semester two USB-A cables are needed for data (one for programming, one for serial communication), one of them from about halfway through. On a personal laptop that may mean a dongle — there are workarounds but they all have downsides, so get one sooner rather than later.

Worked: what is the result of this program?

ldi r16, 0x56
ldi r17, 0x34
add r17, r16

r17 will contain 0x8A, r16 will contain 0x56.

\(\texttt{0x34} + \texttt{0x56} = \texttt{0x8A}\) (that is \(52 + 86 = 138\)), and add rd, rr writes to rd — so r17 takes the sum and r16 is left untouched. An answer that ends with r16 = 0x90 or 0x8A has the destination backwards.

Worked: the status register after a compare

ser r17
ldi r18, 0xF0
cp r17, r18

Z = 0, N = 0, V = 0.

ser r17 sets every bit, so r17 = 0xFF; r18 = 0xF0. Neither ser nor ldi touches a flag, so everything comes from the compare, which computes \(\texttt{0xFF} - \texttt{0xF0} = \texttt{0x0F}\) and throws the result away:

  • Z = 0 — the discarded result 0x0F is not zero.
  • N = 0 — its MSB is 0.
  • V = 0 — as signed values this is \((-1) - (-16) = 15\), comfortably in range.

(C is also 0: no borrow, since \(\texttt{0xFF} \geq \texttt{0xF0}\) unsigned.)

Boolean identities

These identities all hold, and together they are the toolkit the exercises need:

AND OR XOR
\(X \cdot 0 = 0\) \(X + 0 = X\) \(X \oplus 0 = X\)
\(X \cdot 1 = X\) \(X + 1 = 1\) \(X \oplus X = 0\)
\(X \cdot X = X\) \(X + X = X\)

Each operation has one value that passes a bit through and one that forces it — which is exactly what makes masking work. \(X \oplus 1 = \overline{X}\) is the identity that makes XOR the toggling operation. Full treatment in bit-masking.

Bit masking

Sometimes only a few bits of a register matter. A bitwise AND can mask out the bits that are not of interest; masking can also selectively set, clear, toggle or extract bits. Status register flags will be set also.

Worked: which r16 values make andi r16, 0x01 set Z?

The even numbers.

0x01 is 0000 0001, so the AND clears every bit except bit 0 and the result is bit 0 alone. Z is set exactly when that result is zero — i.e. when bit 0 of r16 was 0, which is precisely when r16 is even. So a single masked AND is an even/odd test, and more generally any single-bit mask turns Z into a test of that one bit.

NoteProvided task

Exercises

Write an AVR assembly language program which performs the following operations on values 0x55 and \(23_{10}\) and puts the result in the given register:

  • Bitwise AND → r16
  • Bitwise OR → r5
  • Bitwise EOR → r17
  • Addition → r6
  • Difference (subtraction) → r7
  • One’s complement (inversion) of 0x55 → r8
  • Two’s complement (negation) of 0x55 → r9

Predict the results and status register values (Z, C, N, V) after each operation. Simulate the code in Microchip Studio and check your predictions.

Write AVR assembly language code snippets to:

  • Copy the least significant three bits of register r7 to register r8. Other bits of r8 should be 0.
  • Toggle the most significant four bits of register r9. Other bits should be unchanged.
  • Clear the least significant four bits of register r10. Other bits should be unchanged.
  • Set the most significant four bits of register r11 to be 1. Other bits should be unchanged.

Test these code snippets.

Working — the arithmetic and logic program

The two operands:

\[\texttt{0x55} = \texttt{0101 0101} = 85 \qquad 23_{10} = \texttt{0001 0111} = \texttt{0x17}\]

The constraint that shapes the program: ldi only loads into r16–r31, but five of the seven destinations (r5–r9) are low registers. So the operands are loaded into a pair of high registers and copied down with mov before each operation. mov affects no flags, so each block’s flags come only from its own operation.

The first destination, r16, is also a natural place to hold 0x55 — which would destroy it before the later operations run. Holding the operands in r18/r19 instead avoids that.

    ldi  r18, 0x55       ; first operand
    ldi  r19, 23         ; second operand

    mov  r16, r18        ; --- bitwise AND -> r16
    and  r16, r19

    mov  r5, r18         ; --- bitwise OR -> r5
    or   r5, r19

    mov  r17, r18        ; --- bitwise EOR -> r17
    eor  r17, r19

    mov  r6, r18         ; --- addition -> r6
    add  r6, r19

    mov  r7, r18         ; --- difference -> r7
    sub  r7, r19

    mov  r8, r18         ; --- one's complement of 0x55 -> r8
    com  r8

    mov  r9, r18         ; --- two's complement of 0x55 -> r9
    neg  r9

Predicted results and flags

Operation Result Binary Z C N V
and r16, r19 0x15 (21) 0001 0101 0 unchanged 0 0
or r5, r19 0x57 (87) 0101 0111 0 unchanged 0 0
eor r17, r19 0x42 (66) 0100 0010 0 unchanged 0 0
add r6, r19 0x6C (108) 0110 1100 0 0 0 0
sub r7, r19 0x3E (62) 0011 1110 0 0 0 0
com r8 0xAA (170) 1010 1010 0 1 1 0
neg r9 0xAB (171) 1010 1011 0 1 1 0

Checking the interesting rows:

  • add — \(85 + 23 = 108\), no carry out of bit 7, and both operands positive giving a positive result, so V = 0.
  • sub — \(85 - 23 = 62\); \(23 < 85\) so there is no borrow and C = 0.
  • com — \(\overline{\texttt{0101 0101}} = \texttt{1010 1010}\). N = 1 because the MSB is now set, and C = 1 because com always sets the carry flag — not a carry out of anything, just a defined convention.
  • neg — \(\overline{\texttt{0x55}} + 1 = \texttt{0xAA} + 1 = \texttt{0xAB}\), which is \(-85\) read as two’s complement. C = 1 because neg sets carry unless the result is $00, and V = 0 because V is only set when the result is exactly $80.

The logical operations (and, or, eor) all clear V and leave C completely alone — see avr-instructions. That is why C reads unchanged rather than 0 for the first three rows: it holds whatever it held before the program ran.

Working — the bit manipulation snippets

All four are the same shape: build a mask, pick the instruction that does what you want to the masked bits. The choice follows straight from the identities above, and andi/ori cannot be used because every target here is a low register — so the mask goes into a high scratch register (r16) and the two-register form does the work.

Copy the least significant three bits of r7 to r8, other bits of r8 zero — extract, so AND with 1s on the bits to keep:

    mov  r8, r7
    ldi  r16, 0x07       ; 0000 0111
    and  r8, r16

Toggle the most significant four bits of r9 — toggle, so EOR with 1s on the bits to flip (\(X \oplus 1 = \overline{X}\), \(X \oplus 0 = X\)):

    ldi  r16, 0xF0       ; 1111 0000
    eor  r9, r16

Clear the least significant four bits of r10 — clear, so AND with 0s on the bits to clear (\(X \cdot 0 = 0\), \(X \cdot 1 = X\)):

    ldi  r16, 0xF0       ; 1s mark what to KEEP
    and  r10, r16

Set the most significant four bits of r11 — set, so OR with 1s on the bits to set (\(X + 1 = 1\), \(X + 0 = X\)):

    ldi  r16, 0xF0
    or   r11, r16

The thing worth noticing: 0xF0 is the mask in three of the four, meaning three different things. With and it names the bits that survive; with or and eor it names the bits that change. AND’s mask is written for what you keep, the other two for what you touch — mixing that up is the standard bug.

See also

Lab 8 — State Machines

Learning Lab 8: two FSM design exercises taken all the way from a state diagram to a Logisim circuit. See state-machines for the notation and the design procedure, and 2026-08-20-state-machines for the lecture.

Method: do the hand design first — state diagram → state table → next state logic and output logic — then implement and test in Logisim. (Also watch the LEC 08 — Example FSM Design 1 & 2 videos on Blackboard.)

Worked: the next Gray code value

0000, 0001, 0011, 0010, …

0110.

Gray code changes exactly one bit between consecutive values. From 0010, the values that differ in one bit are 0011 (already used), 0000 (used), 0110, and 1010. The standard reflected ordering takes 0110 next — after which come 0111, 0101, 0100, 1100, … 1010 is also one bit away, but flipping the most significant bit here breaks the reflection pattern. See binary-number-representations and the encoding table in state-machines.

NoteProvided task

Design Task 1 — Sequence Detector

Draw a state diagram for a system that detects the sequence 001 in a series of bits.

  • Input: S
  • Output: X

The output X is 1 whenever the sequence 001 is detected on the input S (i.e. 0 followed by 0 followed by 1).

Example input sequence   S = 00101010010001
Example output sequence  X = 00100000010001

Then:

  • Write down a 2-dimensional state table
  • Choose a state encoding — state encoding = number of flip-flops and their values in each state. Examine different options for state encoding!
  • Write down a 1-dimensional state table using your encoding
  • Determine Boolean expressions for the output (X) and the next state (flip-flop inputs, D’s) in terms of the current state (flip-flop outputs, Q’s) and input (S)
  • Enter the circuit into Logisim and simulate it

Working — Task 1

State diagram

The state has to remember how much of 001 has been matched so far. That gives four states — and the fourth exists only because this is a Moore machine, so “I have just detected it” must be a state of its own in order to have an output of its own.

State Means X
\(S_0\) no useful progress (last bit was a 1, or just started) 0
\(S_1\) seen 0 0
\(S_2\) seen 00 0
\(S_3\) just detected 001 1

Figure 61: The 001 detector. Every state has two arrows out, one per value of S, which is completeness for a one-input machine. The self-loop on S2 is the important one: a run of three or more zeros stays ready to detect, rather than falling back. From S3 the last bit consumed was a 1, so it behaves exactly like S0 — same transitions, different output.

NoteDiagram conventions

Each state is a circle divided by a chord, with the name above and the output below. A transition is a plain single-headed arrow, labelled with a bare 0 or 1 for a one-input machine. Two more conventions in the figure above:

  • The start state is marked by an incoming reset arrow from nowhere.
  • A self-loop is an arrow from a state back to itself. The completeness rule (transition arrows from each state must encompass all possibilities, exactly once) guarantees most machines need them.

See csse2010-diagram-notation for the full list of conventions.

Traced against the example sequence in the task, this machine reproduces the example output exactly; the trace is worked out edge by edge below.

2-dimensional state table

Current state Next state (\(\overline{S}\)) Next state (\(S\)) X
\(S_0\) \(S_1\) \(S_0\) 0
\(S_1\) \(S_2\) \(S_0\) 0
\(S_2\) \(S_2\) \(S_3\) 0
\(S_3\) \(S_1\) \(S_0\) 1

Choosing an encoding

Four states, so two flip-flops. The choice genuinely matters, which is what the instruction to examine different options is getting at.

The obvious assignment \(S_0 = 00\), \(S_1 = 01\), \(S_2 = 10\), \(S_3 = 11\) gives three product terms for \(D_1\) and three more for \(D_0\) — nothing collapses.

Now look at the 2-D table again: the \(\overline{S}\) column and the \(S\) column each contain only two distinct destinations, and on \(S = 1\) every state goes to either \(S_0\) or \(S_3\). If the encoding is arranged so that one flip-flop bit tracks the input directly, that bit’s logic disappears entirely. Assigning

\[S_0 = 01 \qquad S_1 = 00 \qquad S_2 = 10 \qquad S_3 = 11\]

does exactly that.

1-dimensional state table

State \(Q_1 Q_0\) \(S\) Next state \(D_1 D_0\) X
\(S_0\) 01 0 \(S_1\) = 00 0 0 0
\(S_0\) 01 1 \(S_0\) = 01 0 1 0
\(S_1\) 00 0 \(S_2\) = 10 1 0 0
\(S_1\) 00 1 \(S_0\) = 01 0 1 0
\(S_2\) 10 0 \(S_2\) = 10 1 0 0
\(S_2\) 10 1 \(S_3\) = 11 1 1 0
\(S_3\) 11 0 \(S_1\) = 00 0 0 1
\(S_3\) 11 1 \(S_0\) = 01 0 1 1

Boolean expressions

Reading the \(D_0\) column: it is 1 in exactly the four rows where \(S = 1\), and 0 in the four where \(S = 0\).

\[\boxed{D_0 = S}\]

A direct wire from the input to the flip-flop — no gate at all. Reading \(D_1\), which is 1 at \((Q_1Q_0, S) = (00,0), (10,0), (10,1)\):

\[D_1 = \overline{Q_1}\,\overline{Q_0}\,\overline{S} + Q_1\overline{Q_0}\,\overline{S} + Q_1\overline{Q_0}S = \overline{Q_0}\left[\overline{S}(\overline{Q_1} + Q_1) + Q_1 S\right] = \overline{Q_0}\left[\overline{S} + Q_1 S\right]\]

and by the redundancy (simplification) theorem, \(\overline{S} + Q_1 S = \overline{S} + Q_1\):

\[\boxed{D_1 = \overline{Q_0}\,(Q_1 + \overline{S})}\]

\(X\) is 1 only in \(S_3 = 11\):

\[\boxed{X = Q_1 \cdot Q_0}\]

Checking it, edge by edge

Running the expressions against the sequence the task supplies, one column per clock edge — the state shown is the one the machine is in after that edge, and X is that state’s output:

S       =    0  0  1  0  1  0  1  0  0  1  0  0  0  1
state       S1 S2 S3 S1 S0 S1 S0 S1 S2 S3 S1 S2 S2 S3
Q1 Q0       00 10 11 00 01 00 01 00 10 11 00 10 10 11
X       =    0  0  1  0  0  0  0  0  0  1  0  0  0  1

which is X = 00100000010001, the example output sequence in the task, exactly. The three detections land on the final 1 of each 001, including the one at the very end, and the 000 at positions 11–13 shows the self-loop on \(S_2\) doing its job: a third zero keeps the machine ready instead of dropping it back to the start.

The circuit

Figure 62: The 001 detector as a logic diagram, the circuit the task’s last bullet asks for (enter the circuit into Logisim and simulate it). Three things the algebra hides are visible here. D0 is a bare wire from the input S to a flip-flop, with no gate anywhere in the path. Both complements the next-state logic needs come off the flip-flops’ own Qbar pins, so the circuit contains no inverter. And the output AND sits to the right of the flip-flops, fed by Q1 and Q0 only - never by S - which is exactly what makes this a Moore machine. The two long return wires at the bottom carry Qbar1 and Qbar0 back to the gates; lines that cross without a junction dot are not connected.

Challenge — the detector in three chips

The challenge is to implement the sequence detector with just three chips: three 74-series packages, total, for Figure 62.

Two D flip-flops are one 74HCT74, leaving two chips for the logic. The trick is that \(\overline{Q_0}\) and \(\overline{Q_1}\) come free from the flip-flops’ complementary outputs, so no inverter package is needed — and De Morgan turns the OR into a NAND that can use \(\overline{Q_1}\) directly:

\[Q_1 + \overline{S} = \overline{\overline{Q_1} \cdot S} \quad\Longrightarrow\quad D_1 = \overline{Q_0} \cdot \operatorname{NAND}(\overline{Q_1},\, S)\]

Signal Built from
\(D_0 = S\) a wire
\(D_1\) one NAND + one AND, using \(\overline{Q_0}\) and \(\overline{Q_1}\) from the flip-flops
\(X = Q_1 Q_0\) one AND
Chip Used for
74HCT74 dual D flip-flop \(Q_1\), \(Q_0\)
74HCT00 quad NAND 1 gate
74HCT08 quad AND 2 gates

Three chips, with three of the four NAND gates and two of the four AND gates spare. See device-pinouts for the pinouts and circuit-schematics for the drawing rules.

NoteProvided task

Design Task 2 — Sequence Matching

Consider a sequence matching system with

  • 2 inputs A, B
  • 2 outputs X, Y
  • X is 1 if A and B have been the same value (i.e. both 0 or both 1) twice or more in a row, otherwise 0
  • Y is 1 if the A and B values are different, otherwise 0
  • Initially the A and B values are assumed to have been different and Y should be 1

Draw a state diagram and discuss with tutoring staff. Implement: write down a 2-D state table, choose a state encoding, write down a 1-D state table, determine Boolean expressions for the outputs and the next state (flip-flop inputs, D’s) in terms of the current state (flip-flop outputs, Q’s) and inputs, and enter the circuit into Logisim and simulate.

Working — Task 2

Reducing the inputs

A and B never matter individually — only whether they agree. Define

\[M = \overline{A \oplus B} \qquad (M = 1 \text{ when } A = B)\]

so the four input combinations collapse to two cases, and 00 behaves identically to 11.

State diagram

The machine must remember how long the current run of matches is, capped at two:

State Means X Y
\(D\) the last pair differed — the reset state 0 1
\(M_1\) matched once (the pair before differed) 0 0
\(M_2\) matched twice or more in a row 1 0

That the reset state is \(D\) with \(Y = 1\) is given by the specification: initially the A and B values are assumed to have been different and Y should be 1.

Figure 63: The sequence matcher, with M meaning A equals B. Any mismatch drops straight back to D from anywhere, so the run counter resets in one clock; a match walks D to M1 to M2, where it stays. The two outputs are each true in exactly one state, which is what makes the encoding below collapse the output logic to nothing.

2-dimensional state table

Current state \(AB = 00\) (\(M\)) \(01\) (\(\overline{M}\)) \(10\) (\(\overline{M}\)) \(11\) (\(M\)) X Y
\(D\) \(M_1\) \(D\) \(D\) \(M_1\) 0 1
\(M_1\) \(M_2\) \(D\) \(D\) \(M_2\) 0 0
\(M_2\) \(M_2\) \(D\) \(D\) \(M_2\) 1 0

Choosing an encoding

Three states, so two flip-flops, with one code left over. Each output is true in exactly one state, so if the two flip-flops are made to be the two outputs, the output logic vanishes entirely. Take \(Q_1 = X\) and \(Q_0 = Y\):

\[D = 01 \qquad M_1 = 00 \qquad M_2 = 10 \qquad (11 \text{ unused})\]

\[\boxed{X = Q_1} \qquad \boxed{Y = Q_0}\]

1-dimensional state table

State \(Q_1 Q_0\) \(M\) Next state \(D_1 D_0\) X Y
\(D\) 01 0 \(D\) = 01 0 1 0 1
\(D\) 01 1 \(M_1\) = 00 0 0 0 1
\(M_1\) 00 0 \(D\) = 01 0 1 0 0
\(M_1\) 00 1 \(M_2\) = 10 1 0 0 0
\(M_2\) 10 0 \(D\) = 01 0 1 1 0
\(M_2\) 10 1 \(M_2\) = 10 1 0 1 0

Boolean expressions

\(D_0\) is 1 in exactly the rows where \(M = 0\):

\[\boxed{D_0 = \overline{M} = A \oplus B}\]

\(D_1\) is 1 at \((Q_1Q_0, M) = (00, 1)\) and \((10, 1)\), so \(Q_1\) is a don’t-care:

\[D_1 = \overline{Q_1}\,\overline{Q_0}M + Q_1\overline{Q_0}M = \overline{Q_0}M(\overline{Q_1} + Q_1) \quad\Longrightarrow\quad \boxed{D_1 = \overline{Q_0} \cdot M}\]

Writing \(E = A \oplus B\) so that \(M = \overline{E}\), De Morgan folds \(D_1\) into a single gate:

\[D_1 = \overline{Q_0} \cdot \overline{E} = \overline{Q_0 + E} = \operatorname{NOR}(Q_0,\, A \oplus B)\]

So the whole circuit is one XOR feeding both a flip-flop input and a NOR, with the outputs taken straight off the flip-flops.

Figure 64: The sequence matcher as a logic diagram. One XOR does all of the input reduction: E = A xor B is simultaneously D0 and one input of the NOR that forms D1. Because the encoding was chosen so that the two flip-flops are the two outputs, X and Y are taken straight off Q1 and Q0 and there is no output logic at all - the entire machine is two gates and two flip-flops. The one feedback wire, Q0 back to the NOR, is the whole of the next-state logic that depends on the state. Lines crossing without a junction dot are not connected.

At chip level that NOR is the awkward part. The course’s parts list has quad NAND, AND, OR and XOR packages plus a hex inverter, but no NOR — see device-pinouts. Rewriting \(D_1 = \overline{Q_0}\cdot\overline{E}\) as an AND of two complements fixes it: \(\overline{Q_0}\) is free from the flip-flop and \(\overline{E}\) is one inverter on the XOR output, giving 74HCT86 + 74HCT04 + 74HCT08 + 74HCT74, four chips.

Checking the unused state

The encoding leaves \(Q_1Q_0 = 11\) unassigned, so it is worth confirming the machine cannot get stuck there (the same lock-up check as week4-lab-lab-7-exercises). Substituting \(Q_1Q_0 = 11\):

\[D_1 = \overline{Q_0}\cdot M = 0 \cdot M = 0 \qquad D_0 = \overline{M}\]

so from 11 the machine goes to 01 (\(D\)) when \(M = 0\), or 00 (\(M_1\)) when \(M = 1\). Both are legal states, so it self-corrects within one clock — no lock-up, and no extra logic needed to guarantee it.

See also

Week 6

Lecture 11 — Instruction Set Architecture Part 1

The ISA is a document, and this is what is in the document. See instruction-set-architecture for the four-part frame, memory-models for the first part in full, avr-architecture for the register file and avr-io-ports for the I/O registers.

The ISA as an interface

Machine code, the ISA as a specification, and a first look at the AVR are in 2026-08-27-avr-introduction. The split between specification and implementation, in the form the rest of the course leans on:

  • The ISA defines the interface between hardware and software. The ISA is a specification; the microarchitecture is how the control unit is built.
  • Hardware (microarchitecture) designers don’t need to know about the high level software. They just build a microarchitecture that implements the ISA.
  • Software writers (machine language programmers and compiler writers) don’t need to know (much) about microarchitecture. They just write or generate instructions that match the ISA.

Picture software (SW) above, hardware (HW) below, and on the line between them a row of bits — 1 0 1 0 1. The interface is not an API or a protocol; it is a bit pattern, and both sides are built from the same document that says what the pattern means.

What makes an ISA?

Four things:

  1. Memory models
  2. Registers
  3. Instructions
  4. Data types

Parts 1 and 2 and the start of part 3 are below. Instructions continue and data types arrive in 2026-09-03-instruction-set-architecture-part-2. The payoff: if you know all these details you can write machine code that runs on the CPU, and build the CPU.

1. Memory models

The memory model is how memory looks to the CPU. There are four issues, better read as decisions the specification has to make than as problems to be solved:

  • A. Addressable cell size
  • B. Alignment
  • C. Address spaces
  • D. Endianness

Full treatment in memory-models.

Memory organisation

Computer memory is conceptually a set of addressable cells. Cells are usually 8 bits wide (one byte), though various cell widths have been used in the past. Drawn as a grid, the address indexes down the left and the cell width runs across.

Take a 4 × 3 memory: 4 addresses, 3-bit cells. \(2^2 = 4\), so two address bits name four cells.

At gate level that memory is built like this:

  • One cell is a row of three D flip-flops.
  • The address decoder turns A1 A0 into one row-select line. A1 A0 = 0 1 selects row 1.
  • WRITE = 1 gates DATA IN (I2 I1 I0) into the selected row through the AND gates on the left. The selected row’s outputs reach DATA OUT (O2 O1 O0) through the AND-OR tree on the right.

Nothing new appears here: it is flip-flops-and-latches for the storage and combinational-logic-blocks for the selection. Memory is a decoder, some flip-flops and some gates. The whole schematic is in memory-models.

A. Addressable cell size

The most common cell size is 8 bits (1 byte), but not always. The AVR is the counterexample:

AVR Cell width
data 8 bits
program 16 bits

The bus is used to transport the content of a cell. Sometimes the data bus is wider than a cell, i.e. it retrieves several cells (addresses) at once, and then the address bus does not need to be as wide.

Bus sizes

For every doubling of data bus width, remove the least significant bit of the address bus.

For \(2^n\) cells of 8 bits, the address size is \(n\) bits, and the configurations are:

Data bus Address bus Transferred
8 bits \(n\) one cell at a time
16 bits \(n-1\) two cells at a time
32 bits \(n-2\) four cells at a time

A concrete case: a memory with addresses 000000, 000001, 000010, … up to 111111, each cell 8 bits wide.

\[64 \text{ cells} = 2^6 \implies 6 \text{ address bits}\]

Group the cells in pairs and then in fours, and the address bus A goes 6, 5, 4 bits as the data bus D goes 8, 16, 32.

Figure 65: The bus-width trade-off. (a) 64 cells of 8 bits, so a cell needs a 6-bit address. A 16-bit data bus can only ever hand over an aligned pair of cells, and there are 32 pairs — 5 bits; a 32-bit bus hands over a group of four, and there are 16 groups — 4 bits. (b) the same fact read off the two buses at once: every doubling of D removes one bit from A.

Widening the data bus by a factor of two narrows the address bus by exactly one bit, because the transfer now names a group of cells rather than a cell.

Worked: address bus width

If a CPU supports \(2^{35}\) bytes of memory and has a 64 bit data bus, how many bits wide is the address bus?

32.

Start from the cell size. Cell = 8 bits, so \(2^{35}\) bytes is \(2^{35}\) cells, and a byte-at-a-time machine would need a 35-bit address. Then walk the ladder, doubling the data bus and dropping one address bit each time:

Data bus 8 16 32 64
Address bus 35 34 33 32

Three doublings from 8 to 64, so three bits off 35.

B. Alignment

Many architectures require natural alignment, e.g. 4-byte words starting at addresses 0, 4, 8, … and 8-byte words starting at 0, 8, 16, …

An 8-byte example, counting the reads:

Reads
aligned — 8-byte word at address 8 occupies exactly the block 8–15 one
non-aligned — 8-byte word at address 12 half in block 8–15, half in block 16–23 two

Alignment is often required because it is more efficient. The counter-example is the Pentium IV, which fetches 8 bytes at a time from memory (64-bit wide data bus) and for which alignment is not required, so the processor stays backwards compatible with earlier processors:

  • a 4-byte word stored at address 4 takes 1 read (bytes 0 to 7);
  • a 4-byte word stored at address 6 must read bytes 0 to 7 (one read) and bytes 8 to 15 (second read), then extract the 4 required bytes from the 16 bytes read.

Worked: counting reads

How many memory reads are needed to read an 8-byte value on a machine with a 16-bit data bus that does not require natural alignment?

4 or 5.

There are two cases, an even start address and an odd one:

Figure 66: Reading an 8-byte value on a 16-bit data bus. Each row is one 2-byte block, i.e. one read; the numbers are the eight bytes of the value. Start the value at an even address and it fills four whole blocks — 4 reads. Start it at an odd address and one byte sits alone in the block at each end, so five blocks have to be read for eight bytes. Addresses increase upward and the higher-addressed byte of each block is drawn on the left. A × marks a byte in the fetched block that is not part of the value (csse2010-diagram-notation).

“Does not require” is the operative phrase — the machine permits both, so the answer has to cover both. That is why every question of this shape answers “\(k\) or \(k+1\)” rather than a single number.

C. Address spaces

Many microprocessors have a single linear memory address space — the von Neumann architecture — e.g. \(2^{32}\) bytes numbered from 0 to \(2^{32} - 1\) (which may not be bytes — it depends on the addressable cell size). Picture one strip with data at the low end and program at the high end: one space, shared.

The Harvard architecture has separate address spaces for instructions and data: two spaces, each starting at its own 0.

The AVR ATmega 324A is Harvard:

Size
Data address space \(2^{11}\) (2048) bytes 2 kB, 8-bit cells
Instruction address space \(2^{14}\) 16-bit words 16,384 instruction words = 32,768 bytes

The working:

\[2 \cdot 2^{10}\,\text{B} \to 2^{11} \text{ cells} \to 11 \text{ bits}\] \[2^{5} \cdot 2^{10}\,\text{B} = 2^{15}\,\text{B} \xrightarrow{\ \div 2\ } 2^{14} \text{ cells} \to 14 \text{ bits}\]

The \(\div 2\) is the step people drop. 32 kB of program memory is \(2^{15}\) bytes but only \(2^{14}\) addresses, because each address names a 16-bit cell. Convert to cells first, then take the logarithm.

The datasheet memory map fills that in — 32 registers, 64 I/O registers, 160 extended I/O registers and then 2 kB of SRAM up to 0x08FF on the data side; 0x0000 to 0x3FFF of Application and Boot flash on the program side. The map is in memory-models; the rest of the chip is in avr-architecture.

The \(2^{11}\) bytes is the size of the SRAM only. The data space itself runs to 0x08FF, which is that 2 kB plus the 256 locations (0x0000–0x00FF) the register file and the I/O registers occupy in front of it. The two I/O bands together hold 224 I/O registers, a number that comes back with the I/O registers below.

D. Endianness

Different machines may support different byte orderings.

Which end goes at the lowest address Who
Little endian the little end — least significant byte stored first Intel microprocessors (Pentium etc.), AVR
Big endian the big end stored first SPARC, Freescale (formerly Motorola) microprocessors

Most desktop/workstation/server CPUs produced since ~1992 are bi-endian (support both). Some are switchable at boot time, others at run time, i.e. can change dynamically.

Think of a read as SOURCE → TARGET: four memory cells at addresses \(m\), \(m+1\), \(m+2\), \(m+3\) are the source, a four-byte register is the target, and the bytes either cross over (little endian) or run straight across (big endian).

Figure 67: Assembling one 4-byte value out of four memory cells. The only difference between the two machines is which end of the value the lowest address holds. Big endian keeps the order (address \(m\) supplies the most significant byte); little endian reverses it. Nothing about the memory changes — the same four cells give two different values, and only the ISA says which.

Worked example

Given the memory:

Address Contents
0 00001111
1 00110011
2 11011101
3 00101100

The 1-byte word at address 1 is 00110011 — one cell, so endianness does not enter into it.

The 2-byte word at address 0 on a big endian system is 00001111 00110011. Big end first, so address 0 holds the most significant byte and address 1 the least — the arrows run straight across.

Worked: the little endian read

With the memory above, what is the value of the 2-byte word at address 2 if this is a little endian system?

00101100 11011101.

Little end first, so address 2 (11011101) is the least significant byte and address 3 (00101100) the most — and writing the value out most-significant-first therefore reverses them.

There are two mistakes to make here, and only one of them is about endianness. Crossing them gives four candidate answers:

Which word, read which way
A 00110011 11011101 the word at address 1, read big-endian
B 11011101 00110011 the word at address 1, read little-endian
C 11011101 00101100 the right word, read big-endian
D 00101100 11011101 ✓ the right word, read little-endian

So C is the endianness trap; A and B are the off-by-one trap, both dragging in 00110011 from address 1, which is not part of this word at all.

The reliable procedure: list the addresses the value occupies in increasing order, then assemble the answer most significant byte first. Big endian reads that list forwards, little endian backwards.

2. Registers

There are two types of register:

  • General purpose — used for temporary results etc. On the AVR these are r0 … r31.
  • Special purpose, e.g. Program Counter (PC), Stack pointer (SP), Input/Output Registers (224 on the AVR), Status Register (flags N Z C V; Tanenbaum calls this the Program Status Word).

Some other registers are part of the microarchitecture, not the ISA — e.g. the Instruction Register (IR). The programmer doesn’t need to know about these, and can’t directly change or use them.

That is the line the ISA draws. The IR exists, holds the instruction, and is in the CPU diagram of avr-architecture — but no instruction names it, so it is not in the specification and a chip designer may do as they like with it. The PC is in the specification because jmp writes it.

AVR registers

The general purpose registers (0–31) are quite regular and can be used interchangeably, with two exceptions:

  • A few instructions work on half the registers (registers 16–31). Only 4 bits are used to represent the operand in the instruction, and \(2^4 = 16\). This is the same fact that restricts LDI, seen from the encoding side (avr-instructions).
  • The X, Y, Z registers, below.

There are also many I/O registers (224). They are not to be confused with the general purpose registers: some instructions work with I/O registers, others with general purpose registers.

X, Y and Z

The top six registers of the register file pair off into three pointers, listed here with their register addresses:

Pointer Pair Register addresses
X R27 : R26 0x1B : 0x1A
Y R29 : R28 0x1D : 0x1C
Z R31 : R30 0x1F : 0x1E

So Z ≡ R31 : R30. Two 8-bit registers side by side make a 16-bit address, which is what a data space wider than 256 bytes needs and no single register can hold. See avr-architecture.

AVR I/O registers

The AVR ATmega324A has 224 I/O register addresses, used to control peripherals and get data to/from them:

  • Timers and counters
  • Analog to digital converters
  • Serial input/output
  • General purpose input/output ports
  • Each port (x = A, B, C or D) has three registers: DDRx (data direction register), PORTx (values to output), PINx (values on the pins). See learning lab 11.

Some addresses are reserved (not actually available on this device). Everything about these is in avr-io-ports — and the three port registers turn up a lab early, in week6-lab-avr-io-ports.

3. Instructions

Instructions are the main feature of an ISA. Instruction types include:

Input/Output communicate with I/O devices
Load/Store move data from/to memory
Move copy data between registers
Arithmetic addition, subtraction, …
Logical Boolean operations
Branching for deciding which instruction to perform next

The instructions met so far: MOV rd, rr (copy, not move), ADD rd, rr, AND/OR/EOR rd, rr, and LDI rd, K for r16–r31 (avr-instructions).

Input/output instructions

The 224 I/O registers split into two classes by how you are allowed to reach them:

Where Reached by
I/O registers 0 to 223 data memory addresses 32 to 255 ($20 to $FF) load and store instructions
First 64 (0 to 63) — special also in and out
Other 160 (64 to 223) — “extended” I/O registers load and store only

Data memory, lowest addresses first, is r0 … r31, then the 64 I/O registers, then the 160 extended I/O registers. That is where the $20 offset comes from: the register file is in the way.

IN and OUT

in rd, P Load I/O register value into general purpose register rd: r0 to r31; P = I/O register number (0 to 63, 0 to 0x3F)
out P, rr Store value from general purpose register into I/O register rr: r0 to r31; P = 0 to 63 (0 to 0x3F)

One example of each:

\[\texttt{IN r0, 0} \;\equiv\; \texttt{IN r0, PINA}\] \[\texttt{OUT 1, r0} \;\equiv\; \texttt{OUT DDRA, r0}\]

Picture the CPU holding r0 … r31 on one side and the 64 I/O registers on the other. IN is a read of an I/O register and OUT is a write to one. avr-io-ports draws the pair with one arrow each way.

Two things to take from those two lines. The number and the name are the same operand — I/O register 0 is PINA and I/O register 1 is DDRA, and the name only exists because m324Adef.inc was included. And the destination is written first in both, which is why the I/O register moves from second operand to first between them. Both instructions are one word and one clock cycle. Full detail in avr-io-ports.

Summary

The four parts of an ISA:

  1. Memory models ✓
  2. Registers ✓
  3. Instructions — more in Lecture 12
  4. Data types — Lecture 12

If you know all these details, you can write machine code that runs on the CPU and build the CPU.

See also

Lecture 12 — Instruction Set Architecture Part 2

The second half of “what makes an ISA”: the rest of the instructions, the addressing modes, and data types. See avr-instructions for the instruction set as a reference, addressing-modes for the four modes and instruction-set-architecture for the frame.

The four parts of an ISA

The four-part list from 2026-08-31-instruction-set-architecture-part-1, with the lecture each part belongs to:

1. Memory models — A. addressable cell size, B. alignment, C. address spaces, D. endianness Lecture 11
2. Registers Lecture 11
3. Instructions Lecture 12
4. Data types Lecture 12

3. Instructions

Instructions are the main feature of an ISA. There are five types. Unlike the list in Lecture 11, arithmetic and logical are one type, split instead by how many operands an instruction takes.

Type
Input/Output communicate with I/O devices/ports — in and out, met in Lecture 11
Load/Store move data from/to memory
Move copy data between registers
Arithmetic & Logical addition, subtraction, bitwise operations — dyadic (two operands, one result) or monadic (one operand, one result)
Branching for deciding which instruction to perform next

Instructions use various addressing modes, listed at the end of this section.

AVR instruction examples

The instructions from previous lectures. The destination comes first: rd is the destination, rr is the source.

Instruction Example or note
MOV rd, rr — copy rr into rd mov r0, r31 → r0 ← r31
ADD rd, rr add r5, r6 → r5 ← r5 + r6
AND rd, rr; OR rd, rr; EOR rd, rr and r5, r6 — r5 sits over r6, each column of two bits gives one result bit, and the result overwrites r5
COM rd — flip all bits (ones’ complement) NEG is the two’s complement counterpart
LDI rd, K (K is a constant, −128 to 255), r16 to r31 the I is for immediate, the first of the addressing modes below

A logical instruction is eight independent one-bit operations in parallel, which is the whole basis of bit-masking.

IN and OUT

Both are from Lecture 11.

in rd, P rd ← I/O register P in r5, 0x26 — I/O register 0x26 is TCNT0, i.e. timer/counter 0
out P, rr I/O register P ← rr out PORTD, r6

Each takes 1 cell, 1 cycle — one instruction word, one clock cycle. The data memory holds r0 … r31 from address 0, then 64 I/O registers, then 160 extended I/O registers, then SRAM. in reads (R) from the I/O block into the CPU and out writes (W) from the CPU to the I/O block. Details in avr-io-ports.

Load/store instructions

Load Load register from memory location AVR examples: ld, lds
Store Store register value in memory location AVR examples: st, sts

They split by addressing mode.

Indirect — the address is in a pointer register, X, Y or Z. X = r27:r26, Y = r29:r28 and Z = r31:r30. The X form:

    ld   r5, X           ; r5 <- Mem[X]
    st   X, r5           ; Mem[X] <- r5

1 cell, 2 cycles.

Direct — the address is in the instruction:

    lds  r5, 0x20        ; r5 <- Mem[0x20]
    sts  0x20, r5        ; Mem[0x20] <- r5

32 bits → 2 cells, 2 cycles. Spelling out a 16-bit address does not fit in one 16-bit instruction word, so these take two.

The SRAM is 2 kB, hence \(2^{11}\) cells, hence 11 bits of address (memory-models). Load (R) and store (W) reach all of the data space, register file and I/O registers included, as in Figure 68 below.

Data movement instructions

Data is usually copied, not moved. There are five types of movement, each with the instruction that does it:

Movement Called AVR
register → register move mov
memory → register load lds, ld
register → memory store sts, st
I/O register → register input in
register → I/O register output out

Five movements, three storage locations. Which instruction you need is decided entirely by where the two ends are. The mistake to avoid is confusing an I/O register with a memory address.

Figure 68: Where data can move. The CPU’s 32 registers are on the left; the data address space is the stack on the right, lowest address at the top. in and out reach only the first 64 I/O registers, one instruction word and one cycle each; ld, st, lds and sts reach any cell of the whole space, which is what the brace marks. The hex boundaries and the SRAM size are from the datasheet memory map in Lecture 11. The 2 kB / \(2^{11}\) cells / 11 bits label sizes the SRAM alone — the stack as a whole runs to 0x08FF.

Figure 68 puts in/out, load/store and data movement in one picture. The register file, the I/O registers and the SRAM are all cells of the same data address space, and the five instructions differ only in which part of it they can reach and how they name it. in/out are the cheap route but stop at I/O register 63. Everything past there has to be reached the long way, by data address, with lds/sts (avr-io-ports).

Dyadic instructions

A dyadic instruction combines 2 operands to produce a result. There are usually two types: arithmetic (ADD r5, r6) and logical, i.e. bitwise (AND r5, r6).

Monadic instructions

A monadic instruction takes one operand and gives one result:

Operation Example
Setting a register (all 1’s) SER r16 ≡ ldi r16, 0xFF
Clearing a register CLR r5
Negation (2’s complement) NEG r5
Inversion (1’s complement negation) COM r5
Shifting & rotation the shift and rotate instructions below

The register numbers differ for a reason: SER r16 but CLR r5. ser expands to ldi, so it inherits the r16–r31 restriction, while clr expands to eor rd, rd and reaches any register (avr-instructions).

Shift instructions

There are three:

  • LSL = Logical Shift Left
  • LSR = Logical Shift Right
  • ASR = Arithmetic Shift Right

They differ in what enters the vacated end and where the departing bit goes. LSL puts 0 into the bottom and sends bit 7 out to C. LSR puts 0 into the top and sends bit 0 out to C. ASR replicates the sign bit into itself and sends bit 0 out to C.

Worked in four bits, as in Figure 69:

Shift Worked Reading
LSL 0010 2 → 0100 4 → 1000 8, × 2 each step doubling, one place at a time
LSR 1000 (−8) → 0100 4; and 0110 6 ÷2 → 0011 3, unsigned halving, unsigned
ASR 1000 (−8) ÷2 → 1100 (−4), the sign bit replicates halving, signed

Figure 69: The three shifts worked in four bits for legibility. Left: lsl doubles, 2 → 4 → 8, and a 0 always enters at the bottom so the signed and unsigned readings agree. Right: the same four bits shifted right two ways. 1000 does not say whether it means 8 or \(-8\); the instruction is where that is declared, and each answer is right for one reading and wrong for the other.

The 1000 row is the one that matters. The same four bits are 8 to an unsigned reading and −8 to a signed one. Four bits are used here for legibility; in a real 8-bit register the equivalent pair is 10000000, 128 unsigned and −128 signed. The two shifts give different answers: LSR yields 0100 (4, right for the unsigned reading), ASR yields 1100 (−4, right for the signed one). The instruction is where you declare which interpretation you meant — see binary-number-representations and the reference treatment in avr-instructions.

Rotate instructions

There are two:

  • ROL = Rotate Left through Carry
  • ROR = Rotate Right through Carry

Each rotate has two halves: the carry goes into the register at the vacated end, and the bit falling out of the other end goes into the carry. A rotate is a shift whose vacated end is fed from C rather than a constant — so the register and the carry flag together behave as a nine-bit ring.

Worked: shifting a 16-bit value

What AVR instruction should follow lsl r14 to perform a multiplication by 2 of the 16-bit unsigned value stored in r13:r14?

A. asl r13, B. lsl r13, C. rol r13 or D. rol r14.

C. rol r13. Figure 70 shows why.

    lsl  r14             ; low byte x2; its bit 7 falls out into C
    rol  r13             ; high byte x2, pulling C into its bit 0

Figure 70: Doubling a 16-bit value in two steps. r13:r14 is one 16-bit value spread over two 8-bit registers, high byte named first. Step 1, lsl r14, shifts the low byte left, feeds a 0 in at bit 0 and pushes its bit 7 out into C. Step 2, rol r13, shifts the high byte left and pulls exactly that bit back in at its bit 0 — which is why rol r13 is the instruction that follows.

The others fail, each differently:

  • A. asl r13 and B. lsl r13 — the same operation under two names (shifting left, a 0 always enters), and both feed r13 a zero, throwing away the bit r14 just produced.
  • D. rol r14 — the right instruction on the wrong byte.

The general shape: a value wider than the machine is processed low end first, and the carry flag carries between the pieces.

Comparison instructions

A comparison is the same as subtraction, with the result not saved. It sets status register flags (Z, N, C, V …). Equality is what a compare is usually asked, and the flag for that is Z, which is 1 when the two are equal:

    cp   r5, r6          ; computes r5 - r6, keeps only the flags

The instruction reference specifies which status register bits are set by which instructions — per instruction, not by one general rule. The table for the instructions met so far is in avr-instructions.

Branch instructions

Branches are based on status register values:

breq label Branch if Z = 1
brne label Branch if Z = 0

Compare then branch is the entire conditional. Labels and the program skeleton the branches sit in are in avr-program-structure.

Addressing modes

Instruction operands can come from different places:

Mode AVR example
Immediate An operand value is in the instruction andi r17, 0xBA
Register Only register numbers in instruction and r18, r19
Direct Memory address is in the instruction lds r15, $1234
Indirect Memory address in register; the register number is in the instruction ld r5, X

The direct form occupies two instruction words (32 bits). That is the cost that distinguishes it from indirect, which stays one word.

These addressing mode names are as per Tanenbaum, Structured Computer Organization. The AVR instruction set manual uses different names, so match on the behaviour, not the word. Full treatment in addressing-modes.

4. Data types

Numeric

  • Integers of different lengths (8, 16, 32, 64 bits), possibly signed or unsigned
  • Floating point numbers, e.g. 32 bits (single precision) or 64 bits (double precision) — \(A = \pi r^2\) with \(3.14\) is the case that forces the type
  • Many others

Non-numeric

  • Boolean (0 means false, 1 means true) — stored in a whole byte or word
  • Bit-map (collection of Booleans, e.g. 8 in a byte)
  • Characters
  • Pointers (memory addresses)

A Boolean is a bit’s worth of information but costs a whole byte, unless you pack eight of them into one. That is what a bit-map is, and why bit-masking exists as a technique.

Hardware support

Different machines provide hardware support for different data types.

Intel-64 Architecture

Data type 8 bits 16 bits 32 bits 64 bits 128 bits
Signed integer ✓ ✓ ✓ ✓
Unsigned integer ✓ ✓ ✓ ✓
BCD integer ✓
Floating point ✓ ✓

Atmel AVR

Data type 8 bits 16 bits 32 bits 64 bits 128 bits
Signed integer ✓
Unsigned integer ✓
BCD integer
Floating point

Two ticks against eleven. The AVR supports exactly one data type in hardware: an 8-bit integer, signed or unsigned.

Other data types can be supported through software. For example, 16-bit integer operations can be built out of 8-bit operations, using a sequence of instructions. So the table is a statement about cost, not possibility — nothing in it is unavailable, it just takes more instructions and more cycles.

AVR example of 16-bit addition

Add the 16-bit quantity r5:r4 to r11:r10. (Result should be in r11:r10.)

Two instructions, worked as long addition in Figure 71:

    add  r10, r4         ; r10 <- r10 + r4        (low bytes; carry out lands in C)
    adc  r11, r5         ; r11 <- r11 + r5 + C    (high bytes, plus that carry)

Figure 71: 16-bit addition as long addition with one byte per column, high byte on the left. Step 1, add r10, r4, adds the low column and leaves any carry out of bit 7 in C. Step 2, adc r11, r5, adds the high column and that carry. This is the whole of how an 8-bit machine does 16-bit arithmetic.

ADD on the low bytes leaves any carry out of bit 7 in C; ADC on the high bytes adds it back in. It is column-by-column carrying, exactly as on paper, one byte per column — and nothing may sit between the two instructions that disturbs C.

Summary

Memory models Lecture 11
Registers Lecture 11
Instructions ✓
Data types ✓

Knowing all these details is enough to write machine code that runs on the CPU and to build the CPU.

See also

Lab 10 — AVR Assembly and the AVR 324 Dev Board

Learning Lab 10, the first lab where a program leaves the simulator and drives real hardware. See avr-io-ports for the ports and registers, avr-program-structure for the template every task is built on, and io-board for the switches, LEDs and buttons being wired up.

What this lab covers

Admin — dongles. By the end of semester you will be using two USB-A cables for data (one for programming, one for serial communication), one of them from about halfway through the semester. On a personal laptop that may mean a dongle; there are workarounds, but they all have downsides. Get one sooner rather than later. (The same warning as in week5-lab-avr-assembly-one; this is the lab where the cable is first needed.)

From assembly program to chip

A very simplified description of what is happening inside the microcontroller in terms of low-level programming:

\[\text{assembly language program} \longrightarrow \text{machine code} \longrightarrow \text{ATmega324A}\]

The example program

    MOV R3, R5
    ADD R3, R4
    NEG R5
    IN  R3, PINA
    OUT R5, PORTB

assembles to 11010……, 11011……, … which is then downloaded into program memory (Flash — 32 kB). Inside the chip: program memory holding those words, data memory (SRAM — 2 kB), the AVR 8-bit CPU (ALU + CU + Reg), and other components.

Figure 72: A very simplified picture of what is happening inside the microcontroller. Assembly text becomes machine code becomes the contents of flash; the CPU then reads it back out of flash one word at a time. The chip’s own panel is the point: program memory and data memory are separate blocks with separate address spaces (memory-models), which is why the machine code lands in one of them and the program’s variables in the other.

The last two lines of that program are the new part. Everything before them stays inside the CPU; IN and OUT are how a program reaches the outside world. Full picture in avr-architecture.

AVR I/O registers and general purpose I/O ports

  • The ATmega324A has 224 I/O registers, accessible at memory addresses 32 (0x20) to 255 (0xFF) with the ld (load) and st (store) instructions.
  • The first 64 I/O registers (0 to 63) can also be accessed using in and out.
  • Pages 636 to 639 of the datasheet (or the I/O register summary) have the I/O register details.
    • Many registers are reserved (not used).
    • The general purpose I/O port registers are DDRA, PORTA, PINA, DDRB, PORTB, PINB, …

Extract from the I/O register list

The bottom of the list is the twelve port registers. The datasheet writes both numbers in one Address column: the I/O register number first, the data memory address in brackets after it.

Address — I/O reg no. (data memory address) Name
0x0B (0x2B) PORTD
0x0A (0x2A) DDRD
0x09 (0x29) PIND
0x08 (0x28) PORTC
0x07 (0x27) DDRC
0x06 (0x26) PINC
0x05 (0x25) PORTB
0x04 (0x24) DDRB
0x03 (0x23) PINB
0x02 (0x22) PORTA
0x01 (0x21) DDRA
0x00 (0x20) PINA

I/O reg number (0–63) — used with IN/OUT
Data memory address — used with LD/ST

Further up the same table are 0x15 (0x35) TIFR0 through 0x18 (0x38) TIFR3, with 0x14 (0x34) marked Reserved.

Each row also carries the eight bit names for that register — PORTD7 … PORTD0, DDD7 … DDD0, PIND7 … PIND0 — which is where the per-pin names come from. The data-direction bits are DDDn/DDCn/DDBn/DDAn, not DDRDn: the register is DDRD, its bits are DDD7–DDD0.

Two numbers for one register, differing by the 0x20 the general purpose register file occupies at the bottom of the data space. Which number you write depends on which instruction you use, and the two worked questions below both turn on getting that right. See avr-io-ports.

GPIO ports

The datasheet block diagram has PORT A (8), PORT B (8), PORT C (8) and PORT D (8) around the edges of the chip: four 8-bit ports, PA7..0, PB7..0, PD7..0 — and port C as PC5..0 with TOSC1/PC6 and TOSC2/PC7 broken out, since those two pins are shared with the timer oscillator (avr-io-ports).

PIN, PORT and DDR registers

One bit of one port is three D flip-flops, DDRA0, PORTA0 and PINA0, around a tri-state buffer and one microcontroller pin. DDRA0 enables the buffer, PORTA0 supplies what it drives, and PINA0 samples whatever is on the pin. Drawn out and read through in avr-io-ports.

in and out

in rd, P Load I/O register value into general purpose register rd: r0 to r31; P = I/O register number (0 to 63, 0 to 0x3F) or name
out P, rr Store value from general purpose register into I/O register rr: r0 to r31; P = 0 to 63 (0 to 0x3F) or name

The “or name” form is covered under Using port names below.

Worked: setting port A to all outputs

Which instructions will set all bits of port A to be outputs?

Answer:

    ldi r16, 0xFF
    out 0x01, r16

From the table above, I/O register 0x01 is DDRA, and a 1 in a direction bit means output, so 0xFF makes all eight pins outputs. Three wrong answers, each one lookup away:

Changed line Why not
out 0x02, r16 0x02 is PORTA — this writes an output value, not a direction
ldi r16, 0x00 right register, wrong value — 0x00 makes all eight pins inputs
out 0x00, r16 0x00 is PINA — the read register

Right and wrong answers are the same two instructions; only the constant and the I/O register number move.

Using port names

Including the m324Adef.inc file lets a program use names for I/O registers rather than numbers:

.include "m324Adef.inc"

The contents of this file are included directly in the program. So the answer above can be written without ever looking up a number:

    ldi  r16, 0xFF       ; every direction bit 1 = output
    out  DDRA, r16

Identical machine code — the assembler substitutes 0x01 for DDRA. Write the names; look the numbers up only when reading someone else’s listing or an exam question.

Worked: setting port B to all inputs

Which instructions will set all bits of port B to be inputs?

Answer:

    ldi r16, 0x00
    out DDRB, r16

Two independent things have to be right:

  • out, not in. in loads from an I/O register into a general purpose one. in DDRB, r16 is not a legal instruction at all: in’s destination is written first and must be one of r0–r31, and DDRB is not one of those. in r16, DDRB is legal — it reads the direction register into r16, throwing away the constant just loaded there, and changes nothing.
  • 0x00, not 0xFF. out DDRB, r16 with 0xFF in r16 is the correct instruction with the value that makes every pin an output.

Across the two questions, the pair that must line up is (direction register, direction value): 1 is output and 0 is input.

ser and clr instructions

Short-hand ways of setting/clearing all bits of a register:

ser rd (set register) exactly the same as ldi rd, 0xFF — only works with registers ≥ 16 ser r16
clr rd (clear register) exactly the same as eor rd, rd clr r3

So both answers above can drop the constant — one instruction swapped for one, same two-line shape: ser r16 / out DDRA, r16 and clr r16 / out DDRB, r16. The asymmetry in which registers each reaches is not arbitrary — it follows from what they expand to; see avr-instructions.

Labels and the jmp instruction

        jmp RESET
        …
RESET:  …
        …

loop:   …
        …
        jmp loop

AVR assembly language program template

                             ; Comments start with semicolons
.include "m324Adef.inc"
    jmp RESET                ; <- vector table
    ; Interrupt handlers go here
    ; (more on this in week 9/10)

RESET:                       ; Starting point   <- RESET handler
    ...                      ; Initialisation code
                             ; e.g. set DDRs
loop:
    ...                      ; Do stuff        <- main code
    jmp loop                 ; Repeat

Three labelled sections — vector table, RESET handler, main code. Why it has that shape, and why the main body is an infinite loop, is in avr-program-structure.

Connecting the programmer

When attaching the programmer’s ribbon cable to the breadboard:

Red wire on the ground side

Getting this wrong damages hardware. See the Pololu Programmer Guide on Blackboard for the rest.

Tasks

NoteProvided task

Task 1 — AVR assembly program

Write an AVR program to

  • read the value on port A pins
  • flip (invert) all the bits
  • write the value out to port C
  • do this repeatedly

Remember to set data direction registers appropriately before reading/writing values.

Enter the code into Microchip Studio, simulate your code, check that it works by checking the appropriate registers.

Task 2 — Programming the AVR board

Connect 8 switches on the IO Board to AVR port A; and 8 LEDs to AVR port C.

  • Use 4-way cables with 4-way headers on each end
  • Build and download the program you wrote in task 1

See the Pololu Programmer Guide on Blackboard.

Test your program — change the values on the switches connected to port A and observe the LEDs.

Modify your program to output the two’s complement (negative) of the input, rather than the ones’ complement (inversion). Build, download and test it.

Task Three — Adding inputs

Connect 8 switches on the IO Board to AVR port A; and 8 LEDs to AVR port C; and connect the 4 push buttons on the IO Board to AVR port D (4 least significant bits).

  • Use individual jumper wires for this if required

Write an AVR assembly language program to repeatedly

  • Read the value on port A pins (8 bits)
  • Read the value on port D pins (8 bits)
    • Clear the upper nybble (4 bits) of this value (read from the four buttons); consider bitwise AND to do this

Add the two values and output the result to port C.

Make sure you set the data direction registers appropriately.

Build, download and test your program and verify it behaves as expected.

Task Four — Population count

  • Count the number of high bits
  • Read through popcount.pdf on BlackBoard
  • Several variations (extension tasks)

Figure 73: What tasks 2 and 3 ask you to wire, and what each port’s data direction register has to say about it. The direction rule is what fixes each DDR value: 1 is output, 0 is input. The four unconnected port-D pins are the reason task 3 asks for a bitwise AND.

Working — Task 1

The three things the task asks for map one-to-one onto three instructions, and the fourth (“do this repeatedly”) is the jmp at the bottom of the template.

.include "m324Adef.inc"

    jmp RESET

RESET:
    clr  r16
    out  DDRA, r16       ; port A: all inputs  (0 = input)
    ser  r16
    out  DDRC, r16       ; port C: all outputs (1 = output)

loop:
    in   r17, PINA       ; read what is actually on the pins
    com  r17             ; ones' complement - flip every bit
    out  PORTC, r17      ; drive the result out
    jmp  loop

Four things worth being deliberate about:

  • PINA for the read, PORTC for the write. Reading PORTA would give back whatever was last written to it, not what the switches are doing; writing PINC would not drive anything. Input side reads PIN, output side writes PORT — see avr-io-ports.
  • The direction registers are set once, in RESET, not inside the loop. They do not change.
  • ser r16 needs r16 or above, which is why the scratch register is r16 rather than, say, r3. clr would have been happy either way.
  • com is the inversion the task asks for — ones’ complement, i.e. flip every bit (avr-instructions).

Simulating it, as the task asks: Microchip Studio’s simulator has no switches, so set PINA by hand in the I/O view and single-step; r17 should show the complement and PORTC should follow it.

Working — Task 2

Same program, now on real hardware: 8 switches → port A, 8 LEDs → port C, 4-way cables at both ends. Flip a switch and the corresponding LED should go off — the inversion is visible as switch and LED disagreeing on every bit.

The modification is a one-instruction change:

    in   r17, PINA
    neg  r17             ; two's complement instead of ones'
    out  PORTC, r17

com gives \(\overline{x}\); neg gives \(\overline{x} + 1\), which is the two’s complement negation (binary-number-representations). The two differ by exactly one, so on the LEDs the difference is a single increment — easiest to see with all switches down: com shows 1111 1111, neg shows 0000 0000.

Working — Task 3

Three ports now, and one masking step:

.include "m324Adef.inc"

    jmp RESET

RESET:
    clr  r16
    out  DDRA, r16       ; port A: 8 switches, all inputs
    out  DDRD, r16       ; port D: 4 buttons on the low nybble, all inputs
    ser  r16
    out  DDRC, r16       ; port C: 8 LEDs, all outputs

loop:
    in   r17, PINA       ; the eight switches
    in   r18, PIND       ; the four buttons - in the low nybble
    andi r18, 0x0F       ; clear the upper nybble
    add  r17, r18
    out  PORTC, r17      ; sum to the LEDs
    jmp  loop

Why the mask is needed at all, since only four pins are wired: in r18, PIND reads all eight bits of port D, and the four upper pins have nothing connected to them. An unconnected input pin floats, so those bits are unpredictable — masking them off is what makes the sum depend only on the buttons. andi r18, 0x0F is the extract case of bit-masking: 1s on the bits to keep, 0s on the bits to discard.

andi works here because r18 is a high register. Reading the buttons into a low register instead would need the mask in a register of its own:

    ldi  r19, 0x0F
    and  r5, r19

add r17, r18 writes into r17, since AVR is two-operand (avr-instructions) — so the switch value is consumed by the addition, which is fine, it is re-read at the top of every pass.

What to expect on the board: switches give 0–255, buttons add 0–15, and the sum is 8-bit, so pressing buttons with the switches near 0xFF wraps around. That wrap is the carry being discarded, and it is worth watching for deliberately — it is the same 8-bit-only arithmetic that the 16-bit addition in 2026-09-03-instruction-set-architecture-part-2 exists to work around.

Working — Task 4

popcount.pdf on Blackboard has both the method and the extension variations.

One approach with the instructions met so far: shift the value one bit at a time and count the bits that fall out into C. lsr moves bit 0 into the carry flag (avr-instructions), so eight shifts pass every bit through C in turn, and a conditional add of 1 to a counter each time gives the population count. It needs two things beyond those instructions: a carry-conditional branch and a loop counter.

See also

Week 7

Lecture 13 — Introduction to Embedded C Programming

The first lecture of the high-level programming block: what a C program is made of, set against the assembly the course has just finished. A C program is made of five things — variables, functions, constants, operators, control flow — and the sections below take them in that order. The evergreen treatment is split across c-language-basics (structure, variables, functions, constants), c-operators and c-control-flow.

Course overview

The three blocks of the course, from Lecture 1:

Block Status
High-level Programming — Embedded C programming for the ATmega324A the current block
Low-level Programming — ISA and Assembly language programming for the ATmega324A finished as a topic, still in use
Digital Logic Design — Hardware aspects of a microprocessor done

Assembly is finished as a topic but not left behind, because every C construct here is explained by what it compiles down to.

What the course expects in C

The expectation in this course is to:

  • be able to write small C programs and functions from scratch
  • understand the meaning of C programs
  • be able to write/modify C programs

Lectures can’t teach programming. It takes practice.

  • There will be some self-learning examples on EdForum
  • Coding examples in Labs 11–16 will be using embedded C

From Lab 11 on, the lab work is C, and the assembly of Labs 9 and 10 (week5-lab-avr-assembly-one, week6-lab-avr-io-ports) is what it sits on.

C program — basic structure

  • There must be a function called main — this function is executed when the program starts
  • Blocks of code enclosed by braces { }
  • C statements must end with a semicolon ;
  • C statements are case sensitive — variable is not the same as Variable
  • Comments are within /* … */ or from // to end of line

The program sits in a file such as name.c. main() is at the top with its args in the brackets, then a brace and a column of statement lines, each ending in a semicolon. C = A + B is an expression, the thing C lets you write that assembly does not. There are two routes into program memory, drawn in Figure 74.

Figure 74: What happens to one line of C. Two routes converge on program memory: the long compiler arrow runs from the C statement straight to the machine code, and a short assembler arrow drops the assembly line into the same place. Under the machine code sits the control unit, fanning out to the ALU and register file. The bit string 1001 ... 01101 is a placeholder, not a real encoding.

Figure 74 is the frame for the whole block. The bottom three boxes are Lectures 9–12 (fetch-decode-execute-cycle, avr-instructions); C adds one more layer on top, and a compiler to cross it. The compiler’s arrow goes past the assembly box straight into program memory, because the crossing is no longer one-to-one — a single C = A + B; may become several instructions, and the programmer never chooses which registers or even sees the assembly. The asymmetry in short: assembly ↔︎ machine code, 1:1; C → machine code — see 2026-09-10-more-c-programming-on-the-avr.

The five things

① variables
② functions
③ constants
④ operators
⑤ control flow, e.g. if … else

The area-of-a-circle formula \(A = \pi r^2\) is the running example for the first three: \(A\) and \(r\) are variables, \(\pi\) is a constant, and the multiplication and squaring are operators. Five sections below carry the matching number — variables, the function example, constants, operators and if.

① Declaring variables

Declaration: type-name variable-name, variable-name …; — the comma separates names of the same type, the semicolon ends the declaration.

Example Type Size and range
char c; Single byte (two’s complement) 8 bit, −128 … 127
unsigned char x; Single byte (unsigned) 0 … 255
int day; Integers (size is machine dependent). Integers can be unsigned or signed (two’s complement). AVR: 16 bit
unsigned int count; (same)

Two things to remember:

  • char is a number. It is the same 8-bit two’s complement integer the whole hardware block was about (binary-number-representations); the name just says it is big enough for a character. unsigned char is the 0–255 reading of the same byte.
  • int has no fixed size. On the AVR it is 16 bits — two of the machine’s 8-bit cells, which is why Lecture 14’s pointer arithmetic steps by two. On a desktop it is usually 32. Code that assumes one or the other breaks when moved.

char, int, float and double are among the data types supported by C. float and double are the floating-point types the AVR has no hardware for (instruction-set-architecture has the tables), so every floating-point operation is a library call (floating-point-numbers).

Any value can be treated as a boolean — zero means false, non-zero means true. In short: == 0 FALSE, ≠ 0 TRUE. There is no separate boolean type in the C the course uses. The if statement below comes back to this.

② Function example

/*
  Return the average of two integers
  (result will be rounded towards 0)
*/
int average(int a, int b) {
    int avge;

    avge = (a+b)/2;

    return avge;
}

int at the front is the return type, average is the name, and int a, int b are the args. The three lines inside the braces are the statements, each ending in a semicolon. In avge = (a+b)/2; the = is an assignment operator, and (a+b), (a+b)/2 and the whole line are expressions; the outer expression is a statement. return avge; is where the function returns a result when finished.

The comment says rounded towards 0. \(\frac{1+2}{2} = 1.5\), but average(1, 2) is 3/2, integer division, and the .5 is simply dropped, giving 1. Division of two ints in C is integer division; the fraction never exists to be rounded.

Function definitions

The template:

return-type function-name (arg-decl)
{
    variable-declarations;
    …
    statements;
}
Part Meaning
return-type What type is returned by the function, e.g. int or void
function-name Name of the function, e.g. main
arg-decl Argument (parameter) declaration, e.g. int a, float b
variable-declarations Variables used only within the function
statements The code which actually does stuff

void is the return type for a function that returns nothing. The only within the function is scope: avge in the example exists while average runs and is gone afterwards — it has no address anyone outside can name.

③ C constants

Character constants — use single quotes, e.g. 'a', 'b', '1' etc. Some special characters are backslash escaped:

'\n' newline
'\'' single quote
'\t' tab
'\\' backslash

String constants — use double quotes (can include backslash escapes), e.g. "abc \n \" hello\t".

Integer constants

Base Examples
Decimal 3, -27, 65535, +5
Hexadecimal (leading 0x) 0x5F, 0xFFFF, 0xDEADBEEF
Octal (leading 0) 0377 = 255 decimal

Floating point constants — include a decimal point (.) and/or e for exponent: 3.1416, -7., 6.02e23, -5.2e-2. 7 is an integer, 7. is floating point.

In ASCII, A–Z is 65–90, a–z is 97–122, 0–9 is 48–57. That is what makes '1' a character constant and not the number one: '1' is 49. In \(A = \pi r^2\), \(\pi\) is the constant in the running example.

The octal row is the trap to remember. A leading zero changes the base. 0377 is 255, not 377, and 010 is 8. Nobody writes octal on purpose in this course, but a zero-padded decimal will be read as it.

④ Some C operators

Binary operators, by group:

Group
+ addition arithmetic — e.g. A + B, A − B
- subtraction
* multiplication
/ division
% remainder (integer)
> greater than comparison
>= greater than or equal
== equal
!= not equal
< less than
<= less than or equals
& bitwise AND logical — this one group takes in both the bitwise and the logical rows
\| bitwise OR
^ bitwise XOR
&& logical AND
\|\| logical OR
= assignment

Unary operators

Example
! logical not !A ≡ Ā
~ one’s complement (invert) ~A
- two’s complement (negate)
++ increment (prefix or postfix)
-- decrement (prefix or postfix)

The pair to keep apart is == and =: == asks, = does. = copies the right side into the left, so a = b is best read as a ⇐ b. Writing = where == was meant is legal C — it assigns, then tests the assigned value — and is the classic silent bug.

Two more pairs look alike and are not: & against && and | against ||. The single forms are the eight-parallel-columns operations of bit-masking — AND, OR, EOR in avr-instructions — and the double forms are the true/false connectives of boolean-algebra. ~ is the COM instruction and unary - is NEG. The full reference is c-operators.

More operators — bit-shifting and assignment

a << b means a shifted left by b bits
a >> b means a shifted right by b bits
a = b means a is assigned the value of b, i.e. a ⇐ b
a += b is shorthand for a = a + b

Similarly -=, *=, /=, %=, &=, |=, ^=, <<=, >>=.

Examples, with the shifts worked in bits:

Example Worked
1 << 5 is \(1 \times 2^5 = 32\) 000001 << 5 ⇒ 100000 ⇒ 32, with five zeros now to the right of the 1
3 << 4 is \(3 \times 2^4 = 48\) 0000011 << 4 ⇒ 0110000 ⇒ 48, with four zeros now to the right of the 11
a += 1 same as a++ a = a + 1, a++

Figure 75: The two shift examples worked in eight bits. The 1 in 1 << 5 walks five places to the left and lands at bit 5, which is \(2^5 = 32\); the 11 of 3 << 4 walks four places and lands at bits 5 and 4, \(32 + 16 = 48\). The curved arrows span the zeros the 1s hop over.

1 << n is the idiom that matters: it is the mask with only bit \(n\) set, and Lecture 14 connects it to named flags. This is lsl from 2026-09-03-instruction-set-architecture-part-2 with the count written as a number instead of repeated \(n\) times — and the same ×2-per-place reading applies.

Postfix/prefix increment and decrement

An example, with the running value of a for each line:

int a,b,c,d,e;
a = 4;
b = a++;    /* b=a;   a=a+1; */
c = --a;    /* a=a-1; c=a;   */
d = ++a;    /* a=a+1; d=a;   */
e = a--;    /* e=a;   a=a-1; */
Line a before What happens a after
b = a++; 4 b=4, then a=5 5
c = --a; 5 a=4, then c=4 4
d = ++a; 4 a=5, then d=5 5
e = a--; 5 e=5, then a=4 4

After these statements, values are a=4, b=4, c=4, d=5, e=5.

The rule:

  • Postfix (a++) — use value, change value. The change happens after the value is used.
  • Prefix (++a) — change value, use value. The change happens before the value is used.

The comments in the code are the whole definition: each line is two statements, and the only question is which comes first. The two-statement expansion is also why values[9] = values[8]++; in Lecture 14’s array example copies the old values[8].

Worked: what value will b have?

a = 1;
b = 3;
b += a++;

The choices are 1, 2, 3, 4, 5, 6 or none of the above.

b is 4. The line is b = b + a++, and it splits into two statements exactly as above: ① b = b + a ⇒ b = 4, ② a = a + 1 ⇒ a = 2. Postfix means the + 1 on a lands after a’s old value has already gone into the sum. The answer 5 comes from applying the increment first, which is what ++a would have done.

⑤ if statement

The if statement is control flow, the fifth and last of the five things.

if (expression) stmt else stmt — the first stmt runs when the expression is TRUE and the else stmt runs when it is FALSE.

  • The else clause is optional.
  • Expressions: C interprets any 0 value as false, anything else as true.
    • if(a) means if(a != 0) — ≠ 0 TRUE
    • if(!a) means if(a == 0) — == 0 FALSE
  • stmt can be replaced by multiple statements enclosed in braces { }.

There are three kinds of control flow, drawn in Figure 76:

sequential selection (decision) repetition
statements, one after another if … else for; while

Figure 76: The three shapes a C program’s control can take. Left, the default: statements run one after another. Middle, selection: the expression is tested and exactly one of the two branches runs. Right, repetition: the body runs and control returns to the test until the test is false.

Selection is the if statement above. Repetition arrives in Lecture 14 as the for loops that walk an array and the while(1) that every embedded program runs inside — see c-control-flow for all three together.

The if(a) shorthand and the boolean rule under variables are the same fact stated twice, and they connect straight back to hardware: the compiled test is a compare against zero followed by a conditional branch, cp/tst then breq/brne in avr-instructions — the Z flag is what “is it zero” means to the machine.

See also

Lecture 14 — More C: C Programming on the AVR

This is where C meets the hardware: arrays, pointers and what they look like in the AVR’s data memory; the preprocessor and the header file that turns DDRA into a memory address; and a complete program that drives the IO board’s seven-segment display. The evergreen notes are c-pointers-and-arrays, c-preprocessor-and-avr-headers and seven-segment-display; the shift rules go into c-operators.

Bit shifts in C

The three assembly shifts are lsl, lsr and asr, from Lecture 12 (2026-09-03-instruction-set-architecture-part-2):

Instruction Movement of the bits Effect
lsl C ⇐ [ register ] ⇐ 0 × 2
lsr 0 ⇒ [ register ] ⇒ C ÷ 2 unsigned
asr the top bit looped back into itself, ⇒ C ÷ 2 signed

The C equivalents:

a << b a shifted left by b bits
a >> b a shifted right by b bits — a logical shift right if a is unsigned, an arithmetic shift right if a is signed

In assembly the programmer chooses lsr or asr by hand and thereby declares what the bits mean. In C the declaration is the variable’s type, and the compiler picks the instruction: unsigned char gets lsr, char gets asr. There is one >> operator and two instructions behind it. (Strictly, the C standard leaves >> on a negative signed value implementation-defined; avr-gcc chooses the arithmetic shift, and treats plain char as signed, which is what makes the rule hold on this toolchain.)

Two more points:

  • 1 << 5 is 00100000, a single 1 in bit 5. This is the idiom the AVR headers are built on: a flag is a bit number, say FLAG_NAME == 5, and 1 << FLAG_NAME is the mask for it. The worked bits are drawn in the shift figure of 2026-09-07-introduction-to-embedded-c-programming; the idiom is in bit-masking.
  • Assembly to machine code is 1:1: one assembly line is one machine instruction. C also ends up as machine code, but by a route where one statement may become several instructions (the C-to-machine-code figure of 2026-09-07-introduction-to-embedded-c-programming).

Arrays in C

An array is declared as type variable_name[size];

  • char message[16];
  • int values[10];
  • float BT_26[365]; — 365 entries, presumably one per day of a year.

An element is accessed as variable_name[index], where index = 0 … size−1. This is zero-based indexing.

  • message[0] = 'c';
  • values[9] = values[8]++;
  • BT_26[0] = 36.3; down to BT_26[364] = 33.8; — the first and last legal indices of a 365-element array.

BT_26[365] does not exist, and C will not stop you writing to it: it will write to whatever happens to sit after the array in memory. The memory layouts below make that concrete.

values[9] = values[8]++; is postfix, so it is two statements: values[9] = values[8]; and then values[8] = values[8] + 1; — the copy gets the old value (2026-09-07-introduction-to-embedded-c-programming).

Pointers

C has pointers. A pointer is declared as type * variable_name;, which makes variable_name a pointer to something of the given type. A pointer variable stores a memory address.

For example:

char a, b;
char *ptr;      /* can write these on one line: char a,b,*ptr; */

ptr = &a;       /* & is address-of operator - creates a pointer  */
b = *ptr;       /* * is indirection operator - returns value pointed to */

Figure 77 works it in data memory. Say a = 8, with a at address 400, b at address 434 and ptr at address 576. After the two assignments, ptr == 400 and b == 8.

Figure 77: The pointer example in data memory. Three variables, three cells: a holds 8, b holds 8 (copied through the pointer), and ptr holds 400 — which is not a value but the address of a, hence the arrow. The decimal addresses 400, 434 and 576 are only examples; where the compiler actually places variables is its own business. The lowest address is at the top and addresses are written down the right, as in the course’s memory maps, but in decimal here.

The two operators are inverses, and Figure 77 is the way to keep them straight. &a goes from a variable to its address — the number 400. *ptr goes from an address back to the value stored there — follow the arrow, read the cell. b = *ptr; therefore lands 8 in b. ptr is itself an ordinary variable with its own cell at 576; a pointer is just a variable whose contents happen to be an address.

This is the indirect addressing mode of addressing-modes made into a language feature: ptr plays the part of X, and b = *ptr; compiles to something like ld r_b, X.

Pointers and arrays

An array name can be treated as a pointer to the first element, i.e. the address of the first element.

int a[10];
int *ptr;

/* following statements are same */
ptr = a;
ptr = &a[0];

The array is a contiguous run of cells in data memory, and its name means the address where that run starts: 300, say.

Operations on pointers

Addition and subtraction on pointers work in multiples of the size of the object being pointed to.

int a[10];
int *ptr;

/* following statements are same */
ptr = a+5;
ptr = &a[5];

An int on the AVR is 16 bits, and a data memory cell is 8 bits wide. With a at 300, a + 5 is not 300 + 5 = 305 but 300 + 2·5 = 310. In memory a[0] lies across addresses 300 and 301, a[1] across 302 and 303, and so on down to a[9]. a is 300, and so is ptr after ptr = a. Figure 78 draws it out.

Figure 78: int a[10] in the AVR’s data memory. Each cell is 8 bits wide; an int on the AVR is 16 bits, so every element takes two cells and the array runs from 300 to 319. That is why a + 5 is address 310, not 305: pointer arithmetic counts in elements, and the compiler multiplies by the element size. The shaded element is a[5], the one the arithmetic lands on.

The compiler does the multiplication. a + 5 means five elements on, and since an int is two cells on this machine that is ten cells, so 310. Had the array been char, a + 5 would be 305 — the same source expression, a different address, decided entirely by the declared type. This is also why the rule says the size of the object being pointed to rather than a number: the number is machine-dependent, exactly as the size of int itself is (Lecture 13). See memory-models for the AVR’s 8-bit data cells, which are what make the two-cells-per-int happen.

Traversing an array

Two ways of clearing an array, each filling its cells with 0 one after another.

Using an index:

int a[10];
int index;
for(index=0; index<10; index++) {
    a[index] = 0;
}

Using a pointer:

int a[10], *ptr;
for(ptr=a; ptr < a+10; ptr++) {
    *ptr = 0;
}

ptr++ works because adding one to an array pointer makes it point to the next element in the array.

The two loops are the same loop. The index version computes a + index on every iteration and dereferences it; the pointer version keeps that address in ptr and moves it by one element — two cells — each time round. ptr < a+10 is the same bound as index < 10: the address one past the last element, which is the first address the loop must not touch. Both stop before it. The for itself is the repetition column of Lecture 13’s three-shapes figure; the anatomy is in c-control-flow.

Preprocessor

A C program is first parsed by a preprocessor, which replaces preprocessor directives with substitute text. The two directives used here are #include … and #define … (macros); there are many others, such as #if, #ifdef, #else and #undef.

Figure 79 shows #include. A file name.c has #include <header.h> at its top, the directive names a second file header.h, and the combined text is compiled to machine code (M/C).

Figure 79: What #include does. The directive is not an instruction to the compiler; it is replaced, textually, by the contents of the named file before the compiler sees anything — so what gets compiled is one file, name.c with header.h pasted in at the top, drawn on the right.

Header (.h) files

Header files (.h files) hold common macros, function prototypes and so on, like m324Adef.inc for assembly (avr-io-ports).

Two examples:

  • stdio.h — includes the prototypes of printf() etc. The AVR has a simplified version of this (e.g. no files), and printf() will only work if you specify where the characters go, e.g. sent via the serial port.
  • avr/io.h — the AVR’s header of useful constants and functions/macros. Its definitions depend on the actual device targeted.

avr/io.h is what makes DDRA = 0xFF a legal line of C. The macro sections below explain why.

Preprocessor examples

Form Kind of header
#include<filename.h> system
#include"filename.h" user-defined

Angle brackets look in the system’s include directories — where avr/io.h and stdio.h live; double quotes look in your own project first.

A macro is a textual substitution:

Macro Use
#define pi 3.1415 in A = pi * r^2; the pi is replaced by 3.1415
#define EVER ;; in for(EVER) { … } the EVER is replaced by ;;, giving for( ;; ) { … }
#define sum(a,b) (a+b)

EVER shows the mechanism: for(EVER) is not a language feature, it is for(;;) after two semicolons have been pasted in, and for(;;) with no condition loops forever. The preprocessor does not know C. It replaces text, and only afterwards does the compiler read the result as a program.

Worked: SQUARE(1+2)

Given #define SQUARE(x) (x*x), what is the result of SQUARE(1+2)?

5. The substitution is literal, (1+2*1+2), and it is evaluated as written: multiplication first, so \(1 + 2 + 2 = 5\). Not 9.

The fix is to define the macro as ((x)*(x)). Then SQUARE(1+2) is ((1+2)*(1+2)) = 9. The rule: parenthesise every parameter, and the whole body, because the argument is pasted in as text and inherits whatever operators surround it. The AVR headers below are written this way for exactly this reason, with brackets around (mem_addr) and (io_addr).

AVR C macro examples

From avr/io.h (via the device-specific header it pulls in):

#define _MMIO_BYTE(mem_addr) \
                (*(volatile uint8_t *)(mem_addr))
#define _SFR_IO8(io_addr) \
                _MMIO_BYTE((io_addr) + 0x20)

/* Input Pins, Port A */
#define PINA      _SFR_IO8(0x00)

/* Data Direction Register, Port A */
#define DDRA      _SFR_IO8(0x01)

/* Data Register, Port A */
#define PORTA     _SFR_IO8(0x02)

The macros chain: DDRA is defined with _SFR_IO8, and _SFR_IO8 with _MMIO_BYTE, adding 0x20 on the way. Figure 80 unrolls the chain for DDRA = 0xFF.

Figure 80: The macro chain behind DDRA, unrolled from the three #define lines. DDRA expands to _SFR_IO8(0x01), which expands to _MMIO_BYTE(0x21), which expands to a dereferenced pointer to data address 0x21. The + 0x20 is the offset between the I/O-space number an out instruction uses and the data-space address of the same register — the two columns of the I/O register table in the AVR I/O ports note. The memory map on the right is the datasheet’s, as in Lecture 11.

Read the innermost line from the inside out: (uint8_t *)(0x21) says treat the number 0x21 as the address of an 8-bit unsigned byte; the outer * dereferences it, so the whole expression is that byte; and = 0xFF stores into it. volatile tells the compiler the byte can change behind its back — a hardware register does — so it must not cache the value in a register or skip a store it thinks redundant.

The + 0x20 is the same fact as the two columns of the register table in avr-io-ports: the address an out instruction takes is the I/O space number, and the same register sits 0x20 higher in the data space where lds/sts — and a C pointer — reach it. DDRA is I/O 0x01, data 0x21, and the macro converts one to the other.

I/O register names as variables

The upshot of these macro definitions is that I/O register names can be used as variables:

DDRA = 0xFF;
PORTA = PINC | 0xF0;

Compare the assembly for the first (avr-io-ports): ser r16 then out DDRA, r16. The C is one line, and the compiler chooses the register. The second line is a read-modify-write across two ports — read PINC, OR in the mask, write PORTA — and the | 0xF0 is a set mask in the sense of bit-masking: the top four bits are forced to 1, the bottom four pass through from PINC.

Seven segment display programming example

Figure 81 draws the display and the byte that drives it.

The display has seven bars, lettered a across the top, b upper right, c lower right, d across the bottom, e lower left, f upper left, g across the middle, and a small circle dp for the decimal point. Setting the five segments a, b, g, e and d to 1 lights the digit 2.

The microcontroller (MC) drives the display from port A: eight wires, one per segment. The bit order is:

bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
dp g f e d c b a

Two worked bytes:

Digit dp g f e d c b a Value Statement
0 0 0 1 1 1 1 1 1 \(32 + 16 + 15 = 63\) PORTA = 63;
2 0 1 0 1 1 0 1 1 \(64 + 16 + 8 + 3 = 91\) PORTA = 91;

Figure 81: The seven-segment display and its byte. Left: the seven segments lettered a to g clockwise from the top with g across the middle, plus the decimal point; the segments drawn heavy are the ones set to 1, which spell a 2. Right: the byte written to port A, one bit per segment, dp at bit 7 down to a at bit 0, with two worked bytes: 63 for a 0 and 91 for the 2 on the left.

The sums read each byte in chunks: 00111111 is \(32 + 16\) for bits 5 and 4 and then \(15\) for the low nibble 1111; 01011011 is \(64 + 16 + 8\) for the three high ones and 11 \(= 3\) at the bottom. Full encoding table for all ten digits in seven-segment-display.

Seven segment display on IO board

The header pins along the board’s top edge are TX RX CC DP G F E D C B A B3 B2 B1 B0 PR. The display’s pins are CC to A; the silk-screen brackets the display pins as SSD. CC is the common cathode pin, and it selects the digit:

left digit ON CC = 1
right digit ON CC = 0

Two digits, one set of segment lines. The A–G and DP pins go to both digits; CC selects which one is actually lit. So a two-digit number is shown by alternating — drive the left digit’s segments with CC high, then the right digit’s with CC low, fast enough that both look steady. The header itself is in io-board.

The program

#include <avr/io.h>

/* Seven segment display values */
uint8_t seven_seg[10] = { 63,6,91,79,102,109,125,7,127,111};

int main(void) {
  uint8_t digit;

  /* Set port A pins to be outputs, port C pins to be inputs */
  DDRA = 0xFF;
  DDRC = 0;    /* This is the default, could omit. */
  while(1) {
    /* Read in a digit from lower half of port C pins */
    /* We read the whole byte and mask out upper bits */
    digit = PINC & 0x0F;
    /* Write out seven segment display value to port A */
    if(digit < 10) {
      PORTA = seven_seg[digit];
    } else {
      PORTA = 0;
    }
  }
}

Everything above is in this one listing:

  • #include <avr/io.h> — angle brackets, a system header; it is what makes DDRA, DDRC, PINC and PORTA legal names, and uint8_t too.
  • uint8_t seven_seg[10] = { … } — an array, declared with its ten values in braces, outside main so it is not one of main’s locals. Its index is the digit, its contents the byte from Figure 81: the first three values, 63, 6 and 91, are the digits 0, 1 and 2, and seven_seg[0] and seven_seg[2] are the two bytes worked above. uint8_t is the header’s name for an unsigned 8-bit integer — unsigned char with its size written on it.
  • DDRA = 0xFF; DDRC = 0; — direction registers, port A all outputs, port C all inputs, exactly as in week6-lab-avr-io-ports but without the ldi/out pairs.
  • while(1) — the repetition column of Lecture 13’s three-shapes figure with a condition that is always true. An embedded program has nowhere to return to, so its main never finishes; every AVR program from here on has this loop.
  • digit = PINC & 0x0F; — read the input port, keep the low nibble: bit-masking, the extract case, in C.
  • if(digit < 10) — selection, guarding the array: indices 10–15 are possible from four input bits and seven_seg[10] does not exist. The else blanks the display instead of reading past the end of the array.

See also

Week 8

Lecture 15 — Flow of Control

Back to assembly, to fill in the two things a program needs beyond straight-line code: branches and jumps, which is where the AVR’s S flag and the signed/unsigned pairs of branch instructions get explained properly, and procedures, which is where the stack enters. The last part opens the next topic, the AVR’s timer/counters, which Lecture 16 takes up. The evergreen notes are avr-branches-and-jumps, procedures-and-the-stack and avr-timers-and-counters.

Outline

  • Flow of control
    • Branching
    • Procedure Calls
    • Use of stacks
  • Introduction to AVR Timer/Counters

Background

Three things are assumed from here on: the Atmel AVR CPU (the ALU, general purpose and special purpose registers); the main hardware components of the ATmega324A/ATmega328 microcontroller (AVR CPU, Data Memory, Program Memory, GPIO Ports, Timers/Counters, PWM, Communication Interfaces etc); and AVR assembly language instructions.

The course roadmap has four boxes: AVR Assembly language ⇒ AVR C programming ⇒ ALU Operations ⇒ Interaction with I/O. The course does not walk the row left to right. The control-flow instructions here are a step back into assembly, and the timers at the end are the start of the I/O box.

Flow of control

Flow of control is the sequence that instructions actually get executed in. It is linear (i.e. successive instructions) unless there are branches/jumps, procedure calls, etc.

Plot the program counter against time. Linear flow is a straight rising line: the instructions run one after another, and every fetch-decode-execute (FDE) cycle does PC ← PC + 1. Non-linear flow, the typical case, is the same line broken by jumps: a run, then a drop back (a jump to a lower address) or a rise (a jump forward) at each break. A small program with such breaks:

main:   ...
        ...
        call TEST
PING:   ...
        BREQ ABL
TEST:   ...
        ...
        call PING
ABL:

call TEST jumps down to TEST:. Three labels, two calls and a conditional branch: every kind of non-linearity named below is in those nine lines. Figure 82 draws what the program counter does.

Figure 82: The program counter against time. Left: straight-line code, where every fetch-decode-execute cycle adds one to the PC and the plot is a line of constant slope. Right: the same plot for code with a procedure call, its return and a backward conditional branch. Between the breaks the slope is still one instruction per cycle; each break is a single instruction that loads a new value into the PC instead of the next address. A call jumps forward to the procedure, ret drops back to the instruction after the call, and a taken backward branch drops back to a label above it, which is what a loop looks like. The rises and drops are the only thing that separates the two plots: control flow is the PC being overwritten.

What breaks sequential execution

Most instructions result in the PC being incremented (sequential execution), i.e. PC ← PC + 1, as in the fetch-decode-execute-cycle. Instructions are not executed sequentially when there are:

① Branches conditional
② Jumps unconditional
③ Procedures function calls
④ Interrupts / Traps

The first three are the three sections that follow, in that order. Interrupts are in Lecture 17 (2026-09-21-interrupts; the mechanism is in polling-and-interrupts).

Branches

  • AVR branch instructions are typically conditional.
  • They are useful in implementing if-else and loops in assembly language.
  • breq and brne are the two met so far (2026-09-03-instruction-set-architecture-part-2, and the compare-then-branch figure in avr-program-structure).
  • For a comparison such as greater than or equal to, the instruction used depends on whether the numbers being compared are unsigned or signed (two’s complement).

breq/brne only ask equal or not, and equality means the same thing for signed and unsigned bytes. Greater than does not: 1111 1111 is 255 unsigned and −1 signed, so whether it is greater than 0000 0001 depends on which you meant, and the machine cannot know. Hence two instructions.

Branches — AVR assembly example

cp r5, r6 computes r5 − r6 and updates the status flags N, Z, C, V and S. Take this pseudo code on two registers:

r5, r6
if (r5 ≥ r6)
    ⋯    (the if part)
else
    ⋯    (the else part)

In the assembly that implements it, the if body goes under the IF: label and the else body goes in the lines directly after the branch:

        cp   r5, r6
        brge IF
        ...              ; the else part
        ...
        jmp  EXIT
IF:     ...              ; the if part
        ...
EXIT:   nop              ; "no operation"

Figure 83 lays the two side by side.

Figure 83: How an if … else becomes assembly. The compare sets the flags; the conditional branch reads them and jumps to the if part when the condition holds. Because a branch can only jump somewhere, the code that runs when the condition fails has to be the code the branch skips over — so the else part sits directly after the branch, ends in an unconditional jmp past the if part, and the if part lives under a label further down. The two bodies end up in the opposite order from the source, which is the thing to expect when reading assembly back into C. EXIT carries a nop only so that the label has an instruction to name; anything that follows the statement would do.

If S = 0, brge makes the jump. There are three cases where it has to, each placed on the signed number line:

Case Number line Flags
① r5 > r6 0, r6, r5 in that order, both to the right of zero N = 0, V = 0
② r5 = r6 N = 0, V = 0
③ r5 > r6 r6 far to the left, r5 far to the right, and r5 − r6 wrapping round past 127 N = 1, V = 1

In all three S = N ⊕ V = 0, so brge jumps in all three, which is what greater than or equal requires. Case ③ is the one that justifies the S bit: r5 is a large positive and r6 a large negative, so r5 − r6 is bigger than 127 and overflows into a result whose top bit is 1. The N bit therefore says negative, which is wrong; the V bit says but that sign is an overflow artefact; and their XOR cancels the two to give the true sign. Figure 84 draws the three, and a fourth case, r5 < r6, where the branch must not be taken.

Figure 84: Why a signed comparison tests S and not N. Each panel is the signed number line of an 8-bit register, \(-128\) to \(127\), with the two operands of cp r5, r6 marked and the flags the subtraction sets. In the top three cases \(r5 \ge r6\) and brge must jump; in the first two the difference fits and N alone would do. In the third the true difference is larger than 127, the 8-bit result wraps to a negative pattern, and N reports the wrong sign — but the overflow flag V is set at the same time, and S = N \oplus V corrects it back to 0. The bottom panel is the case the branch must not take: \(r5 < r6\) gives a genuinely negative difference, N = 1 with V = 0, so S = 1. Reading S gives the right answer in all four; reading N fails in the third.

AVR “S” status bit

Two status bits met earlier:

  • N bit = negative (1 if the sign bit of the result is 1)
  • V bit = two’s complement overflow

The AVR also has the S bit: S = N ⊕ V, the sign bit corrected for overflow. If overflow happens, the sign bit will be wrong, so instead of checking the N bit, check the S bit.

S has been in the status register since Lecture 10 (avr-architecture); this is what it is for. It exists so that a signed less than is one flag test rather than two.

Branch instructions

Each conditional branch tests one status bit for one value:

Branch if status bit is equal to C N V S = N⊕V Z
0 brsh (= brcc) brpl brvc brge brne
1 brlo (= brcs) brmi brvs brlt breq

Ten instructions, one per flag per value. Two of the columns are the comparisons that matter here:

unsigned brsh — same or higher brlo — or lower
signed brge — greater than or equal brlt — lower than

A worked example: r5 = 1111 1111, r6 = 0000 0001. Read as unsigned, cp computes 255 − 1, which is positive, so brsh is the branch taken. Read as signed, cp computes −1 − 1, which is negative, so brlt is the branch taken. Same two registers, same cp, same flags — and one branch says r5 is higher, the other says r5 is less. Both are right. The unsigned pair reads C, because an unsigned subtraction that needs a borrow is exactly one whose result went below zero; the signed pair reads S, for the reason worked through above. The programmer chooses the instruction and thereby declares what the bits meant, the same decision as lsr versus asr in 2026-09-03-instruction-set-architecture-part-2. Full table and the loop idioms in avr-branches-and-jumps.

Jumps

The AVR has three jump instructions:

jmp label — absolute jump, 32-bit instruction, 3 cycles label is a 14-bit address
rjmp label — relative jump, 16-bit instruction, 2 cycles label becomes an offset, − or + up to 2048 cells
ijmp — indirect jump, 16-bit instruction, 2 cycles, jump target is given in Z register

Why two sizes. jmp carries the destination as a full program-memory address, and an address into the ATmega324A’s 16 K-word flash needs 14 bits — more than fits in a 16-bit instruction word alongside the opcode, so jmp takes two words (avr-instructions on instruction encoding). rjmp instead carries a signed offset from the current PC, 12 bits of it, so it can reach ±2 K words — 2048 cells either way — in a single word and one cycle less. Almost every jump in a small program is within that range, which is why the labs’ template uses rjmp for its main loop. ijmp takes the address from Z, the pointer register of addressing-modes: the destination is a value, computed at run time, rather than a label fixed at assembly time.

Procedures

A procedure is a group of instructions that performs some task.

  • It may have operands (arguments or parameters).
  • It may produce result(s).
  • It can be invoked (called) from multiple places in a program, even from within itself: a recursive procedure.
  • After invocation, control returns to the statement after the call.
  • Good use of procedures helps structure a program well.
  • Other names: subroutine, function (C, Python), method (Java).

The shape of a call:

main:   ...
        ...
        call TEST      ; args ?
        [xxx]          ; the instruction after the call

TEST:   ...
        ...
        ret            ; returns results ?

call TEST jumps down to TEST:, and ret jumps back up to [xxx], the instruction after the call. The two questions in the comments are among the procedure issues below.

Call instructions

The AVR has three call instructions:

call label direct subroutine call, 4 cycles, 32-bit instruction
rcall label relative subroutine call, 3 cycles, 16-bit instruction
icall indirect call, 3 cycles, 16-bit instruction

The same three flavours as the jumps — absolute, relative, indirect — each one cycle longer than its jump, which is the cost of saving the return address.

Procedure issues

Procedures raise three questions:

  • After a procedure finishes, control returns to the statement after the call. How does the procedure know where to return to?
  • How are operands specified (i.e. arguments passed)?
  • How is the result returned?

The first takes the most answering. The other two are answered together, briefly, once the stack is in place.

Return address

There are three places the return address could be stored:

Option Problem
A single fixed memory address or register for all procedure calls procedures can’t call other procedures
A memory location per procedure doesn’t allow for recursion
A stack

The second option fails for a procedure that calls itself:

main:   ...
        call TEST
        [xxx]
TEST:   ...
        call TEST

Two calls of TEST are live at once, so two return addresses must be kept at once; one slot per procedure holds one. Two return addresses kept one above the other are already a stack.

Each option fails on the next level of nesting. A single slot works until a procedure calls a procedure — the second call overwrites the first’s return address and main is never returned to. A slot per procedure works until a procedure calls itself. A stack works for any depth, because every call pushes and every ret pops, so the return address that comes off is always the one that went on most recently, which is the innermost call still running. Figure 85 draws the mechanism.

Procedure call — use of stack

call pushes onto the stack and ret pops from it:

main:   ...
        ...
     →  [xxx]  call TEST     ─── push ──→   the stack
TEST:   ...
        ...
        ret               ←── pop  ───

The stack is a region of data memory, at the opposite end from the data that memory already holds. The pushed cell is xxx, with SP pointing at it, and each cell is 8 bits wide. A stack frame stacks three things together: xxx / args / results.

The stack pointer is the register that keeps track of the top of the stack. On the AVR it is SPH:SPL, two I/O registers for a 16-bit stack pointer.

Figure 85: What call and ret do with the stack. The stack is a region at the top of data memory, addressed downward: it starts at RAMEND and grows toward lower addresses as things are pushed, so it approaches the program’s variables from above. call TEST pushes the address of the instruction after itself — the return address — and moves the stack pointer down; ret pops that address back into the PC and moves the pointer up. On the AVR each cell is one byte and the PC is wider than a byte, so a return address occupies two cells and SP moves by two. The pointer itself lives in two I/O registers, SPH:SPL, and must be set to RAMEND before the first call, or the first push lands wherever the reset value happens to point.

Why the stack is at the top. Data memory’s SRAM runs from 0x0100 to 0x08FF (memory-models); the program’s variables are allocated from the bottom of that region upward, so the stack is started at the very top, RAMEND, and grows down toward them. The two can grow toward each other for as long as the memory lasts, and neither needs to know in advance how much the other will use.

Figure 86: The stack through a nested call. Five snapshots of the stack region, one per event, for main calling TEST and TEST calling PING. Each call pushes one return address on top of whatever is there; each ret pops the top one, which is always the return address of the call made most recently and not yet returned from. After the inner ret the outer return address is exactly where the outer call left it, so TEST returns to main correctly even though another call happened in between. A single fixed slot would have been overwritten by the second push; this is the property that a per-procedure slot lacks for recursion and a stack has for any depth.

Assembly programs — stack initialisation

Assembly language programs must initialise the stack before using it:

.def temp=r16
    ldi temp,low(RAMEND)
    out SPL, temp
    ldi temp,high(RAMEND)
    out SPH, temp

Four instructions that go at the top of RESET: in every program that will ever call anything. RAMEND is the assembler’s name for the last SRAM address, 0x08FF on the 324A; low() and high() split it into its two bytes because SPL and SPH are two 8-bit I/O registers and there is no 16-bit out. This is the line the Lab 10 template was missing (avr-program-structure) — it did not need one, because nothing in it called a procedure. In C the compiler emits this for you; that is one of the things main costs.

Procedure call — arguments and results

There are two ways to pass arguments to a procedure and to return results from it:

  • use registers
  • or use the stack

Registers are the fast answer for a few small values — put the argument in r24, say, and the procedure reads it from there — and the AVR C compiler does exactly that for the first few arguments of a function. The stack is the general answer: the caller pushes arguments before the call, the procedure finds them just above the return address, and results can go back the same way. That is the stack frame — xxx / args / results stacked together. Conventions for which registers and in what order are in procedures-and-the-stack.

AVR timers/counters

The ATmega324A has three timer/counter blocks on its block diagram: 8-bit T/C 0, 16-bit T/C 1 and 8-bit T/C 2. The diagram also has a fourth, 16-bit T/C 3, but that one is on the larger family members, not the 324A (avr-architecture). On the pinout, six pin functions belong to the timers: OC0A and OC0B on PB3 and PB4, OC1B and OC1A on PD4 and PD5, OC2B and OC2A on PD6 and PD7. These are the output compare pins, one pair per timer, and they are where a timer reaches the outside world; Lecture 16 uses them.

  • A counter is a binary up/down counter clocked on some event.
  • A timer is a counter clocked by a regular clock.

So the hardware is one thing — a counter of the kind built in [counters], now wide and in silicon — and timer versus counter is only a statement about where its clock comes from. Clock it from a pin and it counts events; clock it from the system clock and, since every tick is the same length, its count is elapsed time.

ATmega324A — timer/counter clock sources

The three timer/counters:

Width Clock sources
0 8 bit (0 to 255) STOPPED, CLK, CLK/8, CLK/64, CLK/256, CLK/1024, external pin rising edge, external pin falling edge — CLK = system clock
1 16 bit (0 to 65535) the same list
2 8 bit (0 to 255) STOPPED, CLK, CLK/8, CLK/32, CLK/64, CLK/128, CLK/256, CLK/1024 — CLK = system clock or external oscillator

CLK is 8 MHz, the system clock the lab boards run at. Timer 2 trades the two external-pin inputs for two extra divisors and can run from a separate crystal on the TOSC1/TOSC2 pins, the port-C pins that avr-io-ports noted were broken out separately on the block diagram; that is what makes it the real-time-clock timer.

Clock prescaling

Take four clocks: CLK, CLK/2, CLK/4 and CLK/8. The counter advances on the rising edges, and over the same stretch of time there are four on CLK, two on CLK/2, and one each on /4 and /8. An 8-bit count climbs a staircase from 0 to 255, and an event happens when the count reaches the top. The staircase is steepest for CLK and shallower for each further division. Drawn as a sawtooth, the count has short ramps of period T for CLK, and long ramps spanning eight clock periods for CLK/8.

Figure 87: What a prescaler does to a timer. The counter advances by one on every rising edge of its selected clock; dividing the system clock by \(N\) stretches every count to \(N\) system-clock periods. The staircase under each track is the resulting count against the same time axis: at CLK the timer climbs eight steps in the window shown, at CLK/8 it climbs one. A full sweep from 0 to 255 therefore takes \(256 \cdot N\) system-clock cycles, and the prescaler is the coarse control over how long a timer’s period is, before the compare registers give fine control. At 8 MHz the sweep is 32 µs with no prescaling and about 33 ms at CLK/1024.

The prescaler is a chain of flip-flop dividers ([counters] — a ripple counter’s stages are exactly CLK/2, CLK/4, CLK/8, …), and the timer is handed one tap of it. The staircases are the point: the same 0-to-255 sweep takes eight times as long on CLK/8 as on CLK, and 1024 times as long on CLK/1024. At 8 MHz that is the difference between 32 µs and 33 ms per sweep, which is the range that makes an 8-bit counter useful for both microsecond and human-scale timing.

Clock selection

The clock source for timer/counters 0 and 1 is chosen by a multiplexer with seven inputs: 0 (clock stopped), CLK, CLK/8, CLK/64, CLK/256, CLK/1024, and the external source, which enters twice, once directly and once through an inverter so that either edge can be chosen. Three select lines pick the input; the output is the counter clock source.

Figure 88: The clock selection multiplexer in front of each timer/counter. Eight inputs, three select bits: the CSn2:0 field of the timer’s control register picks one, and a code of 000 selects a constant 0, which is how a timer is stopped without any separate enable. Five of the inputs are taps of the prescaler chain. The external pin Tn enters twice, plain and inverted, so that the counter can advance on whichever edge the application wants; choosing one of those two codes is what turns the timer into an event counter. The select codes are the ones the control register uses for timers 0 and 1; timer 2 has the same shape with the two external inputs replaced by extra prescaler taps.

Choosing an input is one three-bit field in a control register, CS02:0 for timer 0 and CS12:0 for timer 1; the codes are in the figure and in avr-timers-and-counters, and Lab 12 sets them from C. What happens when the timer counts — output compare, the modes, and PWM — is Lecture 16, 2026-09-17-pulse-width-modulation.

See also

Lecture 16 — Pulse Width Modulation

The timer/counters introduced at the end of Lecture 15 (2026-09-14-flow-of-control), now put to their main use: generating a pulse-width-modulated signal on a pin, entirely in hardware, so that a digital output can behave like an adjustable analog one. The first part completes the timer material: what a timer is for, which pins it owns, which registers configure it, and its three modes of operation. The rest is PWM itself and the two Fast PWM modes of timer/counter 0. The evergreen notes are avr-timers-and-counters and pulse-width-modulation.

Timer/counters — the three jobs

The block diagram has three timer/counter blocks that matter, numbered 0, 1 and 2; the T/C 3 block is not used (avr-architecture).

An 8-bit timer counting up from 0 at the 8 MHz system clock with no prescaling takes

\[T = \frac{255}{8 \cdot 10^{6}} = 30\ \mu\text{s}\]

This is rounded down from the 32 µs the arithmetic gives (\(256 / 8\,\text{MHz} = 32\ \mu\text{s}\) for the full 256 counts). It is the shortest period the timer can produce, and every other period comes from lengthening it.

A timer/counter is for three things:

  • Timing, e.g. toggling an LED every 10 ms. The count climbs from 0 to 255 again and again, driven by the 8 MHz clock. A compare value in OCR, say 128, is crossed once per sweep, halfway up. The crossing is a regular event, and a pin can be driven high (1) or toggled on it.
  • Counting an external signal. Each step is an external pulse, not a clock tick. With OCR at 100, the crossing means 100 pulses have arrived.
  • Pulse width modulation (PWM): a pulse train on a pin.

Figure 89: The three jobs of a timer/counter, all built from the same two parts: a count that climbs, and a compare register that marks a value on the way up. Timing: the count is driven by the system clock, so each sweep takes a fixed time and the compare match is a regular event, good for toggling a pin or an LED every so many milliseconds. Counting: the count is driven by edges on an external pin, so the match means a fixed number of events has occurred. PWM: the match is used to switch an output pin partway through every sweep, so the pin carries a pulse whose width is set by the compare value. The hardware does all three without the CPU touching the count.

Timer/counters — separate hardware, configured through I/O registers

A timer/counter:

  • can be used to perform actions with pre-defined timing, e.g. do some action every 100 ms;
  • can be used to generate PWM;
  • can be used to count pulses (logic transitions on a given pin);
  • is separate hardware to the CPU;
  • is tied to particular pins on the microcontroller. Configuring the timer/counter changes these pins from their default GPIO operation to timer/counter operation;
  • is configured by reading and writing I/O registers:
Register Kind
Timer/Counter register data: the current value of the count
Control registers control
Output compare registers control
Interrupt registers interrupt

Every I/O register met so far is one of the same three kinds:

\[\text{I/O reg} \leftarrow \begin{cases} \text{data} & (\texttt{PORT}, \texttt{PIN}, \texttt{TCNT}) \\ \text{control} & (\texttt{DDR}, \texttt{OCR}, \texttt{TCCR}\ldots) \\ \text{interrupt} & (\texttt{TIMSK}, \texttt{TIFR}\ldots) \end{cases}\]

A timer is another peripheral configured through I/O registers, exactly like a port. TCNT is the timer’s PIN, the value you read. TCCR and OCR are its DDR, how it is set up. The interrupt registers are new and are covered in Lecture 17 (2026-09-21-interrupts, avr-interrupts). Separate hardware is the important property: once configured, the timer counts, compares and drives its pin with the CPU doing nothing, which is what makes hardware PWM free.

Timer/counters — the pins

Pins 1–8, at the top left of the pinout, are GPIO port B. Six pins carry the output-compare functions:

Timer Pins
0 PB3 = OC0A, PB4 = OC0B
1 PD5 = OC1A, PD4 = OC1B
2 PD7 = OC2A, PD6 = OC2B

Each timer has two compare units, A and B, each with its own register and its own pin. The two give two independent match events per sweep of one counter. With OCR0A = 200 and OCR0B = 128, timer 0’s count from 0 to 255 crosses both values on every sweep, and each crossing is its own match.

AVR timers/counters summary — ATmega324A

Timer/Counter 0 Timer/Counter 1 Timer/Counter 2
Pins PB3 (OC0A) & PB4 (OC0B) PD5 (OC1A) & PD4 (OC1B) PD7 (OC2A) & PD6 (OC2B)
Width 8-bit (counts to 255) 16-bit 8-bit
Supports PWM ✓ ✓ ✓
Modes of operation Normal, CTC, Fast-PWM, phase correct PWM Normal, CTC, Fast-PWM, PC-PWM and PFC-PWM Normal, CTC, Fast-PWM and phase correct PWM
Clock prescaler (\(PRE\)) No clock, F, F/8, F/64, F/256, F/1024 No clock, F, F/8, F/64, F/256, F/1024 No clock, F, F/8, F/32, F/64, F/128, F/256, F/1024
I/O registers TCNT0 (data); TCCR0A, TCCR0B, OCR0A, OCR0B (control); TIMSK0, TIFR0 (interrupt) TCNT1H, TCNT1L; TCCR1A, TCCR1B, TCCR1C; OCR1AH, OCR1AL, OCR1BH, OCR1BL; TIMSK1, TIFR1 TCNT2; TCCR2A, TCCR2B; OCR2A, OCR2B; TIMSK2, TIFR2

The three modes that matter:

Mode Behaviour
Normal the count climbs from 0 to 255 and wraps to 0. It runs freely; a compare value (say OCR = 128) is just a marker on the way
CTC — clear on compare the count resets when it reaches OCR, so the compare value becomes the top of the count
PWM the output is a pulse train

Timer 1 is 16 bits wide, so every one of its data registers is a pair of bytes with H and L suffixes, and it has a third control register, TCCR1C. Timers 0 and 1 have the same prescaler list. Timer 2’s list adds F/32 and F/128, the two extra taps met in Lecture 15. The register-by-register detail, and Lab 12’s walk through TCCR1A/B/C, are in avr-timers-and-counters and week8-lab-avr-timers.

Pulse width modulation (PWM)

PWM is varying the duty cycle of a periodic pulse. The duty cycle is the percentage of time that the signal is on (high):

\[\text{duty cycle} = \frac{T_{ON}}{T} \cdot 100\%\]

The pulse train switches between 5 V and 0. \(T\) is one full period, in seconds, and \(T_{ON}\) is the high part of it. The frequency is \(f = 1/T\), in Hz. At the same period, a duty cycle of 0 % is flat low, 25 % a narrow pulse, 50 % a square wave, 75 % a wide pulse and 100 % flat high.

Figure 90: One period of a PWM signal and the two numbers that describe it. The period \(T\) is fixed and sets the frequency \(f = 1/T\); the on-time \(T_{ON}\) is the part of each period the output spends high. Their ratio is the duty cycle. The five traces have the same period and differ only in \(T_{ON}\): from 0,% (never high) through a square wave at 50,% to 100,% (never low). Modulating the pulse width means moving \(T_{ON}\) while leaving \(T\) alone, which is exactly what changing a compare register does.

PWM — average value

If the periodic pulse is “fast enough”, the signal looks like its average value. The average rises with the duty cycle: the 75 % waveform has a higher average than the 50 % one, and the 50 % one a higher average than the 25 % one. So PWM can be used to control the average voltage delivered to a load, for example to control the speed of a DC motor.

The average over one period, for a 5 V pulse:

\[V_{avg} = \frac{\int_0^{T} v(t)\,dt}{T} = \frac{\int_0^{T_{ON}} 5\,dt}{T} = \frac{T_{ON}}{T} \cdot 5 \;\propto\; \text{duty cycle}\]

Figure 91: Why a PWM signal has an average, and why it is proportional to the duty cycle. The average of any periodic voltage is the area under one period divided by the period. For a pulse the area is a rectangle, \(5,\text{V} \times T_{ON}\), so dividing by \(T\) leaves \(5,\text{V} \times T_{ON}/T\): the supply voltage scaled by the duty cycle. A load that cannot follow the individual pulses — a motor’s inertia, an LED as seen by the eye, a loudspeaker cone — responds to this average and not to the pulses, which is how a pin that is only ever at 0 V or 5 V delivers 1.25 V.

Fast enough means the load has to be slow compared with the period: a motor’s inertia, a lamp’s thermal mass, the eye’s persistence, or an explicit low-pass filter. If the period is long enough for the load to follow the pulses, it sees pulses. So the PWM frequency is chosen for the load, and then the duty cycle is the only thing varied.

PWM — an average that changes over time

The pulse width can be varied so that the “average value” changes over time. A train of pulses whose widths grow and shrink has an average that follows a sine wave, a sine tone: the pulses are wide at the peak and narrow at the trough. Vary \(T_{ON}\) smoothly from period to period and the average traces out whatever waveform you like; filter off the pulses and that waveform is what comes out. This is how PWM generates audio.

Uses of PWM

PWM is useful for generating signals that look analog from a purely digital source. It can be used for:

  • varying the brightness of lights/LEDs (e.g. fading)
  • motor control (variable speed)
  • generating audio (with appropriate filtering)

The AVR has no digital-to-analog converter; PWM plus the load’s own filtering is how it gets an analog-looking output.

LED brightness fading

Take two pulse trains driving an LED, one with a large duty cycle and one with a small one. Each has its own \(V_{avg}\), and the one with the large duty cycle has the higher \(V_{avg}\). Brightness rises with \(V_{avg}\), so it gives the brighter LED. A wider pulse means a higher average current, and the eye — the low-pass filter in this case — sees a brighter LED. Fading is ramping the duty cycle.

PWM on the AVR: Fast PWM mode (example with Timer/Counter 0)

Fast PWM has two options, chosen by the Waveform Generation Mode bits. The other modes are in Lab 12 (week8-lab-avr-timers), which introduced modes 0 (normal) and 4 (CTC) for timer 1.

The two options are two values of the three WGM bits. In each, the timer value against time is a sawtooth, the compare register is a horizontal line across it, and the pin’s waveform sits underneath:

Mode 3: WGM[2:0] = 011 (0x3) Mode 7: WGM[2:0] = 111 (0x7)
Top of the count 255 — the counter always sweeps 0 to 255 OCR0A — TOP is OCR0A in place of 255; the count sweeps 0 to OCR0A
Compare line OCR0A or OCR0B, the Output Compare Register values. Can have two separate PWMs on one timer OCR0A sets the top, OCR0B sets the pulse
Pin waveform for one compare value, say 100, there are two waveforms: inverting and non-inverting — the same match, the opposite polarity, each with its own pulse width the high part of the waveform is the duty cycle; the period is now the shorter sweep

The count is a sawtooth, the compare register is a horizontal line across it, and the pin changes state where they cross. The crossing moves up and down the ramp as the register value changes, and that moves the edge of the pulse, which is what modulating the width means. Whether the pin goes high or low at the crossing is a separate choice, the COM bits, and gives the inverting and non-inverting pair. Mode 3 fixes the period at 256 counts; mode 7 lets OCR0A shorten it, at the price of one of the two compare units.

Fast PWM mode — WGM[2:0] = 011 (0x3)

The count climbs from 0 to 255, so one period is 256 ticks. One tick lasts

\[T_{tick} = \frac{1}{CLK / PRE}\]

so the period and the frequency are

\[T = \frac{256}{CLK / PRE} \qquad\qquad f = \frac{CLK}{256 \cdot PRE}\]

Take a compare value of 191. The gap between it and 255 is 64 counts, so

\[\text{duty cycle} = \frac{T_{ON}}{T} = \frac{64}{256} \cdot 100\% = \mathbf{25\%}\]

Figure 92: Fast PWM with a fixed top of 255 (mode 3, WGM[2:0] = 011) on an 8-bit timer. The count climbs one step per prescaled clock tick from 0 to 255 and wraps, so every period is exactly 256 ticks and the frequency is \(CLK/(256 \cdot PRE)\) regardless of the compare value. The compare register draws a line across the ramp; the pin switches at the crossing and switches back at the wrap. In inverting mode the pin goes high at the match and low at the wrap, so it is high for \(255 - OCR\) ticks; with \(OCR = 191\) that is 64 ticks of 256, a 25,% duty cycle. Non-inverting mode is the same crossing with the polarity swapped: high for \(OCR + 1\) ticks, 75,% here. The two outputs always add up to a full period, so the two modes are one signal and its complement.

Reading the formulas. The prescaler sets the tick, the fixed 256-count sweep sets the period, and only the compare value moves the edge. So in mode 3 frequency and duty cycle are set by different registers and do not interact, which is convenient. The cost is that the frequency can only take the eight values \(CLK/(256 \cdot PRE)\) allows: at 8 MHz, from 31.25 kHz down to 30.5 Hz. If none of those is right, mode 7.

Fast PWM mode — WGM[2:0] = 111 (0x7)

The count now climbs from 0 to OCR0A, which is 1 + OCR0A ticks. TOP is OCR0A, not 255. Take OCR0A = 127 and OCR0B = 95, a gap of 32 counts.

\[T_{tick} = \frac{1}{CLK / PRE} \qquad\qquad T = \frac{1 + OCR0A}{CLK / PRE} \qquad\qquad f = \frac{CLK}{(1 + OCR0A) \cdot PRE}\]

\[\text{duty cycle} = \frac{32}{128} \cdot 100\% = \mathbf{25\%}\]

Figure 93: Fast PWM with OCR0A as the top (mode 7, WGM[2:0] = 111). The count now wraps when it reaches OCR0A instead of 255, so the period is \(OCR0A + 1\) ticks and can be chosen freely instead of being fixed at 256; the frequency becomes \(CLK/((OCR0A+1)\cdot PRE)\). The pulse is generated on the other compare unit: OCR0B draws the line across the shorter ramp and the OC0B pin switches at that crossing. With \(OCR0A = 127\) and \(OCR0B = 95\) the period is 128 ticks and the inverting output is high for \(127 - 95 = 32\) of them, again 25,%. Compare unit A is spent on setting the period, so mode 7 buys frequency control by giving up one of the two PWM outputs; OC0A can at most toggle at each wrap.

The trade. Mode 3 gives two PWM outputs at a fixed frequency; mode 7 gives one PWM output at a chosen frequency. The general formula behind both, \(f = CLK / (PRE \cdot (TOP + 1))\), is the master formula Lab 12 works from, with \(TOP\) = 255 or \(OCR0A\) as the mode dictates (avr-timers-and-counters).

Phase correct PWM

  • The centres of the pulses remain at the same point in the period. At 25 %, 50 % and 75 % the centres line up.
  • It is better for motor speed control.
  • It is implemented by having the timer count up and then down.
  • It is not used in this course, which uses fast PWM mode only.

Figure 94: Fast PWM against phase-correct PWM, for the same three duty cycles. In fast PWM the count is a sawtooth and every pulse starts at the wrap, so its leading edge is fixed and widening the pulse moves only the trailing edge: the pulse’s centre drifts as the duty cycle changes. In phase-correct PWM the count climbs and then descends, and the pin switches on the way up and back on the way down at the same compare value, so the pulse is symmetric about the peak of the triangle: its centre stays put and both edges move outward together. For a motor that is smoother, because the current pulse’s timing relative to the period does not shift as the speed is changed; the price is that the triangle takes twice as long, halving the frequency. This course uses fast PWM only.

Counting up and then down is the whole mechanism: the compare line is crossed twice per triangle, once rising and once falling, and the two crossings are equidistant from the peak. Nothing in the labs or the assignment needs it; fast PWM is the mode the course uses, and it is the one Lab 12’s master formula and the WGM tables describe.

See also

Lab 11 — AVR C Programming

Learning Lab 11, the first lab in C. The seven-segment program from 2026-09-10-more-c-programming-on-the-avr is typed in, wired up and extended to hex digits and to a two-input adder. It also covers the bit-shift and bit-mask idioms that every AVR C program from here on is written in. See seven-segment-display for the display and its lookup table, bit-masking for the four masking operations, and c-operators for <<, |, & and ^.

What this lab covers

  • Microchip Studio C programming
  • AVR C programming exercises

Ed Lessons

The Ed discussion board also provides Ed Lessons, designed to instruct you in the basics of C. The content should be no more complex than CSSE1001 content. C programming for the AVR starts in week eight, with this lab.

The lessons are released in stages:

Date Lesson
14 Aug Basics
28 Aug Next Steps #1
11 Sep Next Steps #2
25 Sep Extension Tasks
16 Oct Floating Point Workshop

The first three were out before this lab.

Worked: (23>>2)<<3

What is printed by this line of code: printf("%d", (23>>2)<<3);

40.

Work it in binary, because the two shifts do not cancel:

Step Binary Decimal
23 1 0 1 1 1 23
23 >> 2 1 0 1 5 — the two low bits 11 fall off the end
5 << 3 1 0 1 0 0 0 40

>> 2 is division by 4 with the remainder thrown away — \(\lfloor 23/4 \rfloor = 5\) — and << 3 is multiplication by 8, so the result is \(8 \cdot 5 = 40\), not \(23 \cdot 2 = 46\). The bits shifted out on the right are gone; shifting back left fills with zeros (c-operators). It is the same loss of information a lsr has in assembly, where the dropped bit lands in C and the next lsl shifts in a 0 (avr-instructions).

Bit shifts and AVR code

It is common to use bit-shifts to indicate which bits are being operated on.

Example: set bit 5 of port B to be an output and other bits to be inputs.

Assembly language C equivalent
ldi r16, (1<<5) out DDRB, r16 DDRB = (1<<5);

1<<5 makes it clear bit 5 is being set. Both are the constant 0b00100000 = 0x20; the assembler evaluates (1<<5) at assembly time exactly as the C compiler does, so neither line costs anything at run time. The point is legibility: 0x20 has to be decoded, 1<<5 says bit 5 in the source. The AVR header files name every register bit this way, which is why (1<<CS11) turns up in week8-lab-avr-timers.

Setting bits and keeping the rest

Example: set bits 3 and 4 of port B to be outputs whilst keeping the direction of the other bits the same.

Assembly language:

    in   r16, DDRB
    ori  r16, (1<<4)|(1<<3)
    out  DDRB, r16

C equivalent:

DDRB |= (1<<4)|(1<<3);

This is shorthand for DDRB = DDRB | ((1<<4)|(1<<3)); (c-operators). Read the three assembly lines against it: in is the read of DDRB on the right-hand side, ori is the |, out is the assignment back. A read-modify-write is three instructions in assembly and one operator in C, and it is the difference between this example and the previous one: DDRB = (1<<5) replaces the register, forcing the other seven bits to 0, whereas |= adds the two bits to whatever was there. The mask (1<<4)|(1<<3) is 0b00011000 = 0x18.

Bit masking operations — more than just bitwise ANDs

The four operations of bit-masking, now in C:

Operator Does Example
Bitwise AND & Clear particular bits (e.g. zero out high 4 bits) var = PINB & 0x0F;
Test particular bits (e.g. is bit 1 set?) if(PINB & 0x02) …
Bitwise OR \| Set particular bits (e.g. set sign bit to 1) PORTC = PINB \| 0x80;
Bitwise XOR ^ Invert particular bits (e.g. invert low 4 bits) PORTC = PINB ^ 0x0F;

The rule for building a mask is the same in every row: put a 1 on the bits the operation should touch — keep, for AND; set, for OR; flip, for XOR — and a 0 everywhere else. 0x0F appears twice with two meanings: with & it keeps the low nibble, with ^ it inverts it.

The test row is the one that is new. PINB & 0x02 is 0x02 if bit 1 is set and 0x00 if not, and since C treats any non-zero value as true (c-control-flow) that expression can sit directly inside an if. It does not need to be compared with 1 — and must not be, because it never is 1.

Seven segment display

  • LEDs arranged in a pattern
  • Eight segments if DP (decimal point) is included
  • One byte drives it, e.g. 0001 1110₂ with the “A” segment as LSB and the “DP” segment as MSB

The segments are lettered A across the top, B upper right, C lower right, D bottom, E lower left, F upper left, G across the middle, and DP the dot — the same lettering as seven-segment-display, just in capitals. With A at bit 0 and DP at bit 7 the byte reads, MSB first, DP G F E D C B A, so 0001 1110 lights E, D, C and B: the right-hand side, the bottom and the lower left — a shape like a J.

Worked: what 0011 1110₂ then 1111 0100₂ spell out (“A” = LSB)

“Uh.”

Byte DP G F E D C B A Lit Shows
0011 1110 0 0 1 1 1 1 1 0 F E D C B U
1111 0100 1 1 1 1 0 1 0 0 DP G F E C h with the dot: h.

In the second byte, F, E and G make the left-hand upright and the middle bar; C adds the lower right; no A, so the top is open and the shape is a lowercase h rather than an H. Bit 7 lights the decimal point after it. Task 2 turns this reading-off into writing the six hex letters.

Tasks

NoteProvided task

Task 1 — Seven Segment Display

  1. Create an AVR C project and type in and build the seven-segment display (SSD) example from lecture 14. The code is also on Blackboard.
  2. Connect up AVR pins to the IO board pins:
    • Connect IO board SSD inputs (A to G and DP) to port A (you can use 2 × 4-way cables and headers for this. SSD pin A should be connected to the least significant bit of port A.)
    • Connect IO board pin CC (SSD digit select input) to button B0
    • Connect IO board switches 0 to 3 to the lower four pins of port C
  3. Download your program to the board and test it — check that the number you enter on switches 0 to 3 shows up as a digit on the seven-segment display. Press and release button B0 and check that the number shows up on the other SSD digit.

Task 2 — Adding Hex Patterns

  1. Modify the task 1 code so that your program can also output values 10 to 15 as hex digits as shown in the following patterns: A b C d E F.
  2. Build, download and test your program.

Task 3 — Addition Results on SSD

  1. Write a program that repeatedly reads the lower 4 bits of port A and the lower 4 bits of port B and adds these two values together and displays (on the SSD, using a port of your choice) the hexadecimal value of the lower 4 bits of the result.
  2. Wire up the IO board and AVR 324 Dev board as required.
  3. Build, download and test your program.

Task 4 — Bitmasking

  • Download lab11-task4.c from Blackboard
  • Read through the comments at the start of the code
  • Run the code as-is and observe the issues
  • Fix the code by bitmasking where required
  • Interrupts will be explained in Lec 17 then Lab 14

Working — Task 1

The project. In Microchip Studio a C project is a GCC C Executable Project for the ATmega324A, the same device selection as the assembly projects of week5-lab-avr-assembly-one; the file it gives you is main.c. The program is the one from Lecture 14, unchanged:

#include <avr/io.h>

/* Seven segment display values */
uint8_t seven_seg[10] = { 63,6,91,79,102,109,125,7,127,111};

int main(void) {
  uint8_t digit;

  /* Set port A pins to be outputs, port C pins to be inputs */
  DDRA = 0xFF;
  DDRC = 0;    /* This is the default, could omit. */
  while(1) {
    /* Read in a digit from lower half of port C pins */
    /* We read the whole byte and mask out upper bits */
    digit = PINC & 0x0F;
    /* Write out seven segment display value to port A */
    if(digit < 10) {
      PORTA = seven_seg[digit];
    } else {
      PORTA = 0;
    }
  }
}

Every line is explained in 2026-09-10-more-c-programming-on-the-avr. The new part is the wiring, and the wiring has one rule that the code silently depends on: SSD pin A goes to PA0. The lookup table was built with segment a at bit 0 and dp at bit 7, so the cable must carry that order across — A on PA0 up through G on PA6 and DP on PA7. Get the two 4-way cables swapped and every digit comes out scrambled.

Figure 95: The three connections Task 1 asks for, and what each one means for the program. Port A carries the eight segment lines in the same order as the bits of the lookup table, so PORTA = seven_seg[digit] lights a digit with no further translation. The low four bits of port C read the switches, and & 0x0F discards the four unconnected pins above them. The CC line is not driven by the AVR at all: it is jumpered to button B0 on the board, so the button alone decides which of the two digits shows the pattern — which is why pressing it moves the number across without the program doing anything.

Testing (c). Set a number on switches 0–3 and the matching digit should appear. The interesting test is the button: CC is wired to B0, not to the AVR, so pressing it changes the common-cathode select in hardware and the same pattern appears on the other digit — the program has not changed, only which digit’s cathode is connected (seven-segment-display). Switch values 10–15 blank the display, which is the else branch doing its job; Task 2 is about making them show something instead.

Working — Task 2

Six more entries and the display can show every value four bits can hold. The patterns are A b C d E F, and the case is not cosmetic. An uppercase B on seven segments is indistinguishable from 8, and an uppercase D from 0, so those two are drawn lowercase; the other four have no such clash and stay capitals.

Digit Segments lit dp g f e d c b a Decimal
A a b c e f g 0111 0111 119
b c d e f g 0111 1100 124
C a d e f 0011 1001 57
d b c d e g 0101 1110 94
E a d e f g 0111 1001 121
F a e f g 0111 0001 113

Figure 96: The six hex letters as seven-segment patterns, with the byte that produces each one in decimal underneath, ready to append to the lookup table. Heavy segments are lit; the bit order is dp g f e d c b a with a at bit 0, as for the ten decimal digits. The letters b and d are the lowercase forms because their capitals would be indistinguishable from 8 and 0 on this display: b is 8 without segments a and b, d is 0 with the top-left corner (a, f) removed and the middle bar g added.

The change to the program is two lines: the table grows to sixteen entries, and the guard is no longer needed because four input bits cannot index past it.

#include <avr/io.h>

/* Seven segment display values: 0-9 then A b C d E F */
uint8_t seven_seg[16] = { 63,6,91,79,102,109,125,7,127,111,
                          119,124,57,94,121,113 };

int main(void) {
  uint8_t digit;

  DDRA = 0xFF;                 /* segments out on port A */
  DDRC = 0;                    /* switches in on port C */
  while(1) {
    digit = PINC & 0x0F;       /* 0 to 15 - every value is now a valid index */
    PORTA = seven_seg[digit];
  }
}

Dropping the if is safe only because of the mask on the line above it: PINC & 0x0F is at most 15 and seven_seg[15] exists. Leaving the guard in as if(digit < 16) costs nothing and documents the assumption; taking the mask out would be the bug (c-pointers-and-arrays — C will not stop an index at 16).

Working — Task 3

Two 4-bit inputs, one 4-bit output. The task fixes the inputs — low nibble of port A, low nibble of port B — and leaves the output port to you; port C is used here, the port Task 1 used for input, with the SSD moved across to it. Port D would do equally well.

#include <avr/io.h>

/* 0-9 then A b C d E F, as in Task 2 */
uint8_t seven_seg[16] = { 63,6,91,79,102,109,125,7,127,111,
                          119,124,57,94,121,113 };

int main(void) {
  uint8_t a, b, sum;

  DDRA = 0;                    /* switches 0-3 on PA0-PA3 */
  DDRB = 0;                    /* switches 4-7 on PB0-PB3 */
  DDRC = 0xFF;                 /* SSD segments on port C  */
  while(1) {
    a = PINA & 0x0F;           /* extract the low nibble of each port */
    b = PINB & 0x0F;
    sum = (a + b) & 0x0F;      /* add, then keep the low 4 bits of the result */
    PORTC = seven_seg[sum];    /* show it as a hex digit */
  }
}

Three things the wording of the task decides:

  • Both masks are needed, not just one. The upper four pins of each port are unconnected and read as unpredictable values, so without the & 0x0F the sum would include junk (week6-lab-avr-io-ports hit the same thing with andi).
  • The result is masked too. The largest sum is \(15 + 15 = 30\), which fits comfortably in a uint8_t, so nothing overflows in C; but the task asks for the lower 4 bits of the result, so bit 4 — the carry out of the nibble — is discarded. $9 + 9 = 18 = $ 0x12 shows as 2, and $8 + 8 = 16 = $ 0x10 shows as 0. That is the answer, not a bug: it is the four-bit adder of 2026-08-04-binary-arithmetic with its carry-out unconnected.
  • The hex table from Task 2 is what makes it display. Sums of 10 to 15 are common (7 + 5, say), and they must show as hex letters, which is why the task follows Task 2 rather than preceding it.

Figure 97: The Task 3 wiring. Two nibbles of switches come in on the low halves of ports A and B, the SSD segment lines go out on port C, and the direction registers follow: 0 for the two input ports, 0xFF for the output port. The upper four pins of ports A and B are left unconnected, which is what makes the & 0x0F on each read necessary rather than decorative. CC can be left tied to a button as in Task 1; the program only ever drives one digit.

Testing. With all eight switches down the display shows 0; raise switch 0 alone and it shows 1, switch 4 alone and it also shows 1 (that is the other operand); switches 0 and 4 together show 2. Setting both nibbles to 1111 shows E: $15 + 15 = 30 = $ 0x1E, low nibble E.

Working — Task 4

lab11-task4.c is a Blackboard download. The exercise is a program that runs but misbehaves, where every fault is a whole-port write or read that should have been a masked one. The toolkit for fixing it is the bit-masking table above, applied at the points where a program touches only some of a port’s pins:

Symptom Likely line Fix
Setting one pin’s direction disturbs the others DDRx = (1<<n); DDRx \|= (1<<n);
Writing one output changes neighbouring outputs PORTx = value; PORTx = (PORTx & ~mask) \| (value & mask); — or \|= / &= for a single bit
An input test is never true if(PINx & (1<<n) == 1) if(PINx & (1<<n)) — the result is 1<<n, not 1
Unconnected pins leak into a value var = PINx; var = PINx & 0x0F;

The third row is the test case from the bit-masking table: PINB & 0x02 is either 0x02 or 0, and comparing it to 1 is always false.

Interrupts are explained in Lecture 17, then Lab 14. The downloaded file presumably contains an interrupt handler, which is to be left alone for now; only the masking is to be fixed. Lecture 17 is 2026-09-21-interrupts, and what an ISR(...) function is and how it gets called is in avr-interrupts.

See also

Lab 12 — AVR Timers

Learning Lab 12, where a timer/counter is configured for the first time: which I/O registers are involved, how the control bits are laid out, the one formula that turns a wanted frequency into register values, and two programs — a hardware-toggled LED and a two-digit multiplexed display driven by a pulse counter. The timers themselves are in avr-timers-and-counters; the lectures this lab builds on are 2026-09-14-flow-of-control (Lecture 15, the introduction) and 2026-09-17-pulse-width-modulation (Lecture 16).

Outline

  • AVR timers
    • the I/O registers involved
    • how to set up a timer
  • Exercises

ATmega324A — timer/counter summary

The ATmega324A has three timer/counters, separate hardware from the CPU. The datasheet block diagram names them 8bit T/C 0, 16bit T/C 1 and 8bit T/C 2. Between them they have six output-compare pins on the 40-pin package: OC0A/OC0B on PB3/PB4, OC1A/OC1B on PD5/PD4, OC2A/OC2B on PD7/PD6 (avr-architecture).

Timer/Counter 0 Timer/Counter 1 Timer/Counter 2
Pins PB3 (OC0A) & PB4 (OC0B) PD5 (OC1A) & PD4 (OC1B) PD7 (OC2A) & PD6 (OC2B)
Width 8-bit timer/counter 16-bit timer/counter 8-bit timer/counter
PWM Supports PWM Supports PWM Supports PWM
Modes of operation Normal, CTC, Fast-PWM and phase correct PWM Normal, CTC, Fast-PWM, PC-PWM and PFC-PWM Normal, CTC, Fast-PWM and phase correct PWM
Clock prescalar No clock, F, F/8, F/64, F/256, F/1024 No clock, F, F/8, F/64, F/256, F/1024 No clock, F, F/8, F/32, F/64, F/128, F/256, F/1024
I/O registers TCNT0; TCCR0A, TCCR0B; OCR0A, OCR0B; TIMSK0, TIFR0 TCNT1H, TCNT1L; TCCR1A, TCCR1B, TCCR1C; OCR1AH, OCR1AL, OCR1BH, OCR1BL; TIMSK1, TIFR1 TCNT2; TCCR2A, TCCR2B; OCR2A, OCR2B; TIMSK2, TIFR2

Read the three columns as one design in three sizes. Every unit has the same four kinds of register — a count (TCNTn), control (TCCRnA/B), output compare (OCRnA/B) and interrupt (TIMSKn, TIFRn) — and two output-compare pins. Timer 1 is the odd one out only in width: 16 bits means every data register comes as a high/low pair and there is a third control register. Timer 2 has two extra prescaler taps. The lab works timer 1 in Task 1 and timer 0 in Task 2.

Timer/counter clock sources

There are 3 timer/counters:

  • 0: 8 bit (0 to 255)
  • 1: 16 bit (0 to 65535)
    • Clock sources: STOPPED, CLK, CLK/8, CLK/64, CLK/256, CLK/1024, external pin rising edge, external pin falling edge. CLK = system clock.
  • 2: 8 bit (0 to 255)
    • Clock sources: STOPPED, CLK, CLK/8, CLK/32, CLK/64, CLK/128, CLK/256, CLK/1024. CLK = system clock or external oscillator.

“External pin” for timers 0 and 1 is the T0/T1 pin (the clock-selection section below says which pin), and it is what makes those two counters as well as timers: fed from a button instead of the system clock, TCNT0 counts presses. Timer 2 has no external-pin option; its alternative is a crystal on TOSC1/TOSC2.

Timer/counter registers — TCNT, count values

Register Memory address I/O register
TCNT0 0x46 0x26
TCNT1 (16 bits) — TCNT1L 0x84 —
TCNT1H 0x85 —
TCNT2 0xB2 —

Only TCNT0 has an I/O-register number, and so only TCNT0 is reachable with in/out (avr-io-ports — I/O numbers stop at 0x3F). The others sit in the extended I/O region and need lds/sts in assembly; in C the distinction disappears, because the header defines every one of them as a memory address (c-preprocessor-and-avr-headers) and TCNT1 = 0; is legal whichever region it lives in.

Output compare registers

Each timer/counter has output compare registers (these are I/O registers). They are for matching timer/counter values. Actions can be taken when the value is reached, e.g.

  • set the output-compare match bit in a register
  • clear the timer (reset to 0)
  • toggle / set / clear an external pin
Timer Registers
Timer 0 (8 bit) OCR0A, OCR0B
Timer 1 (16 bit) OCR1AH, OCR1AL (in C, access as 16-bit “variable” OCR1A); OCR1BH, OCR1BL (in C: OCR1B)
Timer 2 (8 bit) OCR2A, OCR2B

The three actions are three separate things the hardware can do at the instant TCNTn equals OCRnA (or OCRnB), and they are enabled independently: the flag bit is always set; clearing the timer happens only in CTC mode (the WGM bits); the pin action is chosen by the COM bits. Task 1 uses all three at once — CTC to set the period, the pin toggle to make the LED blink, and nothing reads the flag; Task 2 uses the flag alone as a 1 ms tick.

Accessing 16-bit I/O registers

Example: set output compare register 1B (16 bits) to 4321.

In assembly language:

    ldi  r16, high(4321)
    sts  OCR1BH, r16
    ldi  r16, low(4321)
    sts  OCR1BL, r16

The processor requires the high byte to be written first.

In C:

OCR1B = 4321;

The order is not a style rule. The 16-bit timer registers share one hidden temporary byte: a write to the high byte goes into the temporary register, and a write to the low byte transfers both bytes into the real register in one go, so that the hardware never sees a half-updated value. High first, low second, is what makes that work — and the compiler knows it, which is why the C line is one assignment. sts rather than out because OCR1BH/OCR1BL are beyond the 64 I/O registers (avr-io-ports). Reading goes the other way, low byte first, for the same reason.

Setting up a 16-bit timer

A 16-bit timer has 3 control registers. For timer/counter 1 (n = 1) the “n” in each bit name is replaced by 1, e.g. COM1A1, COM1A0, COM1B1, COM1B0.

Figure 98: The three control registers of timer/counter 1 in the datasheet’s three-row form: bit numbers above, bit names in the boxes, access and reset value below. Grey boxes are reserved and read as 0. The bits that matter group into four fields, and one of them — the waveform generation mode — is split across two registers, WGM11:10 at the bottom of TCCR1A and WGM13:12 in the middle of TCCR1B, so a four-bit mode number has to be written in two halves. Everything a normal program sets lives in TCCR1A and TCCR1B; TCCR1C is left at 0.

The pattern to notice is that the register letter and the pin letter are different things. COM1A1 and COM1A0 are the two bits for pin OC1A; COM1B1 and COM1B0 are for OC1B; and both pairs live in TCCR1A.

The different “A”s

Names with an “A” in them:

COMnA OCnA TCCRnA
OCRnA OCIEnA PINA
PORTA
DDRA

These fall into three groups. The items in each group are related, but each group is independent of the others: the “A”s are different “A”s.

  • Channel A of a timer — COMnA (its output-compare action bits), OCRnA (its compare register), OCnA (its pin), OCIEnA (its interrupt enable). These four do go together: one compare channel, one letter.
  • Control register A — TCCRnA is simply the first of the timer’s control registers. It holds channel B’s COM bits as well as channel A’s, so the A here is not the channel.
  • Port A — PINA, PORTA, DDRA are a GPIO port and have nothing to do with timers at all.

There are 2 hard problems in computer science: cache invalidation, naming things, and off-by-1 errors. The off-by-one matters here: it is the + 1 in the master formula below, and Task 0 turns on it.

WGM — waveform generation modes

WGM11, WGM10 are bits 1 and 0 of TCCR1A; WGM13, WGM12 are bits 4 and 3 of TCCR1B (Figure 98).

Table 16-5 on page 138 of the datasheet describes the modes. Two are of interest:

  • 0: 0000 — normal. The count goes 0 → 1 → … → 65535 → 0 → …
  • 4: 0100 — CTC, Clear Timer on Compare match. The counter resets to 0 when it reaches the value in the OCR1A register.

Mode 4 is the one that makes a timer programmable. In normal mode the period is fixed by the width — 65 536 counts, whatever the prescaler — and the only way to get a different period is to reload TCNT1 by hand. In CTC the period is OCR1A + 1 counts, chosen by the program, and the reset is done by the hardware. The fast PWM modes of Lecture 16 are the other members of this table (pulse-width-modulation).

The master formula

\[f_{\text{event}} = \frac{f_{\text{clk\_I/O}}}{N \cdot (\text{TOP} + 1)}\]

  • \(f_{\text{clk\_I/O}}\) is the clock frequency of the device — 8 MHz for the ATmega324A.
  • \(N\) is the prescaler.
  • TOP is the maximum value that the timer will reach. This can be some fixed constant, or a value in an output compare register.
  • \(f_{\text{event}}\) is the frequency of the event in question.

What event means, case by case:

  • For hardware pin toggling, \(f_{\text{event}}\) is the frequency that the pin is toggled. The waveform consists of one falling edge and one rising edge. The frequency of that waveform is thus half of \(f_{\text{event}}\).
  • For PWM (more on that in a later lab), \(f_{\text{event}}\) is the frequency of falling edges in non-inverting mode, and the frequency of rising edges in inverting mode.
  • For interrupts (more on that in a later lab), \(f_{\text{event}}\) is the frequency that the interrupt runs.

Why the formula has the shape it does: the counter ticks at \(f_{\text{clk}} / N\) and each period is \(\text{TOP} + 1\) ticks long — from 0 up to TOP inclusive — so a period lasts \(N (\text{TOP}+1) / f_{\text{clk}}\) seconds and the event happens once per period. The \(+1\) is the off-by-one: TOP is the last value counted, not the number of values.

Worked: what is the frequency of this wave?

A sine wave is plotted on an axis marked 0 at the left and 1 at the right, and it completes three full cycles between the two marks. What is its frequency?

3 Hz. Three cycles per unit of time is 3 Hz, taking the unlabelled 0 and 1 as seconds. 6 Hz is wrong: it counts the half-cycles — each hump — which is the pin-toggling trap again: six edges per second is three cycles per second. 8 MHz is the AVR’s clock, not this wave.

Clock selection

CS12, CS11, CS10 are bits 2–0 of TCCR1B. From Table 16-6 on page 139 of the datasheet (here n = 1):

CSn2 CSn1 CSn0 Description
0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clk\(_{\text{I/O}}\)/1 (No prescaling)
0 1 0 clk\(_{\text{I/O}}\)/8 (From prescaler)
0 1 1 clk\(_{\text{I/O}}\)/64 (From prescaler)
1 0 0 clk\(_{\text{I/O}}\)/256 (From prescaler)
1 0 1 clk\(_{\text{I/O}}\)/1024 (From prescaler)
1 1 0 External clock source on Tn pin. Clock on falling edge
1 1 1 External clock source on Tn pin. Clock on rising edge

The T1 pin is port B, pin 1 (PB1, package pin 2, PCINT9/CLKO/T1; see p11 of the datasheet). The table is the clock-selection mux from Lecture 15: three bits pick one of eight inputs, and 000 is the stopped input, which is why writing zero to the CS bits is how a timer is switched off — and why a timer whose CS bits have not been set does nothing at all.

Clock selection — code example

Row 0 1 1 of the table — clk\(_{\text{I/O}}\)/64 (from prescaler) — is:

TCCR1B = (1<<CS11) | (1<<CS10);

Bit labels can be used in code expressions. CS11 and CS10 are defined in the header as the bit numbers 1 and 0 (c-preprocessor-and-avr-headers), so (1<<CS11)|(1<<CS10) is 0b011 = 0x03, and the assignment also writes 0 to every other bit of TCCR1B — normal mode, no input capture. That is fine for this line but it is the reason Task 1 has to put its WGM bit in the same expression: a second TCCR1B = (1<<WGM12); would wipe the clock select out again (bit-masking).

Output compare actions — can toggle/clear/set pin

COM1A1, COM1A0, COM1B1, COM1B0 are bits 7–4 of TCCR1A. From Table 16-2 on page 136 of the datasheet (n = 1):

COMnA1/COMnB1 COMnA0/COMnB0 Description
0 0 Normal port operation, OCnA/OCnB disconnected
0 1 Toggle OCnA/OCnB on Compare Match
1 0 Clear OCnA/OCnB on Compare Match (Set output to low level)
1 1 Set OCnA/OCnB on Compare Match (Set output to high level)

The OC1A pin, for example, is PD5, package pin 19 (see p11 of the datasheet). Two things follow. Any non-zero COM value takes the pin away from the port — PORTD bit 5 no longer drives it, the timer does — so the pin changes from GPIO to timer/counter operation. And the pin still has to be made an output with DDRD, because the timer only decides the value, not the direction.

Tasks

NoteProvided task

Task 0

To toggle an output compare pin 8 times per second (4 Hz period) with timer/counter 1, what

  • clock prescale
  • output compare

values do we need?

Task 1 — Output Compare Based Timer

  • Consider lab12-1.c (on Blackboard).
  • The code is to toggle the OC1A pin (what pin is this?) 8 times per second (i.e. 4 Hz period).
    • This pin is connected to an LED (e.g. LD0).
  • Fill in the blanks to make the code work.
    • Set up the hardware to do the work; software does nothing after that.
  • Build and test your code on the AVR board.
  • Look at the generated list (lss) file for the assembly language equivalent.

Task 2 — Count push button presses & display count on SSD with display multiplexing

  • Consider lab12-2.c (on Blackboard).
  • The 7 segment display is connected to port A, with CC (digit select) connected to port D, pin 0.
  • The push button is connected to pin T0 (work out which pin this is).
    • Count the number of rising edges on this pin.
      • Use timer/counter 0.
  • Display the tens place on the left digit for 1 ms, then the ones place on the right digit for 1 ms.
    • This is display multiplexing.
      • Alternate fast enough and it will appear that both digits are on (though brightness will be reduced).
  • Fill in the blanks in the code, build and test.
  • Slow down the multiplexing rate so you can see the digits changing (e.g. 4 times per second).

Working — Task 0

“Toggle 8 times per second” is the event rate: \(f_{\text{event}} = 8\ \text{Hz}\). Each toggle is one edge, so the LED waveform has 4 rising edges a second — the task’s “4 Hz period” — and the pin-toggling rule (waveform frequency is half of \(f_{\text{event}}\)) is what reconciles the two numbers.

Put \(f_{\text{clk}} = 8\,\text{MHz}\) and \(f_{\text{event}} = 8\,\text{Hz}\) into the master formula and solve for the product:

\[N \cdot (\text{TOP} + 1) = \frac{8\,000\,000}{8} = 1\,000\,000\]

Then try each prescaler timer 1 offers:

\(N\) \(\text{TOP} + 1 = 10^6 / N\) TOP Usable?
1 1 000 000 999 999 no — timer 1 stops at 65 535
8 125 000 124 999 no — too big for 16 bits
64 15 625 15 624 yes — exact
256 3 906.25 — no — not a whole number
1024 976.5625 — no — not a whole number

So prescaler 64 (CS12:0 = 011) and OCR1A = 15624 in CTC mode, where TOP is OCR1A. It is the only combination that is both exact and fits, which is typical: the prescaler is chosen to bring TOP under 65 536, and then TOP is whatever the division leaves. The 256 and 1024 rows could be used at the cost of a fractional error (OCR1A = 3905 gives 8.00195 Hz), but the task wants the exact one.

Figure 99: Clear-timer-on-compare mode with the output-compare pin set to toggle. The count climbs from 0 at the prescaled clock rate, reaches OCR1A (the TOP value), and is cleared to 0 by the hardware on the same tick that OC1A flips. One compare match is one event, so the events come at \(f_{\text{clk}} / (N(\text{TOP}+1))\) — but the pin only completes a full high-then-low cycle every two events, which is why the waveform on the LED runs at half the event frequency. With \(N = 64\) and \(\text{TOP} = 15624\) the matches are 125 ms apart and the LED cycle is 250 ms.

Working — Task 1

lab12-1.c is a Blackboard download with blanks to fill in. The task fixes what the blanks must produce, and the whole configuration is four register writes plus one direction bit, so the program is given in full here and can be matched against the download line by line.

What pin is OC1A? PD5 — package pin 19, PCINT29/OC1A. It has to be wired to an LED (LD0 on the IO board) and made an output.

#include <avr/io.h>

int main(void) {
  /* OC1A is PD5 - the timer decides its value, but it must be an output */
  DDRD |= (1<<5);

  /* Start counting from 0, and set the period: TOP = 15624 with N = 64
     gives 8 MHz / (64 * 15625) = 8 compare matches per second */
  TCNT1 = 0;
  OCR1A = 15624;

  /* Toggle OC1A on compare match: COM1A1:0 = 01.  WGM11:10 = 00. */
  TCCR1A = (1<<COM1A0);

  /* CTC mode: WGM13:12 = 01 (mode 4 = 0100).  Prescaler 64: CS12:0 = 011.
     This write starts the timer, so it comes last. */
  TCCR1B = (1<<WGM12) | (1<<CS11) | (1<<CS10);

  while(1) {
    /* Nothing.  The hardware toggles the pin; the CPU is idle. */
  }
}

Points where a blank is easy to get wrong:

  • Mode 4 is 0100, split across the registers: WGM12 is the only 1, and it is in TCCR1B (Figure 98). WGM11/WGM10 in TCCR1A stay 0.
  • Toggle is COM1A0 alone (01), in TCCR1A. Setting COM1A1 instead gives clear on match (10), and the pin goes low once and stays there.
  • The clock-select bits and the WGM bit go in one assignment. Two separate TCCR1B = … lines would each erase the other’s bits; |= on both would also work.
  • OCR1A = 15624, not 15625. TOP is the last value counted; the period is TOP + 1 ticks.
  • Order: OCR1A before the clock is started, so the first period is the right length; TCNT1 = 0 is what reset leaves anyway, but writing it makes the intent visible.

Software does nothing after that — the while(1) body is empty and the LED blinks regardless. That is the point of the exercise: the timer is separate hardware, and a program that has set it up can go on to do anything else, or nothing.

The .lss file is the compiler’s listing, C source interleaved with the assembly it became. The five register writes appear as ldi/out for DDRD and TCCR1A… and ldi/sts pairs for OCR1A and TCNT1, high byte then low byte, exactly as under Accessing 16-bit I/O registers above; the empty loop is a single rjmp to itself (avr-program-structure).

Working — Task 2

lab12-2.c is also a Blackboard download with blanks to fill in. The task statement is enough to write the program, so what follows is a complete version that meets it; the download will have the same registers in its blanks.

Which pin is T0? From the pinout, T0 is on PB0 — package pin 1, PCINT8/XCK0/T0. (T1 is PB1, as in the clock-selection section.) The push button goes there, and it must be an input.

Two timers do two jobs:

  • Timer/counter 0 counts the presses. Clock select 111 — external clock source on T0 pin, clock on rising edge — in normal mode. Every rising edge on PB0 adds one to TCNT0, with no software involved; the program just reads TCNT0 when it wants the count.
  • Timer/counter 1 provides the 1 ms tick. CTC mode with OCR1A from the master formula: \(f_{\text{event}} = 1000\,\text{Hz}\), so \(N(\text{TOP}+1) = 8000\); \(N = 8\), \(\text{TOP} = 999\). Nothing is wired to OC1A this time — the program polls the compare-match flag, OCF1A in TIFR1, which the hardware sets on every match. The flag is cleared by writing a 1 to it.
#include <avr/io.h>

/* Seven segment display values */
uint8_t seven_seg[10] = { 63,6,91,79,102,109,125,7,127,111 };

int main(void) {
  uint8_t count;
  uint8_t left = 0;             /* which digit is lit this millisecond */

  DDRA = 0xFF;                  /* segments on port A            */
  DDRD |= (1<<0);               /* CC on PD0                     */
  DDRB &= ~(1<<0);              /* T0 = PB0 is an input          */

  /* Timer/counter 0: normal mode, clocked by rising edges on T0 */
  TCNT0 = 0;
  TCCR0A = 0;
  TCCR0B = (1<<CS02) | (1<<CS01) | (1<<CS00);

  /* Timer/counter 1: CTC, compare match every 1 ms
     8 MHz / (8 * (999+1)) = 1000 Hz */
  TCNT1 = 0;
  OCR1A = 999;
  TCCR1A = 0;
  TCCR1B = (1<<WGM12) | (1<<CS11);

  while(1) {
    count = TCNT0 % 100;        /* two digits' worth of the running count */

    if(left) {
      PORTA = seven_seg[count / 10];     /* tens */
      PORTD |= (1<<0);                   /* CC = 1: left digit */
    } else {
      PORTA = seven_seg[count % 10];     /* ones */
      PORTD &= ~(1<<0);                  /* CC = 0: right digit */
    }

    /* Wait for the 1 ms compare match, then clear the flag */
    while((TIFR1 & (1<<OCF1A)) == 0) {
    }
    TIFR1 = (1<<OCF1A);

    left = !left;               /* other digit next time */
  }
}

Figure 100: Display multiplexing on a 1 ms tick. The two digits share the eight segment lines, so only one can show its own pattern at a time; the program writes the tens pattern with CC high, waits 1 ms, writes the ones pattern with CC low, waits 1 ms, and repeats. Each digit is therefore lit half the time, at 500 Hz — far too fast for the eye to see it flicker, so both appear steady, at half brightness. Slow the tick to 250 ms and the same program visibly flips between the two digits, which is the task’s last step.

What each part is doing, and why:

  • TCCR0B = (1<<CS02)|(1<<CS01)|(1<<CS00) is row 111 of the clock-selection table, for timer 0. The button is the timer’s clock. A mechanical button bounces, so one press may register as several rising edges — the count can jump by two or three per press; that is the hardware being honest, not a bug in the code, and de-bouncing is a later problem.
  • TCNT0 % 100 — an 8-bit count runs 0–255, and two digits show 0–99, so the display shows the count modulo 100. Without this, count / 10 reaches 25 and indexes past the end of the table (c-pointers-and-arrays).
  • The wait loop — while((TIFR1 & (1<<OCF1A)) == 0) spins until the hardware sets the flag; TIFR1 = (1<<OCF1A) clears it by writing a 1 (a flag register clears the bits you write 1 to, the opposite of a port). The & (1<<OCF1A) is the test row of the bit-masking table from week8-lab-avr-c-programming. This is the software half of the compare match; Task 1 used the hardware half (the pin) and ignored the flag.
  • Segments before CC. Each branch writes the pattern first and then selects the digit, so the newly selected digit never briefly shows the other digit’s pattern.
  • left = !left alternates; left ^= 1 is the same thing spelled as an XOR mask.

Slowing it down — 4 times per second means a 250 ms tick: \(N(\text{TOP}+1) = 8\,000\,000 / 4 = 2\,000\,000\), and the only exact 16-bit fit is \(N = 64\), \(\text{TOP} = 31\,249\):

  OCR1A = 31249;
  TCCR1B = (1<<WGM12) | (1<<CS11) | (1<<CS10);   /* prescaler 64 */

Now the two digits are visibly taking turns, each on for a quarter of a second, and the multiplexing stops being an illusion.

See also

Week 9

Lecture 17 — Interrupts

The last of the four ways the program counter leaves its sequence. The list is branches, jumps, procedures, interrupts/traps, and the first three are in Lecture 15 (2026-09-14-flow-of-control). An interrupt is a call that nobody wrote: a device signals the CPU, and the hardware diverts the running program into a handler and later puts it back exactly where it was. The stack comes first, because that is where exactly where it was is kept. Then comes the problem the CPU has with slow I/O and the two ways to solve it, polling and interrupts, followed by the three issues an interrupt raises: finding the handler, preserving the registers, and what to do when a second interrupt arrives. Each issue gets the AVR’s answer, in assembly and in C. Traps, the software counterpart, come last. The evergreen notes are polling-and-interrupts (the mechanism, on any CPU) and avr-interrupts (the ATmega324A’s vector table, the ISR template, ISR() in C, and setting an interrupt up); the stack itself is procedures-and-the-stack.

The fast CPU and slow I/O

The topic is input/output: the stack revisited, then polling, then interrupts. The stack is what the rest is built on.

The problem is the interface between a fast CPU and slow I/O:

\[\text{CPU (FAST)} \;\longleftrightarrow\; \text{I/O (SLOW)}\]

On the ATmega324A block diagram (avr-architecture), the CPU side is the AVR CPU, running at 8 MHz, with FLASH and SRAM. The I/O side is PORT A, PORT B, PORT C, the A/D converter, and the three timer/counters 8bit T/C 0, 16bit T/C 1 and 8bit T/C 2.

Everything on the I/O side runs at the pace of the outside world. A pin changes when someone presses a button, a timer matches when its count gets there, a converter finishes when the conversion is done. Meanwhile the CPU is completing an instruction every one or two cycles of an 8 MHz clock. For scale, a button held down for a tenth of a second spans 800 000 of those cycles. The question is how the fast side finds out when the slow side has something for it.

AVR Stack

Two instructions move one register on and off the stack:

  • push Rr places the value in register Rr on top of the stack, then adjusts the stack pointer: SP ← SP − 1.
  • pop Rd places the value on top of the stack in register Rd, and adjusts the stack pointer: SP ← SP + 1.

The procedure-call instructions are call, rcall, icall and ret. For example, call label does three things:

  • it places the program counter value (the return address) on top of the stack;
  • SP ← SP − 2, since 16 bits are needed for the return address;
  • PC ← the value of label.

The stack is in data memory and grows towards address 0x000. Say the stack already holds some earlier values and Rr holds 100. push Rr writes 100 into the cell SP points at, the empty cell just above the earlier values, and leaves the stack pointer one cell further up, at SP − 1. pop Rd moves the stack pointer back down and takes the 100 out into Rd.

This is the summary of procedures-and-the-stack, and one detail matters for everything that follows: SP points at the next free cell, so a push writes first and then decrements, and a pop increments first and then reads. A call lowers SP by 2 because the stack is 8 bits wide and a return address is not, so a call uses two cells.

Function call — example

In program memory, main: has a few instructions and then call TEST. The instruction after the call is at address 100. Further down is TEST:, whose instructions end in ret. The call and the return take five steps:

  1. PC ← 100
  2. push PC, which puts the 100 on the stack
  3. PC ← TEST, and TEST runs
  4. pop PC, at the ret
  5. the instruction at address 100 runs

Step 1 is the return address: 100 is the address of the instruction after the call, which is where the PC would have gone next anyway. The call saves it, overwrites the PC with the target, and ret puts the saved value back.

Program memory has 2¹⁴ cells, so an address is 14 bits. The stack is in data memory, where a cell is 8 bits wide. The address does not fit in one cell, so the 100 takes the two cells above the earlier values and the stack pointer is left at SP − 2:

Figure 101: Why a call moves the stack pointer by two. Program memory on the ATmega324A has \(2^{14}\) cells, so the program counter is 14 bits wide, and the return address it holds (here 100, the address of the instruction after the call) does not fit in one byte. The stack is data memory, 8 bits to a cell, so the address is padded to 16 bits and stored as two bytes: the low byte goes into the free cell the stack pointer marks, the high byte into the one above it, and the stack pointer ends two cells further up, at SP − 2. ret reads the same two cells back into the PC and moves SP down by two. A push or pop of a register moves one byte and changes SP by one; mixing the two up is how a procedure that pushes without popping ends up returning to a register’s contents.

Worked: what is in r17 and r18?

What values are in r17 and r18 after this code?

ldi  r17, 20
ldi  r18, 33
push r17
push r18
pop  r17
clr  r17
pop  r17
r17 r18
A. 0 20
B. 0 33
C. 20 20
D. 20 33
E. 33 20
F. 33 33

Answer: D. Take the instructions in the order they run and keep a running record of the two registers. r17 = 20 after its ldi, then 33 after the first pop, then 0 after the clr, then 20 after the second pop. r18 = 33 throughout. After the two pushes the stack holds 20 with 33 on top of it. The first pop takes the 33 back off and the second takes the 20.

Figure 102: The seven instructions, with the stack drawn after each one (the two ldis share the first column). The stack pointer always marks the next free cell, and the stack grows up the page. The question turns on pop taking whatever is on top, with no record of which register put it there: the first pop r17 receives the 33 that r18 pushed, clr zeroes r17, and the second pop r17 receives the 20 that r17 pushed originally, so the clr has no lasting effect. r18 is never written after its ldi. A popped value is not erased; it stays in memory (grey) but sits above the stack pointer, so the next push will overwrite it.

The trap is reading pop r17 as give r17 back its value. The stack keeps values, not names: pushes and pops are matched by order, not by register, which is also what makes the stack useful for swapping two registers or handing a value from one to another. The two pushes and two pops balance, so the stack pointer ends where it began. That matters for interrupts, because an ISR that leaves the stack unbalanced returns to the wrong place.

CPU Interacting with I/O

The CPU operates at a faster speed than I/O, and I/O can sometimes be asynchronous. The CPU needs to know:

  • when data is available from input devices;
  • when output devices are ready to accept data.

There are two options: polling-driven I/O and interrupt-driven I/O.

Asynchronous is the harder half: I/O is not just slow, it is unrelated to the CPU’s clock and to where the program is, so a key can be pressed during any instruction. The two options are drawn side by side against the same events in polling-and-interrupts.

Polling the Input(s)

In polling, the processor periodically asks devices and waits for responses. This is inefficient, because time is wasted asking and waiting, but it may be OK if the processor has nothing else to do.

Polling is what every lab program so far has done: read PINA each time round the main loop, or spin on TIFR1 until the timer flag is set (avr-timers-and-counters). It costs in two places: every ask that finds nothing, and the delay between an event and the next ask. When the processor has nothing else to do, neither cost matters.

Interrupts

With interrupts, the device tells the CPU when it is ready. This is more efficient for the CPU, and it changes the flow of control. Examples:

  • a device is ready to accept more output: the serial transmit buffer is empty;
  • a device has input ready: a key is pressed on the keyboard;
  • a regular interrupt: a timer generates an interrupt every e.g. 20 ms.

An interrupt arrives while some instruction of main is running. Each source of interrupt has its own routine, such as ISR0: and ISR_timer:, sitting in program memory below main like any procedure, and each ends in reti rather than ret.

The three examples are the three kinds of source that the AVR vector table below groups: output ready (a USART’s data register empty), input ready (an external interrupt pin), and time (a timer’s compare match or overflow). The change in the flow of control is the link back to Lecture 15. The PC leaves its sequence, as it does for a branch, jump or call, but here no instruction in the running program asks it to.

Interrupts — the handler, and three issues

When the CPU receives an interrupt, it executes software to handle the interrupt. The software routine is called an interrupt handler or interrupt service routine (ISR). When the handler completes, control must be returned to where the program left off. That raises three issues:

  1. How does the CPU know where the ISR is?
  2. All registers, including the status register, must have their values preserved. How?
  3. What happens if another interrupt arrives while an interrupt is being serviced?

Issue 1 is answered by the vector table, issue 2 by transparency and the ISR template, and issue 3 by nesting and priority.

Finding the Interrupt Handler

This is issue 1. The CPU determines the address of the ISR from the interrupt source, then jumps to that address. It finds the address by looking in the interrupt vector table, which is often at the beginning of memory. The table is either a table of addresses or a table of jump instructions. The AVR uses a table of jump instructions.

Vector sometimes refers to the interrupt number (the index into the vector table) and sometimes to the address of the interrupt handler itself.

The two kinds of table differ in who does the last step. With a table of addresses, the CPU reads the entry for the source and loads the number it finds into the PC. With a table of jumps, the CPU loads the PC with the address of the entry itself, and the instruction stored there — a jmp — does the rest. The AVR does the second. That is why each AVR entry is a two-word jmp (avr-branches-and-jumps) and why consecutive entries are two addresses apart.

The two meanings of vector are worth keeping in mind when reading the datasheet and avr-libc. The vector number is the entry’s row in the table (INT0 is vector 2), and the vector address is where that row sits in program memory (0x0002). In C, the vector’s name (INT0_vect) identifies the entry. avr-libc numbers the entries from 0, with RESET as 0, so the same entry is its vector 1: one more reason to check which counting is meant.

Finding the Interrupt Handler — the whole path

Take a timer interrupt that arrives while an instruction of main is running. Call the return address xxx. Below main in program memory are the handlers, ISR_timer: and ISR0:, each ending in reti. The vector table is at the very top of program memory:

Entry Address
jmp ISR0 0x0000
jmp ISR1 0x0002
⋮
jmp ISR_timer 0x0014

The hardware pushes the return address xxx onto the stack (push PC) exactly as a call would, loads the PC with the table address for the source (0x0014), and the jmp stored there reaches ISR_timer. The handler’s reti then pops the return address back into the PC (pop PC), and main carries on. The numbering of the first two entries is generic: on the ATmega324A, 0x0000 is RESET and 0x0002 is INT0. The third is exact. 0x0014 is vector 11, Timer/Counter2 Compare Match B, so ISR_timer is the right name for what sits there. The path is drawn step by step, with the stack, in avr-interrupts.

AVR Interrupts

The vector table of the ATmega324A (datasheet, pages 69-70). The last column sorts the sources into kinds of I/O:

Vector Program Addr Source Interrupt Definition Kind
1 0x0000 RESET RESET, Watchdog Reset, etc.
2 0x0002 INT0 External Interrupt Request 0 GPIO
3 0x0004 INT1 External Interrupt Request 1 GPIO
…
11 0x0014 TIMER2_COMPB Timer/Counter2 Compare Match B T/C
12 0x0016 TIMER2_OVF Timer/Counter2 Overflow T/C
…
20 0x0026 SPI_STC SPI Serial Transfer Complete Comms
21 0x0028 USART0_RX USART0 Receive Complete Comms
22 0x002A USART0_UDRE USART0 Data Register Empty Comms
23 0x002C USART0_TX USART0 Transmit Complete Comms
24 0x002E ANALOG_COMP Analog Comparator
…

Three things can be read straight off it:

  • Address = 2 × (vector − 1). Entries are two program-memory words apart because each holds a two-word jmp.
  • RESET is vector 1. Reset is handled as the first entry of the same table, which is why every program begins with jmp RESET at 0x0000 (avr-program-structure).
  • The three groups are kinds of I/O. GPIO: pins that raise an interrupt on an edge or level. T/C: the timers. Comms: the serial interfaces. The first two are the ports and timers on the I/O side of the block diagram.

All 31 rows, with their C names, are listed in avr-interrupts.

Preserving Register Values

This is issue 2. If an ISR uses registers, it must save copies of those registers before using them and restore the values afterwards, before returning from the interrupt. In particular, the status register must be saved. Many CPUs do this automatically. The AVR does not: it must be done manually, if the status register would be changed by the handler. This is called transparency: when the ISR finishes, the computer is in the same state as it was before the interrupt.

A procedure’s caller knows the call is coming and can agree with the procedure which registers it may use (procedures-and-the-stack). The code an interrupt lands in has no such chance: the interrupt can arrive between any two instructions. That includes the gap between a cp and the breq that reads its result. If the ISR changes Z and does not put it back, the branch goes the wrong way. It does so only when the interrupt happens to land in that two-instruction window, which is what makes the bug so hard to find. So everything the ISR touches must be restored, the status register above all, and the ISR is then transparent: the interrupted program cannot tell it ran.

Interrupt Summary — Sequence of Actions

The whole sequence is fourteen steps, shared between the hardware and the ISR. Hardware:

  1. Device asserts interrupt line
  2. CPU determines source of interrupt
  3. Push PC (return address) onto stack
    • Some CPUs push the status register as well, but not the AVR
  4. Determine address of ISR (e.g. from the interrupt vector table)
  5. CPU puts address of ISR into PC
  6. CPU disables interrupts

Software (ISR):

  1. Save all registers to be used
  2. Determine source of interrupt (if this is not done by hardware)
  3. Handle the interrupt by executing the ISR code (e.g. do the required input or output)
  4. Restore registers
  5. Execute return from interrupt instruction

Back to hardware:

  1. Interrupts are re-enabled
  2. CPU pops PC off the stack and restores it
  3. Execution continues from where it was “interrupted”

Steps 6 and 12 are a pair. On the AVR, disables interrupts is the hardware clearing the I bit of the status register (avr-architecture) as it takes the vector, and re-enabled is reti setting it again. Between them, no other interrupt can start. Step 8 mostly does not arise on the AVR, because every source has its own vector and so the hardware has already told the ISR which source fired. The exception is the pin-change interrupts: PCINT0–PCINT3 each cover a whole port, and their handler must work out which pin changed. Steps 11 to 13 are a single instruction: reti is ret plus set I. The whole sequence is drawn, with the stack and the I bit at each stage, in polling-and-interrupts.

Instructions which change the Status Register

The Instruction Set Reference says which instructions change the status register. Its Flags affected column is summarised for the instructions this course uses in avr-instructions. The short version is enough to decide whether an ISR must save SREG:

Change flags Change no flags
arithmetic: add, adc, sub, subi, inc, dec, neg data movement: ldi, mov, lds, sts
logic: and, andi, or, ori, eor, com, clr, tst I/O: in, out, sbi, cbi
compare: cp, cpi stack: push, pop
shifts and rotates: lsl, lsr, asr, rol, ror jumps, calls, returns and branches

An ISR built only from the right-hand column cannot disturb the flags, so it has no need to save them. The worked question after the ISR template tests that rule. (Three instructions change the I bit and nothing else: sei, cli and reti.)

Template AVR ISR

isr_label:                ; Save any registers used
            push r0
            in   r0, SREG
            push r0

            ; … perform operation
            ; … (usually Input/output)

            ; Restore registers
            pop  r0
            out  SREG, r0
            pop  r0
            ; return from interrupt
            reti

The first three instructions store on the stack: r0, then the SREG copy that in r0, SREG takes and the second push r0 saves. The three before the reti restore from the stack: out SREG, r0 puts the flags back and the last pop r0 puts r0 back.

Each line is there for a reason:

  • r0 is pushed first because SREG cannot be pushed directly. push takes a general-purpose register, and SREG is an I/O register, so its value has to travel through one. That register’s own contents must be saved before it is used as the carrier.
  • The flags saved are the interrupted program’s. Apart from I, which the next point covers, nothing between the interrupt and in r0, SREG changes them, since push does not touch the flags. They are exactly what the interrupted code last left in SREG.
  • The restore is the mirror image, because the stack returns things in reverse order. The saved SREG copy comes off first, so it is popped into r0 and written to SREG; then r0’s own value comes off.
  • The saved I bit is 0. The hardware cleared I before the first instruction of the ISR ran, so the copy taken by in r0, SREG has I = 0, and writing it back leaves interrupts off. It is reti, the last instruction, that turns them on again.

Any other register the body uses gets its own push after these three and its pop before the restore, in reverse order. The stack through the whole template is drawn in avr-interrupts.

Worked: a suitable ISR for port B to port C

Which of these is a suitable interrupt service routine that reads a byte from the port B pins and outputs it to port C? There are four handlers for INT0, each with .def temp = r16:

; (a)
int0: push temp
      in   temp, SREG
      push temp
      in   temp, PINB
      out  PORTC, temp
      reti
; (b)
int0: push temp
      in   temp, SREG
      push temp
      in   temp, PINB
      out  PORTC, temp
      pop  temp
      pop  temp
      out  SREG, temp
      reti
; (c)
int0: push temp
      in   temp, SREG
      push temp
      in   temp, PORTB
      out  PINC, temp
      pop  temp
      out  SREG, temp
      pop  temp
      reti
; (d)
int0: push temp
      in   temp, PINB
      out  PORTC, temp
      pop  temp
      reti

Figure 103: The four candidate handlers, each with its stack drawn at its fullest, just before it starts to unwind. (a) pushes two bytes and pops none, so reti takes the saved SREG copy and r16 as its return address and jumps into the program at an address made of them. (b) pops the two bytes in the wrong order: the stack is balanced, so it returns correctly, but SREG receives r16’s old value and the interrupted code resumes with meaningless flags. (c) saves and restores exactly as the template does, but reads PORTB, port B’s output register, instead of PINB, its pins, and writes to PINC, port C’s input register, instead of PORTC; on this chip a 1 written to a PINx bit toggles the matching PORTx bit, so the outputs would flip rather than copy port B. (d) saves the one register it uses and never touches the flags, since in, out, push and pop change none of them; it is correct, and the shortest.

The answer is (d). It looks the least careful of the four because it skips the SREG lines, but SREG has to be saved only if the status register would be changed by the handler, and nothing in (d) changes it. The other three each make a different mistake worth recognising. (a) leaves the stack unbalanced, (b) restores in the wrong order, and (c) confuses a port’s three registers (avr-io-ports). PINx is what the pins read, PORTx is what the port drives, and the two are not interchangeable. All four assume, as the question does, that port B’s pins were set as inputs and port C’s as outputs during initialisation.

AVR Interrupts in C

Start with #include <avr/interrupt.h>. An interrupt handler can then be written as a C function, using the special ISR macro:

ISR(INT0_vect) {
    … /* code here */
}

This is the handler for the INT0 external interrupt. The interrupt vector table setup and the register saving and restoring happen automatically. The name to use is the source name from the datasheet followed by _vect. The AVR LibC manual documents avr/interrupt.h.

The argument, INT0_vect, is the name that matters. ISR is not a function name but a macro, and what it is given is the vector. From that the compiler does the three things the assembly programmer does by hand: it places a jump to this function in the vector table at INT0’s entry (0x0002), wraps the body in the save-and-restore the template writes out, SREG included, and ends it with reti instead of ret. The naming rule is the Source column of the table plus _vect, which gives TIMER2_COMPB_vect, USART0_RX_vect, ANALOG_COMP_vect, and so on.

Setting up interrupts

Besides the handler, the program also needs to:

  • set up the conditions for the interrupt;
  • enable that particular interrupt. An I/O register bit for each interrupt controls whether that interrupt is enabled or not;
  • clear the specific interrupt flag, to ensure the interrupt doesn’t trigger immediately. This is usually done by writing 1 to some I/O register bit;
  • turn on interrupts globally, with the sei() macro (the same as the sei assembly language instruction).

These are four switches, and an interrupt reaches its handler only when all of them are on. For a timer 1 compare-match interrupt:

Step Timer 1, compare A
conditions TCCR1A/TCCR1B and OCR1A: the mode, prescaler and match value (avr-timers-and-counters)
enable that interrupt OCIE1A in TIMSK1
clear its flag TIFR1 = (1<<OCF1A);, a 1 written to clear it
enable globally sei();, which sets I in SREG

Clearing the flag first matters because the flag is set by the hardware whether or not its interrupt is enabled. A timer that has been counting while the interrupt was off has very likely matched already. Without the clear, the moment the enable and sei() go on, the CPU would take a stale interrupt for an event that happened long before. The complete program is in avr-interrupts.

Volatile variables in C

A variable that can be changed outside the normal flow of a program (e.g. in an interrupt handler) should be declared as volatile:

volatile uint8_t count;

This prevents the code optimiser from assuming the variable’s value doesn’t change and optimising code away.

For example, take a loop in main:

int i = 0;
while (i < 10) {
    …
}

and a handler that writes the variable:

ISR() {
    i = 100;
}

The optimiser concludes that the condition i < 10 is always TRUE.

Figure 104: What volatile changes. main loops while i < 10, nothing in the loop body writes i, and an ISR sets i = 100. The compiler analyses main on its own and has no way to know that a handler may run between any two of its instructions. Without volatile it may keep i in a register, or conclude that i < 10 can never become false and drop the test entirely: the ISR’s write reaches memory, but the loop never reads memory again and never ends. With volatile, every read of i in the source becomes a load from memory in the machine code, so the first test after the ISR has run sees 100 and the loop exits. The program is identical in both columns; only what the compiler is permitted to assume differs.

The compiler is not wrong to optimise; it is working from a program that, as far as it can see, never changes i in the loop. volatile is how the programmer tells it about the other writer. The declaration of count uses uint8_t where the loop uses int, and uint8_t is the safer choice on this CPU, for a reason drawn out in avr-interrupts. A one-byte variable is read by a single instruction, so an interrupt cannot land halfway through reading it.

Nested Interrupts

This is issue 3. There is a chance that another device interrupts during ISR execution. There are two policies:

  • Simply disable subsequent interrupts during the ISR. Usually, the global interrupt enable flag is one of the flags restored by the return from interrupt instruction.
  • Better, prioritise interrupts, and allow higher priority interrupts to interrupt lower priority ones (and not vice versa, or at the same level). Many CPUs support this, but not the AVR.

The first is the AVR’s: interrupts are off for the whole ISR. On a CPU that saves the status register automatically, restoring it on return brings the enable flag back with everything else. The AVR does not save SREG, but reti sets I directly, which comes to the same thing. The second policy — priority nesting, where only a more urgent source may interrupt an ISR — is the better one, and the AVR does not have it. The three policies, including the one the AVR allows by choice, are compared in polling-and-interrupts.

AVR Interrupt Priority

Priority is determined by vector: the lowest vector is the highest priority. The top of the vector table is HIGH priority and the bottom is LOW. So RESET outranks everything, INT0 is the highest-priority real interrupt, and down the table external pins come before timers, which come before the serial interfaces.

Three rules say when priority applies:

  • Priorities only matter when two (or more) interrupts are waiting to be serviced. The highest priority (lowest vector) is serviced first.
  • Interrupts are disabled during an ISR, and re-enabled by the reti instruction.
  • It is possible to enable interrupts during an ISR. Priorities are not relevant then: any incoming (or pending) interrupt may be serviced, even if it is lower priority.

The first rule is the one people get wrong. On the AVR, priority does not mean that a more important interrupt can cut into a less important ISR. It only decides the order in which waiting interrupts are taken, once the CPU is free to take one. An interrupt waits by leaving its flag set, so nothing is lost while I is 0, as long as each source fires only once in the meantime.

Figure 105: Two cases, each with the I bit traced underneath. (a) The default. While the USART0_RX handler runs, I is 0, so the timer overflow and then INT0 arrive and wait, their flags set (the two middle traces). When reti sets I again, the lower vector goes first: INT0 (vector 2) is serviced before TIMER2_OVF (vector 12) even though it arrived later. That ordering is the only thing priority does on the AVR. Between two handlers the CPU executes one instruction of main, as the datasheet specifies, so a steady stream of interrupts cannot starve the main program completely. (b) An ISR that executes sei early. From that instruction on, I is 1 and any interrupt is taken at once, however low its priority: the timer overflow nests inside the INT0 handler, and INT0’s handler finishes only after the nested one returns. The hardware saves nothing extra for the nesting; each level’s return address is simply one more pair of bytes on the stack.

The (b) case is sometimes exactly what is wanted. A long, unhurried handler can re-enable interrupts so that a time-critical source is not kept waiting. But it gives up the protection the default provides: the handler can now be interrupted by anything, including a second copy of itself if its own source fires again, and every level of nesting costs more stack. Nothing in the course’s labs needs it.

Traps

Traps are software interrupts: they are caused by events in software rather than hardware. The events are exceptional ones. Examples:

  • overflow
  • divide by zero
  • undefined opcode

Traps save continually checking for errors. Trap handlers (service routines) don’t always return to the original program. The AVR doesn’t provide traps, but it is possible to generate hardware interrupts from software.

Traps are to error checking what interrupts are to polling. Without them, a program that cares about overflow has to test V after every addition, which is polling for errors. With them, the hardware watches, and the program is diverted only when the error actually happens. That a handler doesn’t always return follows from what the errors are: after a division by zero or an undefined opcode there is often no sensible instruction to continue with, and under an operating system the usual outcome is that the program is ended. On the AVR none of this exists. Overflow simply sets V for the program to test with a branch (avr-branches-and-jumps), and there is no divide instruction to fail. The hardware interrupts that software can generate are the external interrupt pins: the datasheet notes that INT0–INT2 still trigger when their pins are configured as outputs, so writing the pin’s PORT bit raises the interrupt on purpose.

See also

Lecture 18 — Serial Input/Output

How a microcontroller talks to another computer over a single wire, and a first look at reading analog voltages. It covers serial against parallel and synchronous against asynchronous links, the UART frame with its start, data, parity and stop bits, how a receiver finds the bits with no shared clock, baud rate, and the ATmega324A’s USART: its registers and its three interrupts. The last part is the PC end of the link, RS232, and analog to digital conversion. The reference notes are serial-communication, avr-usart and analog-to-digital-conversion.

Where serial I/O fits

The parts of the ATmega324A used so far (avr-architecture):

Part What it has been used for
Ports A, B, C, D switches, buttons and the seven-segment display (avr-io-ports, seven-segment-display)
CPU, flash, SRAM running the program
Timer/counters 0, 1, 2 timing, waveforms and PWM (avr-timers-and-counters)

Three more blocks come into play from here:

  • USART0 and USART1: two serial ports. A key typed in a terminal program on a PC travels down a wire and arrives in the microcontroller as a character, and the microcontroller can send characters back.
  • SPI: the chip’s other serial interface, a synchronous one. It is the one that will drive the LED display.
  • The A/D converter: reads a voltage, such as the position of a joystick, as a number.

The block diagram in the datasheet is shared by a family of chips and shows timers the 324A does not have. The 324A has exactly three: two 8-bit and one 16-bit.

Interrupt set-up, once more

A device can interrupt the CPU only when three things are true at once (avr-interrupts):

  1. Interrupts are enabled globally: sei() has set the I bit, bit 7 of SREG.
  2. The device’s own interrupt is enabled: for a timer 1 compare match, OCIE1A in TIMSK1.
  3. The device’s interrupt flag is set: OCF1A in TIFR1, set by the hardware when the event happens.

The set-up code makes the first two true and leaves them that way. The third is different, because the flag is set by the hardware, at the moment of the event. Set-up does two things about it. It configures the device so that the event will happen: for the timer that is the mode, the prescaler and a compare value such as OCR1A = 200, after which the flag is set every time the count reaches 200. And it clears the flag first, so that an event from before the program was ready does not fire the handler straight away. Clearing it is the step that reads backwards.

An interrupt flag is cleared by writing a 1 to it. Writing a 0 does nothing.

Check. Which of these is false when configuring interrupt-driven I/O?

  • A. Global interrupts should be enabled
  • B. SREG bit 7 should be set to 1
  • C. The interrupt should be enabled in the I/O device
  • D. A 1 should be written to the particular interrupt flag bit
  • E. A 0 should be written to the particular interrupt flag bit

E. A and B are the same statement, since bit 7 of SREG is the global enable. C is the device’s enable bit. D is how a flag is cleared.

Figure 106: What has to be true for a timer compare match to interrupt the CPU, as the inputs of two AND gates. The set-up code puts the first two lines at 1 and they stay there. The third line is the flag, which the timer sets at each compare match, so the output goes to 1 only when the event happens. Without the first or the second the handler never runs. Set-up also clears the flag to begin with, by writing a 1 to it, so that an old event cannot run the handler straight away.

When the interrupt is taken, the address of the next instruction is pushed on the stack, the CPU jumps through the vector table to the handler, and reti pops the address to resume (procedures-and-the-stack).

Serial and parallel, synchronous and asynchronous

Two independent choices describe a communication link.

Serial or parallel is about how many wires carry data. A parallel link has one wire per bit and sends the bits together. A serial link has one wire, and the bits take turns. Serial needs fewer pins and wires, which is why almost every link between devices is serial.

Synchronous or asynchronous is about how the receiver knows when to look at the wire. A synchronous link sends a clock on a second wire alongside the data. An asynchronous link has no clock wire, so the receiver must recover the timing from the data itself, and the data must be encoded to make that possible.

Example
synchronous serial SPI, Serial Peripheral Interface
asynchronous serial UART, Universal Asynchronous Receiver and Transmitter; USB

Figure 107: Four ways to join a transmitter to a receiver. Top row: the same five bits sent serially, one after another down a single wire, and in parallel, on five wires at once. Bottom row: two kinds of serial link. A synchronous link has a second wire carrying the clock that says when each data bit is valid. An asynchronous link has the data wire only, and the transmitter adds extra bits to the stream so that the receiver can work out the timing for itself.

The difficulty with no clock wire is that a run of identical bits is a flat line with nothing to time against. The encodings in use are different ways of guaranteeing edges:

  • Start and stop bits: every character begins with a guaranteed edge. This is what a UART does.
  • 4B/5B and 8B/10B: every 4 or 8 bits are sent as a 5- or 10-bit code chosen so that the line changes often.
  • Bit stuffing: an opposite bit is inserted after a run of identical ones. USB at low and full speed does this.

The UART frame

The AVR’s serial port is a USART, a Universal Synchronous and Asynchronous Receiver/Transmitter. It can do both, and the course uses it mainly in asynchronous mode, so it is usually just called a UART. Three things characterise it:

  • It is serial: data goes one bit at a time, in groups called frames.
  • It is asynchronous: no clock is sent. Each end has its own clock. The two clocks can be quite different, as long as each end can derive nearly the same bit time from its own.
  • It uses start and stop bits to mark each frame.

A frame is one character’s worth of data wrapped in framing bits, in this order:

Field Bits Value
start bit 1 always 0
data bits 5 to 9 the data, bit 0 first
parity bit 0 or 1 computed from the data; optional
stop bits 1 or 2 always 1

Between frames the line idles at 1. So a start bit is always a fall from 1 to 0, which is the event the receiver waits for, and the stop bit puts the line back at 1 so that the next start bit is a fall too. After the stop bit, either the next frame starts at once or the line stays idle.

Figure 108: One UART frame, field by field. The line idles at 1. The start bit is always 0, so every frame begins with a falling edge. The data bits follow, least significant first: there are at least five and at most nine. The parity bit is optional. One or two stop bits, always 1, end the frame and return the line to its idle level, ready for the falling edge of the next start bit.

Parity

The parity bit is for error detection. Both ends agree on even or odd parity beforehand.

  • Even parity: the number of 1s in the data bits plus the parity bit must be even.
  • Odd parity: that number must be odd.

The transmitter works out the parity bit and sends it. The receiver counts the 1s in everything it received, parity bit included, and a count of the wrong kind means at least one bit was changed on the way.

Example. Nine data bits 0 0 1 0 0 1 1 1 1 contain five 1s. For even parity the parity bit is 1, making six. For odd parity it is 0, leaving five.

Check. 0xA7 is to be sent as 8 data bits with odd parity. What is the parity bit? 0xA7 is 1010 0111: two 1s and three 1s, five in all. Five is already odd, so the parity bit is 0.

Check. 0xA9 arrives with parity bit 1 on a link using even parity. Was there an error? 0xA9 is 1010 1001, four 1s. With the parity bit that is five, which is odd. Yes: at least one of the nine bits is not what was sent.

Parity can say that something went wrong. It cannot say which bit, and if two bits flip the count comes out right again and the error goes unnoticed. Finding and repairing the wrong bit is error correction, which takes more check bits arranged as a Hamming code and is not part of a UART frame.

How the receiver finds the bits

The receiver has to know the baud rate in advance, but its clock does not have to be synchronised with the transmitter’s. It works like this:

  1. It samples the line much faster than the bits arrive: 16 samples per bit on the AVR (8 in double-speed mode).
  2. The fall of the start bit starts it counting samples.
  3. It reads each bit from the three samples in the middle of that bit’s time, by majority vote. Three 0s in the middle of the first bit time confirm a real start bit and not a spike of noise.

Reading in the middle is what makes an unsynchronised clock tolerable. If the receiver’s bit time is a little long or short, its sampling point drifts a little further with every bit, and starting from the centre leaves half a bit of margin either way. The drift has only one frame to build up before the next start bit resets it.

Figure 109: How a UART receiver reads a bit without a shared clock. It samples the line 16 times per bit. The falling edge of the start bit starts the count, and each bit is decided by a majority vote of the three samples at its centre, shown tall. Three 0s in the middle of the first bit time confirm a start bit. The same three positions in the next bit time read 1, 1, 1, so the first data bit is 1. Because the count restarts at every start bit, the two ends only have to agree on the bit time closely enough for the sampling point to stay inside the bit for one frame.

Baud rate

Baud rate = symbols per second. It is not the same as the bit rate, the number of useful data bits per second.

Every bit time on the wire is one symbol, whether it carries data or framing. With 8 data bits, no parity, one start bit and one stop bit, a frame is 10 symbols and carries 8 bits:

\[9600 \text{ baud} \times \tfrac{8}{10} = 7680 \text{ bits per second} = 960 \text{ bytes per second}\]

The industry-standard rates are 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600 and 115200.

On the AVR the rate is set by a number in the baud-rate register, worked out from the clock frequency and the 16 samples per symbol:

\[UBRRn = \frac{f_{OSC}}{16 \cdot BAUD} - 1\]

For 9600 baud with the 8 MHz clock: \(8\,000\,000 / (16 \times 9600) - 1 = 51.08\), so the register is 51. The real rate is then \(8\,000\,000 / (16 \times 52) = 9615\) baud, about 0.2 % fast, which is easily close enough. The datasheet tabulates the values for the standard rates (pages 198 to 201), and avr-usart works them out. The formula has the same shape as the timer’s master formula (avr-timers-and-counters) for the same reason: counting through the values 0 to \(N\) takes \(N + 1\) clock cycles, here with \(N = UBRR\).

The AVR USART

USART0 uses two pins of port D: PD0 is RXD0, receive, and PD1 is TXD0, transmit. The USART is described on pages 175 to 201 of the datasheet.

At the centre of each half is a shift register (shift-registers). To transmit, a byte written to the data register is loaded into the transmit shift register and shifted out of TxD one bit per bit time, with the framing bits added. To receive, bits arriving on RxD are shifted in one at a time, and the completed byte is copied to the data register. A UART is a parallel-to-serial converter and a serial-to-parallel converter with framing.

Figure 110: The USART reduced to what a program uses, joined to a PC. The baud-rate register sets the bit time for both halves. A byte written to the data register is copied into the transmit shift register and shifted out of the TxD pin, with the start, parity and stop bits added on the way. Bits arriving on RxD are shifted into the receive shift register, checked and stripped of their framing, and the byte is copied to the data register to be read. The two ends are cross-connected: each one’s transmit pin goes to the other’s receive pin.

A program works the USART through five I/O registers.

UDR0, the data register. One name, two registers: writing UDR0 puts a byte in the transmit buffer, and reading UDR0 takes a byte from the receive buffer. Reading it does not give back what was last written.

UCSR0A, UCSR0B, UCSR0C, the control and status registers.

7 6 5 4 3 2 1 0
UCSR0A RXC0 TXC0 UDRE0 FE0 DOR0 UPE0 U2X0 MPCM0
UCSR0B RXCIE0 TXCIE0 UDRIE0 RXEN0 TXEN0 UCSZ02 RXB80 TXB80
UCSR0C UMSEL01 UMSEL00 UPM01 UPM00 USBS0 UCSZ01 UCSZ00 UCPOL0

The pattern that makes these readable:

  • The top three bits of A are the interrupt flags: receive complete, transmit complete, data register empty.
  • The top three bits of B, directly beneath them, are the matching interrupt enables. IE in each name is interrupt enable.
  • C holds the frame format: UPM selects the parity (none, even or odd) and USBS selects one or two stop bits.

After reset, C is set for 8 data bits, no parity and one stop bit, the commonest format. Every bit is explained in avr-usart.

UBRR0, the baud-rate register. A 12-bit value held in two bytes, UBRR0H and UBRR0L. Either compute it from the formula or take it from the datasheet’s tables.

The three serial interrupts

Each serial port has three interrupt sources.

Interrupt Means
Receive complete a frame, usually a character, has arrived and can be read
Transmit complete a frame has been sent and no more data is waiting to go
Data register empty the port is ready to accept another byte for transmission

The last two are easy to confuse. The USART can hold two bytes on the way out: one in the shift register being sent, and one in the data register waiting. Data register empty means the waiting place is free, so the next byte can be written even though the previous one is still going out. Transmit complete means the last bit has left and nothing was waiting, so the line has gone idle.

The PC end

A PC has no UART pins. The IO board (io-board) has a USB-serial device on it, which appears to the PC as a serial port and presents the two serial lines to the breadboard. On the PC a terminal program such as PuTTY sends what is typed and shows what arrives. It has to be told:

  • the COM port, which serial port to use (Device Manager shows which one the board has been given);
  • the baud rate and the frame format: data bits, parity, stop bits.

Nothing on the wire announces these settings, so the two ends must simply be set the same. A mismatch gives wrong characters, not an error message.

RS232

RS232 is the long-established serial standard, more than forty years old and still in use, typically on a 9-pin D-sub connector. It carries the same frames at different voltages:

AVR pin RS232
logical 1 5 V a negative voltage, −3 to −15 V
logical 0 0 V a positive voltage, +3 to +15 V

The levels are inverted as well as larger, so a converter chip such as the MAX-232 is needed between the two. RS232 is full duplex: it can transmit and receive at the same time, because each direction has its own wire. The minimum connection is three signals: transmit data (TxD), receive data (RxD) and ground.

Analog to digital conversion

Every input so far has been digital: the processor sees 0 or 1. An analog to digital converter (ADC) takes a voltage anywhere between 0 and a maximum, the reference voltage \(V_{ref}\), and turns it into a number in proportion.

An ADC has a resolution, the number of bits in its result. With 10 bits there are \(2^{10} = 1024\) possible results, 0 to 1023.

A joystick is the standard example. It produces two voltages, one for each direction of travel, and after conversion its position is a pair of numbers.

Figure 111: What a 10-bit converter does to a joystick. Left: the stick’s position as two voltages, each between 0 V and the reference, here 5 V. Right: the same position after conversion, as two numbers from 0 to 1023. The converter divides the range of each voltage into 1024 equal steps, about 4.9 mV each, and reports which step the voltage is on. The marked position, 3.75 V across and 1.25 V up, becomes 768 and 256.

On the ATmega324A:

  • The port A pins can be used as analog inputs.
  • One input is converted at a time. An analog multiplexer selects which pin is connected to the converter, so a joystick’s two voltages are read one after the other.
  • \(V_{ref}\) can be chosen. The course uses \(V_{cc} = 5\ \text{V}\).
  • The resolution is 10 bits, 0 to 1023.
  • A conversion takes time: up to 3200 clock cycles, 0.4 ms at 8 MHz. Accuracy can be traded for speed.

0.4 ms is long enough for a couple of thousand instructions, so the end of a conversion is another event a program either polls for or takes as an interrupt (polling-and-interrupts). More in analog-to-digital-conversion.

See also

Lab 14 — AVR Interrupts

Learning Lab 14: interrupts in C, used to build a stopwatch. A timer interrupt every 10 ms keeps the time, and two push buttons start, stop and reset it. The lab has a preparation task, which is to design the stopwatch’s controller as a state machine and to work out the timer values. The ideas are in avr-interrupts, polling-and-interrupts, software-timers and state-machines.

The stopwatch

  • The two-digit seven-segment display shows the elapsed time in seconds and tenths, from 0.0 up to 9.9, and then wraps round to 0.0.
  • There are two push buttons: S, start/stop, and R, reset.
  • Start/stop takes effect when S is pushed.
  • Reset takes effect when R is released.

Preparation: the controller

The controller is a Moore machine (state-machines). Its inputs are the two buttons and it has three outputs, written as three bits in the order C T D:

State C T D C: clear the count T: the count advances D: the time is displayed
RESET 100 yes no no
RUN 011 no yes yes
STOP 001 no no yes

D is 0 only in RESET, so taken literally the display is blank until the stopwatch is first started, and blank again after each reset. The programs below do exactly that. To show 0.0 in RESET instead, light the display in every state.

There are many right answers. A design is checked against four questions:

  1. Does it do what was asked?
  2. Does it deal with a button being pushed and then released? Start/stop acts on the push, reset on the release.
  3. What happens while a button is held down? Nothing more should.
  4. What if both buttons are down at once, and then let go in either order?

With edges as inputs

The simplest design takes its inputs as events: S is “the start/stop button has just been pushed” and R is “the reset button has just been released”. Three states are enough.

Figure 112: The stopwatch controller when its inputs are edges: S is a push of start/stop and R is a release of reset. Each state shows its name over its outputs C T D. A push of S starts the count from RESET, and after that alternates between RUN and STOP. A release of R returns to RESET from anywhere, and R is written alone on those arrows because it wins if both events arrive together. With nothing happening every state loops back to itself.

Against the four questions:

  • Pushed and released. Only one edge of each button is an input, so the other edge does nothing. Letting go of S is not an event, and neither is pushing R.
  • Held down. A held button produces no more edges, so nothing more happens.
  • Both at once. With both buttons held, nothing happens. Letting go of R resets, whether S is still down or not, and letting go of S is not an event. If a push of S and a release of R arrive in the same step, the arrows for S are labelled \(S\overline{R}\) and the arrows for R are labelled \(R\) alone, so the reset wins.

This is the design that fits interrupts, because an edge on a pin is exactly what an external interrupt reports.

With levels as inputs

If R is instead the level of the reset button, 1 for as long as it is down, the machine has to do the waiting itself. Going straight to RESET when R becomes 1 would reset on the push. So each of RUN and STOP gets a partner state that means “reset is being held”, and the move to RESET happens when R goes back to 0.

Figure 113: The controller when R is the level of the reset button, 1 while it is held down. Two states are added. While reset is held the machine waits in RUN_RST or STOP_RST, with the same outputs as the state it came from, so the stopwatch carries on exactly as it was. Only when the button is let go does it move to RESET. S has to be a single push of start/stop, 1 for one step, and it is ignored for as long as R is 1.

  • Reset on release. RUN to RUN_RST on \(R\), wait there while \(R\) stays 1, then RUN_RST to RESET on \(\overline{R}\). The same from STOP.
  • Held down. RUN_RST and STOP_RST loop on \(R\) for as long as the button is held, and the stopwatch does not change in the meantime: a running count keeps running.
  • Both at once. From RUN or STOP, \(R\) takes priority over \(S\). In the waiting states S is not looked at. Whichever order the buttons are let go in, the machine arrives in RESET with nothing pending.

For this to work S has to be an event, 1 for a single step when the button goes down. If S were a raw level too, holding it would flip between RUN and STOP on every step, and it would need waiting states of its own.

Figure 114: One run of the stopwatch. The count starts at the moment S is pushed and not when it is let go, and each later push of S stops or restarts it. Holding S down for a long time does nothing extra. When R is pushed the count carries on, and the stopwatch clears only at the moment R is let go. In the design with levels as inputs, the stretch where R is held is the waiting state RUN_RST, which has the same outputs as RUN.

Preparation: timer 1 for a 10 ms tick

The stopwatch needs something to happen 100 times a second. Timer/counter 1 does it with a compare match A every 10 ms:

  • divide the 8 MHz clock by 8, so the timer counts at 1 MHz;
  • clear the count on the compare match (CTC mode), so the match comes round at a steady rate;
  • leave the output pins alone.

What goes in OCR1A? From the master formula (avr-timers-and-counters):

\[100 = \frac{8\,000\,000}{8 \times (OCR1A + 1)} \quad\Longrightarrow\quad OCR1A + 1 = 10\,000 \quad\Longrightarrow\quad OCR1A = \mathbf{9999}\]

The register is 16 bits, held as two bytes OCR1AH and OCR1AL. In C it is written as one 16-bit value and the compiler splits it.

What goes in TCCR1A and TCCR1B? Pages 136 to 139 of the datasheet.

Setting Bits
no output pins COM1A1:0 = 00, COM1B1:0 = 00 all 0 in TCCR1A
CTC, top in OCR1A WGM13:0 = 0100 WGM12 in TCCR1B. The other three are 0
clock / 8 CS12:0 = 010 CS11 in TCCR1B
OCR1A  = 9999;
TCCR1A = 0;
TCCR1B = (1<<WGM12) | (1<<CS11);

Interrupts in C

The global switch. The I bit, bit 7 of the status register SREG, turns all interrupts on or off together. sei() sets it and cli() clears it. In assembly the same two are the instructions sei and cli.

Setting an interrupt up takes five things:

  1. Set the conditions for the interrupt, such as a timer’s mode and compare value, or which edge of a pin.
  2. Enable that interrupt by setting its bit in the mask register.
  3. Clear its flag, in case it is already set from before. A flag is cleared by writing a 1 to it.
  4. Have a handler for it.
  5. Turn interrupts on globally with sei().

The handler is a function with no arguments and no return value, written with the ISR macro:

#include <avr/interrupt.h>

ISR(INT0_vect) {
    /* code that runs when the interrupt happens */
}

The name in the brackets is the interrupt’s source name from the vector table (pages 69 to 70 of the datasheet) with _vect on the end: INT0_vect, TIMER1_COMPA_vect, and ADC_vect for the end of an analog conversion. The full list is in the avr-libc documentation for <avr/interrupt.h>.

The compiler does the rest. In C there is no vector table to write and no registers to save by hand. ISR puts the handler’s address in the table, and the compiled handler saves the registers it uses on the way in and restores them on the way out.

Handlers must be short. While one runs, everything else waits, other interrupts included. A handler records what happened and returns. Printing in a handler is far too slow. The stopwatch’s tick handler does a little more than count, since it also lights the next display digit, but both jobs together take well under a thousand clock cycles out of the 80 000 between ticks.

Shared variables are volatile. A variable that a handler changes and the main program reads must be declared volatile, as in volatile uint8_t count;. Without it the compiler may assume the variable cannot change behind the main program’s back and never read it again (avr-interrupts).

Three checks

What is the handler for timer/counter 1’s compare match A called? The source name in the vector table is TIMER1_COMPA, so the handler is ISR(TIMER1_COMPA_vect).

Of these interrupts, which has the highest priority? TIMER0_COMPA, TIMER0_COMPB, TIMER1_COMPA, TIMER1_COMPB, TIMER2_COMPA, TIMER2_COMPB, USART0_RX, USART0_TX.

Priority goes by position in the vector table, lowest vector number first:

Source Vector
TIMER2_COMPA 10
TIMER2_COMPB 11
TIMER1_COMPA 14
TIMER1_COMPB 15
TIMER0_COMPA 17
TIMER0_COMPB 18
USART0_RX 21
USART0_TX 23

So TIMER2_COMPA. The trap is to expect timer 0 to come first. The table lists the timers in the order 2, 1, 0.

Which pin is INT1? PD3. INT0 is PD2, next to it.

Two worked set-ups

A timer compare match

To run a handler on every compare match A of timer/counter 1:

ISR(TIMER1_COMPA_vect) {
    /* runs on every compare match A */
}

/* in main */
OCR1A  = 9999;                          /* 1: the conditions              */
TCCR1A = 0;
TCCR1B = (1<<WGM12) | (1<<CS11);
TIMSK1 = (1<<OCIE1A);                   /* 2: enable (bit 1 of TIMSK1)    */
TIFR1  = (1<<OCF1A);                    /* 3: clear the flag by writing 1 */
sei();                                  /* 5: interrupts on               */

TIMSK1 is on page 142 of the datasheet and TIFR1 on page 143.

An external interrupt on a rising edge

To run a handler whenever pin INT0 (PD2) goes from 0 to 1:

ISR(INT0_vect) {
    /* runs on every rising edge of PD2 */
}

/* in main */
EICRA = (1<<ISC01) | (1<<ISC00);        /* 1: rising edge                 */
EIMSK = (1<<INT0);                      /* 2: enable                      */
EIFR  = (1<<INTF0);                     /* 3: clear the flag by writing 1 */
sei();                                  /* 5: interrupts on               */

The sense control bits in EICRA choose what counts as a request (avr-interrupts):

ISCn1:0 A request is made
00 for as long as the pin is low
01 on any change of the pin
10 on a falling edge
11 on a rising edge

These registers are on pages 75 and 76 of the datasheet. The register diagrams there label the bits IINT0 and IINTF0, which is a misprint. The names are INT0 and INTF0.

One timer, many timings

Three timer/counters are not enough if each timed thing gets one to itself. A software timer gets round it. One timer interrupt at a fixed interval adds 1 to a global count of the time since reset, and everything else reads that count. Copying the count into a local variable marks the moment something happened, and subtracting two such copies gives a duration, in units of the interrupt period. Code built this way never has to sit in a delay doing nothing (software-timers).

The stopwatch is a first step towards it. Its time is a count of 10 ms ticks, advanced by the tick handler only while the stopwatch is running.

The tasks

NoteExercises
  1. Start from lab14-1.c.
    • Fill in the code where indicated, using the register values worked out above.
    • Add the controller code from the state diagram.
    • Compile and simulate. Put a breakpoint in the handler and make sure it is reached, and check the cycle counter is what it should be.
    • Check that it works on the board.
  2. Start from lab14-2.c. Make start/stop a push button on an external interrupt: a rising edge on INT0 (pin D2). Set up the edge, enable the interrupt and clear the flag. Compile, simulate, download and test.
  3. Add a reset button: an interrupt on the falling edge of INT1 (pin D3).
  4. Extension: after 9.9 s, show whole seconds (10, 11, 12, and so on) instead of wrapping round.

Working — Exercise 1

lab14-1.c and lab14-2.c come with gaps to fill in. These are complete programs that do the job, to compare against.

Wiring. The seven-segment display is on port A with its digit select CC on PD0, as in Lab 12. Start/stop is on PD2 and reset on PD3, which are the pins the later exercises need. The buttons read 1 while pressed.

The design. The timer handler runs every 10 ms. It advances the count while the stopwatch is running and lights one of the two digits. The main loop is the controller of Figure 113. It reads the buttons as levels once per tick, steps the state machine, and sets the three outputs from the state.

#include <avr/io.h>
#include <avr/interrupt.h>

/* controller states */
#define RESET     0
#define RUN       1
#define STOP      2
#define RUN_RST   3       /* running, reset button held */
#define STOP_RST  4       /* stopped, reset button held */

uint8_t seven_seg[10] = { 63,6,91,79,102,109,125,7,127,111 };

/* shared between main and the handler, so all volatile */
volatile uint16_t count;       /* elapsed time, in hundredths of a second */
volatile uint8_t  timing;      /* T: the count advances while this is 1   */
volatile uint8_t  showing;     /* D: the digits are lit while this is 1   */
volatile uint8_t  tick;        /* set by the handler every 10 ms          */

/* runs 100 times a second */
ISR(TIMER1_COMPA_vect) {
    static uint8_t left = 0;
    uint8_t tenths;

    if (timing) {
        count++;
        if (count == 1000) {            /* 9.99 s rolls over to 0.00 */
            count = 0;
        }
    }

    /* one digit per tick: seconds on the left, tenths on the right */
    tenths = count / 10;                /* 0 to 99 */
    left = !left;
    if (!showing) {
        PORTA = 0;
    } else if (left) {
        PORTA = seven_seg[tenths / 10] | 0x80;     /* with the decimal point */
        PORTD |= (1<<0);
    } else {
        PORTA = seven_seg[tenths % 10];
        PORTD &= ~(1<<0);
    }

    tick = 1;
}

int main(void) {
    uint8_t state = RESET;
    uint8_t s, r, s_before = 0, pushed;

    DDRA = 0xFF;                        /* segments                        */
    DDRD = (1<<0);                      /* CC out; PD2 (S) and PD3 (R) in  */

    /* timer 1: compare match A every 10 ms */
    OCR1A  = 9999;
    TCCR1A = 0;
    TCCR1B = (1<<WGM12) | (1<<CS11);

    TIMSK1 = (1<<OCIE1A);               /* enable the compare match A interrupt */
    TIFR1  = (1<<OCF1A);                /* clear its flag by writing 1          */
    sei();                              /* interrupts on                        */

    while (1) {
        if (tick) {                     /* once per 10 ms */
            tick = 0;

            s = (PIND >> 2) & 1;
            r = (PIND >> 3) & 1;
            pushed = s && !s_before;    /* S has gone down since the last tick */
            s_before = s;

            /* next state */
            switch (state) {
            case RESET:
                if (pushed && !r) { state = RUN; }
                break;
            case RUN:
                if (r)           { state = RUN_RST; }
                else if (pushed) { state = STOP; }
                break;
            case STOP:
                if (r)           { state = STOP_RST; }
                else if (pushed) { state = RUN; }
                break;
            case RUN_RST:
            case STOP_RST:
                if (!r) { state = RESET; }
                break;
            }

            /* outputs: they depend on the state alone */
            timing  = (state == RUN || state == RUN_RST);     /* T */
            showing = (state != RESET);                       /* D */
            if (state == RESET) {                             /* C */
                cli();
                count = 0;
                sei();
            }
        }
    }
}

How the code follows the diagram.

  • One case per state, one if per arrow. Testing r before pushed is what makes reset win when both happen together. A state’s loop back to itself is the case where no if fires.
  • S as an event. PIND gives the level of the button, 1 on every pass while it is held. The diagram wants a push. Comparing each reading with the one before, s && !s_before, is true only on the pass where the reading goes from 0 to 1.
  • R as a level. r is used as it is read, and the two waiting states turn the level into “act on the release”.
  • Outputs from the state. timing, showing and the clearing of count are set from state and nothing else, which is what makes it a Moore machine.
  • cli() around count = 0. count is 16 bits, and an 8-bit processor writes it one byte at a time. Turning interrupts off for those two instructions keeps the handler from running in between and seeing half of the old value with half of the new (software-timers).
  • Reading the buttons once per tick also deals with contact bounce. A button’s contacts chatter for a few milliseconds as they close. With readings 10 ms apart, at most one of them can land in the chatter, so a push is still seen as a single change from 0 to 1.

In the simulator. Put a breakpoint on the first line of the handler and run. Each time the program stops there, the cycle counter should have advanced by 80 000, which is 10 ms at 8 MHz. If the breakpoint is never reached, one of the five set-up steps is missing. If the interval is wrong, check OCR1A and the prescaler bits.

Working — Exercises 2 and 3

With the buttons on external interrupts the hardware finds the edges, so the controller becomes the three-state machine of Figure 112 and each button’s handler is one of its inputs.

#include <avr/io.h>
#include <avr/interrupt.h>

#define RESET  0
#define RUN    1
#define STOP   2

uint8_t seven_seg[10] = { 63,6,91,79,102,109,125,7,127,111 };

volatile uint16_t count;              /* hundredths of a second */
volatile uint8_t  state = RESET;

/* every 10 ms */
ISR(TIMER1_COMPA_vect) {
    static uint8_t left = 0;
    uint8_t tenths;

    if (state == RUN) {               /* T */
        count++;
        if (count == 1000) {
            count = 0;
        }
    }

    tenths = count / 10;
    left = !left;
    if (state == RESET) {             /* D is 0 */
        PORTA = 0;
    } else if (left) {
        PORTA = seven_seg[tenths / 10] | 0x80;
        PORTD |= (1<<0);
    } else {
        PORTA = seven_seg[tenths % 10];
        PORTD &= ~(1<<0);
    }
}

/* Exercise 2. Start/stop: a rising edge on INT0 (PD2), the push */
ISR(INT0_vect) {
    if (state == RUN) {
        state = STOP;
    } else {
        state = RUN;                  /* from RESET or from STOP */
    }
}

/* Exercise 3. Reset: a falling edge on INT1 (PD3), the release */
ISR(INT1_vect) {
    state = RESET;
    count = 0;                        /* C */
}

int main(void) {
    DDRA = 0xFF;
    DDRD = (1<<0);

    OCR1A  = 9999;
    TCCR1A = 0;
    TCCR1B = (1<<WGM12) | (1<<CS11);
    TIMSK1 = (1<<OCIE1A);
    TIFR1  = (1<<OCF1A);

    /* INT0 on a rising edge  (ISC01:0 = 11)
       INT1 on a falling edge (ISC11:0 = 10) */
    EICRA = (1<<ISC01) | (1<<ISC00) | (1<<ISC11);
    EIMSK = (1<<INT0) | (1<<INT1);
    EIFR  = (1<<INTF0) | (1<<INTF1);

    sei();

    while (1) {
        /* nothing to do: the handlers do all the work */
    }
}

For Exercise 2 on its own, leave out the INT1 handler and the ISC11, INT1 and INTF1 bits.

Points to notice.

  • The main loop is empty. Nothing polls the buttons. The processor is only interrupted when something happens.
  • Push and release come from the edge chosen. Start/stop uses the rising edge, so it acts as the button goes down. Reset uses the falling edge, so it acts as the button comes up. Holding either one down produces no further edges, and so no further interrupts.
  • No cli() round count = 0 this time. Inside a handler interrupts are already off, so the timer handler cannot run in the middle of it.
  • Both at once. If both flags are set together, INT0 has the lower vector and runs first, then INT1 runs and resets. Reset wins, as the diagram says it should.
  • Why these two pins. INT0 and INT1 are fixed to PD2 and PD3. The buttons have to be wired there.
  • Bounce shows up here. An edge interrupt responds to every edge, and a bouncing contact makes several, in both directions. A bouncing push of S can start and stop the stopwatch at once, and so can a bouncing release, which makes rising edges too. A bouncing push of R makes falling edges, so the reset can happen on the push instead of the release. A cure is to keep a count of ticks that never stops (software-timers) and ignore an edge that comes within a few ticks of the last one on the same button.

Working — Exercise 4

To carry on past 9.9 s, the count has to run further and the display has to change what it shows. count is in hundredths of a second and is 16 bits wide, so it can go up to 99.99 s without any change of type.

In the timer handler, let the count run to 100 seconds:

    if (state == RUN) {
        count++;
        if (count == 10000) {          /* 99.99 s rolls over to 0.00 */
            count = 0;
        }
    }

and choose the two digits by range. This replaces tenths and the two lines that use it:

    uint8_t l, r;

    if (count < 1000) {                /* under 10 s: seconds and tenths */
        l = seven_seg[count / 100] | 0x80;
        r = seven_seg[(count / 10) % 10];
    } else {                           /* 10 s and over: whole seconds   */
        l = seven_seg[count / 1000];
        r = seven_seg[(count / 100) % 10];
    }

    left = !left;
    if (state == RESET) {
        PORTA = 0;
    } else if (left) {
        PORTA = l;
        PORTD |= (1<<0);
    } else {
        PORTA = r;
        PORTD &= ~(1<<0);
    }
count Time Left digit Right digit Shows
0 0.00 s count / 100 = 0, with point (count / 10) % 10 = 0 0.0
990 9.90 s 9, with point 9 9.9
1000 10.00 s count / 1000 = 1 (count / 100) % 10 = 0 10
1234 12.34 s 1 2 12
9999 99.99 s 9 9 99

The decimal point is what tells the two ranges apart on the display: 9.9 is followed by 10.

See also

Lab 13 — AVR PWM

Learning Lab 13: generating pulse width modulation from the timer/counters. Two programs come out of it. The first fades two LEDs with timer/counter 0, and the second plays a tone on a piezo buzzer with timer/counter 1, with push buttons changing its pitch and its duty cycle. The lab assumes Lab 12 (week8-lab-avr-timers). The ideas are in pulse-width-modulation and avr-timers-and-counters.

Facts to have ready

Five things the lab takes for granted, as quick checks.

Question Answer
How many timer/counters does the ATmega324A have? 3
What is the clock frequency? 8 MHz
How wide is each timer/counter? timer 0 is 8-bit, timer 1 is 16-bit, timer 2 is 8-bit
What is the largest value each can hold? timers 0 and 2: \(2^8 - 1 = 255\). Timer 1: \(2^{16} - 1 = 65535\)
Which pin is OC0B? PB4 (OC0A is PB3)

Fast PWM on timer/counter 0

The duty cycle of a waveform is the fraction of each period for which it is high. A pin toggled in CTC mode, as in Lab 12, is high for exactly half of every cycle, a duty cycle of 50 %, and nothing about it can be adjusted except the frequency. PWM is what makes the duty cycle adjustable.

In fast PWM the count, held in TCNT0, is a sawtooth: it climbs from 0 to a top value and drops back to 0. An output-compare register sets a level somewhere on the ramp. The output pin changes where the count crosses that level, and changes back when the count wraps. Moving the level moves the crossing, and that changes how much of each period the pin is high.

The waveform generation mode bits choose among all of a timer’s modes: normal, CTC and the PWM modes. Timer 0 has two fast PWM modes:

WGM02:0 Top of the count Compare registers free for PWM Frequency set by
011 (mode 3) 255, fixed OCR0A and OCR0B: two PWM outputs the prescaler only
111 (mode 7) the value in OCR0A OCR0B only: one PWM output the prescaler and OCR0A

Four things apply in both modes:

  • The waveform appears on the output-compare pin only if that pin’s DDR bit is set to make it an output.
  • The output can be non-inverting or inverting, chosen by the compare output mode bits.
  • The prescaler sets how fast the count climbs, and so the slope of the ramp.
  • The output-compare registers are double buffered. A new value written to one does not take effect until the next cycle begins, so a pulse is never cut short halfway through.

Figure 115: Fast PWM, one compare value, both polarities. The count ramps from 0 to TOP and wraps. In non-inverting mode the pin is set at the wrap and cleared at the compare match, so it is high for the first \(OCR + 1\) ticks of each period. In inverting mode it is the exact opposite, low until the match and high until the wrap. The two outputs are complements, and their duty cycles add up to 1.

The two formulas

Frequency: the master formula (avr-timers-and-counters).

\[f_{event} = \frac{f_{clk\_I/O}}{N \cdot (TOP + 1)}\]

\(f_{clk\_I/O}\) is 8 MHz, \(N\) is the prescaler, and \(TOP\) is either the largest value the register can hold or the value in OCRnA, depending on the mode. What “the event” is depends on the use:

Use \(f_{event}\) is
a pin set to toggle how often the pin toggles. The waveform is half that frequency, since one cycle needs a rise and a fall
PWM the frequency of falling edges in non-inverting mode, and of rising edges in inverting mode. That is the PWM frequency
an interrupt how often the handler runs

Duty cycle.

\[d.c._{nin} = \frac{OCRnx + 1}{TOP + 1} \qquad\qquad d.c._{inv} = 1 - \frac{OCRnx + 1}{TOP + 1} = 1 - d.c._{nin}\]

OCRnx is the compare register for the output in question, A or B.

The two formulas pull against each other in the choice of mode:

  • When TOP is OCRnA, the frequency can be set to almost anything, but OCRnA is used up setting it. Only OCRnB gives a meaningful duty cycle.
  • When TOP is a fixed constant (0xFF for the 8-bit timers, with several choices for the 16-bit timer), both OCRnA and OCRnB give a duty cycle. But the frequency can then be changed only through the prescaler, or for timer 1 through the choice of constant.

Timer 0’s control bits

Figure 116: Where timer/counter 0’s settings live. The compare output mode bits come in two pairs, one for each output pin, and both pairs are in TCCR0A. The waveform generation mode is one three-bit number split across the two registers, with its low two bits in TCCR0A and its top bit in TCCR0B. The clock select bits choose the prescaler, and while they are 000 the timer is stopped. Grey cells are unused.

These are on pages 109 to 113 of the datasheet. Clock select 110 and 111 take the clock from the T0 pin instead of the prescaler, which is how Lab 12 counted button presses. The compare output modes in fast PWM:

COM0x1:0 The pin OC0x
00 is disconnected from the timer: an ordinary port pin
01 OC0A toggles at each compare match, in mode 7 only. Not used for OC0B
10 non-inverting: cleared at the compare match, set at the wrap
11 inverting: set at the compare match, cleared at the wrap

Delay macros

#define F_CPU 8000000UL
#include <util/delay.h>

With these two lines, the macros _delay_ms() and _delay_us() are available. Each takes a constant number and makes the CPU do nothing for that many milliseconds or microseconds.

_delay_ms(10);     /* do nothing for 10 ms */

F_CPU has to be defined before the include, because the macros work out how many instructions to waste from the clock frequency. If it is missing the header only warns and assumes 1 MHz, and on this board every delay then runs 8 times too short. The macros are documented under <util/delay.h> in avr-libc.

This is busy waiting: the processor is fully occupied counting down and can do nothing else in the meantime. It is fine for a quick experiment and a bad habit for anything bigger. The alternative is a timer keeping time in the background (software-timers).

The tasks

NoteTask 1 — fade two LEDs

Complete lab13-1.c so that two LEDs fade on and off using PWM, one connected to OC0A and one to OC0B.

  • Work out the register values from pages 109 to 113 of the datasheet.
  • Build it, download it and test it. Predict which LED starts on and which starts off.
  • Change the clock prescaler to CLK/1024 and explain what you see.
NoteTask 2 — sound from the piezo buzzer

Complete lab13-2.c to generate sound on the piezo buzzer using PWM on timer/counter 1.

  • Connect the buzzer between OC1B and ground, and an LED to OC1B as well so that what is happening can be seen.
  • Push buttons vary both the frequency and the duty cycle.
  • The code uses 32-bit constants such as 105UL in places. Why are they necessary?
  • Challenge: show the duty cycle, 0 to 99, on the seven-segment display.

Working — Task 1

lab13-1.c comes with gaps to fill in. This is a complete program that does the job, to compare against.

The design. Fast PWM with TOP fixed at 255 (mode 3), because two outputs are needed and the frequency does not matter much. One compare value, level, is swept slowly from 0 up to 255 and back, and written to both compare registers. OC0A is made non-inverting and OC0B inverting, so as one LED brightens the other dims.

The register values.

Setting Bits Value
fast PWM, TOP = 255 WGM02:0 = 011 WGM01, WGM00 in TCCR0A. WGM02 stays 0
OC0A non-inverting COM0A1:0 = 10 COM0A1
OC0B inverting COM0B1:0 = 11 COM0B1, COM0B0
clock / 64 CS02:0 = 011 CS01, CS00 in TCCR0B

The PWM frequency is \(8\,000\,000 / (64 \times 256) = 488\ \text{Hz}\), far too fast to see.

#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    uint8_t level = 0;      /* compare value: 0 to 255          */
    int8_t  step  = 1;      /* +1 on the way up, -1 on the way down */

    /* OC0A is PB3 and OC0B is PB4: both must be outputs */
    DDRB |= (1<<3) | (1<<4);

    /* Fast PWM with TOP = 255; OC0A non-inverting, OC0B inverting */
    TCCR0A = (1<<COM0A1) | (1<<COM0B1) | (1<<COM0B0)
           | (1<<WGM01) | (1<<WGM00);

    /* Clock / 64.  This starts the timer. */
    TCCR0B = (1<<CS01) | (1<<CS00);

    while (1) {
        OCR0A = level;
        OCR0B = level;
        _delay_ms(5);                 /* 255 steps of 5 ms: about 1.3 s each way */

        if (level == 255) {
            step = -1;
        } else if (level == 0) {
            step = 1;
        }
        level += step;
    }
}

Which LED starts on? At the start level is 0.

  • OC0A, non-inverting: duty \(= (0 + 1)/256 \approx 0.4\,\%\). The LED on PB3 starts off.
  • OC0B, inverting: duty \(= 1 - 1/256 \approx 99.6\,\%\). The LED on PB4 starts on.

As level rises the first brightens and the second dims, they cross at half brightness, and at 255 they have swapped. The non-inverting output never reaches exactly 0 %: even with a compare value of 0 the pin is high for one tick in 256.

Figure 117: The fade in Task 1. The compare value is swept up from 0 to 255 and back down, about 1.3 seconds each way. The two outputs share that one value but have opposite polarity, so their duty cycles are mirror images: the LED on OC0A is brightest when the value is 255 and the LED on OC0B is brightest when it is 0. The dim end of each is one tick in 256 short of fully off.

With the prescaler at CLK/1024. Change the last register write to

    TCCR0B = (1<<CS02) | (1<<CS00);   /* clock / 1024 */

The PWM frequency drops to \(8\,000\,000 / (1024 \times 256) = 30.5\ \text{Hz}\). The eye can follow that. The LEDs flicker instead of dimming smoothly, most obviously when the duty cycle is low and the LED is giving short flashes thirty times a second. The fade itself takes just as long as before, because _delay_ms(5) sets its speed, not the timer. The duty cycle is unchanged as well. Only the PWM frequency has changed, and this is what shows that PWM dims an LED only when it is too fast to see.

The fade also turns into steps. A PWM period is now 32.8 ms, and a new compare value only takes effect at the start of a period, so of the values written every 5 ms only about one in six or seven is ever used.

Working — Task 2

lab13-2.c also comes with gaps. This is a complete program that meets the task.

The design. A tone needs a frequency that can be set freely, so this uses a fast PWM mode in which TOP is OCR1A. That leaves OCR1B for the duty cycle, which is why the buzzer goes on OC1B. Timer 1 is 16 bits wide, so one prescaler setting covers the whole audible range.

Setting Bits Where
fast PWM, TOP = OCR1A WGM13:0 = 1111 (mode 15) WGM11, WGM10 in TCCR1A; WGM13, WGM12 in TCCR1B
OC1B non-inverting COM1B1:0 = 10 COM1B1 in TCCR1A
clock / 8 CS12:0 = 010 CS11 in TCCR1B

With the prescaler at 8 the timer counts at 1 MHz, one tick per microsecond. For a tone of frequency \(f\):

\[\text{period in ticks} = \frac{1\,000\,000}{f} \qquad OCR1A = \text{period} - 1 \qquad OCR1B = \frac{\text{duty} \times \text{period}}{100} - 1\]

The first is the master formula rearranged, and the last is the duty-cycle formula rearranged, with the duty as a percentage. At 200 Hz the period is 5000 ticks, so OCR1A is 4999, and a 50 % duty cycle makes OCR1B 2499.

Figure 118: The two settings of Task 2 and what each one changes. OCR1A is the top of the count, so it sets the length of the period and with it the pitch. OCR1B sets how much of each period the pin is high, the duty cycle. Halving the period while keeping the duty cycle at 50 percent gives the middle waveform, an octave higher. Keeping the period and narrowing the pulse to 25 percent gives the bottom one, the same pitch with less energy.

The program. Four push buttons on port C: PC0 raises the frequency and PC1 lowers it, PC2 raises the duty cycle and PC3 lowers it. The buttons read 1 while pressed, and each press counts once.

#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>

uint16_t freq = 200;     /* Hz                      */
uint8_t  duty = 50;      /* percent, 0 to 99        */

/* Load the timer from freq and duty.  The timer counts at 1 MHz. */
void update_pwm(void) {
    uint16_t period = 1000000UL / freq;                   /* ticks per cycle */
    uint16_t width  = (duty * (uint32_t)period) / 100;    /* ticks high      */

    OCR1A = period - 1;                 /* TOP: sets the frequency           */
    if (width == 0) {
        TCCR1A &= ~(1<<COM1B1);         /* 0 %: hand the pin back to PORTD   */
    } else {
        OCR1B = width - 1;              /* high for OCR1B + 1 ticks          */
        TCCR1A |= (1<<COM1B1);
    }
}

int main(void) {
    uint8_t now, before = 0, pressed;

    DDRD |= (1<<4);                     /* OC1B is PD4                       */
    PORTD &= ~(1<<4);                   /* low whenever the timer lets go    */
    DDRC &= 0xF0;                       /* PC0 to PC3 are the buttons        */

    update_pwm();                       /* load OCR1A and OCR1B first        */

    /* Fast PWM with TOP = OCR1A (mode 15), OC1B non-inverting, clock / 8 */
    TCCR1A = (1<<COM1B1) | (1<<WGM11) | (1<<WGM10);
    TCCR1B = (1<<WGM13) | (1<<WGM12) | (1<<CS11);   /* this starts the timer */

    while (1) {
        now = PINC & 0x0F;
        pressed = now & ~before;        /* buttons that have just gone down  */
        before = now;

        if (pressed & (1<<0)) { freq = freq * 105UL / 100; }   /* up 5 %    */
        if (pressed & (1<<1)) { freq = freq * 100UL / 105; }   /* down 5 %  */
        if (pressed & (1<<2)) { duty = (duty >= 95) ? 99 : duty + 5; }
        if (pressed & (1<<3)) { duty = (duty == 99) ? 95 : (duty >= 5 ? duty - 5 : 0); }

        if (freq < 20)    { freq = 20; }
        if (freq > 10000) { freq = 10000; }

        if (pressed) {
            update_pwm();
        }
        _delay_ms(10);                  /* ride out contact bounce           */
    }
}

Why the UL constants are needed. On the AVR an int is 16 bits. In freq * 105 / 100 both operands would be 16-bit, the multiplication would be done in 16 bits, and the result would overflow as soon as freq passed \(65535 / 105 = 624\) Hz. A tone of 1000 Hz would give \(105\,000\), which wraps to 39 464, and the “5 % higher” frequency would come out as 394 Hz. Writing 105UL makes the constant an unsigned long, 32 bits, so the compiler does the whole multiplication in 32 bits and only the final result is narrowed back to 16. The suffix matters on the constants that would fit in an int, 105UL and 100UL. On 1000000UL it is harmless but not needed, since a number too big for an int is given a 32-bit type anyway. The (uint32_t) cast in the width calculation does the same job as the suffix, where duty * period can reach nearly five million (c-language-basics: an int is 16 bits on the AVR).

Other points.

  • The pin still needs DDRD. The timer decides the pin’s value. The DDR bit decides whether the pin drives anything.
  • Changing the values while it runs. Each compare register is double buffered: a new value is held back and loaded when the count wraps, so a pulse already under way is not disturbed. The two registers are written a few instructions apart, so at worst one period uses the new OCR1A with the old OCR1B, which is one odd cycle of a tone. Disconnecting the pin for 0 % is not buffered and takes effect at once.
  • Load the compare registers before starting the timer. main calls update_pwm() first, so the timer never runs with OCR1A still at 0.
  • 0 % is a special case. In non-inverting fast PWM the pin is high for OCR1B + 1 ticks, which is at least one. For a true 0 % the function disconnects the pin from the timer, and the port bit, set to 0, holds it low.
  • The lowest frequency. With the prescaler at 8, the longest period is 65 536 ticks, about 15 Hz. The program stops at 20 Hz.
  • What duty cycle does to a tone. The pitch depends only on the frequency. The duty cycle changes the loudness and the character of the sound, and is loudest near 50 %. On the LED it shows as brightness.

Challenge: the duty cycle on the seven-segment display. The two-digit multiplexing of Lab 12 fits into the main loop, which already comes round every 10 ms. Show one digit per pass: the display is on port A, with the digit select CC on PD0 (seven-segment-display).

uint8_t seven_seg[10] = { 63,6,91,79,102,109,125,7,127,111 };
uint8_t left = 0;

/* in main, before the loop */
DDRA = 0xFF;
DDRD |= (1<<0);

/* in the loop, once per pass */
if (left) {
    PORTA = seven_seg[duty / 10];     /* tens  */
    PORTD |= (1<<0);                  /* CC = 1: left digit  */
} else {
    PORTA = seven_seg[duty % 10];     /* ones  */
    PORTD &= ~(1<<0);                 /* CC = 0: right digit */
}
left = !left;

Each digit is refreshed 50 times a second, which is just fast enough to look steady. Shortening the delay to 5 ms makes it more comfortable.

Next

Lab 14 has a preparation task, to be done before the session (week9-lab-avr-interrupts).

See also

Week 10

Lecture 19 — More I/O

Two more ways for a microcontroller to talk to other chips, and the habits that make I/O code correct and readable. The first half is about buses: which device is in charge of a transfer, the two-wire I²C bus (TWI on the AVR), and SPI, a synchronous serial bus built from two shift registers joined in a ring, with the ATmega324A’s SPI port, its pins and its clock rates, and bit bashing for when the hardware is missing. The second half is AVR I/O coding: volatile for variables an interrupt handler changes, and setting, clearing and toggling bits of I/O registers by name. The reference notes are serial-communication, avr-spi, bit-masking and avr-io-ports.

Goals

  • Say what makes a device a bus master or a bus slave, and why memory is always a slave.
  • Describe the I²C bus and find the ATmega324A’s TWI pins.
  • Explain how SPI sends a byte each way at once, using two shift registers joined in a ring.
  • Connect several SPI slaves to one master, with a select line each or as a daisy chain.
  • Find the SPI pins on the ATmega324A and work out an SPI clock rate from its divider.
  • Say what bit bashing is and when it is the answer.
  • Declare a variable volatile when an interrupt handler changes it, and say what the optimiser does otherwise.
  • Set, clear and toggle single bits of an I/O register, with the bits named.

Bus masters and slaves

When several devices share wires, one of them has to decide when a transfer happens and which way it goes.

  • The master is the device that initiates and controls the transfer of data. It decides when a transfer starts and which device it is with, and on a synchronous bus it also drives the clock.
  • A slave waits for requests and responds to the master. It never starts a transfer of its own.

The roles belong to a transfer, not to a device for all time. Some devices can be masters and slaves, at different times. The ATmega324A’s SPI port and its TWI port can each be set up as either.

Memory can never be a bus master. It only ever answers a read or a write of an address that something else has chosen. On the AVR’s memory bus the CPU is the master and the memories are slaves.

Check. A CPU, a memory chip and an ATmega324A’s SPI port are on buses together. Which of them could start a transfer? The CPU, always. The SPI port, when it is set up as a master. The memory, never: it has no way to begin anything, only to answer.

I²C and TWI

I²C is the Inter-Integrated Circuit bus, created by Philips Semiconductor, now NXP. TWI, the Two-wire Interface, is the name Atmel uses for it. Both are synchronous serial: one of the wires is a clock (serial-communication).

Every device on the bus, device 1 to device n, connects to the same two wires:

Wire Carries
SDA serial data, in either direction
SCL serial clock, driven by the master

Two wires serve many devices, and adding one adds no wires. The price is that every device sees every transfer, so the master begins each one by sending the address of the slave it wants, and the others ignore it. With one data wire, data goes one way at a time. The bus is drawn, with the pull-up resistors that make the sharing work, in serial-communication.

TWI on the ATmega324A

  • The ATmega324A has one TWI port.
  • Its two wires are an alternate use of two port C pins: PC0 is SCL and PC1 is SDA. While the TWI is switched on, those pins belong to it, not to PORTC.
  • The datasheet describes the TWI in full on pages 211 to 239.

SPI

SPI is the Serial Peripheral Interface. The master and the slave each hold an 8-bit shift register (shift-registers), and the wires join the two registers into one ring. There are four signals:

Signal Driven by Carries
SCK (also written SCLK) master the serial clock, one pulse per bit
MOSI master Master Out, Slave In: data to the slave
MISO slave Master In, Slave Out: data to the master
\(\overline{\text{SS}}\) master Slave Select, active low: 0 selects the slave

Figure 119: SPI as two 8-bit shift registers joined in a ring. Each pulse of SCK, made by the master’s clock generator, shifts both registers one place towards the MSB. At the slave, SCK is the register’s shift enable, so the slave’s register moves only when a pulse arrives from the master. The master’s MSB leaves on MOSI and enters the slave at its LSB, while the slave’s MSB leaves on MISO and enters the master at its LSB. After eight pulses the two bytes have changed places, so every transfer moves a byte in each direction. The dashed lines are the edges of the two chips, with the pin names just inside them and the wiring between. The slave’s \(\overline{\text{SS}}\) is tied to ground, so it is always selected; the master’s own \(\overline{\text{SS}}\) is tied to \(V_{CC}\), which keeps it a master.

How the ring moves a byte. On each clock pulse both registers shift one place towards the MSB, at the same moment. At the slave, SCK is the register’s shift enable: the slave’s register moves only when a pulse arrives from the master. The bit that falls off the master’s MSB end goes out on MOSI and into the slave’s LSB end; the bit that falls off the slave’s MSB end goes out on MISO and into the master’s LSB end. Neither register gains or loses anything overall: the two of them are a single 16-bit register rotating. After eight pulses every bit has moved eight places, which carries the master’s byte entirely into the slave and the slave’s byte entirely into the master.

So every SPI transfer is an exchange. To read a byte from a slave the master has to send one, even a meaningless one, and every byte sent brings one back, which the master may simply ignore.

The master’s clock generator decides when every bit moves, so the slave never has to time a bit for itself, and nothing has to be agreed about speed beyond the fastest the slave can follow. That is the advantage of a synchronous link over a UART, where both ends must be set to the same baud rate beforehand.

Worked: one exchange

The master’s register holds 0x4D and the slave’s holds 0x73, most significant bit first. What travels on each data wire, and what does each register hold after eight clocks?

MOSI carries the master’s byte, MSB first: 0 1 0 0 1 1 0 1. MISO carries the slave’s: 0 1 1 1 0 0 1 1. After eight clocks the master holds 0x73 and the slave holds 0x4D. The register contents after each clock are tabulated in avr-spi.

Several slaves

One master can drive several slaves, wired in either of two ways.

Figure 120: Two ways to give one SPI master three slaves. Left, independent selects: SCK and MOSI go to every slave, every slave’s MISO joins the one wire back to the master, and each slave has a select line of its own. The master pulls one select low at a time, and a slave that is not selected lets go of MISO, which is what lets them share it. Right, a daisy chain: one select line goes to all three, and the data goes through them in turn, from the master’s MOSI into slave 1, out of each slave’s MISO into the next one’s MOSI, and from the last slave’s MISO back to the master. A dot is a connection; lines that cross without a dot are not connected.

Independent selects. SCK and MOSI go to every slave, and all the slaves’ MISO pins share the one wire back. Each slave gets its own select line, \(\overline{\text{SS1}}\), \(\overline{\text{SS2}}\), \(\overline{\text{SS3}}\), and the master pulls exactly one of them low for a transfer. An unselected slave ignores the clock and lets go of MISO, so only the selected one drives it. Each extra slave costs the master one more pin.

Daisy chain. One select line for all of them, and the data passes through each slave on its way round: master MOSI to slave 1, each slave’s MISO to the next slave’s MOSI, the last slave’s MISO back to the master’s MISO. The registers now make one long ring, 8 bits for the master and 8 more for each slave. It needs no extra pins however many slaves there are, but every transfer goes through all of them.

Worked: loading a daisy chain

Three slaves are daisy-chained and the master wants 0xA1 in slave 3, 0xB2 in slave 2 and 0xC3 in slave 1. In what order does it send the bytes, for how many clocks, and what comes back?

Each byte sent pushes every byte already in the chain one slave further along, so the byte meant for the farthest slave has to go first: 0xA1, then 0xB2, then 0xC3, with \(\overline{\text{SS}}\) held low for all 24 clocks. After the first 8, 0xA1 is in slave 1; the next 8 push it to slave 2 and put 0xB2 in slave 1; the last 8 push it to slave 3. What comes back to the master is what the slaves held before, the farthest slave’s old byte first: if they held 0x11, 0x22 and 0x33, the master receives 0x33, 0x22, 0x11. The step-by-step picture is in avr-spi.

SPI on the ATmega324A

  • The ATmega324A has one SPI port.
  • It shares pins with the upper half of port B: PB4 is \(\overline{\text{SS}}\), PB5 is MOSI, PB6 is MISO and PB7 is SCK.
  • The hardware generates the signals. The program writes one byte; the port makes the eight clock pulses and does the shifting by itself.
  • It can be a master or a slave, chosen by a bit in its control register.
  • The datasheet covers it on pages 166 to 174.
  • The USARTs can also be used as SPI masters, which gives the chip up to three (avr-spi).

Inside the chip the SPI block is wired to port B, the TWI block to port C, and the two USARTs to port D, apart from USART0’s clock pin on port B (the chip’s other blocks are in avr-architecture). The pins are:

Figure 121: The ATmega324A’s 40 pins, with the serial interfaces marked. Each pin is named for its port bit, and the boxed names are the alternate uses that matter here. The SPI port is the upper half of port B, PB4 to PB7. The TWI is PC0 and PC1. USART0 receives and transmits on PD0 and PD1, and USART1 on PD2 and PD3; XCK0 and XCK1 are the USARTs’ clock pins, which is where the clock comes out when a USART works as an SPI master. Whichever interface is switched on takes its pins over from the port.

The datasheet’s pinout is shared with bigger chips in the same family, and some pins also list functions of a fourth timer (T3, ICP3, OC3A, OC3B) that the ATmega324A does not have, just as its block diagram shows a 16-bit T/C 3 (2026-08-27-avr-introduction).

The SPI clock rate

As a master, the AVR makes SCK by dividing its own clock, and the divider can be chosen. With the 8 MHz clock:

Divider SCK
2 4 MHz
4 2 MHz
8 1 MHz
16 500 kHz
32 250 kHz
64 125 kHz
128 62.5 kHz

As a slave, the fastest SCK it can follow is \(f_{OSC}/4\), 2 MHz at 8 MHz. A slave does not run its SPI logic from SCK directly. It samples the incoming SCK with its own clock, and each high and each low half of SCK has to last a couple of its own clock cycles to be seen reliably. Which bits choose the divider is in avr-spi.

Worked: how long does a byte take?

A byte is 8 SCK periods, and each period is divider CPU clock cycles.

Divider CPU cycles per byte Time per byte at 8 MHz
2 \(8 \times 2 = 16\) 2 µs
16 \(8 \times 16 = 128\) 16 µs
128 \(8 \times 128 = 1024\) 128 µs

For comparison, one 8N1 UART frame at 9600 baud takes \(10 / 9600 \approx 1.04\) ms, about 500 times as long as an SPI byte at the fastest rate.

Worked: two AVRs

Two ATmega324As, both on 8 MHz clocks, are joined by SPI. What is the fastest master setting that works? The slave can follow at most \(8\text{ MHz}/4 = 2\) MHz, so the master’s divider must be 4 or more. Divider 2 gives 4 MHz, which a master can produce but this slave cannot follow.

Bit bashing

Sometimes a microcontroller has no hardware support for a bus standard, or not enough interfaces of that standard: a second SPI bus wanted on a chip with one SPI port, say. The standard can then be simulated with general purpose port pins. The program drives each output pin and reads each input pin itself, one edge at a time, in the order the standard lays down. This is bit bashing, also called bit banging.

For an SPI master, each of the eight bits is four steps on ordinary pins: put the next bit on the MOSI pin, raise the SCK pin, read the MISO pin, lower the SCK pin. The code, and what it costs, are in serial-communication.

Bit bashing suits a synchronous standard well. The master makes the clock, so if the program is held up between two edges, by an interrupt for instance, the transfer just pauses and nothing goes wrong. An asynchronous standard such as a UART has no clock to wait for, so a bit-bashed UART has to time every bit exactly.

Worked: one SPI port, two SPI buses

A design on the ATmega324A needs to be the master on two separate SPI buses, and the SPI port is already in use for one of them. What are the options for the other?

  • A USART in master SPI mode. Hardware does the shifting, as with the SPI port, on the USART’s XCK, TXD and RXD pins (avr-spi).
  • Bit bashing on any three spare port pins, plus one for the select. It works anywhere, but the CPU does all of the work and the bus runs much slower.

If the second “bus” is really just more slaves, neither is needed: one SPI port drives several slaves through separate select lines.

AVR I/O coding

Volatile variables

volatile int running;

volatile tells the compiler that the variable can change outside the standard flow of control: in an interrupt handler, or in another thread. The compiler must then not apply the optimisations that assume only the code in front of it changes the variable. Every read in the source becomes a real read of memory, and every write a real write.

Worked: a loop that never ends

A button on INT0 is meant to start the program running:

volatile int running;

ISR(INT0_vect) {
    running = 1;              /* the button has been pushed */
}

int main(void) {
    /* ... set up INT0 for the button, then sei() ... */
    running = 0;
    while (!running) {
        ;                     /* do nothing until the button is pushed */
    }
    /* carry on */
}

What does an optimising compiler do with the loop if running is declared without volatile?

It changes the loop to

while (1) {
    ;
}

The compiler looks at main on its own. It has just set running to 0, and nothing inside the loop writes running, so as far as it can tell !running is true every time and testing it again is wasted work. The handler is a separate function that main never calls, so its write is invisible to that reasoning. The result is a program that never leaves the loop, however often the button is pushed. With volatile, each test of !running reads the variable from memory, and the first test after the handler has run sees 1 and the loop ends.

The register names PINC, PORTA and the rest are volatile for the same reason: a pin can change without the program changing it (c-preprocessor-and-avr-headers). On this 8-bit CPU a one-byte uint8_t is a better type for a flag than int, because it is read in a single instruction and an interrupt cannot land halfway through (avr-interrupts). The two-column picture of what volatile changes is in 2026-09-21-interrupts.

Setting I/O register bits

When setting or clearing particular bits of an I/O register, be explicit about which bits. These three lines all have the same effect:

Code What the reader has to do
Poor TCCR1B = 10; convert 10 to binary, then look up what each 1 is
Better TCCR1B = 0x0A; read the bits off the hex, then look them up
Best TCCR1B = (1<<WGM12)\|(1<<CS11); nothing: the two bits being set are named
Worked: are they really the same?

\(10 = 8 + 2\), which is 0000 1010, which is 0x0A. In TCCR1B, WGM12 is bit 3 and CS11 is bit 1, so

\[(1 \ll 3)\ |\ (1 \ll 1) = \texttt{0000 1000}\ |\ \texttt{0000 0010} = \texttt{0000 1010}\]

All three are the same byte, and since the compiler works out (1<<WGM12)|(1<<CS11) while compiling, all three produce the same machine code. The readable form costs nothing.

And what does it do? WGM12 = 1, with WGM13 cleared by the same write and WGM11:10 left at 0 in TCCR1A, makes WGM13:0 = 0100: CTC mode with the top of the count in OCR1A. CS12:0 = 010 divides the clock by 8. It is the set-up for the 10 ms tick in week9-lab-avr-interrupts (avr-timers-and-counters). The best form says so to anyone who knows the bit names. The poor form says nothing.

Where the names come from

The register and bit names are the datasheet’s. Each register is drawn in its section of the datasheet with its address and its bits. The datasheet has errors in places, so check a name against the I/O register summary at the back before trusting it. The SPI port is a case in point: its own chapter calls the enable bit SPE and the master bit MSTR, but the names that compile are SPE0 and MSTR0, which is how the summary writes them (avr-spi). For timer/counter 0’s TCCR0B, on page 112:

Figure 122: Timer/counter 0’s control register B in the datasheet’s three-row form: bit numbers above, names in the boxes, then whether each bit can be read or written and its value after reset. The register is I/O register 0x25, data address 0x45. Bits 5 and 4, shaded grey, are unused and read as 0; the two FOC bits can only be written. Each bit name is defined in the device header as its bit number, so WGM02 is 3 and CS01 is 1, and shifting 1 left by that number puts a 1 in the named column. The two outlined columns follow each name up through its bit number to its 1 in the top row: ORed together, (1<<WGM02)|(1<<CS01) is 0000 1010, which is 0x0A.

Bit names are macros, defined in the device header that <avr/io.h> pulls in:

#define WGM02 3

A bit name is the bit’s number, not its mask. That is why it is always written (1<<WGM02): the shift turns the number 3 into the mask 0000 1000.

The same names work in assembly, where the assembler works out the expression:

    ldi  r16, (1<<WGM02)|(1<<CS01)
Worked: what does that load?

WGM02 is 3 and CS01 is 1, so the constant is 0000 1000 | 0000 0010 = 0x0A, and the instruction in flash is simply ldi r16, 0x0A. To put it in the register takes out TCCR0B, r16, which works because TCCR0B is I/O register 0x25, inside the 64 that out can reach (avr-io-ports).

It is the same byte as TCCR1B = 0x0A above, and it shows why the names matter. In TCCR1B, bit 3 is WGM12, one bit of timer 1’s four-bit mode, and 0x0A gives CTC. In TCCR0B, bit 3 is WGM02, the top bit of timer 0’s three-bit mode, and with TCCR0A’s two mode bits at 0 it makes the mode 100, which is reserved: no use at all. Timer 0’s CTC mode is WGM01, in TCCR0A. A bit name means something only in its own register, and (1<<WGM12) written into TCCR0B would quietly set WGM02, because both are bit 3.

Figure 123: One byte, two registers, two meanings. The byte 0x0A has its 1s in bits 3 and 1, outlined. In TCCR1B those bits are WGM12 and CS11; in TCCR0B the same positions are WGM02 and CS01, because bit names are only bit numbers. The clock select field lines up in both, so the clock is divided by 8 either way. The mode does not: with the mode bits in TCCR1A and TCCR0A left at 0, bit 3 makes timer 1’s four-bit mode 0100, CTC, and timer 0’s three-bit mode 100, a reserved code that should not be used. Unused bits are shaded grey.

Clearing and toggling I/O register bits

The same rules apply: name the bit, and change only that bit.

PORTC &= ~(1<<5);         /* clear bit 5 of port C's output: PC5 driven low   */
TIMSK2 ^= (1<<OCIE2A);    /* toggle the timer 2 output compare A interrupt enable */
  • To clear a bit, AND with a mask that has a 0 on that bit and 1s everywhere else. ~(1<<5) is the complement of 0010 0000, which is 1101 1111. ANDing with 1 keeps a bit and ANDing with 0 clears it.
  • To toggle a bit, XOR with a mask that has a 1 on that bit. OCIE2A is bit 1 of TIMSK2, so the mask is 0000 0010. XOR with 1 flips a bit and XOR with 0 keeps it.
  • To set a bit, OR with a 1 on it, as above.

Each of these reads the register, changes one bit and writes it back, leaving the other seven alone. Set, clear and toggle side by side on one byte are drawn in bit-masking.

Worked: clear bit 5 of port C

Which register does the clear go to?

PORTC, the register that holds the values port C drives: PORTC &= ~(1<<5); makes PC5 go low and leaves the other seven outputs as they were. Not PINC. PINC holds the levels on the pins, it is not a store, and on this chip writing a 1 to a bit of PINC toggles the matching bit of PORTC. PINC &= ~(1<<5) reads the pins, clears bit 5 of that reading and writes it back, which flips every other output that happened to read high and leaves PC5 alone: the opposite of what was wanted. The details are in avr-io-ports.

Worked: does this line enable the interrupt?
/* enable output compare A interrupt for timer 2 */
TIMSK2 ^= (1<<OCIE2A);

Only if it was off. XOR flips the bit. If OCIE2A was 0 this sets it and the interrupt is enabled; if it was already 1, the same line clears it and disables the interrupt. Run twice, it undoes itself. To enable, whatever the bit was before, set it:

TIMSK2 |= (1<<OCIE2A);    /* enable  */
TIMSK2 &= ~(1<<OCIE2A);   /* disable */

Toggling is for things that are meant to alternate, like blinking an LED with PORTC ^= (1<<0); from a timer handler.

See also

Lecture 20 — Assembly Process

Assembly language is more than instructions, and turning it into machine code takes more than translating one line at a time. This covers the four fields of a statement, the directives that speak to the assembler instead of the CPU, the AVR’s three memory segments, and the two-pass assembler that gets round the forward reference problem. Two programs are traced to find the address every label is given. The reference note is assembly-process. The program skeleton it all fits into is avr-program-structure, and the memories behind the segments are in memory-models.

Goals

  1. See that an assembly program holds more than instructions: directives tell the assembler where things go and what names mean.
  2. Know the AVR’s memory segments and which directives put what in each.
  3. Understand how an assembly program becomes machine code, and why the assembler reads the source twice.
  4. Be able to work out by hand the address each label is given.

Where assembly sits

The six levels of a computer are in 2026-07-27-course-intro-bits-bytes-binary. There are two roads down to machine code:

Each instruction on its own has a fixed binary form, its machine code (avr-instructions). That leaves two questions: what else goes in an assembly program, and how does the assembler turn a whole program into machine code?

The four fields of a statement

A statement has four parts, called fields:

formula:   ldi r20, i       ; register r20 = i
Field Here What it is
label formula: a name for the address this statement lands at
operation (opcode) ldi the mnemonic
operand(s) r20, i what the operation works on
comment ; register r20 = i explanation, ignored by the assembler

The fields are drawn one by one in assembly-process.

  • Labels are needed so that statements can be jumped to, and so that data can be referred to. The label’s value is an address: formula is the address of that ldi. A label usually starts in column 1, with everything else indented.
  • The operation is a symbolic abbreviation for the opcode, for example LDS, Load Direct from data Space.
  • The operand field gives the addresses and registers the instruction uses. Register names vary from machine to machine: the Pentium has eax, ebx, esi, edi and so on; SPARC has o0..o7, i0..i7, l0..l7 and g0..g7; the AVR simply has r0..r31.
  • The comment is for people only, and in assembly it is vital: the instructions say what happens, never why.
  • Some assemblers require a semicolon to end each statement and some do not. The AVR’s does not, and there a semicolon begins a comment.

Directives

The assembler needs information that is not an instruction:

  • where in memory the program and its data should go;
  • nicer names to use for registers and addresses, such as temp or SPH.

That information is a command to the assembler itself, a pseudo-instruction or directive. Directives are preceded by a dot: .byte reserves space for a variable, and .def temp = r16 lets the program say temp for register r16.

Memory segments

To the assembler, the different types of memory are segments, and directives choose which segment code and data go into. The AVR has three:

Segment Directive Memory What goes there
data .dseg RAM (SRAM) nothing can be placed: only space reserved, for variables
code .cseg flash program code or constant data
EEPROM .eseg EEPROM constants

One source file can switch between segments as often as it likes. Each piece goes to its own memory, and pieces of the same segment are joined end to end, as Figure 124 below shows for data and assembly-process shows for all three.

The directives

The assembler in Microchip Studio (formerly Atmel Studio) is AVRASM2. It has these directives, among others:

Kind Directives
choosing a segment .cseg code, .dseg data, .eseg EEPROM; .csegsize sets the program memory size
reserving and defining data .byte reserves bytes for a variable; .db defines constant bytes; .dw defines constant words
naming .def gives a register a symbolic name; .equ sets a symbol to an expression; .set does the same but can be changed
placing .org sets the program origin, the location counter
files .include reads source from another file; .exit stops reading this one
list file .list and .nolist turn list-file generation on and off; .listmac shows macro expansions in it
macros .macro begins one; .endm or .endmacro ends it
conditional assembly .if opens a block that is assembled only when its condition holds; .else, .elif and .endif continue and close it

Each is described in assembly-process.

Reserving space and defining constants

.byte reserves space, and it is allowed only in the data segment.

.cseg and .dseg let the code and data segments be built up in pieces: switching back to a segment carries on where it left off.

Worked: a data segment built in pieces

Where do amount and count go?

        .dseg
amount: .byte 2
        .cseg
formula: ...
        .dseg
count:  .byte 2

The data counter starts at 0x0100 (256), the first SRAM address after the 32 registers, the 64 I/O registers and the 160 extended I/O registers.

  1. .dseg: use the data counter, at 0x0100.
  2. amount = 0x0100. .byte 2 reserves 0x0100 and 0x0101; the counter moves to 0x0102.
  3. .cseg: formula and whatever follows it go to program memory, under the code counter. The data counter is left alone at 0x0102.
  4. .dseg: back to the data counter, still 0x0102.
  5. count = 0x0102 (258). It reserves 0x0102 and 0x0103, and the counter ends at 0x0104.

So count sits immediately after amount in SRAM, although the code for formula lies between them in the file.

Figure 124: A data segment built in two pieces. The data counter starts at 0x0100, just past the registers and the I/O registers, so amount gets the two bytes there. The code in the middle of the file goes to program memory under the code counter and does not move the data counter, so when the file returns to the data segment count takes the next two bytes, 0x0102 and 0x0103. Nothing is written into these bytes: the assembler only gives out addresses, and the rest of SRAM up to 0x08FF stays free. Blue marks the data segment and grey the code segment.

.db initialises constants in the code or EEPROM segment, 8 bits each. .dw does the same with 16-bit words. Program memory is 16 bits wide, so .db bytes go two to a word, and an odd count is padded with a zero byte.

Worked: a lookup table

Where do the three tables go, and what is in each word?

        .cseg
table1: .db  11, 12, 30
table2: .dw  100, 133
        .org 500
table3: .dw  ...

With the code counter at 0:

  • table1 = 0. Word 0 holds 11 and 12; word 1 holds 30 and a pad 0. The counter moves to 2. Writing the pad as a fourth value, .db 11, 12, 30, 0, gives exactly the same two words, without the assembler’s padding warning.
  • table2 = 2. Word 2 is 100 and word 3 is 133. The counter moves to 4.
  • .org 500 sets the counter to 500, skipping words 4 to 499.
  • table3 = 500.

The layout is drawn in assembly-process.

Registers, devices and files

  • .def makes a definition, for registers only:

    .def  ZH=r31
    .def  ZL=r30
  • .device says exactly which processor the program is for, as in .device ATmega324A. The assembler then refuses any instruction that chip does not implement.

  • .include includes another file at that point, as .include "m324Adef.inc" does in every program so far (avr-program-structure).

  • .exit stops processing the file.

Symbols and the location counter

  • .equ equates a symbol to a value, and the value cannot be changed.

  • .set equates too, but the value can be changed by a later .set.

    .equ sreg      = 0x3f     ; Status register
    .set io_offset = 0x23     ; For now

    sreg is fixed for the whole file. io_offset is 0x23 for now: a later .set io_offset = ... replaces it from that line on.

  • .org sets the location counter, the address the next item will be placed at, in whichever segment is current.

All of these are the syntax of the assembler built into Microchip Studio. Other assemblers, even ones for the AVR, use different syntax: avr-gcc’s assembler reads .byte as “store these bytes”, not “reserve this many”.

The forward reference problem

An assembly program is a sequence of one-line statements, but the assembler cannot always read a statement and produce its machine code on the spot. add r1, r2 is fine: the opcode and both registers are known, so the word can be written immediately. A program’s first statement is usually

        jmp  RESET

and the RESET: label is further down. At the jmp, the assembler knows the opcode but not the operand: it has no address for RESET, so it cannot generate the instruction. This is the forward reference problem.

Figure 125: Why a single pass from top to bottom is not enough. The add names only registers, so its machine word is complete the moment the line is read. The jmp is two words: the first holds the opcode and can be written, but the second must hold the address of RESET, and RESET is defined further down. By the time the assembler reaches that definition and learns the address, the jmp is already behind it. Red marks the word that cannot be filled in yet and the line that supplies its value.

Two passes

The solution is to process the file twice.

  • Pass one defines all the symbols: labels, and the names made by .equ, .set and .def. It keeps a location counter for each segment and records every symbol’s value in a symbol table. It does not need any operand to do this, only each statement’s size.
  • Pass two starts again from the top. The values of all the symbols are now known, so it can assemble each instruction, which means producing the actual machine code.

The pipeline is drawn in assembly-process.

Worked: the two-pass example

At what program address will the instruction at label RESET be placed, and what are the other symbols’ values?

        .equ    RAMEND = $08FF
        .equ    SPH = $3E
        .equ    SPL = $3D
        .def    ZH = r31
        .def    ZL = r30
        jmp     RESET
        .dseg
var1:   .byte   2
var2:   .byte   2
        .cseg
        .def    temp = r16
mesg:   .db     72,101,108,108,111
table:  .dw     var1, var2
RESET:  ldi     temp, low(RAMEND)
        out     SPL, temp
        ldi     temp, high(RAMEND)
        out     SPH, temp
        ...
        ldi     ZH, high(mesg*2)
        ldi     ZL, low(mesg*2)
        lpm                     ;R0 <= M[Z]

Pass one, one line at a time. Code counter from 0 (in words), data counter from 256, 0x0100 (in bytes), EEPROM counter not used.

Line Segment Placed at Size Counter after Symbol table gains
.equ RAMEND = $08FF 0 RAMEND = 0x08FF
.equ SPH = $3E 0 SPH = 0x3E
.equ SPL = $3D 0 SPL = 0x3D
.def ZH = r31 0 ZH = r31
.def ZL = r30 0 ZL = r30
jmp RESET code 0, 1 2 words code 2
.dseg data 0 data 256
var1: .byte 2 data 256, 257 2 bytes data 258 var1 = 256
var2: .byte 2 data 258, 259 2 bytes data 260 var2 = 258
.cseg code 0 code 2
.def temp = r16 0 temp = r16
mesg: .db 72,101,108,108,111 code 2, 3, 4 5 bytes + pad = 3 words code 5 mesg = 2
table: .dw var1, var2 code 5, 6 2 words code 7 table = 5
RESET: ldi temp, low(RAMEND) code 7 1 word code 8 RESET = 7
out SPL, temp code 8 1 word code 9
ldi temp, high(RAMEND) code 9 1 word code 10
out SPH, temp code 10 1 word code 11

The data counter runs 256, 258, 260, and the code counter 0, 2, 5, 7 and on.

The instruction at RESET is at program address 7. The full table, and the trace drawn line by line, are in assembly-process.

Symbol Segment Value
RAMEND 0x08FF
SPH 0x3E
SPL 0x3D
ZH r31
ZL r30
RESET code 7
var1 data 256
var2 data 258
temp r16
mesg code 2
table code 5

RESET can go in the table the moment the jmp mentions it, with its value left blank until RESET: turns up; the finished table is the same either way.

Pass two fills in every operand:

  • jmp RESET becomes jmp 7, two words 0x940C 0x0007.
  • .dw var1, var2 writes the two data addresses, 256 and 258 (0x0100 and 0x0102), into words 5 and 6.
  • ldi temp, low(RAMEND) becomes ldi r16, 0xFF and ldi temp, high(RAMEND) becomes ldi r16, 0x08. With the two outs to SPL and SPH (I/O addresses 0x3D and 0x3E), they set the stack pointer to the top of SRAM (procedures-and-the-stack).
  • mesg*2 = 4, so ldi ZH, high(mesg*2) loads 0 and ldi ZL, low(mesg*2) loads 4. mesg is word 2, which starts at byte 4, and lpm wants a byte address in Z. It loads r0 with the byte there: 72, the H of Hello (memory-models).

Every encoded word is listed in assembly-process.

Worked: where does RESET land?

At what program address will the instruction at label RESET be placed?

        jmp RESET
        jmp ISR1
        jmp ISR2
.dseg
var1: .BYTE 1
var2: .BYTE 3
var3: .BYTE 2
.cseg
.def temp=r20
message1: .DB 72,101,111,111,0
message2: .DB 0,65,66,68,0
RESET:
        ldi temp, low(RAMEND)
        out SPL, temp
        ldi temp, high(RAMEND)
        out SPH, temp
  • A. 9
  • B. 12
  • C. 15
  • D. 18
  • E. None of the above

B, 12. Follow the code counter only:

  1. Three jmps at 2 words each: addresses 0, 2 and 4. The counter is at 6.
  2. The .dseg block moves the data counter: var1 = 0x0100, var2 = 0x0101, var3 = 0x0104, ending at 0x0106. The code counter does not move.
  3. .cseg returns to the code counter, still 6. .def takes no space.
  4. message1: 5 bytes, padded to 6, is 3 words: 6, 7 and 8. The counter is at 9.
  5. message2: another 5 bytes, padded to 6, so 3 words: 9, 10 and 11. The counter is at 12.
  6. RESET: labels the next instruction: 12.

\[\underbrace{3 \times 2}_{\texttt{jmp}} + \underbrace{3}_{\texttt{message1}} + \underbrace{3}_{\texttt{message2}} = 12\]

Figure 126: Program memory for the question, one 16-bit word per row, lowest address at the top. Each jmp takes two words, the opcode and the target address. Each .DB line of five bytes fills two and a half words, and the assembler pads the last half with a zero so the next line starts on a whole word. That puts message1 at 6, message2 at 9 and RESET at 12. The variables are in data memory under their own counter, so they take no program memory at all. Light grey marks instructions, blue the .DB bytes and the variables, and dark grey the pad bytes.

Each wrong answer matches a slip worth recognising:

  • A, 9, counts each jmp as one word: \(3 + 3 + 3\).
  • C, 15, lets the six bytes of variables into the code counter as three words: \(6 + 3 + 3 + 3\). The .dseg lines have their own counter and take no program memory.
  • D, 18, makes the same mistake with the six bytes as six words, \(6 + 6 + 3 + 3\), or gives every .DB byte a word of its own, \(6 + 6 + 6\) with the pads.
  • E would be right if the two strings were packed together with no padding between them, \(6 + 5 = 11\). The assembler pads each .DB line separately.

See also

Lab 16 — A/D and SPI

Learning Lab 16: two more of the ATmega324A’s peripherals, each with a device to drive. The analog to digital converter reads a joystick, and the SPI port sends commands to an LED matrix. Five tasks build from wiring the joystick up to an Etch-A-Sketch that draws on the matrix with it. The converter is in analog-to-digital-conversion, the SPI bus in avr-spi, the joystick and the LED matrix in io-board, and the timer used to pace the programs in avr-timers-and-counters. The lectures behind it are 2026-09-24-serial-io (Lecture 18) and 2026-10-05-more-io (Lecture 19).

Outline

  • The A/D converter, used to read the joystick
  • SPI, used to drive the LED matrix
  • One timer question, about a slow count for pacing a program
  • Five tasks, worked in full at the end

The A/D converter

The facts the lab relies on (analog-to-digital-conversion):

  • The port A pins can be used as analog inputs.
  • There is one converter, behind an analog multiplexer, so one input is converted at a time.
  • The reference voltage can be chosen. The lab uses the supply, \(V_{cc} = 5\ \text{V}\), which reaches the converter as AVCC.
  • The resolution is 10 bits: results from 0 to 1023.
  • A conversion takes time: up to 3200 clock cycles, 0.4 ms at 8 MHz. The converter runs on its own clock, and a conversion takes 13 of its cycles, 25 for the first one after it is switched on. At the slowest setting, the clock divided by 128, that first conversion is \(25 \times 128 = 3200\) cycles. A faster converter clock gives a quicker answer with fewer accurate bits.
  • So the program has to find out when a conversion has finished, either by polling the start bit ADSC, which reads 1 until the result is ready, or by taking the interrupt at the end of the conversion (polling-and-interrupts).

Worked: the ADC clock prescaler

The ADC clock needs to run between 50 kHz and 200 kHz for full precision. What are the bounds for the ADC clock prescaler?

A. 80 to 320 · B. 40 to 160 · C. 20 to 80 · D. 25 to 100 · E. 50 to 150 · F. 160 to 640 · G. 30 to 120 · H. 10 to 40

B. The ADC clock is the 8 MHz system clock divided by the prescaler \(N\), so

\[50\ \text{kHz} \le \frac{8\ \text{MHz}}{N} \le 200\ \text{kHz} \quad\Longleftrightarrow\quad \frac{8\ \text{MHz}}{200\ \text{kHz}} \le N \le \frac{8\ \text{MHz}}{50\ \text{kHz}} \quad\Longleftrightarrow\quad 40 \le N \le 160.\]

A bigger divisor gives a slower clock, so the upper frequency limit sets the lower bound on \(N\). The bounds are in the ratio 4 to 1 because the frequencies are, and most of the other options have that ratio too: A, C, D, F, G and H are the right answers for system clocks of 16, 4, 5, 32, 6 and 2 MHz. E, 50 to 150, is not in the ratio 4 to 1 and is right for no clock.

The prescaler only offers powers of two, 2 to 128, so two settings land in the window: 64, giving 125 kHz, and 128, giving 62.5 kHz. The programs below use 64, which puts the clock in the middle of the window and makes a conversion \(13 \times 64 = 832\) cycles, 104 µs.

Worked: the ADMUX value

What value needs to go in ADMUX to use AVCC as the reference voltage, right adjust the result and select input ADC1?

ADMUX holds three fields (analog-to-digital-conversion):

Field Bits Wanted Value
REFS1:0, reference 7, 6 AVCC 01
ADLAR, adjust 5 right adjusted 0
MUX4:0, input 4 to 0 ADC1 on its own 00001

Put together, 0100 0001, which is 0x41. In C, ADMUX = (1<<REFS0) | 1;, or (1<<REFS0) | (1<<MUX0).

Figure 127: The value 0x41 in ADMUX, bit by bit. The top two bits choose the reference voltage, and 01 means AVCC, the 5 V supply. Bit 5 chooses how the 10-bit result sits in its 16-bit register, and 0 means right adjusted, so it reads as a number from 0 to 1023. The bottom five bits choose the input, and 00001 is ADC1, pin PA1. The two shaded bits are the ones set.

The joystick

The joystick is a small board made to sit in the breadboard. Each axis is a potentiometer between its own supply pin and ground, and the stick moves the wiper, so each axis gives a voltage between 0 and 5 V (io-board):

Pin Connect to What it is
L/R+ and U/D+ VCC, 5 V, both of them the top end of each potentiometer
GND (two of them) GND, one is enough the bottom end of both
L/R (two of them) an analog input x: 0 V with the stick to the left, 5 V to the right
U/D (two of them) an analog input y: 0 V at the bottom, 5 V at the top

The pins come in pairs that are joined on the board, so only one L/R, one U/D and one GND need a wire. The two + pins are not joined to each other, so both need one.

Where it goes. At the right-hand end of the breadboard, leaving room for the microcontroller board and its programmer to the left. Turned the right way, the X arrow printed on the board points to the top of the breadboard. So the stick’s own left and right, the direction x measures, run along the breadboard from bottom to top, and its up and down run from right to left. The board’s pins are protected by a piece of black foam when it is not in use, which is worth keeping.

The programs below use PA0 (ADC0) for x and PA1 (ADC1) for y.

Figure 128: The joystick wired to the microcontroller. Each axis is a potentiometer from its own supply pin down to ground, and the stick sets the wiper, so the wiper voltage goes from 0 V to 5 V as the stick crosses from one side to the other. The two supply pins, L/R+ and U/D+, are separate and both go to VCC. The x output goes to PA0, which is analog input ADC0, and the y output to PA1, ADC1. The module’s second L/R, U/D and GND pins are joined to these inside it and are left unconnected.

Worked: the stick pulled down

The joystick is seen from above, turned a quarter turn clockwise from the way it sits in the breadboard, so that its L/R+ and U/D+ pins are at the top corners and its two GND pins at the bottom corners. That puts its own x axis across and its y axis up. The stick is pulled straight towards the bottom edge. What (x, y) should the ADC read?

A. (−511, 0) · B. (−511, 511) · C. (−511, 1023) · D. (0, −511) · E. (0, 511) · F. (0, 1023) · G. (511, −511) · H. (511, 0) · I. (1023, −511) · J. (1023, 0)

H, (511, 0). Straight down leaves x where it rests, in the middle, and takes y as low as it goes.

  • x is in the middle of its range. The wiper sits halfway, 2.5 V, and halfway through 0 to 1023 is 511.5. A reading of 511 or 512 both mean centred.
  • y is at the bottom of its range, 0 V, which reads 0.
  • No reading is negative. The converter’s result is an unsigned number from 0 to 1023, so every option with \(-511\) in it is out. Those are what a reading measured from the centre would look like, which a program can work out by subtracting 511, but the converter itself never reports.

Figure 129: Why the stick’s x runs across and its y runs up in this view. The X and Y arrows printed under the stick mark the directions in which L/R and U/D rise from 0 V to 5 V. Placed in the breadboard (a), X points to the top of the breadboard and Y to the left. A quarter turn clockwise (b) puts L/R+ and U/D+ at the top corners and the GND pins at the bottom corners, and turns X to point right and Y up, so the readings are laid out the usual way. The blue dot is the stick, pulled towards the bottom edge. That is at right angles to X, so x stays at the centre of its range, and straight against Y, so y is at its lowest.

It is “should”, not “will”. A real stick at rest sits a few counts away from 511, and when pulled all the way it may not quite reach 0 V. A program that tests for “centred” or “pushed down” needs a margin either side, as the programs below have.

Worked: where is (614, 689)?

The ADC is reading (x, y) = (614, 689). Where is the joystick? There are two parts to the answer, which way the stick is pushed and how far.

A. 15° anticlockwise of the right half-axis · B. 30° · C. 45° · D. 60° · E. 75°

F. 20 % tilted · G. 40 % tilted · H. 60 % tilted · I. 80 % tilted · J. 100 % tilted

D and G: 60° anticlockwise of the right half-axis, 40 % tilted. Measure from the centre, (511, 511):

\[\Delta x = 614 - 511 = 103, \qquad \Delta y = 689 - 511 = 178.\]

Both are positive, so the stick is up and to the right. Its direction, as an angle measured anticlockwise from straight right, is

\[\theta = \tan^{-1}\frac{\Delta y}{\Delta x} = \tan^{-1}\frac{178}{103} = \tan^{-1} 1.728 = 59.9^\circ \approx 60^\circ.\]

How far it is pushed is its distance from the centre, as a fraction of the 511 counts from the centre to full deflection:

\[\frac{\sqrt{103^2 + 178^2}}{511} = \frac{205.7}{511} = 0.40, \quad\text{so } 40\,\%.\]

Working backwards confirms it. Taking the exact centre, 511.5, full deflection is 511.5 counts, and 40 % of it is 204.6. At 60° that is \(204.6 \cos 60^\circ = 102.3\) across and \(204.6 \sin 60^\circ = 177.2\) up, which lands on (613.8, 688.7), and the converter reports whole numbers, (614, 689). Mixing up the axes gives 30°, since (689, 614) is the reading at 30°.

Figure 130: The joystick’s readings as a plane, x across and y up, each from 0 to 1023, with the centre at (511, 511). The dashed circle is full deflection, 511 counts from the centre. Pulling the stick straight down gives (511, 0): x stays centred and y goes to the bottom of its range. The reading (614, 689) is 103 counts right of the centre and 178 up. That is 206 counts from the centre, 40 % of full deflection, at 60° anticlockwise from the right half-axis. No reading is ever negative: the converter’s result runs from 0 to 1023.

SPI

SPI, the Serial Peripheral Interface, is the AVR’s synchronous serial port (avr-spi). The master and the slave each have an 8-bit shift register, and the two are joined in a ring: MOSI carries bits out of the master’s most significant end into the slave’s least significant end, and MISO carries bits out of the slave’s most significant end back into the master’s least significant end. The master makes the clock, SCK, and each pulse shifts both registers one place, so after eight pulses the two bytes have changed places. The slave takes part only while its select line, \(\overline{\text{SS}}\), is held low. With one master and one slave, the simplest arrangement holds the master’s own \(\overline{\text{SS}}\) high, so that it stays the master, and ties the slave’s low, so that it is always selected.

Sending a byte is writing it to the data register, and like a conversion it takes time: eight clock pulses. The program finds out it has finished by polling the flag SPIF0, or by taking the “serial transfer complete” interrupt, SPI_STC.

The names in code

The datasheet describes the SPI registers on pages 172 and 173 as SPCR and SPSR, but the ATmega324A header names them SPCR0 and SPSR0, with a 0 for SPI port 0. Their bit names take a 0 on the end as well: SPIE is SPIE0, SPE is SPE0, and SPR1 is SPR10. The data register follows the same pattern, SPDR0.

The datasheet’s register summary already has the 0s, with one slip: the bit printed there as SPR01 is SPR10.

Worked: master mode, slowest clock

Which bits of the SPI control registers SPCR and SPSR need to be set (1) to enable SPI in master mode with the slowest possible clock rate?

In SPCR0: SPE0, MSTR0, SPR10 and SPR00. In SPSR0: none. So SPCR0 = 0x53.

  • SPE0, bit 6 of SPCR0, switches SPI on.
  • MSTR0, bit 4, makes the AVR the master, the end that drives the clock.
  • The clock rate is set by three bits in two registers, SPI2X0 in SPSR0 and SPR10:SPR00 in SPCR0:
SPI2X0 SPR10 SPR00 SCK
0 0 0 clock / 4
0 0 1 clock / 16
0 1 0 clock / 64
0 1 1 clock / 128
1 0 0 clock / 2
1 0 1 clock / 8
1 1 0 clock / 32
1 1 1 clock / 64

SPI2X0 doubles the speed, so the slowest rate has it at 0 and both SPR bits at 1: \(8\ \text{MHz} / 128 = 62.5\ \text{kHz}\). One byte then takes \(8 / 62\,500 = 128\ \text{µs}\).

The other bits stay 0: no interrupt (SPIE0), the most significant bit first (DORD0), and the clock idling low with data sampled on its rising edge (CPOL0, CPHA0). SPIF0 and WCOL0, the top two bits of SPSR0, are flags the hardware sets, not settings.

SPCR0 = (1<<SPE0) | (1<<MSTR0) | (1<<SPR10) | (1<<SPR00);    /* 0x53 */

Figure 131: The two SPI registers set for master mode at the slowest clock. In SPCR0 the shaded bits are set: SPE0 turns SPI on, MSTR0 makes the AVR the master, and SPR10 and SPR00 select the slowest rate. The rate is the one setting split across two registers. Its third bit, SPI2X0, is bit 0 of SPSR0, and it stays 0, since setting it would double the speed. The top two bits of SPSR0 are status flags that the hardware sets.

The LED matrix

The LED matrix is 16 columns by 8 rows of pixels, each with a red and a green LED. It is an SPI slave: it takes commands, one byte at a time, from the AVR. It has two connection headers (io-board):

  • K1, two pins, is its power. A two-wire lead joins it to the I/O board’s connector J1, VCC on the left pin and GND on the right.
  • K2, four pins, is the SPI connection. It goes to the AVR’s SPI port, PB7 to PB4: SCK on PB7, MISO on PB6, MOSI on PB5 and \(\overline{\text{SS}}\) on PB4. The order of the four pins on K2 has to be matched against the pin names in the datasheet before the lead is plugged in.

The matrix’s reference manual describes everything it understands. The programs here use two commands, which are enough to draw anything.

The SPI pins are also the programming pins. The programmer loads the AVR’s flash through PB7 to PB5, so the matrix sees the programming traffic too, takes it for nonsense commands, and can end up showing Err. To clear it, hold the AVR’s reset button down for at least half a second after programming, then let the program start.

Figure 132: How the LED matrix is connected. Its SPI header K2 takes the four SPI pins of port B: the clock SCK, the data MOSI and the select line SS, which the AVR drives, and the data MISO coming back. Its power header K1 is fed from connector J1 on the I/O board, VCC on the left pin and GND on the right. The matrix only acts on bytes sent while SS is low.

The commands and the colour byte

Every message starts with a command byte. The two used here:

Command Bytes Does
clear 0x0F turns every pixel off
set one pixel 0x01, position, colour sets the pixel at position to colour
  • The position byte is the row in the high nibble and the column in the low nibble: (y << 4) | x, with x from 0 to 15 across and y from 0 to 7 up, (0, 0) being the bottom-left pixel.
  • The colour byte is the green brightness in the high nibble and the red brightness in the low nibble, each from 0 (off) to 15 (full): (green << 4) | red. Mixing the two gives the colours between red and green.
Colour byte Green Red Colour
0x00 0 0 off (black)
0x0F 0 15 red
0x7F 7 15 orange
0xFF 15 15 yellow
0xF7 15 7 chartreuse, a yellow-green
0xF0 15 0 green

Worked: what colour is 0x7F?

What colour would a 0x7F colour data byte produce?

A. Red · B. Orange · C. Yellow · D. Chartreuse · E. Green · F. Black · G. Blue · H. Octarine

B, orange. 0x7F splits into a green nibble of 7 and a red nibble of 15: full red with about half as much green. Full red with full green, 0xFF, is yellow, so red with half the green sits between red and yellow, which is orange. Swapping the nibbles, 0xF7, gives chartreuse, the colour halfway from yellow to green. Blue is impossible on a matrix with only red and green LEDs, and octarine is a colour from fiction.

Worked: what do these bytes draw?

What would the LED matrix look like after receiving the bytes 0x0F, 0x01 0x24 0xF0, 0x01 0x46 0x0F? The six candidate pictures, A to F in Figure 133, each show one red and one green pixel, with each place given as (x, y): x across from the left and y up from the bottom, both counted from 0.

Figure 133: The six candidate pictures, each a 16 by 8 matrix with one red and one green pixel. E is what the bytes draw. Each of the others is the same two commands read with one slip, and the slip shows in where the pixels land. Reading the position byte’s nibbles the wrong way round swaps each pixel’s x and y (A). Counting x from the right mirrors the picture left to right (D). Counting from 1 instead of 0 moves every pixel one place down and one to the left (B). Reading the colour byte’s nibbles the wrong way round leaves the places alone but swaps the colours (C). F makes both swaps, A’s and C’s.

E. Split the bytes into commands:

  1. 0x0F: clear the display.
  2. 0x01 0x24 0xF0: set one pixel. The position 0x24 is y = 2, x = 4, and the colour 0xF0 is green 15, red 0. Green at (4, 2).
  3. 0x01 0x46 0x0F: set one pixel. Position 0x46 is y = 4, x = 6, colour 0x0F is red. Red at (6, 4).

Each wrong picture comes from one slip. A reads the position nibbles the wrong way round, taking 0x24 as x = 2, y = 4. C swaps the colour nibbles, so 0xF0 becomes red. F does both. D counts x from the right-hand edge, putting x = 4 in column 11 from the left. B counts from 1 instead of 0, so every pixel lands one column left and one row down.

Figure 134: Seven bytes sent to the LED matrix, and what they draw. The stream divides into commands: 0x0F clears the display, and each 0x01 is followed by a position and a colour. A position byte holds y in its high nibble and x in its low nibble, so 0x24 is the pixel at x = 4, y = 2, counting from 0 at the bottom-left. A colour byte holds green in its high nibble and red in its low nibble, so 0xF0 is full green and 0x0F full red. Here red and green are the colours the LEDs show.

Worked: how fast does TCNT1 >> 8 count?

With a \(clk_{I/O}/1024\) prescaler, how quickly does TCNT1>>8 increment?

A. 7812 Hz · B. 3906 Hz · C. 1953 Hz · D. 976 Hz · E. 488 Hz · F. 244 Hz · G. 122 Hz · H. 61 Hz · I. 31 Hz · J. 15 Hz

I, 31 Hz. Timer/counter 1 counts at \(8\ \text{MHz} / 1024 = 7812.5\) counts a second. Shifting right by 8 throws away the bottom eight bits, so TCNT1>>8 goes up by one every \(2^8 = 256\) counts:

\[\frac{7812.5}{256} = 30.5\ \text{Hz}.\]

Each option is half the one before, and they line up with the shifts: A is TCNT1 itself, B is TCNT1>>1, and so on down to I for TCNT1>>8. TCNT1>>8 is the high byte of the count, 0 to 255, and it comes back round to 0 every \(65\,536 / 7812.5 = 8.4\) seconds (avr-timers-and-counters).

This is the timing the programs below use. Nothing has to be set up beyond the prescaler: the timer runs freely in normal mode, and a program that wants to do something every tenth of a second or so waits for TCNT1>>8 to move on by 3.

The tasks

NoteExercises
  1. Joystick wiring test. Wire up the joystick and connect its two outputs to two LEDs on the I/O board. Wobble the stick: the LEDs’ brightness should change. Then unplug the LEDs, which upset the ADC readings if they are left connected.
  2. Joystick demo. Create a project with lab16-1.c. Consult the datasheet and update the code as needed, then build and test it.
  3. LED matrix demo. Create a project with lab16-2.c. Consult the datasheet and update the code as needed, then build and test it.
  4. Marquee. Needs two LED matrices, so work with someone else. Create a project with lab16-3.c, which runs on one matrix as it is. Change it to drive two devices on the same MOSI, MISO and SCK pins but different SS pins.
  5. Etch-A-Sketch. Create a project with lab16-4.c: draw on the LED matrix with the joystick.

Working — Task 0

Join both + pins to VCC and one GND pin to GND. Run a wire from one L/R pin to LED L0 on the I/O board and one from a U/D pin to L1 (io-board). As the stick moves, each LED’s brightness follows the voltage on its axis, dim at one side and bright at the other. That shows both potentiometers are powered and both outputs move, before any code is involved.

Why the LEDs have to come off. A potentiometer’s wiper is a weak source. It sets the voltage, but it cannot supply current without that voltage changing. An LED draws current from it and pulls the voltage away from where the stick has put it, so the ADC would read the LED’s effect and not the stick’s position. The ADC input itself draws almost nothing.

Working — Task 1

lab16-1.c needs the converter’s register values from the datasheet. This is a complete program that does the job, to compare against. It reads both axes about ten times a second and prints them over the serial port, with the direction the stick is pushed. The serial set-up is the one from avr-usart.

#include <avr/io.h>
#include <stdint.h>

/* L/R (x) on PA0 = ADC0, U/D (y) on PA1 = ADC1.
   TXD0 (PD1) to the I/O board's serial receive, 9600 baud. */
#define X_CHANNEL 0
#define Y_CHANNEL 1

void adc_init(void) {
    ADMUX  = (1<<REFS0);                            /* AVCC, right adjusted, ADC0 */
    ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1);   /* on, clock = 8 MHz / 64     */
}

uint16_t adc_read(uint8_t channel) {
    ADMUX = (1<<REFS0) | channel;     /* for channel 1 this is 0x41        */
    ADCSRA |= (1<<ADSC);              /* start one conversion              */
    while (ADCSRA & (1<<ADSC)) { }    /* ADSC goes back to 0 when finished */
    return ADC;                       /* ADCL then ADCH: 0 to 1023         */
}

void uart_init(void) {
    UBRR0  = 51;                      /* 9600 baud                      */
    UCSR0B = (1<<TXEN0);              /* transmitter on; 8 data bits,   */
                                      /* no parity, 1 stop from reset   */
}

void uart_put(char c) {
    while (!(UCSR0A & (1<<UDRE0))) { }
    UDR0 = c;
}

void uart_print(const char *s) {
    while (*s) {
        uart_put(*s++);
    }
}

void uart_number(uint16_t n) {        /* four characters, right aligned */
    char d[4];
    int8_t i;

    for (i = 3; i >= 0; i--) {
        d[i] = '0' + n % 10;
        n /= 10;
    }
    for (i = 0; i < 3 && d[i] == '0'; i++) {
        d[i] = ' ';                   /* blank the leading zeros */
    }
    for (i = 0; i < 4; i++) {
        uart_put(d[i]);
    }
}

/* Which way the stick is pushed. Readings within 128 of the
   centre count as centred, so a stick at rest reads "centre". */
const char *direction(uint16_t x, uint16_t y) {
    static const char *name[3][3] = {
        /* x low        x middle    x high       */
        { "down-left", "down",     "down-right" },   /* y low    */
        { "left",      "centre",   "right"      },   /* y middle */
        { "up-left",   "up",       "up-right"   },   /* y high   */
    };
    uint8_t col = (x < 384) ? 0 : (x > 640) ? 2 : 1;
    uint8_t row = (y < 384) ? 0 : (y > 640) ? 2 : 1;
    return name[row][col];
}

int main(void) {
    uint16_t x, y;
    uint8_t now, last = 0;

    adc_init();
    uart_init();
    TCCR1A = 0;
    TCCR1B = (1<<CS12) | (1<<CS10);   /* timer 1 free running at 8 MHz / 1024 */

    while (1) {
        now = TCNT1 >> 8;                     /* advances 30.5 times a second */
        if ((uint8_t)(now - last) >= 3) {     /* so about 10 reports a second */
            last = now;
            x = adc_read(X_CHANNEL);
            y = adc_read(Y_CHANNEL);
            uart_print("x = ");
            uart_number(x);
            uart_print("   y = ");
            uart_number(y);
            uart_print("   ");
            uart_print(direction(x, y));
            uart_print("\r\n");
        }
    }
}

What each piece does.

  • adc_init sets the reference to AVCC and switches the converter on with its clock at 8 MHz / 64 = 125 kHz, the setting chosen above: ADPS2:0 = 110 (analog-to-digital-conversion).
  • adc_read selects the input, starts a conversion by setting ADSC, and waits for ADSC to drop back to 0, which the hardware does when the result is ready. REFS0 is written again every time, because writing ADMUX replaces all eight bits.
  • ADC is the 16-bit result register. The compiler reads its low byte ADCL first and then ADCH, which is the order the hardware needs.
  • The pacing. Timer 1 runs freely at 8 MHz / 1024, so TCNT1 >> 8 goes up 30.5 times a second (worked above). A report goes out each time it has moved on by 3, about every 0.1 s. Subtracting as uint8_t keeps the comparison right when the count wraps from 255 to 0.
  • direction sorts each axis into low, middle or high with a margin of 128 either side of the centre, so that a stick at rest, which is never exactly at 511, reads centre.

Run on the joystick, it prints lines like

x =  511   y =  511   centre
x =  511   y =    0   down
x =  614   y =  689   up
x = 1023   y =  511   right

The reading (614, 689) comes out as up because its x is within the margin. At 60°, it is nearer straight up than the diagonal.

Working — Task 2

lab16-2.c needs the SPI register values from the datasheet. This program sets SPI up, sends the seven bytes decoded above, waits about two seconds, and then fills the matrix with every mix of red and green.

#include <avr/io.h>
#include <stdint.h>

#define CMD_PIXEL  0x01     /* then a position byte and a colour byte */
#define CMD_CLEAR  0x0F     /* every pixel off                         */

#define COLOUR(green, red)  (((green) << 4) | (red))    /* each 0 to 15 */

void spi_init(void) {
    DDRB  |= (1<<DDB7) | (1<<DDB5) | (1<<DDB4);   /* SCK, MOSI and SS out; MISO in */
    PORTB |= (1<<PORTB4);                          /* SS high to start with         */
    SPCR0  = (1<<SPE0) | (1<<MSTR0) | (1<<SPR10) | (1<<SPR00);   /* master, / 128  */
    /* SPI2X0 in SPSR0 stays 0 from reset */
    PORTB &= ~(1<<PORTB4);                         /* SS low: the matrix listens    */
}

uint8_t spi_send(uint8_t byte) {
    SPDR0 = byte;                       /* writing SPDR0 starts the transfer  */
    while (!(SPSR0 & (1<<SPIF0))) { }   /* SPIF0 is set after eight clocks    */
    return SPDR0;                       /* and reading SPDR0 next clears it   */
}

void matrix_clear(void) {
    spi_send(CMD_CLEAR);
}

void matrix_pixel(uint8_t x, uint8_t y, uint8_t colour) {
    spi_send(CMD_PIXEL);
    spi_send(((y & 0x07) << 4) | (x & 0x0F));   /* row high nibble, column low */
    spi_send(colour);
}

int main(void) {
    uint8_t x, y, start;

    spi_init();
    TCCR1A = 0;
    TCCR1B = (1<<CS12) | (1<<CS10);   /* 8 MHz / 1024 */

    /* the bytes 0x0F, 0x01 0x24 0xF0, 0x01 0x46 0x0F */
    matrix_clear();
    matrix_pixel(4, 2, COLOUR(15, 0));        /* green */
    matrix_pixel(6, 4, COLOUR(0, 15));        /* red   */

    start = TCNT1 >> 8;
    while ((uint8_t)((TCNT1 >> 8) - start) < 61) { }   /* about 2 seconds */

    /* every mix of the two colours: red grows to the right, green upwards */
    for (y = 0; y < 8; y++) {
        for (x = 0; x < 16; x++) {
            matrix_pixel(x, y, COLOUR(2 * y + 1, x));
        }
    }

    while (1) { }
}

Points to notice.

  • Direction bits. In master mode the AVR drives SCK, MOSI and SS, so their DDRB bits must be 1. MISO is made an input by the SPI hardware whatever its DDRB bit says.
  • SS must be an output, or held high. If PB4 were an input and something pulled it low, the AVR would take that as another master claiming the bus, clear MSTR0 and drop out of master mode. As an output it is just a pin the program controls, here the matrix’s select line.
  • spi_send waits on SPIF0. The flag is cleared by reading SPSR0 while it is set and then reading SPDR0, which is what the loop and the return do. The byte returned is whatever the matrix shifted back, which these programs ignore.
  • COLOUR(green, red) builds the colour byte from two brightnesses. The chart has red rising from 0 at the left to 15 at the right, and green from 1 at the bottom to 15 at the top. The bottom-right pixel is 0x1F, nearly pure red, and the top-right is 0xFF, yellow. The orange of 0x7F is at the right-hand end of row 3.
  • Speed. At 62.5 kHz a byte takes 128 µs, so the 128 pixel commands of the chart, 384 bytes, take about 49 ms.

Working — Task 3

Two matrices can share SCK, MOSI and MISO, because only the one whose \(\overline{\text{SS}}\) is low takes any notice of the bus. Each gets its own select line: the left matrix keeps PB4, and the right one is given PB3. The program selects a matrix, sends it complete commands, and selects the other. The two set-ups also need their grounds joined, since a signal on a wire only means something against a ground both ends share.

PB4 stays an output even when the right-hand matrix is the one selected, which keeps the AVR in master mode, for the reason given under Task 2.

Figure 135: Two LED matrices on one SPI port. SCK, MOSI and MISO run to both, and a dot marks each real connection. Lines that cross without a dot are not connected. Each matrix has its own select line, PB4 for the left one and PB3 for the right one, and the program holds at most one of them low at a time. Only the selected matrix acts on the bytes on the bus. PB4 stays an output throughout, so the AVR stays the master.

The marquee. The message is laid out as a strip of columns: 32 blank ones, then each letter as five columns from a 5 by 7 font with one blank column after it. “CSSE2010” makes \(32 + 8 \times 6 = 80\) columns. The two matrices together are a window 32 columns wide onto the strip. At step \(s\) the left matrix shows columns \(s\) to \(s + 15\) and the right one \(s + 16\) to \(s + 31\). Each step moves the window one column to the right, which moves the text one column left, and after 80 steps the window is back at the start. The 32 blank columns let the text come in from the right-hand edge and go fully off the left before it starts again.

Figure 136: The marquee as a window sliding along a strip. The strip is 80 columns: 32 blank, so that the text can enter from the right, and then CSSE2010 in a 5 by 7 font with a blank column after each letter. At step s the left matrix shows columns s to s + 15 and the right matrix columns s + 16 to s + 31. Here s = 34. Each step adds 1 to s, and the text appears to move one column to the left.

#include <avr/io.h>
#include <stdint.h>

#define CMD_PIXEL  0x01
#define CMD_CLEAR  0x0F
#define COLOUR(green, red)  (((green) << 4) | (red))
#define TEXT       COLOUR(7, 15)            /* 0x7F, orange */

/* Both matrices are on SCK (PB7), MISO (PB6) and MOSI (PB5).
   Each has its own select line: the left one PB4, the right one PB3. */
#define SS_LEFT    PORTB4
#define SS_RIGHT   PORTB3

/* 5 x 7 letters, one byte per column, bit 0 the top row */
const char    letters[] = "CSE210 ";
const uint8_t font[][5] = {
    { 0x3E, 0x41, 0x41, 0x41, 0x22 },   /* C     */
    { 0x46, 0x49, 0x49, 0x49, 0x31 },   /* S     */
    { 0x7F, 0x49, 0x49, 0x49, 0x41 },   /* E     */
    { 0x42, 0x61, 0x51, 0x49, 0x46 },   /* 2     */
    { 0x00, 0x42, 0x7F, 0x40, 0x00 },   /* 1     */
    { 0x3E, 0x51, 0x49, 0x45, 0x3E },   /* 0     */
    { 0x00, 0x00, 0x00, 0x00, 0x00 },   /* space */
};

const char message[] = "CSSE2010";
#define MESSAGE_LENGTH  8
#define LEAD_IN         32                              /* blank columns first */
#define STRIP_LENGTH    (LEAD_IN + 6 * MESSAGE_LENGTH)  /* 80 columns          */

uint8_t shown[2][16];        /* the columns each matrix is showing now */

void spi_init(void) {
    DDRB  |= (1<<DDB7) | (1<<DDB5) | (1<<DDB4) | (1<<DDB3);
    PORTB |= (1<<SS_LEFT) | (1<<SS_RIGHT);       /* neither matrix selected */
    SPCR0  = (1<<SPE0) | (1<<MSTR0) | (1<<SPR10) | (1<<SPR00);
}

uint8_t spi_send(uint8_t byte) {
    SPDR0 = byte;
    while (!(SPSR0 & (1<<SPIF0))) { }
    return SPDR0;
}

void matrix_select(uint8_t m) {                  /* 0 = left, 1 = right */
    PORTB |= (1<<SS_LEFT) | (1<<SS_RIGHT);
    if (m == 0) {
        PORTB &= ~(1<<SS_LEFT);
    } else {
        PORTB &= ~(1<<SS_RIGHT);
    }
}

void matrix_pixel(uint8_t x, uint8_t y, uint8_t colour) {
    spi_send(CMD_PIXEL);
    spi_send(((y & 0x07) << 4) | (x & 0x0F));
    spi_send(colour);
}

/* Column i of the strip: 32 blank columns, then each letter
   as five columns and one blank column after it. */
uint8_t strip_column(uint8_t i) {
    uint8_t n, c, k;

    if (i < LEAD_IN) {
        return 0;
    }
    i -= LEAD_IN;
    n = i / 6;                        /* which letter of the message  */
    c = i % 6;                        /* which column of that letter  */
    if (c == 5) {
        return 0;                     /* the gap between letters      */
    }
    for (k = 0; letters[k] != message[n]; k++) { }
    return font[k][c];
}

/* Change column x of matrix m (already selected) to show bits,
   sending only the pixels that differ from what it shows now. */
void show_column(uint8_t m, uint8_t x, uint8_t bits) {
    uint8_t changed = bits ^ shown[m][x];
    uint8_t k;

    for (k = 0; k < 7; k++) {
        if (changed & (1<<k)) {
            matrix_pixel(x, 7 - k, (bits & (1<<k)) ? TEXT : 0x00);
        }
    }
    shown[m][x] = bits;
}

int main(void) {
    uint8_t step = 0, m, x, now, last;

    spi_init();
    TCCR1A = 0;
    TCCR1B = (1<<CS12) | (1<<CS10);         /* TCNT1 >> 8 counts at 30.5 Hz */

    for (m = 0; m < 2; m++) {
        matrix_select(m);
        spi_send(CMD_CLEAR);
    }

    last = TCNT1 >> 8;
    while (1) {
        now = TCNT1 >> 8;
        if ((uint8_t)(now - last) >= 3) {   /* one step about every 0.1 s */
            last = now;
            for (m = 0; m < 2; m++) {
                matrix_select(m);
                for (x = 0; x < 16; x++) {
                    show_column(m, x, strip_column((step + 16 * m + x) % STRIP_LENGTH));
                }
            }
            step = (step + 1) % STRIP_LENGTH;
        }
    }
}

How it works.

  • The font. Each letter is five bytes, one per column, with bit 0 the top row. A row number \(k\) from the top becomes \(y = 7 - k\) on the matrix, so the letters fill rows 7 down to 1 and row 0 stays blank.
  • Only changes are sent. shown remembers what each column of each matrix is showing. XOR with the new column gives a 1 for every pixel that has to change, and only those get a command. Redrawing both matrices in full would be \(2 \times 128 \times 3 = 768\) bytes, about 0.1 s at 128 µs a byte, which would use up the whole step. Sending only the changes is a few dozen pixels a step.
  • Selecting. matrix_select raises both select lines and then lowers one, so the two are never low together, and it is only called between complete commands. A matrix deselected halfway through a command would be left waiting for the rest of it.
  • The pace is three counts of TCNT1 >> 8, \(3 \times 256 / 7812.5 = 98\) ms a step, so the 80-step cycle takes just under 8 seconds.

Working — Task 4

The Etch-A-Sketch has a pen, a red pixel that blinks, and the stick moves it one pixel at a time. Wherever the pen has been is left green. A push of button B0 on the I/O board, wired to PD2, wipes the drawing.

#include <avr/io.h>
#include <stdint.h>

#define CMD_PIXEL  0x01
#define CMD_CLEAR  0x0F
#define COLOUR(green, red)  (((green) << 4) | (red))
#define TRAIL      COLOUR(15, 0)     /* green: the line drawn */
#define PEN        COLOUR(0, 15)     /* red: where the pen is */
#define BLANK      0x00

/* Joystick x on PA0 (ADC0), y on PA1 (ADC1). LED matrix on PB7 to PB4.
   Push button B0 on PD2 clears the drawing. */

uint8_t drawn[16];           /* bit y of drawn[x] is 1 where the line has been */

void adc_init(void) {
    ADMUX  = (1<<REFS0);
    ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1);
}

uint16_t adc_read(uint8_t channel) {
    ADMUX = (1<<REFS0) | channel;
    ADCSRA |= (1<<ADSC);
    while (ADCSRA & (1<<ADSC)) { }
    return ADC;
}

void spi_init(void) {
    DDRB  |= (1<<DDB7) | (1<<DDB5) | (1<<DDB4);
    PORTB |= (1<<PORTB4);
    SPCR0  = (1<<SPE0) | (1<<MSTR0) | (1<<SPR10) | (1<<SPR00);
    PORTB &= ~(1<<PORTB4);
}

uint8_t spi_send(uint8_t byte) {
    SPDR0 = byte;
    while (!(SPSR0 & (1<<SPIF0))) { }
    return SPDR0;
}

void matrix_pixel(uint8_t x, uint8_t y, uint8_t colour) {
    spi_send(CMD_PIXEL);
    spi_send(((y & 0x07) << 4) | (x & 0x0F));
    spi_send(colour);
}

void clear_drawing(void) {
    uint8_t x;

    spi_send(CMD_CLEAR);
    for (x = 0; x < 16; x++) {
        drawn[x] = 0;
    }
}

/* -1, 0 or +1 for one axis: it has to be pushed past half way */
int8_t step_for(uint16_t reading) {
    if (reading < 256) {
        return -1;
    }
    if (reading > 767) {
        return 1;
    }
    return 0;
}

int main(void) {
    uint8_t x = 8, y = 4;                /* the pen starts in the middle */
    int8_t nx, ny;
    uint8_t now, last_move, blink, shown_blink = 2;
    uint8_t button, last_button = 0;

    adc_init();
    spi_init();
    DDRD &= ~(1<<DDD2);                  /* the clear button is an input */
    TCCR1A = 0;
    TCCR1B = (1<<CS12) | (1<<CS10);      /* 8 MHz / 1024 */

    clear_drawing();
    last_move = TCNT1 >> 8;

    while (1) {
        /* clear on the push of the button, not for as long as it is held */
        button = (PIND >> PIND2) & 1;
        if (button && !last_button) {
            clear_drawing();
            shown_blink = 2;             /* make the pen be drawn again */
        }
        last_button = button;

        /* move at most one pixel every 4 counts of TCNT1 >> 8: 7.6 a second */
        now = TCNT1 >> 8;
        if ((uint8_t)(now - last_move) >= 4) {
            last_move = now;
            nx = x + step_for(adc_read(0));
            ny = y + step_for(adc_read(1));
            if (nx < 0)  { nx = 0; }
            if (nx > 15) { nx = 15; }
            if (ny < 0)  { ny = 0; }
            if (ny > 7)  { ny = 7; }
            if (nx != x || ny != y) {
                drawn[x] |= (1<<y);          /* leave the line where the pen was */
                matrix_pixel(x, y, TRAIL);
                x = nx;
                y = ny;
                shown_blink = 2;
            }
        }

        /* the pen blinks: bit 12 of TCNT1 flips every 4096 counts, 0.52 s */
        blink = (TCNT1 >> 12) & 1;
        if (blink != shown_blink) {
            if (blink) {
                matrix_pixel(x, y, PEN);
            } else {
                matrix_pixel(x, y, (drawn[x] & (1<<y)) ? TRAIL : BLANK);
            }
            shown_blink = blink;
        }
    }
}

How it works.

  • Reading the stick as a step. step_for turns a reading into \(-1\), 0 or \(+1\), with the stick pushed past half way, below 256 or above 767, before it counts. Both axes are read each time, so a diagonal push moves the pen diagonally.
  • Pacing from the timer. The pen moves at most once per 4 counts of TCNT1 >> 8, which is \(4 \times 256 / 7812.5 = 131\) ms, about 7.6 moves a second. Without it the pen would cross the matrix in a few milliseconds.
  • Blinking from the timer. Bit 12 of TCNT1 changes every \(2^{12} = 4096\) counts, 0.52 s, so (TCNT1 >> 12) & 1 is a square wave with a period of just over a second, for nothing more than a read of the count. The pixel is only resent when that bit changes, not on every pass of the loop.
  • Remembering the drawing. drawn holds one bit per pixel, so that when the pen blinks off it shows the line underneath, or nothing, as it should.
  • shown_blink = 2 is a value the bit can never have, which forces the pen to be redrawn on the next pass after a move or a clear.
  • The button clears on its rising edge, the moment it goes down, using the same comparison with the previous reading as the stopwatch in week9-lab-avr-interrupts.

Which way is up. The program moves the pen in the joystick’s own frame: right with x, up with y. Set in the breadboard as described above, the joystick’s x points to the top of the breadboard (Figure 129), so pushing the stick away moves the pen right. To have the pen follow the stick as seen from in front of the breadboard, swap the axes and reverse one: move right as y falls and up as x rises, which is nx = x - step_for(adc_read(1)) and ny = y + step_for(adc_read(0)).

See also

Week 11

Lecture 22 — Compilation and Linking

What happens between a C program and the machine code that runs it. The note covers compiled against interpreted languages, with Java and Python’s bytecode in between; where a C compiler puts global, local and static variables; why programs are built from separately compiled object files, and the six sections of one; how the linker relocates and resolves addresses; libraries, and how a header differs from a library; and dynamic linking. It picks up from the assembler’s two passes in 2026-10-08-assembly-process. The reference note is compilation-and-linking. Where variables live is also in procedures-and-the-stack and c-language-basics, and headers against libraries in c-preprocessor-and-avr-headers.

Goals

  1. Tell compiling from interpreting, and place Java and Python’s bytecode and just-in-time compilation between the two.
  2. Say where a C compiler puts global, local and static variables in the AVR’s data memory.
  3. Explain why programs are compiled into separate object files, and what each of the six sections of an object file holds.
  4. Link modules by hand: lay them out in link order, relocate their internal addresses and resolve their external ones.
  5. Tell a header file from a library, and static linking from dynamic linking.

Compilation

A program has to be converted to machine code before it can run. The processor only fetches, decodes and executes machine instructions (fetch-decode-execute-cycle). The conversion is called compilation, and it often goes by way of assembly language: the compiler writes assembly, and the assembler turns that into machine code.

Not every program is compiled, though.

Interpretation

Some languages are interpreted, Python, Java and MATLAB among them. The high-level program is never turned into machine code. It is the input to an interpreter, a program that reads the source and carries out each statement as it reaches it. What runs on the processor is the interpreter, which is machine code like any other program. Many interpreters first turn the source into bytecode, a compact instruction format of their own, and then interpret that.

The trade-off:

  • + Portability. The program is not tied to any instruction set. It runs on any machine that has an interpreter for its language.
  • − Slow. Each time a statement runs, the interpreter works out again what it means, which costs many of its own instructions. In a loop it does that on every pass. A compiled program did that work once, before it started.

Java and Python

Java, and Python in the same way, takes a route between the two.

  1. The source is “compiled”, but into bytecode, not machine code. Bytecode is the instruction set of an imaginary machine, so it is portable across all platforms: the same file runs anywhere.
  2. The bytecode is the input to the Java Virtual Machine, an interpreter for bytecode, which runs on the processor.
  3. To recover the speed, the virtual machine just-in-time compiles the parts that run most often into real machine code while the program is running. From then on those parts run on the processor directly.

Numba does the third step for Python: it compiles a chosen Python function to machine code the first time it is called. More in compilation-and-linking.

Figure 137: Three ways from a program to the processor. The grey boxes are machine code, which is the only thing a processor can run. A compiled program becomes machine code before it runs. An interpreted program never does: the interpreter is what runs, and it carries out the program’s statements one at a time, which is portable but slow. Java and Python compile to bytecode, which is the same on every platform, and a virtual machine interprets it. The virtual machine also compiles the busiest parts to machine code while the program runs, and from then on those parts run on the processor directly.

What compiling C involves

In a simplified view, compiling a C program is three jobs.

  1. Mapping variables to memory: giving every variable a place.
  2. Translating C code into assembler instructions: each statement becomes however many instructions it needs.
  3. Turning assembler instructions into machine code, which is the assembly process (assembly-process).

So the route is C → assembly → machine code. Some compilers go straight from C to machine code and skip the assembly text, but the jobs are the same. Job 1 is the subject of the next two sections. The whole chain from source file to flash is drawn in compilation-and-linking.

Global variables

Variables come in two kinds as far as memory is concerned. Global variables are declared outside every function. Local variables are declared inside one.

A global can be used by any function at any time, for the whole run, so the compiler gives it a fixed address in data memory. It works out the addresses itself, in the same way an assembly programmer reserves space with .dseg and .byte. On the ATmega324A the data space begins with 32 registers (addresses 0 to 31), 64 I/O registers (32 to 95) and 160 extended I/O registers (96 to 255), so the first byte free for variables is 256, 0x0100 (memory-models).

Worked: placing three globals

Where do these three globals go in the ATmega324A’s data memory, and what assembly reserves the same space?

/* global variables */
int count;
char c;
static int a;

Sizes first. On the AVR an int is 16 bits, 2 bytes, and a char is 8 bits, 1 byte (c-language-basics).

Then the addresses, one after another from 256 in the order declared. That is one layout a compiler may choose, since the order is up to the compiler.

Variable Size Addresses
count 2 bytes 256 and 257
c 1 byte 258
a 2 bytes 259 and 260

The next free byte is 261.

The assembly that reserves the same bytes:

.dseg               ; data segment: starts at the first SRAM byte, 256
count:  .byte 2     ; 256-257
c:      .byte 1     ; 258
a:      .byte 2     ; 259-260
.org 500
b:      .byte 1     ; 500

.byte n reserves \(n\) bytes and gives the first one the label’s name. .org moves the location counter, so a variable can be put at a chosen address. Here b is at 500, and 261 to 499 are left unused. That is something the assembly programmer decides. The C programmer leaves every address to the compiler.

And static? On a global, static does not change where the variable is stored: a is placed exactly like count. It makes the name private to this source file, so no other file can link to a (compilation-and-linking).

Figure 138: Three global variables placed in the ATmega324A’s data memory, with the lowest address at the top and decimal addresses on the right. The registers and the two banks of I/O registers fill addresses 0 to 255, so the globals start at 256 (0x0100). Each takes as many bytes as its type: two for an int and one for a char. On the right is the assembly that reserves the same bytes. In assembly, .org can put a variable at any address, here 500, leaving the bytes in between unused. The break in the column means the gap is not drawn to scale.

Local and static variables

A local variable exists only while its function is running. Each call gets a fresh copy, which is what makes recursion work, so a local cannot have a fixed address. It lives in the call’s stack frame instead, which holds the call’s arguments, its local variables and its return address.

When main executes call TEST, the frame for TEST is pushed onto the stack. When TEST reaches ret, the frame is popped and its locals are gone. The stack is described in procedures-and-the-stack.

The whole data memory then looks like this, from the lowest address up:

  1. registers r0 to r31, the I/O registers and the extended I/O registers, up to address 255;
  2. the globals, from 256;
  3. the heap, from which malloc() hands out memory while the program runs, growing toward higher addresses;
  4. free memory;
  5. the stack, which starts at the top of SRAM and grows down toward the heap. The stack pointer SP marks its current end, and the frames of all running calls sit between SP and the top.

If the stack grows down far enough to meet the heap, that is a stack overflow, and nothing stops it. This layout is drawn in compilation-and-linking.

Worked: where three variables of one function live

In this function, where is each of a, b and c stored, and for how long?

void function(void) {
    int8_t   a;
    uint16_t b;
    static int c;
    ...
}
  • a is a local, 1 byte. It is in function’s stack frame. It is created when function is called and is gone at the return.
  • b is a local, 2 bytes. It is also in the frame, so the frame holds 3 bytes of locals next to the 2-byte return address.
  • c is declared inside the function but marked static. It is not in the frame. It lives among the globals, at a fixed address from 256 up, for the whole run. Only function can use the name c, but its value survives from one call to the next.

So if function is called twice, a and b start out with whatever happens to be on the stack each time, while c still holds what the first call left in it. The frame itself is drawn in procedures-and-the-stack.

Compiling C into object files

Compiling a C program runs into the same problem as the assembly process: there are names whose addresses are not yet known.

  • The compiler often produces object files (.o) as an intermediate step. Assemblers can produce object files too.
  • All the object files are generated first. Each of the program’s own .c files is compiled, with its .h files and macros already expanded by the preprocessor, and the libraries arrive as object files that were compiled long ago.
  • Then they are all linked together, and the final details, such as memory locations, are worked out at that point.

An object file is machine code plus information. Suppose there are three source files, and the third defines a procedure TEST at its address 80. Each file is compiled as if it started at address 0, so in its object file TEST is only “80 from the start of this module”. The first file calls TEST but cannot know where TEST will end up, because that depends on where the linker puts the third module. So the object file records that the call needs TEST’s address. Once the linker has laid the modules out end to end, the third module’s start is known, TEST is that start plus 80, and the call is filled in.

Why object files

It is often useful to compile or assemble modules separately and then link them together. Change one file and only that file has to be compiled again.

The consequence is that, at compile time, nobody knows where the code will end up, meaning the addresses it will occupy. Once the location is known, the code has to be fixed. Code that carries the information needed for that is a relocatable object module. “Object module” and “object file” are used interchangeably.

The six sections of an object file

An object file is made of six sections, numbered from the bottom up. The structure is drawn in compilation-and-linking.

Section Holds
6 End of module (perhaps) a checksum to catch errors; the address at which to start execution
5 Relocation dictionary the addresses in section 4 that need relocating
4 Machine instructions and constants the code segment; the data segment, both initialised and uninitialised data
3 External reference table symbols used here but defined elsewhere, and the instructions that use them
2 Entry point table symbols defined here that other modules may use, with their addresses
1 Identification the module’s name; where the other sections are in the file; the assembly date

There are many different object file formats, among them a.out, COFF and ELF. ELF is what the AVR GCC toolchain produces. DWARF, often listed with them, is a format for debugging information, usually stored inside ELF files.

1. Identification section. The name of the module, the location of the other sections in the file, and the assembly date. The linker needs the locations to find everything else.

2. Entry point table. The list of symbols defined in the module that other modules may reference, with their values. The values are addresses: procedure entry points and variables. The addresses are relative to the beginning of this object module. For example, a file that defines a procedure called abs_value at address 10 lists abs_value with the value 10.

3. External reference table. The list of all symbols that are used in the module but not defined in it: procedure names and variables defined in some other module. Against each one is the list of instructions which use that symbol, the places that will need its address filled in.

4. Machine instructions and constants. The assembled code and constants, as a code segment and a data segment with both its initialised and uninitialised data. The addresses referenced in this code are not correct, because they assume the module starts at 0. They need relocation.

5. Relocation dictionary. The list of addresses of code and data in section 4 that need to be relocated. When the module is placed, a relocation constant is added to the instruction or data at each of these addresses, with different constants for code and data.

6. End of module. Possibly a checksum, to catch errors, and the address at which to start execution.

Worked: the tables for two modules

Module A defines a procedure SUM at its address 80, and calls and jumps to a procedure X. Module B defines X at its address 71, and calls SUM. Write each module’s entry point table and external reference table.

Defined here and offered to others goes in the entry point table, with the address relative to the module’s own start. Used here but defined elsewhere goes in the external reference table, with the instructions that use it. In this example A’s call X is at 12, its jmp X at 40, and B’s call SUM at 30.

Module Entry point table External reference table
A SUM at 80 X: used by the call at 12 and the jmp at 40
B X at 71 SUM: used by the call at 30

Each symbol is defined in one module and used in the other. SUM is an entry point of A and an external reference of B, and X is an entry point of B and an external reference of A. Neither module can finish its instructions alone. The linker finishes them by matching every external reference against an entry point.

Worked: where does X end up?

Module A’s code is 100 words and its data 30 bytes. A and B are linked in the order A, then B, with code and data each starting at 0. X is at 71 in B. What are B’s relocation constants, what is X’s final address, and what do the instructions that use SUM and X become?

B’s relocation constants. B’s code goes straight after A’s code, and B’s data straight after A’s data:

  • code constant = A’s code size = 100
  • data constant = A’s data size = 30

The two constants differ because A’s code and A’s data are different sizes. That is why the relocation dictionary has to say, for each address, whether it is a code address or a data address.

X’s final address is its offset in B plus B’s code constant: \(100 + 71 = \mathbf{171}\).

The instructions.

  • A’s call X at 12 and jmp X at 40 are resolved: the linker looks X up and writes 171 into both.
  • B’s call SUM moves to \(100 + 30 = 130\) and is resolved too. A is first, so its constant is 0, and SUM stays at 80.
  • If B contained a branch to its own address 71, that branch would be in B’s relocation dictionary and would be relocated: \(71 + 100 = 171\). It lands in the same place, by adding a constant this time, because the target is inside the module being moved.

Figure 139: Two modules that each use a procedure the other defines, before and after linking, with addresses increasing up the page. Each module is assembled from 0. Its entry point table lists what it offers, with addresses relative to its own start, and its external reference table lists what it needs and which instructions need it. Linking A first and then B gives B a code relocation constant of 100, A’s size. X moves from 71 to 171, and the call and jump in A are filled in with 171. A’s constant is 0, so SUM stays at 80, and that is the address the call in B receives. The bold operands are the ones the linker wrote.

The linker and libraries

The linker combines object modules into an executable binary program, which is machine code. Each source procedure, in C or in assembly, goes through a translator (a compiler or an assembler) and becomes an object module. The linker takes all the object modules, plus whatever it needs from a library, and produces the one executable. The chain is drawn in compilation-and-linking.

A library is

  • a collection of object files with an additional index, which tells the linker which member defines which symbol, and
  • a collection of useful functions and procedures, ready to link.

The principle is not to reinvent the wheel, and to use library code where possible. The standard C library is the usual example. It provides:

  • standard input and output,
  • string handling,
  • date and time functions,
  • general utilities.

More in compilation-and-linking.

Header files against the library

A header file (.h) is not the library. A header file

  • defines useful preprocessor macros,
  • declares the functions that are in the library, as function prototypes, and
  • declares the variables that are available externally, with extern.

The library is the collection of object files that implements the functions.

A prototype tells the compiler the name, the argument types and the return type, which is enough to check a call and generate it. It contains no code. The code is in the library, and it is the linker that joins it on. The header goes to the compiler, by way of the preprocessor, and the library goes to the linker. Forgetting the header shows up when compiling, as an “implicit declaration” of the function: a warning from older compilers, an error from newer ones. Forgetting the library shows up when linking, as an “undefined reference”. See c-preprocessor-and-avr-headers.

Linking: relocating and resolving

Linking is a similar problem to assembling. It has the external reference problem: symbols are used before their values are known. A module can call a procedure in a module the linker has not read yet. So the linker needs two passes as well, in the same way the assembler does (assembly-process). The first pass places every module and collects every entry point. The second pass patches the code.

When modules are joined together, addresses need relocating or resolving.

  • Relocating means adding some constant value: the module’s starting address, added to an address that points within the module.
  • Resolving means finding the value of an “external” address: one that points into a different module, looked up from the entry points the linker collected.

The passes are described step by step in compilation-and-linking.

Worked: linking modules A and B

Four object modules are each assembled from 0. Module A (length 400) holds BRANCH TO 200 at 0, MOVE P TO X at 200 and CALL B at 300. Module B (length 600) holds BRANCH TO 300 at 0, MOVE Q TO X at 300 and CALL C at 500. Module C (length 500) begins with BRANCH TO 200. The modules are linked in the order A, B, C, D, after 100 words of start-up code. Where does B start, and what does each instruction of A and B become?

Where everything goes. The start-up code fills 0 to 99, so A starts at 100. A is 400 long, so it fills 100 to 499 and B starts at 100 + 400 = 500. B is 600 long, so C starts at 500 + 600 = 1100. The relocation constants are +100 for A and +500 for B.

Each instruction. An instruction at offset \(o\) in a module starting at \(s\) is now at \(s + o\).

Now at Was Becomes How
100 A: BRANCH TO 200 BRANCH TO 300 relocate, +100
300 A: MOVE P TO X unchanged no code address
400 A: CALL B CALL 500 resolve: B starts at 500
500 B: BRANCH TO 300 BRANCH TO 800 relocate, +500 (100 + 400)
800 B: MOVE Q TO X unchanged no code address
1000 B: CALL C CALL 1100 resolve: C starts at 1100
1100 C: BRANCH TO 200 BRANCH TO 1300 relocate, +1100

Check that nothing broke. A’s branch at 100 now targets 300, which is exactly where A’s MOVE P TO X went. B’s branch at 500 targets 800, where B’s MOVE Q TO X went. A relocated branch still lands on the same instruction, because the branch and its target moved by the same amount. A call to another module is not fixed by adding A’s constant, though. CALL B needs B’s start, which only the layout of the whole program determines.

Finishing the job with D (length 300, at 1600) gives CALL D → CALL 1600 and D’s BRANCH TO 200 → BRANCH TO 1800. The complete table, and a drawing of the program after each of the linker’s two passes, are in compilation-and-linking.

Dynamic linking

So far, all the object code, library and main program alike, is linked into one binary before the program runs. That is static linking.

Alternatively, linking can happen at run time: a library procedure is linked when it is first called. The executable contains only a reference to it, and the library stays in a file of its own. DLLs on Windows work this way.

The advantages:

  • It saves space. The libraries are not linked into the binary executable, and every program that uses a library shares the one copy.
  • The library can be updated independently of the programs that use it, and a fix reaches all of them without relinking.

The second is also a disadvantage. A program can break because something else installed a different version of a DLL it depends on. On earlier versions of Windows this happened often enough to be called “DLL hell”.

An AVR program has no operating system to do the run-time linking, so everything is linked statically. The two are compared side by side in compilation-and-linking.

See also

Week 12

Lecture 23 — Floating Point Numbers

How a computer stores fractions, and numbers far too large or too small for any sensible number of integer bits. The note starts from why that is needed, with the number of air molecules in a coffee cup; covers fixed point, where the binary point sits at an agreed place, and the trade-off between range and precision it forces; then lets the point float, by way of scientific notation, normalisation and the log-table origin of the word “mantissa”; and then works through the IEEE 754 single and double precision formats, converting in both directions, finite precision and what it does to arithmetic, the formats from quarter to octuple precision, the special values zero, subnormal, infinity and NaN, and floating point in C and on the AVR. The reference notes are fixed-point-numbers and floating-point-numbers. Whole-number formats, including the excess notation the exponent uses, are in binary-number-representations.

Goals

  1. See why a fixed number of integer bits cannot hold both very large and very small quantities.
  2. Represent fractions in fixed point: convert a value to an \(m.n\) format and read a bit pattern in one, unsigned and two’s complement, and state the range and precision of every 8-bit format.
  3. Write numbers in normalised scientific notation, in decimal and in binary, and say where the word “mantissa” comes from.
  4. Describe the IEEE 754 single and double precision formats: the fields, the biased exponent, the implicit leading 1, and why the fields are in that order.
  5. Convert a decimal number to IEEE single precision in hexadecimal, and back.
  6. Explain the limits of floating point: finite precision and its effect on arithmetic, the special values, and how the formats from quarter to octuple precision compare.
  7. Know how C and the AVR handle floating point, and why integer arithmetic is preferred on the AVR.

The problem: how many molecules in a cup?

Worked: air molecules in an empty coffee cup

How many air molecules are in an empty 12 fl oz coffee cup at 1 atm and 26.85 °C?

The ideal gas law, \(pV = nRT\), gives the amount of gas \(n\) in moles. In SI units, rounded to keep the arithmetic simple:

Quantity Given SI, rounded
pressure \(p\) 1 atm \(100\,000\) Pa
volume \(V\) 12 fl oz \(0.00036\ \text{m}^3\)
gas constant \(R\) \(8\ \text{J/(K·mol)}\)
temperature \(T\) 26.85 °C \(300\) K

\[n = \frac{pV}{RT} = \frac{100\,000 \times 0.00036}{8 \times 300} = \frac{36}{2400} = 0.015\ \text{mol}.\]

Molecules = \(n \times\) Avogadro’s number, \(N_A = 6.02214076 \times 10^{23}\) = 602214076000000000000000:

\[0.015 \times 602\,214\,076\,000\,000\,000\,000\,000 = 9\,033\,211\,140\,000\,000\,000\,000 \approx 9.03 \times 10^{21}.\]

(The roundings are generous: 1 atm is 101 325 Pa, 12 US fl oz is \(0.000355\ \text{m}^3\) and \(R\) is 8.314. With those, \(n \approx 0.0144\) mol and the count is about \(8.7 \times 10^{21}\). Either way only the first two or three digits mean anything.)

What this says about storing numbers. Avogadro’s number needs 79 bits as an integer, and the answer 73. The volume, \(0.00036\), has its first 1 only in the 12th place after the binary point (\(2^{-12} \approx 0.000244\)), so it needs at least 12 fractional bits to register at all. A format that held all three exactly would need about 80 integer bits and a few dozen fractional bits, almost all of them zero in any one value, and every digit past the third would be noise anyway. What is worth storing is the significant digits and the scale, separately. That is floating point, and the stepping stone to it is fixed point.

Fractions in binary: fixed point

Place values continue past the binary point by halving: \(2^{-1} = \tfrac12\), \(2^{-2} = \tfrac14\), \(2^{-3} = \tfrac18\), \(2^{-4} = \tfrac1{16}\). Fixed-point notation chooses a place for the point, arbitrarily, and keeps it there. The point is never stored; it is an agreement about how to read the bits.

\(2^3\) \(2^2\) \(2^1\) \(2^0\) . \(2^{-1}\) \(2^{-2}\) \(2^{-3}\) \(2^{-4}\)
8 4 2 1 . \(\tfrac12\) \(\tfrac14\) \(\tfrac18\) \(\tfrac1{16}\)

A format with \(m\) integer bits and \(n\) fractional bits is called \(m.n\). The full treatment is fixed-point-numbers.

Worked: representing 4.375

How is 4.375 represented in 8-bit fixed point, with 4, 5 or 3 integer bits?

Whole part: \(4 = 100_2\).

Fraction, by repeated doubling: \(0.375 \times 2 = 0.75\) (bit 0), \(0.75 \times 2 = 1.5\) (bit 1), \(0.5 \times 2 = 1.0\) (bit 1), and the fraction is now 0. Reading the bits in the order they came: \(0.375 = 0.011_2\). As a check by subtraction, \(0.375 - 0.25 = 0.125 = \tfrac18\), so the \(\tfrac14\) and \(\tfrac18\) bits are set.

Or all at once: with 3 fractional bits, every value is a whole number of eighths. \(4.375 \times 8 = 35 = 100011_2\); put the point back three places from the right: \(100.011_2\).

So \(4.375 = 100.011_2\), and in each format:

Format Bits
4.4 0100.0110
5.3 00100.011
3.5 100.01100

Figure 141: The value 4.375 in three 8-bit fixed-point formats. The significant bits 1, 0, 0, 0, 1, 1 are the same every time; each lines up with the same place values, 4, 1/4 and 1/8, wherever the point is put. Moving the point one place left therefore shifts the bits one place left in the byte, a 0 dropping off the left end and a 0 joining on the right. The format decides which values fit: 4.375 needs at least 3 integer bits and 3 fractional bits, and all three formats here have that.

Worked: 10110101 as unsigned 5.3

What does the 8-bit number 10110101 represent in unsigned fixed-point notation with 5 integer bits and 3 fractional bits?

Split it 5 and 3: 10110.101.

  • Integer bits 10110 \(= 16 + 4 + 2 = 22\).
  • Fraction bits .101 \(= \tfrac12 + \tfrac18 = 0.625\).

Answer: 22.625. Check: read as a whole number the byte is 181, and \(181 / 2^3 = 22.625\).

Worked: 10110101 as two’s complement 5.3

What does the same 10110101 represent in two’s complement fixed-point notation with 5 integer bits and 3 fractional bits? Choices: \(-9.375\), \(-10.625\), \(-9.625\).

In two’s complement the MSB’s weight is negative (binary-number-representations). In 5.3 the MSB is worth \(-2^4 = -16\), and every other bit keeps its positive weight, fraction bits included:

\[\underbrace{-16}_{1} + \underbrace{0}_{0} + \underbrace{4}_{1} + \underbrace{2}_{1} + \underbrace{0}_{0}\ .\ \underbrace{\tfrac12}_{1} + \underbrace{0}_{0} + \underbrace{\tfrac18}_{1} = -10 + 0.625 = -9.375.\]

Answer: \(-9.375\). Two checks:

  • Unsigned it was 22.625. A set MSB in two’s complement subtracts \(2^5 = 32\) from the unsigned reading: \(22.625 - 32 = -9.375\).
  • Negate it: invert every bit, 01001.010 \(= 9.25\), and add 1 in the last place, \(\tfrac18\): \(9.375\). So the original is \(-9.375\).

Where the other two come from:

  • \(-10.625\) reads the integer bits correctly as \(-10\) and then attaches the fraction as if it shared the sign, \(-(10 + 0.625)\). But the fraction bits have positive weight: \(-10 + 0.625 = -9.375\).
  • \(-9.625\) inverts only the integer bits (10110 → 01001 = 9) and keeps .101 as it is. That is neither rule: negating needs every bit inverted and then a 1 added in the last place.

Figure 142: One byte, 10110101, read in two 5.3 formats. The weights are identical except for the MSB, which is worth +16 unsigned and -16 in two’s complement. Summing the weights of the 1 bits (the weights of the 0 bits are greyed out) gives 22.625 unsigned and -9.375 two’s complement, and the two differ by exactly 32, twice the MSB’s weight. The fraction bits add 1/2 and 1/8 in both readings: a two’s complement fraction is never subtracted.

Range against precision

Every 8-bit format has the same 256 patterns; the format only spaces them. For unsigned \(m.n\) the precision is the last bit’s weight, \(2^{-n}\), and the maximum is all ones, \(255 \times 2^{-n}\):

Format Maximum Precision Format Maximum Precision
8.0 255 1 4.4 15.9375 0.0625
7.1 127.5 0.5 3.5 7.96875 0.03125
6.2 63.75 0.25 2.6 3.984375 0.015625
5.3 31.875 0.125 1.7 1.9921875 0.0078125
“9.$-\(1" | 510 | 2 | | 0.8 | 0.99609375 | 0.00390625 | | "10.\)-$2” 1020 4

8.0 is xxxxxxxx. (an ordinary byte), 7.1 is xxxxxxx.x, 6.2 is xxxxxx.xx, and so on. Each place the point moves left halves both the maximum and the step. The formats in quotes go the other way: in “9.$-\(1" the point sits one place *beyond* the byte, `xxxxxxxx0.`, so the lowest stored bit is worth 2 and only even numbers up to 510 exist; "10.\)-$2” is xxxxxxxx00., multiples of 4 up to 1020. No choice of point gets range and precision together. Two’s complement ranges, and a drawing of the point sliding, are in fixed-point-numbers.

Letting the point move

Natural language and scientific notation

People handle the same problem with a variable decimal point. In words, SI prefixes move it: kilometre, milligram, femtometre, yoctogram, each prefix a power of 10. In symbols, scientific notation writes significant digits times a power of 10: Avogadro’s number is \(6.02 \times 10^{23}\), and the cup’s \(0.00036\ \text{m}^3\) is \(3.6 \times 10^{-4}\ \text{m}^3\). A few digits plus an exponent covers any size.

Normalisation

The same value can be written \(602 \times 10^{21}\), \(60.2 \times 10^{22}\), \(6.02 \times 10^{23}\) or \(0.602 \times 10^{24}\). Normalised means one non-zero digit before the point, the digits in \([1, 10)\), so \(6.02 \times 10^{23}\) is the normalised one: \(602 \times 10^{21}\) and \(60.2 \times 10^{22}\) have too many digits before the point, and \(0.602 \times 10^{24}\) has a zero there.

In binary the range is \([1, 2)\): the only non-zero binary digit is 1, so a normalised binary number is always \(1.xxx_2 \times 2^e\).

Worked: which two are correctly normalised in binary?

Which two of these values have the correct binary normalisation?

A. \(15.940 \times 2^{75}\) B. \(7.970 \times 2^{76}\) C. \(3.985 \times 2^{77}\) D. \(1.993 \times 2^{78}\) E. \(0.996 \times 2^{79}\)

F. \(11.796 \times 2^{-15}\) G. \(5.898 \times 2^{-14}\) H. \(2.949 \times 2^{-13}\) I. \(1.475 \times 2^{-12}\) J. \(0.737 \times 2^{-11}\)

Answer: D and I, the only two with the multiplier in \([1, 2)\).

The two rows are each one number written five ways: halving the multiplier and adding 1 to the exponent leaves the value unchanged. A to E are all \(\approx 6.02 \times 10^{23}\), Avogadro’s number; F to J are all \(\approx 3.60 \times 10^{-4}\), the volume of the cup in m³ (to the three decimals shown). Exactly one spelling of each is normalised.

Option Multiplier Normalised in binary? Why not
A 15.940 \(\times\) \(\geq 2\): shift three more places
B 7.970 \(\times\) \(\geq 2\): shift two more places
C 3.985 \(\times\) \(\geq 2\): shift one more place
D 1.993 \(\checkmark\)
E 0.996 \(\times\) \(< 1\): a leading 0
F 11.796 \(\times\) \(\geq 2\)
G 5.898 \(\times\) \(\geq 2\)
H 2.949 \(\times\) \(\geq 2\)
I 1.475 \(\checkmark\)
J 0.737 \(\times\) \(< 1\): a leading 0

The trap is the decimal rule. B, C, G and H have one non-zero digit before the point, so they look normalised by the \([1, 10)\) rule. But the base here is 2, and with base 2 the multiplier must be in \([1, 2)\). E and J fail the other way: their leading digit is 0.

Figure 143: The ten multipliers on a number line, Avogadro’s number written five ways above the line and the cup’s volume five ways below. Each step left halves the multiplier and adds 1 to the power of 2, so the value stays the same. A binary normalised multiplier must lie in [1, 2), the shaded window, and exactly one spelling of each number lands in it: D, 1.993, and I, 1.475. E, at 0.996, sits just outside the left edge, and D just inside the right one. The wider window [1, 10) of decimal normalisation would wrongly admit B, C, G and H as well.

Why “mantissa”

The digits part of a floating-point number is called the mantissa, a name taken from logarithm tables. Logarithms turn multiplication into addition, \(\log(a \times b) = \log a + \log b\), and before calculators that was done with printed tables. A standard four-figure table gives the logarithms of 1.00 to 9.99: row 12, column 3 reads 0899, meaning \(\log_{10} 1.23 \approx 0.0899\).

Worked: three logarithms from one table entry

Given \(\log_{10} 1.23 \approx 0.0899\), what are \(\log_{10} 12.3\), \(\log_{10} 123\) and \(\log_{10} 0.123\)?

Each is \(1.23\) times a power of 10, and the log of a product is the sum of the logs:

  • \(\log_{10} 12.3 = \log_{10} (1.23 \times 10) = 0.0899 + 1 = \mathbf{1.0899}\)
  • \(\log_{10} 123 = \log_{10} (1.23 \times 10^2) = 0.0899 + 2 = \mathbf{2.0899}\)
  • \(\log_{10} 0.123 = \log_{10} (1.23 \times 10^{-1}) = 0.0899 - 1 = \mathbf{-0.9101}\)

The fractional part, 0.0899, is the same every time and depends only on the digits 1, 2, 3: that was the mantissa. The integer part, 1, 2 or \(-1\), only places the point: that was the characteristic. (For \(0.123\), tables kept the mantissa visible by writing \(\bar{1}.0899\), meaning \(-1 + 0.0899\).) So the table only needs mantissas, and the power of 10 is handled by adding a whole number. A floating-point number splits the same way, digits and an exponent, and the digits took the old name.

Figure 144: Logarithms of 0.123, 1.23, 12.3 and 123 on a log scale. Each is ten times the one before, so each sits exactly one unit further along. Every logarithm splits into a whole number, the characteristic, plus the same fractional part, 0.0899, which depends only on the digits 1, 2, 3; that fractional part was called the mantissa. The characteristic only records the power of 10, which is to say where the point goes.

IEEE 754

The standard formats store a sign bit \(S\), an exponent field \(E\) and a mantissa field \(M\), and mean

\[(-1)^S \times 1.M_2 \times 2^{E - \text{bias}}.\]

  • Single precision, 32 bits: 1 sign bit, 8 exponent bits in excess-127 format, 23 mantissa bits.
  • Double precision, 64 bits: 1 sign bit, 11 exponent bits in excess-1023 format, 52 mantissa bits.
  • The mantissa is normalised, so it begins with 1, and that 1 is implicit: it is not stored, which buys a 24th (or 53rd) significant bit. The exception is the subnormal numbers (below), where the hidden bit is 0.

Excess-127 means the field holds the true exponent plus 127. It is the excess notation of binary-number-representations, but with a bias one less than \(2^7 = 128\). The field layouts are drawn in floating-point-numbers.

Worked: why sign, then exponent, then mantissa?

Why are the fields in the order sign, exponent, mantissa?

So that floats compare like integers. Take \(1 \times 2^{100}\) and \(3 \times 2^{20}\). The first is far bigger despite the smaller leading number, because the exponent fixes the scale and the mantissa only refines it within that scale. Normalised, they are \(1.0_2 \times 2^{100}\) and \(1.1_2 \times 2^{21}\), with exponent fields \(100 + 127 = 227\) and \(21 + 127 = 148\). With the exponent in the high bits, comparing the two 32-bit patterns as unsigned integers compares 227 with 148 first and gets the right answer without looking at the mantissas. The mantissa only decides between numbers with equal exponents, which is exactly when it should.

The bias helps: in excess form larger exponents, negative ones included, are always larger unsigned fields. And the sign at the very top separates negatives from positives first. So the integer comparison circuits can sort non-negative floats directly.

Conversion steps

  1. Convert to binary scientific notation, normalised.
  2. Store the sign: \(+ \to 0\), \(- \to 1\).
  3. Store the biased exponent: true exponent \(+ 127\).
  4. Store the mantissa: drop the implicit 1 and right-pad with zeros to 23 bits.

Then group into nibbles for hex. And beware of special values: zero, infinity and NaN have reserved patterns.

Worked: \(-23.25\) to IEEE single precision

Convert \(-23.25\) to an IEEE single-precision floating-point number, expressed in hexadecimal.

1. Binary scientific notation. \(23 = 10111_2\) and \(0.25 = 0.01_2\), so \(23.25 = 10111.01_2\). Move the point four places left: \(10111.01_2 = 1.011101_2 \times 2^4\).

2. Sign. Negative, so \(S = 1\).

3. Exponent. \(4 + 127 = 131 = 10000011_2\).

4. Mantissa. Drop the leading 1: 011101, then pad with zeros on the right to 23 bits: 01110100000000000000000.

Assemble and group:

S Exponent Mantissa
1 10000011 01110100000000000000000

1100 0001 1011 1010 0000 0000 0000 0000 = C 1 B A 0 0 0 0, so \(-23.25\) = 0xC1BA0000.

Checks: \(+23.25\) differs only in the sign bit, 0x41BA0000. In double precision the exponent is \(4 + 1023 = 1027\) and the pattern 0xC037400000000000; in half precision (5-bit exponent, bias 15) it is 0xCDD0.

Figure 145: Encoding -23.25 in single precision. The minus sign becomes a 1 in the sign bit. The value 10111.01 in binary is normalised to 1.011101 times 2 to the 4, the 4 is stored as 4 + 127 = 131, and the bits after the leading 1 fill the mantissa field from the left, with zeros padding it out on the right. The 32 bits then group into nibbles from the left, giving C1BA0000 in hexadecimal. The nibble boundaries do not line up with the field boundaries: the C takes the sign and the first three exponent bits.

Worked: 0x422F0000 to decimal

Convert 0x422F0000 from an IEEE floating-point number to a decimal value.

Bits. 4 2 2 F 0 0 0 0 = 0100 0010 0010 1111 0000 0000 0000 0000.

Split 1 / 8 / 23.

S Exponent Mantissa
0 10000100 01011110000000000000000
  • Sign 0: positive.
  • Exponent \(10000100_2 = 132\), not all 0s or all 1s, so normal; true exponent \(132 - 127 = 5\).
  • Mantissa: put back the hidden 1: \(1.0101111_2\).

Value. \(+1.0101111_2 \times 2^5\): move the point five places right, \(101011.11_2 = 32 + 8 + 2 + 1 + \tfrac12 + \tfrac14 = \mathbf{43.75}\).

Figure 146: Decoding 0x422F0000. Each hex digit expands to four bits, and the 32 bits are then cut at the field boundaries, which fall in the middle of the first three hex digits. The sign bit 0 means positive. The exponent field 10000100 is 132, so the true exponent is 132 - 127 = 5. The mantissa field gets its hidden 1 back in front, giving 1.0101111, and shifting the point five places right gives 101011.11, which is 43.75.

Finite precision

Not every number can be represented precisely. A float has a fixed number of mantissa bits, so a value that needs more is rounded, and rounding happens again after every operation.

Worked: does \((10.0 \div 3) \times 3\) give 10.0?

Is \((10.0 \div 3) \times 3\) equal to \(10.0\) in floating point?

\(10 \div 3 = 3.333\ldots = 11.010101\ldots_2\), with 01 repeating for ever, so the stored quotient is cut short and is not exactly \(\tfrac{10}{3}\). In 3-digit decimal the effect is plain: \(10.0 \div 3 = 3.33\), and \(3.33 \times 3 = 9.99\).

In binary it depends on how the two roundings fall. For this particular case they cancel, and single and double precision both give exactly 10.0. But nothing guarantees it: in single precision \((1 \div 41) \times 41 = 0.99999994\), in double \((1 \div 49) \times 49 = 0.9999999999999999\), and in quarter precision \((13 \div 3) \times 3 = 14\) (floating-point-numbers). So \((10.0 \div 3) \times 3\) may not equal \(10.0\), and floats should be compared with a tolerance, never with == after arithmetic.

Worked: does the order of addition matter?

Can \((A + B) + C\) differ from \(A + (B + C)\)?

Yes. The order in which operations are done can change the answer, which is often summed up loosely as floating point being occasionally non-commutative. Strictly, the law that fails is associativity: \(A + B\) always equals \(B + A\), but grouping the terms differently rounds different intermediate sums. In double precision:

  • \((0.1 + 0.2) + 0.3 = 0.6000000000000001\)
  • \(0.1 + (0.2 + 0.3) = 0.6\)

Worked: when is \((X + \delta) - X = 0\)?

If \(X \gg \delta\), what is \((X + \delta) - X\)?

It can be zero. Near \(X\) the representable values are about \(X \times 2^{-23}\) apart in single precision. If \(\delta\) is under half that gap, \(X + \delta\) rounds back to \(X\) and \(\delta\) is lost; at exactly half it is a tie, which goes to whichever neighbour has a 0 as its last mantissa bit. With \(X = 2^{24} = 16\,777\,216\), where the gap is 2, and \(\delta = 1\): \(X + 1\) is a tie between \(X\) and \(X + 2\), goes to \(X\) (the even one), and \((X + 1) - X = 0\). It also gives a second non-associative sum: \((X + 1) + 1 = X\), but \(X + (1 + 1) = X + 2\). The same thing in quarter precision is drawn in floating-point-numbers.

Comparing float sizes

Every IEEE binary format has the same structure; only the widths change. With \(m\) mantissa bits the next value after 1 is \(1 + 2^{-m}\), and the largest finite value is \((2 - 2^{-m}) \times 2^{\text{bias}}\).

Quarter Half Single Double Quadruple Octuple
Total bits 8 16 32 64 128 256
Sign bits 1 1 1 1 1 1
Exponent bits 4 5 8 11 15 19
Mantissa bits 3 10 23 52 112 236
Next after 1 \(1 + \tfrac18 = 1.125\) \(1 + \tfrac1{1024} \approx 1.001\) \(1 + 2^{-23}\) \(\approx 1 + 1.2 \times 10^{-7}\) \(1 + 2^{-52}\) \(\approx 1 + 2.2 \times 10^{-16}\) \(1 + 2^{-112}\) \(\approx 1 + 1.9 \times 10^{-34}\) \(1 + 2^{-236}\) \(\approx 1 + 9.1 \times 10^{-72}\)
Maximum 240 65504 \(\approx 3.4 \times 10^{38}\) \(\approx 1.8 \times 10^{308}\) \(\approx 1.2 \times 10^{4932}\) \(\approx 1.6 \times 10^{78913}\)
Use ultra rare rare common common rare ultra rare

Quarter precision is not a standard format; it follows the same rules at 8 bits (bias 7) so that every value can be listed. The exponent width sets the range and the mantissa width the precision, and as the formats grow almost all the extra bits go to the mantissa. Each extra exponent bit roughly squares the maximum: \(240 \approx 2^8\) with 4 bits, \(65504 \approx 2^{16}\) with 5, \(3.4 \times 10^{38} \approx 2^{128}\) with 8, \(1.8 \times 10^{308} \approx 2^{1024}\) with 11. A to-scale drawing of the six layouts is in floating-point-numbers.

Special values

Two exponent fields are reserved. The exponent in this table is the field exactly as stored, with no bias taken off: 0 means the bits are all 0s, and the maximum, all 1s, is 255 in single precision.

Exponent field (as stored) Mantissa \(= 0\) Mantissa \(\neq 0\)
0 \(\to\) all 0s \(\pm 0\) subnormal numbers
anything else normal numbers normal numbers
maximum \(\to\) all 1s (255 for single precision) \(\pm\) infinity \(\pm\) NaN (not a number)

This raw field is often called the unbiased exponent, in the sense that the bias has not yet been subtracted; the true exponent of a normal number is the field minus 127.

  • Zero is zero: all exponent and mantissa bits 0. It cannot be normalised, so it needs its own pattern, and with the separate sign bit there is a \(+0\) and a \(-0\).
  • Subnormal numbers have an implicit leading 0 instead of 1, which breaks the scientific-notation convention on purpose so that values below the smallest normal number can be held. They use the same exponent as the smallest normal numbers, \(2^{-126}\) in single precision, not the \(2^{0 - 127} = 2^{-127}\) the bias would suggest; that way they continue the smallest normal binade at the same spacing down to 0.
  • Infinity: numbers too big to store (past about \(3.4 \times 10^{38}\) in single), and results such as \(1 \div 0\), \(-\log 0\) and \(\tan(\pi \div 2)\).
  • NaN: “bad” calculations with no meaningful result.

Worked: every positive quarter-precision float

List every positive value of the quarter-precision format (1 sign, 4 exponent, 3 mantissa bits, bias 7).

Rows are the sign bit and exponent field, columns the mantissa field. A normal row \(E\) holds \(1.M_2 \times 2^{E - 7}\); row 0000 (italics) holds the subnormals, \(0.M_2 \times 2^{-6}\); row 1111 holds infinity and NaN.

Sign, exponent …000 …001 …010 …011 …100 …101 …110 …111
0 0000 0 0.001953125 0.00390625 0.005859375 0.0078125 0.009765625 0.01171875 0.013671875
0 0001 0.015625 0.017578125 0.01953125 0.021484375 0.0234375 0.025390625 0.02734375 0.029296875
0 0010 0.03125 0.03515625 0.0390625 0.04296875 0.046875 0.05078125 0.0546875 0.05859375
0 0011 0.0625 0.0703125 0.078125 0.0859375 0.09375 0.1015625 0.109375 0.1171875
0 0100 0.125 0.140625 0.15625 0.171875 0.1875 0.203125 0.21875 0.234375
0 0101 0.25 0.28125 0.3125 0.34375 0.375 0.40625 0.4375 0.46875
0 0110 0.5 0.5625 0.625 0.6875 0.75 0.8125 0.875 0.9375
0 0111 1 1.125 1.25 1.375 1.5 1.625 1.75 1.875
0 1000 2 2.25 2.5 2.75 3 3.25 3.5 3.75
0 1001 4 4.5 5 5.5 6 6.5 7 7.5
0 1010 8 9 10 11 12 13 14 15
0 1011 16 18 20 22 24 26 28 30
0 1100 32 36 40 44 48 52 56 60
0 1101 64 72 80 88 96 104 112 120
0 1110 128 144 160 176 192 208 224 240
0 1111 Inf NaN NaN NaN NaN NaN NaN NaN

Three cells worked by hand:

  • 0 0111 000: \(E = 7\), \(1.000_2 \times 2^{0} = 1\). Exponent field 7 is the bias, so this row runs from 1 to 1.875 in steps of \(\tfrac18\), which is where “next after 1 = 1.125” comes from.
  • 0 1110 111: \(1.111_2 \times 2^{14-7} = 1.875 \times 128 = 240\), the maximum.
  • 0 0000 001: subnormal, \(0.001_2 \times 2^{-6} = \tfrac18 \times \tfrac1{64} = \tfrac1{512} = 0.001953125\), the smallest positive value. The step along this row, \(\tfrac1{512}\), is the same as the step along row 0001.

Each normal row is twice the one above it, so the gap between neighbours doubles every row while the relative precision stays the same; and counting up through the bit patterns counts up through the values. The number-line picture is in floating-point-numbers.

Not a number (NaN)

NaN represents the result of an operation that has no solution:

  • \(0 \div 0\), \(0 \times \infty\), \(\infty - \infty\);
  • \(\sqrt{-1}\), \(\log(-1)\), \(\sin^{-1} 20\);
  • \(0^0\), an indeterminate form (IEEE’s powr(0, 0) gives NaN, though C’s pow(0, 0) returns 1).

Once a NaN appears it propagates as a NaN through subsequent operations: \(\text{NaN} + 1\), \(\text{NaN} \times 0\) and \(\sqrt{\text{NaN}}\) are all NaN, so the final result shows that something went wrong earlier. The exceptions are the few functions whose answer does not depend on the missing value, such as pow(NaN, 0) = 1, and comparisons, which return false instead: x == x is false for a NaN, which is how one is detected.

Floating point in C and on the AVR

  • float and double are usually single and double precision, but C only sets minimums. Simplified, float must represent numbers up to \(10^{37}\) with 6 decimal digits of accuracy, and double numbers up to \(10^{37}\) with 10 decimal digits, and not less accurately than float.
  • In AVR C, double is the same as float, 32-bit single precision. That falls short of the standard, since single precision gives only about 7 digits.
  • GCC provides _Float16 and __float128 for half and quadruple precision. There is no type for quarter or octuple precision.
  • Integer calculations with equivalent results are preferable. The AVR has no floating-point hardware, so every float operation is a library routine.
PORTB = PINA / 3;        /* 8 branchless instructions          */
PORTB = PINA * 0.334f;   /* 300+ instructions, with branches   */

Both give the same PORTB for all 256 values of PINA (checked exhaustively). The first divides by a constant, which a compiler can do with an integer multiply and a shift, for example \((x \times 171) \gg 9\), which equals \(\lfloor x / 3 \rfloor\) for every byte. The second converts PINA to a float, runs the software multiply, and converts back, each step a routine that unpacks fields, normalises, rounds and tests for special cases. More in floating-point-numbers and c-language-basics.

See also

Lecture 24 — Memory, Disks and Files

The memories a computer is built from, from the registers down to the disk, and how a disk’s sectors become named files. The note covers why computers need memory and the ways memory is classified; static and dynamic RAM; volatile and non-volatile memory and the family from ROM to flash; the ATmega324A’s three memories; when a megabyte is not a megabyte; the generations of DRAM; the memory hierarchy and cache; how a magnetic disk is organised and how long it takes to reach a sector; and files, file systems, formatting, blocks and fragmentation. The reference notes are memory-technologies, memory-hierarchy-and-cache, magnetic-disks and file-systems. The AVR’s address spaces are in memory-models.

Goals

  1. Classify a memory as random or sequential access, static or dynamic, volatile or non-volatile, read-only or read/write, and primary or secondary, and place SRAM, DRAM, ROM, flash, SSDs and hard disks on each axis.
  2. Explain how SRAM and DRAM store a bit, and why DRAM needs refreshing.
  3. Tell ROM, EPROM, EEPROM and flash apart by how each is erased, and say which memory on the ATmega324A holds what.
  4. Convert between the decimal and binary meanings of kB, MB and GB, and say which is used where.
  5. Describe the memory hierarchy and explain how a cache reduces the average access time.
  6. Describe a disk’s platters, surfaces, tracks, sectors and cylinders, and calculate its average access time.
  7. Explain what a file system does, what formatting and deleting change, how block size trades map size against wasted space, and why fragmentation slows access.

Why computers need memory

A computer needs memory for three different jobs. A running program needs somewhere to keep its temporary results. The program itself has to be stored somewhere the processor can fetch it from. And some things, settings above all, have to be remembered while the power is off.

They pull in different directions: fast and endlessly rewritable for the first, permanent for the third. So there are many different types of memory, and five questions sort them (memory-technologies).

Classifying memory

Axis Meaning Examples
Random access or sequential access any cell reached directly by its address, or the data passed over in order to get to it almost all memory chips are random access; a tape is sequential
Static or dynamic a bit held by a flip-flop, or as charge that must be refreshed SRAM (flip-flops) is static; DRAM is dynamic
Volatile or non-volatile contents lost or kept at power-off SRAM and DRAM are volatile; flash is non-volatile
Read-only cannot be written in normal use ROM
Primary or secondary addressed directly by the processor, or reached through I/O SRAM (and DRAM) are primary; SSDs and HDDs are secondary

Random access is what an address decoder provides (memory-models): the address bits select one cell directly, and every cell takes the same time. With 1 address bit there are 2 cells to choose from, with 2 bits 4, each address picking out its own cell.

Where SRAM, DRAM, ROM, flash, SSDs and hard disks fall on each of the five axes is charted in memory-technologies.

Static and dynamic memory

Static memory, SRAM, keeps each bit in a flip-flop or latch (flip-flops-and-latches). A flip-flop holds its bit for as long as there is power with nothing more to do, and it is fast, but it takes several transistors per bit, so SRAM is expensive.

Dynamic memory, DRAM, builds each cell from a transistor, used as a switch, and a capacitor. The bit is the charge on the capacitor. That charge leaks away, so every cell has to be refreshed, read and written back, every few tens of milliseconds (around 20 ms).

Both are kinds of RAM, random access memory. The name once meant only that any cell could be reached directly, as opposed to sequential access, which would make ROM random access too. In current use it means volatile read/write memory, and SRAM and DRAM are its two forms. The cells of each are drawn in memory-technologies.

Volatility

A volatile memory loses its contents when the power goes off, and both SRAM and DRAM are volatile. DRAM is the more forgetful of the two: even with the power on, a cell that is not refreshed loses its charge within milliseconds.

A non-volatile memory keeps its contents with the power off. ROM, EPROM, EEPROM and flash are all non-volatile, and they differ in whether, and how, they can be rewritten.

Non-volatile memory chips

The four non-volatile chips form a family, each easier to rewrite than the last.

  • ROM (read-only memory) has its contents fixed in the silicon by the maker. It can never be changed.
  • EPROM (erasable programmable ROM) is programmed electrically and erased with ultraviolet light. The package has a small window over the chip; a UV lamp shone through it erases the whole chip, ready to be programmed again.
  • EEPROM (electrically erasable PROM) is erased by applying a voltage, so it can be rewritten in the circuit, one cell at a time.
  • Flash is a newer EEPROM. The two began as different technologies and have been converging; what still separates them is that flash is written and erased in blocks, while EEPROM is written and erased one cell at a time.

The ATmega324A’s flash is split into two blocks, an application section and a boot loader section. A boot loader is a small program that writes a new program into the application section, and keeping the two in separate blocks lets one be erased and rewritten while the other is left alone. Other AVR devices have a single flash block, and some have more. The family is drawn in memory-technologies.

The ATmega324A’s memories

The chip’s block diagram has three memories among its peripherals, each a separate address space with its own assembler segment (memory-models):

Memory Technology Volatile? Holds Segment
FLASH, 32 kB flash no the program .cseg
SRAM, 2 kB static RAM yes variables and the stack .dseg
EEPROM, 1 kB EEPROM no data that must survive power-off .eseg

All three connect to the AVR CPU over the chip’s internal data bus, alongside the A/D converter, the analog comparator, SPI, TWI, JTAG and the four timer/counters. What each memory is for, and how the boot loader rewrites the application block, is drawn in memory-technologies; the address maps of program and data memory are in memory-models.

When is a megabyte not a megabyte?

A megabyte is not always \(2^{20}\) bytes: sometimes it is a million. In SI units and in physics, kilo, mega and giga are \(10^3 = 1000\), \(10^6\) and \(10^9\). In computing they have conventionally, or at least historically, been \(2^{10} = 1024\), \(2^{20}\) and \(2^{30}\). The full treatment is in memory-technologies.

Worked: 1 MB and 1 GB in their various meanings

How many bytes are in 1 MB, and in 1 GB? How big is the difference between the meanings?

1 MB.

  • Conventionally: \(1\text{ MB} = 2^{10}\text{ kB} = 1{,}024\text{ kB} = 2^{20}\text{ B} = \mathbf{1{,}048{,}576}\) B.
  • Sometimes: \(1\text{ MB} = 10^6\text{ B} = \mathbf{1{,}000{,}000}\) B.
  • Or in between: \(1000\text{ kB} = 1000 \times 1024 = \mathbf{1{,}024{,}000}\) B.

1 GB.

  • Conventionally: \(1\text{ GB} = 2^{10}\text{ MB} = 2^{20}\text{ kB} = 2^{30}\text{ B} = \mathbf{1{,}073{,}741{,}824}\) B.
  • Sometimes: \(1\text{ GB} = 10^9\text{ B} = \mathbf{1{,}000{,}000{,}000}\) B.
  • Or in between: \(1000 \times 2^{20} = \mathbf{1{,}048{,}576{,}000}\) B.

The difference. \(2^{30} - 10^9 = 73{,}741{,}824\) bytes, and

\[\frac{73{,}741{,}824}{10^9} = 7.37\,\% \approx 7.4\,\%.\]

So the binary gigabyte is 7.4 % bigger than the decimal one. (Measured the other way, the decimal gigabyte is \(73{,}741{,}824 / 2^{30} = 6.87\,\%\) smaller.) For the megabyte the gap is only \(48{,}576 / 10^6 = 4.86\,\%\), and for the kilobyte \(24/1000 = 2.4\,\%\): the gap grows with each prefix because each step multiplies by 1024 rather than 1000.

Figure 147: The three meanings of 1 MB and of 1 GB, placed on one scale by how far each lies above the decimal meaning. A binary megabyte, 1,048,576 bytes, is 4.86 per cent above a million bytes; a binary gigabyte, 1,073,741,824 bytes, is 7.37 per cent above a billion. The in-between meaning, a decimal thousand of the next binary unit down, is always one factor of 1.024 (2.4 per cent, the arrows) short of the binary one, so the in-between gigabyte lands exactly on the binary megabyte’s 4.86 per cent (dashed).

When do we use powers of 2, and when powers of 10?

  • Main memory capacity is always quoted in powers of 2: \(1\text{ GB} = 1024 \times 1024 \times 1024\text{ bytes} = 2^{30}\) bytes. A memory with \(n\) address lines has exactly \(2^n\) cells (2 for one line, \(2^2 = 4\) for two, \(2^3 = 8\) for three), so memory comes in powers of 2.
  • Hard disk makers quote powers of 10, \(1\text{ GB} = 1000 \times 1000 \times 1000\text{ bytes} = 10^9\) bytes, which makes a disk look bigger.
  • Operating systems such as Windows count in powers of 2, which is why a new disk always shows less than its label.
  • Data rates are usually powers of 10: 1 Gbps (gigabit per second) is \(10^9\) bits per second.
  • Occasionally a figure mixes the two.

Worked: the 1.44 MB floppy disk

A “1.44 MB” floppy disk stores \(1.44 \times 1000 \times 1024\) bytes. How many bytes is that, and how many MB is it in each of the two pure meanings?

\[1.44 \times 1000 \times 1024 = \mathbf{1{,}474{,}560}\ \textbf{bytes}.\]

In binary megabytes that is \(1{,}474{,}560 / 2^{20} = 1.40625\) MB; in decimal megabytes, \(1{,}474{,}560 / 10^6 = 1.47456\) MB. The “1.44” is neither: it counts thousands of 1024-byte kilobytes, a decimal mega of binary kilos.

Worked: a disk in the operating system

A disk sold as 500 GB is formatted and the operating system, counting in powers of 2, reports its size. About how many “GB” does it show?

The maker’s 500 GB is \(500 \times 10^9\) bytes. The OS divides by \(2^{30}\): \(500 \times 10^9 / 1{,}073{,}741{,}824 = \mathbf{465.66}\) GB. Nothing is missing; the gigabytes differ by 7.4 %. (Formatting takes a little more, for the file system’s tables.)

Kibibytes and mebibytes

In SI units kilo, mega and giga mean powers of 10, so separate names were standardised for the binary meanings:

  • 1 kibibyte \(=\) 1 KiB \(=\) 1024 bytes;
  • 1 mebibyte \(=\) 1 MiB \(=\) 1024 KiB;
  • 1 gibibyte \(=\) 1 GiB \(=\) 1024 MiB.

They have not caught on, and kilo, mega and giga are still used for both meanings. These notes do the same, so the context decides which is meant, and it is worth saying so when it matters.

Types of DRAM

DRAM stores bits as charge on capacitors rather than in flip-flops. Its cells are smaller, so a chip holds more bits than a static memory chip, at the cost of being slower. The cell has stayed the same while the interface has gone through many generations:

  • Fast Page Mode (FPM DRAM) and Extended Data Out (EDO DRAM), a closely related pair of asynchronous designs, EDO a refinement of FPM;
  • Synchronous DRAM (SDRAM), clocked, the step every later type builds on;
  • Rambus DRAM (RDRAM);
  • Double Data Rate DRAM (DDR DRAM), generations 1, 2, 3, 4 and now 5, which move data on both clock edges;
  • and, for graphics cards, GDDR, now at GDDR7.

What each changed is in memory-technologies.

The memory hierarchy

No memory is fast, big and cheap at once, so computers use a hierarchy of them, with the CPU at the top.

Level Technology Capacity Cost per bit Access time
Registers (r0 to r31 on the AVR) flip-flops under a kB $$$ ~1 ns
Cache, itself in levels L1, L2, L3 SRAM ~MB $$ ~10 ns
Main memory DRAM ~GB $ up to ~1 µs
Magnetic disk HDD, or an SSD ~TB a fraction of a $ ~1 to 10 ms
Tape, optical disk ~PB a smaller fraction ~100 ms and up

Going down the hierarchy, capacity increases, cost per bit falls, and access time grows. The values are orders of magnitude, and the point is the trend. The hierarchy is drawn as a pyramid, with the CPU at its apex, in memory-hierarchy-and-cache.

Cache memory

A CPU runs faster than its main memory can answer, and memory fast enough to keep up is too expensive to use for all of it. A CPU that waited on main memory for every access would spend most of its time idle.

A cache gets around this with a small amount of very fast memory in front of the large, slow one. It holds copies of the words in most frequent use. The CPU looks in the cache first and goes to main memory only if the word is not there, so when most accesses find their word in the cache, the average access time comes down close to the cache’s own.

Worked: why a loop runs from the cache

A program runs for (i = 0; i < 1000; i++) { ... }, reading i once per iteration. The cache answers in 10 ns, main memory in 1 µs, and the CPU looks in the cache first. What fraction of the reads of i hit the cache, and what is their average access time?

The first read of i is a miss: i is fetched from main memory over the bus and a copy is kept in the cache. Every later read finds it there. So 999 of the 1000 reads hit, \(h = 0.999\), and

\[t_{\text{avg}} = t_c + (1 - h)\,t_m = 10 + 0.001 \times 1000 = \mathbf{11\ ns},\]

against 1000 ns with no cache. A loop that ran \(10^{20}\) times would make the single miss vanish entirely. Programs reuse the same few words like this all the time, which is why a small cache answers most accesses. The general formula, and the cases \(h\) = 90, 95 and 99 %, are in memory-hierarchy-and-cache.

Cache levels

A cache is often built in levels, each larger and a little slower than the one before. L1 is inside the CPU itself and runs at the CPU’s speed; it is small, typically 32 kB to 128 kB. L2 is bigger, typically 256 kB to 16 MB, and may be slightly slower than the CPU; it can be on the CPU’s own chip or on a separate chip, possibly in the same module. Some machines add an L3, typically 2 MB to 256 MB. The CPU tries L1, then L2, then L3, and only then main memory. These sizes are in bytes: B is a byte and b is a bit, so 32 kB is \(32 \times 1024 \times 8 = 262{,}144\) bits.

Magnetic disks

A hard disk drive (HDD) is a stack of platters with a magnetised coating, spinning together on one spindle at thousands of rpm, 10,000 rpm on a fast disk. Data is stored magnetically in circular tracks: a patch magnetised one way (north up) is a 1 and the other way (south up) a 0. The read/write heads float a few nanometres (of the order of 5 nm) above the surfaces, and both sides of each platter are usually used.

The simplified view

A disk with four platters has eight surfaces, numbered 0 to 7 from the bottom, and one read/write head per surface. The heads are on one arm assembly and move in and out together. The disk is drawn from the side, with the cylinder the heads sit over, in magnetic-disks.

Sectors, tracks and cylinders

A track is one circle on one surface, and each track is divided into sectors. A cylinder is the set of tracks at a given radial position. Assuming both sides of every platter are used,

\[\text{number of tracks in a cylinder} = 2 \times \text{number of platters},\]

so the four-platter disk has 8 tracks per cylinder. The heads move together, to a certain cylinder (magnetic-disks).

Sectors

Each track is cut into fixed-length sectors, and the sector is the smallest unit the disk handles: it always reads or writes a whole one. A sector starts with a preamble, a known pattern the head uses to synchronise to the data; then comes the data; then error correction codes (ECCs) to repair small read errors; and then an inter-sector gap before the next sector.

Laid along the track, that is PRE | DATA | ECC | GAP. It is the same pattern as a UART frame of start bit, data, parity and stop bits (serial-communication): something to synchronise on, the payload, a check, and a separator. The layout is drawn in magnetic-disks.

Worked: how much of a disk holds files

About 85 % of a disk’s capacity is usable by the operating system, and about 95 % of that is usable for user data; the remaining ~5 % is file-system overhead. What fraction of the raw capacity holds user data, and how much of a 1 TB (\(10^{12}\) byte) disk is that?

User data gets \(0.85 \times 0.95 = 0.8075\), about 81 % of the raw capacity; file-system overhead is \(0.85 \times 0.05 = 4.25\,\%\) of it. On a 1 TB disk: \(0.85 \times 10^{12} = 850\) GB for the OS, and \(0.8075 \times 10^{12} = \mathbf{807.5}\) GB for files, which an OS counting in powers of 2 shows as \(807.5 \times 10^9 / 2^{30} = 752.04\) GB.

Access time

\[\text{access time} = \text{seek time} + \text{rotational latency} + \text{transfer time}\]

The seek time is spent moving the heads to the right cylinder. The rotational latency is spent waiting for the sector to come round under the head. The transfer time is the sector passing under the head as it is read, and it is so short compared with the other two that it can be neglected.

Average seek time. Suppose seek time is proportional to the distance the heads move. Measure positions from 0 at one edge to 1 at the other, and take the start \(x\) and the target \(y\) as independent and uniformly random. The average distance is

\[\int_0^1\!\!\int_0^1 |x - y|\,dx\,dy = 2\int_0^1\!\!\int_0^x (x-y)\,dy\,dx = 2\int_0^1 \frac{x^2}{2}\,dx = \frac13,\]

so

\[\text{average seek time} = \frac13\,[\text{edge-to-edge seek time}].\]

Average rotational latency. With rotation period \(T\), the wait is anything from 0 (the sector is just arriving) to \(T\) (it has just gone by), all equally likely, so the average is

\[\text{average rotational latency} = \frac{T + 0}{2} = \frac12\,T.\]

Both are derived in more detail in magnetic-disks.

Worked: average access time of a 7200 rpm disk

What is the average access time for a hard disk which rotates at 7200 rpm and has an edge-to-edge seek time of 10 ms? (Assume that seek time is proportional to the number of tracks to seek.)

The rotation period.

\[\frac{7200}{60}\ \text{rps} = 120\ \text{rps} \quad\Rightarrow\quad T = \frac{1}{120}\ \text{s} = \frac{1000}{120}\ \text{ms} = 8.33\ \text{ms}.\]

The average access time.

\[\text{average access time} = \frac13\,[10\ \text{ms}] + \frac12\left[\frac{1000}{120}\ \text{ms}\right] + \text{negligible} = 3.33 + 4.17 \approx \mathbf{7.5\ ms}.\]

Which seek convention. This uses one third of the edge-to-edge seek, because the seek is proportional to distance and both the start and the target are random, which makes the average distance a third of the way across. Taking half instead would give \(5 + 4.17 = 9.17\) ms; half is the average only when every seek starts from an edge.

Checking “negligible”. A track holds hundreds of sectors. With 1000 sectors on the track, one passes under the head in \(8.33\ \text{ms}/1000 = 8.3\ \mu\text{s}\), about 0.1 % of the 7.5 ms.

Figure 148: Three access times for the same 7200 rpm disk with a 10 ms edge-to-edge seek, drawn to scale, each a seek (dark) followed by a rotational wait (light). The true average, with both ends of the seek random, is a third of the edge-to-edge seek plus half a turn: 3.33 + 4.17 = 7.5 ms. Taking half the edge-to-edge seek, which is right only if every seek starts at an edge, overstates it at 9.17 ms. The worst case, a seek right across the disk that arrives just after the sector has passed and so waits a whole turn, is 10 + 8.33 = 18.33 ms, more than twice the average. The transfer takes microseconds and is too short to draw.

Virtual I/O: files

A program that wants to save some data should not have to know which drive, head, cylinder and sector it will land on, or what to do when a read times out and has to be retried. The operating system hides all of that behind the file, the abstraction almost all I/O goes through. To the OS a file is just a sequence of bytes; whatever structure it has, lines of text or the header of an image, is the application’s business (file-systems).

File systems

Files are far easier to use, and to program with, when they have names. A file system provides the names: it ties each file, which is really a collection of sectors, to a name in a directory. To do that it sets some sectors aside for its own index information, the File Allocation Table of the FAT file systems being one example, and uses the rest to store the files themselves. There are many file systems, differing in how they organise those tables: FAT, FAT32, exFAT, NTFS, EXT2, EXT3, EXT4, APFS, HFS+, UFS and ZFS among them.

Disk formatting

Formatting happens at two levels. A low-level format rewrites every sector from scratch, its preamble, empty data and ECC, and leaves no file system at all. A high-level format creates an empty file system by writing only the index and table sectors; the data sectors are not touched.

Deleting works the same way as a high-level format, on a smaller scale. The OS removes the file’s index entry and marks its blocks free, but it does not overwrite the sectors that hold the data. The file’s bytes are still there until something new is written over them, which is why deleted files can often be recovered (file-systems).

Files and blocks

Thanks to the OS, a file is called FinalReport.doc rather than by its cylinder and sector numbers. A program writes and reads the file as bytes; the OS keeps a map from the name to the file’s blocks, and from each block to its sectors, with the names arranged in a hierarchy of directories (folders).

Space is handed out in blocks, also called allocation units: one sector, or several consecutive sectors, typically 512 bytes to 32 kB. The block size is a trade-off. Larger blocks mean fewer of them, so a smaller map, but more space wasted at the end of each file (the EOF).

Block size and wasted space

A file fills whole blocks except the last, which is usually only partly used. The rest of that block is wasted. If the amount spilling into the last block is equally likely to be anything up to a full block,

\[\text{wasted space} \approx \frac12\,[\text{block size}]\]

per file, on average. Small blocks cut the file into many pieces with little waste at the end; large blocks cut it into few pieces with a big remainder (file-systems).

Worked: one file, three block sizes

A 10,000-byte file test.c is stored with 512-byte, 4 kB (4096-byte) or 32 kB (32,768-byte) blocks. How many blocks does it take, and how much space is wasted? With half a block wasted per file on average, how much is wasted over 10,000 files?

The number of blocks is the size divided by the block size, rounded up.

Block size Blocks Space used Wasted at EOF Average waste, 10,000 files
512 B \(\lceil 10000/512 \rceil = 20\) 10,240 B 240 B \(10^4 \times 256 = 2{,}560{,}000\) B
4096 B \(\lceil 10000/4096 \rceil = 3\) 12,288 B 2,288 B \(10^4 \times 2048 = 20{,}480{,}000\) B
32,768 B \(\lceil 10000/32768 \rceil = 1\) 32,768 B 22,768 B \(10^4 \times 16384 = 163{,}840{,}000\) B

In exchange, the map shrinks: a 1 GiB volume has \(2^{30}/512 = 2{,}097{,}152\) blocks to track at 512 B but only \(2^{30}/32768 = 32{,}768\) at 32 kB. The full comparison is in file-systems.

Figure 149: The 10,000-byte file test.c stored with each of the three block sizes, drawn to scale. Grey is the file and hatching the unused end of its last block; each percentage is the share of the space taken that is wasted. With 512-byte blocks the file takes 20 blocks and wastes only 240 bytes, a sliver too thin to see; with 4 kB blocks it takes 3 and wastes 2,288; with one 32 kB block it wastes 22,768 bytes, more than twice the file itself. The column on the right is the other side of the trade: the number of blocks the map must track on a 1 GiB volume falls from over two million to 32,768 as the blocks grow.

Disk allocation

Take a file of 15 sectors, with 1 block = 1 sector, on a surface of five tracks with twelve sectors each.

  • (a) Contiguous: blocks 0 to 11 fill one track in order, and 12 to 14 continue on the next track. This is ideal: one seek and one rotational wait reach block 0, blocks 0 to 11 then stream past the head in a single turn, and blocks 12 to 14 cost only a step to the adjacent track and a wait for block 12 to come round.
  • (b) Fragmented: the blocks are scattered over every track. That is the likely case, because disks become fragmented as files are created and deleted.

Fragmentation means slow access: each jump to another track costs a seek, and each jump to a sector that is not next under the head costs rotational latency. Both layouts are drawn on one surface in file-systems.

See also

Reference material

Addressing Modes

Instruction operands can come from different places, and how an instruction says where to find its operand is its addressing mode. It is part of the instruction encoding, so it is part of the ISA (instruction-set-architecture) — see avr-instructions for the instructions named here.

The names below are as per Tanenbaum, Structured Computer Organization. The AVR instruction set manual uses different names for the same ideas, so match on the behaviour rather than the word when reading the datasheet.

The four modes

Mode What is in the instruction Where the operand is AVR example
Immediate the operand value itself in the instruction word andi r17, 0xBA
Register only register numbers in a register and r18, r19
Direct the memory address in memory, at that address lds r15, $1234
Indirect a register number; that register holds the address in memory, at the address the register holds ld r5, X

Figure 150: The four modes as one question: how far does the machine have to go to reach the operand? Immediate stops at the instruction itself. Register takes one hop, into the register file. Direct takes one hop into memory, but needs a second instruction word to carry the address. Indirect takes two hops and stays one word, and because its address lives in a register it can change while the program runs. The field splits shown inside the instruction words are schematic, not the real AVR encodings.

Figure 150 is the whole comparison in one line: immediate, register, direct, indirect is a list in increasing order of indirection, and every step down it either costs an instruction word or costs a hop through some storage on the way to the operand.

Immediate addressing

An operand value is in the instruction. andi r17, 0xBA carries 0xBA inside the instruction word itself — nothing is fetched from anywhere, the bits are the number. On AVR the immediate instructions are the ones whose mnemonic ends in i (ldi, andi, ori, cpi) and they pay for the immediate with encoding space: only four bits are left for the register, which is exactly why they reach r16–r31 only.

Register addressing

Only register numbers in the instruction. and r18, r19 names two registers and nothing else; the values are already inside the CPU. This is the cheapest mode there is — no memory access at all — and it is why the AVR is a load/store machine: no arithmetic or logic instruction touches memory, its operands are either registers (and r18, r19) or an immediate carried in the instruction word (andi r17, 0xBA). Anything in SRAM has to be loaded into a register first.

Direct addressing

Memory address is in the instruction. lds r15, $1234 spells the address out in full.

These AVR instructions occupy two instruction words (32 bits): sixteen bits are nowhere near enough for both an opcode and a 16-bit address, so the address gets a word of its own. That is the standing trade — a direct access is simple to read and needs no setup, but it costs double the program memory and cannot be computed at run time.

Indirect addressing

Memory address in register; register number is in the instruction. ld r5, X says “load from wherever X points”, and X is the pointer register pair of avr-architecture.

The instruction stays one word, because it only has to name which pointer. The address itself is data now, not code — which is what makes loops over arrays possible: increment the pointer and the same instruction reaches the next element.

Reading the trade-off

Instruction words Address decided Costs
Immediate 1 when you write the program encoding space, hence ldi’s r16–r31 limit
Register 1 — nothing; the value is already in the CPU
Direct 2 when you write the program an extra program-memory word per access
Indirect 1 at run time a pointer register, and loading it first

The pattern: anything the instruction has to say costs instruction bits; anything it can point at costs a register and a setup step instead. Direct and indirect are the same access to the same memory cell — they differ only in which of those two prices you pay.

What the extra word does not cost

ld/st (indirect) are one instruction word, two cycles; lds/sts (direct) are two instruction words, two cycles. So direct addressing’s extra cost is paid entirely in program memory, not in time — both memory forms take the same two cycles, because both make one data-memory access and that access is what dominates.

For contrast, in/out use neither mode — they name an I/O register number directly in the instruction — and take one word, one cycle. That one-cycle figure is the reason in/out exist at all rather than everything going through lds/sts (avr-io-ports).

See also

Analog to Digital Conversion

Turning a voltage into a number the processor can use. A digital input pin only distinguishes 0 from 1. An analog to digital converter (ADC) reports how big a voltage is, to a fixed number of bits. First met in 2026-09-24-serial-io, and used to read a joystick in week10-lab-adc-and-spi.

What a converter does

An ADC takes an input voltage between 0 and a maximum, the reference voltage \(V_{ref}\), and produces an unsigned integer in proportion to it. Zero volts gives 0, and a voltage just under \(V_{ref}\) gives the largest value the result can hold.

The number of bits in the result is the converter’s resolution. With \(n\) bits there are \(2^n\) possible results, 0 to \(2^n - 1\):

Resolution Results Range
8 bits 256 0 to 255
10 bits 1024 0 to 1023
12 bits 4096 0 to 4095

From voltage to number

The converter divides the range from 0 to \(V_{ref}\) into \(2^n\) equal steps and reports which step the input is on. For a 10-bit converter:

\[\text{result} = \left\lfloor \frac{V_{in}}{V_{ref}} \times 1024 \right\rfloor, \qquad \text{at most } 1023\]

and the size of one step is

\[\frac{V_{ref}}{1024} = \frac{5\ \text{V}}{1024} \approx 4.9\ \text{mV} \quad\text{when } V_{ref} = 5\ \text{V}.\]

\(V_{in}\) (with \(V_{ref}\) = 5 V) Result
0 V 0
1.25 V 256
2.5 V 512
3.75 V 768
5 V 1023

Two things follow from the staircase in Figure 151.

  • The result is rounded down to a step. Every voltage within one step gives the same number, so a result is only known to within one step, 4.9 mV here. More bits means smaller steps.
  • The top result is \(2^n - 1\), not \(2^n\). There are 1024 steps numbered from 0, so full scale reads 1023.

Going the other way, a result \(r\) stands for a voltage of about \(r \times V_{ref} / 1024\). A reading of 300 with a 5 V reference is about \(300 \times 4.88\ \text{mV} = 1.46\ \text{V}\).

Figure 151: Conversion with a 3-bit converter and a 5 V reference, drawn with few enough steps to see. The input range is cut into \(2^3 = 8\) equal steps of 0.625 V, and the result is the number of the step the input is on, from 0 to 7. Every voltage within a step gives the same result, so 2.6 V and 3.0 V both read 4. A 10-bit converter does the same thing with 1024 steps of about 4.9 mV.

The ATmega324A’s converter

  • Inputs. The eight port A pins can be used as analog inputs. A pin used this way is not read through PINA. The result comes from the converter’s own data register, ADC, which is 16 bits wide to hold the 10-bit result.
  • One at a time. There is a single converter, with an analog multiplexer in front of it that connects one of the pins to it. To read two voltages, such as the two axes of a joystick, select one pin and convert, then select the other and convert.
  • Reference. \(V_{ref}\) can be chosen. The course uses the supply, \(V_{cc} = 5\ \text{V}\).
  • Resolution. 10 bits: results from 0 to 1023.
  • Time. A conversion is not instant. It takes up to 3200 clock cycles, which is 0.4 ms with the 8 MHz clock. The converter can be run faster at the cost of accuracy.

Because a conversion takes thousands of clock cycles, starting one and getting the answer are separate moments. Between them the program either waits and checks whether the converter has finished, or does something else and lets the converter raise an interrupt when it has (polling-and-interrupts). The interrupt has its own vector, written ISR(ADC_vect) in C (avr-interrupts).

Worked: a joystick

A joystick gives two voltages between 0 and 5 V, one for left-right and one for up-down. Pushed three-quarters of the way right and a quarter of the way up, it gives 3.75 V and 1.25 V, which convert to 768 and 256. Centred, each axis is near 2.5 V and reads near 512. Each reading takes its own conversion, so the two numbers are from slightly different moments.

Inside, each axis is a potentiometer between 5 V and ground, and the stick moves its wiper, so the wiper’s voltage follows the stick from one side to the other (io-board).

Worked: where is the stick?

A joystick’s reading is easiest to interpret measured from the centre. Half of 1023 is 511.5, so 511 and 512 do equally well as the centre. Taking 511 on both axes,

\[\Delta x = x - 511, \qquad \Delta y = y - 511,\]

the direction of the stick is the angle \(\tan^{-1}(\Delta y / \Delta x)\), measured anticlockwise from straight right and put in the right quadrant by the signs, and how far it is pushed is \(\sqrt{\Delta x^2 + \Delta y^2} / 511\) of full deflection.

  • (511, 0): \(\Delta x = 0\), \(\Delta y = -511\). Straight down, all the way.
  • (614, 689): \(\Delta x = 103\), \(\Delta y = 178\). The angle is \(\tan^{-1}(178/103) = 60^\circ\), and the distance is \(\sqrt{103^2 + 178^2} = 206\), which is \(206 / 511 = 40\,\%\) of full deflection.

The readings themselves are never negative: \(\Delta x\) and \(\Delta y\) are what a program works out, not what the converter reports. And the centre is only roughly 511, since a real stick at rest sits a few counts to one side, so a program tests against a margin, as in week10-lab-adc-and-spi.

The registers

A program runs the converter through three registers, counting the 16-bit result as one:

Register Holds
ADMUX which reference, which input, and how the result is lined up
ADCSRA on and off, start, the finished flag and its interrupt enable, and the clock prescaler
ADC, as ADCH and ADCL the result

Figure 152: The converter’s two control registers, with their bits grouped by what they do. In ADMUX the top two bits choose the reference voltage, bit 5 chooses whether the 10-bit result is lined up at the right or the left of its 16-bit register, and the bottom five choose the input pin. In ADCSRA bit 7 switches the converter on, bit 6 starts a conversion and stays 1 while it runs, bit 4 is the flag set when a result is ready and bit 3 its interrupt enable, and the bottom three bits divide the system clock down to the converter’s own clock.

ADMUX: what to convert

REFS1 REFS0 Reference voltage
0 0 whatever is on the AREF pin
0 1 AVCC, the converter’s supply, 5 V on the lab boards
1 0 an internal 1.1 V
1 1 an internal 2.56 V
  • ADLAR, ADC left adjust result, is 0 for a result lined up at the right of the 16-bit register, so that it reads as a number from 0 to 1023. Set to 1, it is lined up at the left instead (below).
  • MUX4:0 picks the input. 00000 to 00111 are the pins ADC0 to ADC7, which are PA0 to PA7, each on its own. The other codes select differential pairs of pins and two internal test voltages, which the course does not use.
Worked: the value for ADC1

AVCC as the reference, right adjusted, input ADC1:

\[\underbrace{01}_{\texttt{REFS1:0}}\ \underbrace{0}_{\texttt{ADLAR}}\ \underbrace{00001}_{\texttt{MUX4:0}} = \texttt{0100 0001} = \texttt{0x41}\]

In C, ADMUX = (1<<REFS0) | 1;. Writing the register replaces all eight bits, so the reference bits have to be included every time the input is changed. ADMUX = 1; alone would select ADC1 with the AREF pin as the reference, which on a board with nothing connected to AREF gives meaningless results.

ADCSRA: control and status

Bit Name
7 ADEN enable: 1 switches the converter on. Nothing happens without it
6 ADSC start conversion: write a 1 to start one. It reads 1 while the conversion runs and drops to 0 when the result is ready
5 ADATE auto trigger: start conversions automatically, for example one after another. Left 0 here
4 ADIF interrupt flag: set when a conversion finishes. Cleared by writing a 1 to it, or by the hardware when the interrupt is taken
3 ADIE interrupt enable for that flag
2–0 ADPS2:0 prescaler: what the system clock is divided by to make the ADC clock
ADPS2:0 000 001 010 011 100 101 110 111
Divide by 2 2 4 8 16 32 64 128
ADC clock at 8 MHz 4 MHz 4 MHz 2 MHz 1 MHz 500 kHz 250 kHz 125 kHz 62.5 kHz

ADEN and the prescaler are set once. ADSC is set for every conversion.

The result: ADCH and ADCL

The 10-bit result sits in a 16-bit register made of two bytes, ADCH and ADCL. ADLAR decides where.

Figure 153: Where the 10 result bits go in ADCH:ADCL. Right adjusted, with ADLAR = 0, bits 9 and 8 are the bottom two bits of ADCH and the rest fill ADCL, so the 16-bit register reads as a number from 0 to 1023 and the six unused bits are 0. Left adjusted, with ADLAR = 1, the result starts at the top, so ADCH on its own holds the top 8 bits, a result from 0 to 255 for a program that does not need all 10.

  • Read the low byte first. Reading ADCL locks the register, so that a conversion finishing in between cannot replace one byte and not the other, and reading ADCH unlocks it. The order is ADCL, then ADCH.
  • In C, read ADC. The header defines ADC as the 16-bit register, and the compiler reads the two bytes in the right order.
  • Left adjusted, ADCH alone will do. With ADLAR = 1 the top 8 bits are all in ADCH, and reading ADCH by itself is allowed. It gives an 8-bit result, steps of about 20 mV with a 5 V reference.

The ADC clock

The converter has its own clock, made by dividing the system clock with the prescaler in ADCSRA. For the full 10 bits of precision, the ADC clock must be between 50 kHz and 200 kHz. A faster clock gives a quicker conversion with fewer accurate bits, which is the trade between accuracy and speed.

A conversion takes 13 ADC clock cycles. The first one after ADEN is set takes 25, because the analog circuits have to settle. At the slowest setting, the system clock divided by 128, that first conversion is \(25 \times 128 = 3200\) system clock cycles, 0.4 ms at 8 MHz, which is the “up to 3200 clock cycles” above.

Worked: choosing the prescaler

With the 8 MHz system clock, the ADC clock is \(8\ \text{MHz} / N\). For it to lie between 50 and 200 kHz,

\[\frac{8\ \text{MHz}}{200\ \text{kHz}} \le N \le \frac{8\ \text{MHz}}{50\ \text{kHz}} \quad\Longrightarrow\quad 40 \le N \le 160.\]

Of the settings on offer, 64 (125 kHz) and 128 (62.5 kHz) are in range. Either is right. 64 is the faster of the two: a conversion takes \(13 \times 64 = 832\) system cycles, 104 µs.

Figure 154: The prescaler settings against the window for full precision. Each setting divides the 8 MHz system clock, giving the ADC clock above the axis and the time for one 13-cycle conversion below it. Only the shaded band, an ADC clock from 50 to 200 kHz, gives all 10 bits. That band is a divisor from 40 to 160, and the two settings inside it are 64 and 128. Settings to the left are faster but less accurate.

A conversion, step by step

  1. Choose the reference and the input in ADMUX.
  2. Switch on the converter and set its clock: ADEN and the prescaler bits in ADCSRA. Once is enough.
  3. Start a conversion by setting ADSC.
  4. Wait until it has finished. ADSC reads 1 until then, and at the end the hardware clears it and sets ADIF.
  5. Read the result from ADC.

Figure 155: One conversion against time. The program writes a 1 to ADSC and the conversion starts. ADSC stays at 1 for the 13 cycles of the ADC clock that the conversion takes, 25 for the first one after the converter is switched on. At the end the hardware puts ADSC back to 0, sets the flag ADIF and leaves the new result in ADCH:ADCL. A program can wait for either bit, or enable the interrupt and be told.

By polling. Wait for ADSC to drop:

#include <avr/io.h>
#include <stdint.h>

uint16_t adc_read(uint8_t channel) {
    ADMUX = (1<<REFS0) | channel;     /* AVCC, right adjusted, this input */
    ADCSRA |= (1<<ADSC);              /* start                             */
    while (ADCSRA & (1<<ADSC)) { }    /* busy while ADSC reads 1           */
    return ADC;                       /* ADCL, then ADCH                   */
}

int main(void) {
    uint16_t x, y;

    ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1);   /* on, 8 MHz / 64 = 125 kHz */
    while (1) {
        x = adc_read(0);
        y = adc_read(1);
        (void)x; (void)y;
    }
}

Waiting on ADSC needs no clearing up afterwards. Waiting on ADIF works too, but the flag stays set until a 1 is written to it, so the program has to clear it before the next conversion.

By interrupt. Set ADIE and write a handler for ADC_vect (avr-interrupts). The handler here collects each result and starts the next conversion, so the converter runs continuously and the main program reads the latest value whenever it wants one:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint.h>

volatile uint16_t latest;             /* the newest result */

ISR(ADC_vect) {
    latest = ADC;                     /* ADIF is cleared as the handler starts */
    ADCSRA |= (1<<ADSC);              /* start the next conversion             */
}

int main(void) {
    uint16_t x;

    ADMUX  = (1<<REFS0);                                      /* AVCC, ADC0 */
    ADCSRA = (1<<ADEN) | (1<<ADIE) | (1<<ADPS2) | (1<<ADPS1); /* / 64       */
    sei();
    ADCSRA |= (1<<ADSC);              /* the first conversion */

    while (1) {
        cli();                        /* a 16-bit copy must not be split */
        x = latest;
        sei();
        /* ... use x ... */
        (void)x;
    }
}

latest is two bytes, so the main program copies it with interrupts off, for the reason in software-timers.

Changing input. A change to ADMUX during a conversion only takes effect when that conversion has finished. Change the input between conversions, as adc_read does.

Common mistakes

  • Expecting 1024 at full scale. The largest 10-bit result is 1023.
  • Forgetting the reference. The same result means a different voltage with a different \(V_{ref}\). A result is a fraction of the reference.
  • Treating the result as exact. It is the step the voltage was on, good to one step.
  • Expecting two inputs to be read together. One converter, one input at a time.
  • Using the result the instant a conversion is started. It is not ready for up to 0.4 ms.
  • Forgetting ADEN. Setting ADSC on a converter that is switched off starts nothing.
  • Losing the reference bits. ADMUX = 1; selects ADC1 but also sets REFS1:0 to 00, the AREF pin. Keep (1<<REFS0) in every write.
  • A prescaler outside the window. At 8 MHz only 64 and 128 put the ADC clock between 50 and 200 kHz. Anything faster gives fewer good bits.
  • Reading ADCH before ADCL. Reading ADCL locks the result until ADCH is read. Read the 16-bit ADC in C and the order is right.
  • Expecting negative readings. The result is unsigned, 0 to 1023. A joystick’s offset from its centre is something the program works out by subtracting.
  • Loading the input. An LED, or the pin’s own pull-up resistor switched on through PORTA, draws current from the voltage being measured and changes it. A potentiometer’s wiper in particular cannot supply current without its voltage moving.

See also

Arithmetic Logic Unit

The ALU is versatile hardware which can perform various operations based on some control inputs — it does considerably more than adding. See cpu-organisation for where it sits in the CPU, and combinational-logic-blocks and logic-gates for the pieces it is built from.

The ALU as a block

A function/control input indicates the operation the ALU is to perform: addition, increment (\(+1\)), subtraction, bitwise AND, bitwise OR, and so on.

Figure 156: The ALU as a block. A and B are n-bit data inputs and Output is the n-bit result; the m-bit Function/Control input selects which operation is performed, and the carry in and out let several ALUs be chained. Slashes mark bus widths.

Like adders, ALUs can be made up from 1-bit slices — an \(n\)-bit ALU is \(n\) identical circuits, one per bit position.

The 1-bit ALU (bit slice)

Figure 157: One bit slice. The ENA/INVA/ENB gates on the left condition the two data inputs into internal signals X and Y; the four function blocks in the middle compute AND, NOT, OR and sum from them simultaneously; the multiplexer selects which one reaches the output, under the F1 F0 select. Cin and Cout belong to the full adder, and are what chain one slice to the next.

\(F_1\) and \(F_0\) select which of the four function blocks reaches the output:

\(F_1 F_0\) Function
00 A and B logical
01 invert B logical
10 A or B logical
11 A plus B arithmetic

Two levels of control

The bit slice has control inputs at two distinct levels, and keeping them apart is what makes the combinations table below readable:

  1. Permutations of the data inputs — ENA, ENB and INVA condition A and B before any function sees them.
  2. Function select — \(F_1 F_0\) picks which operation’s result is actually output.

The conditioning gates are worth working out explicitly, because most of the useful ALU tricks come from them rather than from the function select. Writing \(X\) for the conditioned A line and \(Y\) for the conditioned B line:

\[X = (A \cdot \text{ENA}) \oplus \text{INVA} \qquad\qquad Y = B \cdot \text{ENB}\]

ENA INVA \(X\) ENB \(Y\)
0 0 0 0 0
0 1 1 1 \(B\)
1 0 \(A\)
1 1 \(\overline{A}\)

So the A line can be forced to a constant 0, a constant 1 (all ones across the whole word, i.e. \(-1\) in two’s complement), \(A\) itself, or \(\overline{A}\) — and that constant-generating ability is what lets one ALU compute \(-1\), \(B-1\) and \(B - A\) without any dedicated hardware for them.

INC is the third conditioning input: it is the carry into the least significant slice, 0 for addition and 1 for increment.

Cascading into an \(n\)-bit ALU

A machine word is \(n\) bits (often 8, 16, 32, …), and an \(n\)-bit ALU is built from \(n\) identical bit slices.

Figure 158: An 8-bit ALU as eight cascaded slices. Each slice takes its own bit of A and B and produces its own bit of the output; the carry out of one slice is the carry in of the next, rippling from right (least significant) to left. F1, F0, ENA, ENB and INVA are shared by every slice, so all eight always perform the same operation.

\(F_1\), \(F_0\), ENA, ENB and INVA are shared between all bit slices — there is one function select for the whole ALU, not one per bit. Only the carry is per-slice, and it ripples through from right to left, which is exactly the ripple-carry adder behaviour from earlier in the course.

Useful combinations of ALU inputs

Everything a single ALU can be made to do, by choosing the six control inputs. This table is worth understanding rather than memorising — each row follows from \(X\), \(Y\) and the function select above.

\(F_1\) \(F_0\) ENA ENB INVA INC Function
1 0 1 0 0 0 \(A\)
1 0 0 1 0 0 \(B\)
1 0 1 0 1 0 \(\overline{A}\)
0 1 1 1 0 0 \(\overline{B}\)
1 1 1 1 0 0 \(A + B\)
1 1 1 1 0 1 \(A + B + 1\)
1 1 1 0 0 1 \(A + 1\)
1 1 0 1 0 1 \(B + 1\)
1 1 1 1 1 1 \(B - A\)
1 1 0 1 1 0 \(B - 1\)
1 1 1 0 1 1 \(-A\)
0 0 1 1 0 0 \(A\) AND \(B\)
1 0 1 1 0 0 \(A\) OR \(B\)
1 0 0 0 0 0 \(0\)
1 1 0 0 0 1 \(1\)
1 0 0 0 1 0 \(-1\)

Reading a few rows to see the pattern:

  • \(A\) — select OR (\(F_1F_0 = 10\)), pass \(A\) through (\(X = A\)), force the other side to zero (\(Y = 0\) via \(\text{ENB} = 0\)). \(A + 0 = A\) in the OR sense.
  • \(-1\) — select OR, force \(X\) to all ones (\(\text{ENA}=0\), \(\text{INVA}=1\)) and \(Y\) to zero. All ones is \(-1\) in two’s complement.
  • \(B - 1\) — select the adder, \(Y = B\), $X = $ all ones \(= -1\), and no extra carry. So \(B + (-1)\).
  • \(1\) — select the adder with both inputs forced to zero and \(\text{INC} = 1\), so the result is the carry alone.

Worked example — computing \(B - A\)

What are the values of \(F_1\), \(F_0\), ENA, ENB, INVA and INC to calculate \(B - A\)?

The route is two’s complement negation:

\[B - A = B + (-A) = B + (\overline{A} + 1) = B + \overline{A} + 1\]

So the ALU needs \(\overline{A}\) on one adder input, \(B\) on the other, and a carry of 1 into the bottom slice:

Control Value Why
\(F_1 F_0\) 1, 1 select the adder
ENA 1 let \(A\) through
INVA 1 invert it, giving \(\overline{A}\)
ENB 1 let \(B\) through
INC 1 the \(+1\) of the negation

Laid out as a column addition across the word, this is:

\[\begin{array}{cccccc} & B_7 & B_6 & \cdots & B_1 & B_0 \\ + & \overline{A_7} & \overline{A_6} & \cdots & \overline{A_1} & \overline{A_0} \\ + & 0 & 0 & \cdots & 0 & 1 \end{array}\]

The final row is the INC carry entering at the least significant slice and rippling left — which is why the \(+1\) costs no extra hardware at all.

Overflow: the flag the carry-out does not give you

Every arithmetic row of the table above can go wrong in the same way: the true answer needs more bits than the word has. The ALU still produces a result, and it is a wrong one — so something has to say so.

The carry-out is not that something. \(C_{out}\) in Figure 156 is the correct overflow test for unsigned arithmetic and the wrong one for two’s complement. In two’s complement a carry out of the top slice is routine and is simply discarded (1111 + 1111 gives a carry out and the perfectly correct answer \(-2\)), while \(0111 + 0001\) produces no carry out at all and is nonetheless an overflow. The signed test is whether the top slice’s carry in and carry out disagree:

\[V = C_{n} \oplus C_{n-1}\]

and equivalently, in terms of signs: overflow happens exactly when the two operands share a sign and the result does not. Adding two positives cannot legitimately give a negative; adding two negatives cannot legitimately give a positive.

When \(C_{n-1}\) is not available

That formula assumes you can reach the carry into the most significant slice, which inside your own cascade of bit slices you can. On a single-package adder you cannot: a 74HCT283 wires \(C_1\), \(C_2\) and \(C_3\) stage-to-stage inside the chip and brings out only \(C_0\) and \(C_4\) (see device-pinouts). Learning Lab 3 makes exactly this its extension task — build an overflow LED using only \(A_3\), \(B_3\), \(S_3\) and \(C_4\) — so the sign form is the one you actually wire:

\[V = A_3 B_3 \overline{S_3} + \overline{A_3}\,\overline{B_3} S_3\]

Read literally: (both operands negative and the sum positive) or (both operands positive and the sum negative). With only the two-input gates the course’s parts list stocks, the same function factors into three gates — “the signs agree” AND “the sum disagrees with them”:

\[V = (A_3 \odot B_3) \cdot (A_3 \oplus S_3)\]

Figure 159: Two’s complement overflow detected from the pins a packaged adder actually brings out. A3 and B3 are tapped from the operand inputs and S3 from the sum output; the XNOR asks whether the two operands agree in sign and the XOR asks whether the sum disagrees with them, and overflow is both at once. C4 is deliberately left going nowhere, because the carry-out is the unsigned overflow test, not this one. The adder outline, the ‘+’ glyph and the input/output placement follow the course’s 74HCT283 schematic symbol.

There is a cheaper form still. A full adder gives \(S_3 = A_3 \oplus B_3 \oplus C_3\), so the missing internal carry can be recovered as \(C_3 = A_3 \oplus B_3 \oplus S_3\), and substituting into \(V = C_4 \oplus C_3\) leaves

\[V = C_4 \oplus A_3 \oplus B_3 \oplus S_3\]

— three two-input XOR gates, all four of which fit in a single 74HCT86.

Back to \(B - A\)

The worked example above computes \(B - A\) as \(B + \overline{A} + 1\), and it is an ordinary addition as far as the top slice is concerned — so it is the conditioned operand that the overflow test must look at. The sign bit entering the adder is \(\overline{A_{n-1}}\), not \(A_{n-1}\), which is why a subtraction of two numbers whose signs differ is the case that can overflow, while an addition of two numbers whose signs differ never can. See week2-lab-binary-arithmetic for the lab build and 2026-08-04-binary-arithmetic for the arithmetic behind the rule.

See also

The Assembly Process

How an assembly language program becomes machine code. It covers the four fields of a statement, the directives that tell the assembler what to do as opposed to the CPU, the three memory segments of the AVR and the location counter that walks through each, and the two-pass assembler with its symbol table, which is how a program can jump to a label it has not reached yet. The program skeleton these pieces fit into is avr-program-structure, and the memories the segments map onto are in memory-models and avr-architecture. First met in 2026-10-08-assembly-process.

What an assembler does

An assembler turns a text file of assembly language into the bits that go into the chip’s memories. Most of that is translation, one statement at a time: add r1, r2 has a fixed binary form, 0000 1100 0001 0010, and nothing else in the file can change it (avr-instructions). Each instruction becomes exactly one machine instruction (instruction-set-architecture).

Two things make it more than a lookup table:

  • A program is more than instructions. It has to say where things go in memory, reserve space for variables, put constant tables in flash and give registers and addresses readable names. None of that is an instruction for the CPU. These lines are directives, commands to the assembler itself.
  • Names stand for numbers that are not known yet. jmp RESET needs the address of RESET, and if RESET: is further down the file, a single read from top to bottom cannot supply it. The cure is to read the file twice.

C reaches machine code by a different road: the compiler turns one line of C into many instructions (2026-09-07-introduction-to-embedded-c-programming), and how that output is joined into a program is compilation-and-linking.

The format of a statement

An assembly program is a sequence of one-line statements. A statement has up to four fields, and any of them may be empty:

Figure 160: The four fields of one assembly statement. The label names the address this statement ends up at, so other statements can jump to it or refer to the data there. The operation field holds the mnemonic, which is either an instruction for the CPU or, if it starts with a dot, a directive for the assembler. The operands are what the operation works on: registers, constants or symbols, separated by commas. The comment runs from the semicolon to the end of the line and is thrown away by the assembler.

Label. A name for a position in memory. Labels exist so that statements can be jumped to and so that data can be referred to by name. Its value is the address the statement lands at: a word address in program memory for code, a byte address in data memory for a variable. By convention a label starts in column 1 and everything else is indented, so labels stand out down the left edge. In AVR assembly it ends with a colon.

Operation. A symbolic abbreviation for an instruction’s opcode, a mnemonic: LDS for Load Direct from data Space, ldi for load immediate. Or a directive, which starts with a dot.

Operands. The registers and addresses the instruction uses. Register names belong to the machine:

Machine Register names
Pentium eax, ebx, esi, edi, …
SPARC o0..o7, i0..i7, l0..l7, g0..g7 (out, in, local and global)
AVR simply r0..r31

An address operand is usually written as a label, lds r16, count, and the assembler substitutes the number.

Comment. Space for explanation, only for people: the assembler discards it. In assembly comments are not optional politeness. ldi r20, 13 says nothing about why; the comment is the only place the intent is written down.

Ending a statement. Some assemblers want a semicolon at the end of every statement and others do not. AVR assembly does not: the end of the line ends the statement, and a semicolon starts a comment.

Directives

Besides instructions, the assembler needs other information, for example:

  • where in memory the code and data should go;
  • nicer names for registers and addresses, such as temp for r16 or SPH for I/O address 0x3E;
  • space for variables and tables of constants.

That information is given as a directive, also called a pseudo-instruction: a command to the assembler itself, written where an instruction would be and preceded by a dot, as in .byte or .def temp = r16. Most directives produce no machine code at all. They change what the assembler knows or where it is putting things.

The assembler in Microchip Studio, AVRASM2, has these, among others:

Directive What it does
.byte reserve bytes for a variable
.cseg switch to the code segment
.csegsize set the program memory size
.db define constant byte(s)
.def give a register a symbolic name
.device name the exact processor the program is for
.dseg switch to the data segment
.dw define constant word(s)
.equ set a symbol equal to an expression, permanently
.eseg switch to the EEPROM segment
.exit stop processing this file
.include read source from another file, here
.list, .nolist turn generation of the list file on, off
.listmac show macro expansions in the list file
.macro, .endm (or .endmacro) begin, end a macro
.org set the location counter: the address of what comes next
.set set a symbol equal to an expression, changeably
.if, .else, .elif, .endif conditional assembly: include lines only if a condition holds

All of this is AVRASM2’s syntax. Other assemblers, even ones for the AVR, spell things differently. The GNU assembler used behind avr-gcc has a .byte directive too, and there it stores the bytes listed instead of reserving space.

Segments and location counters

The AVR has three memories (avr-architecture), and to the assembler each is a segment. Directives choose which segment the following lines go into:

Segment Directive Memory What can go there
code .cseg flash, program memory instructions, and constant data
data .dseg SRAM, data memory space only, reserved for variables
EEPROM .eseg EEPROM constants

The data segment cannot be given values. The assembler’s output is programmed into flash and EEPROM, which keep their contents with the power off. SRAM is empty at power-up and holds nothing until the running program writes to it, so all the assembler can do there is decide which addresses each variable will use.

Each segment has its own location counter: the address the next thing in that segment will be placed at. A label takes the current value of its segment’s counter, and every statement that places something advances the counter by its size. Switching segment does not reset anything. It only changes which counter is in use, so a segment can be built up in pieces, and each piece carries on where the last piece of the same segment stopped.

Figure 161: One source file feeding three memories. The file switches segment four times, and each piece goes to the memory its directive names, carrying on from where the previous piece of the same segment stopped: the second code piece follows the first in flash, and total follows count in SRAM. Each segment has its own location counter. The code counter starts at 0 and counts 16-bit words. The data counter starts at 0x0100, the first address after the registers and I/O, and counts bytes. The EEPROM counter starts at 0 and counts bytes. Grey marks code, blue data and green EEPROM.

Where each counter starts:

  • Code: at 0, the reset address, and the assembler starts in the code segment, so a file with no segment directives is all code. The counter counts 16-bit words, because each program-memory address names a word (memory-models).
  • Data: at the first free SRAM address, 0x0100 on the ATmega324A, since 0x0000 to 0x00FF are the registers and I/O registers. The counter counts bytes.
  • EEPROM: at 0, counting bytes.

.org sets the counter of the current segment to a given value, so whatever follows is placed there. It works in any segment, in that segment’s units.

Reserving and defining data

Three directives put data in memory:

Directive Segment Places Size
.byte n data nothing: reserves n bytes n bytes
.db a, b, … code or EEPROM constant bytes, 8 bits each one byte each
.dw a, b, … code or EEPROM constant words, 16 bits each two bytes each

.byte is allowed only in the data segment: it is how a variable gets an address. .db and .dw initialise constants, so they belong where constants can live: the code segment or the EEPROM segment.

.db in the code segment packs two bytes per word. Program memory is 16 bits wide, so consecutive bytes share a word, the first in the low byte and the second in the high byte. A .db line with an odd number of bytes leaves half a word over, and the assembler fills it with a zero pad byte so that the next line starts on a whole word. Each .db line is padded on its own, so two 5-byte lines take 3 words each, not 5 words between them. AVRASM2 warns when it pads. Writing the 0 yourself gives the same layout without the warning.

.dw takes one whole word per value, so it is the natural way to store numbers bigger than 255, or addresses.

Worked: a lookup table in flash

A lookup table (LUT) is a table of constants a program reads instead of computing. Lay out:

        .cseg
table1: .db  11, 12, 30
table2: .dw  100, 133
        .org 500
table3: .dw  ...

The code counter starts at 0.

  • table1 = 0. Three bytes: 11 and 12 share word 0, 30 takes the low half of word 1, and a pad 0 fills its high half. The counter moves to 2.
  • table2 = 2. Two words, 100 at word 2 and 133 at word 3. The counter moves to 4.
  • .org 500 sets the counter to 500. Words 4 to 499 are skipped, and nothing is placed there.
  • table3 = 500 (0x01F4).

Figure 162: The lookup table laid out in program memory, one 16-bit word per row, lowest address at the top. A .db puts two bytes in each word, the first in the low byte, and pads an odd count with a zero byte so that the next label starts on a whole word: here 30 shares word 1 with a pad. Each .dw value fills a whole word. The .org moves the location counter forward and leaves words 4 to 499 untouched, so table3 lands at word 500. The diagonal break means the gap is not drawn to scale. Grey marks the .db bytes, dark grey the pad and blue the .dw words.

On the data side, two .byte 2 lines in separate .dseg pieces end up next to each other, at 0x0100 and 0x0102, whatever code sits between them in the file. That is worked in 2026-10-08-assembly-process.

Naming things: .def, .equ and .set

Three directives give a name to something. None of them places anything or moves a location counter.

Directive Names Can it be changed later? Example
.def a register, and only a register yes, by another .def .def ZH = r31
.equ a value: a number, an I/O address, an expression no .equ sreg = 0x3f ; Status register
.set a value yes, by another .set .set io_offset = 0x23 ; For now

.equ is the usual choice for a constant, because a second definition is an error and catches a clash of names. .set is for a value that a later part of the file deliberately redefines, which is what for now in the comment above says.

Check. The same program defines .equ SPH = $3E and .def ZH = r31. Why .equ for one and .def for the other? SPH is an I/O register, which instructions such as out reach by its I/O address, 0x3E. To the assembler that is just a number, so .equ. ZH is general-purpose register r31, the high byte of the Z pointer, which instructions name as a register operand, so .def.

Two more directives are about files and the processor rather than names:

  • .include "file" reads another file in at that point, as if its text were typed there. .include "m324Adef.inc" is how PORTA, SPH, RAMEND and the rest get defined: the file is mostly .equ and .def lines (avr-io-ports).
  • .device ATmega324A names the exact processor. The assembler then rejects any instruction that chip does not implement.
  • .exit stops reading the file at that line. Anything after it is ignored.

The forward reference problem

Read top to bottom, most statements can be translated on the spot. add r1, r2 names two registers and nothing else, so its machine word is known at once.

A label used before it is defined is different. A program usually starts with

        jmp  RESET
        ...
RESET:  ldi  temp, low(RAMEND)

When the assembler reaches the jmp, it knows the opcode but not the operand: RESET has not been seen, so there is no address to put in the instruction. This is the forward reference problem. One forward reference anywhere in a file is enough to stop a single top-to-bottom pass from finishing the job.

The two-pass assembler

The fix is to process the file twice.

Pass one: define every symbol. Go through the file without generating anything. Keep a location counter for each segment, starting at 0 for code and EEPROM and at 0x0100 for data. For each line:

  • if it has a label, enter the label in the symbol table with its segment and the current value of that segment’s counter;
  • if it is .equ, .set or .def, enter that name and its value;
  • if it is .cseg, .dseg or .eseg, switch counters; if it is .org, set the current counter;
  • advance the current counter by the line’s size: 1 or 2 words for an instruction, the padded number of words for .db, a word per value for .dw, n bytes for .byte n, and 0 for a line that only names something.

Pass one only needs each line’s size, and every instruction’s size is known without knowing its operands: jmp RESET takes 2 words whatever RESET turns out to be.

Pass two: assemble. Go through the file again with the counters reset. Now every symbol’s value is in the table, so each instruction can be assembled, turned into actual machine code, with its operands filled in, and each .db and .dw value can be written.

Figure 163: The two-pass assembler. Pass one reads the whole source and produces no code: it steps the location counters and records each symbol’s segment and value in the symbol table. Pass two reads the same source again from the top and, with every value now in the table, encodes each instruction and writes each constant. Its output is the contents of flash and of EEPROM. The data segment produces no output, only the addresses its labels were given.

Worked: a two-pass trace

The program:

        .equ    RAMEND = $08FF
        .equ    SPH = $3E
        .equ    SPL = $3D
        .def    ZH = r31
        .def    ZL = r30
        jmp     RESET
        .dseg
var1:   .byte   2
var2:   .byte   2
        .cseg
        .def    temp = r16
mesg:   .db     72,101,108,108,111
table:  .dw     var1, var2
RESET:  ldi     temp, low(RAMEND)
        out     SPL, temp
        ldi     temp, high(RAMEND)
        out     SPH, temp
        ...
        ldi     ZH, high(mesg*2)
        ldi     ZL, low(mesg*2)
        lpm                     ;R0 <= M[Z]

Pass one. The code counter starts at 0 and the data counter at 0x0100 (256).

  • The five .equ and .def lines enter RAMEND, SPH, SPL, ZH and ZL in the table and place nothing.
  • jmp RESET is a 2-word instruction, so it takes words 0 and 1 and the code counter goes to 2. RESET is not known yet, and pass one does not need it to be.
  • .dseg switches to the data counter. var1 = 256 (0x0100) and .byte 2 moves the counter to 258. var2 = 258 (0x0102) and the counter goes to 260.
  • .cseg switches back to the code counter, still at 2. .def temp = r16 enters temp.
  • mesg = 2. Five bytes need three words with a pad, words 2 to 4, and the counter goes to 5.
  • table = 5. Two words, 5 and 6, and the counter goes to 7.
  • RESET = 7. Each of the four instructions from here is one word: ldi at 7, out at 8, ldi at 9, out at 10.

The counters run code 0, 2, 5, 7, 8, 9, 10, 11 and data 256, 258, 260. The EEPROM counter is never used.

Figure 164: Pass one over the example, line by line. The two address columns show where each line is placed in its own segment, so a range means the line takes several words or bytes: the jmp two words, the 5-byte .db three words with its pad, the .dw two words, each .byte 2 two bytes. Lines that only name something or switch segment take no space and have no address. The code and data counters advance independently, which is why mesg comes straight after the jmp even though the data lines sit between them in the file. On the right is the symbol table pass one leaves behind: every name, the segment its value belongs to, and the value. The .equ and .def names have no segment.

So the instruction at RESET is at program address 7, mesg is at 2, table at 5, and the variables at 256 and 258.

Only one reference in the program is forward: jmp RESET. Every other symbol (RAMEND, var1, var2, mesg, SPL, SPH, ZH, ZL, temp) is defined above the line that uses it. One is enough to need the second pass.

Worked: what pass two writes

With the table complete, pass two replaces every symbol by its value and encodes:

Address Statement With symbols replaced Machine word(s)
0–1 jmp RESET jmp 7 0x940C 0x0007
2–4 .db 72,101,108,108,111 bytes 72, 101, 108, 108, 111 and a pad 0 0x6548 0x6C6C 0x006F
5–6 .dw var1, var2 .dw 0x0100, 0x0102 0x0100 0x0102
7 ldi temp, low(RAMEND) ldi r16, 0xFF 0xEF0F
8 out SPL, temp out 0x3D, r16 0xBF0D
9 ldi temp, high(RAMEND) ldi r16, 0x08 0xE008
10 out SPH, temp out 0x3E, r16 0xBF0E
later ldi ZH, high(mesg*2) ldi r31, 0x00 0xE0F0
later ldi ZL, low(mesg*2) ldi r30, 0x04 0xE0E4
later lpm lpm 0x95C8

Points worth checking by hand:

  • ldi r16, 0xFF. The form is 1110 KKKK dddd KKKK, with dddd the register number minus 16. K = 1111 1111 and dddd = 0000, so 1110 1111 0000 1111 = 0xEF0F.
  • The .db words. The first byte of each pair is the low byte: 72 and 101 make 0x6548. The odd fifth byte, 111 = 0x6F, shares its word with the pad.
  • low() and high() split a 16-bit value into its bytes at assembly time. RAMEND = 0x08FF gives 0xFF and 0x08: this is the stack pointer being set to the top of SRAM (procedures-and-the-stack).
  • mesg*2. mesg is a word address, 2. lpm reads one byte of program memory from the byte address in Z, and word 2 starts at byte 4. So Z = 0x0004, and lpm loads r0 with the byte there, 72, the H of Hello. The two kinds of address are drawn in memory-models.
  • table holds the two variables’ addresses, 0x0100 and 0x0102: a table of pointers, in flash, into the data segment.

Common mistakes

  • Counting jmp as one word. It is two, because it carries a full program address (avr-branches-and-jumps). rjmp is one.
  • Forgetting the pad. A .db line with an odd number of bytes takes a whole extra word, and each line is padded separately.
  • Counting .db bytes as words. Two bytes share a word in program memory.
  • Letting .dseg lines move the code counter, or the other way round. Each segment has its own counter, and switching segments only chooses which one is in use.
  • Giving size to lines that only name things. .equ, .set, .def, .cseg, .dseg, .include and comments place nothing.
  • Expecting .byte to store a value. .byte 2 reserves two bytes. It does not put a 2 anywhere. Constants go in flash or EEPROM with .db or .dw.
  • .def for a constant, or .equ for a register. .def is for registers only.
  • Redefining an .equ. It cannot be changed; that is what .set is for.
  • Handing a code label straight to lpm. A code label is a word address. lpm wants the byte address, the label times 2.
  • Ending statements with a semicolon out of habit from another language. In AVR assembly it starts a comment.
  • Assuming another assembler reads the same way. Directive names and meanings change between assemblers, even for the same chip.

See also

AVR Architecture

The Atmel AVR: what is on the chip, how the CPU is laid out, and where the fetch-decode-execute cycle happens in it. See cpu-organisation for the generic picture this specialises and avr-instructions for what it executes.

Microcontroller, not microprocessor

Atmel AVR devices are microcontrollers. A microcontroller includes lots of components on one chip:

  • CPU
  • Memory (RAM)
  • Program memory
  • Input/output devices

That is the distinction from a microprocessor, which is the CPU alone. An ATmega324A is not a CPU — it contains a CPU, alongside memory and a large collection of peripherals, so that a useful system can be one chip rather than a board full of them.

The AVR CPU

Figure 165: The AVR CPU core, with the three stages of the cycle marked. Fetch (dashed) reads the next instruction from flash under the program counter into the instruction register; decode (dotted) turns it into control lines; execute (solid) runs it over the register file, ALU and status register, with the 8-bit data bus tying everything together. The two lines dropping to the Data SRAM are the direct and indirect addressing routes — both come out of the instruction, which is why they leave from the instruction register. The execute group takes in the status register, the register file and the ALU; the Data SRAM sits outside it.

Reading the diagram as the cycle of fetch-decode-execute-cycle:

Stage Blocks involved
Fetch Program Counter → Flash Program Memory → Instruction Register
Decode Instruction Register → Instruction Decoder → Control Lines
Execute General purpose registers → ALU → back to registers, with Status and Control updated

Because these three groups are largely separate hardware, the AVR overlaps them: while one instruction executes, the next is being fetched. This course calls it a three-stage pipeline. The ATmega164A/324A/644A/1284P datasheet describes the core as “single level pipelining”, i.e. fetch and execute overlapping, which is two stages. Answer three-stage pipeline in the exam, but the datasheet is the authority on the hardware.

The pieces

Block Notes
Flash program memory Holds the program. 32 kB on the ATmega324A, and non-volatile — it survives power loss
Program Counter Addresses flash to select the next instruction — the PC of cpu-organisation
Instruction Register Holds the instruction currently being worked on
Instruction Decoder Turns the instruction’s bits into control lines — this is the control unit
32 × 8 general purpose registers R0–R31, each 8 bits wide, built from flip-flops
ALU 8-bit, so AVR is an 8-bit machine
Status and Control Holds the flags the ALU produces — N, Z, C, V among others
Data SRAM 2 kB, volatile — static RAM, i.e. flip-flops
Data bus 8 bits wide, tying the execute-side blocks together

Two addressing routes reach the SRAM, drawn as the two vertical paths in Figure 165 — direct addressing (the address is in the instruction) and indirect addressing (the address is in a register). Both leave from the instruction register, because in either case it is the instruction that says which cell is wanted; they differ only in whether it says so with a literal address or with the name of a pointer. Both, and the other two modes, are in addressing-modes.

Four numbers define the chip: the flash is 32 kB and non-volatile; the SRAM is 2 kB, volatile, and made of static flip-flops; the register file is 32 registers, r0…r31, each 8 bits wide and made of flip-flops; and the ALU is 8-bit, which makes the AVR an 8-bit machine.

The register file

General purpose registers (0–31) are quite regular and can be used interchangeably. Two exceptions are worth having by heart:

  • A few instructions work on half the registers (r16–r31), because only 4 bits are used to represent the operand in the instruction and \(2^4 = 16\). LDI, SER, ANDI, ORI and CPI are among them — see avr-instructions.
  • X, Y and Z are register pairs that double as 16-bit pointers.

X, Y and Z

The top six registers of the file are those three pairs, low byte in the lower-numbered register:

Pointer High : Low Register addresses
X R27 : R26 0x1B : 0x1A
Y R29 : R28 0x1D : 0x1C
Z R31 : R30 0x1F : 0x1E

Two 8-bit registers side by side make a 16-bit address — which is what the data space needs and no single 8-bit register can hold. They are what indirect addressing uses: ld r5, X means “load from wherever X points”, and the instruction only has to name which pointer, so it stays one word (addressing-modes).

The low byte living in the lower-numbered register is the same little-endian convention the AVR uses in memory (memory-models).

Address spaces

The AVR is a Harvard machine — separate address spaces for instructions and data — so 0x0000 names two entirely different locations depending on which space is meant, and the instruction decides.

Data address space — 0x0000 to 0x08FF

Region Addresses Size
32 Registers 0x0000–0x001F 32
64 I/O Registers 0x0020–0x005F 64
160 Ext I/O Reg. 0x0060–0x00FF 160
Internal SRAM 0x0100–0x08FF 2048 bytes (2 kB)

The register file and all 224 I/O registers are mapped into the data space, ahead of the SRAM. That is what lets lds/sts reach an I/O register by its data address while in/out reach the first 64 by their I/O register number — the two numbering systems differ by exactly the 0x20 the register file occupies. Details in avr-io-ports.

The datasheet draws the SRAM box as 1024/2048/4096/16384 × 8 because the diagram covers the whole ATmega164A/324A/644A/1284P family; the 324A is the 2048 entry, which is what puts the top of the data space at 0x08FF.

Program memory — 0x0000 to 0x3FFF

\(2^{14}\) 16-bit words: 16,384 instruction words = 32,768 bytes = 32 kB. The datasheet splits it into an Application Flash Section and, at the highest addresses, a Boot Flash Section.

0x3FFF \(= 2^{14} - 1\), and the sizing arithmetic — why 32 kB of program memory is 14 address bits rather than 15 — is worked through in memory-models. The short version: the cells are 16 bits wide, so there are half as many of them as there are bytes.

The AVR status register

8 bits, all readable and writable, all reset to 0:

Figure 166: The status register, in the three-row form the datasheet uses: bit numbers above, flag names in the boxes, then the access row and the value each bit takes after reset. The callout names bit 7, the global interrupt enable; the braces underneath mark the four ALU flags and the sign flag \(S = N \oplus V\).

Instruction descriptions refer to these as SREG(n) by bit number:

Flag Bit Meaning
C SREG(0) carry — was a carry out generated?
Z SREG(1) zero — was the result 0?
N SREG(2) negative — the sign bit of the result
V SREG(3) overflow — did a two’s complement addition/subtraction overflow?
S SREG(4) sign, \(= N \oplus V\) — the sign of the result corrected for any overflow
H SREG(5) half-carry — carry out of bit 3
T SREG(6) transfer bit, used by BLD and BST
I SREG(7) global interrupt enable — set by sei, cleared by cli; cleared by the hardware when it takes an interrupt and set again by reti (avr-interrupts)

C, Z, N and V are exactly the four flags of fetch-decode-execute-cycle.

S is not simply “the sign bit” — that is N. \(S = N \oplus V\) means: the result is negative (with no overflow), or would have been negative had overflow not occurred. That correction is what makes signed comparisons work, which is why the signed branches (BRLT, BRGE) test S while the unsigned ones (BRLO, BRSH) test C. The four cases — including the overflow case where N alone gives the wrong answer — are drawn in 2026-09-14-flow-of-control, and the branch pairs are tabulated in avr-branches-and-jumps.

The one-line meanings and the SREG(n) numbering are those of Atmel’s AVR Instruction Set Manual and the instruction summary in the ATmega324A datasheet. The I/O register map is the I/O register summary, pages 636–639 of the ATmega164A/324A/644A/1284P datasheet, which writes the I/O register number first and the data memory address in parentheses after it.

On-chip peripherals (ATmega324A)

Beyond the CPU and its memories, the chip carries a large set of peripherals — this is what makes it a microcontroller rather than a processor. The two figures nest: the whole of Figure 165 is what sits inside the single box marked AVR CPU in Figure 167.

Figure 167: What is on the ATmega324A: the datasheet block diagram, rearranged into clusters by kind of thing — GPIO, memory, communication, timers/counters, analog and system. The dashed outline is the package boundary and the heavy rectangle inside it the internal bus, both as the datasheet draws them; the individual peripheral-to-port wiring is left out.

Group On the chip
General purpose I/O PORT A, PORT B, PORT C, PORT D — four 8-bit ports
Communication USART 0, USART 1, SPI, TWI
Timers/counters 8-bit T/C 0, 16-bit T/C 1, 8-bit T/C 2 (T/C 3 is on the ATmega1284/1284P, not the 324A — the family datasheet’s block diagram covers both)
Analog A/D converter, analog comparator, internal bandgap reference
Memory Flash (program), SRAM (data), EEPROM (data, non-volatile)
System Power supervision (POR/BOD & reset), watchdog timer and oscillator, oscillator/clock generation (XTAL1, XTAL2), JTAG/OCD

There are three memories with three different jobs: flash for the program, SRAM for volatile working data, and EEPROM for data that must survive a power cycle. SRAM and EEPROM are the pair to keep straight: both hold data, and they differ only in surviving a power cycle.

See also

AVR Branches and Jumps

How an AVR program’s control leaves the straight line: the ten conditional branches and which status flag each one reads, why greater than needs two different instructions for signed and unsigned bytes, the three unconditional jumps and how far each can reach, and the assembly idioms — if, if … else, counted and conditional loops — built from them. First met in 2026-09-14-flow-of-control, with the compare instructions and breq/brne first met in 2026-09-03-instruction-set-architecture-part-2. Procedure calls, the other way control moves, are in procedures-and-the-stack.

Flow of control

The flow of control is the sequence in which instructions actually execute. By default it is linear: every fetch-decode-execute cycle ends with \(PC \leftarrow PC + 1\) (fetch-decode-execute-cycle), so the next instruction is the next one in memory. Four kinds of instruction replace that increment with a new value:

Decides
Branches conditional a status-register flag
Jumps unconditional nothing — always taken
Procedure calls and returns unconditional, and they remember where they came from procedures-and-the-stack
Interrupts / traps triggered by hardware, not by an instruction polling-and-interrupts · avr-interrupts

Everything below is one instruction that writes the PC.

Conditional branches

A conditional branch tests one bit of the status register (avr-architecture) and, if the bit has the value the instruction wants, loads the PC with the address of a label; otherwise execution falls through to the next instruction. There is one instruction per flag per value:

Branch if flag = C N V S = N ⊕ V Z T H I
0 brsh (= brcc) brpl brvc brge brne brtc brhc brid
1 brlo (= brcs) brmi brvs brlt breq brts brhs brie

The first five columns are the ten branches counted above; the last three are the same pattern applied to the remaining flags and are in the instruction set reference. The mnemonics read as the condition, not the flag: brsh is branch if same or higher and happens to be branch if carry clear; brge is branch if greater or equal and happens to be branch if S clear. Learn them as conditions and the flags take care of themselves.

Every branch is relative and short. The offset is seven bits, so a conditional branch can reach only about 64 words either side of itself. For a farther target, branch on the opposite condition around a jmp:

    cp   r5, r6
    brne skip          ; opposite of the condition wanted
    jmp  far_away      ; taken only when r5 == r6
skip:

A taken branch costs two cycles, a not-taken one; the branch itself is one 16-bit word.

Setting the flags first

A branch reads flags; something has to have written them. Usually that is a compare (avr-instructions):

Computes Keeps
cp rd, rr rd − rr flags only
cpi rd, K rd − K flags only — rd must be r16–r31
tst rd rd AND rd flags only — Z and N say whether rd is zero or negative

but any ALU instruction sets flags, and a branch straight after an add, sub, dec or andi tests the result of that. dec r17 followed by brne loop is the standard loop counter, and no cp is needed. The rule from avr-program-structure holds either way: nothing that disturbs the flag may sit between the setter and the branch.

Signed and unsigned comparisons

Equality is the same question for signed and unsigned bytes, so breq and brne serve both. Ordering is not: whether 1111 1111 is bigger than 0000 0001 depends on whether it means 255 or −1, and the bits alone cannot say (binary-number-representations). The cp sets the same flags either way; the programmer chooses which pair of branches to read them with, and thereby declares the type:

Branch if rd ≥ rr Branch if rd < rr Reads
unsigned brsh — same or higher brlo — lower C: an unsigned subtraction needs a borrow exactly when the result went below zero
signed brge — greater or equal brlt — less than S = N ⊕ V: the sign of the result, corrected for overflow

Figure 168: The same two bit patterns on the two number lines an 8-bit register can be read against. As unsigned values, 0xFF is 255 and sits at the far right, above 0x01; as two’s complement values it is \(-1\) and sits just left of zero, below 0x01. One cp r5, r6 produces one set of flags for both readings. The unsigned branches take their answer from the carry flag, which records whether the subtraction had to borrow; the signed branches take theirs from S, which is the sign of the difference with any overflow undone. Choosing brsh or brlt after the compare is the only place the program says which line it meant.

Why S and not N. N is the top bit of the 8-bit result. When a signed subtraction overflows — a large positive minus a large negative, say — the true difference does not fit in 8 bits, the stored result wraps, and its top bit is the opposite of the true sign. V is set in exactly that case. So \(S = N \oplus V\) is the true sign whether or not overflow happened, and one flag test decides < correctly across the whole range; the four cases are drawn in 2026-09-14-flow-of-control. In C none of this is visible: the compiler reads the variable’s declared type and emits brlo for unsigned char and brlt for char, the same way it picks lsr or asr for >> (c-operators).

Unconditional jumps

Instruction Target Size Cycles Reach
jmp label absolute address 32-bit (two words) 3 anywhere in program memory
rjmp label PC + signed offset 16-bit 2 ±2 K words (12-bit offset, −2048 to +2047)
ijmp the address held in Z 16-bit 2 anywhere; the target is a run-time value

jmp carries a full program-memory address — 14 bits for the ATmega324A’s 16 K words of flash — which does not fit beside an opcode in one 16-bit word, so it takes two words and an extra cycle. rjmp carries a 12-bit offset from the instruction’s own position in one word, one cycle less, and reaches ±2 K words; in a program of a few hundred instructions every jump is within range, and it is the normal choice. ijmp takes the destination from Z, the pointer register of addressing-modes, so a program can compute where to go — a jump table, or C’s switch. The assembler resolves labels to addresses or offsets for all three; the programmer writes the label.

Figure 169: How far each kind of jump can reach from the instruction executing it. Program memory is the ATmega324A’s 16,K words; the marker is the current PC. A conditional branch carries a 7-bit offset and reaches about 64 words either way, an rjmp carries a 12-bit offset and reaches 2,K words either way, and a jmp carries the whole 14-bit address and reaches anywhere. The three are drawn to scale against the memory: the branch window is a sliver, the rjmp window covers a quarter of the chip, and the labs’ programs never leave either. The narrower the reach, the shorter and faster the instruction.

The idioms

Every C control structure (c-control-flow) compiles to a handful of these shapes. The branch is always on the opposite of the source condition, because what the branch does is skip the body.

if:

    cp   r5, r6
    brlt endif         ; skip the body when r5 < r6 (signed)
    ...                ; body: runs when r5 >= r6
endif:

if … else — the else part is the code the branch does not skip, and it needs a jmp past the if part:

    cp   r5, r6
    brge then
    ...                ; else part
    rjmp endif
then:
    ...                ; if part
endif:

while — test at the top, jump back at the bottom:

loop:
    cp   r5, r6
    brsh done          ; exit when r5 >= r6 (unsigned)
    ...                ; body
    rjmp loop
done:

Counted loop — count down to zero so the decrement sets Z for free:

    ldi  r17, 10       ; ten times
loop:
    ...                ; body
    dec  r17           ; sets Z when r17 reaches 0
    brne loop

Figure 170: A counted loop, as a flowchart and as the four instructions that implement it. The counter is loaded once; the body runs; the decrement both updates the counter and sets the zero flag from the result; brne reads that flag and either returns to the label or falls out. Counting down rather than up saves the compare: dec leaves Z = 1 exactly when the counter has reached zero, so the branch tests the arithmetic directly. The body executes ten times, with r17 holding 10 down to 1 inside it and 0 on exit — the assembly form of for (i = 10; i != 0; i--).

Picking the branch. Write the C condition, decide signed or unsigned, and take the opposite instruction from the table:

Source condition Unsigned: skip with Signed: skip with
a == b brne brne
a != b breq breq
a < b brsh brge
a >= b brlo brlt
a > b swap operands: cp b, a then brsh cp b, a then brge
a <= b cp b, a then brlo cp b, a then brlt

There is no greater than branch; a > b is b < a, so compare the other way round.

See also

AVR Instructions

The AVR instructions introduced so far, in assembly and in machine code. See instruction-set-architecture for what an instruction set is and avr-architecture for the hardware that runs these.

The full alphabetical instruction set — each mnemonic with its operation, description, flags affected, clock count, opcode pattern and an example — is in the AVR instruction set reference: Atmel’s AVR Instruction Set Manual, and the instruction summary in the ATmega324A datasheet the course says to keep open. The notation key immediately below and the per-instruction flag table at the end are unverified against that reference — check them against your own copy before leaning on them.

Reading the instruction set reference

Operand notation — how an operand’s allowed values map onto opcode bits:

Notation Meaning Values Opcode pattern
Rd destination register (may be a source too) r0…r31 ddddd
r16…r31 dddd (register number − 16)
Rr source register r0…r31 rrrrr
Rh:Rl register pair as a 16-bit quantity r25:r24 / X / Y / Z dd (00 / 01 / 10 / 11)
K constant data 0…255 KKKKKKKK
k constant address −64…63, −2048…2047, 0…65535 kkkkkkk … kkkk kkkk kkkk kkkk
b bit number in a register 0…7 bbb
s bit in the status register 0…7 sss
P I/O register number 0…63 PPPPPP
q displacement for direct addressing 0…63 qqqqqq

The Rd row is the whole story behind LDI’s restriction — an instruction spending five bits on the register gets all 32; one spending four gets sixteen, and pays for it by starting at r16.

Operation notation — used in the Operation column:

M[a] / PM[a] / IO[a] SRAM cell / program memory (flash) byte / I/O register at address a
PC / SP / STACK program counter / stack pointer / M[SP]
← assigned value
reg(a) bit a of register reg, numbered 7…0 most to least significant

Flag names in the Flags Affected column are the SREG bits of avr-architecture.

Register conventions

Two operand names recur throughout the instruction set:

  • rd — the destination register.
  • rr — the source register.

AVR is a two-operand machine: the destination is also one of the sources, so add rd, rr means rd ← rd + rr. (Contrast a three-operand ISA such as ARM, where add rd, r1, r2 leaves both sources untouched.) This matters when reading code — an AVR arithmetic instruction always overwrites one of its inputs.

Instructions by type

The instruction set can be cut two ways.

By what the instruction touches — the instruction-type list of instruction-set-architecture, filled in with the instructions so far:

Type Does AVR so far
Input/Output communicate with I/O devices/ports IN, OUT
Load/Store move data from/to memory LD, LDS, ST, STS
Move copy data between registers MOV
Arithmetic addition, subtraction, … ADD, ADC, SUB, INC, NEG
Logical Boolean operations AND, ANDI, OR, ORI, EOR, COM
Branching deciding which instruction to perform next JMP, BREQ, BRNE

By operand count, which splits the arithmetic and logical group instead:

AVR examples
Dyadic combine 2 operands to produce a result add r5, r6 (arithmetic) · and r5, r6 (logical, bitwise)
Monadic one operand → one result ser r16 (set) · clr r5 (clear) · neg r5 (2’s complement) · com r5 (1’s complement) · the shifts and rotates

The second cut is the one that predicts the syntax: a dyadic instruction has a comma in it, a monadic one does not.

The instructions so far

Instruction Meaning Example
MOV rd, rr copy contents of rr into rd — rd ← rr mov r3, r14
ADD rd, rr add contents of rr to rd — rd ← rd + rr add r5, r6
ADC rd, rr add with carry — rd ← rd + rr + C adc r11, r5
AND rd, rr bitwise AND, result into rd
OR rd, rr bitwise OR, result into rd
EOR rd, rr bitwise exclusive-OR, result into rd
INC rd rd ← rd + 1 inc r22
LDI rd, number load immediate — put the number into rd ldi r16, 73
SER rd set all bits — rd ← $FF. Same as ldi rd, 0xFF, so r16–r31 only ser r17
CLR rd clear all bits — rd ← 0. Same as eor rd, rd, so any register clr r3
SUB rd, rr rd ← rd − rr sub r7, r19
COM rd one’s complement — flip all bits com r8
NEG rd two’s complement — negate neg r9
ANDI rd, K bitwise AND with a constant — r16–r31 only andi r16, 0x01
ORI rd, K bitwise OR with a constant — r16–r31 only ori r16, 0xF0

MOV is named misleadingly: it copies, it does not move. The source register is unchanged. It also affects no flags, which is what makes it safe to shuffle values between operations without disturbing the status register.

SER and CLR are short-hand ways of setting/clearing all bits of a register, and their restrictions differ because their expansions do:

Exactly the same as Reaches
ser rd (set register) ldi rd, 0xFF r16–r31 only — it inherits LDI’s four-bit register field
clr rd (clear register) eor rd, rd any register, r0–r31 — EOR is a two-register instruction with five bits for each

So clr r3 is legal and ser r3 is not, which looks arbitrary until you look at what each one assembles to. clr is also the reason \(X \oplus X = 0\) from bit-masking is worth remembering: XORing a register with itself is how the machine zeroes one.

Compare instructions

These do the arithmetic, discard the result, and keep only the flags — which is exactly what a conditional branch needs.

Instruction Does Note
CP rd, rr rd − rr compares two registers
CPI rd, K rd − K compares against a constant — like ldi, r16–r31 only
TST rd rd AND rd examines one register; literally the same operation as and rd, rd

tst looks odd until you notice that ANDing a value with itself leaves it unchanged (\(X \cdot X = X\)) but still sets N and Z from it — so it is a zero/sign test that costs nothing and clobbers nothing. See bit-masking.

A comparison is the same as subtraction, with the result not saved — it exists only to set status register flags (Z, N, C, V …). And the instruction reference specifies which status register bits are set by which instructions: the flags are defined per instruction rather than falling out of one shared adder, which is the point of the table at the end of this note.

Branch instructions

Based on status register values — the flags a compare just set:

Branches to label if
BREQ label Z = 1
BRNE label Z = 0

Together with CP that is a complete conditional: compare, which sets Z exactly when the two operands were equal, then branch on Z.

    cp   r5, r6          ; r5 - r6, result thrown away, flags kept
    breq same            ; Z = 1, i.e. r5 == r6

JMP label is the unconditional version — it tests nothing and always goes. Labels, and the program skeleton the branches live in, are in avr-program-structure.

breq/brne are two of ten: there is one branch per status flag per value, and the pairs that matter for ordering are brsh/brlo (unsigned, on C) and brge/brlt (signed, on S) — the full table, and why the signed pair reads S rather than N, are in avr-branches-and-jumps.

Control flow

The instructions that write the PC, and the two stack instructions that go with the calls (avr-branches-and-jumps, procedures-and-the-stack):

Instruction Does Words Cycles
BRxx label branch if a flag has the wanted value; reach ±64 words 1 1 (not taken) / 2 (taken)
JMP label PC ← address of label 2 3
RJMP label PC ← PC + offset; reach ±2 K words 1 2
IJMP PC ← Z 1 2
CALL label push the return address, then as JMP 2 4
RCALL label push the return address, then as RJMP 1 3
ICALL push the return address, then as IJMP 1 3
RET pop the return address into PC 1 4
PUSH rr store rr at SP, SP ← SP − 1 1 2
POP rd SP ← SP + 1, load rd from SP 1 2

None of these touches the status register except by what the pushed and popped values happen to be; a call between a cp and its branch is safe only if the procedure preserves the flags, which in practice means it is not.

Three more belong to interrupts, and between them they are the only instructions that change the I bit (avr-interrupts):

Instruction Does Words Cycles
SEI I ← 1: interrupts enabled 1 1
CLI I ← 0: interrupts disabled 1 1
RETI pop the return address into PC, and I ← 1 1 4

RETI is RET plus set I. A handler that ends in RET returns to the right place and leaves interrupts off for good.

Data movement

Data is usually copied, not moved — in every instruction below the source is left alone. What changes is where the two ends are:

Direction Called AVR
register → register move mov
memory → register load lds, ld
register → memory store sts, st
I/O register → register input in
register → I/O register output out

Three different places a value can live — a general purpose register, data memory, an I/O register — and a different instruction family for each. The one thing that is genuinely out of reach is SRAM from in/out: P only goes up to 0x3F, so those two never leave the first 64 I/O registers.

Everything else is a question of cost and numbering, not reachability. Because the I/O registers are mapped into the data space (avr-io-ports), lds/sts can reach one — in r16, 0x09 and lds r16, 0x29 both read PIND, the second for two instruction words instead of one. The bug to actually watch for is writing the I/O register number where the data address belongs, or the reverse.

Load and store

Does Addressing Words Cycles
LD rd, X rd ← Mem[X] indirect — address in the pointer register 1 2
ST X, rr Mem[X] ← rr indirect 1 2
LDS rd, k rd ← Mem[k] direct — 16-bit address in the instruction 2 (32 bits) 2
STS k, rr Mem[k] ← rr direct 2 2

For example:

    ld   r5, X           ; r5 <- Mem[X]
    st   X, r5           ; Mem[X] <- r5
    lds  r5, 0x20        ; r5 <- Mem[0x20]
    sts  0x20, r5        ; Mem[0x20] <- r5

Both pairs reach the same data space — the difference is only where the address comes from (addressing-modes), and lds/sts pay a second instruction word for spelling it out. X here is the pointer pair of avr-architecture.

In and out

Does Words Cycles
IN rd, P rd ← I/O register P 1 1
OUT P, rr I/O register P ← rr 1 1

rd/rr may be any of r0–r31 — unlike ldi, these are not restricted to the top half — and P is an I/O register number 0–63 (0x00–0x3F) or a name from m324Adef.inc. Examples: in r5, 0x26 (I/O register 0x26 is TCNT0) and out PORTD, r6. Full treatment in avr-io-ports.

One word and one cycle makes these the cheapest access on the chip — cheaper than reaching the very same register through lds/sts, which is the whole reason the first 64 I/O registers are special.

Shifts and rotates

Monadic instructions that move every bit one place. They differ only in what arrives at the vacated end and what happens to the bit that falls off — and in all five, the bit that falls off lands in C.

Figure 171: The three shift instructions. LSL and LSR feed a 0 into the vacated end; ASR feeds the sign bit back into itself, which is what makes it a signed division. In all three the bit shifted out lands in the carry flag.

Figure 172: The two rotate instructions. A rotate is a shift whose vacated end is fed from the carry flag instead of a constant, so the register and C together behave as a nine-bit ring.

Name Into the vacated end Out
LSL rd Logical Shift Left 0 → bit 0 bit 7 → C
LSR rd Logical Shift Right 0 → bit 7 bit 0 → C
ASR rd Arithmetic Shift Right bit 7 replicated into itself bit 0 → C
ROL rd ROtate Left through carry C → bit 0 bit 7 → C
ROR rd ROtate Right through carry C → bit 7 bit 0 → C

What they compute

Shifting a binary number one place is multiplying or dividing it by two, which is the whole reason these exist. Using four bits for legibility:

Worked example
LSL × 2 0010 (2) → 0100 (4) → 1000 (8)
LSR ÷ 2, read unsigned 0110 (6) → 0011 (3); 1000 (8 unsigned) → 0100 (4)
ASR ÷ 2, read signed 1000 (\(-8\)) → 1100 (\(-4\))

LSR and ASR are the pair to keep straight. Given 1000, LSR produces 0100 — right if the value meant unsigned 8, wrong if it meant \(-8\). ASR replicates the sign bit into the vacated position and produces 1100 \(= -4\). The same bits go in; the instruction is where you declare which interpretation you meant (binary-number-representations).

There is no matching pair going the other way, because left shifts need no such distinction: a 0 always enters at the bottom, and the signed and unsigned readings of “× 2” agree — right up until the result stops fitting in eight bits.

Shifting a value wider than eight bits

Rotates exist to carry a bit from one byte into the next. To multiply the 16-bit unsigned value in r13:r14 by two (so r13 is the high byte, r14 the low):

    lsl  r14             ; low byte x2; bit 7 falls out into C
    rol  r13             ; high byte x2, pulling C into its bit 0

LSL on the low byte pushes its top bit into C; ROL on the high byte pulls exactly that bit back in at the bottom. The two instructions together shift a sixteen-bit quantity one place.

The wrong answers are worth naming, because each fails differently. lsl r13 (and asl r13, which is the same operation under another name — shifting left, a 0 always enters) shifts the high byte but feeds it a 0, discarding the bit the low byte just produced. rol r14 rotates the wrong byte.

Building wider operations from 8-bit ones

The AVR supports exactly one data type in hardware — an 8-bit integer (instruction-set-architecture). Everything wider is a sequence of instructions, and C is what stitches the pieces together.

Add the 16-bit quantity r5:r4 to r11:r10, result in r11:r10 — high byte named first, so r4 and r10 are the low bytes:

    add  r10, r4         ; r10 <- r10 + r4        (low bytes; carry out lands in C)
    adc  r11, r5         ; r11 <- r11 + r5 + C    (high bytes, plus that carry)

ADD on the low bytes leaves any carry out of bit 7 in C, and ADC on the high bytes adds it back in — the same column-by-column carrying as long addition on paper, one byte per column.

The order is not negotiable, and neither is what sits between the two lines: adc has to run after the add that produced the carry, and any instruction in between that touches C ruins the result. That is the general shape of multi-byte arithmetic on an 8-bit machine — low end first, and nothing allowed to disturb the flag in the middle.

Constants

Constants do not have to be hexadecimal. All five of these load the same value into r17:

Written Radix
ldi r17, 0x34 hexadecimal 0x prefix
ldi r17, $34 hexadecimal $ prefix
ldi r17, 52 decimal no prefix
ldi r17, 064 octal a leading 0
ldi r17, 0b00110100 binary 0b prefix

\(\texttt{0x34} = 52 = 64_8 = \texttt{0b00110100}\). The octal form is the trap: a leading zero changes the radix, so 012 is 10, not 12.

LDI’s restrictions

LDI is the one with strings attached:

  • Registers r16 to r31 only. Not r0–r15.
  • 8-bit numbers, 00000000 to 11111111. Written in decimal the range is \(-128\) to \(255\) — that span covers both the signed and the unsigned reading of eight bits.

A counter-example, and the legal version of it:

    ldi  r0, 5           ; NOT legal - r0 is below r16
    ldi  r16, 5          ; the same idea, in a register ldi can reach

The register restriction is not arbitrary: it falls straight out of the encoding below, which has only four bits for the register number.

Machine code

Each instruction is a 16-bit word made of an opcode and operand bit fields — see instruction-set-architecture. In the AVR datasheet’s notation, a format like 0000 11rd dddd rrrr means the literal bits are fixed and each letter is one bit of an operand, gathered from wherever it appears.

Figure 173: Three AVR instruction encodings, each 16 bits. Fixed opcode bits are shaded; letters are operand bits. In ADD and LDI the operand bits are not contiguous — the register number’s top bit sits apart from the rest, and LDI’s constant is split into two nibbles either side of the register field.

ADD — 0000 11rd dddd rrrr

The opcode is bits 15–10, 0000 11 — six fixed bits, all that is left once the two five-bit register numbers have taken ten of the sixteen. The destination register number is d dddd — five bits, so all 32 registers — and the source is r rrrr. Both have their top bit separated from the other four, and note the order in the middle nibble: the source’s top bit (r, bit 9) comes before the destination’s (d, bit 8), even though the mnemonic writes the destination first.

Worked example: add r23, r7.

Register In binary (5 bits) Split as
rd r23 = 16 + 4 + 2 + 1 10111 d = 1, dddd = 0111
rr r7 = 4 + 2 + 1 00111 r = 0, rrrr = 0111

Dropping those into 0000 11rd dddd rrrr:

\[\texttt{0000 1101 0111 0111}\]

Figure 174: Assembling add r23, r7. Each register number is written as five bits, then torn in two: the top bit goes into the middle nibble and the low four into their own field. Shading, not position, is what tells the two operands apart here. The two guide lines cross because the destination’s bit sits between the source’s two pieces.

COM — 1001 010d dddd 0000

Flip all bits — one’s complement. One register operand, again as d dddd.

Worked example: com r19. r19 = 16 + 2 + 1 = 10011, so d = 1 and dddd = 0011:

\[\texttt{1001 0101 0011 0000}\]

LDI — 1110 KKKK dddd KKKK

Two operand fields:

  • K — the 8-bit constant, split into two nibbles: the high four bits in the first KKKK field, the low four in the last.
  • d — the register number minus 16.

That subtraction is why LDI only reaches r16–r31: the field is four bits, so it can express \(2^4 = 16\) distinct registers, and the ISA spends them on the top half of the register file.

Applying the rule to ldi r16, 73: \(d = 16 - 16 = 0\), so dddd = 0000; \(73 = \texttt{0100 1001}\), so the high nibble is 0100 and the low nibble 1001:

\[\texttt{1110 0100 0000 1001}\]

Flags, by instruction

The reference’s Flags Affected column is worth reading rather than assuming — the flags are defined per instruction, not derived from a single adder. For the instructions above:

Instruction Z C N V
MOV, LDI, SER — — — —
AND, ANDI, OR, ORI, EOR, TST from result unchanged from result cleared to 0
ADD, ADC, SUB, CP, CPI from result from carry/borrow from result signed overflow
CLR always 1 unchanged always 0 cleared to 0
COM from result always set to 1 from result cleared to 0
NEG from result set unless the result is $00 from result set only if the result is $80

Two of these will catch you out. The logical operations leave C alone entirely — whatever it held before an and it still holds after. And COM sets C unconditionally, which is not a carry out of anything; it is a defined convention, chosen so that com followed by an increment behaves like a negation.

The CLR row is just the logical row with a result that is guaranteed to be 0x00 — clr rd is eor rd, rd — which makes it the one instruction whose flags you can predict without knowing the operand.

For the shift, rotate and branch instructions, look the flags up in the reference rather than guessing. The one part that is visible in the diagrams above is C: every shift and rotate sets it from the bit that fell out. The rest is defined per instruction, as the paragraph opening this section warns.

For ADD specifically, the manual gives the flags as Boolean formulas over the operand and result bits, writing \(R\) for the result (which equals Rd after the operation):

\[N = R_7 \qquad Z = \overline{R_7}\cdot\overline{R_6}\cdot\overline{R_5}\cdot\overline{R_4}\cdot\overline{R_3}\cdot\overline{R_2}\cdot\overline{R_1}\cdot\overline{R_0}\] \[V = Rd_7 \cdot Rr_7 \cdot \overline{R_7} + \overline{Rd_7}\cdot\overline{Rr_7}\cdot R_7 \qquad C = Rd_7 \cdot Rr_7 + Rr_7 \cdot \overline{R_7} + \overline{R_7}\cdot Rd_7\]

\(Z\) is a NOR over every result bit. \(V\) says overflow happened exactly when both operands had the same sign and the result’s differs — two negatives giving a positive, or two positives giving a negative. And \(S = N \oplus V\), for signed tests. See avr-architecture.

See also

AVR Interrupts

How the ATmega324A implements interrupts, and how to write one and switch it on, in assembly and in C: the path from a device’s request to the handler and back, the vector table, the switches that decide whether a request is taken, the ISR template and its stack, ISR() and the _vect names, volatile, priority, and a complete timer-interrupt program. First met in 2026-09-21-interrupts. What an interrupt is on any CPU (polling versus interrupts, the fourteen-step sequence, transparency, nesting) is polling-and-interrupts.

The path of an interrupt

An interrupt is a procedure call the hardware makes (procedures-and-the-stack). The CPU finishes the instruction in progress, pushes the address of the next one, turns interrupts off and loads the PC with the address of the vector table entry for the source. The entry holds a jmp to the handler. The handler ends with reti, which pops the return address and turns interrupts back on.

Figure 175: One timer interrupt from start to finish. The request (1) arrives while cp is executing, and the CPU lets it finish (2): an AVR instruction is never abandoned halfway. The hardware then pushes the address of the next instruction, breq, clears the I bit (3), and loads the PC with 0x0014 (4), the vector table entry for Timer/Counter 2 compare match B. The jmp stored there reaches the handler (5), which saves what it uses, does its work, restores, and ends with reti (6). That pops the return address and sets I again, and execution continues at breq (7) as if nothing had happened. It will, provided the handler restored the status register, because breq is about to read the Z flag that cp set. Nothing in the main program refers to the handler; the vector table is the only link between them.

The vector table

The first addresses of program memory hold the interrupt vector table: one entry per interrupt source, in a fixed order, each a two-word jmp to that source’s handler (avr-branches-and-jumps). The AVR uses a table of jump instructions, not a table of addresses. When it takes an interrupt it loads the PC with the address of the entry itself and executes what it finds there. So:

\[\text{entry address} = 2 \times (\text{vector} - 1)\]

RESET is vector 1, at 0x0000. A reset is taken through the same table as an interrupt, which is why every program begins with jmp RESET (avr-program-structure). The table has 31 entries on the ATmega324A and ends at 0x003C, so the program proper starts at 0x003E.

Figure 176: The bottom of program memory. Each vector-table entry is two words, the two halves of a jmp, so entry \(n\) sits at address \(2(n-1)\), and the table’s order is also its priority order: when two requests are waiting, the one nearer the top is taken first. The expanded entry shows what one of them holds, taking vector 14, Timer/Counter 1 compare match A, as the example. An entry for a source the program does not use can hold anything, as long as that interrupt is never enabled. The program itself starts at the first address after the table, which the jmp in entry 1 reaches at reset.

The full table for the ATmega324A, from pages 69–70 of the datasheet. The Group column sorts the sources by kind: GPIO, T/C, Comms, analog and system. The C name is the Source followed by _vect.

Vector Address Source Interrupt definition Group C handler
1 0x0000 RESET RESET, watchdog reset, etc. — — (the program’s start)
2 0x0002 INT0 External Interrupt Request 0 GPIO ISR(INT0_vect)
3 0x0004 INT1 External Interrupt Request 1 GPIO ISR(INT1_vect)
4 0x0006 INT2 External Interrupt Request 2 GPIO ISR(INT2_vect)
5 0x0008 PCINT0 Pin Change Interrupt Request 0 (port A) GPIO ISR(PCINT0_vect)
6 0x000A PCINT1 Pin Change Interrupt Request 1 (port B) GPIO ISR(PCINT1_vect)
7 0x000C PCINT2 Pin Change Interrupt Request 2 (port C) GPIO ISR(PCINT2_vect)
8 0x000E PCINT3 Pin Change Interrupt Request 3 (port D) GPIO ISR(PCINT3_vect)
9 0x0010 WDT Watchdog Time-out Interrupt system ISR(WDT_vect)
10 0x0012 TIMER2_COMPA Timer/Counter2 Compare Match A T/C ISR(TIMER2_COMPA_vect)
11 0x0014 TIMER2_COMPB Timer/Counter2 Compare Match B T/C ISR(TIMER2_COMPB_vect)
12 0x0016 TIMER2_OVF Timer/Counter2 Overflow T/C ISR(TIMER2_OVF_vect)
13 0x0018 TIMER1_CAPT Timer/Counter1 Capture Event T/C ISR(TIMER1_CAPT_vect)
14 0x001A TIMER1_COMPA Timer/Counter1 Compare Match A T/C ISR(TIMER1_COMPA_vect)
15 0x001C TIMER1_COMPB Timer/Counter1 Compare Match B T/C ISR(TIMER1_COMPB_vect)
16 0x001E TIMER1_OVF Timer/Counter1 Overflow T/C ISR(TIMER1_OVF_vect)
17 0x0020 TIMER0_COMPA Timer/Counter0 Compare Match A T/C ISR(TIMER0_COMPA_vect)
18 0x0022 TIMER0_COMPB Timer/Counter0 Compare Match B T/C ISR(TIMER0_COMPB_vect)
19 0x0024 TIMER0_OVF Timer/Counter0 Overflow T/C ISR(TIMER0_OVF_vect)
20 0x0026 SPI_STC SPI Serial Transfer Complete Comms ISR(SPI_STC_vect)
21 0x0028 USART0_RX USART0 Receive Complete Comms ISR(USART0_RX_vect)
22 0x002A USART0_UDRE USART0 Data Register Empty Comms ISR(USART0_UDRE_vect)
23 0x002C USART0_TX USART0 Transmit Complete Comms ISR(USART0_TX_vect)
24 0x002E ANALOG_COMP Analog Comparator analog ISR(ANALOG_COMP_vect)
25 0x0030 ADC ADC Conversion Complete analog ISR(ADC_vect)
26 0x0032 EE_READY EEPROM Ready system ISR(EE_READY_vect)
27 0x0034 TWI 2-wire Serial Interface Comms ISR(TWI_vect)
28 0x0036 SPM_READY Store Program Memory Ready system ISR(SPM_READY_vect)
29 0x0038 USART1_RX USART1 Receive Complete Comms ISR(USART1_RX_vect)
30 0x003A USART1_UDRE USART1 Data Register Empty Comms ISR(USART1_UDRE_vect)
31 0x003C USART1_TX USART1 Transmit Complete Comms ISR(USART1_TX_vect)

Every timer event the course uses has its own vector. The three units’ compare matches and overflows are vectors 10–19, and a unit’s compare A and compare B are separate sources with separate handlers, just as they have separate flags (avr-timers-and-counters).

When a request is taken

Four things have to be true before a source’s handler runs. The four setup steps (set up the conditions, enable the interrupt, clear its flag, enable globally) arrange for them:

  1. The conditions for the interrupt are set up, so that the event can happen at all: a timer running in the right mode, or a pin configured to sense an edge.
  2. That particular interrupt is enabled, by its own bit in an I/O register. There is one bit per source.
  3. Its flag is set. The hardware does this when the event occurs, whether or not the interrupt is enabled. That is why the third setup step clears the flag before the interrupt is enabled: afterwards only a fresh event can set it, and an event from before the setup does not fire at once. Clearing is done by writing a 1 to the flag’s bit.
  4. Interrupts are enabled globally: the I bit of the status register is 1. sei (or sei() in C) sets it.

Figure 177: Whether a request becomes an interrupt, drawn as the logic it amounts to. Each source has a flag, set by its event, and an enable bit, set by the program. The source requests an interrupt only while both are 1, and all three sources here are gated the same way. If more than one is requesting, the lowest vector number wins. The winner is taken only if the I bit is also 1, and taking it clears I. For these sources, taking the vector also clears the flag. So a flag with its enable bit off simply stays set, available to be polled, and a flag that goes up while I is 0 waits and is taken the moment I returns to 1.

For the sources the course meets, the bits are:

Source Flag (register) Enable (register) Conditions set up in
INT0 (pin PD2) INTF0 (EIFR) INT0 (EIMSK) EICRA: bits ISC01, ISC00 choose low level 00, any change 01, falling edge 10 or rising edge 11
TIMER0_COMPA OCF0A (TIFR0) OCIE0A (TIMSK0) TCCR0A, TCCR0B, OCR0A
TIMER0_OVF TOV0 (TIFR0) TOIE0 (TIMSK0) TCCR0A, TCCR0B
TIMER1_COMPA OCF1A (TIFR1) OCIE1A (TIMSK1) TCCR1A, TCCR1B, OCR1A
TIMER1_OVF TOV1 (TIFR1) TOIE1 (TIMSK1) TCCR1A, TCCR1B

The naming pattern is regular: an F for the flag and an IE for interrupt enable, with OC for output compare and TOV/TOIE for timer overflow. Each of these flags is cleared automatically when its vector is taken, so a handler does not normally clear its own flag. A program that polls a flag instead, with the interrupt left disabled, must clear it itself (avr-timers-and-counters).

The I bit

I Also
sei ← 1
cli ← 0
taking an interrupt (hardware) ← 0 pushes PC, loads the vector address
reti ← 1 pops PC

I is bit 7 of SREG (avr-architecture), and it is 0 after reset, so no interrupt happens until the program executes sei. Because the hardware clears it on entry, a handler runs with interrupts off unless it turns them back on itself.

External interrupts

An external interrupt is requested by a pin. The ATmega324A has three, each fixed to one pin:

Interrupt Pin
INT0 PD2
INT1 PD3
INT2 PB2

What the pin has to do to make a request is chosen by two sense control bits per interrupt, in EICRA:

ISCn1:0 A request is made
00 for as long as the pin is low
01 on any change of the pin
10 on a falling edge, 1 to 0
11 on a rising edge, 0 to 1

Figure 178: What each sense control setting responds to, for a push button that reads 1 while it is held. A rising edge is the moment the button is pushed and a falling edge is the moment it is let go. Any change gives a request at both. The low level setting is different in kind: it asks for the whole time the pin is low, so the handler runs again and again until the pin goes high.

Setting one up follows the same steps as any other interrupt. For a rising edge on INT0 and a falling edge on INT1:

ISR(INT0_vect) { /* PD2 went from 0 to 1 */ }
ISR(INT1_vect) { /* PD3 went from 1 to 0 */ }

/* in main */
EICRA = (1<<ISC01) | (1<<ISC00) | (1<<ISC11);   /* INT0 rising, INT1 falling */
EIMSK = (1<<INT0) | (1<<INT1);                  /* enable both               */
EIFR  = (1<<INTF0) | (1<<INTF1);                /* clear both flags          */
sei();
  • Edges fit buttons. An edge happens once per push, however long the button is held. That makes an external interrupt a natural way to act on a push or on a release without the program having to remember what the button was doing last time.
  • Bounce. A mechanical contact chatters for a moment as it closes, and each chatter is an edge. One push can then run the handler several times.
  • The low level setting keeps asking. If the pin is still low when the handler returns, the interrupt is taken again straight away.
  • Priority. INT0, INT1 and INT2 are vectors 2, 3 and 4, directly after reset, so they come before every timer and serial interrupt.

Used for the start/stop and reset buttons of a stopwatch in week9-lab-avr-interrupts.

Writing an ISR in assembly

The template:

isr_label:
    push r0              ; save r0: it is about to carry SREG
    in   r0, SREG
    push r0              ; save the interrupted program's flags

    ; ... perform the operation, usually input/output ...
    ; (any other register used: push it here, pop it below)

    pop  r0
    out  SREG, r0        ; flags back as they were
    pop  r0              ; r0 back as it was
    reti                 ; pop PC and set I

SREG cannot be pushed directly, because push takes a general-purpose register. So one register carries it, and that register is saved first. The restore is the save in reverse. Two consequences follow from where the save happens:

  • The flags saved are the interrupted program’s. Apart from I, the hardware does not touch them on entry, and push changes none, so the copy is exactly what the interrupted code left.
  • The saved I bit is 0, because the hardware cleared it before the first instruction of the ISR. Writing the copy back therefore leaves interrupts off until reti, which is the right moment for them to come back.

Figure 179: The stack through the ISR template, with the three things the interrupted program relies on (r0, its flags, and the I bit) traced underneath. The hardware’s push of the return address comes first, then the template’s two pushes, the SREG copy on top. The body is free to change r0 and the flags because both are safely on the stack. The restore pops the copy into r0 and writes it to SREG, then pops r0’s own value. When reti runs, the return address is on top again, exactly as the hardware left it. I stays 0 from entry to reti, the copy in the middle included, and it is reti that sets it.

Which registers to save is decided by what the body does. Save any register the body writes. Save SREG if any instruction in the body changes a flag, which rules in arithmetic, logic, compares and shifts but not in, out, ldi, mov, push or pop (avr-instructions). A handler that only copies a port to another port needs one register and no SREG at all (worked in 2026-09-21-interrupts).

Placing the entry in the table

The template in avr-program-structure puts jmp RESET at 0x0000 and leaves a comment where the handlers go. Once a vector is used, its jmp has to sit at exactly that vector’s address. The assembler’s .org directive sets the address of whatever comes next (assembly-process):

.include "m324Adef.inc"

.org 0x0000
        jmp  RESET
.org 0x001A              ; vector 14: TIMER1_COMPA
        jmp  timer1_compa_isr
.org 0x003E              ; first address after the table
RESET:
        ; stack pointer, ports, timer 1, TIMSK1 ...
        sei
loop:
        ; ...
        rjmp loop

timer1_compa_isr:
        push r0
        in   r0, SREG
        push r0
        ; ...
        pop  r0
        out  SREG, r0
        pop  r0
        reti

An assembly program that uses interrupts must also set up the stack pointer before the first sei (procedures-and-the-stack), since taking an interrupt pushes the return address.

Writing an ISR in C

#include <avr/interrupt.h>

ISR(INT0_vect) {
    /* code here */
}

ISR is a macro from avr/interrupt.h, and its argument names the vector: the source name from the datasheet followed by _vect (the table above). From it the compiler does everything the assembly programmer does by hand. The vector table is set up automatically: the handler’s jmp goes in the right entry. Registers are saved and restored automatically, SREG included, and the function ends in reti. What ISR() does not do is any of the four setup steps. In C, as in assembly, the program still sets up the conditions, enables the interrupt, clears its flag and calls sei(). sei() and cli() are macros for the single instructions.

A complete example

Timer 1 in CTC mode, matching eight times a second, with the handler toggling an LED and counting ticks. The timer set-up is Lab 12’s (week8-lab-avr-timers): \(8\,\text{MHz} / (64 \times 15625) = 8\ \text{Hz}\).

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t ticks = 0;            /* written by the ISR, read by main */

ISR(TIMER1_COMPA_vect) {
    PORTA ^= (1<<0);                    /* toggle the LED on PA0 */
    ticks++;
}

int main(void) {
    DDRA = (1<<0);                      /* PA0 is an output */

    /* 1. conditions: CTC mode, clock/64, match at 15624 */
    OCR1A  = 15624;
    TCCR1A = 0;
    TCCR1B = (1<<WGM12) | (1<<CS11) | (1<<CS10);

    /* 2 and 3. clear any stale match, then enable this interrupt */
    TIFR1  = (1<<OCF1A);
    TIMSK1 = (1<<OCIE1A);

    /* 4. enable interrupts globally */
    sei();

    while (1) {
        if (ticks >= 8) {               /* a second has gone by */
            ticks = 0;
            /* ... once-a-second work ... */
        }
        /* ... anything else: the LED keeps time by itself ... */
    }
}

Figure 180: The example program running, one trace per signal. The count climbs to OCR1A = 15624 and is cleared (CTC mode), once every 125 ms. Each match sets OCF1A; the interrupt is enabled and I is 1, so the vector is taken a few cycles later, and taking it clears the flag again. The handler is a sliver of time in which the LED output is toggled and ticks counted, and the rest of the time belongs to main. Nothing in main looks at the timer. The LED blinks at 4 Hz, one toggle per match, however busy main is.

volatile: variables shared with a handler

A variable that can change outside the normal flow of the program, in an interrupt handler for instance, must be declared volatile. Without it the optimiser may assume the value cannot change while main is not changing it, keep it in a register or drop a test on it altogether, and never see the handler’s writes. In the example above, while (1) { if (ticks >= 8) … } without volatile could read ticks once and never again. An example of exactly this, a loop that never ends, is drawn in 2026-09-21-interrupts. The same keyword is what makes the I/O register macros work (c-preprocessor-and-avr-headers): in both cases the value in memory changes behind the program’s back.

volatile is not enough for a variable wider than a byte. The AVR reads a 16-bit variable with two 8-bit loads, and an interrupt can land between them. Suppose a handler increments ms from 0x00FF to 0x0100 just after main has read the low byte: main gets 0xFF from the old value and 0x01 from the new, and reads 0x01FF, off by 256. The cure is to keep interrupts off for the read:

volatile uint16_t ms;                  /* incremented by a 1 ms timer ISR */

uint16_t now;
cli();                                 /* no interrupt between the two bytes */
now = ms;
sei();

(If interrupts might already have been off, ATOMIC_BLOCK(ATOMIC_RESTORESTATE) from util/atomic.h does the same and puts I back as it found it.) An 8-bit shared variable needs none of this, which is one good reason to keep shared variables to a byte where possible.

Priority

Priority is determined by vector: the lowest vector is the highest priority. RESET is highest, then INT0, and so on down the table. On the AVR, priority only matters when two or more interrupts are waiting to be serviced, and it decides which is taken first. It never lets one interrupt cut into another’s handler, because I is 0 throughout a handler. The datasheet adds one rule: after reti, the CPU always executes one instruction of the interrupted program before taking the next waiting interrupt, so a stream of interrupts can slow main down but never stop it altogether.

Interrupts can be re-enabled inside a handler with sei. Any incoming or waiting interrupt may then be serviced immediately, nested inside the current handler, even if it has lower priority. Priority plays no part there. Both cases are traced in 2026-09-21-interrupts and set against true priority nesting in polling-and-interrupts.

Pitfalls

  • Forgetting sei(). Everything else is set up, and nothing ever happens, because I is 0 from reset.
  • Enabling an interrupt that has no handler. In C, avr-libc fills every unused vector with a jump to a default handler that jumps to address 0, so the program restarts whenever the event occurs. It is not a true reset: the I/O registers keep whatever they held, which can make the restart behave differently from a power-up.
  • Misspelling the vector name. ISR(TIMER1_COMPA_Vect) compiles with only a warning, and the handler is never placed in the table, which makes it the previous pitfall.
  • Not clearing a stale flag before enabling: the interrupt fires once immediately, for an event that happened before the program was ready.
  • Clearing a flag with |=. If the compiler turns it into a read, an OR and a write, it clears every flag in the register that happens to be set (avr-timers-and-counters). Writing just the one bit, TIFR1 = (1<<OCF1A);, is safe however it is compiled.
  • In assembly: not saving SREG, unbalanced pushes and pops, or ret instead of reti. The first corrupts the interrupted code’s flags. The second returns to the wrong address. The third returns correctly but leaves I at 0, so no interrupt ever happens again.
  • Long handlers. No delay loops and no waiting inside an ISR: every other interrupt waits too, and repeated events of one source merge into one.
  • A shared variable without volatile, or a multi-byte one read without cli().

See also

AVR I/O Ports

How an AVR program actually reads a switch and lights an LED: the I/O register file, the three registers behind every port, the two instructions that reach them, how to change one bit of a port without disturbing the others, what writing to PINx really does, and the pins’ alternate uses by the serial interfaces. See avr-architecture for the chip these live on, avr-instructions for the instruction set, and io-board for the devices that get wired to the pins.

I/O registers

The ATmega324A has 224 I/O registers — registers that control the peripherals and carry data to and from them:

  • Timers and counters
  • Analog to digital converters
  • Serial input/output
  • General purpose input/output ports

They are not the general purpose registers. Some instructions work with these, others with r0–r31, and confusing the two is the standard beginner error — ldi r16, 0xFF and out DDRA, r16 name completely different register files with the same-looking numbers.

Some addresses are reserved (not actually available on this device). The full list is the I/O register summary, pages 636 to 639 of the datasheet.

Where they live, and how you get at them

I/O registers 0 to 223 sit in the data address space at memory addresses 32 to 255 (0x20 to 0xFF) — see memory-models for why the AVR has a separate data space at all. That gives two ways to name the same register, and two names for it:

Range Reached by
First 64 I/O registers (0 to 63) data addresses 0x20–0x5F in and out and ld/st
Other 160 — the “extended” I/O registers (64 to 223) data addresses 0x60–0xFF ld/st only

so the two numbering systems differ by a constant:

\[\text{data memory address} = \text{I/O register number} + \texttt{0x20}\]

The offset is exactly the 32 general purpose registers, which occupy 0x0000–0x001F at the bottom of the data space ahead of them.

Why the split exists at all: in/out encode the I/O register number in six bits of the instruction word, and \(2^6 = 64\). Everything past register 63 has no room in the encoding, so it can only be reached the long way round, by its data address.

Figure 181: The bottom of the ATmega324A data address space, and the two numbering systems that live on it. Every I/O register has two numbers — its I/O register number (what in/out take) and its data memory address (what ld/st take) — and they differ by a constant 0x20, because the 32 general purpose registers sit in front of them in the same space. Only the first 64 I/O registers have an I/O register number small enough to fit the six operand bits of in/out; the 160 extended ones can be reached by their data address alone. The map follows the convention of csse2010-diagram-notation: lowest address at the top, hex addresses outside.

Extract from the I/O register list

The general purpose port registers are the first twelve entries, in the order PIN, DDR, PORT for each port in turn:

Data address I/O reg number Name
0x2B 0x0B PORTD
0x2A 0x0A DDRD
0x29 0x09 PIND
0x28 0x08 PORTC
0x27 0x07 DDRC
0x26 0x06 PINC
0x25 0x05 PORTB
0x24 0x04 DDRB
0x23 0x03 PINB
0x22 0x02 PORTA
0x21 0x01 DDRA
0x20 0x00 PINA

Further up the same list, to show the pattern continues and that reserved entries are real:

Data address I/O reg number Name
0x38 0x18 TIFR3
0x37 0x17 TIFR2
0x36 0x16 TIFR1
0x35 0x15 TIFR0
0x34 0x14 Reserved

Read the two columns carefully in an exam question. out 0x02, r16 writes PORTA, but sts 0x02, r16 writes general purpose register r2 — the same number, two address spaces, and only the instruction tells them apart.

GPIO ports

The ATmega324A has four 8-bit general purpose I/O ports — PORT A, PORT B, PORT C, PORT D — appearing on the datasheet block diagram as PA7..0, PB7..0, PD7..0 around the edge of the chip, with port C drawn as PC5..0 plus TOSC1/PC6 and TOSC2/PC7 broken out separately — those two pins double as the timer oscillator connections. They are still port C bits, and DDRC/PORTC/PINC still cover all eight.

Three registers are associated with each (x = A, B, C or D):

Register Name What it holds
DDRx Data Direction Register which pins are outputs
PORTx values to output
PINx values on the pins

Each is 8 bits — one bit per pin. DDRA0, PORTA0 and PINA0 are the three bits belonging to pin PA0.

What one bit of a port looks like

Figure 182: One bit of an AVR port — the three flip-flops behind pin PA0. DDRA0 enables the tri-state buffer, so it decides whether PORTA0’s value is driven onto the pin or the pin is left free for something outside to drive. PINA0 samples whatever is on the pin either way. Hence: DDR is direction, PORT is what you write, PIN is what you read.

1 means output, 0 means input. Writing 0xFF to DDRA makes every bit of port A an output, and writing 0x00 to DDRB makes every bit of port B an input.

Three consequences fall straight out of the circuit:

  • PORTx does nothing on a pin whose DDRx bit is 0. The buffer is off; the value sits in the flip-flop unused. (On real AVR hardware it switches an internal pull-up instead.)
  • PINx is always live. It samples the pin whether the pin is being driven from inside or outside, so reading PINx on an output pin reads back what you are driving.
  • Reading PORTx is not reading the pin. It gives you the value you last wrote. To find out what is there, read PINx — which is why every input example uses in rd, PINx and never in rd, PORTx.

in and out

The two instructions that reach the first 64 I/O registers:

Does Operands
in rd, P Load I/O register value into general purpose register rd: r0 to r31. P = I/O register number (0 to 63, 0x00 to 0x3F) or name
out P, rr Store value from general purpose register into I/O register rr: r0 to r31. P = 0 to 63 (0x00 to 0x3F) or name

The operand order flips between them, and it flips for a consistent reason: like every AVR instruction, the destination is written first. So the I/O register is the second operand of in and the first of out.

Figure 183: in and out between the two register files: the CPU’s general purpose registers r0–r31 and the first 64 I/O registers. in reads from an I/O register into a general purpose register, out writes the other way, and the head of each arrow, marked destination, is the operand written first. That is why the I/O register is the second operand of in and the first of out.

Answers of the form in DDRB, r16 are the standard trap. What is wrong with them is the mnemonic, not the direction: in’s destination is always one of r0–r31, so it can never be DDRB. Moving a general purpose register into an I/O register is exactly what out does — which is why the right answer in that shape is out DDRB, r16.

in and out reach all 32 general purpose registers, r0–r31 — unlike ldi, they are not restricted to the top half.

Both are one instruction word and one clock cycle, which makes them the cheapest way to touch a peripheral.

Three equivalences, all of them just the number/name table above:

Written with a number Same instruction, written with a name
in r0, 0 in r0, PINA
out 1, r0 out DDRA, r0
in r5, 0x26 in r5, TCNT0 — I/O register 0x26 is timer/counter 0

Using port names

Numbers are how the machine sees it; names are how you should write it:

.include "m324Adef.inc"

The contents of this file are included directly in the program, and it defines the names for the I/O registers — so DDRA, PORTA, PINA, TCNT0 and the rest can be written instead of 0x01, 0x02, 0x00, 0x26. Everything about the generated machine code is identical; the assembler substitutes the number.

Setting port A (all bits) to be an output, which is the shape of nearly every initialisation block:

    ldi  r16, 0xFF       ; every bit 1 = output
    out  DDRA, r16       ; ... into the direction register

or, using the shorthand of avr-instructions, ser r16 in place of the ldi. Setting a port to be all inputs is the same two lines with 0x00 (or clr), and a mixed port is any other constant — DDRA is a bit pattern like everything else, so ldi r16, 0x0F gives four outputs and four inputs.

Changing one bit of a port

Writing a whole port register is right at initialisation. Afterwards a program usually wants to change one pin and leave the other seven alone, because the other pins belong to other parts of the program. In C that is a read-modify-write with a one-bit mask, the bit named rather than given as a number (bit-masking):

DDRC  |= (1<<5);          /* PC5 becomes an output     */
PORTC |= (1<<5);          /* PC5 driven high           */
PORTC &= ~(1<<5);         /* PC5 driven low            */
PORTC ^= (1<<5);          /* PC5 flipped               */
if (PINC & (1<<2)) { }    /* is PC2 high?              */

In assembly there are two ways:

Register Set or clear one bit
I/O registers 0 to 31, which includes every PINx, DDRx and PORTx sbi PORTC, 5 and cbi PORTC, 5 one instruction, other bits untouched
any register in/out reach, 0 to 63 in r16, TCCR0B, then ori or andi with the mask, then out TCCR0B, r16 three instructions, and a spare register

sbi and cbi hold the register number in five bits of the instruction, so they reach only the first 32 I/O registers. TCCR0B is I/O register 0x25, 37, which is past them: the long way is the only way. The extended registers past 63, such as TIMSK2 and TCCR1B, need lds and sts in place of in and out.

Writing to PINx

PINx is the port’s input register: reading it gives the levels on the pins. Writing to it is not storing a value. On the ATmega324A, writing a 1 to a bit of PINx toggles the matching bit of PORTx, whatever the pin’s direction, and writing a 0 does nothing.

That makes PINx a quick way to flip a pin:

PINC = (1<<0);            /* toggle PC0; the 0s written to the other bits do nothing */

and in assembly sbi PINC, 0 does the same in one instruction.

It also makes PINx the wrong register for a clear or a set. PINC &= ~(1<<5) does not clear PC5. If the compiler turns it into a single cbi PINC, 5, it writes a 0 to bit 5 of PINC and nothing happens. If it does a read, an AND and a write, it writes 1s to every other bit that read high, and those pins flip:

Figure 184: Why a read-modify-write on PINC goes wrong. Port C is all outputs, driving 0110 0001, so its pins read the same. PINC &= ~(1<<5) reads them, clears bit 5 of the reading and writes the result to PINC. A 1 written to a PINx bit is an order to toggle that bit of PORTx, not a value to keep, and a 0 does nothing. So the two other 1s, shaded, flip PC6 and PC0 low, and PC5, the bit meant to be cleared, stays high. The bottom row is what PORTC &= ~(1<<5) would have given.

So: set and clear through PORTx, read through PINx, and write PINx only to toggle.

Alternate pin functions

Most pins have a second job. When the peripheral that owns a pin is switched on, it takes the pin over from the port, and for some pins it overrides DDRx too. The serial interfaces use these:

Port pin Package pin Alternate use Peripheral
PB0 1 XCK0 USART0’s clock, used when it is an SPI master
PB4 5 \(\overline{\text{SS}}\) SPI (avr-spi)
PB5 6 MOSI SPI
PB6 7 MISO SPI
PB7 8 SCK SPI
PC0 22 SCL TWI
PC1 23 SDA TWI
PD0 14 RXD0 USART0 (avr-usart)
PD1 15 TXD0 USART0
PD2 16 RXD1 USART1
PD3 17 TXD1 USART1
PD4 18 XCK1 USART1’s clock, used when it is an SPI master

So the SPI port is the upper half of port B, and the TWI is the bottom two bits of port C. Other pins carry timer outputs, the external interrupts (INT0 and INT1 share PD2 and PD3 with USART1) and, on port A, the analog inputs. A pin can do only one job at a time, so a program that uses the SPI cannot also use PB4 to PB7 as general purpose I/O. The whole pinout is drawn in 2026-10-05-more-io.

Common mistakes

  • in DDRB, r16. in always writes a general purpose register. Writing an I/O register is out DDRB, r16.
  • Reading PORTx to find out what is on a pin. That gives back what was last written. The pins are PINx.
  • Setting or clearing a bit through PINx. A 1 written there toggles, so PINC &= ~(1<<5) flips other pins and leaves PC5 alone.
  • PORTC = (1<<5) to set one pin. = writes all eight bits and drives the other seven low. Use |=.
  • sbi or cbi on a register past 31, such as TCCR0B. They cannot reach it; use in, ori/andi, out.
  • Using a pin as general I/O while its peripheral is on. The SPI, the TWI and the USARTs take their pins over.

See also

AVR Assembly Program Structure

The skeleton every AVR assembly program in this course is built on — what goes at the top, where execution starts, and why it ends in an infinite loop. See avr-instructions for what fills it in and avr-io-ports for what the initialisation section usually does.

The template

                             ; Comments start with semicolons
.include "m324Adef.inc"

    jmp RESET                ; <- vector table
    ; Interrupt handlers go here
    ; (more on this in week 9/10)

RESET:                       ; Starting point   <- RESET handler
    ...                      ; Initialisation code
                             ; e.g. set DDRs

loop:                        ; <- main code
    ...                      ; Do stuff
    jmp loop                 ; Repeat

Three sections, and each is there for a reason:

Section What it is
Vector table jmp RESET, then the interrupt handlers
RESET handler the starting point — initialisation code, e.g. setting the data direction registers
Main code the work, ending in a jump back to its own label

Comments and directives

Comments start with semicolons. Everything from a ; to the end of the line is ignored by the assembler.

.include "m324Adef.inc" is an assembler directive, not an instruction — nothing is generated for it. The contents of the file are included directly in the program, which is what makes DDRA, PORTC, TCNT0 and the rest usable as names instead of I/O register numbers (see avr-io-ports). The leading dot is the giveaway: a line starting . speaks to the assembler, a line starting with a mnemonic speaks to the CPU.

Every line has the same shape, with up to four fields: a label, an operation, its operands and a comment, as in loop: jmp loop ; Repeat. The operation is either an instruction or, with the leading dot, a directive. Two more directives turn up in most programs: .def temp = r16 gives a register a name, and .equ gives a number a name. The fields, and every directive with what it does, are in assembly-process.

Why the vector table comes first

The chip begins executing at program address 0x0000 — the top of the program memory map in memory-models — and the addresses immediately after it are reserved for interrupt vectors, one per interrupt source. So the very first instruction has to jump over them to reach the real start of the program. That is all jmp RESET is doing.

Everything between that jump and the RESET: label is the vector table itself. It stays empty (comments only) in a program that uses no interrupts — but the jmp has to be there from the first program, because without it execution would fall straight into whatever occupied the vector slots. Once a program does use an interrupt, each vector slot it needs holds a jmp to that source’s handler at a fixed address, placed with .org; the table, the handlers and how to enable them are in avr-interrupts.

Labels and jmp

A label is a name for a position in the program:

        jmp RESET
        …
RESET:  …
        …

loop:   …
        …
        jmp loop

The assembler replaces each label with the program-memory address it ended up at, so jmp loop becomes a jump to a real address. Two properties matter in practice:

  • A label is written at the start of the line, ending in a colon; the instruction it names can be on the same line or the next one.
  • Labels let you write code without ever computing an address by hand, which is most of what an assembler buys you over machine code (instruction-set-architecture).

jmp RESET at the top of the template needs the address of a label the assembler has not reached yet. It copes by reading the file twice: the first pass only works out where every label lands, using each line’s size, and the second fills the addresses into the instructions (assembly-process). In the template RESET is the address straight after the vector table, worked out the same way.

jmp itself is unconditional. For jumping only sometimes, the branch instructions below take a label in exactly the same way.

Conditional control flow

A branch instruction takes a label just as jmp does, but jumps only if a status register bit says so — so a decision is always written as two instructions, one that sets the flags and one that reads them:

breq label branch if Z = 1
brne label branch if Z = 0

The usual flag-setter is cp, which is a subtraction whose result is not saved: it computes rd - rr purely to set Z, N, C, V and the rest, so cp r5, r6 followed by breq branches exactly when the two registers were equal. The instruction reference specifies which status register bits are set by which instructions, per instruction rather than by one general rule — so a compare is not always needed, because whatever ran last may already have set Z. avr-instructions tabulates which does what.

Figure 185: Compare-then-branch: the whole of an AVR conditional. cp performs the subtraction and throws the difference away, keeping only what it did to the flags; brne then reads exactly one of them and either loads the label’s address into the program counter or lets execution fall through to the next instruction. The flag names and their order are those of the AVR status register; the outline on Z marks the one flag brne tests.

Figure 185 is worth reading as the reason labels matter. The branch does not encode “go back three instructions” in a form you have to count out by hand; it names a label, and the assembler works out the address — the same service it performs for jmp RESET at the top of the file.

Two consequences for the template above. First, a loop that should sometimes end is still written as a label plus a branch, not as a special construct: the body falls through when the condition fails. Second, nothing may sit between the flag-setter and the branch that disturbs the flag being tested — the status register is a single shared piece of state, and the instruction in between will happily overwrite it.

The two branches above are the equality pair. The other eight — including the signed and unsigned less than pairs that a loop bound usually needs — and the loop idioms built from them are in avr-branches-and-jumps.

When the program calls procedures

The template above has no stack, because nothing in it calls anything. The moment a program uses call or rcall — or push — the stack pointer must be set first, and it goes at the top of RESET:, before any of the other initialisation:

RESET:
    ldi  r16, low(RAMEND)
    out  SPL, r16
    ldi  r16, high(RAMEND)
    out  SPH, r16
    ...                      ; then set DDRs and the rest as before

RAMEND is the last SRAM address, 0x08FF; the stack starts there and grows downward. Why it has to, and what call and ret do with it, is procedures-and-the-stack. A C program gets these four instructions for free from the compiler’s start-up code.

Variables and constants

The template holds only code. Variables and tables of constants go in the other segments (assembly-process), chosen by .dseg and .cseg:

.include "m324Adef.inc"
.def    temp = r16              ; a name for a register

        .dseg                   ; SRAM: space only
count:  .byte 1                 ; one byte, at 0x0100

        .cseg                   ; flash: code and constants
        jmp  RESET              ; vector table
RESET:
        ldi  temp, low(RAMEND)  ; stack pointer, if anything is called
        out  SPL, temp
        ldi  temp, high(RAMEND)
        out  SPH, temp
        ...                     ; initialisation
loop:
        ...                     ; main code
        jmp  loop

digits: .db  63, 6, 91, 79, 102, 109, 125, 7, 127, 111   ; seven-segment patterns, 0 to 9

Three rules come with it:

  • A variable is a label on a .byte in the data segment. It gets an address, 0x0100 for the first one, but no value. The program has to store something there, with sts count, temp for example, before reading it.
  • Constants go in the code segment, out of the path of execution. The CPU runs whatever is in program memory at the PC, so a table in the middle of the code would be executed as if it were instructions. After the main loop’s jmp loop is safe, because execution never gets there. Between jmp RESET and RESET: is safe for the same reason, but only in a program that uses no interrupts, because that is where the interrupt vectors go. digits is ten bytes, an even number, so it fills five words with no pad (assembly-process).
  • A constant is read with lpm, at its byte address, the label times 2, in Z (memory-models).

Why it ends in an infinite loop

loop: … jmp loop is not a placeholder. A microcontroller program has nowhere to return to — there is no operating system underneath it, and the CPU keeps fetching whatever comes next for as long as it has power. So the main body of an AVR program is a loop that never exits, and “do this repeatedly”, which is how nearly every lab task is worded, is the normal shape rather than a special case.

The division of labour that follows: anything that should happen once goes in the RESET handler (setting DDRs, loading constants), and anything that should happen forever goes in the loop (reading inputs, computing, writing outputs).

See also

SPI on the AVR

The Serial Peripheral Interface, and the ATmega324A’s SPI port: the four signals, how two shift registers exchange a byte, one transfer in time, the ways to connect several slaves, the pins, the three registers, the clock rate, code to send and receive, the interrupt, and the USARTs as extra SPI masters. Where SPI sits among serial links, next to the UART and I²C, is in serial-communication. First met in 2026-10-05-more-io. The datasheet covers the SPI on pages 166 to 174.

What SPI is

SPI is a synchronous serial bus with one master and one or more slaves (serial-communication).

  • Synchronous: the master sends a clock, and both ends move a bit on each pulse of it. Nothing about speed has to be agreed beforehand, except that the master must not go faster than the slave can follow.
  • Full duplex: there is a data wire in each direction, and every clock pulse moves one bit each way.
  • The master starts every transfer and makes the clock. A slave only answers.
Signal Driven by Carries
SCK (also written SCLK) master serial clock, one pulse per bit
MOSI master Master Out, Slave In
MISO slave Master In, Slave Out
\(\overline{\text{SS}}\) master Slave Select, active low: a slave takes part only while its \(\overline{\text{SS}}\) is 0

The names say which end drives each wire, so the wiring is MOSI to MOSI and MISO to MISO. It is not crossed over the way a UART’s Tx and Rx are.

The exchange: two shift registers in a ring

Master and slave each have an 8-bit shift register (shift-registers). MOSI joins the master’s MSB end to the slave’s LSB end, and MISO joins the slave’s MSB end to the master’s LSB end. Together they are one 16-bit register bent into a ring, and each SCK pulse rotates it by one place. The hardware view, with the clock generator and the select pins, is drawn in 2026-10-05-more-io.

Figure 186: The exchange as data. Before the transfer the master’s register holds 0x4D, shaded blue, and the slave’s holds 0x73, shaded orange. Each SCK pulse moves every bit one place round the ring: towards the MSB inside each register, and across on MOSI or MISO at the ends. After eight pulses each byte has gone all the way across and the shading has changed sides: the master holds 0x73 and the slave 0x4D. A byte has been sent in each direction at once.

Two consequences follow from the ring:

  • To receive, the master must send. There is no read-only transfer. To collect a byte from a slave, the master sends a dummy byte, often 0x00 or 0xFF, and keeps what comes back.
  • To send is also to receive. Every byte sent brings one back. If it is of no interest, the master reads it and throws it away.

Worked: one exchange, clock by clock

The master’s register holds 0x4D (0100 1101) and the slave’s holds 0x73 (0111 0011), and the bytes go most significant bit first. Each clock, each register’s top bit leaves on its data wire, the other seven move up one place, and the bit arriving from the other end fills the bottom:

After clock MOSI carried MISO carried Master Slave
start 0100 1101 0111 0011
1 0 0 1001 1010 1110 0110
2 1 1 0011 0101 1100 1101
3 0 1 0110 1011 1001 1010
4 0 1 1101 0111 0011 0100
5 1 0 1010 1110 0110 1001
6 1 0 0101 1100 1101 0011
7 0 1 1011 1001 1010 0110
8 1 1 0111 0011 0100 1101

The MOSI column, read down, is 0100 1101, the master’s byte, and the MISO column is 0111 0011, the slave’s. After 8 clocks the master holds 0x73 and the slave 0x4D.

One transfer in time

Figure 187: One SPI transfer in the AVR’s default mode: SCK idles low, both ends sample their incoming data wire on each rising edge of SCK (the dotted lines), and both put out their next bit on each falling edge. The master pulls \(\overline{\text{SS}}\) low to select the slave, and the slave’s first bit appears on MISO at that moment. Eight clock pulses then carry 0x4D from master to slave on MOSI and 0x73 from slave to master on MISO, most significant bit first, with the bit values written under each data wire. Raising \(\overline{\text{SS}}\) ends the transfer. The data wires matter only while \(\overline{\text{SS}}\) is low, so they are drawn only then.

A transfer, from the master’s side:

  1. Pull \(\overline{\text{SS}}\) low. The selected slave wakes up and puts its first bit on MISO.
  2. Write the byte to the data register. The SPI hardware makes eight pulses on SCK. On each rising edge both ends read the data wire coming in; on each falling edge both shift their next bit out.
  3. Wait for the transfer-complete flag, then read the byte that came in.
  4. Send more bytes the same way, or raise \(\overline{\text{SS}}\) to end the transfer.

The AVR’s SPI hardware never moves \(\overline{\text{SS}}\) itself in master mode. Steps 1 and 4 are the program’s job, done with PORTB.

Clock polarity and phase

The figure shows the AVR’s mode after reset. Two bits in the control register change it: CPOL, which level SCK rests at, and CPHA, whether data is read on the first or the second edge of each pulse. Together they number four modes:

Mode CPOL CPHA SCK when idle Data read on
0 0 0 low the rising edge, the first of each pulse
1 0 1 low the falling edge, the second of each pulse
2 1 0 high the falling edge, the first of each pulse
3 1 1 high the rising edge, the second of each pulse

A third setting is the bit order, MSB first or LSB first. A device’s datasheet says which mode and bit order it uses, and the master has to match it. As with a UART’s settings (serial-communication), nothing on the wires says which is in use, and a mismatch gives wrong bytes, not an error.

Several slaves

Both wirings are drawn in 2026-10-05-more-io.

Independent selects. SCK and MOSI go to every slave, and every slave’s MISO joins the one wire back to the master. Each slave has its own select line from the master, and the master pulls one low at a time. A slave whose \(\overline{\text{SS}}\) is high ignores SCK and lets go of MISO (the AVR as a slave makes all its SPI pins inputs), so only the selected slave drives the shared wire. Every slave costs one more master pin.

Daisy chain. One select line goes to all the slaves, and the data passes through them in turn: master MOSI into slave 1’s MOSI, each slave’s MISO into the next one’s MOSI, the last slave’s MISO back to the master’s MISO. The master’s register and the slaves’ registers make one ring, \(8 \times (\text{slaves} + 1)\) bits round. A chainable device acts on the byte it holds when \(\overline{\text{SS}}\) goes back high, so everything has to be in place by then.

Figure 188: A daisy chain of three slaves as one long shift register, 32 bits round. Each row is the chain at one moment, read left to right in the direction the data moves, and the arrow underneath is the last slave’s MISO returning to the master. Shaded bytes are the ones the master has sent. Every 8 clocks move every byte one place along, so the first byte sent, 0xA1, ends up in the farthest slave, and the master receives the slaves’ old bytes, the farthest slave’s first. Between bytes the master reads what has arrived and writes the next byte to send.

Worked: which byte goes first?

To leave 0xA1 in slave 3, 0xB2 in slave 2 and 0xC3 in slave 1, send 0xA1, 0xB2, 0xC3, in that order, with \(\overline{\text{SS}}\) low for all 24 clocks. The byte for the farthest slave goes first, because every later byte pushes it one place further along. The three bytes that come back are the slaves’ previous contents, slave 3’s first.

The pins

The SPI port uses the upper half of port B (avr-io-ports):

Port pin Package pin Signal As master As slave
PB4 5 \(\overline{\text{SS}}\) the program’s to use: make it an output input
PB5 6 MOSI output: the program sets its DDRB bit input
PB6 7 MISO input output: the program sets its DDRB bit
PB7 8 SCK output: the program sets its DDRB bit input

Switching the SPI on forces some pins’ directions and leaves others to DDRB. A pin marked input is made an input by the hardware. A pin that has to be an output, the program has to make an output itself.

The \(\overline{\text{SS}}\) pin in master mode. If PB4 is left as an input and something pulls it low, the AVR takes it that another master is selecting it as a slave. It clears MSTR0, becoming a slave, and sets the transfer-complete flag. A master therefore makes PB4 an output, usually as the select line for its slave, or else guarantees that it stays high. As an output it is an ordinary port pin and the SPI ignores it.

These same pins are the ones a programmer uses to download a program into the AVR, which is worth remembering when a device is attached to them.

The registers

Register Holds
SPCR0 control: on/off, master or slave, bit order, clock mode, clock rate, interrupt enable
SPSR0 status: the transfer-complete and write-collision flags, and the double-speed bit
SPDR0 data: write a byte to send it, read the byte received

The datasheet’s SPI chapter (pages 172 and 173) calls these SPCR, SPSR and SPDR, and its bit names have no 0 either. In C and assembly every name carries the 0: SPCR0, SPE0, MSTR0, SPIF0, and SPR1 becomes SPR10. The I/O register summary still names the registers SPCR and SPSR, but writes the bit names with the 0, except that it labels bit 1 SPR01 where the header has SPR10.

Figure 189: The SPI port’s two control and status registers, with the names used in code. SPCR0 sets the port up: bit 6 turns it on, bit 4 chooses master or slave, bit 5 the bit order, bits 3 and 2 the clock mode, and the bottom two bits the clock rate when it is a master. Bit 7 lets the end of a transfer raise an interrupt. In SPSR0, bit 7 is the flag that says a transfer has finished, bit 6 reports a write to the data register in the middle of a transfer, and bit 0 doubles the master’s clock rate, a third clock-rate bit to go with the two in SPCR0. Every bit is 0 after reset, so the port starts switched off.

SPCR0: the set-up

Bit Name When 1 When 0
7 SPIE0 the end of a transfer raises an interrupt no interrupt
6 SPE0 the SPI port is on off: the pins belong to port B
5 DORD0 LSB first MSB first
4 MSTR0 master slave
3 CPOL0 SCK idles high SCK idles low
2 CPHA0 data read on the second edge of each pulse data read on the first edge
1:0 SPR10, SPR00 the clock rate, with SPI2X0 (below)

SPSR0: what has happened

Bit Name Set when Cleared by
7 SPIF0 a transfer has finished; also when a master’s \(\overline{\text{SS}}\) input is pulled low the interrupt handler running, or reading SPSR0 and then SPDR0
6 WCOL0 SPDR0 was written while a transfer was going on reading SPSR0 and then SPDR0
0 SPI2X0 (a setting) 1 doubles the master’s SCK

Bits 5 to 1 are unused.

SPDR0: the data

Writing SPDR0 starts a transfer when the port is a master: the byte goes into the shift register and the eight clock pulses begin. Reading SPDR0 gives the byte received. The two directions are buffered differently. On the way out there is only the shift register, so a byte written during a transfer is not sent and sets WCOL0 instead. On the way in the finished byte is copied to a buffer, where it waits until the next byte is complete, so it has to be read before then or it is lost.

Choosing the clock rate

In master mode three bits pick the divider:

SPI2X0 SPR10 SPR00 SCK At 8 MHz
0 0 0 \(f_{OSC}/4\) 2 MHz
0 0 1 \(f_{OSC}/16\) 500 kHz
0 1 0 \(f_{OSC}/64\) 125 kHz
0 1 1 \(f_{OSC}/128\) 62.5 kHz
1 0 0 \(f_{OSC}/2\) 4 MHz
1 0 1 \(f_{OSC}/8\) 1 MHz
1 1 0 \(f_{OSC}/32\) 250 kHz
1 1 1 \(f_{OSC}/64\) 125 kHz

SPI2X0 halves the divider chosen by the other two. Eight codes give seven dividers, because 64 appears twice. After reset all three bits are 0, which is divider 4.

In slave mode these bits do nothing, because the slave’s clock comes from the master. A slave samples the incoming SCK with its own clock and is only guaranteed to keep up to \(f_{OSC}/4\), 2 MHz at 8 MHz.

A byte takes 8 SCK periods, which is \(8 \times\) divider CPU cycles: 16 cycles (2 µs) at the fastest, 1024 (128 µs) at the slowest.

Worked: the slowest master clock

Which bits must be 1 to switch the SPI on as a master with the slowest clock, and what is written to SPCR0?

The slowest divider is 128, code SPI2X0 SPR10 SPR00 = 0 1 1. Add SPE0 to switch the port on and MSTR0 to make it a master. Nothing in SPSR0 needs to be 1, since SPI2X0 must stay 0.

SPCR0 = (1<<SPE0) | (1<<MSTR0) | (1<<SPR10) | (1<<SPR00);   /* 0101 0011 = 0x53 */

Bits 6, 4, 1 and 0 make 0100 0000 + 0001 0000 + 0000 0010 + 0000 0001 = 0x53, and SCK is \(8\text{ MHz}/128 = 62.5\) kHz.

Worked: a 1 MHz clock

\(8\text{ MHz}/1\text{ MHz} = 8\), which is code 1 0 1: SPR00 in SPCR0 and SPI2X0 in SPSR0.

SPCR0 = (1<<SPE0) | (1<<MSTR0) | (1<<SPR00);
SPSR0 = (1<<SPI2X0);

Sending and receiving, by polling

A master that sends and receives one byte at a time:

#include <avr/io.h>

#define SS_PIN 4                          /* PB4 used as the slave's select */

void spi_init_master(void) {
    DDRB  |= (1<<SS_PIN) | (1<<5) | (1<<7);   /* SS, MOSI, SCK outputs; MISO stays an input */
    PORTB |= (1<<SS_PIN);                     /* SS high: no slave selected yet             */
    SPCR0  = (1<<SPE0) | (1<<MSTR0) | (1<<SPR00);   /* on, master, f/16 = 500 kHz        */
}

uint8_t spi_exchange(uint8_t out) {
    SPDR0 = out;                          /* writing starts the eight clocks   */
    while (!(SPSR0 & (1<<SPIF0))) {       /* wait for the transfer to finish   */
    }
    return SPDR0;                         /* the byte that came back; reading  */
                                          /* SPSR0 then SPDR0 clears SPIF0     */
}

and a transfer of two bytes, the second one to collect the slave’s reply:

uint8_t reply;

PORTB &= ~(1<<SS_PIN);                    /* select the slave                */
spi_exchange(0x4D);                       /* send; what comes back is ignored */
reply = spi_exchange(0x00);               /* send a dummy byte to read one   */
PORTB |= (1<<SS_PIN);                     /* deselect                        */

The rules it follows:

  • The program moves \(\overline{\text{SS}}\), low before the first byte and high after the last.
  • One byte at a time. Write SPDR0, wait for SPIF0, then write the next. A write during a transfer is lost.
  • To read, send.

At 500 kHz the wait is 16 µs, 128 CPU cycles, against about a millisecond for a UART frame at 9600 baud. Waiting by polling (polling-and-interrupts) is often the sensible choice for SPI.

As a slave, the AVR only makes MISO an output and switches the port on with MSTR0 left at 0:

void spi_init_slave(void) {
    DDRB |= (1<<6);                       /* MISO is the slave's one output */
    SPCR0 = (1<<SPE0);                    /* on, slave                      */
}

A slave can never start anything. It puts the reply it wants to give in SPDR0 ahead of time, and when the master has clocked a byte through, SPIF0 is set and SPDR0 holds what the master sent.

The interrupt

Event Flag (SPSR0) Enable (SPCR0) Handler
transfer complete SPIF0 SPIE0 ISR(SPI_STC_vect)

It is vector 20 in the table (avr-interrupts), and running the handler clears SPIF0. The usual use is a queue of bytes: the handler reads the byte that has just arrived and writes the next one to SPDR0, so a run of bytes goes out without the main program waiting on each. On a slave, the interrupt is how the program finds out that the master has just exchanged a byte with it.

The USARTs as SPI masters

Each USART can also work as an SPI master, by setting its mode bits UMSELn1:0 in UCSRnC to 11 (avr-usart). Its pins then take the SPI roles:

USART SCK Data out (MOSI) Data in (MISO)
USART0 XCK0, PB0 TXD0, PD1 RXD0, PD0
USART1 XCK1, PD4 TXD1, PD3 RXD1, PD2

There is no select pin: the program drives any spare port pin as \(\overline{\text{SS}}\). A USART in this mode can only be a master. With the SPI port as well, the ATmega324A can be the master on three separate SPI buses.

Common mistakes

  • Crossing MOSI and MISO as if they were a UART’s Tx and Rx. MOSI goes to MOSI.
  • Expecting to read without sending. The master gets a byte only by sending one.
  • Leaving PB4 an input in master mode. If it floats or is pulled low, MSTR0 is cleared and the AVR silently becomes a slave.
  • Not setting DDRB for MOSI and SCK on a master, or MISO on a slave. Switching the SPI on does not make those pins outputs.
  • Waiting for the hardware to drive \(\overline{\text{SS}}\). A master has to do it in software.
  • Writing SPDR0 before the last transfer has finished. The byte is not sent and WCOL0 is set.
  • Using the datasheet names SPCR, SPE, SPR1 in code. The header names have a 0: SPCR0, SPE0, SPR10.
  • Mismatched mode or bit order with the slave device: wrong bytes and no error.
  • Clocking an AVR slave faster than \(f_{OSC}/4\).
  • Loading a daisy chain nearest slave first. The first byte sent ends up in the farthest slave.

See also

AVR Timers and Counters

The ATmega324A’s three timer/counter units: what they are, which pins and registers belong to each, how their clock is chosen and prescaled, the modes that decide what the count does when it reaches its top, the output compare actions that let a match drive a pin, and the one formula that turns a wanted event frequency into register values. From 2026-09-14-flow-of-control and 2026-09-17-pulse-width-modulation, with the register-level detail from week8-lab-avr-timers. PWM, the timers’ main use, has its own note: pulse-width-modulation.

Timer, counter

  • A counter is a binary up/down counter clocked on some event.
  • A timer is a counter clocked by a regular clock.

One piece of hardware, two names for what its clock is. Clock it from an external pin and each count is an event; clock it from the system clock and each count is a fixed slice of time, so the count is elapsed time. It is the wide, fast, silicon version of the counters of [counters], and it is separate hardware from the CPU: once configured it counts, compares and drives its pins with no instructions running, which is the whole reason to have it.

Three things a timer/counter is used for, in this course:

Use Clock The event
Timing — do something every 100 ms, toggle an LED, tick a clock system clock ÷ prescaler the count reaching a compare value or wrapping, at a known interval
Counting — how many pulses arrived on a pin edges on the external pin Tn the count reaching a compare value: that many pulses
PWM — an adjustable-width pulse on a pin, in hardware system clock ÷ prescaler the compare match switching the OCnx pin partway through each sweep

The three units

Timer/Counter 0 Timer/Counter 1 Timer/Counter 2
Width 8-bit (0–255) 16-bit (0–65535) 8-bit (0–255)
Output compare pins PB3 = OC0A, PB4 = OC0B PD5 = OC1A, PD4 = OC1B PD7 = OC2A, PD6 = OC2B
External clock pin PB0 = T0 PB1 = T1 none — TOSC1/TOSC2 (PC6/PC7) take a separate crystal instead
Prescaler taps 1, 8, 64, 256, 1024 1, 8, 64, 256, 1024 1, 8, 32, 64, 128, 256, 1024
Modes Normal, CTC, Fast PWM, Phase Correct PWM Normal, CTC, Fast PWM, PC PWM, PFC PWM Normal, CTC, Fast PWM, Phase Correct PWM
Count register TCNT0 TCNT1H:TCNT1L TCNT2
Control registers TCCR0A, TCCR0B TCCR1A, TCCR1B, TCCR1C TCCR2A, TCCR2B
Compare registers OCR0A, OCR0B OCR1AH:OCR1AL, OCR1BH:OCR1BL OCR2A, OCR2B
Interrupt registers TIMSK0, TIFR0 TIMSK1, TIFR1 TIMSK2, TIFR2

Every unit has two compare units, A and B, each with its own register and its own pin. Timer 1 is the one to reach for when 255 is not enough: its 16 bits give periods 256 times longer at the same prescaler, and it is the timer Lab 12 sets up. Timer 2 is the one with a separate clock source, for real-time-clock use. The T/C 3 in the family datasheet’s block diagram is on the ATmega1284, not this chip (avr-architecture).

The pins are shared with GPIO. OC0A is PB3 until timer 0 is told to drive it; configuring a compare output takes the pin away from PORTB and hands it to the timer. The DDR bit must still be set to output, since the timer only decides what the pin shows, not whether it drives.

Figure 190: One timer/counter unit, from clock to pins. The clock select multiplexer feeds the counter either a prescaler tap or an edge on the external pin, or nothing; the counter increments on each pulse of whatever it is given. Two compare registers are each checked against the count every tick, and a match raises that unit’s flag and fires the waveform generator for its pin. Reaching the top of the count raises the overflow flag and, depending on the mode, wraps the count. The flags collect in TIFRn, where a program can poll them or, with the matching bits set in TIMSKn, have them raise an interrupt. Every box is configured through I/O registers and then runs with no CPU involvement.

Registers: data, control, interrupt

A timer is configured the way a port is — through I/O registers (avr-io-ports) — and its registers sort into the same three kinds:

Timer registers Port equivalent
data TCNTn — the current count PIN / PORT read it to see where the count is; write it to preset
control TCCRnA, TCCRnB (TCCR1C) — mode, clock, pin action; OCRnA, OCRnB — the values to match DDR set once, then leave
interrupt TIMSKn — which events raise an interrupt; TIFRn — which events have happened — read the flags by polling, or enable interrupts: avr-interrupts

Where they are

The timer registers are spread across both the in/out range and the extended I/O space that only lds/sts reach (avr-io-ports):

Register I/O address Data-memory address
TCNT0 0x26 0x46
TCNT1L / TCNT1H — 0x84 / 0x85
TCNT2 — 0xB2

In C none of this matters: avr/io.h defines every one of them as a memory-mapped byte (c-preprocessor-and-avr-headers), and TCNT0, OCR1A and TCCR2B are assigned to like variables.

16-bit registers

Timer 1’s count and compare registers are two bytes each, and the hardware guards them with a shared temporary register so that a 16-bit value is read or written atomically: write the high byte first, then the low; read the low byte first, then the high. In assembly:

    ldi  r16, high(4321)
    sts  OCR1BH, r16       ; high byte first — goes into the temp register
    ldi  r16, low(4321)
    sts  OCR1BL, r16       ; low byte — both bytes land together

In C the compiler knows the rule, and OCR1B = 4321; is the whole thing. The H/L names still exist, but OCR1A, OCR1B, TCNT1 and ICR1 are 16-bit variables in the header.

The read rule has a consequence: reading TCNT1H on its own gives a stale value. Reading the low byte is what copies the high byte into the temporary register, and a read of the high byte returns that copy. So for the top half of the count, read the whole of TCNT1 and shift, as in TCNT1 >> 8, which reads the low byte first (below).

Choosing the clock

The count advances once per rising edge of whatever the clock select field CSn2:0 in TCCRnB picks — drawn as a multiplexer in 2026-09-14-flow-of-control:

CSn2 CSn1 CSn0 Timers 0 and 1 Timer 2
0 0 0 no clock — timer stopped no clock
0 0 1 clk / 1 (no prescaling) clk / 1
0 1 0 clk / 8 clk / 8
0 1 1 clk / 64 clk / 32
1 0 0 clk / 256 clk / 64
1 0 1 clk / 1024 clk / 128
1 1 0 external pin Tn, falling edge clk / 256
1 1 1 external pin Tn, rising edge clk / 1024

Two things to read off the table. A timer with CS = 000 does not run, which is both the reset state and the way to stop one. And timer 2’s codes are different — it spends the two external-pin codes on its extra prescaler taps — so a CS value copied from a timer-1 example means something else on timer 2.

The prescaler is a chain of dividers on the system clock (8 MHz on the lab boards), and each tap makes every count last that many system cycles. With an 8-bit timer the full 0-to-255 sweep therefore takes \(256 \cdot N\) cycles:

Prescaler \(N\) Tick Sweep of 256 counts (8 MHz) Sweep of 65536 counts (timer 1)
1 0.125 µs 32 µs 8.2 ms
8 1 µs 256 µs 65.5 ms
64 8 µs 2.05 ms 524 ms
256 32 µs 8.19 ms 2.1 s
1024 128 µs 32.8 ms 8.4 s

Coarse control over the period comes from this table; fine control comes from the compare registers and the mode.

Worked: a slow count from TCNT1 >> 8

With the clock divided by 1024, how quickly does TCNT1 >> 8 go up?

Timer 1 then counts \(8\ \text{MHz} / 1024 = 7812.5\) times a second. Shifting right by 8 drops the bottom eight bits, so what is left goes up by one every \(2^8 = 256\) counts:

\[\frac{7812.5}{256} = 30.5\ \text{Hz}, \quad\text{once every } 32.8\ \text{ms}.\]

TCNT1 >> 8 is the high byte of the count. It runs from 0 to 255 and comes back round to 0 every \(65\,536 / 7812.5 = 8.4\) seconds.

The same reasoning works for any shift. Each bit of a counter changes half as often as the bit below it, so TCNT1 >> k goes up \(7812.5 / 2^k\) times a second: 3906 for a shift of 1, 1953 for 2, and so on down to 30.5 for 8. A single bit is a square wave: (TCNT1 >> 12) & 1 changes every \(2^{12} = 4096\) counts, 0.52 s, which is enough to blink something about once a second without a single interrupt.

Figure 191: Timer 1’s count as a set of slower counters. With the clock divided by 1024 the whole of TCNT1 goes up 7812.5 times a second. Each bit changes half as often as the one to its right, so bit 8 changes once every 256 counts, and the top byte, TCNT1 >> 8, is a counter of its own that goes up 30.5 times a second and wraps every 8.4 s. Bit 12, shaded, changes every 0.52 s on its own.

In code, the timer only needs its prescaler, and it runs freely in normal mode:

TCCR1A = 0;
TCCR1B = (1<<CS12) | (1<<CS10);              /* normal mode, clock / 1024 */

uint8_t start = TCNT1 >> 8;
while ((uint8_t)((TCNT1 >> 8) - start) < 61) { }   /* 61 x 32.8 ms = 2.0 s */

The subtraction is done in 8 bits on purpose. When the count wraps from 255 to 0, now - start still comes out as the number of steps in between, so long as fewer than 256 have passed. week10-lab-adc-and-spi paces all its programs this way.

Modes: what happens at TOP

The waveform generation mode bits — WGM02:0 for the 8-bit timers, WGM13:0 for timer 1, split across TCCRnA and TCCRnB — decide what the count does when it reaches its TOP, and what TOP is:

Mode TOP At TOP Timer 0 WGM02:0 Timer 1 WGM13:0
Normal 0xFF / 0xFFFF wrap to 0, set TOVn 000 (0) 0000 (0)
CTC — clear timer on compare match OCRnA clear to 0, set OCFnA 010 (2) 0100 (4)
Fast PWM, fixed top 0xFF wrap to 0 011 (3) 0101–0111 (8-, 9-, 10-bit)
Fast PWM, top in a register OCRnA wrap to 0 111 (7) 1111 (15; 1110 uses ICR1)
Phase correct PWM 0xFF or OCRnA count back down 001 (1), 101 (5) 0001–0011, 1011

Figure 192: The three modes this course uses, as the count against time. In normal mode the counter runs to its full range and wraps; a compare value is just a marker it passes on the way, and the period is fixed at \(2^{8}\) or \(2^{16}\) ticks. In CTC mode reaching OCRnA clears the counter, so the compare value is the period and can be set to anything — the mode for producing an event at a chosen rate. In fast PWM the counter runs as in normal mode (or, in the register-top variant, as in CTC) while the compare match switches a pin partway through each sweep: the period sets the frequency and the compare value sets the pulse width. The same counter and the same compare registers produce all three; the mode bits only change what the top of the count means.

Normal is the mode after reset and the mode for a free-running count: read TCNTn to see how much time has passed, or let it overflow and take the overflow as the tick. CTC is the mode for an event every \(X\) ticks: the period is OCRnA + 1 exactly, with no wasted counts, and the count never exceeds the compare value. Both PWM modes are in pulse-width-modulation.

Output compare: what a match does to the pin

Each compare unit has two compare output mode bits, COMnx1:0 in TCCRnA, that decide what happens to the OCnx pin when TCNTn equals OCRnx. In the non-PWM modes (Normal, CTC):

COMnx1 COMnx0 On compare match
0 0 normal port operation — the pin belongs to the port, timer disconnected
0 1 toggle OCnx
1 0 clear OCnx — set the output low
1 1 set OCnx — set the output high

Toggle is the useful one for a square wave: a CTC count that toggles the pin on every match produces a waveform whose frequency is half the match frequency, since it takes two matches for one full cycle. In the PWM modes the same bits select non-inverting (10) or inverting (11) output, and 01 becomes toggle OCnA on match only in the register-top mode — see pulse-width-modulation.

Figure 193: The two control registers of timer/counter 0, bit by bit, in the datasheet’s three-row form. The compare output mode fields sit at the top of TCCR0A, one two-bit field per compare unit; the three waveform generation mode bits are split, two at the bottom of TCCR0A and one in the middle of TCCR0B; the clock select field is the bottom three bits of TCCR0B. The two force-output-compare bits are for tests and are left alone. Every bit resets to 0, which decodes as normal mode, pins disconnected, timer stopped — so a timer does nothing until a program writes both registers. Timer 2’s registers have the same layout; timer 1 spreads the same fields over three registers with a fourth WGM bit.

Setting them from C uses the bit names from the header as shift counts, the idiom of bit-masking: TCCR1B = (1<<WGM12) | (1<<CS11) | (1<<CS10); selects CTC mode with clock ÷ 64 on timer 1, and TCCR0A = (1<<COM0A0); makes OC0A toggle on match. Write the whole register rather than |= when setting a timer up, so that nothing left over from before survives.

The master formula

Every timing question reduces to one relation between the clock, the prescaler and the top of the count:

\[f_{event} = \frac{f_{clk\_I/O}}{N \cdot (TOP + 1)}\]

  • \(f_{clk\_I/O}\) is the device clock — 8 MHz on the ATmega324A boards.
  • \(N\) is the prescaler: 1, 8, 64, 256 or 1024.
  • \(TOP\) is the highest value the count reaches before it restarts: 255 or 65535 in normal mode and the fixed PWM modes, the value in OCRnA in CTC mode and the register-top PWM modes. The \(+1\) is because the count from 0 to \(TOP\) takes \(TOP + 1\) ticks.
  • \(f_{event}\) is how often the count restarts — which is how often whatever is tied to the restart happens.

What the event is depends on what is hung off the timer:

Tied to the restart \(f_{event}\) is Note
a pin set to toggle on match the toggle rate the resulting square wave has frequency \(f_{event}/2\) — one cycle needs a rise and a fall
a PWM output the pulse rate one falling edge per period in non-inverting mode, one rising edge in inverting
an interrupt how often the handler runs avr-interrupts

Worked example. Toggle a pin 8 times a second (a 4 Hz square wave) from timer 1: \(f_{event} = 8\), so \(N \cdot (TOP + 1) = 8\,000\,000 / 8 = 1\,000\,000\):

\(N\) \(TOP + 1\) \(TOP\) Usable?
1 1 000 000 999 999 no — exceeds 65535
8 125 000 124 999 no — exceeds 65535
64 15 625 15 624 yes — integer and fits
256 3 906.25 — no — not an integer
1024 976.5625 — no — not an integer

So OCR1A = 15624 in CTC mode with CS12:0 = 011. The recipe is always the same: fix \(f_{event}\), try each \(N\), keep the one that gives an integer \(TOP\) that fits the timer’s width; if none does exactly, take the nearest and accept the error. Lab 12 works this example in full (week8-lab-avr-timers).

Reading the flags

A program finds out that a match or overflow happened either by polling TIFRn, below, or by enabling the matching bit in TIMSKn so that the event raises an interrupt (avr-interrupts). When an interrupt is taken, the hardware clears the flag itself; a polling program must clear it. Two things about those flags are unlike anything on a port:

  • A flag is cleared by writing a 1 to it, not a 0: TIFR1 = (1<<OCF1A); clears the compare-A flag and leaves the others alone (writing 0 to a bit does nothing). It is the one place where |= is a mistake, since it would clear every flag that happened to be set.
  • The flag is set by the hardware whether or not the pin is connected or an interrupt is enabled, so a CTC timer with COM = 00 still raises OCFnA every period — a free periodic tick for a program that just needs to wait.
/* wait one period of a running CTC timer 1 */
while (!(TIFR1 & (1<<OCF1A))) { }   /* spin until the flag is set */
TIFR1 = (1<<OCF1A);                  /* clear it for next time */

See also

The AVR USART

The ATmega324A’s serial port: the pins, the five registers a program uses, how to set the baud rate, how to send and receive a byte, and the three interrupts. What a UART frame is, and what baud rate and parity mean, are in serial-communication. First met in 2026-09-24-serial-io. The datasheet covers the USART on pages 175 to 201.

What it is

A USART is a Universal Synchronous and Asynchronous Receiver/Transmitter. The course uses it in its asynchronous mode, as a UART: frames with start and stop bits, no clock wire.

The ATmega324A has two, USART0 and USART1. USART0’s pins are on port D:

Pin Name Direction
PD0 RXD0 receive: data coming in
PD1 TXD0 transmit: data going out

Turning the receiver or transmitter on takes its pin away from the port, in the same way a timer takes over its output-compare pin (avr-timers-and-counters).

The registers

Register Holds
UDR0 the data: write a byte to send it, read to collect a received byte
UCSR0A status flags, and two mode bits
UCSR0B interrupt enables, receiver and transmitter enables
UCSR0C the frame format
UBRR0 (UBRR0H, UBRR0L) the baud rate

The 0 in each name is the USART number. The datasheet writes the names with an n in its place, as in UDRn.

The data register

UDR0 is two registers at one address. A write goes to the transmit buffer. A read comes from the receive buffer. So

UDR0 = 'A';        /* send the letter A            */
c = UDR0;          /* collect whatever has arrived */

and reading UDR0 never returns the value that was written to it.

Behind each buffer is a shift register (shift-registers). A byte written to UDR0 waits there until the transmit shift register is free, is copied across, and is shifted out of TXD0 bit by bit, with the start bit, any parity bit and the stop bits added. On the way in, bits from RXD0 are shifted into the receive shift register, and the finished byte is copied to the receive buffer.

That makes the transmitter two bytes deep: one byte going out and one waiting behind it. It is why there are two separate “finished” conditions, below.

Control and status registers

Figure 194: The three control and status registers of USART0, with their bits grouped by what they do. The top three bits of UCSR0A are the flags for the three serial events, and the top three bits of UCSR0B, directly beneath, are the interrupt enables for the same three events in the same order. UCSR0B also switches the receiver and transmitter on. UCSR0C sets the frame format. The number of data bits is the one setting split across two registers: UCSZ02 is in UCSR0B and UCSZ01:00 are in UCSR0C.

UCSR0A: what has happened

Bit Name Set when Cleared by
7 RXC0 receive complete: a byte has arrived and has not been read reading UDR0
6 TXC0 transmit complete: a frame has been sent and nothing is waiting its interrupt running, or writing a 1 to it
5 UDRE0 data register empty: UDR0 can take another byte writing UDR0
4 FE0 frame error: the stop bit of the received frame was 0 the next read of UDR0
3 DOR0 data overrun: a byte arrived with no room left for it and was lost the next read of UDR0
2 UPE0 parity error in the received frame the next read of UDR0
1 U2X0 (a setting) 1 doubles the speed: 8 samples per bit, not 16
0 MPCM0 (a setting) multi-processor mode, not used here

After reset UDRE0 is 1, because the transmit buffer starts empty, and every other bit is 0. The three error flags describe the byte currently waiting in UDR0, so they must be read before UDR0.

UCSR0B: what is switched on

Bit Name When 1
7 RXCIE0 the receive-complete flag raises an interrupt
6 TXCIE0 the transmit-complete flag raises an interrupt
5 UDRIE0 the data-register-empty flag raises an interrupt
4 RXEN0 the receiver is on, and PD0 belongs to it
3 TXEN0 the transmitter is on, and PD1 belongs to it
2 UCSZ02 top bit of the data-bits setting (1 only for 9 data bits)
1 RXB80 the ninth data bit of a received 9-bit frame
0 TXB80 the ninth data bit to send in a 9-bit frame

All 0 after reset: the USART does nothing until RXEN0 or TXEN0 is set.

UCSR0C: the frame format

Bits Name Setting
7:6 UMSEL01:00 mode. 00 asynchronous, the one used here
5:4 UPM01:00 parity. 00 none, 10 even, 11 odd
3 USBS0 stop bits. 0 one, 1 two
2:1 UCSZ01:00 data bits, with UCSZ02: 000 5, 001 6, 010 7, 011 8, 111 9
0 UCPOL0 clock polarity, synchronous mode only

After reset this register holds UCSZ01:00 = 11 and 0 elsewhere, which is 8 data bits, no parity, 1 stop bit. A program that wants 8N1 does not need to write UCSR0C at all.

Setting the baud rate

\[UBRR0 = \frac{f_{OSC}}{16 \cdot BAUD} - 1\]

\(f_{OSC}\) is the clock, 8 MHz. This is the formula for asynchronous normal mode, the one the course uses, in which the receiver takes 16 samples per bit, and that is where the 16 comes from. The \(-1\) is there because the baud-rate generator counts from UBRR0 down to 0, which is \(UBRR0 + 1\) clock cycles per sample. UBRR0 is 12 bits wide, so 0 to 4095.

The result is rarely a whole number. Round it to the nearest, then work out what rate that really gives, \(f_{OSC} / (16 \cdot (UBRR0 + 1))\), and how far off it is.

Baud rate \(\dfrac{8\,000\,000}{16 \cdot BAUD} - 1\) UBRR0 Actual rate Error
2400 207.3 207 2404 +0.2 %
4800 103.2 103 4808 +0.2 %
9600 51.1 51 9615 +0.2 %
14400 33.7 34 14286 −0.8 %
19200 25.0 25 19231 +0.2 %
28800 16.4 16 29412 +2.1 %
38400 12.0 12 38462 +0.2 %
57600 7.7 8 55556 −3.5 %
115200 3.3 3 125000 +8.5 %

The receiver tolerates an error of a few percent (serial-communication), so the rates up to 38400 are all within about 2 % at 8 MHz and work, with 28800 the closest to the limit. 57600 is marginal and 115200 does not work. The faster the rate, the fewer clock cycles there are per bit and the coarser the choice of rates becomes. The datasheet has the same table on pages 198 to 201.

In C the register is written in one assignment and the compiler handles the two bytes:

UBRR0 = 51;        /* 9600 baud at 8 MHz */

Sending and receiving, by polling

The smallest complete program: 9600 baud, 8N1, echo every character back.

#include <avr/io.h>

int main(void) {
    uint8_t c;

    UBRR0  = 51;                          /* 9600 baud at 8 MHz              */
    UCSR0B = (1<<RXEN0) | (1<<TXEN0);     /* receiver and transmitter on     */
                                          /* UCSR0C left at reset: 8N1       */
    while (1) {
        while (!(UCSR0A & (1<<RXC0))) {   /* wait for a byte to arrive       */
        }
        c = UDR0;                         /* collect it (this clears RXC0)   */

        while (!(UCSR0A & (1<<UDRE0))) {  /* wait for room in the data reg.  */
        }
        UDR0 = c;                         /* send it back                    */
    }
}

The two rules it follows:

  • Before reading UDR0, check RXC0. If nothing has arrived there is nothing to read.
  • Before writing UDR0, check UDRE0. A write while the previous byte is still waiting is ignored, so the new byte is never sent.

Both loops are polling (polling-and-interrupts): the processor does nothing else while it waits. At 9600 baud a frame takes about a millisecond to go out, more than 8000 clock cycles.

The three interrupts

Event Flag (UCSR0A) Enable (UCSR0B) Handler
receive complete RXC0 RXCIE0 ISR(USART0_RX_vect)
data register empty UDRE0 UDRIE0 ISR(USART0_UDRE_vect)
transmit complete TXC0 TXCIE0 ISR(USART0_TX_vect)

They are vectors 21, 22 and 23, in that order, so receive has the highest priority of the three (avr-interrupts).

Data register empty or transmit complete? They mark different moments, because the transmitter holds two bytes.

Figure 195: Sending two bytes, A then B, one straight after the other. A moves from the data register into the shift register as soon as it is written, so UDRE0 drops only for an instant and B can be written while A is still on the wire. B then waits in the data register, UDRE0 staying at 0, until A’s stop bit has gone, when it moves across and UDRE0 returns to 1. TXC0 is set only at the very end: the last frame has left and no byte is waiting behind it.

  • Use data register empty to keep data flowing: each time it fires, hand over the next byte.
  • Use transmit complete when the program needs to know the line has gone quiet, for example before switching the transmitter off.

Receiving by interrupt. The handler runs once per byte, and reading UDR0 is what clears the flag:

#include <avr/io.h>
#include <avr/interrupt.h>

ISR(USART0_RX_vect) {
    uint8_t c = UDR0;                     /* reading clears RXC0             */
    UDR0 = c;                             /* echo (assumes room, see below)  */
}

int main(void) {
    UBRR0  = 51;
    UCSR0B = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0);
    sei();
    while (1) {
        /* free to do anything else */
    }
}

A handler that does not read UDR0 leaves RXC0 set, and it is called again the moment it returns, for ever. The echo here is safe because bytes cannot arrive faster than they can be sent back at the same baud rate.

UDRIE0 needs care. The data register is empty most of the time, so its flag is nearly always set. Enabling the interrupt with nothing to send calls the handler continuously. The pattern is to enable UDRIE0 when there is data queued and have the handler disable it again when the queue runs out.

Common mistakes

  • Reading UDR0 to see what was written. Reads and writes go to different registers.
  • Forgetting RXEN0 or TXEN0. The baud rate and format can be perfect and nothing happens.
  • Forgetting the \(-1\) in the baud-rate formula, giving 52 for 9600 instead of 51.
  • Writing UDR0 without checking UDRE0, which loses bytes when sending more than one.
  • Reading UDR0 before the error flags. The flags belong to the byte being read and are gone afterwards.
  • A receive handler that does not read UDR0.
  • Leaving UDRIE0 enabled with nothing to send.
  • Mismatched settings at the two ends. The symptom is garbled characters, not silence (serial-communication).

See also

Binary Conversion Drill

Convert between different number representations. All binary numbers are eight bits.

On the HTML site, fill in the blank with your answer (as a quoted string, e.g. "1A"), then click Run Code on the exercise to check. Reload the page for a new random question. In the PDF, the reference implementation is shown instead (interactive exercises need a browser).

The two short reference sections below are the minimum needed to attempt the drills without looking anything up; for the full treatment see binary-number-representations, and for the lab on these conversions, week1-lab-number-representations. Fractions, which these drills leave out, are in fixed-point-numbers and floating-point-numbers.

Doing a base conversion: one number, all four bases

The first drill picks two of decimal, hexadecimal, octal and unsigned binary at random and asks you to convert between them. Which pair comes up decides whether the job is regrouping or arithmetic:

  • A hexadecimal digit stands for sixteen values, and so do 4 bits (\(2^4 = 16\)). An octal digit stands for eight values, and so do 3 bits. Both therefore convert to binary digit by digit, with no arithmetic at all.
  • A base-10 digit stands for ten values, and so do \(3.321928\ldots\) bits — not a whole number. Decimal never lines up with a group of bits, so every decimal conversion costs real arithmetic: repeated division by 2 going in, a sum of powers of two coming out.

Figure 196: The same value, 205, written in all four bases the first drill uses, with the two groupings drawn on the one row of bits. The hexadecimal nibbles and the octal triples are cut from the same eight bits; the octal grouping needs a padding zero on the left, by the rule that 123 = 0123 but 456 is not 4560.

Two things to carry into the drill:

  • Group from the right, and pad the leftmost group with zeroes. If the bit count is not a multiple of 3 or 4, the short group is the leading one. \(123 = 0123\), but \(456 \neq 4560\).
  • Hex to octal has no shortcut. Three and four bits share no smaller common grouping, so expand the hex digits to bits and regroup them in threes. For example, 0xC55E7201 becomes 32 bits, pads to 33, and regroups as \(30527471001_8\).

Doing a signed conversion: four recipes on the same number

The second drill converts between decimal and the four signed formats. Going from decimal to bits, each format has its own recipe, and only one of them is really a negation at all.

Figure 197: Plus and minus 47 carried through all four formats, arranged so the recipes can be compared on one number. Orange marks the bit a recipe actually changes; blue marks bits that are recomputed wholesale. The last row is the trap: excess-128 biases positive values too, so it is the one format that does not share the positive patterns with the others.

As a table, for looking up mid-drill:

Format Encode a negative by Range, 8-bit
Signed magnitude inverting the sign bit alone \(-127\) to \(+127\)
Ones’ complement inverting all the bits \(-127\) to \(+127\)
Two’s complement inverting all the bits and adding 1 \(-128\) to \(+127\)
Excess-128 storing value \(+128\) as plain unsigned \(-128\) to \(+127\)

Signed magnitude and ones’ complement each spend two of their 256 patterns on zero (00000000 and 10000000; 00000000 and 11111111), which is exactly the one value of range they give up compared with two’s complement.

Number base conversion

A random question is generated once per page load using an ojs cell, then passed into the Python exercise cells below via the input cell option – this keeps the question stable across repeated “Run Code” clicks (setup blocks re-run on every evaluation, so randomising there would change the question out from under the learner).

Signed number format conversion

Reading one pattern under one format

“What is 10010010 converted to decimal?” has no answer until someone names the format. This drill is that question, generated: it hands you eight bits and one format, and asks what value they hold. Answer with a plain integer (e.g. -110), not a string.

Binary Number Representations

Bits, bytes, and words

  • Bit = binary digit (0 or 1).
  • Nibble = 4 bits. It is the unit that makes hexadecimal convenient (one hex digit = one nibble).
  • Byte = 8 bits, e.g. 01010111.
  • Modern computers deal with words, usually a power-of-2 number of bytes: 1, 2, 4, or 8 bytes = 8, 16, 32, 64 bits. The AVR used in this course is at the small end — an 8-bit (1-byte) word; modern CPUs sit at the other end, 32- or 64-bit.

Representing whole (unsigned) numbers

Each bit position has a value — a power of 2, increasing from right (least significant) to left (most significant). Binary → decimal: add the values of each position where the bit is 1.

Figure 198: Place values for an unsigned binary number, and a worked conversion. Position \(i\) is worth \(2^i\), so reading a binary number is just adding the place values of the positions holding a 1: \(10010001_2 = 128 + 16 + 1 = 145\).

Most and least significant bits

Figure 199: The two ends of a word get names, because almost every later convention (shifting, sign bits, bit numbering in AVR registers) is stated in terms of them. For an \(n\)-bit unsigned word the MSB is worth \(2^{n-1}\) — here \(2^7 = 128\) — and the LSB is always worth \(2^0 = 1\).

Converting decimal to binary

Two equivalent methods, both worked on the same number, 53.

Method 1 — sum of powers of 2. Rewrite \(n\) as a sum of powers of 2, by repeatedly subtracting the largest power of 2 not greater than \(n\) (\(53 - 32 = 21\), \(21 - 16 = 5\), \(5 - 4 = 1\), \(1 - 1 = 0\)). Then assemble the binary number from 1’s in the bit positions corresponding to those powers of 2, and 0’s everywhere else.

Figure 200: Method 1 on \(53\). Each power of two in the decomposition names one bit position — \(2^5\) is position 5, \(2^4\) is position 4, and so on — and every position with no term in the sum gets a 0. Reading the row off left to right gives \(00110101_2\).

Method 2 — repeated division. Build the bits up from the right (least significant): divide \(n\) by 2, the remainder (0 or 1) is the next bit, then repeat with \(n\) = the quotient. Stop when the quotient reaches 0, and read the remainders upwards.

Figure 201: Method 2 on \(53\). The remainders come out LSB-first, which is why the answer has to be read back up the column: \(110101_2\), or \(00110101_2\) padded to a byte. The same procedure with a divisor of 16 or 8 converts to hexadecimal or octal instead.

Number range (unsigned)

  • Smallest representable value: all 0’s → 0.
  • Largest representable value: all 1’s → for an \(n\)-bit word, \(2^n - 1\) (e.g. 255 for 8 bits).

The \(-1\) is the part worth understanding: an \(n\)-bit word has \(2^n\) distinct patterns, but one of them is spent on zero.

Figure 202: Why the largest unsigned value is \(2^n-1\) and not \(2^n\). Counting up from all-zeros steps through every pattern in turn — each extra bit doubles how many there are, so 8 bits give \(2^8 = 256\) patterns — and because the count starts at 0, the last one is 255.

Other radices

Radix = number system base. A radix-\(k\) number system has \(k\) distinct symbols for digits \(0\) to \(k-1\), and the value of each digit (from the right) is \(k^0, k^1, k^2, \dots\) — so a radix-\(k\) number \(d_{m}\dots d_1 d_0\) is worth \(\sum_i d_i k^i\). E.g. \(1\mathrm{A}_{16} = 1 \cdot 16^1 + 10 \cdot 16^0 = 16 + 10 = 26\).

  • Octal (radix-8): symbols 0–7. One octal digit corresponds to exactly 3 bits.
  • Hexadecimal (radix-16): symbols 0–9, A–F. One hex digit corresponds to exactly 4 bits — very convenient for grouping binary.
Dec 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Oct 0 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 20 21
Hex 0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11

Converting binary ↔︎ hex/octal by grouping

Because \(16 = 2^4\) and \(8 = 2^3\), no arithmetic is needed: group the bits from the right — four at a time for hex, three at a time for octal — and translate each group with the table above. Pad the leftmost group with leading zeros.

Figure 203: One bit pattern read two ways. Grouping \(00011010_2\) into nibbles from the right gives \(1\) and \(\mathrm{A}\), i.e. \(1\mathrm{A}_{16}\); grouping the same bits in threes gives \(0\), \(3\) and \(2\), i.e. \(32_{8}\). The grouping must start at the right — starting at the left gives the wrong answer whenever the width is not a multiple of 3 or 4.

The same trick read backwards is why hex is used for bit patterns at all: a full byte of 1’s, 1111 1111, is F F = \(\mathtt{0xFF}\) = 255, and any byte can be written as two hex digits.

To convert decimal → any radix, use Method 2 with that radix as the divisor: \(26 \div 16\) gives quotient 1 remainder 10 (= A), so \(26_{10} = 1\mathrm{A}_{16}\); \(26 \div 8\) gives quotient 3 remainder 2, so \(26_{10} = 32_8\). See 2026-07-27-course-intro-bits-bytes-binary for that worked exercise.

Radix notation conventions

Since a bare number like 101 or 747 is ambiguous, a radix indicator is needed. A subscript works generically (e.g. \(101_2\), \(101_{16}\)); in code/assembly, conventions vary. Bolded rows are the ones this course mostly uses:

Radix Convention Example Where used
any subscript \(101_2\), \(101_{16}\) generic/mathematical
Hex leading 0x 0x101 C, Atmel AVR
Hex trailing h 101h some assembly languages
Hex leading $ $747 Atmel AVR assembly
Octal leading 0 0101 C, Atmel AVR
Octal trailing q 101q some assembly languages
Octal leading @ @747 some assembly languages
Binary leading 0b 0b101 Atmel AVR assembly, some C
Binary trailing b 101b some assembly languages
Binary leading % %101 some assembly languages

The octal convention is the trap: in C, a leading 0 silently changes the radix, so 0101 is \(65_{10}\), not \(101_{10}\).

Representing signed numbers

Computers don’t store \(+\) and \(-\) signs; the sign has to be encoded in the bits themselves. Four formats have been used, and all four — plus unsigned — represent positive numbers identically. Only the negatives differ.

Signed magnitude

The leftmost bit is a sign bit (0 positive, 1 negative) and contributes nothing to the magnitude. Negate by inverting the sign bit alone.

Ones’ complement

The sign bit now also carries weight: its position value is \(-(2^{N-1}-1)\). Negate by inverting all the bits.

Two’s complement

The sign bit’s position value is \(-2^{N-1}\). Negate by inverting all the bits and adding 1. This is the one actually used in practice.

Compare the position values, 8-bit:

bit 7 6 5 4 3 2 1 0
Signed magnitude sign 64 32 16 8 4 2 1
Ones’ complement \(-127\) 64 32 16 8 4 2 1
Two’s complement \(-128\) 64 32 16 8 4 2 1

Excess-\(2^{N-1}\)

For 8 bits, “excess 128”: the value stored is the true value plus 128. So \(-3\) is stored as \(125\) and \(3\) as \(131\).

It is exactly two’s complement with the sign bit reversed — a 0 in the MSB means bit value \(-128\), a 1 means 0. Its practical use is that comparing two signed numbers becomes simple in hardware. The exponent of an IEEE floating-point number is stored in excess notation for exactly that reason, with a bias one smaller: excess-127 for 8 bits (floating-point-numbers).

Ranges

Format 8-bit \(n\)-bit
Unsigned \(0\) to \(255\) \(0\) to \(2^n - 1\)
Signed magnitude \(-127\) to \(127\) \(-(2^{n-1}-1)\) to \(2^{n-1}-1\)
Ones’ complement \(-127\) to \(127\) \(-(2^{n-1}-1)\) to \(2^{n-1}-1\)
Two’s complement \(-128\) to \(127\) \(-2^{n-1}\) to \(2^{n-1}-1\)
Excess-\(2^{n-1}\) \(-128\) to \(127\) \(-2^{n-1}\) to \(2^{n-1}-1\)

Worked example — \(\pm 47\) in 8 bits

\(+47 = \texttt{00101111}\) in every format.

Format \(-47\) How
Signed magnitude 10101111 flip the sign bit
Ones’ complement 11010000 invert all bits
Two’s complement 11010001 invert all bits, add 1
Excess-128 01010001 \(-47 + 128 = 81\)

And in 4 bits, \(-3\) is 1100 in ones’ complement and 1101 in two’s complement.

Why “complement”?

A thing and its complement together make a whole — an angle and its complement make a right angle, a set and its complement a universal set.

  • Ones’ complement: a number plus its negative gives a string of ones (11111111 in 8 bits).
  • Two’s complement: a number plus its negative gives a power of two, with overflow (1 00000000). It would more accurately be called power-of-two’s complement.

Base 10 has the same pair — nines’ and ten’s complement — used on early mechanical adding machines to do subtraction.

Why two’s complement wins

Two representations of zero, which wastes a bit pattern that could have extended the range:

  • Signed magnitude: 00000000 and 10000000
  • Ones’ complement: 00000000 and 11111111

Asymmetric range: two’s complement and excess-\(2^{n-1}\) (one more negative than positive).

Arithmetic: signed-magnitude addition requires taking cases; ones’ complement addition requires an extra addition step (the end-around carry); sign extension and comparison are non-trivial in both. Two’s complement has a single zero and its addition is just binary addition — no special cases.

Format matters

The same eight bits mean different things under different formats. 10010010 reads as:

Read as Value
Unsigned 146
Two’s complement \(-110\)
Ones’ complement \(-109\)
Signed magnitude \(-18\)
Excess-128 18

Or 01010101: 85 unsigned, \(-43\) in excess-128, 'U' in ASCII, or 10.625 as fixed point with 5 bits before the binary point and 3 after.

The format is not encoded in the data. It has to be known separately — by a human, by a program, or by the hardware. See week1-lab-number-representations for the full 4-bit table across all five formats, and 2026-08-04-binary-arithmetic for what happens when you add these.

Fractions: fixed and floating point

Everything above is whole numbers. Place values carry on past a binary point as \(\tfrac12, \tfrac14, \tfrac18, \dots\), and there are two ways to use them.

  • Fixed point: agree where the point sits, as in the 5.3 reading of 01010101 above, and read the bits as before. Ordinary integer hardware does the arithmetic, but the format fixes the range and the precision once and for all. See fixed-point-numbers.
  • Floating point: store the digits and the position of the point separately, as binary scientific notation: a sign, a biased exponent and a mantissa. This is IEEE 754, the float and double of C. See floating-point-numbers.

Bit Masking

Using a bitwise operation against a constant mask to touch only the bits you care about, leaving the rest alone. See boolean-algebra for the underlying laws and avr-instructions for the instructions used here. The same masks, written from the bit names in the AVR’s header files, are how every I/O register is set up in C: see set, clear and toggle and writing register bits by name.

Sometimes you are interested in only a few bits of a register. A bitwise AND can mask out the bits that are not of interest — and more generally, masking can selectively set, clear, toggle or extract bits.

The reason any of this is possible is that a bitwise instruction is not one eight-bit operation. It is eight independent one-bit operations running in parallel, and the two operands’ bit \(i\) decide result bit \(i\) with no reference to any other column.

Figure 204: Why a mask works, one column at a time. Two rows of bits, an arrow down out of each column into a result row that overwrites the destination: here and r8, r16 with the mask 0x07, extracting the low three bits. The eight columns never interact — one mask bit decides one result bit, a 1 passing the value’s bit through and a 0 forcing it to zero — and all eight happen at once in a single instruction. Choosing a mask is therefore nothing more than deciding, position by position, which bits to keep.

Read Figure 204 column by column and the technique stops needing to be memorised: since the columns are independent, choosing a mask is just choosing, for each of the eight positions separately, whether that position gets passed through or forced.

The three identities that make it work

Each of AND, OR and XOR has a value that passes a bit through unchanged and a value that forces it. That pairing is the whole technique.

\(X \cdot 0\) \(X \cdot 1\) \(X \cdot X\)
AND \(= 0\) \(= X\) \(= X\)
\(X + 0\) \(X + 1\) \(X + X\)
OR \(= X\) \(= 1\) \(= X\)
\(X \oplus 0\) \(X \oplus 1\) \(X \oplus X\)
XOR \(= X\) \(= \overline{X}\) \(= 0\)

Reading off the pass-through and force columns gives the operation to reach for:

To do this to the selected bits Use Mask bit = 1 on Mask bit = 0 on
Clear them to 0 AND the bits to keep — \(X \cdot 1 = X\) the bits to clear — \(X \cdot 0 = 0\)
Set them to 1 OR the bits to set — \(X + 1 = 1\) everything else — \(X + 0 = X\)
Toggle them EOR the bits to flip — \(X \oplus 1 = \overline{X}\) everything else — \(X \oplus 0 = X\)
Extract them (others zeroed) AND the bits to keep — \(X \cdot 1 = X\) the bits to discard — \(X \cdot 0 = 0\)

Note the asymmetry: AND’s mask is 1 on the bits you keep, whereas OR’s and XOR’s masks are 1 on the bits you act on. Getting that backwards is the usual bug — with AND you write the mask for what survives, with the other two for what changes.

\(X \oplus X = 0\) is the other one worth remembering: XORing a register with itself is the cheapest way to zero it.

In AVR assembly

The masks are ordinary constants, so the bitwise instructions of avr-instructions do the work. On AVR the immediate forms (andi, ori) only reach r16–r31; for a low register, load the mask into a high register and use the two-register form.

Extract the least significant three bits of r7 into r8, other bits of r8 zero.

    mov  r8, r7          ; copy the source
    ldi  r16, 0x07       ; mask 0000 0111 — keep the bottom three
    and  r8, r16         ; everything else forced to 0

Toggle the most significant four bits of r9, other bits unchanged.

    ldi  r16, 0xF0       ; 1111 0000 — flip the top four
    eor  r9, r16         ; bottom four XOR 0, so unchanged

Clear the least significant four bits of r10, other bits unchanged.

    ldi  r16, 0xF0       ; 1 on the bits to KEEP
    and  r10, r16        ; bottom four AND 0 -> 0

Set the most significant four bits of r11 to 1, other bits unchanged.

    ldi  r16, 0xF0       ; 1 on the bits to set
    or   r11, r16        ; bottom four OR 0, so unchanged

Note how 0xF0 appears as the mask in three of these with three different meanings — keep, flip, set — decided entirely by the instruction it is paired with.

In C

The same four operations with C’s bitwise operators (c-operators), which is how every AVR C program touches its ports. The masks are the same; the immediate-register restriction disappears, since the compiler chooses the registers.

Operation Operator Example Reads as
Clear particular bits & with 0s on the bits to clear var = PINB & 0x0F; keep the low nibble, zero the high
Test particular bits & with a 1 on the bit to test if (PINB & 0x02) … true if bit 1 is set
Set particular bits \| with 1s on the bits to set PORTC = PINB \| 0x80; force bit 7 to 1
Invert particular bits ^ with 1s on the bits to flip PORTC = PINB ^ 0x0F; flip the low nibble

Write the mask as a shift, not a hex constant: (1<<5) says bit 5 where 0x20 has to be decoded, and the header files name every register bit as a bit number for exactly this use (c-preprocessor-and-avr-headers):

DDRB  = (1<<5);                 /* bit 5 output, every other bit input: REPLACES the register */
DDRB |= (1<<4) | (1<<3);        /* bits 3 and 4 output, the rest unchanged: read-modify-write */
DDRB &= ~(1<<3);                /* bit 3 back to input, the rest unchanged                    */
PORTC ^= (1<<0);                /* toggle bit 0                                              */
TCCR1B = (1<<WGM12) | (1<<CS11) | (1<<CS10);   /* named bits, ORed into one value            */

The difference between the first two lines is the one that bites: = writes the whole register and silently sets the other seven bits to 0, |= ORs into what is already there. In assembly the second line is three instructions — in, ori, out — and the C compiler emits exactly those (week8-lab-avr-c-programming). For a single-bit clear the mask is the complement of the set mask, ~(1<<n), which is why clear bit 3 is &= ~(1<<3) and not &= (1<<3).

The test idiom needs no comparison. PINB & 0x02 is 0x02 when bit 1 is set and 0 when it is not, and C treats any non-zero value as true (c-control-flow) — so if (PINB & 0x02) is right and if ((PINB & 0x02) == 1) is always false, because the masked value is 2, never 1.

Set, clear and toggle on an I/O register

Changing one bit of an I/O register, and only that bit, is one of three lines. Each reads the register, combines it with a one-bit mask and writes it back:

To Write The mask Why the other bits survive
set bit n REG \|= (1<<n); a 1 on bit n \(X + 0 = X\)
clear bit n REG &= ~(1<<n); a 0 on bit n, 1s elsewhere \(X \cdot 1 = X\)
toggle bit n REG ^= (1<<n); a 1 on bit n \(X \oplus 0 = X\)

Figure 205: Set, clear and toggle on one register byte. Each panel starts from the same value of PORTC, 0110 0101, and changes one bit, outlined, with a single read-modify-write. The mask is a 1 shifted to the bit’s position, complemented for a clear. In every other column the mask holds the value that leaves a bit alone: 0 for OR and XOR, 1 for AND. Set gives 0110 1101, clear gives 0100 0101 and toggle gives 0110 0111, and each time the other seven bits are untouched.

Toggle is not enable. TIMSK2 ^= (1<<OCIE2A); turns the timer 2 compare A interrupt on only if it was off, and a second run turns it off again. To enable whatever the bit was before, set it with |=; to disable, clear it with &= ~. Toggling is for things meant to alternate, like an LED blinking.

The register has to be one that stores what is written. PORTx and DDRx do. PINx does not: it reads the pins, and on the ATmega324A a 1 written to one of its bits toggles the matching PORTx bit, so a read-modify-write on PINx changes the wrong bits (avr-io-ports).

Writing register bits by name

When setting or clearing bits of an I/O register, be explicit about which bits. Three ways to write the same value, from worst to best:

TCCR1B = 10;                          /* poor:   a number                    */
TCCR1B = 0x0A;                        /* better: the pattern, 0000 1010      */
TCCR1B = (1<<WGM12) | (1<<CS11);      /* best:   the bits, by name           */

WGM12 is bit 3 of TCCR1B and CS11 is bit 1, so all three are 0000 1010. Only the last says which bits, so a reader can check them against the datasheet without decoding anything: CTC mode, clock divided by 8 (avr-timers-and-counters). It costs nothing, either. The compiler works out (1<<WGM12) | (1<<CS11) while compiling, and all three lines become the same instructions.

The names are bit numbers. The device header that <avr/io.h> includes defines every bit name as the bit’s position in its register:

#define WGM02 3

A name is not a mask; 1<< makes it one (c-preprocessor-and-avr-headers). The names are the datasheet’s, and the datasheet has errors in places, so the I/O register summary at the back is the one to check a name against.

Assembly uses the same names. In ldi r16, (1<<WGM02)|(1<<CS01) the assembler works out the constant, 0x0A, and the instruction stored is ldi r16, 0x0A.

A name belongs to one register. WGM12 and WGM02 are both 3, so (1<<WGM12) written into TCCR0B sets WGM02, and the compiler cannot notice, because all it sees is the number 3. Pair each name with the register whose datasheet entry defines it. The same byte 0x0A is CTC mode in TCCR1B and a reserved mode in TCCR0B (2026-10-05-more-io).

Masking sets the status flags too

Status register flags will be set also — a mask operation is a real ALU operation, not a free one. AND, OR and EOR all clear V and set N and Z from the result (C is untouched); see avr-architecture.

That side effect is often the actual point. andi r16, 0x01 keeps only bit 0, so:

\[Z = 1 \iff \text{bit 0 of } \texttt{r16} \text{ is } 0 \iff \texttt{r16} \text{ is even}\]

which makes a single masked AND an even/odd test. Any single-bit mask turns the Z flag into a test of that one bit — and tst rd, which is just and rd, rd, is the degenerate case that tests the whole register against zero.

Common mistakes

  • &= (1<<n) to clear bit n. That keeps bit n and clears the other seven. A clear’s mask is the complement, ~(1<<n).
  • = where |= was meant. DDRB = (1<<5) makes PB5 an output and every other pin of port B an input.
  • A bit name without the shift. TCCR1B |= WGM12; ORs in the number 3, 0000 0011, which sets CS11 and CS10, clock divided by 64, and leaves WGM12 alone.
  • A bit name in the wrong register. (1<<WGM12) in TCCR0B sets WGM02.
  • ^= to enable. A toggle enables only from off; run twice, it disables.
  • A read-modify-write on PINx. Writing PINx toggles outputs, so it cannot clear or set a bit.
  • Getting AND’s mask backwards. With AND the 1s mark the bits to keep; with OR and XOR they mark the bits to change.
  • if ((x & mask) == 1). The masked value is the mask’s own value, so the test is false unless the mask is bit 0. Test for non-zero.

See also

Boolean Algebra

Logic functions can be expressed as expressions of variables (literals, e.g. \(A, B, X\)) and functions (the operators \(+\), \(\cdot\), \(\oplus\), \(\bar{\ }\)) — i.e. an output written in terms of its inputs, \(X = f(A,B)\). Variables and functions can only take the values 0 or 1. Boolean algebra is the set of rules governing how such expressions can be manipulated.

Notation conventions

  • Inversion: overline, e.g. \(\text{NOT}(A) = \bar A\) (pronounced “A bar”).
  • AND: dot, or implied by adjacency, e.g. \(\text{AND}(A,B) = AB = A \cdot B\).
  • OR: plus sign, e.g. \(\text{OR}(A,B,C) = A+B+C\).
  • Other examples: \(\text{XOR}(A,B) = A \oplus B = \bar A B + A \bar B\); \(\text{NAND}(A,B,C) = \overline{ABC}\); \(\text{NOR}(A,B) = \overline{A+B}\).

\(+\) and \(\cdot\) are OR and AND, not arithmetic addition and multiplication — \(1 + 1 = 1\) here.

Boolean identities

Name AND form OR form
Identity law \(1A = A\) \(0 + A = A\)
Null law \(0A = 0\) \(1 + A = 1\)
Idempotent law \(AA = A\) \(A + A = A\)
Inverse law \(A\bar A = 0\) \(A + \bar A = 1\)
Commutative law \(AB = BA\) \(A + B = B + A\)
Associative law \((AB)C = A(BC)\) \((A+B)+C = A+(B+C)\)
Distributive law \(A + BC = (A+B)(A+C)\) \(A(B+C) = AB + AC\)
Absorption law \(A(A+B) = A\) \(A + AB = A\)
De Morgan’s law \(\overline{AB} = \bar A + \bar B\) \(\overline{A+B} = \bar A \bar B\)

Two rows in particular do the heavy lifting when simplifying: the inverse law (\(A\bar A = 0\), \(A + \bar A = 1\)) collapses whole terms to a constant, and the absorption law (\(A + AB = A\)) deletes a term outright.

The distributive law in its AND form is not the arithmetic one — \(A + BC = (A+B)(A+C)\) has no algebraic analogue and is easy to misremember.

De Morgan’s law and gate equivalents

De Morgan’s law says AND and OR can be interchanged if you invert both the inputs and the output. Drawn as gates, that gives four equivalences — every gate has a second symbol, and pushing an inversion through a gate always flips its shape:

Figure 206: De Morgan’s law drawn as gate symbols. (a) a NAND is an OR with inverted inputs; (b) a NOR is an AND with inverted inputs; (c) and (d) are the same two statements read the other way. Each pair is the same function, so either symbol may be used - pick whichever makes the surrounding bubbles cancel.

Exercise: verify each of the four with a truth table.

This is also why NAND-only and NOR-only circuits can implement any function (see logic-gates) — an AND feeding an OR can always be redrawn as a NAND feeding a NAND.

Simplifying an expression

Worked example:

\[\text{CODE} = C + CD + \overline{(D + \bar D)}\]

  1. Apply De Morgan’s law to the last term: \(\overline{D + \bar D} = \bar D \cdot \bar{\bar D} = \bar D \cdot D = 0\) (the double overline cancels, then the inverse law \(A\bar A = 0\) applies).
  2. The identity law \(0 + A = A\) drops that term: \(\text{CODE} = C + CD\).
  3. The absorption law \(A + AB = A\) finishes it: \(\text{CODE} = C\).

The whole expression is just \(C\) — neither \(D\) nor the \(CD\) term affects the output at all.

Sum of products

Any logic function can be implemented as the OR of AND combinations of its inputs (a sum of products):

  1. For each row where the truth table output is 1, write the AND term of the inputs (complementing wherever the input is 0) that produces that row.
  2. OR all of those terms together.

Because every 1-row gets its own term, and each term is true for exactly that one row, the result is guaranteed to reproduce the table. Worked through in full, with the resulting circuit drawn out, in 2026-07-30-intro-to-logic-gates.

Sum of products always works, but does not necessarily give the minimum number of gates — the resulting expression can usually be simplified further with the identities above. E.g. \(Z = AB + AC = A(B+C)\) (distributive law) needs two gates rather than three.

C Control Flow

The three shapes a C program’s control can take — sequential, selection and repetition — with the statements the course uses for each: if … else, while and for. First met in 2026-09-07-introduction-to-embedded-c-programming and 2026-09-10-more-c-programming-on-the-avr; the assembly equivalents are in avr-program-structure.

The three shapes

Shape Statements
sequential statements run one after another the default — any list of statements
selection (decision) a test picks one of two paths if … else
repetition a body runs again while a test holds for, while

All three are drawn as flowcharts in 2026-09-07-introduction-to-embedded-c-programming. Every program is built from nothing but these, nested.

Truth

There is no boolean type. C interprets any 0 value as false, anything else as true. So:

Written Means
if(a) if(a != 0)
if(!a) if(a == 0)

Comparisons yield 1 or 0, so if (a > b) and if ((a > b) != 0) are the same test. A bitwise test like PINC & 0x01 yields either 0x01 or 0x00, which is why it can sit directly inside an if — anything non-zero is true, and it does not need to be exactly 1.

To the hardware a truth test is a compare against zero and a branch on Z — tst/cp then breq/brne in avr-instructions. if(a) is the C spelling of branch if not zero.

Selection — if

if (expression)
    stmt
else
    stmt
  • The else clause is optional.
  • stmt can be replaced by multiple statements enclosed in braces { }. Without the braces, only the one statement following the if (or else) is conditional — a second line at the same indentation runs unconditionally, whatever the indentation suggests. Always use the braces.

An if used as a guard:

if(digit < 10) {
    PORTA = seven_seg[digit];
} else {
    PORTA = 0;
}

Four input bits can hold 0–15, the array has ten entries, and the if is what keeps seven_seg[digit] inside it (c-pointers-and-arrays — C does not check).

An else if chain is an else whose single statement is another if; nothing new is needed for it.

Repetition — while

while (expression)
    stmt

Test first; if true, run the body, then test again; stop when the test is false. If the test is false to begin with, the body never runs.

while(1) — a condition that is always true — is the shape of every embedded program:

int main(void) {
    /* set-up, once */
    DDRA = 0xFF;
    while(1) {
        /* read inputs, compute, write outputs — forever */
        digit = PINC & 0x0F;
        …
    }
}

On the AVR main has nowhere to return to. The program is set-up, then loop forever, and the loop body is one pass of reading inputs and writing outputs. In assembly this was a label and an unconditional rjmp back to it (avr-program-structure); while(1) is the same jump with the label hidden.

Repetition — for

for (init; test; step)
    stmt

is exactly

init;
while (test) {
    stmt
    step;
}

— the for only gathers the three parts of a counted loop onto one line so they cannot drift apart. Two traversals of the array a:

for(index=0; index<10; index++) {     /* init: index=0; test: index<10; step: index++ */
    a[index] = 0;
}

for(ptr=a; ptr < a+10; ptr++) {       /* same loop, counting in addresses */
    *ptr = 0;
}

Figure 207: Where the three clauses of a for run, drawn on the repetition shape. init runs once, before anything; test runs before every pass, including the first; step runs after every pass, before the next test. The body of for(index=0; index<10; index++) therefore runs exactly ten times, with index taking 0 through 9 — and when the loop exits index is 10, the first value that failed the test. This is the while equivalence above, drawn.

The bound is the thing to get right. index < 10 runs the body for 0 through 9, the ten legal indices of a[10]; index <= 10 runs it once more, for a[10], which does not exist. The pointer form has the same edge: ptr < a+10 stops at the address one past the end without ever touching it.

Infinite loops, deliberately

The macro #define EVER ;; makes for(EVER) a spelling of for(;;) — a for with no init, no test and no step, which loops forever (c-preprocessor-and-avr-headers). It is while(1) in a different costume; the course’s programs use while(1).

Other control statements

switch, do … while, break and continue are all real C. They are not in these notes yet.

See also

C Language Basics

What a C program is made of: the shape of a program, variables and their types, functions, and constants. Operators are in c-operators, the if/while/for statements in c-control-flow, arrays and pointers in c-pointers-and-arrays, and the preprocessor in c-preprocessor-and-avr-headers. First met in 2026-09-07-introduction-to-embedded-c-programming.

Where C sits

C is the top layer of the course’s three blocks — high-level programming over low-level programming over digital logic design — and the course’s C is embedded C for the ATmega324A, the same chip the assembly targeted. The difference from assembly is one extra tool. An assembler turns each line into exactly one instruction; a compiler turns each C statement into however many instructions it needs, chooses the registers, and hands the result to the assembler. The chain from C statement down to control unit is drawn in 2026-09-07-introduction-to-embedded-c-programming, and the steps after the compiler, object files and the linker, are in compilation-and-linking.

What is expected: write small C programs and functions from scratch, understand the meaning of C programs, and write or modify C programs — practised in Labs 11–16, which all use C.

The shape of a program

  • There must be a function called main; it is executed when the program starts.
  • Blocks of code are enclosed by braces { }.
  • Statements end with a semicolon ;.
  • C is case sensitive — variable and Variable are different names.
  • Comments are /* … */ (any length, may span lines) or // to the end of the line.
/* the smallest useful embedded program: */
#include <avr/io.h>

int main(void) {
    DDRA = 0xFF;        /* a statement */
    while(1) {          /* a block */
        PORTA = 0x55;
    }
}

On the AVR main never returns — there is no operating system to return to — so every program ends in an infinite loop (c-control-flow). #include is the preprocessor’s (c-preprocessor-and-avr-headers).

Variables and types

Declaration: type-name variable-name, variable-name …;

A declaration reserves room in data memory (memory-models) and gives it a name and a type. The type decides two things: how many cells the variable takes, and how the bits are read — the signed/unsigned question of binary-number-representations, now answered once at the declaration instead of instruction by instruction.

Declaration Size Range
char c; 1 byte −128 … 127 two’s complement
unsigned char x; 1 byte 0 … 255
int day; machine dependent — 16 bits on the AVR −32768 … 32767 two’s complement
unsigned int count; as int 0 … 65535 on the AVR
float 32 bits about \(\pm 3.4 \times 10^{38}\), 7 digits IEEE single precision; no AVR hardware — done in software
double 64 bits in general; 32 on avr-gcc likewise

On avr-gcc float and double are interchangeable: both are 32 bits (below).

Figure 208: What three declarations reserve in the AVR’s 8-bit data memory, drawn as a memory map. char is one cell. int is two, because int is 16 bits on the AVR — which is why a pointer to an int steps by two in the pointers note. float is four, because single precision is 32 bits. The compiler decides the actual addresses; the addresses here are schematic and the order is arbitrary.

Three consequences worth carrying around:

  • char is an integer. It is exactly the 8-bit two’s complement byte of the hardware block; the name only promises it can hold a character code. Arithmetic on it is byte arithmetic, and 'A' + 1 is 'B' because 'A' is 65.
  • int is not one size. Write code that assumes 16 bits and it breaks on a desktop; assume 32 and it breaks on the AVR. The AVR headers provide uint8_t, int16_t and friends — types with the width in the name — and the course’s example program uses uint8_t for exactly this reason.
  • Nothing is checked. Storing 300 in an unsigned char does not fail; it stores 300 mod 256, i.e. 44. (For a signed char the C standard leaves the result implementation-defined; gcc also gives 44.) The type is a reading rule, not a guard.

Booleans. There is no boolean type in the course’s C. Any value can be treated as a boolean: zero means false, non-zero means true. This is what lets if(a) mean if(a != 0) (c-control-flow).

Functions

return-type function-name (arg-decl)
{
    variable-declarations;
    …
    statements;
}
Part Meaning Example
return-type what type is returned, or void for nothing int, void
function-name the name; main for the entry point average
arg-decl argument (parameter) declarations, comma-separated, each with its type int a, float b
variable-declarations variables used only within the function int avge;
statements the code which actually does stuff

An example:

/*
  Return the average of two integers
  (result will be rounded towards 0)
*/
int average(int a, int b) {
    int avge;

    avge = (a+b)/2;

    return avge;
}
  • avge = (a+b)/2; is a statement built from expressions — (a+b), then (a+b)/2, then the assignment; the outermost expression plus its semicolon is the statement.
  • return avge; hands the value back and ends the function.
  • avge is local: it exists only while average is running. Nothing outside can name it.
  • Integer division truncates toward zero. average(1, 2) computes 3/2 and returns 1; the .5 never exists. The comment says rounded towards 0, and that is the whole of C’s rule for / on integers — -3/2 is -1, not -2.

A function with void in front returns nothing and is called for its effect. int main(void) is a function whose argument list is explicitly empty.

Where a variable lives

Where a declaration is written decides where the compiler stores the variable and how long it exists.

Declaration Kind Stored Exists
outside every function: int count; global at a fixed address in data memory, from 0x0100 up for the whole run
inside a function: int avge; local in the call’s stack frame only while that call runs
inside a function: static int calls; static local with the globals, at a fixed address for the whole run, keeping its value between calls
outside every function: static int a; static global like any global for the whole run; the name is private to its file

So avge in average above is made fresh on every call and is gone at the return, and a local that is never assigned starts out holding whatever was left on the stack. A static local is the way to have a function remember something from one call to the next. Memory obtained from malloc() comes from a third place, the heap, which grows from above the globals toward the stack. The full picture is in compilation-and-linking, and the frame itself is in procedures-and-the-stack.

Constants

Character constants

Single quotes: 'a', 'b', '1'. A character constant is a number — its ASCII code — so '1' is 49, not 1.

Range Codes
'A' … 'Z' 65 … 90
'a' … 'z' 97 … 122
'0' … '9' 48 … 57

Which makes c - '0' the digit value of a digit character, and c + ('a' - 'A') the lower-case of an upper-case letter — both plain integer arithmetic.

Special characters are backslash escaped:

'\n' newline
'\'' single quote
'\t' tab
'\\' backslash

String constants

Double quotes, escapes allowed inside: "abc \n \" hello\t". A string is an array of char (c-pointers-and-arrays).

Integer constants

Base Written Examples
Decimal as usual 3, -27, 65535, +5
Hexadecimal leading 0x 0x5F, 0xFFFF, 0xDEADBEEF
Octal leading 0 0377 = 255

The octal rule is a trap: a leading zero changes the base. 010 is eight. Do not zero-pad a decimal constant.

Hexadecimal is the natural notation for anything that is really a bit pattern — port values, masks — because each digit is exactly one nibble (binary-number-representations). 0xFF is 11111111 at a glance; 255 is not.

Floating point constants

Include a decimal point and/or an e exponent: 3.1416, -7., 6.02e23, -5.2e-2. 7 is an integer; 7. is floating point. The type of a constant is decided by how it is written, and it decides what arithmetic happens: 7/2 is 3, 7./2 is 3.5.

Floating point on the AVR

float and double are usually IEEE single and double precision, but the C standard only asks for minimums: about 6 significant decimal digits for float and 10 for double, both up to \(10^{37}\). avr-gcc makes double the same 32-bit single precision as float, which gives about 7 digits and so falls short of what the standard asks of double. Code written for a desktop that relies on double quietly loses half its digits on the AVR.

The AVR also has no floating-point hardware: its only hardware data type is the 8-bit integer (instruction-set-architecture). Every float add, multiply or conversion is a call into a software library, hundreds of instructions with branches where an integer operation takes a few. So where integer arithmetic can give the same result, use it:

PORTB = PINA / 3;        /* integer: a handful of instructions, no branches */
PORTB = PINA * 0.334f;   /* float: the same results, 300+ instructions      */

Scaling to whole units (millivolts, tenths of a degree) or using fixed-point-numbers keeps the fractions without the floats. The formats themselves, and why 0.1 cannot be stored exactly, are in floating-point-numbers.

See also

C Operators

The operators the course uses, in groups — arithmetic, comparison, bitwise, logical, assignment — with the two families that look alike and are not, the shift operators and what they compile to, and the prefix/postfix rule. First met in 2026-09-07-introduction-to-embedded-c-programming; the signed/unsigned shift rule is in 2026-09-10-more-c-programming-on-the-avr. Types are in c-language-basics.

Binary operators

Group Operator Meaning AVR instruction behind it
arithmetic + addition add, adc
- subtraction sub, sbc
* multiplication mul
/ division (integer, truncates toward 0) a library routine — the AVR has no divide
% remainder (integer) likewise
comparison > >= < <= ordering cp then a branch on the flags
== equal cp then breq
!= not equal cp then brne
bitwise & bitwise AND and, andi
\| bitwise OR or, ori
^ bitwise XOR eor
logical && logical AND compare-and-branch sequences
\|\| logical OR
assignment = assignment a mov, ld/st, or in/out — whatever the two sides are

The instructions in the last column are in avr-instructions.

A comparison produces a value: 1 if true, 0 if false. So a > b is an ordinary expression that can be assigned, and (a > b) + (c > d) counts how many are true.

Unary operators

Operator Meaning Example AVR
! logical not !A ≡ Ā test-and-branch
~ one’s complement (invert every bit) ~A com
- two’s complement (negate) neg
++ increment (prefix or postfix) inc, or subi rd, -1
-- decrement (prefix or postfix) dec

Bitwise is not logical

The two pairs &/&& and |/||, and the pair ~/!, are the easiest mistake in C to make and the hardest to see.

  • Bitwise &, |, ^, ~ work column by column: bit \(i\) of the result depends only on bit \(i\) of each operand. This is the eight-parallel-columns picture of bit-masking and the AND/OR/EOR/COM of avr-instructions.
  • Logical &&, ||, ! treat each whole operand as true or false (non-zero or zero) and yield 1 or 0.
unsigned char a = 0x0F, b = 0xF0;

a & b      /* 0x00 — no column has a 1 in both  */
a && b     /* 1    — both are non-zero, so true */

~a         /* 0xF0 — every bit flipped           */
!a         /* 0    — a is non-zero, so "not a" is false */

a & b is zero and a && b is one, from the same two operands. Inside an if, if (PINC & 0x01) tests one bit, which is what is usually meant; if (PINC && 0x01) is true whenever anything on port C is high. The compiler accepts both.

== is not =

Read a = b as a ⇐ b.

  • = does. a = b copies b into a. The arrow reading is the honest one: data flows right to left, the same destination first rule as mov rd, rr in avr-instructions.
  • == asks. a == b is 1 if they are equal, 0 if not, and changes nothing.

if (a = 0) is legal C. It stores 0 in a, tests the stored value, and never takes the branch — silently.

Assignment shorthands

a += b is shorthand for a = a + b, and similarly -=, *=, /=, %=, &=, |=, ^=, <<=, >>=. a += 1 is the same as a++.

The three that matter most on the AVR are the bitwise ones, because they are the read-modify-write of a port in one line:

PORTA |= 0x01;      /* set bit 0, leave the rest    */
PORTA &= ~0x01;     /* clear bit 0, leave the rest  */
PORTA ^= 0x01;      /* toggle bit 0                 */

each a mask operation from bit-masking — and the ~ in the second is the reason the mask can be written as the bit to clear rather than as its complement.

Shifts

AVR
a << b a shifted left by b bits; 0 enters at the bottom lsl, b times
a >> b a shifted right by b bits — logical if a is unsigned, arithmetic if a is signed lsr or asr, b times

A left shift by \(n\) multiplies by \(2^n\); a right shift by \(n\) divides by \(2^n\), rounding toward \(-\infty\) for signed values. Two examples: 1 << 5 is \(1 \times 2^5 = 32\) and 3 << 4 is \(3 \times 2^4 = 48\) — worked in bits in the shift figure of 2026-09-07-introduction-to-embedded-c-programming.

The type picks the instruction. In assembly the programmer chose lsr or asr and thereby declared whether the byte was unsigned or signed (2026-09-03-instruction-set-architecture-part-2). In C there is one >>, and the declaration made the choice already:

Figure 209: One operator, two instructions. The same bit pattern 10000000 is shifted right by one under two declarations. As unsigned char it means 128, the compiler emits lsr, a 0 enters at the top, and the result is 64. As char it means \(-128\), the compiler emits asr, the sign bit is copied back into the top, and the result is \(-64\). Both are the correct halving of what the bits were declared to mean.

1 << n is the mask with only bit \(n\) set. The AVR headers name every flag and pin as a bit number, so 1 << FLAG_NAME — with FLAG_NAME == 5 giving 00100000 — is how a mask is written from a name rather than a magic constant (c-preprocessor-and-avr-headers). Combined with the shorthands above:

PORTA |= (1 << 5);     /* set bit 5     */
PORTA &= ~(1 << 5);    /* clear bit 5   */
if (PINC & (1 << 3))   /* test bit 3    */

Prefix and postfix ++ and --

a++ and ++a both add one to a. They differ in what the expression is worth:

Order Rule
postfix a++ use value, change value the expression is the old a; then a becomes a + 1
prefix ++a change value, use value a becomes a + 1; the expression is the new a

Every use is two statements in disguise, and only the order differs:

int a,b,c,d,e;
a = 4;
b = a++;    /* b=a;   a=a+1; */   /* b=4, a=5 */
c = --a;    /* a=a-1; c=a;   */   /* a=4, c=4 */
d = ++a;    /* a=a+1; d=a;   */   /* a=5, d=5 */
e = a--;    /* e=a;   a=a-1; */   /* e=5, a=4 */

Final values: a=4, b=4, c=4, d=5, e=5.

Worked: a = 1; b = 3; b += a++; leaves b = 4, because b += a++ is b = b + a with the old a, and only then a = a + 1. An answer of 5 applies the increment first, which is what ++a does.

On its own line, a++; and ++a; are indistinguishable: the value of the expression is thrown away, and only the change remains. The difference exists only when the expression is used — assigned, passed, indexed, as in values[9] = values[8]++; (c-pointers-and-arrays).

Precedence

The one place precedence bites is the SQUARE(1+2) example in c-preprocessor-and-avr-headers, where * binding tighter than + turns (1+2*1+2) into 5. The rule the course relies on is the schoolroom one — *, /, % before +, - — and the practical advice is parenthesise anything you would have to think about. Two cases to know because the natural reading is wrong:

  • & binds looser than ==, so x & 1 == 0 is x & (1 == 0), i.e. x & 0. Write (x & 1) == 0.
  • << binds looser than +, so 1 << n + 1 is 1 << (n + 1). Write (1 << n) + 1 if that is what is meant.

These are the two that catch AVR code in particular.

See also

C Pointers and Arrays

Arrays, pointers, and the fact that connects them: an array name is the address of its first element, and pointer arithmetic counts in elements, not cells. Both are made concrete in the AVR’s 8-bit data memory (memory-models), where an int is two cells and so a + 5 is ten cells past a. First met in 2026-09-10-more-c-programming-on-the-avr; the language basics are in c-language-basics.

Arrays

Declaring: type variable_name[size];

char message[16];
int  values[10];
uint8_t seven_seg[10] = { 63,6,91,79,102,109,125,7,127,111 };   /* with initial values */

Accessing: variable_name[index], with index = 0 … size−1 — zero-based indexing. A 365-element array has elements [0] through [364]; [365] is not one of them.

message[0] = 'c';
values[9] = values[8]++;        /* copies the OLD values[8], then increments it */

The declaration reserves size elements of the type contiguously — one after another with nothing between — which is what makes both the indexing and the pointer arithmetic below work. The elements are ordinary variables of the element type; values[3] is an int like any other.

C does not check the index. values[10] and values[-1] compile, and at run time they read or write whichever cell happens to sit past the end or before the start. The seven_seg[digit] lookup is guarded with if(digit < 10) for exactly this reason (c-control-flow).

Pointers

A pointer variable stores a memory address. Declaration: type *variable_name; — variable_name is a pointer to something of the given type.

char a, b;
char *ptr;          /* or all on one line: char a,b,*ptr; */

ptr = &a;           /* & — address-of: ptr now holds a's address  */
b = *ptr;           /* * — indirection: the value at that address */

The two operators are inverses:

From To
&a a variable its address address-of — makes a pointer
*ptr an address the value stored there indirection — follows a pointer

In memory, say a holds 8 at address 400, b is at 434, and ptr is at 576 holding 400 — an address, not a value (drawn in 2026-09-10-more-c-programming-on-the-avr). ptr is a variable like the others, with its own cell; only its contents are special. On the AVR a data address is 16 bits (memory-models), so a pointer is two cells whatever it points at.

*ptr can also be assigned to: *ptr = 0; writes through the pointer into whatever it points at. That is how the pointer traversal below clears an array.

The * in a declaration and the * in an expression are different things. char *ptr; declares ptr as a pointer; *ptr later uses it. The declaration form reads as the thing *ptr is a char.

The hardware view

A pointer is the indirect addressing mode of addressing-modes as a language feature. ptr plays the part of the X, Y or Z register pair, *ptr is ld rd, X, and *ptr = v is st X, rr. ptr++ is the post-increment form ld rd, X+ that the instruction set provides precisely because walking a table is so common. The compiler chooses which of X, Y, Z it uses.

Arrays are pointers to their first element

An array name can be treated as a pointer to the first element — the address of the first element.

int a[10];
int *ptr;

/* the following are the same */
ptr = a;
ptr = &a[0];

So a on its own is an address, a[0] is the int there, and *a is the same int. In general a[i] is *(a + i) — the bracket notation is shorthand for pointer arithmetic, which is why the arithmetic has the rule it has.

Pointer arithmetic

Addition and subtraction on pointers work in multiples of the size of the object pointed to.

int a[10];
int *ptr;

/* the following are the same */
ptr = a+5;
ptr = &a[5];

If a starts at 300 and an int is 16 bits — two 8-bit cells — then a + 5 is 310, not 305: five elements on, two cells each. The sum is 300 + 2·5 = 310, not 300 + 5 = 305. The array is drawn in memory in 2026-09-10-more-c-programming-on-the-avr.

Figure 210: ptr++ on a pointer to int, on the AVR. Each step moves the pointer by one element, which is two 8-bit cells, so the addresses it visits are 300, 302, 304, … and it lands on every element exactly once. The same ptr++ on a char pointer would step by one cell. The compiler multiplies the step by the element size; the source says ++ either way. The pointer is the traversal loop’s, drawn at three successive steps.

The consequences:

  • The same expression means different addresses for different types. a + 5 is 310 for int a[] and 305 for char a[]. The type is part of the arithmetic.
  • ptr - a counts elements, not cells: for ptr = &a[5] it is 5.
  • Comparison works in addresses. ptr < a + 10 is true while ptr is inside the array.
  • int is 16 bits on the AVR; on a 32-bit machine a + 5 would be twenty cells on. The rule is stated in terms of the size of the object because the number is machine-dependent (c-language-basics).

Traversing an array

Two ways to clear int a[10]:

/* using an index */
int a[10];
int index;
for(index=0; index<10; index++) {
    a[index] = 0;
}

/* using a pointer */
int a[10], *ptr;
for(ptr=a; ptr < a+10; ptr++) {
    *ptr = 0;
}

Adding one to an array pointer makes it point to the next element in the array. The two loops visit the same ten cells in the same order. The index loop computes a + index afresh each pass; the pointer loop keeps that address in ptr and steps it. The bound is the same in both — the address one past the last element, tested with < so it is never touched. See c-control-flow for the for itself.

The pointer form is closer to what the compiler emits either way — a register pair holding an address, an st X+, r in the body — which is why C has it.

Strings, briefly

A string constant "abc" (c-language-basics) is an array of char with a terminating zero byte after the last character, so "abc" occupies four cells. char message[16]; therefore holds at most fifteen characters, though message[16] looks like room for sixteen. The terminator is standard C.

See also

C Preprocessor and AVR Headers

The preprocessor — #include and #define — and the three lines of avr/io.h that let DDRA = 0xFF; be written as if a hardware register were a variable. First met in 2026-09-10-more-c-programming-on-the-avr; the port registers themselves are in avr-io-ports.

What the preprocessor is

C programs are first parsed by a preprocessor, which replaces preprocessor directives with substitute text. Only then does the compiler see the program. Directives start with #:

Directive Does
#include … paste in a file
#define … define a macro — a textual substitution
#if, #ifdef, #else, #undef, … conditional inclusion, un-definition, and others

The preprocessor does not know C. It edits text. Whatever it produces is what the compiler compiles, and every surprise in this note comes from forgetting that.

#include

Form Kind of header Looks in
#include <filename.h> system the system include directories — where avr/io.h and stdio.h live
#include "filename.h" user-defined your own project directory first

The directive is replaced by the whole contents of the named file, at that point. After preprocessing there is one file, with the header pasted in at the top.

Header files

Header (.h) files are used for common macros, function prototypes etc — the C counterpart of m324Adef.inc in assembly (avr-io-ports).

  • stdio.h — prototypes of printf() etc. The AVR has a simplified version (no files); printf() only works if you say where the characters go, e.g. a serial port.
  • avr/io.h — defines the AVR’s useful constants and functions/macros. Definitions depend on the actual device targeted: it reads which chip is being compiled for and pulls in that chip’s register map, so DDRA means the right address for the ATmega324A and a different one for another part. It also supplies uint8_t and the other fixed-width types.

Every program in the course starts with #include <avr/io.h>.

Headers against libraries

A header file is not the library. A header

  • defines useful preprocessor macros,
  • declares the functions that are in the library, as function prototypes, and
  • declares variables that are available externally, with extern.

The library is the collection of object files that implements the functions (compilation-and-linking).

A prototype such as int printf(const char *fmt, ...); tells the compiler the name, the argument types and the return type. That is enough for the compiler to check a call and generate it. There is no code in it, so in main.o the call to printf is left as an external reference. The code is in the library, an object file printf.o inside it, and the linker joins it on and fills in the address. An extern declaration does the same for a variable: extern int count; says that count exists somewhere else and reserves nothing.

So the header goes to the compiler, through the preprocessor, and the library goes to the linker. The two kinds of mistake show up at different steps:

Missing Shows up when Typical message
the #include compiling implicit declaration of function printf
the library, or the .c file that defines the function linking undefined reference to printf

Figure 211: Where a header and a library each come into play, for a program that calls printf. The header holds only declarations. The preprocessor pastes it into main.c so that the compiler can check and generate the call, and in main.o that call is still an external reference. The library holds the definitions, as already compiled object files with an index. The linker finds printf.o through the index, links it in, and fills in the call. The header is used by the compiler and the library by the linker.

#define — macros

Macros are textual substitutions.

Macro Effect
#define pi 3.1415 every later pi becomes 3.1415 — A = pi * r²; becomes A = 3.1415 * r²; (the superscript is shorthand; in real C the square would be r * r)
#define EVER ;; for(EVER) becomes for(;;), an infinite loop
#define sum(a,b) (a+b) a macro with parameters: sum(x, 2) becomes (x+2)

A macro with parameters looks like a function call and is not one: no call happens, the arguments are pasted into the body as text, and the result is compiled in place.

The SQUARE trap

Given #define SQUARE(x) (x*x), what is SQUARE(1+2)?

5, not 9. Paste the text: (1+2*1+2). Multiplication binds tighter than addition, so it is \(1 + 2 + 2\). The argument was never evaluated first, because there is no function to evaluate it.

The fix is parentheses around every parameter, and around the whole body:

#define SQUARE(x) ((x)*(x))       /* SQUARE(1+2) -> ((1+2)*(1+2)) = 9 */

The outer pair matters as much as the inner: without it, 1 / SQUARE(a) becomes 1 / (a)*(a), which is \(a\), not \(1/a^2\). Write every macro this way. The AVR headers below do — note the brackets around (mem_addr) and (io_addr).

A second pitfall: an argument with a side effect is pasted as many times as the parameter appears. SQUARE(i++) becomes ((i++)*(i++)) and increments i twice.

The avr/io.h register macros

The definitions behind the port names, from avr/io.h and the device header it includes:

#define _MMIO_BYTE(mem_addr) \
                (*(volatile uint8_t *)(mem_addr))
#define _SFR_IO8(io_addr) \
                _MMIO_BYTE((io_addr) + 0x20)

/* Input Pins, Port A */
#define PINA      _SFR_IO8(0x00)

/* Data Direction Register, Port A */
#define DDRA      _SFR_IO8(0x01)

/* Data Register, Port A */
#define PORTA     _SFR_IO8(0x02)

(\ at the end of a line continues a directive onto the next line.)

Upshot: I/O register names can be used as variables.

DDRA = 0xFF;
PORTA = PINC | 0xF0;

Unrolling DDRA

Step Text
as written DDRA = 0xFF;
#define DDRA _SFR_IO8(0x01) = 0xFF;
#define _SFR_IO8 _MMIO_BYTE((0x01) + 0x20) = 0xFF;
#define _MMIO_BYTE (*(volatile uint8_t *)((0x01) + 0x20)) = 0xFF;

Reading the final line from the inside out:

  1. (0x01) + 0x20 is 0x21 — a number.
  2. (volatile uint8_t *) casts it: treat this number as the address of an 8-bit unsigned byte. Now it is a pointer (c-pointers-and-arrays).
  3. The leading * dereferences it: the byte at that address.
  4. = 0xFF stores into that byte.

So DDRA = 0xFF; is a store to data address 0x21, and x = PINC; is a load from data address 0x26. There is no variable called DDRA anywhere; the name dissolves before the compiler sees it.

Why + 0x20

The AVR’s 64 I/O registers have two addresses each (avr-io-ports): an I/O-space number 0–63, which is what in and out use, and a data-space address 0x20 higher, where lds/sts — and any C pointer — find the same register. DDRA is I/O 0x01 and data 0x21. The macro takes the I/O number the datasheet lists and adds the offset, because a C pointer can only name data-space addresses. (The compiler, seeing a constant address in the I/O range, will usually emit in/out anyway.)

Why volatile

volatile tells the compiler the value at this address can change without the program changing it, and that every read and write matters. Without it the compiler is entitled to assume that a byte it wrote a moment ago still holds what it wrote, and that two reads with nothing between them give the same answer — both false for a port: PINC changes whenever the pins do, and PORTA is written for its effect on the pins, not to be read back. volatile forbids the optimisations that would break that. It is the one piece of the macro that is about hardware rather than addressing.

The same keyword belongs on any ordinary variable that an interrupt handler writes. To the code in main, a handler’s write is as invisible as a pin changing, and for the same reason: nothing in main’s own flow of control explains it. See avr-interrupts.

Naming bits

The headers also define bit numbers for every flag and pin — for example FLAG_NAME == 5 — so a mask is written from a name rather than a constant:

1 << FLAG_NAME              /* 00100000 when FLAG_NAME is 5 */
PORTA |= (1 << 5);          /* set one bit                   */
PORTA &= ~(1 << 5);         /* clear one bit                 */

The shift and the |=/&= shorthands are in c-operators; the mask patterns are in bit-masking. FLAG_NAME is a placeholder name; the actual names for the ATmega324A’s pins and flags come from the device header, as #define WGM02 3 does in 2026-10-05-more-io.

See also

Circuit Schematics

A logic diagram shows the idea of a circuit and is hardware-independent (see logic-gates). A circuit schematic goes further: it tells you how to actually build the circuit on real hardware — labelled ICs, pin numbers, power connections — so it’s hardware-specific. Schematics are drawn for practicals and assessment using 74-series logic chips and the CSSE2010/CSSE7201 IO Board (see device-pinouts for pin layouts). The rules are set out in the CSSE2010/CSSE7201 - Guide to Drawing Circuit Schematics (Blackboard, v2.3).

Required elements

Every circuit schematic must show:

  • Labelled inputs and outputs — every input/output needs a sensible, unique name. Inputs and outputs use different symbols, and by convention inputs are drawn on the left, outputs on the right.
    • Both symbols are the same right-pointing pentagon; what differs is which end the wire attaches to. An input has its wire leaving the point, so the signal flows out of the tip into the circuit. An output has its wire arriving at the flat back edge, with the point left free. Getting this backwards is one of the common errors below.
  • Labelled devices — each physical device (chip or IO board) gets a unique identifier: one or more letters for the device type, then a sequential number starting from 1.
    • Logic chips: U1, U2, U3, …
    • IO board: IO1 (IO2 for a second board, etc.) — when a group of inputs/outputs all belong to the same IO board, it only needs to be labelled once for the whole group, not per signal.
  • Gate labels within a chip — where a chip contains multiple gates, each gate is labelled A, B, C, … after the chip ID, separated by a colon (e.g. U1:A, U1:B). Labels can be assigned to gates in any order. A chip with only one gate/device doesn’t need a gate letter (just U3).
  • Device type — written on the line below the device ID (e.g. 74HCT00, 74HCT04, IOBOARD).
  • Pin numbers — every pin used must be numbered per the actual device pinout (see device-pinouts).
  • Power supply connections — shown once per device type, not per individual chip. Where two+ chip types share the same power pins, they can be grouped together. The IO board doesn’t need power connections shown.

Worked example

Figure 212: A correct schematic. Every rule above is visible here at once: five named inputs (A-E) and one named output (X0) on the IO board, four gates of one 74HCT00 labelled U1:A to U1:D, a fifth NAND that had to move to a second chip U2, an inverter on a third chip U3 because it is a different gate type, a pin number on every terminal, a junction dot where E splits to both inputs of U2:A, and one power-supply block covering both chip types.

Reading it against the rules:

  • Naming: the inputs are A, B, C, D, E and the output is X0. The two IO-board groups are each labelled IO1/IOBOARD once, not per signal.
  • Chip identifiers: U1 supplies four NAND gates (U1:A–U1:D). A fifth NAND is needed, so it comes from a second chip, U2:A. The inverter is a different gate type, so it needs a third chip, U3:A, of type 74HCT04.
  • Pin numbers: the 74HCT00’s four gates use inputs 1&2, 4&5, 9&10, 12&13 with outputs 3, 6, 8, 11 respectively — so those are the numbers written on U1:A–U1:D. U3:A uses 1 → 2.
  • The junction dot: E (pin 25) drives both inputs of U2:A, which is what turns a NAND into an inverter. The dot at the split is what says the two wires are joined.
  • Power: 74HCT00 and 74HCT04 have the same power pins, so they are braced together into one block: Vcc on pin 14, GND on pin 7. Nothing is shown per chip, and nothing at all for the IO board.

Common errors

Figure 213: The same circuit with seven deliberate mistakes ringed and numbered left to right, matching the list below. Compare each ring against the corresponding part of the correct schematic above.

  1. Duplicate names — two inputs given the same name (both called A). Every input needs a unique name.
  2. Missing junction dots — where wires join or split, a dot must mark the connection. Wires that merely cross on the page, with no dot, are not electrically connected. Here the split feeding both inputs of the NAND-as-inverter has no dot.
  3. Gate label exceeds chip capacity — U1:E on a 74HCT00, which only has four 2-input NAND gates (A–D). A fifth gate needs a new chip ID (U2:A or similar).
  4. Wrong device for the gate type — U1:F is a NOT gate, a different type from the rest of U1, so it needs its own chip identifier (U3:A). (The figure also gives it as a 74LS04 while the rest of the schematic uses 74HCT parts.)
  5. Reusing pin numbers — U1:C is drawn with pins 1, 2 → 3, the same physical gate as U1:A. You can’t use one gate twice.
  6. Inconsistent device type — U1:D is labelled 74HCT47 when the rest of U1 is a 74HCT00. Every gate labelled U1:something must show the same chip type.
  7. Output errors — two distinct mistakes on X0:
    1. The input symbol is used (wire attached to the point) where the output symbol is needed (wire attached to the flat back) — see Figure 212.
    2. An input is wired to the output of a gate. An input should never be tied straight to a gate’s output; this may destroy the device. Gate outputs should only feed output devices (e.g. LEDs) or the inputs of other gates.

See also

  • device-pinouts — the pin numbers and symbols every schematic has to match
  • logic-gates — the gate symbols themselves, and the logic-diagram level above this one
  • week3-lab-lab-4-pre-work — the preparation task that asks for schematics of a 2-to-1 mux, a 2-to-4 decoder and a 4-bit adder/subtractor

Combinational Logic Blocks

Reference note for the standard combinational building blocks: the adder-subtractor, the multiplexer, and the decoder. See logic-gates for the gate symbols/truth tables and boolean-algebra for the notation used below.

What makes a circuit combinational

A combinational circuit is a combination of logic gates with \(n\) inputs and \(m\) outputs:

  • Each output can be expressed as a function of the \(n\) input variables.
  • The output depends on the current inputs only — there is no memory of previous inputs. (Contrast with sequential-circuits, where the output also depends on stored state.)
  • It can always be written as a truth table with \(n\) input columns, \(m\) output columns, and \(2^n\) rows (one per possible input combination).

Figure 214: The general shape of a combinational circuit and the truth table it is always equivalent to. The row count \(2^n\) depends only on the number of inputs, and the output column count \(m\) only on the number of outputs — so a block with six inputs needs 64 rows however few gates are inside it.

Binary subtraction

\(A - B\) is usually implemented as \(A + (-B)\), where:

  • \(A\) and \(B\) are multi-bit quantities;
  • “+” here means addition, not OR;
  • \(-B\) means the two’s complement of \(B\) (see binary-number-representations).

The two’s complement of \(B\) is calculated by flipping all the bits and adding 1:

\[-B = \bar B + 1\]

So a subtractor is just an adder with two extra pieces: something that conditionally inverts \(B\), and something that adds the extra 1.

The controlled inverter (XOR trick)

We need a gate that flips a bit only sometimes: given a mode bit \(M\),

\[Z = \bar B \text{ when } M = 1, \qquad Z = B \text{ when } M = 0\]

From the XOR truth table: XOR with one input held at 0 passes the other input through unchanged, and XOR with one input held at 1 inverts it. So the gate is a 2-input XOR:

\[Z = B \oplus M\]

M B \(Z = B \oplus M\) Effect
0 0 0 pass through
0 1 1 pass through
1 0 1 invert
1 1 0 invert

Figure 215: The controlled inverter: one XOR gate per bit, with the mode line on the second input. The two identities on the right are the whole trick, and they hold for any signal X — XOR against a constant 0 is a wire, XOR against a constant 1 is an inverter.

This is called a controlled inverter.

Adder-subtractor circuit

A 4-bit adder-subtractor is built from a 4-bit binary adder (a ripple-carry adder — see 2026-08-04-binary-arithmetic) plus four XOR gates:

  • Data input \(A\) (\(A_0 \ldots A_3\)) goes straight into the adder’s \(A\) inputs.
  • Data input \(B\) (\(B_0 \ldots B_3\)) goes into the adder’s \(B\) inputs via one XOR gate per bit; the second input of every XOR gate is the shared mode select line \(M\).
  • \(M = 0\) means add, \(M = 1\) means subtract.
  • The adder produces the data output \(S_0 \ldots S_3\), plus a carry-out \(C_4\) and taking a carry-in \(C_0\).

The carry-in. With \(M = 1\) the XOR gates supply \(\bar B\), and two’s complement needs \(\bar B + 1\) — the extra \(+1\) is supplied by feeding it in as the carry-in. With \(M = 0\) we want plain addition, which needs a carry-in of 0. Both cases are satisfied by

\[C_0 = M\]

so the mode select line is wired to both the XOR gates and the adder’s carry-in.

Figure 216: The 4-bit adder-subtractor. One mode line does two jobs: it conditions every bit of B through an XOR, and it is the adder’s carry-in. With M = 0 the XORs pass B through and the carry-in is 0, so the adder computes A + B; with M = 1 the XORs deliver B-bar and the carry-in is 1, so it computes A + B-bar + 1, which is A + (-B). No extra hardware is spent on the +1 at all.

The cost of subtraction is therefore four XOR gates and one wire on top of an adder — a 74HCT86 (quad 2-input XOR) plus a 74HCT283 (4-bit adder), see device-pinouts.

Multiplexer (mux)

A multiplexer — also called a data selector — has:

  • \(2^n\) data inputs,
  • 1 output,
  • \(n\) control (or select) inputs, which select one of the data inputs to be “sent” or “steered” to the output.

Figure 217: The multiplexer logic symbol at two sizes, 4-to-1 and 2-to-1. Data inputs enter the tall left edge, the single output leaves the short right edge, and the select inputs enter from underneath. The number of select lines is what fixes the size: n selects steer 2^n data inputs.

4-to-1 multiplexer

Data inputs \(D_0 \ldots D_3\), select inputs \(S_1 S_0\), output \(F\). The logic symbol is the characteristic trapezoid with the data inputs on the wide (left) edge, \(F\) on the narrow (right) edge, and the select inputs entering the bottom.

Function table:

\(S_1\) \(S_0\) \(F\)
0 0 \(D_0\)
0 1 \(D_1\)
1 0 \(D_2\)
1 1 \(D_3\)

This is a function table, not a full truth table — the full truth table would need \(2^6 = 64\) rows for the six inputs \(S_1, S_0, D_0, D_1, D_2, D_3\). The function table’s four rows say the same thing far more compactly, which is why it is what gets drawn.

4-to-1 mux logic circuit implementation

  • \(S_1\) and \(S_0\) each feed an inverter, giving \(\bar S_1\) and \(\bar S_0\) as well as the true forms.
  • Four 3-input AND gates, one per data input. Each AND gate takes its data input plus the select-literal pair that identifies it: \(D_0\) with \(\bar S_1 \bar S_0\), \(D_1\) with \(\bar S_1 S_0\), \(D_2\) with \(S_1 \bar S_0\), \(D_3\) with \(S_1 S_0\).
  • The four AND outputs feed a single 4-input OR gate whose output is \(F\).

Figure 218: A 4-to-1 multiplexer built from gates. The two inverters generate the complemented selects; the four vertical rails carry S1, S1-bar, S0 and S0-bar past every AND gate; each AND gate is one data input gated by the one select combination that names it, and the OR gate collects them. Only the dots are connections — every other crossing is two wires passing.

That is exactly the sum-of-products form:

\[F = D_0 \bar S_1 \bar S_0 + D_1 \bar S_1 S_0 + D_2 S_1 \bar S_0 + D_3 S_1 S_0\]

Only the AND gate whose select literals match the current \(S_1 S_0\) can be 1, so exactly one data input reaches the OR gate at a time. The other three AND gates output 0, and \(0\) is the identity for OR, so they contribute nothing.

The gate-level version needs 3-input ANDs and a 4-input OR, neither of which exists in the lab kit (see device-pinouts) — building this from the available 2-input chips means cascading them.

2-to-1 multiplexer

Data inputs \(D_0\) and \(D_1\), one control input \(S_0\), output \(F\).

Function table:

\(S_0\) \(F\)
0 \(D_0\)
1 \(D_1\)

Expanded to a full truth table over all three inputs (\(2^3 = 8\) rows):

\(S_0\) \(D_0\) \(D_1\) \(F\)
0 0 0 0
0 0 1 0
0 1 0 1
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1

i.e. \(F = D_0 \bar S_0 + D_1 S_0\). When \(S_0 = 0\) the output tracks \(D_0\) and ignores \(D_1\); when \(S_0 = 1\) it tracks \(D_1\) and ignores \(D_0\).

A quad 2-input multiplexer is available as an off-the-shelf IC — the 74HCT157, see device-pinouts.

Using a mux to implement a logic function

Because the data inputs can be tied to constant 0 or 1, an \(n\)-select mux with its selects wired to the function’s variables can implement any function of those \(n\) variables: set data input \(D_i\) to the value the function should take when the selects equal \(i\). The function table is the truth table of the function, read off directly. See the worked question in 2026-08-06-combinational-logic.

Decoder

A decoder converts an \(n\)-bit input to a logic 1 on exactly one of its \(2^n\) outputs (the one whose index equals the input value); all other outputs are 0.

Figure 219: The decoder as a block: n inputs in, 2^n outputs out, and the shape widens accordingly. It is the mux’s opposite — a mux funnels 2^n inputs down to one output under n selects, a decoder fans n inputs out to 2^n outputs.

3-to-8 decoder

Inputs \(A, B, C\) (with \(A\) the most significant), outputs \(D_0 \ldots D_7\).

A B C \(D_0\) \(D_1\) \(D_2\) \(D_3\) \(D_4\) \(D_5\) \(D_6\) \(D_7\)
0 0 0 1 0 0 0 0 0 0 0
0 0 1 0 1 0 0 0 0 0 0
0 1 0 0 0 1 0 0 0 0 0
0 1 1 0 0 0 1 0 0 0 0
1 0 0 0 0 0 0 1 0 0 0
1 0 1 0 0 0 0 0 1 0 0
1 1 0 0 0 0 0 0 0 1 0
1 1 1 0 0 0 0 0 0 0 1

The 1 always sits in the column whose index is the binary value of \(ABC\).

Each row of the table is one minterm: the top row is \(\bar A \bar B \bar C\) and the bottom row is \(ABC\).

3-to-8 decoder logic circuit implementation

  • Each of \(A\), \(B\), \(C\) is fanned out to an inverter, so all six literals \(A, \bar A, B, \bar B, C, \bar C\) are available on a vertical bus.
  • Eight 3-input AND gates, one per output. Each taps the three literals matching its index:

\[D_0 = \bar A \bar B \bar C, \quad D_1 = \bar A \bar B C, \quad D_2 = \bar A B \bar C, \quad D_3 = \bar A B C\] \[D_4 = A \bar B \bar C, \quad D_5 = A \bar B C, \quad D_6 = A B \bar C, \quad D_7 = ABC\]

Figure 220: A 3-to-8 decoder built from gates. Three inverters generate the complements onto six vertical rails; each of the eight AND gates taps the one literal triple that matches its index, so it is the minterm for that input combination. Exactly one AND gate can be high at a time, which is the decoder’s defining property.

Each AND gate is the minterm for one input combination, so exactly one is high at any time.

Using a decoder to implement a logic function

Because a decoder hands you every minterm of its inputs on a separate wire, any function of those inputs is just an OR of the minterm outputs whose truth-table rows are 1. For example, take

\[F = \bar A \bar B \bar C + ABC\]

which is \(D_0 + D_7\) — one OR gate on two decoder outputs, with nothing else needed.

Figure 221: A function built on a decoder: F = A-bar B-bar C-bar + ABC is D0 + D7, so it costs a single OR gate on top of the decoder. Any function of A, B and C can be built this way — pick out the outputs for its true rows and OR them together.

This is the same idea as the mux trick above, approached from the other side: a mux picks one of \(2^n\) values, a decoder hands you all \(2^n\) minterms and you OR the ones you want.

See also

Compilation and Linking

How a C program turns into the machine code in the AVR’s flash. This note covers compiling against interpreting, where the compiler puts global, local and static variables, object files and their six sections, the linker’s two jobs (relocating and resolving), libraries, how header files differ from libraries, and static against dynamic linking. The assembler’s part, with its two passes and symbol table, is in assembly-process. First met in 2026-10-15-compilation-and-linking.

Compiled or interpreted

A processor runs machine code and nothing else. The fetch-decode-execute cycle (fetch-decode-execute-cycle) reads instruction words from memory, and nothing in it knows the program was once written in C. A program in a high-level language reaches the processor in one of two ways.

  • Compilation translates the whole program into machine code before it runs, often by way of assembly language. The machine code then runs directly on the processor. C works this way.
  • Interpretation never turns the program into machine code. Another program, the interpreter, reads the source and carries out each statement when it gets to it. The interpreter is itself machine code, and it is the interpreter that the processor runs. Python, Java and MATLAB work this way.
Compiled Interpreted
What the processor runs the program’s own machine code the interpreter’s machine code
When translation happens once, before the program runs every time a statement is executed
Speed fast slow
Portability the machine code suits one processor only runs anywhere an interpreter exists

Why interpreting is slow. Every time a statement is executed, the interpreter has to work out again what the statement means and then carry it out. That costs many of its own instructions per statement, and inside a loop it is repeated on every pass. A compiler does that work once, ahead of time.

Why it is portable. The program never becomes machine code, so nothing in it is tied to one instruction set. Moving it to a new processor only needs an interpreter built for that processor.

Bytecode and just-in-time compilation

Java and Python take a route in between. The source is first compiled, but not into machine code. It becomes bytecode, the instruction set of an imaginary machine. Bytecode is the same on every platform, so a compiled Java program is portable across all of them.

The bytecode is then run by a virtual machine, which is an interpreter for bytecode. The Java Virtual Machine is the one for Java. Running bytecode is faster than interpreting source text, because the parsing has already been done, but it is still interpretation.

To win back the speed, the virtual machine watches which parts of the program run most often and compiles them into real machine code while the program is running. This is just-in-time (JIT) compilation. Once a part has been JIT-compiled, it runs directly on the processor like compiled code. Standard Python interprets its bytecode, and a JIT compiler such as Numba can compile chosen Python functions to machine code in the same way.

The toolchain

Figure 222: How a three-file C program becomes a running program. Each source file goes through the first three steps by itself. The preprocessor pastes in headers and expands macros, the compiler turns C into assembly, and the assembler turns assembly into an object file, which is machine code plus the information needed to link it. Only the linker sees the whole program. It joins the object files to each other and to the library members they use, fixes up every address, and writes one executable. That executable is then loaded into memory, which on the AVR means programming it into flash. Changing one source file means repeating the first three steps for that file alone, then linking again.

Step Takes Produces Notes
Preprocess a .c file C with every #include pasted in and every macro expanded c-preprocessor-and-avr-headers
Compile that C assembly language maps variables to memory, and translates each statement into instructions
Assemble the assembly an object file, .o assembly-process
Link all the object files, plus the library one executable relocates and resolves addresses
Load the executable the program in memory, ready to run on the AVR, the executable is programmed into flash

Some compilers write machine code directly and never produce assembly text. The object file that comes out is the same either way, so the three middle steps are often just called “compiling”. In the simplified view the compiler itself does two things, mapping variables to memory and translating C into assembler instructions. Turning those instructions into machine code is the assembler’s work.

With the AVR GCC toolchain the object files and the executable are ELF files. The .hex file that gets programmed into flash is extracted from the ELF executable.

How a compiler maps variables to memory

The compiler decides where each variable goes by how long it has to exist.

Declared Lives Stored Address
outside every function: a global for the whole run in the fixed data area, which starts at the bottom of SRAM fixed before the program runs
inside a function: a local only while that call is running in the call’s stack frame depends on how deep the stack is at the call
inside a function, marked static for the whole run, and it keeps its value between calls with the globals fixed
nowhere: obtained from malloc() until it is given back on the heap handed out while the program runs

Globals. A global can be used at any moment from any function, so it needs one address that never changes. The compiler reserves as many bytes as the type needs (c-language-basics), one variable after another, from the start of SRAM. On the ATmega324A that is 0x0100 = 256, because addresses 0 to 255 are taken by the registers and the I/O registers (memory-models). It is the same thing an assembly programmer does with .dseg and .byte.

Locals. A local exists only while its function is running, and a recursive function can have several calls running at once, each needing its own copy. So the compiler cannot give it a fixed address. Instead, each call builds a stack frame, a block on the stack holding that call’s arguments, its return address and its local variables. The return takes the frame away again (procedures-and-the-stack). The same local therefore sits at different addresses on different calls.

static locals. static inside a function keeps the name private to the function but gives the variable a global’s lifetime. It is stored with the globals, at a fixed address, and is never part of a frame. That is why it still holds its value the next time the function is called.

static on a global means something else. The variable is stored exactly like any global, but its name is private to its own source file. It is left out of the object file’s entry point table (below), so no other file can link to it.

The heap and the stack grow toward each other. The heap starts above the globals and grows toward higher addresses. The stack starts at the top of SRAM (RAMEND) and grows down. The free memory between them shrinks from both ends, and if the two meet, that is a stack overflow. Nothing on the chip detects it. The first sign is usually a global or heap variable changing for no reason.

Figure 223: Where each kind of C variable ends up in the ATmega324A’s data memory, with the lowest address at the top. Globals and static variables are given fixed addresses from 0x0100, the first SRAM byte, so a static local such as c sits among the globals even though only its own function can name it. The heap, which malloc() hands out while the program runs, grows down the page toward the stack. The stack grows up the page from RAMEND. Each running call has a frame on it, and the frame of function() holds its locals a and b. When function() returns, that frame is gone. If the stack and the heap meet, the stack has overflowed.

Object files

A program of any size is split into several source files, and it pays to compile or assemble each one separately and then link them together. Change one file and only that file has to be compiled again. The others’ object files are reused as they are.

The price is that when a file is compiled, nobody knows where its code will end up. The file is translated as if it started at address 0. Every address inside it is relative to its own start, and any symbol defined in another file has no address at all yet. Once the linker has decided where everything goes, these addresses have to be fixed. A file that carries enough information for that fixing is a relocatable object module. “Object module” and “object file” mean the same thing.

So an object file is machine code plus information for the linker. There are many formats for it: a.out, COFF and ELF are object file formats, and DWARF is a format for debugging information, usually carried inside ELF files.

The six sections

Figure 224: The six sections of a relocatable object module, numbered from the bottom. Only section 4 is program: the machine instructions and constants, assembled as if the module began at address 0. The other five are information for the linker. They say what the module is called and where its parts are in the file (1), which of its symbols other modules may use (2), which symbols it uses but does not define (3), which addresses in section 4 have to be moved when the module is moved (5), and where execution starts (6). Linking reads 1, 2, 3, 5 and 6 to decide how to rewrite 4.

1. Identification. The name of the module, where each of the other sections is in the file, and the date it was assembled.

2. Entry point table. The symbols defined in this module that other modules may refer to, with their values. A value is an address: a procedure’s entry point, or a variable’s location. It is relative to the beginning of this object module. A file that defines a procedure abs_value at its address 10 has the entry abs_value 10. Anything not listed, such as a static global or a label used only inside the module, cannot be reached from another file.

3. External reference table. The symbols used in this module but not defined in it, both procedure names and variables, and for each one the list of instructions that use it. Those instructions are the places the linker will have to fill in once it knows the address.

One module’s entry point is another module’s external reference. If module A defines SUM and module B calls it, SUM appears in A’s entry point table and in B’s external reference table.

4. Machine instructions and constants. The assembled code and constants: the code segment, and the data segment holding the initialised and the uninitialised data. An initialised global such as int n = 5; needs its starting value stored in the file. An uninitialised one needs only its size. The addresses used in this code are not yet correct. They were worked out as if the module started at 0, so they need relocation.

5. Relocation dictionary. The list of addresses in section 4 that need to be relocated. When the module is placed, a relocation constant is added to the instruction or data at each of those addresses. There is one constant for code and a different one for data, because a module’s code goes in program memory and its data in data memory, and the two start in different places.

6. End of module. Possibly a checksum, to catch a corrupted file, and the address at which execution starts.

The linker

The linker combines object modules, the program’s own and any it needs from libraries, into a single executable binary program of machine code.

Its problem is the assembler’s problem again, one level up. That is the external reference problem: symbols are used before their values are known. Module A can call a procedure in module B before the linker has even read B. So the linker, like the assembler, works in two passes (assembly-process).

Pass 1: lay the program out.

  1. Read each module’s sizes and give it a place, in link order. Each module’s code starts where the previous module’s code ended, and the same goes for data. These starting addresses are the module’s two relocation constants.
  2. Read every entry point table. Add each symbol to one global symbol table, with its final address: its value relative to its module, plus that module’s starting address.

Pass 2: copy and patch.

  1. Copy each module’s section 4 to its place.
  2. Relocate. For each address in the module’s relocation dictionary, add the module’s constant, the code constant for a code address and the data constant for a data address.
  3. Resolve. For each external reference, look the symbol up in the global table and write its final address into every instruction listed against it. A symbol that no module defines cannot be resolved, so linking fails with an “undefined reference” error.

The two words to keep straight:

Relocating = adding a constant: fixing an address that points into the module’s own code or data, which moved when the module moved. Resolving = finding the value of an external address: filling in an address that points into another module.

Where a module starts follows from the order alone. A module’s code starts at the program start plus the code sizes of every module linked before it, and its data starts at the data start plus the data sizes of those same modules. Code and data are counted separately, in their own units: on the AVR, words of program memory and bytes of data memory (memory-models).

Worked: linking four modules

Four object modules, each assembled from address 0. Their lengths are A = 400, B = 600, C = 500, D = 300. Each holds a branch within itself, a data move, and (apart from D) a call to the next module.

Module At Instruction
A 0 BRANCH TO 200
A 200 MOVE P TO X
A 300 CALL B
B 0 BRANCH TO 300
B 300 MOVE Q TO X
B 500 CALL C
C 0 BRANCH TO 200
C 200 MOVE R TO X
C 400 CALL D
D 0 BRANCH TO 200
D 200 MOVE S TO X

They are linked in the order A, B, C, D. The first 100 addresses hold start-up code, the code that runs before main (on the AVR it sets the stack pointer and prepares the data), so A starts at 100.

Pass 1: place the modules. Each starts where the previous one ends.

Module Length Starts at Ends at Relocation constant
A 400 100 499 +100
B 600 100 + 400 = 500 1099 +500
C 500 500 + 600 = 1100 1599 +1100
D 300 1100 + 500 = 1600 1899 +1600

The global symbol table holds the module names as entry points: A = 100, B = 500, C = 1100, D = 1600. The program ends at 1899, and 1900 is the first free address.

Pass 2: patch each instruction. An instruction moves to its offset plus its module’s start. A branch inside a module is relocated: the target moves by the same constant as the instruction, so it still lands on the same MOVE. A call to another module is resolved from the symbol table.

New address Was Becomes Because
100 A: BRANCH TO 200 BRANCH TO 300 relocate: 200 + 100
300 A: MOVE P TO X MOVE P TO X no code address in it
400 A: CALL B CALL 500 resolve: B starts at 500
500 B: BRANCH TO 300 BRANCH TO 800 relocate: 300 + 500
800 B: MOVE Q TO X MOVE Q TO X no code address in it
1000 B: CALL C CALL 1100 resolve: C starts at 1100
1100 C: BRANCH TO 200 BRANCH TO 1300 relocate: 200 + 1100
1300 C: MOVE R TO X MOVE R TO X no code address in it
1500 C: CALL D CALL 1600 resolve: D starts at 1600
1600 D: BRANCH TO 200 BRANCH TO 1800 relocate: 200 + 1600
1800 D: MOVE S TO X MOVE S TO X no code address in it

B’s constant, 500, is the start-up code plus all of A: 100 + 400. Every branch ends up pointing at the instruction it pointed at before: A’s branch at 100 reaches A’s MOVE at 300, and B’s at 500 reaches B’s MOVE at 800. The MOVEs name data, P, Q, R, S and X. Those addresses are fixed in the same way with each module’s data constant, which this example leaves out so that only the code is followed.

Figure 225: Linking four object modules in the order A, B, C, D, with addresses increasing up the page and start-up code in 0 to 99. Left: after the first pass. Every module has its place, each starting where the one before it ends, but the instructions are still exactly as assembled. A’s branch at 100 still names 200, its target counted from A’s own 0, and 200 is now in the middle of A, not at its MOVE. Each call still names a module, not an address. Right: after the second pass. Each branch within a module has been relocated by its module’s starting address, so it lands on that module’s MOVE again, and each call to another module has been resolved to that module’s start. The bold operands are the ones the linker rewrote.

Worked: where each module starts

Three modules have these sizes. Code is measured in words, because AVR program memory holds 16-bit words, and data in bytes.

Module Code size (words) Data size (bytes)
1 45 17
2 67 5
3 100 25

They are linked in the order 2, 1, 3, starting at program address 62 and data address 256. Where does each module’s code and data start, and where do two sample references inside module 1 end up?

Lay them out in link order, keeping a running total for each memory:

Module Code Data Code constant Data constant
2 62 to 62 + 67 − 1 = 128 256 to 256 + 5 − 1 = 260 +62 +256
1 129 to 129 + 45 − 1 = 173 261 to 261 + 17 − 1 = 277 +129 +261
3 174 to 174 + 100 − 1 = 273 278 to 278 + 25 − 1 = 302 +174 +278

The next free code word is 274 and the next free data byte is 303. Both totals come out the same as for any other order, because the same three sizes are added up. Only where each module falls changes.

Relocate inside module 1. Suppose module 1 has, at its own word 20, a branch to its own word 40, and at its own word 30, a load from its own data byte 4.

  • The branch moves to 20 + 129 = 149, and its target is relocated by the same code constant, 40 + 129 = 169.
  • The load moves to 30 + 129 = 159, and its operand is a data address, relocated by the data constant: 4 + 261 = 265.

Adding the code constant to the data address would give 133, and the load would read the wrong byte. This is why the relocation dictionary has to say whether each entry is a code address or a data address.

Why 62 and 256? On the ATmega324A, program words 0 to 61 (0x0000 to 0x003D) are the interrupt vector table (avr-interrupts), so 0x003E = 62 is the first free word. Data addresses 0 to 255 are registers and I/O, so 0x0100 = 256 is the first byte of SRAM.

Libraries

A library is a collection of object files with an additional index. It provides useful functions and procedures that have already been written, tested and compiled. The rule is not to reinvent the wheel: use library code where it exists.

The index maps each symbol to the member object file that defines it. When an external reference is still unresolved, say a call to printf, the linker looks the name up in the index, takes that one member, and links it in like any other module. The rest of the library stays out of the program.

The standard C library is the one every C program can count on. It covers:

  • standard input and output (stdio.h: printf, getchar, …)
  • string handling (string.h: strlen, strcpy, …)
  • date and time functions (time.h)
  • general utilities (stdlib.h: malloc, abs, atoi, …)

On the AVR it is provided by avr-libc, which also supplies the avr/io.h and avr/interrupt.h headers.

Header files are not the library

The two are easy to mix up, because #include <stdio.h> is what lets a program call printf.

A header file (.h)

  • defines useful preprocessor macros,
  • declares the functions that are in the library, as function prototypes, and
  • declares variables that are available externally, with extern.

The library is the collection of object files that implement those functions.

A declaration says what a name is and what type it has, so the compiler can check every use and generate the call. It contains no code, so the call still has nowhere to go. The header is therefore read by the compiler, and the library is read by the linker. Each kind of mistake shows up at its own step:

Missing When it shows Typical message
the header compiling implicit declaration of function printf
the library, or the file that defines the function linking undefined reference to printf

How a header gets pasted in is covered in c-preprocessor-and-avr-headers.

Static and dynamic linking

Everything so far is static linking. All the object code, the library’s and the main program’s, is joined into one binary before the program ever runs.

In dynamic linking, linking happens at run time instead: a library procedure is linked when it is first called. The executable holds only a reference to it, and the library stays in a separate file that is loaded when the program needs it. DLLs (dynamic-link libraries) on Windows work this way, and so do shared libraries (.so files) on Linux.

Static Dynamic
Library code is joined in when the program is linked when the procedure is first called
Library code is stored inside every executable that uses it once, in its own file, shared
Executable size larger smaller
Updating the library means relinking each program takes effect in every program at once

Its advantages:

  • It saves space. Libraries are not linked into the executable, so ten programs that use the same library share one copy of it.
  • The library can be updated independently of the programs that use it. A bug fixed in the DLL is fixed in all of them, without relinking anything.

The second advantage is also its weakness. A program tested with one version of a library can break when another installation replaces that library with a version that behaves differently. On earlier versions of Windows this was common enough to be called “DLL hell”.

Figure 226: The same two programs, both calling printf, linked statically and dynamically. Static linking copies printf’s object code into each executable when it is linked, so each program carries its own copy and is complete in itself. Dynamic linking leaves a reference in each executable and keeps a single copy of printf in a shared library file. The reference is linked to that copy at run time, when printf is first called. That saves space, and updating the shared file changes the printf both programs get, for better or worse.

The ATmega324A has no operating system to load a library at run time, so every AVR program is linked statically. Everything it will ever call is already in flash.

Common mistakes

  • Treating the header as the library. #include <math.h> makes sqrt compile. It does not supply sqrt. Without the library the link fails with an undefined reference.
  • Counting from the wrong module. A module’s start depends on the modules linked before it in link order, not on its number. In the order 3, 2, 1, module 2 starts after module 3.
  • Mixing code and data sizes. The code start adds up code sizes only, and the data start adds up data sizes only. On the AVR they are not even in the same unit: words against bytes.
  • Off by one at a boundary. A module of size \(n\) starting at \(s\) occupies \(s\) to \(s + n - 1\), and the next module starts at \(s + n\).
  • Relocating an external reference. A call into another module is not fixed by adding this module’s constant. Its address comes from the symbol table, which holds the other module’s start plus the symbol’s offset in it.
  • Relocating a data address with the code constant, or the other way round.
  • Expecting a local variable to keep its value between calls. The frame is gone when the function returns. Use static if the value must persist.
  • Returning a pointer to a local. The address points into a frame that no longer exists, and the next call will overwrite it.
  • Thinking “interpreted” means “never compiled”. Java is compiled, to bytecode, and a JIT compiles parts of it again to machine code. What makes it interpreted is that the virtual machine, and not the processor, runs the bytecode.

See also

Counters

A counter is a multi-bit register that goes through a determined sequence of states (values) upon the application of input (clock) pulses. It is a synchronous sequential circuit built from D flip-flops plus some combinational logic in the feedback path.

Binary counters

A counter which follows the binary number sequence is a binary counter.

An \(n\)-bit binary counter:

  • has \(n\) flip-flops;
  • has \(2^n\) different states;
  • counts from \(0\) to \(2^n - 1\), then wraps back to \(0\).

For example, a 2-bit binary counter counts

\[00 \to 01 \to 10 \to 11 \to 00 \to \ldots\]

i.e. \(0 \to 1 \to 2 \to 3 \to 0 \to \ldots\)

4-bit binary counter — counting sequence

Bit 3 Bit 2 Bit 1 Bit 0 Value
0 0 0 0 0
0 0 0 1 1
0 0 1 0 2
0 0 1 1 3
0 1 0 0 4
0 1 0 1 5
0 1 1 0 6
0 1 1 1 7
1 0 0 0 8
1 0 0 1 9
1 0 1 0 10
1 0 1 1 11
1 1 0 0 12
1 1 0 1 13
1 1 1 0 14
1 1 1 1 15
0 0 0 0 0

Each bit toggles at half the rate of the bit to its right — bit 0 changes every count, bit 1 every second count, bit 2 every fourth, bit 3 every eighth.

Key points

  • The next state is a function of the present state (and possibly of external inputs).
  • The count sequence can be the binary numbers but does not have to be — if it is, the counter is a binary counter; otherwise it is just some arbitrary cycle through states.
  • These circuits are synchronous: all flip-flops share the same clock.
  • Asynchronous counters exist too, but are not discussed in this course.

State: the design idea

This is the whole trick, and it is what makes counter design mechanical:

  • The values stored in the flip-flops are the current (present) state of the circuit.
  • The \(D\) inputs to the flip-flops are the next state — whatever is sitting on \(D\) at the clock edge becomes the new state.
  • The \(D\) inputs are some combinational function of the current state (and of any external inputs).

So for a counter with state bits \(Q_{n-1} \ldots Q_1 Q_0\), designing the counter means finding \(n\) Boolean expressions

\[D_i = f_i(Q_{n-1}, \ldots, Q_1, Q_0)\]

and building each one out of gates.

Figure 227: A counter is the general sequential-circuit block diagram with the external inputs deleted. That diagram, as Mano draws it, is a combinational circuit feeding flip-flops, the flip-flop outputs routed back round to the combinational circuit, and the clock entering the flip-flops on its own labelled stub. A counter may or may not have external inputs; removing them, as here, is what makes the design mechanical: with nothing else to depend on, each D is a function of the Q values alone, so the present-state/next-state table below is a complete specification of the circuit.

Design recipe

  1. Write down the count sequence you want, as a cycle of state values.
  2. Build a present-state / next-state table. One row per possible state — all \(2^n\) of them, not just the ones in your sequence. Columns: present state \(Q_{n-1}\ldots Q_0\), then next state \(D_{n-1}\ldots D_0\). Fill each next-state entry by reading off what follows that state in your sequence.
  3. Handle unused states. If your sequence doesn’t use all \(2^n\) states, the next state for the unused ones is a don’t-care (X). You may set each X to whatever makes the algebra simplest — but check afterwards where the unused state actually goes, because a self-correcting counter (one whose unused states lead back into the cycle) is nicer than one that can get stuck.
  4. Read each \(D\) column as a Boolean function of the \(Q\)s. The table is a truth table with the \(Q\)s as inputs and \(D_i\) as the output, so write it in sum-of-products form: OR together one AND term per row where \(D_i = 1\). See boolean-algebra.
  5. Simplify each expression using the Boolean algebra laws (and the don’t-cares), then draw the circuit: the combinational logic for \(D_i\) feeding flip-flop \(i\), with every flip-flop on a common clock. See circuit-schematics for schematic conventions and device-pinouts for the 74HCT74 / 74HCT175 D flip-flop packages.

The smallest case falls straight out of the recipe: a 1-bit counter counts \(0 \to 1 \to 0 \to \ldots\), so its next state is always the complement of its present state, giving \(D = \bar Q\) — a single flip-flop with its \(\bar Q\) output wired back to its own \(D\) input (a toggle).

Worked example — a 2-bit counter for \(00 \to 10 \to 01 \to 00\)

Step 1–2 — present-state / next-state table. The sequence uses three of the four states; \(11\) is unused, so its next state is a don’t-care.

\(Q_1\) \(Q_0\) \(D_1\) \(D_0\) comment
0 0 1 0 \(00 \to 10\)
0 1 0 0 \(01 \to 00\)
1 0 0 1 \(10 \to 01\)
1 1 X X unused state

Step 4 — read off the columns.

\(D_1\) is 1 only in the row \(Q_1Q_0 = 00\). Making the don’t-care 1 would give \(Q_1 \odot Q_0\) (XNOR), which is no simpler, so take the don’t-care as 0 (\(X_1 = 0\)):

\[D_1 = \bar Q_1 \bar Q_0\]

\(D_0\) is 1 only in the row \(Q_1Q_0 = 10\), which gives \(D_0 = Q_1\bar Q_0\). Here the don’t-care does help: setting it to 1 (\(X_0 = 1\)) makes \(D_0 = 1\) for both rows with \(Q_1 = 1\), so

\[D_0 = Q_1\]

Step 5 — the circuit. Two D flip-flops on a common clock. Flip-flop 0’s \(D\) input is wired directly to flip-flop 1’s \(Q_1\) output — no gate at all. Flip-flop 1’s \(D\) input is driven by a 2-input NOR of \(Q_1\) and \(Q_0\) (since \(\bar Q_1 \bar Q_0 = \overline{Q_1 + Q_0}\)), or equivalently by an AND of the two \(\bar Q\) outputs.

Figure 228: The whole counter, drawn from the derivation above. Each Q runs back to a vertical rail that the next-state logic taps, which is the physical form of the feedback loop in the block diagram earlier: D0 is FF1’s Q wired straight across with no gate at all, and D1 is one NOR gate. Dots are connections; where the Q0 rail and the CLOCK rail cross the D0 wire there is no dot and no connection. The circuit takes the NOR form of D1; an AND of the two Q-bar outputs is the same function and would need the flip-flops’ Q-bar pins instead.

Check, including the unused state:

present \(D_1 D_0\) next
00 1 0 10
10 0 1 01
01 0 0 00
11 0 1 01

The cycle is right, and the unused state falls into the cycle on the next clock edge, \(11 \to 01\), so the counter is self-correcting — a robust design. (Choosing \(D_0 = Q_1\bar Q_0\) instead — don’t-care set to 0 — would send \(11 \to 00\), also fine, at the cost of a whole extra gate: an AND fed from \(Q_1\) and the flip-flop’s \(\bar Q_0\) pin, where \(D_0 = Q_1\) needs no gate at all.)

Applied exercise

week4-lab-lab-7-exercises is exactly this recipe at \(n = 3\): design a 3-bit synchronous counter that steps through an allocated 7-state sequence, with the eighth (missing) state treated as a don’t-care.

CPU Organisation

Where the digital logic of the first half of the course ends up: the blocks a processor is made of, and what each one holds. See arithmetic-logic-unit for the ALU in detail and fetch-decode-execute-cycle for what the control unit does with all of it.

Computer organisation

A simplified view of a whole machine: a CPU connected by external buses to main memory, secondary storage and IO devices, with internal buses wiring together the CPU’s own blocks.

Figure 229: Simplified computer organisation. The CPU’s three blocks are joined by internal buses; a single external bus carries everything between the CPU and the rest of the machine. Main memory holds both the program and the data operated on, so it is both program memory and data memory.

Main memory holds both the program and the data: the instructions to be fetched and the values to be operated on.

Parts of a CPU

Block Role
Control Unit Fetches instructions from memory, and makes the ALU and the registers perform the instruction
ALU Performs arithmetic and logical operations
Registers High-speed memory — stores temporary results and control information

How many registers, and how wide, varies enormously with the machine: a small CPU may have 8 × 8-bit registers, a large one 64 × 32-bit registers. The AVR used later in this course has 32 registers (R0–R31) and an 8-bit word, so it also has an 8-bit ALU.

Registers

Registers are temporary storage locations inside the CPU. Two types:

General purpose registers hold the data to be operated on (e.g. data read from memory) and the results of operations. Collectively they are the register file, and their width is the CPU word size.

Special purpose registers are used by the system rather than by the program’s arithmetic:

Register Holds
Program Counter (PC) the address of the next instruction to be fetched from memory
Instruction Register (IR) the current instruction

Figure 230: The two types of register, and why the distinction matters. A general purpose register is one anonymous row of the file, as wide as the machine word and picked by number; a special purpose register is named, and what it holds is interpreted — the PC as an address into program memory, the IR as an instruction to be decoded. The particular bit patterns shown in memory are illustrative only.

A third special purpose register, the status register, records what the last ALU operation did — see fetch-decode-execute-cycle. PC and IR are the two the fetch step manipulates directly.

See also

CSSE2010 Diagram Notation

The drawing conventions this course actually uses, inferred from its own materials. This is the reference every later diagram in CSSE2010 should be checked against.

Scope. This note covers the diagram families that the two existing notation notes do not: gate symbols and logic diagrams, timing/waveform diagrams, state diagrams and state tables, block and datapath diagrams, register/memory layout diagrams, and the AVR architecture figures. It also records the algebraic and textual notation the figures depend on. For circuit-schematic rules (device IDs, gate letters, pin numbers, junction dots, power blocks, IO-board input/output pentagons) see circuit-schematics; for the 74-series pinouts and their schematic symbols see device-pinouts. Those two are not repeated here.

What was read

An honest statement of the sample, because most of what follows is inferred from drawings rather than stated in prose.

Guides — all three read in full (9 of 9 pages):

  • CSSE2010/CSSE7201 Device Pinouts and Symbols (v4), pp. 1–2
  • CSSE2010/CSSE7201 — Guide to Drawing Circuit Schematics (v2.3, Semester One 2016), pp. 1–2
  • I/O Board User Manual, pp. 1–5

Lecture decks — 221 of 246 pages:

Deck Pages read of
L01 Intro and Binary Numbers 1–20 21
L02 Intro to Logic Gates 1–24 24
L03 Binary Arithmetic 8–17 17
L04 Combinational Logic 1–19 19
L05 Flip-Flops 4–19 19
L06 Shift Registers 3–17 17
L07 Counters 3–17 17
L08 State Machines 2–21 21
L09 ALU and Control Unit 3–22 22
L10 AVR Introduction 3–19 19
L11 ISA Part 1 3–28 28
L12 ISA Part 2 2–20 22

Unread: L01 p21, L03 pp1–7, L05 pp1–3, L12 pp21–22 — title, outline and admin pages in every case except L03 pp1–7 (number-representation recap, no new diagram family). Labs, past papers and the course profile were not sampled at all.

Citation format below: “L04 s10” means lecture deck 04, slide 10. Slide numbers printed on the slides match the PDF page numbers in every deck checked.

The course ships no notation guide for these diagram families

The three guides are hardware documents. Between them they settle schematic layout, device labelling, pin numbering and the physical IO board — nothing about gate-symbol family, waveform drawing, state diagrams, block diagrams or memory layout. The Device Pinouts and Symbols sheet comes closest: it has a “Logic Diagram Symbol” column (p. 1–2) that shows the gate shapes and the flip-flop/mux/adder block symbols, but it gives no rules, only examples.

So: everything in the sections below except the schematic rules is inferred from the drawings, and every entry is cited so you can check the inference.

Figure sources the slides cite

This matters more than it looks. L01 s8 says “No textbook required” — yet four different figure sources are credited across the semester, each bringing its own drawing style. There is no single house style.

Source, quoted as printed Where What it supplies
[Figure from Mano, "Digital Design", 3rd edition] L03 s16, L04 s4, L04 s10, L05 s17, L08 s3 Ripple-carry adder, 4-to-1 mux circuit, sequential-circuit block diagram
[Mano, Digital Design, 3rd ed.] (short form) L06 s6, L06 s8, L06 s9 4-bit register, 4-bit shift register
Images taken from Instructor Resources of Digital Fundamentals, Thomas L. Flyod, Pearson Educations Inc., 2015 (misspelling in the original) L07 s4, s5, s7 Shift-register type diagrams, digital-system application block diagram
[Figure from Tanenbaum, "Structured Computer Organization"] — no edition given L09 s8 Full ALU internal logic diagram
[From ATmega324A datasheet] L11 s14 AVR data and program memory maps
Some datasheet extracts follow (prose, not a caption) L10 s9, covering s10–s11 AVR CPU architecture, ATmega324A chip block diagram
Source: Google Images L01 s4 Photo collages only, not line art

Tanenbaum is also cited in prose twice as the source of terminology, not figures: (Tanenbaum calls this Program Status Word) (L11 s19) and These addressing mode names are as per Tanenbaum "Structured Computer Organization" (L12 s16).

Consequence for a new diagram: the block-diagram idiom the course leans on most is Mano’s (five citations across four decks). If you redraw a block diagram and want it to look native, match Mano, not Floyd. Floyd appears in exactly one deck. See Inconsistencies — this is not a settled question.

Gate symbols and logic diagrams

Symbol family

Distinctive-shape symbols throughout — no IEC rectangles anywhere. AND is a flat-backed body with a semicircular nose; OR has a concave back and a pointed nose; NOT is a triangle with a bubble on its tip; NAND/NOR/XNOR are the base shape with a bubble on the output; XOR/XNOR add a second concave arc set back from the input edge.

Evidence: the definitional table at L02 s6–s8 (all seven gates), then every working diagram in the course — L02 s14, s18, s19, s22, s23; L03 s15; L04 s10, s14; L05 s10, s11, s13; L07 s3, s12; L09 s6, s7, s8, s10; L11 s6. Also the “Logic Diagram Symbol” column of Device Pinouts and Symbols p. 1–2.

Consistency: holds without exception across all 221 deck pages and all three guides. The course never names the family; the identification as ANSI/IEEE Std 91 distinctive-shape is mine, from the shapes.

Inversion bubble

A small open circle at the symbol boundary, always. On outputs it makes NAND/NOR/XNOR/NOT (L02 s6–s8). It is also legitimate on inputs, to express a De Morgan equivalent: L02 s22 draws OR-with-inverted-inputs ≡ NAND, and AND-with-inverted-inputs ≡ NOR, with bubbles sitting on the input leads at the body edge. Active-low control pins carry it too (74HCT157 ENABLE, Device Pinouts p. 2). Consistency: every occurrence, throughout.

Flow direction and wiring

  • Inputs on the left, outputs on the right. Stated in words, twice: L02 s14 (“Inputs are conventionally on left” / “Outputs are conventionally on right”) and the Guide to Drawing Circuit Schematics p. 1. Held in every logic diagram sampled.
  • Orthogonal routing only — wires run horizontally and vertically, turning at right angles; no diagonal segments in any figure. (L02 s14, s18; L04 s14; L05 s13; L11 s6.)
  • Junction dot = connection. Crossing with no dot = no connection. L02 s14 labels both cases explicitly on the same figure (“Indicates Electrical Connection”, “No Connection”). Restated as error 2 of the schematics guide p. 2. Consistency: the single most-repeated drawing rule in the course.
  • One line weight for all signals in a gate-level diagram. Thick lines appear only in datapath block diagrams (see below).

Labelling inside a logic diagram

  • Gate-type names are written above the symbol only in the definitional table (L02 s6–s8: “AND”, “OR”, “NAND”, “NOR”, “XOR”, “XNOR”; the NOT symbol on s6 is left unnamed). In every working diagram the shape alone carries the function — no type label. (L02 s14, s18, s19; L03 s15; L04 s14; L09 s6.)
  • Signal names: single uppercase letters for primary inputs (A, B, C, D, E), and X, M, F or Z for outputs (L02 s6–s8, s14, s18; L03 s15; L04 s14). Complements carry an overline (Ā).
  • Intermediate signals are labelled on the wire, immediately at the gate’s output, with the expression they carry: AB, AC, AB + AC, B + C, A(B + C) (L02 s19; L05 s16; L06 s5), or written above the wire (ĀBC, AB̄C, ABC̄, ABC — L02 s18).
  • Numbered gates: where a figure needs to refer to individual gates it puts a bare arabic numeral inside the gate body (L02 s18: inverters 1–3, ANDs 4–7, OR 8). Seen once. Extrapolate with caution.
  • Signal rails: when one variable feeds many gates, it is run as a vertical rail crossing the whole figure, tapped with junction dots, and labelled at the top of the rail (L02 s18 — rails A B C Ā B̄ C̄; L04 s14, the 3-to-8 decoder, same idiom). Two instances, two decks.
  • Sub-figure labels are lowercase letters in parentheses, centred under each variant: (a) (b) (c) (d) (L02 s22; L05 s14, s15).

Block and MSI symbols

Multiplexer — trapezoid, wide edge left

Long parallel edge on the left carrying the data inputs stacked top-to-bottom (D0 … D3, or bare 0/1/2/3 when the inputs are anonymous); short parallel edge on the right with the single output; select inputs enter through the bottom sloping edge, labelled outside the body (S1 S0, SEL, DIRN, F1 F0).

Evidence: L04 s9, s10, s11, s12; L06 s12; L09 s6, s7, s10; L11 s6; Device Pinouts p. 2 (74HCT157, with SEL and ENABLE on the bottom edge). Consistency: five decks plus the guide — solid.

Decoder — trapezoid, wide edge right

The mirror flare: short edge on the left with the n inputs (A B C), long edge on the right with the 2ⁿ outputs (D0 … D7). (L04 s13.) Consistency: one figure only. The orientation is unmistakable in it, but it is a single instance.

Adder — trapezoid with a + in the body

Long edge left with the two operand groups and the carry-in at the top corner; short edge right with the sum group and the carry-out. A large + sits in the middle of the body. (L04 s7; Device Pinouts p. 2, 74HCT283.) The Floyd figure instead labels its adder block A Σ / B C_out (L07 s7) — see Inconsistencies.

D flip-flop — plain rectangle

D inside at the top-left, Q inside at the top-right, clock entering the lower-left edge, Q̄ under Q when the complement is needed. The triangular wedge (>) at the clock input means edge-triggered; no wedge means a level-triggered latch; a bubble in front of the wedge means falling-edge, no bubble means rising-edge. L05 s14 states all four cases explicitly as figures (a)–(d) with the caption “Triangle indicates edge-triggered (therefore flip-flop)”.

Evidence: L05 s5, s6, s14; L06 s4, s10, s11, s12; L07 s3, s8, s10, s11, s12; Device Pinouts p. 1–2. Consistency: the rectangle-with-wedge is universal; only the clock label varies (see Inconsistencies).

Asynchronous set/clear, when shown, are written SET above and CLR below inside the box (L07 s3, s12) and may be omitted entirely when unused — Device Pinouts p. 1 says so in words: “(Set and clear inputs can be omitted if not needed)”. Active-low asynchronous inputs are marked by overlining the name (P̄R̄Ē, C̄L̄R̄ — L05 s13) or by a bubble on the pin (Device Pinouts p. 1, 74HCT74). L06 s4 states the rule in prose: “The SET and CLR inputs are typically active-low”.

Register — rectangle with a name plate

Rectangle with the word Register written above the box, input pin names down the left edge, output pin names down the right, a plain vertical line joining the first and last name of a contiguous range (meaning “and all the ones between”), enable name centred at the bottom inside, clock wedge on the left edge. (L06 s15, the 4-stage 8-bit queue.) One figure.

ALU

Two shapes, both used, both in the same deck — see Inconsistencies. The notched trapezoid (wide edge up, a V-notch cut into the top edge, operands entering the top, result leaving the bottom, ALU lettered in the body) is the more common: L09 s15, s16, s20; L10 s10. The plain rectangle with ALU centred and heavy arrows on all four sides is used at L09 s5 and s9.

Timing and waveform diagrams

See timing-diagrams for what a timing diagram means; this is how it is drawn.

  • Time runs left to right. Where the axis is marked at all it is a short solid horizontal arrow labelled Time placed under or to the right of the waveform block (L04 s15, s18). Most figures omit it (L04 s16, s17; L05 s6, s8).
  • One horizontal track per signal, stacked vertically. The signal name sits to the left of its track, followed by a colon: Input:, Output:, D:, CLK:, Q:, A:, B:. (L04 s15, s16, s17; L05 s6, s8.) Consistency: every timing figure sampled.
  • Two horizontal dashed reference lines bound each track — upper = logic 1, lower = logic 0. Where they are labelled, the labels read Logic 1 and Logic 0 and sit at the end of the rails (L04 s15, s18). In most figures the rails are drawn but left unlabelled (L04 s16, s17; L05 s6, s8).
  • The waveform is a heavy solid black line, noticeably heavier than the dashed rails, riding on the lower rail for 0 and the upper for 1.
  • Idealised transitions are vertical (zero rise/fall time): L04 s15, s16, s17; L05 s6, s8. Sloped edges appear only in the one figure whose subject is real timing — L04 s18, “Gates Aren’t Perfect … The Reality of Timing”, where the slope is the point.
  • Input waveforms enumerate every input combination exactly once, in equal-width intervals. L04 s16 states it: “All combinations of inputs are covered”. For two inputs the pattern is A = 0 0 1 1, B = 0 1 0 1 across four equal intervals (L04 s16, s17).
  • Measured intervals are marked by dropping vertical dashed lines from the two instants and drawing a red double-headed arrow between them, labelled in blue (Propagation delay, Fall time, Rise time). L04 s18 — one figure only, so treat the colour choice as that figure’s, not a rule.
  • Clock waveforms come two ways, both consistent within their purpose: a train of narrow rectangular pulses (mark shorter than space, no dashed rails) when the clock is the whole subject (L05 s18; L06 s7), and a full-height square wave on its own labelled track with rails when it sits alongside data signals (L05 s6, s8).
  • A vertical dashed grid aligned to the clock edges may be laid over a multi-signal figure so the waveforms can be read against each other (L05 s8). One figure.

State diagrams

L08 s9 is the one slide in the whole course that states a diagram convention rather than merely demonstrating one. Everything here comes from it, plus the worked example on s18.

  • A state is a circle divided by a horizontal chord. The state name goes in the upper half (bold); the output value(s) go in the lower half. Nothing else goes in the circle. (L08 s9, which prints the empty template State Name / Output Value(s) next to two filled examples, S0/101 and Alex/01.)
  • State names are free-form. The same slide sanctions both a systematic S0, S1, S2, S3 scheme (used in the worked example, L08 s18) and an arbitrary word (Alex). Outputs are written as a bare bit string with no separators or subscripts: 101, 01, 00, 11.
  • A transition is a plain single-headed arrow, labelled with a Boolean logic expression written above the arrow. “If expression is true, state transition is made.” (L08 s9.)
  • An unlabelled arrow means “true” — always transition. Stated in words on L08 s9.
  • Special case, exactly one input: the label degenerates to a bare 0 or 1. L08 s9 boxes this case in red and annotates it “Special case for only one input”.
  • Transition-label algebra is the ordinary Boolean notation of L02 s12: overbar for NOT, . or juxtaposition for AND, + for OR. L08 s9’s own examples are Z, R̄Ē S̄ĒT̄, and A+B.C̄.
  • Completeness: “Each possible combination of inputs should be addressed exactly once for each state — i.e. transition arrows from each state must encompass all possibilities (exactly once).” (L08 s14.) This is a correctness rule, not a drawing rule, but it constrains what you draw.
  • Layout: the one worked diagram (L08 s18) puts the states in a left-to-right row with forward transitions between neighbours and the wrap-around transition drawn as a long arc below the row. Single instance — the row layout is an example, not established as required.

State tables

Two forms, both defined on their own slide, both with an empty template printed so the column structure is unambiguous.

One-dimensional (L08 s15) — one row per (current state, input) combination, annotated “Every combination of state and inputs”:

Current State Input U Next State Outputs
Q1 Q0

Two-dimensional (L08 s16) — one row per state (“One row per state”), with the next-state column split by input combination (“Every combination of inputs”):

Current State Next State Outputs
Ū U Q1 Q0

Structural conventions common to both: headers bold and centred; a heavy rule under the header block and heavy vertical rules between column groups, thin rules inside a group; the individual output bits are sub-columns under a single spanning Outputs header; the input name appears in the header, not just its values.

For a counter with no external input, the same table is written with the next-state columns named after the flip-flop D inputs rather than the state: Current State (Q₁, Q₀) | Next State (D₁, D₀) (L07 s11). L08 s21 lists the design pipeline these tables sit in: state definition → state diagram → state table (1D or 2D) → state encoding → Boolean expressions → logic diagram → Logisim → hardware.

The characteristic table of a flip-flop uses different headers again: D | Q(t+1), with the right-hand column glossed “What the output will be on the next clock edge” (L05 s7).

Block and datapath diagrams

  • Plain rectangles. No rounded corners, no drop shadows, no fill in the line-art figures. The block name is centred inside, on one or two lines. (L04 s8; L05 s17; L06 s6; L07 s16; L08 s3, s7; L09 s15, s16.)
  • Flow left to right; feedback routed around the outside, usually below the blocks, returning to the left edge of the first block (L05 s17; L06 s6; L07 s16; L08 s3, s7). Consistency: every sequential-circuit block diagram in the course, across four decks.
  • Every connection gets an arrowhead at its destination.
  • The clock enters on its own labelled stub, not bundled with the data inputs — Clock pulses entering from below-left in the Mano figures (L05 s17; L06 s6; L08 s3), Clock entering from above in the UQ redraw (L08 s7).
  • Multi-bit paths are drawn heavy, single-bit control thin. L09 s15/s16 draw the A, B and Dest buses as thick black arrows against thin control lines; the caption “Buses (A,B,C)” points at them. L09 s5 and s9 draw the ALU’s A, B, Output and Function/Control as heavy arrows with the width lettered beside them (n, n, n, m).
  • Grouped signals are collected with a curly brace and one text label rather than labelled individually: Data input A, Data output (L04 s7); Control registers, To and from memory (L09 s15); Before / Today (L12 s2); the IO-board input/output groups (Device Pinouts p. 2).
  • Anonymous repetition uses a vertical ellipsis between the first and last drawn line, with the count given in words beside the group: “n inputs”, “m outputs” (L04 s8).
  • Bus width is marked two ways — see Inconsistencies.

Register and memory layout diagrams

Bit fields

A single row of equal-width boxes, MSB on the left, LSB on the right. Bit positions are numbered above the boxes, descending left to right and ending at 0. Values or field names go inside the boxes.

Evidence: L01 s12 (a byte, 0 1 0 1 0 1 1 1), s13 (positions 9 8 7 … 0 above, powers 2⁹ … 2⁰ and decimal weights 512 … 1 inside), s16 (MSB/LSB called out by red arrows to the extreme boxes), s17; L10 s15. Consistency: every bit-field figure. L01 s16 states the underlying rule: “the MSB is worth 2^(n-1)”.

The AVR-datasheet register diagram

For a named hardware register the three-row datasheet form is used: bit numbers 7 … 0 above the row of boxes, flag names inside the boxes (bold), an R/W access row underneath, and an initial-value row (0) under that. (L10 s15, the AVR status register I T H S V N Z C.) One figure in the sampled decks, but it is verbatim datasheet form and is the obvious template for any other AVR register.

Memory maps

L11 s14, the one memory map with an explicit source ([From ATmega324A datasheet]):

  • Vertical stack of rectangles, lowest address at the top, highest at the bottom.
  • Hex addresses written outside, to the right, aligned with the region boundaries — as a range for a fully-specified region (0x0000 - 0x001F) or as the single start address of an open region (0x0100), with the final address at the bottom (0x08FF).
  • Hex is written 0x + a fixed number of digits, four for the address space (0x0000), two for the register file (0x00 … 0x1F, L11 s22).
  • Region names inside the boxes, with the size in parentheses where useful (Internal SRAM (1024/2048/4096/16384 x 8)).
  • Grey fill for the large or coarsely-described regions, white for the enumerated ones.
  • A diagonal break across the block shows the drawing is not to scale (between Application Flash Section and Boot Flash Section).
  • Column heading above each stack (Data, Program Memory).

The generic memory-organisation figure (L11 s5) agrees on direction — addresses 0 1 2 3 … down the left side, increasing downward — and adds a double-headed arrow across the top labelled Cell width. The alignment figure disagrees; see Inconsistencies.

The register file

L11 s22: vertical stack, R0 at the top through R31 at the bottom, hex address to the right of each row, an ellipsis row ... for the elided middle, a heavy horizontal rule at the R15/R16 boundary marking the split that matters for ldi, and free text further right for the X/Y/Z aliases (X-register Low Byte, etc.).

Shift and rotate

L12 s10, s11: the printed figure is only a row of empty boxes. The direction arrows inside the boxes, the 0 entering the vacated end, the separate small box labelled C for the carry, and the wrap-around arc for a rotate are all drawn in the lecturer’s ink. Record this as the idiom the course uses, but note that nothing about it is printed — see Not established by the source.

AVR architecture figures

  • The AVR CPU architecture diagram (L10 s10) and the ATmega324A chip block diagram (L10 s11) are datasheet reproductions, introduced only by the prose line “Some datasheet extracts follow” on L10 s9. Neither carries a caption. The only in-figure datasheet attribution anywhere is on the memory maps, L11 s14.
  • CPU diagram style: black line art, no fill. The 8-bit data bus is a heavy vertical black bar running the full height, labelled Data Bus 8-bit at the top. Blocks attach to the bus with double-headed arrows; instruction and control flow use thin single-headed arrows. The ALU inside is the notched trapezoid. Path labels that run vertically are set as rotated text (Direct Addressing, Indirect Addressing). Block names are two or three centred lines (Flash Program Memory, 32 x 8 General Purpose Registers, Instruction Decoder, Data SRAM).
  • Chip-level diagram style (L10 s11): a dashed rectangle is the package boundary, with pin and port names outside it (VCC, GND, RESET, XTAL1, XTAL2, PA7..0, PB7..0, TOSC2/PC7). A heavy solid outline inside is the internal bus, drawn with an arrowhead to show its direction. Peripherals are plain rectangles named for the function, with the width in parentheses for ports (PORT A (8)). Pin ranges are written PA7..0, high first.
  • The generic CPU figure the AVR specialises (L09 s3, s4; L10 s3) is a heavy outer rectangle labelled CPU containing three filled boxes — Control Unit, Arithmetic Logic Unit (ALU), Registers — with Primary Memory as a separate box outside it. This one is filled with colour (green, cyan, lilac), used only to separate adjacent blocks. See avr-architecture and cpu-organisation.

Truth tables and function tables

  • Inputs first (left), outputs last (right), separated by a heavier vertical rule. (L02 s6–s10; L03 s11, s14; L04 s11, s13; L05 s10.) Consistency: every truth table sampled.
  • Rows in ascending binary counting order of the input columns, starting from all-zeros, all 2ⁿ of them. (Every table sampled.) L02 s13 states the underlying instruction: “Lists output for all 2ⁿ combinations of inputs — Best to list inputs in a systematic way”.
  • Column headers are the bare signal names, bold. No units, no types.
  • Function tables for MSI blocks list only the selector combinations, and the output column holds the name of the selected signal, not a bit: S1 S0 | F with entries D0, D1, D2, D3 (L04 s9, s11). The header is called out as Function table (L04 s9) or Function Table (L04 s11).
  • A highlighted cell or row uses a pale fill — pale orange for the active decoder output (L04 s13), pale grey for the changing bits of a counting sequence (L07 s9).
  • Visual styling of tables is not fixed — see Inconsistencies. Only the column semantics and row ordering are stable.
  • Multi-column comparison tables (Intel-64 vs AVR data-type support, L12 s18) use a check mark ✔ for “supported” and an empty cell for “not supported” — no cross, no “N/A”.

Boolean and textual notation

L02 s12 is titled “Boolean Algebra conventions” and states them outright — the only place in the course where notation is legislated rather than demonstrated:

  • Inversion: overline. NOT(A) = Ā, “pronounced as A bar”.
  • AND: a dot, or implied by adjacency. AND(A,B) = AB = A.B.
  • OR: a plus sign. OR(A,B,C) = A+B+C.
  • XOR: ⊕. XOR(A,B) = A⊕B = ĀB + AB̄.
  • The overline extends over exactly the sub-expression negated: NAND(A,B,C) = A̅B̅C̅ as one bar over ABC; NOR(A,B) = A̅+̅B̅ as one bar over A + B. Nested negation stacks bars (L02 s22: A̿ + B̿).

Held throughout the semester (L02 s16–s23; L03 s14; L04 s10; L07 s11, s14; L08 s9; L09 s11).

Beware the operator clash the course flags itself: in an arithmetic context + means addition, not OR — L04 s5 says “‘+’ in this case means addition (not OR)”.

Indexed signals take subscripts: Q₁, Q₀, D₁, D₀, S₁, S₀, A₃…A₀, C₄, F₁, F₀ (L03 s16; L04 s9; L07 s10–s12; L09 s6, s10). Not universally — see Inconsistencies.

Numbers

  • Radix by subscript: 26₁₀, 101₂, 101₁₆, 8₁₀ - 9₁₀ (L01 s19, s20; L09 s22).
  • Radix by prefix: 0x (C and AVR), $ (AVR assembly), 0b (binary), leading 0 (octal). L01 s20 lists every alternative in a table and marks these ones “We’ll mostly use these”, ruling out the trailing-h, trailing-q, trailing-b, @ and % forms.
  • Binary literals are grouped in fours with a space: 0000 1101 0111 0111, 00001010, 1110 KKKK dddd KKKK (L01 s18; L03 s8, s9; L10 s4, s16–s18). Short literals under about 8 bits are often left ungrouped (00001111, L11 s16).

AVR assembly and machine code

  • Machine-code layouts write fixed bits as 0/1 and each variable field as a repeated letter, one letter per bit — 0000 11rd dddd rrrr (ADD), 1001 010d dddd 0000 (COM), 1110 KKKK dddd KKKK (LDI). d = destination register, r = source register, K = constant. Note the case split: register-field letters lowercase, the constant uppercase. (L10 s16, s17, s18.)
  • Register-transfer notation uses a left arrow: r3 ← r3 + r4, r22 ← r22 + 1 (L10 s8, s12, s13).
  • Multi-byte quantities are written as a high:low register pair: r5:r4, r11:r10, r13:r14, R31:R30 (L11 s22; L12 s12, s20). High byte first, always.
  • Code is set in a monospace font, and concrete examples in the body text are coloured red (mov r3, r14, add r5,r6, ldi r16,73 — L10 s12–s14).
  • Mnemonic case is not settled — see Inconsistencies.

Colour and annotation

Colour carries no defined meaning anywhere in this course. No slide and none of the three guides ever says what a colour signifies. What can be observed:

  • Red is the usual colour for a callout pointing into a figure — an arrow plus a short label, sitting outside the drawing (L01 s13 Bit position, Value (Powers of 2); L01 s16 MSB/LSB; L02 s14 the four connection callouts; L04 s4 Full-adders; L09 s5 Function/Control; L09 s15 Buses (A,B,C); L11 s5 Address/Cell width).
  • Blue is the usual colour for an explanatory label attached to a figure element (L04 s15 Logic 1/Logic 0, s18 Propagation delay; L05 s15, s17 Logic Gates; L09 s10 Carry ripples through from right to left).
  • But the two are swapped freely. L04 s15 uses red for Change in input causes output to change; L08 s15/s16 use red for both the brace and its explanation; L09 s20 uses red for the Status callout with a green-filled fact box beside it; L09 s15 uses purple.
  • Fills are decorative, used only to separate adjacent blocks: yellow for the levels-of-abstraction stack (L01 s9; L02 s5), green/cyan/lilac for the three CPU parts (L09 s3, s4; L10 s3), pale blue/green/lilac for the fetch-decode-execute fact boxes (L09 s13).
  • Table highlighting is a pale fill on the cell or row of interest (L04 s13; L07 s9).

Handwritten ink on the slides is the lecturer’s live annotation, not part of the published figure. It is present on most technical slides, in red, blue, purple, green and orange, and the colour there tracks nothing but which pen was in hand — L11 s13 uses three ink colours in one worked example purely to separate three sub-workings. Nothing that exists only in ink should be treated as an established figure convention; where a convention below is ink-only it is flagged as such and repeated under Not established.

Inconsistencies

Places where the course does the same thing more than one way. None of these is resolved here — a decision is needed before a new diagram commits to one.

  1. The ALU has two symbol shapes, in one deck. A plain rectangle with ALU centred and heavy arrows on four sides (L09 s5, s9), and a notched trapezoid with operands in the top and result out the bottom (L09 s15, s16, s20; also the AVR datasheet figure, L10 s10). Both are the ALU of the same machine, ten slides apart. Decision needed.

  2. The flip-flop clock input has four labels. CLK (L05 s5, s6; L06 s4; L07 s10, s11, s12; Device Pinouts p. 2 on the 74HCT175), CK (L05 s14 — the very slide titled “D Latches and Flip-flops — Symbols Used”), italic serif C (L06 s8, s9 — the Mano figures), and lowercase italic clk as the net name on the wire (L06 s10, s11; L07 s15). Decision needed.

  3. The asynchronous inputs have three naming schemes. SET / CLR (Device Pinouts p. 1, 74HCT74 schematic symbol; L07 s3, s12), P̄R̄Ē (preset) / C̄L̄R̄ (L05 s13), and R with a bubble (Mano’s register, L06 s8). Device Pinouts p. 2 gives the 74HCT175 only a C̄L̄R̄. Decision needed.

  4. “Current state” vs “present state”, and “next state” vs “Q(t+1)”. Printed slides say Current State (L07 s11; L08 s15, s16); the lecturer’s worked tables say Present State (L07 s8, s14 — ink). The flip-flop characteristic table calls the next-state column Q(t+1) (L05 s7) where the state table calls it Next State (L07 s11; L08 s15). Decision needed.

  5. Three textbook figure styles coexist, none declared canonical. Mano, Digital Design 3rd ed. — black-and-white line art, thin rules, italic serif signal names with subscripts (B₃, A₃, C₄, S₀, SI, SO, CLK), plain square blocks with italic FA inside (L03 s16; L04 s4, s10; L05 s17; L06 s6, s8, s9; L08 s3). Floyd, Digital Fundamentals — pale-blue and beige filled blocks, magenta arrows and magenta text labels, serif (a) Serial in/shift right/serial out sub-captions (L07 s4, s5, s7). Tanenbaum, Structured Computer Organization — dense line art with dashed boxes grouping sub-circuits (L09 s8). And L01 s8 says there is no textbook. Decision needed: which family a redrawn figure should imitate.

  6. The same block diagram exists in two drawing styles. The sequential-circuit block diagram appears as the Mano original — thin rules, serif lowercase labels Combinational circuit / Flip-flops / Clock pulses (L05 s17; L06 s6; L07 s16; L08 s3) — and as a UQ redraw in bold sans-serif with heavy borders (L08 s7, the Moore/Mealy slide). Same content, same course, different look. Decision needed.

  7. Memory addresses increase downward in some figures and upward in others. Downward: the generic cell diagram (L11 s5, addresses 0 1 2 3 … down the left), the AVR address-space maps (L11 s14, 0x0000 at the top), the register file (L11 s22, R0 at the top), the endianness examples (L11 s16, s17). Upward: the alignment figure (L11 s10), where the row addresses 0 8 16 24 run bottom to top and the byte numbers within a row run high-to-low left to right (15 14 13 12 11 10 9 8). Decision needed.

  8. Hex is prefixed 0x in some places and $ in others — sometimes on the same slide. 0x: L10 s15 area, L11 s14 (0x0000), L11 s22 (0x1F), L11 s27 (“0 to 0x3F”), L12 s15 (andi r17, 0xBA). $: L11 s26 (“$20 to $FF”), L12 s15 (lds r15, $1234). L01 s20 blesses both. Decision needed.

  9. Assembly mnemonic case in the generic form. Uppercase: MOV rd, rr, ADD rd, rr, AND rd, rr, LDI rd, K (L10 s12, s13, s14; L11 s25; L12 s4, s9). Lowercase bold-italic: in rd, P, out P, rr (L11 s27; L12 s5), and lowercase throughout the addressing-modes slide (andi, and, lds, ld — L12 s15, s16). Concrete examples are lowercase in print (mov r3, r14) but uppercase in the lecturer’s ink (ADD r10, r4, L12 s20). Decision needed.

  10. Register names: R0–R31 or r0–r31. Uppercase in the register-file figure (L11 s22) and the AVR architecture block (L10 s10, 32 x 8 General Purpose Registers); lowercase everywhere in prose and code (L10 s12–s14; L11 s27; L12 s4–s6). Decision needed.

  11. Truth-table visual styling has three treatments. Dark-red header row with pink zebra striping (L02 s9, s10; L03 s11; L04 s11); plain black-on-white with a bold header and a heavy input/output divider (L02 s6, s7; L03 s14; L04 s13; L05 s10); light-grey header with grey cell highlighting (L07 s9). Column semantics and row order are stable across all three; only the appearance differs. Decision needed for a house table style.

  12. Bus width is marked two ways. A short slash across the line with the width beside it (Device Pinouts p. 2, the 4-marked buses of the 74HCT157 and 74HCT283 logic-diagram symbols). Or the width simply lettered next to a plain arrow, no slash (L09 s5, s9 — n, n, m, n). Decision needed.

  13. The adder’s function glyph. A large + in the trapezoid body (L04 s7; Device Pinouts p. 2). Or Σ on the block’s output pin with A, B, C_out on the others (L07 s7, the Floyd figure). Decision needed.

  14. Indexed signals are subscripted inconsistently. Subscripted Q₁, Q₀, D₁, D₀ in the counter state table and its circuit (L07 s10, s11, s12). Unsubscripted Q1, Q0 in the state-table templates (L08 s15, s16) and S0, D0 in the mux function table (L04 s9). Decision needed.

Not established by the source

Things a CSSE2010 diagram may well need that the materials simply do not settle. These are where invention risk lives.

  • Karnaugh maps: entirely absent. No K-map appears on any of the 221 deck pages sampled, nor in any of the three guides. The course’s simplification path runs truth table → sum of products → Boolean identities → algebraic manipulation (L02 s16–s21), and De Morgan is done algebraically (L02 s21, s22). If a K-map is needed, everything about it is invention: cell ordering and whether the axes are Gray-coded, which variable goes on which axis, how variable labels are written along the edges, the style of the grouping loops, and the don’t-care mark.
  • The initial/reset state of a state diagram. L08 s9 defines only the state circle and the transition arrow. The one worked diagram (s18) has no incoming arrow from nowhere, no double circle, no reset label. How to mark the start state is unspecified.
  • Mealy outputs on a state diagram. L08 s6, s7 define both machine types, then s7 says “We’ll stick to Moore machines in this course”. The notation slide therefore supplies only the two-half circle, which is a Moore output. There is no notation for an output written on a transition (no input/output slash form anywhere).
  • Self-loop transitions. None is drawn anywhere sampled, although the completeness rule (L08 s14) guarantees most machines need them. Loop shape, side of the circle, and label placement are all unspecified.
  • The don’t-care symbol. X is used for don’t-care next-state entries at L07 s14 and for “byte not part of this word” at L11 s10 — both in the lecturer’s ink, never in print. No printed definition of the symbol exists.
  • The shift/rotate register idiom. L12 s10, s11 print only a row of empty boxes; the direction arrows, the 0 entering the vacated end, the separate C carry box and the rotate wrap-arc are all ink. The idiom is clear, but it has no printed authority.
  • Numeric values written inside timing-diagram segments. The 0/1 written in the middle of each waveform segment is always the lecturer’s ink (L04 s15, s16, s17; L05 s6), never printed. Whether a finished diagram should carry them is unsettled.
  • Setup and hold time. Only propagation delay, rise time and fall time are named and drawn (L04 s18). Setup/hold appear nowhere, so their marking is unspecified.
  • Waveforms for multi-bit buses. The “hexagon” (split-and-rejoin) idiom for a bus carrying a value is never drawn. Every waveform in the course is a single-bit two-level trace.
  • Whether a multi-bit signal in a gate-level logic diagram should be thickened or slashed. The datapath figures use heavy arrows (L09 s15, s16) and the guide’s MSI symbols use slashes (Device Pinouts p. 2), but gate-level diagrams use exactly one line weight and no slashes. Nothing bridges the two.
  • Tri-state, open-collector and bidirectional signal marking. Not drawn anywhere. The AVR datasheet figures use double-headed arrows for bidirectional bus attachment (L10 s10, s11), but that idiom is inherited, not taught.
  • Symbols for gates with three or more inputs. L02 s9, s10 ask for 3-input NAND and XOR truth tables but never draw a 3-input symbol, and the parts list contains only 2-input gates plus the hex inverter (Device Pinouts p. 1; see device-pinouts). How to extend the body and space the input leads is unspecified.
  • Figure numbering and captioning. The decks caption almost nothing. The only figure caption in any deck is Mano’s own, retained inside a reproduced image: Fig. 6-3 4-Bit Shift Register (L06 s9). Source credits sit as a bracketed line under the figure. There is no course figure-numbering scheme, so any new note must choose its own.
  • Stroke weights, arrowhead geometry, fonts and sizes. No slide or guide specifies any of these numerically.
  • What colour means. Nothing in any slide or guide assigns meaning to a colour. The near-patterns recorded above are observations, not rules — and they are broken more than once. Do not attach semantic meaning to colour in a new diagram unless you define it in that diagram’s own caption.

See also

  • circuit-schematics — the schematic rules this note deliberately does not repeat: device IDs, gate letters, pin numbers, junction dots, power-supply blocks, the seven common errors
  • device-pinouts — 74-series pinouts, the logic-diagram vs circuit-schematic symbol columns, the IO board
  • logic-gates — the seven gate types and their truth tables
  • timing-diagrams — what a timing diagram means, as opposed to how it is drawn
  • state-machines — state diagrams and state tables as content
  • boolean-algebra — the identities the transition-label algebra uses
  • avr-architecture — the AVR figures described here, read for content

Sample Mid-semester Exam #1

This is the first of UQ’s sample mid-semester papers for csse2010 — CSSE2010/CSSE7201 Introduction to Computer Systems — printed for the Semester One Mid-semester Examinations, 2020, St Lucia campus. It runs for 60 minutes with 10 minutes of reading time beforehand, and it is an open book examination: no electronic aids (laptops, phones), but a Casio FX82-series or other UQ-approved calculator is allowed. Answers go on a supplied “True/False and Multiple Choice Answer Sheet”. There are 25 questions, each worth one mark, and the marking is blunt — a correct answer earns one mark, and an incorrect, missing or multiple answer earns zero, so there is no penalty for guessing.

WarningAnswers are derived, not official

The source paper ships without an answer key, so every answer below was worked out during transcription rather than taken from UQ. Each one shows its reasoning so it can be checked rather than trusted; anything uncertain is flagged. Treat a disagreement between your working and the answer here as a reason to check both.

How to use this

Two ways. For a timed run, set a clock for 60 minutes and work straight through all 25 questions — on the website the answers are collapsed, so they stay hidden until you click them, and the paper reads like the real thing. For targeted practice, use the question index below to pick out only the questions for one week or one concept, and follow the concept links when a step in the working is unfamiliar. Note that the PDF build prints every answer inline, so the site version is the one to practise from.

Question index

Q Topic Week Concept notes
1 One’s complement 1 binary-number-representations
2 Octal conversion 1 binary-number-representations
3 Range of a radix-r number 1 binary-number-representations
4 Properties across signed formats 1 binary-number-representations
5 Reading a gate-level circuit 1 logic-gates
6 Gate equivalence and De Morgan 1 logic-gates · boolean-algebra
7 Boolean simplification 2 boolean-algebra
8 Truth table to sum of products 2 boolean-algebra
9 Timing diagram to logic function 2 timing-diagrams
10 XOR identities 2 boolean-algebra
11 NOR-only implementation 2 boolean-algebra · logic-gates
12 NOR latch behaviour 3 flip-flops-and-latches
13 D flip-flop timing 3 flip-flops-and-latches · timing-diagrams
14 Two’s complement addition 2 binary-number-representations
15 Detecting overflow 2 binary-number-representations
16 Overflow on a positive sum 2 binary-number-representations
17 Programming a multiplexer 2 combinational-logic-blocks
18 Shift register with hold 3 shift-registers
19 Counter width 4 [counters]
20 Synchronous counter sequence 4 [counters]
21 State diagram to state table 4 state-machines
22 Tracing a state machine 4 state-machines
23 Tanenbaum ALU bit slice 5 arithmetic-logic-unit
24 ALU bit slice with an 8-way mux 5 arithmetic-logic-unit
25 What an ALU cannot compute 5 arithmetic-logic-unit

Q1 — One’s complement of a negative

What is \(-21_{10}\) expressed in 8-bit one’s complement format?

  1. 10010101

  2. 11101010

  3. 11101011

  4. 11110010

  5. None of the above

(b)

One’s complement negates by inverting every bit of the magnitude, so start from \(+21\) in 8 bits:

\[21 = 16 + 4 + 1 = 0001\,0101_2\]

Inverting all eight bits gives

\[\overline{0001\,0101} = 1110\,1010_2\]

which is option (b). Option (c), 11101011, is the two’s complement of \(-21\) (one’s complement plus one) — the classic distractor here. See binary-number-representations.

Q2 — Octal conversion

\(111_8\) is equal to

  1. \(1001001_2\)

  2. \(71_{10}\)

  3. 0x73

  4. \(7_{10}\)

  5. None of the above

(a)

Each octal digit is exactly three bits, so the conversion to binary is done digit by digit with no arithmetic at all:

\[1_8 \to 001, \quad 1_8 \to 001, \quad 1_8 \to 001 \;\Rightarrow\; 111_8 = 001\,001\,001_2 = 1001001_2\]

That is option (a). Checking the others against the decimal value \(1 \times 64 + 1 \times 8 + 1 = 73_{10}\): (b) is 71, not 73; (d) is 7; and (c) is the trap — 0x73 is hexadecimal 73, which is \(7 \times 16 + 3 = 115_{10}\), not the decimal 73 the value happens to equal. See binary-number-representations.

Q3 — Range of a radix-r number

An n-digit radix-r number can represent unsigned integer values from 0 up to

  1. \(2^{(n-1)}\)

  2. \(2^n\) - 1

  3. \(r^{(n-1)}\) - 1

  4. \(r^n\) - 1

  5. None of the above

(d)

With \(n\) digits and \(r\) choices per digit there are \(r^n\) distinct patterns. Counting from zero, the largest value is one less than the count:

\[0 \le \text{value} \le r^n - 1\]

Two other routes to the same answer:

  • The smallest value you cannot represent is a one followed by \(n\) zeroes, which is worth \(r^n\). The largest you can represent is one below it.
  • The largest value is \(n\) copies of the largest digit, \(r-1\) — 9999 in base 10, FF in hex — and summing that as a geometric series gives \(\sum_{i=0}^{n-1} r^i (r-1) = r^n - 1\).

Option (b) is the same formula specialised to \(r = 2\), which is only correct for binary, and the question asks for general radix \(r\). See binary-number-representations and week1-lab-number-representations.

Q4 — Properties across signed formats

Which of the following statements about the 8 bit binary number 01100101 is true?

  1. The number is negative in signed magnitude, two’s complement, one’s complement and excess-128 formats.

  2. The number is positive in signed magnitude, two’s complement, one’s complement and excess-128 formats.

  3. The number is odd when considered to be in signed magnitude, two’s complement, one’s complement or excess-128 formats.

  4. The number is even when considered to be in signed magnitude, two’s complement, one’s complement or excess-128 formats.

  5. None of the above

(c)

Read the pattern once in each format. \(0110\,0101_2 = 101_{10}\) as a plain unsigned number, and only the leading bit is read differently from one format to the next.

Figure 231: One bit pattern, four readings. Bits 6 down to 0 carry the same place values in every format, so the only question is what the leading bit is worth: nothing at all in signed magnitude, and a plain 0 in the two complement formats because it is clear. Excess-128 is the outlier - it reads the eight bits as plain unsigned and then takes the bias off the whole value, which is why the same pattern comes out negative there.

That immediately kills (a) and (b): the first three formats all read it as positive, but excess-128 reads it as \(-27\), so it is neither negative in all four nor positive in all four.

Parity is the property that does survive all four. In the three sign-magnitude-style formats the value is \(\pm 101\), which is odd; in excess-128 it is \(-27\), also odd. So (c) is true and (d) is false. See binary-number-representations.

Q5 — Reading a gate-level circuit

Which of the following logic circuits is an implementation of the function \(A \cdot (B \oplus C) \cdot D\)?

Figure 232: Question 5’s five candidate circuits. (a) is a three-input AND fed by A, an XNOR of B and C, and D; (b)–(e) each combine two two-input gates into a third.

  1. None of the above

(d)

Read each circuit out as an expression:

Option Circuit Function
(a) 3-input AND of A, XNOR(B,C) and D \(A \cdot \overline{(B \oplus C)} \cdot D\)
(b) AND(A,D) and XOR(B,C) into an OR \(A \cdot D + (B \oplus C)\)
(c) AND(A,D) and OR(B,C) into an AND \(A \cdot D \cdot (B + C)\)
(d) AND(A,D) and XOR(B,C) into an AND \(A \cdot D \cdot (B \oplus C)\)
(e) AND(A,B) and AND(C,D) into an XOR \((A \cdot B) \oplus (C \cdot D)\)

AND is associative and commutative, so (d)’s \(A \cdot D \cdot (B \oplus C)\) is the same function as the target \(A \cdot (B \oplus C) \cdot D\).

The two near misses are worth naming. (a) has the right shape but the middle gate carries an output bubble, making it XNOR rather than XOR — the exact complement of what is wanted. (b) has both correct sub-gates but joins them with OR instead of AND. See logic-gates.

Q6 — Gate equivalence and De Morgan

Which of the following circuits is equivalent to:

Figure 233: Question 6’s given circuit (top) and its four candidate equivalents. The given circuit is an AND gate with its A input inverted; each candidate is a single two-input gate with bubbles on some of its terminals.

  1. None of the above

(b)

The given circuit is an AND with a bubble on its A input, so it computes

\[F = \overline{A} \cdot B\]

Push that through De Morgan’s law to get an OR-shaped form:

\[\overline{A} \cdot B = \overline{\overline{\overline{A} \cdot B}} = \overline{A + \overline{B}}\]

That is a gate with a bubble on the B input and a bubble on the output — an OR body with both, which is exactly option (b).

Checking the rest: (a) is the same gate without the output bubble, so \(A + \overline{B}\); (d) is an OR with the A input inverted, \(\overline{A} + B\); and (c) is an XNOR with A inverted, \(\overline{\overline{A} \oplus B} = A \oplus B\). None of those equals \(\overline{A} \cdot B\). See boolean-algebra and logic-gates.

Q7 — Boolean simplification

Which of the following logic functions is identical to \(\overline{\overline{(\overline{A} + \overline{B})} \cdot \overline{C} + \overline{B}}\)?

  1. 0

  2. \(AC + \overline{B}\)

  3. \(AB + \overline{B}C\)

  4. \(\overline{A}B + BC\)

  5. None of the above

(d)

Work outwards from the innermost bar. The inner complement is a straight De Morgan:

\[\overline{\overline{A} + \overline{B}} = A \cdot B\]

so the expression under the long outer bar is \(A B \overline{C} + \overline{B}\). That simplifies by the absorption identity \(X \cdot Y + \overline{X} = Y + \overline{X}\), taking \(X = B\) and \(Y = A\overline{C}\):

\[B \cdot (A\overline{C}) + \overline{B} = A\overline{C} + \overline{B}\]

Now apply the outer bar:

\[\overline{A\overline{C} + \overline{B}} = \overline{A\overline{C}} \cdot B = (\overline{A} + C) \cdot B = \overline{A}B + BC\]

which is option (d).

Checking a couple of rows against the original settles it. With \(A=0, B=1, C=0\) the inside is \(0 \cdot 1 \cdot 1 + 0 = 0\), so the whole expression is 1, and (d) gives \(\overline{A}B = 1\). With \(A=1, B=1, C=0\) the inside is \(1 \cdot 1 \cdot 1 + 0 = 1\), so the expression is 0, and (d) gives \(0 + 0 = 0\). See boolean-algebra.

Q8 — Truth table to sum of products

Consider the logic function represented by the following truth table:

A B C X
0 0 0 1
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 0

Which of the following expressions is equivalent to the function represented in this table?

  1. \(X = A + B + C\)

  2. \(X = A\overline{B}.\overline{C} + \overline{A}.\overline{B}.C + \overline{A}.B.\overline{C}\)

  3. \(X = \overline{A}.B.\overline{C} + \overline{A}.B.C + \overline{A}.\overline{B}.\overline{C}\)

  4. \(X = \overline{A.B.C}\)

  5. None of the above

(e)

The table has \(X = 1\) on exactly three rows: \(ABC = 000\), \(100\) and \(101\). Writing one product term per row,

\[X = \overline{A}\,\overline{B}\,\overline{C} + A\,\overline{B}\,\overline{C} + A\,\overline{B}\,C = \overline{B}\,\overline{C} + A\overline{B} = \overline{B}(\overline{C} + A)\]

Now check each option against those three minterms:

Option Minterms it covers (\(ABC\)) Matches?
(a) \(A+B+C\) everything except 000 no — it is 0 exactly where the table is 1
(b) \(A\overline{B}\overline{C} + \overline{A}\overline{B}C + \overline{A}B\overline{C}\) 100, 001, 010 no — 001 and 010 are 0 in the table
(c) \(\overline{A}B\overline{C} + \overline{A}BC + \overline{A}\,\overline{B}\,\overline{C}\) 010, 011, 000 no
(d) \(\overline{A \cdot B \cdot C}\) everything except 111 no — it is 1 on 001, which the table makes 0

None reproduces \(\{000, 100, 101\}\), so the answer is (e).

Option (b) is the closest — it shares the minterm 100 with the correct function and has the right number of terms — which is presumably the intended trap. See boolean-algebra.

Confirmed on review. “None of the above” is an unusual answer for a routine sum-of-products question, and it would also follow from a single mis-set bar in the source’s option (b). A second independent pass measured the bar positions in option (b) against the glyph positions at 1800 dpi: the bars sit over the first term’s B and C, the second term’s A and B, and the third term’s A and C, exactly as transcribed. Option (b) shares only the minterm 100 with the function, so it is two terms out, not one bar out, and (e) stands.

Q9 — Timing diagram to logic function

What logic function is represented by the following timing diagram?

Figure 234: Question 9’s timing diagram. A, B and C step through all eight combinations — A toggling every interval, B every two, C every four — and X is the output to be identified.

  1. \(X = \overline{C}.\overline{B}.A + \overline{C}.B.A + C.B.\overline{A}\)

  2. \(X = \overline{C}.\overline{B}.\overline{A} + C.B.\overline{A} + \overline{C}.B.\overline{A}\)

  3. \(X = C.\overline{B}.A + C.\overline{B} + C.\overline{A}\)

  4. \(X = \overline{C}.\overline{B}.A + C.\overline{B}.\overline{A} + C.B.\overline{A}\)

  5. None of the above

(d)

A toggles every interval, B every two and C every four, so the eight intervals walk \(CBA\) through \(000, 001, 010, \ldots, 111\) in order. Read X off interval by interval:

Interval C B A X
1 0 0 0 0
2 0 0 1 1
3 0 1 0 0
4 0 1 1 0
5 1 0 0 1
6 1 0 1 0
7 1 1 0 1
8 1 1 1 0

One product term per high interval:

\[X = \overline{C}\,\overline{B}\,A + C\,\overline{B}\,\overline{A} + C\,B\,\overline{A}\]

which is option (d) exactly, term for term. See timing-diagrams.

Q10 — XOR identities

Which of the following logic functions is identical to \(A \oplus \overline{B}\)?

  1. \(A.\overline{B} + \overline{A}.B\)

  2. \(\overline{A}.\overline{B} + \overline{A}.B + A.B\)

  3. \(A + \overline{B}\)

  4. \(\overline{A \oplus B}\)

  5. None of the above

(d)

Inverting one input of an XOR inverts its output — this is the standard identity \(A \oplus \overline{B} = \overline{A \oplus B}\), which is option (d) as written.

To see it rather than quote it, expand:

\[A \oplus \overline{B} = A\,\overline{\overline{B}} + \overline{A}\,\overline{B} = A B + \overline{A}\,\overline{B}\]

That is 1 exactly when A and B agree, which is the definition of XNOR, i.e. \(\overline{A \oplus B}\).

The others: (a) is plain \(A \oplus B\), the complement of what is wanted; (b) simplifies as \(\overline{A}(\overline{B} + B) + AB = \overline{A} + AB = \overline{A} + B\), which fails at \(A=0, B=1\) (it gives 1, the target gives 0); (c) \(A + \overline{B}\) fails at \(A=1, B=0\) (it gives 1, the target gives 0). See boolean-algebra.

Q11 — NOR-only implementation

Which of the following circuits is a NOR-gate only implementation of the following function:

Figure 235: Question 11’s given function A.B + C.D (top) and its four candidate implementations. In (c) and (d) the NOR gates with both inputs tied together are acting as inverters; (d) has one more of them than (c).

  1. None of the above

(d)

The function to reproduce is \(F = A \cdot B + C \cdot D\).

A NOR gate with both inputs tied together is an inverter, since \(\overline{X + X} = \overline{X}\) — that is what the small gates on the left of (c) and (d) are. With inverters available, a NOR fed by two complemented inputs is an AND:

\[\overline{\overline{A} + \overline{B}} = A \cdot B\]

So in both (c) and (d) the two middle NORs produce \(A \cdot B\) and \(C \cdot D\), and the NOR that joins them produces

\[\overline{A B + C D} = \overline{F}\]

which is the complement of what is wanted. (c) stops there and is therefore wrong. (d) adds one more tied-input NOR on the output, inverting once more to give \(F\) itself — so (d) is the NOR-only implementation.

The other two: (a) is a correct implementation of \(A B + C D\), but built from NAND gates, not NOR; (b) is three NOR gates in the same shape as the given circuit, which computes \(\overline{\overline{A+B} + \overline{C+D}} = (A+B)(C+D)\), a different function. See boolean-algebra and logic-gates.

Q12 — NOR latch behaviour

Which truth table correctly captures the behaviour of the following latch circuit?

Figure 236: Question 12’s latch: two cross-coupled NOR gates. M is the external input to the gate that drives Q, N the input to the gate that drives Q-bar, and each gate’s output feeds back to the other gate’s second input.

M N Q \(\overline{Q}\)
0 0 Q \(\overline{Q}\)
0 1 0 1
1 0 1 0
1 1 0 0
M N Q \(\overline{Q}\)
0 0 Q \(\overline{Q}\)
0 1 1 0
1 0 0 1
1 1 1 1
M N Q \(\overline{Q}\)
0 0 Q \(\overline{Q}\)
0 1 0 1
1 0 1 0
1 1 1 1
M N Q \(\overline{Q}\)
0 0 Q \(\overline{Q}\)
0 1 1 0
1 0 0 1
1 1 0 0
  1. None of the above

(d)

This is the standard cross-coupled NOR latch, so M behaves as the reset input and N as the set input — note which output each drives: M feeds the gate whose output is Q, so asserting M forces Q low.

Writing the two gate equations,

\[Q = \overline{M + \overline{Q}} \qquad \overline{Q} = \overline{N + Q}\]

and working through the four input combinations:

M N Working Q \(\overline{Q}\)
0 0 both NORs just invert their feedback, so the state holds Q \(\overline{Q}\)
0 1 N = 1 forces the lower NOR’s output to 0, so \(\overline{Q} = 0\); the upper NOR then sees \(0 + 0\) and outputs 1 1 0
1 0 M = 1 forces the upper NOR’s output to 0, so \(Q = 0\); the lower NOR sees \(0 + 0\) and outputs 1 0 1
1 1 a 1 on either NOR forces its output low, so both outputs go to 0 0 0

That is option (d). The distinguishing rows are the middle two — (a) and (c) have them the wrong way round, treating M as set rather than reset — and the last row, where (b) and (c) claim both outputs go to 1 rather than 0. In a NOR latch the forbidden combination drives both outputs low; it is the NAND latch that drives them both high. See flip-flops-and-latches.

Q13 — D flip-flop timing

For the flip-flop circuit below and the given CLK and A values over time, which of the diagrams below best shows the Q output?

Figure 237: Question 13’s positive-edge-triggered D flip-flop, the CLK and A waveforms driving it, and the four candidate Q outputs (a) to (d).

  1. None of the above

(b)

The clock input is drawn with a plain triangle and no bubble, so the flip-flop is positive-edge-triggered: Q takes the value of A at each rising edge of CLK and holds it until the next one.

There are four rising edges. Reading A at each:

Rising edge A at that instant Q after
1st 0 — A does not go high until just after this edge 0
2nd 0 — A has already fallen 0
3rd 1 — A goes high just before this edge 1
4th 1 — A is still high 1

So Q sits at 0 through the first two edges, rises at the third and stays high. That is exactly diagram (b), whose transition lands on the third rising edge.

The distractors are instructive. (c) is A itself, which is what a transparent latch would give rather than an edge-triggered flip-flop. (a) is what a negative-edge-triggered flip-flop would give: sampling on the falling edges catches A high at the first and third of them. (d) rises one clock too late, at the fourth edge. See flip-flops-and-latches and timing-diagrams.

Q14 — Two’s complement addition

What’s the result of adding the 5-bit two’s complement numbers 11101 and 01001?

  1. 00110

  2. 00111

  3. 01100

  4. 10110

  5. 10111

(a)

Add the bit patterns as if they were unsigned and discard anything past bit 4 — that is the whole point of two’s complement:

\[\begin{array}{r} 11101 \\ +\;01001 \\ \hline 1\,00110 \end{array}\]

Dropping the carry out of the top bit leaves 00110, which is option (a).

The decimal check: 11101 has its sign bit set, so its magnitude is \(\overline{11101} + 1 = 00010 + 1 = 00011 = 3\), i.e. it is \(-3\). 01001 is \(+9\). And \(-3 + 9 = 6 = 00110_2\). The signs differ, so overflow is impossible here and the discarded carry is harmless. See binary-number-representations.

Q15 — Detecting overflow

Which of the following operations will result in an overflow in 5-bit two’s complement arithmetic?

  1. 10010+00010

  2. 10010–00010

  3. 01000+01010

  4. 01000–01010

  5. None of the above

(c)

A 5-bit two’s complement word covers \(-16\) to \(+15\). Overflow means the true result falls outside that range, which can only happen when two operands of the same sign are added (or operands of opposite sign are subtracted).

Option Decimal Result In range \([-16, 15]\)?
(a) \(-14 + 2\) \(-12\) yes — and adding a positive to a negative can never overflow
(b) \(-14 - 2\) \(-16\) yes — \(-16\) is exactly the most negative representable value
(c) \(8 + 10\) \(18\) no — 18 > 15, so this overflows
(d) \(8 - 10\) \(-2\) yes

Option (b) is the near miss worth checking carefully: \(-16\) sits right on the boundary and is representable, as 10000. Only (c) leaves the range. See binary-number-representations.

Q16 — Overflow on a positive sum

Consider the binary addition operation 0111 + 0001. Which of the following statements is true if the numbers are interpreted as two’s complement?

  1. The result is negative and no overflow occurs

  2. The result should be negative but overflow occurs

  3. The result is positive and no overflow occurs

  4. The result should be positive but overflow occurs

  5. The result is zero

(d)

These are 4-bit two’s complement numbers, so the range is \(-8\) to \(+7\).

\[0111_2 = +7, \qquad 0001_2 = +1\]

The bit-level sum is

\[\begin{array}{r} 0111 \\ +\;0001 \\ \hline 1000 \end{array}\]

and 1000 read as 4-bit two’s complement is \(-8\). The true answer \(+8\) is one past the top of the range, so it cannot be represented: the addition of two positives has produced a negative pattern, which is the textbook overflow signature. The result should be positive but overflow has occurred — option (d).

Note that no carry leaves the top bit here, which is why “carry out” alone is not an overflow test in signed arithmetic; the test is the sign pattern of the operands versus the result. See binary-number-representations.

Q17 — Programming a multiplexer

Consider the following multiplexer. What must the inputs A,B,C,D be so that the multiplexer implements the function \(X = S_1 \oplus S_0\)?

Figure 238: Question 17’s 4-to-1 multiplexer. A, B, C and D are wired to data inputs 0 to 3; S1 and S0 are the select lines, and X is the output.

  1. A=1, B=1, C=1, D=1

  2. A=1, B=0, C=0, D=1

  3. A=0, B=1, C=1, D=0

  4. A=1, B=1, C=0, D=0

  5. None of the above

(c)

A multiplexer used this way is a lookup table: the select lines index a data input, and that input’s constant value becomes the output. So each data input holds one row of the truth table of the function being built, with \(S_1\) as the high-order select bit.

\(S_1\) \(S_0\) Input selected \(S_1 \oplus S_0\) So that input must be
0 0 0 (A) 0 A = 0
0 1 1 (B) 1 B = 1
1 0 2 (C) 1 C = 1
1 1 3 (D) 0 D = 0

That is \(A=0, B=1, C=1, D=0\) — option (c). Swapping which select line is the high bit changes nothing here, because XOR is symmetric in its two inputs, so (c) is the answer either way. The distractors are different functions: (d) is 1 on the two inputs reached when \(S_1 = 0\) and 0 on the other two, i.e. \(\overline{S_1}\) — what you get by reading only the high select bit — and (b) is the XNOR, the complement of the target. See combinational-logic-blocks.

Q18 — Shift register with hold

Which of the following statements about this shift register circuit is true?

Figure 239: Question 18’s two-stage shift register. Each stage is a 2-to-1 multiplexer feeding a D flip-flop: input 1 of each multiplexer takes the data from the left, input 0 takes that stage’s own Q back again, and FN drives both selects.

  1. When A is 1, data will be shifted to the right on every rising clock edge

  2. When A is 0, data will be shifted to the right on every rising clock edge

  3. When FN is 1, data will be shifted to the left on every rising clock edge

  4. When FN is 0, the flip-flops will maintain their values (even if the circuit is clocked)

  5. None of the above

(d)

Trace what each multiplexer feeds its flip-flop:

  • Input 1 of the first multiplexer is A, and input 1 of the second is the first stage’s Q. So with the selects at 1, the chain is \(A \to \text{FF}_1 \to \text{FF}_2\) — data moves one stage to the right per clock.
  • Input 0 of each multiplexer is that stage’s own Q, looped back over the top. So with the selects at 0, each flip-flop is reloaded with the value it already holds, and nothing changes even though the clock keeps running.

Both selects are driven by FN, so FN chooses shift (1) or hold (0), and A is data, not control. That makes (d) true: with FN = 0 the flip-flops maintain their values through any number of clock edges.

The others fail because A is a data input, not a mode control — (a) and (b) confuse the two — and because the connection order runs left to right, so FN = 1 shifts right, not left, killing (c).

This “recirculating” pattern is the standard way to add a hold or enable to a register without gating the clock, which would risk glitches. See shift-registers.

Q19 — Counter width

What’s the minimum number of flip-flops needed to build a synchronous binary counter capable of counting from 0 to 32 (inclusive)?

  1. 5

  2. 6

  3. 7

  4. 32

  5. 33

(b)

“0 to 32 inclusive” is 33 distinct values, not 32 — that off-by-one is the whole question. Each flip-flop holds one bit, and \(n\) flip-flops give \(2^n\) states, so we need the smallest \(n\) with

\[2^n \ge 33\]

\(2^5 = 32\), which is one short; \(2^6 = 64\), which is enough. So six flip-flops — option (b).

Option (a) is the answer to “0 to 31”, which is the trap. See [counters].

Q20 — Synchronous counter sequence

What sequence will the following synchronous counter count through?

Figure 240: Question 20’s two-bit synchronous counter. The left flip-flop’s D input comes from its own Q-bar, so Q1 toggles every clock; the right flip-flop’s D input is the XNOR of Q1 and Q0. Both flip-flops share the clock.

  1. \(Q_1Q_0\): \(00 \to 01 \to 10 \to 11 \to 00 \to \ldots\)

  2. \(Q_1Q_0\): \(00 \to 10 \to 11 \to 01 \to 00 \to \ldots\)

  3. \(Q_1Q_0\): \(00 \to 11 \to 01 \to 10 \to 00 \to \ldots\)

  4. \(Q_1Q_0\): \(00 \to 01 \to 11 \to 10 \to 00 \to \ldots\)

  5. None of the above

(c)

Read the two excitation equations off the schematic. The left flip-flop’s D input is wired straight back to its own \(\overline{Q}\), and the right flip-flop’s D input is the XNOR of the two Q outputs:

\[D_1 = \overline{Q_1} \qquad D_0 = \overline{Q_1 \oplus Q_0}\]

Both flip-flops share the clock, so both update together from the current state. Starting at 00:

\(Q_1 Q_0\) \(D_1 = \overline{Q_1}\) \(D_0 = \overline{Q_1 \oplus Q_0}\) Next
0 0 1 \(\overline{0 \oplus 0} = 1\) 1 1
1 1 0 \(\overline{1 \oplus 1} = 1\) 0 1
0 1 1 \(\overline{0 \oplus 1} = 0\) 1 0
1 0 0 \(\overline{1 \oplus 0} = 0\) 0 0

So the sequence is \(00 \to 11 \to 01 \to 10 \to 00\), option (c). All four states appear, so the counter is a valid four-state cycle — just not in binary order.

The gate identity is what to watch here: the bubble on the gate’s output makes it an XNOR, and an XOR there would have produced a different sequence entirely. See [counters].

Q21 — State diagram to state table

Consider the state diagram below.

Figure 241: Question 21’s state diagram. Each state shows its name above the rule and its XY output below; the labels on the arrows are the values of the single input A.

Which of the following is an equivalent state table?

Current State Input (A) Next State Outputs (X,Y)
S0 0 S0 01
S0 1 S1 01
S1 0 S1 00
S1 1 S2 00
S2 0 S2 00
S2 1 S3 00
S3 0 S0 11
S3 1 S1 11
Current State Input (A) Next State Outputs (X,Y)
S0 0 S0 01
S0 1 S1 01
S1 0 S2 00
S1 1 S1 00
S2 0 S2 00
S2 1 S3 00
S3 0 S0 11
S3 1 S2 11
Current State Next State (A=0) Next State (A=1) Outputs (X,Y)
S0 S0 S1 01
S1 S2 S1 00
S2 S2 S3 00
S3 S0 S1 11
Current State Next State (A=0) Next State (A=1) Outputs (X,Y)
S0 S0 S1 00
S1 S2 S1 01
S2 S2 S3 10
S3 S0 S1 11
  1. None of the above

(c)

Read the eight arrows off the diagram — every state has exactly two, one per value of A, which is completeness for a one-input machine:

State Output XY A = 0 A = 1
S0 01 self-loop, stays S0 goes to S1
S1 00 goes down to S2 self-loop, stays S1
S2 00 self-loop, stays S2 goes across to S3
S3 11 goes up to S0 goes diagonally to S1

That is option (c), row for row.

Where each of the others goes wrong:

  • (a) gets S1’s two arrows backwards — it makes S1 self-loop on 0 and go to S2 on 1, whereas the diagram has the self-loop labelled 1.
  • (b) has the right S1 rows but sends S3 to S2 on A = 1; the diagonal arrow out of S3 goes to S1.
  • (d) has the right next-state columns but the wrong outputs: it lists 00, 01, 10, 11 down the states, whereas the diagram gives 01, 00, 00, 11.

This is a Moore machine — the output is written inside each state bubble, so it depends only on the state and not on A, which is why (c) can fold the eight rows into four. See state-machines.

Q22 — Tracing a state machine

Consider the state machine represented by the state diagram in question 21 above (see Q21). What sequence of states is traversed if the machine starts in state S0 and A goes through the sequence 110011 (i.e. two 1’s followed by two 0’s followed by two 1’s)?

  1. S0\(\to\)S1\(\to\)S2\(\to\)S2\(\to\)S3\(\to\)S1\(\to\)S1

  2. S0\(\to\)S1\(\to\)S2\(\to\)S3\(\to\)S0\(\to\)S1\(\to\)S2

  3. S0\(\to\)S1\(\to\)S1\(\to\)S2\(\to\)S2\(\to\)S3\(\to\)S3

  4. S0\(\to\)S1\(\to\)S2\(\to\)S3\(\to\)S1\(\to\)S2\(\to\)S3

  5. S0\(\to\)S1\(\to\)S1\(\to\)S2\(\to\)S2\(\to\)S3\(\to\)S1

(e)

Feed the six input bits into the table derived in Q21, one transition per bit, starting from S0:

Step Input A From To
1 1 S0 S1
2 1 S1 S1 (self-loop on 1)
3 0 S1 S2
4 0 S2 S2 (self-loop on 0)
5 1 S2 S3
6 1 S3 S1

Including the starting state, the traversal is

\[S0 \to S1 \to S1 \to S2 \to S2 \to S3 \to S1\]

which is option (e). The two self-loops are what separate it from the distractors: (a) and (b) skip them, and (c) has the right shape but ends with a self-loop on S3, which the diagram does not have — S3’s arrows both leave. See state-machines.

Q23 — Tanenbaum ALU bit slice

Consider the ALU bit slice below (from the Tanenbaum textbook, also shown in lectures)

Figure 242: Question 23’s ALU bit slice, the one from Tanenbaum. ENA, INVA and ENB condition A and B into the internal signals X and Y; the logical unit computes AB, A + B and B-bar from them and the full adder computes their sum; a two-to-four decoder driven by F0 and F1 raises exactly one enable line, so exactly one of the four results reaches the output OR.

For the ALU bit slice above, under what conditions will the ALU output be \(A\)?

  1. ENA = 0, ENB = 0, INVA = 1, F\(_0\) = 1, F\(_1\) = 0, Carry in = 0

  2. ENA = 1, ENB = 1, INVA = 1, F\(_0\) = 0, F\(_1\) = 0, Carry in = 0

  3. ENA = 1, ENB = 0, INVA = 1, F\(_0\) = 0, F\(_1\) = 1, Carry in = 0

  4. ENA = 1, ENB = 0, INVA = 0, F\(_0\) = 1, F\(_1\) = 1, Carry in = 0

  5. None of the above

(d)

Two things have to be worked out for every option: what the conditioning gates make of A and B, and which of the four function blocks the decoder enables.

The conditioning is read straight off the left of the figure:

\[X = (A \cdot \text{ENA}) \oplus \text{INVA} \qquad\qquad Y = B \cdot \text{ENB}\]

and the decoder’s four outputs pick the function in Tanenbaum’s order:

\(F_0\) \(F_1\) Function selected
0 0 \(X\) AND \(Y\)
0 1 \(X\) OR \(Y\)
1 0 \(\overline{Y}\)
1 1 \(X + Y + \text{Carry in}\) (the adder)

Now evaluate each option:

Option \(X\) \(Y\) Function Output
(a) ENA=0, INVA=1 \(\Rightarrow\) 1 ENB=0 \(\Rightarrow\) 0 \(\overline{Y}\) \(\overline{0} = 1\)
(b) ENA=1, INVA=1 \(\Rightarrow\) \(\overline{A}\) ENB=1 \(\Rightarrow\) \(B\) AND \(\overline{A} \cdot B\)
(c) ENA=1, INVA=1 \(\Rightarrow\) \(\overline{A}\) ENB=0 \(\Rightarrow\) 0 OR \(\overline{A} + 0 = \overline{A}\)
(d) ENA=1, INVA=0 \(\Rightarrow\) \(A\) ENB=0 \(\Rightarrow\) 0 adder \(A + 0 + 0 = A\)

Only (d) gives \(A\).

It is worth noticing why (d) works: the adder with one input forced to zero and no carry in is just a pass-through, so the arithmetic unit can move A to the output as easily as the logical unit can. The more familiar recipe from the combinations table — select OR, pass A, force the other side to zero — is not on offer here, since no option pairs \(F_0 = 0, F_1 = 1\) with INVA = 0. See arithmetic-logic-unit for the full table of useful control combinations.

Q24 — ALU bit slice with an 8-way mux

Consider the ALU bit slice below.

Figure 243: Question 24’s ALU bit slice. X = (A.ENA) xor INVA and Y = B.ENB feed eight candidate results; the multiplexer selects one under F2 F1 F0, giving in order X.Y, X + Y, X xor Y, NOT(X.Y), the carry in, the right shift in, Y-bar, and the full adder’s sum. The carry out is X.Y or the propagate term, which is gated so it only passes in add mode.

For an ALU made up of 8 of the bit slices above, which of the following control input settings will result in the ALU output being \(A - 1\)? (The “Right Shift In” control input refers to that for the most significant bit; the “Carry in” control input refers to that for the least significant bit.)

  1. ENA = 1, ENB = 0, INVA = 0, F\(_2\) = 1, F\(_1\) = 1, F\(_0\) = 1, Right Shift In = 0, Carry in = 0

  2. ENA = 1, ENB = 0, INVA = 1, F\(_2\) = 1, F\(_1\) = 1, F\(_0\) = 1, Right Shift In = 0, Carry in = 0

  3. ENA = 1, ENB = 0, INVA = 0, F\(_2\) = 1, F\(_1\) = 1, F\(_0\) = 1, Right Shift In = 0, Carry in = 1

  4. ENA = 1, ENB = 0, INVA = 1, F\(_2\) = 1, F\(_1\) = 1, F\(_0\) = 1, Right Shift In = 0, Carry in = 1

  5. None of the above

(e)

The conditioning is the same as in Q23:

\[X = (A \cdot \text{ENA}) \oplus \text{INVA} \qquad\qquad Y = B \cdot \text{ENB}\]

and the multiplexer’s eight inputs, in order, are

\(F_2 F_1 F_0\) Output
000 \(X \cdot Y\)
001 \(X + Y\)
010 \(X \oplus Y\)
011 \(\overline{X \cdot Y}\)
100 Carry in
101 Right Shift In
110 \(\overline{Y}\)
111 \(X + Y + \text{Carry in}\) (the full adder’s sum)

Every option sets \(F_2 F_1 F_0 = 111\), so every option is doing arithmetic, and every option sets ENB = 0, so \(Y = 0\) across the whole word. That reduces the adder to \(X + 0 + C_{in}\), and there are only four things it can produce:

Option INVA \(X\) \(C_{in}\) Result
(a) 0 \(A\) 0 \(A\)
(b) 1 \(\overline{A}\) 0 \(\overline{A}\), which is \(-A - 1\)
(c) 0 \(A\) 1 \(A + 1\)
(d) 1 \(\overline{A}\) 1 \(\overline{A} + 1\), which is \(-A\)

None of them is \(A - 1\), so the answer is (e).

The reason is structural rather than a matter of picking the right row. \(A - 1\) means \(A + (-1)\), i.e. adding a word of all ones. The only way this slice can conjure a constant into the adder is through the B side, and B’s conditioning is just \(Y = B \cdot \text{ENB}\) — it can force Y to 0 or pass B through, but it can never force Y to 1. The A side can be forced to all ones (ENA = 0, INVA = 1), which is how \(B - 1\) is done, but there is no matching path to put A on the other adder input. Q25 is the same observation asked directly, and the two answers corroborate each other.

Q25 — What an ALU cannot compute

For the ALU in question 24 (see Q24), which of the following arithmetic operations can NOT be performed?

  1. \(A + 1\)

  2. \(B + 1\)

  3. \(A - 1\)

  4. \(B - 1\)

  5. All of the above operations can be performed

(c)

Work through the four operations using \(X = (A \cdot \text{ENA}) \oplus \text{INVA}\), \(Y = B \cdot \text{ENB}\) and the adder selected by \(F_2 F_1 F_0 = 111\):

Operation ENA INVA ENB Carry in \(X\) \(Y\) Sum
\(A + 1\) 1 0 0 1 \(A\) 0 \(A + 1\) ✓
\(B + 1\) 0 0 1 1 0 \(B\) \(B + 1\) ✓
\(B - 1\) 0 1 1 0 all ones \(= -1\) \(B\) \(B - 1\) ✓
\(A - 1\) ? ? ? ? see below

The three that work draw on two mechanisms, and both of them live on the A side or on the carry. A \(+1\) comes free as the carry into the least significant slice, which is how \(A + 1\) and \(B + 1\) are built. A \(-1\) has to be an operand of all ones, and the only place one can be conjured is the A path: setting ENA = 0 and INVA = 1 forces X to all ones, which is \(-1\) in two’s complement, and that is how \(B - 1\) is built.

\(A - 1\) needs the mirror image — A itself on one adder input and \(-1\) on the other — and the B side cannot produce a constant. \(Y = B \cdot \text{ENB}\) is either \(B\) or zero, never all ones, and there is no inverter on the B path to make it one. So \(A - 1\) cannot be done in a single pass, and the answer is (c).

Note the asymmetry is deliberate in this style of ALU: only one operand needs constant-generating hardware, because \(B - A\), \(B - 1\) and \(-1\) all fall out of putting it on the A side. See arithmetic-logic-unit, whose table of useful control combinations shows the same pattern.

Your score

Reload the page to clear your answers.

Sample Mid-semester Exam #2

The second of UQ’s sample mid-semester papers for CSSE2010/CSSE7201 Introduction to Computer Systems — see csse2010 for the course note. The cover page is from the Semester One mid-semester examinations, 2020, for St Lucia campus students. It allows 60 minutes of working time plus 10 minutes of reading time, is an open book examination with no electronic aids other than a Casio FX82-series or UQ-approved calculator, and is answered on a supplied multiple choice answer sheet. There are 25 questions, each worth one mark, and the marking is “choose the answer which best answers the question or completes the statement” — a correct answer scores one mark, and an incorrect, missing or multiple answer scores zero. There is no penalty for guessing.

WarningAnswers are derived, not official

The source paper ships without an answer key, so every answer below was worked out during transcription rather than taken from UQ. Each one shows its reasoning so it can be checked rather than trusted; anything uncertain is flagged. Treat a disagreement between your working and the answer here as a reason to check both.

How to use this

Two ways. Timed run — sit all 25 questions in 60 minutes as if it were the real thing; on the website the answers are collapsed, so they stay hidden until you click them. Targeted practice — use the index table below to pick out only the questions for one week or one concept, and follow the wikilink to the note that covers the method.

Note that the PDF build of this vault renders every callout expanded, so the answers are visible there. Practise from the site version.

Question index

Q Topic Week Concept notes
1 Two’s complement representation 1 binary-number-representations
2 Octal, hex and decimal 1 binary-number-representations
3 Excess-N range 1 binary-number-representations
4 One’s complement to excess-N 1 binary-number-representations
5 Reading a gate circuit 1 logic-gates · boolean-algebra
6 Circuit for an XOR function 1 logic-gates
7 Boolean simplification 1 boolean-algebra
8 Truth table for an XOR chain 1 logic-gates
9 Sum of products from a table 1 boolean-algebra
10 XOR identities 1 boolean-algebra · logic-gates
11 NAND as a universal gate 1 logic-gates
12 Multiplexer as function generator 2 combinational-logic-blocks
13 Two’s complement addition 2 binary-number-representations
14 D flip-flop timing 3 flip-flops-and-latches · timing-diagrams
15 NOR SR latch behaviour 3 flip-flops-and-latches
16 Shift register with function select 3 shift-registers
17 Synchronous counter sequence 4 [counters] · sequential-circuits
18 Overflow detection 2 binary-number-representations
19 Overflow in a signed addition 2 binary-number-representations
20 State table to state diagram 4 state-machines
21 Flip-flops needed for a machine 4 state-machines
22 Tracing a state machine 4 state-machines
23 ALU control for NOR 5 arithmetic-logic-unit
24 ALU control for NOT B 5 arithmetic-logic-unit
25 Half adder from multiplexers 2 combinational-logic-blocks

Q1 — Two’s complement representation

What is \(-27_{10}\) expressed in 7-bit two’s complement format?

  1. 0011011

  2. 1011011

  3. 1100100

  4. 1100101

  5. 1100110

(d)

Two’s complement negation is “invert every bit, then add one”. Start from \(+27\) in seven bits:

\[27 = 16 + 8 + 2 + 1 = 0011011_2\]

Invert: \(1100100\). Add one: \(1100100 + 1 = 1100101\).

The distractors are the intermediate steps, which is exactly the trap: (a) is \(+27\), (c) is the one’s complement (the inverted bits, before the \(+1\)), and (b) is \(+27\) with only the sign bit flipped, i.e. sign-and-magnitude. See binary-number-representations.

Q2 — Octal, hex and decimal

\(110_8\) is equal to

  1. \(10001000_2\)

  2. \(68_{10}\)

  3. 0x48

  4. \(6_{10}\)

  5. None of the above

(c)

Octal digits are worth powers of 8, so

\[110_8 = 1 \times 8^2 + 1 \times 8^1 + 0 \times 8^0 = 64 + 8 = 72_{10}\]

Checking each option: (a) \(10001000_2 = 128 + 8 = 136\); (b) 68; (c) \(0\text{x}48 = 4 \times 16 + 8 = 72\) ✓; (d) 6.

The quick route avoids decimal altogether — each octal digit is three bits, so \(110_8 = 001\,001\,000_2 = 0100\,1000_2\), and regrouping those bits into nibbles reads straight off as 0x48. See binary-number-representations.

Q3 — Excess-N range

A 10-bit binary number in excess-512 representation can represent integers from

  1. -512 to 511

  2. -512 to 512

  3. -511 to 511

  4. -511 to 512

  5. None of the above

(a)

In excess-\(N\), the stored bit pattern is the value plus the bias: \(\text{pattern} = \text{value} + N\). Ten bits hold the unsigned patterns \(0\) through \(1023\), so with \(N = 512\):

\[\text{value} = \text{pattern} - 512 \quad\Rightarrow\quad 0 - 512 = -512 \;\text{ to }\; 1023 - 512 = 511\]

That is the same range as 10-bit two’s complement, which is the point of choosing the bias to be \(2^{n-1}\) — the two representations differ only in the most significant bit. See binary-number-representations.

Q4 — One’s complement to excess-N

How can any n-bit binary number in one’s complement representation be converted to excess-2n-1 representation?

  1. By flipping the most-significant bit and then adding 1

  2. By flipping the most-significant bit and then adding the value of the most-significant bit

  3. By adding the value of the most-significant bit and then flipping the most-significant bit

  4. By adding the value of the most-significant bit and flipping all the bits

  5. By flipping all the bits except the most-significant bit

(c)

Go through two’s complement, because each leg is a one-line rule:

  1. One’s complement → two’s complement. The two representations agree on non-negative values; for negative values the one’s complement pattern is one less than the two’s complement one. So add 1 when the number is negative and 0 when it is not — and “is it negative” is exactly the most significant bit. Adding the value of the MSB does both cases at once.
  2. Two’s complement → excess-\(2^{n-1}\). Adding the bias \(2^{n-1}\) modulo \(2^n\) is the same thing as flipping the most significant bit, because \(2^{n-1}\) is the MSB’s weight.

Doing those in order gives (c). Worked on \(n = 4\), with the pattern \(1000\) (one’s complement \(-7\)): add the MSB, \(1000 + 1 = 1001\) (two’s complement \(-7\)); flip the MSB, \(0001 = 1\), and \(-7 + 8 = 1\) ✓.

Option (b) has the same two steps in the other order, and this is where the word any in the question earns its underline. Read literally, (b) flips the MSB first, so “the value of the most-significant bit” it then adds is the flipped bit — the opposite of what is wanted. Only (c) reads the MSB while it still means “is this number negative”.

Check this one. If you read the “value of the most-significant bit” in (b) as the value it had before the flip, then (b) and (c) describe the same operation and both are correct — flipping the MSB is addition of \(2^{n-1}\) modulo \(2^n\), which commutes with adding 1. The paper can only have one answer, so the intended distinction must be the reading above, but it rests on wording rather than on arithmetic.

Q5 — Reading a gate circuit

What function is implemented by the following circuit?

Figure 244: Question 5’s circuit: a NAND on A and B, a NOR on C and D, and a NOR combining the two.

  1. \((\overline{A.B}) + (\overline{C + D})\)

  2. \(\overline{(\overline{A.B}) + (\overline{C + D})}\)

  3. \(\overline{(\bar{A}.\bar{B}) + (\overline{C + D})}\)

  4. \((\overline{A.B}) \oplus (\overline{C + D})\)

  5. \((\overline{A.B}) \oplus (C \oplus D)\)

(b)

Name the two first-stage outputs and then wrap them in the output gate. The top gate is an AND with a bubble, so it is a NAND: \(P = \overline{A \cdot B}\). The bottom gate is an OR with a bubble, so it is a NOR: \(Q = \overline{C + D}\). The output gate is an OR with a bubble, so it is a NOR of those two:

\[X = \overline{P + Q} = \overline{(\overline{A.B}) + (\overline{C+D})}\]

which is (b) verbatim. Option (a) is the same expression without the final inversion — the trap for anyone who reads the last gate as a plain OR.

Simplifying confirms it is not any of the others: De Morgan turns \(X = \overline{P + Q}\) into \(\overline{P} \cdot \overline{Q}\), and \(\overline{P}\) and \(\overline{Q}\) undo the two first-stage bubbles, so \(X = (A \cdot B) \cdot (C + D)\). The circuit is really “A and B, and at least one of C or D”. See logic-gates for the bubble-means-invert convention and boolean-algebra for De Morgan.

Q6 — Circuit for an XOR function

Which of the following circuits implements the function \(A \oplus (B + C) \oplus D\)

Figure 245: Question 6’s five candidate circuits, laid out (a) to (e) as they appear on the paper.

(a)

XOR is both commutative and associative, so the target function can be regrouped freely:

\[A \oplus (B + C) \oplus D = (A \oplus D) \oplus (B + C)\]

That is exactly circuit (a): an XOR on A and D, an OR on B and C, and an XOR joining them.

The others each break one gate. (b) replaces the OR with a NOR, giving \((A \oplus D) \oplus \overline{B + C}\) — the complement of the right answer, since inverting one input of an XOR inverts its output. (c) uses an OR as the final gate rather than an XOR. (d) swaps the two first-stage gates, giving \((A + D) \oplus (B \oplus C)\). (e) is built from NORs and computes \(\overline{\overline{A + (B+C)} + D}\), which is not an XOR of anything. See logic-gates.

Q7 — Boolean simplification

Which of the following logic functions is equivalent to \(\overline{(A + B.\bar{C}).(\overline{\bar{A} + B})}\)

  1. \(\bar{A} + B\)

  2. \(\bar{A} + C + B\)

  3. \(A.\bar{B}\)

  4. \(\bar{A}.C + B\)

  5. None of the above

(a)

Write \(P = A + B\bar{C}\) and \(Q = \bar{A} + B\), so the expression is \(\overline{P \cdot \bar{Q}}\). De Morgan turns that into a sum:

\[\overline{P \cdot \bar{Q}} = \bar{P} + \bar{\bar{Q}} = \bar{P} + Q\]

Now expand \(\bar{P}\) with De Morgan again:

\[\bar{P} = \overline{A + B\bar{C}} = \bar{A} \cdot \overline{B\bar{C}} = \bar{A}(\bar{B} + C)\]

so

\[\bar{P} + Q = \bar{A}\bar{B} + \bar{A}C + \bar{A} + B\]

Every one of the first two terms contains \(\bar{A}\), so absorption collapses them into the standalone \(\bar{A}\):

\[\bar{A}\bar{B} + \bar{A}C + \bar{A} = \bar{A}\]

leaving \(\bar{A} + B\), which is (a).

Sanity check without any algebra: the whole expression is \(\bar{P} + Q\), and \(Q = \bar{A} + B\) is false only when \(A = 1, B = 0\). In that case \(P = 1 + 0 = 1\), so \(\bar{P} = 0\) and the expression is 0 too. Whenever \(Q\) is true the expression is true. So the expression equals \(Q = \bar{A} + B\) exactly. See boolean-algebra.

Q8 — Truth table for an XOR chain

What is the truth table corresponding to \(= \bar{A} \oplus \bar{B} \oplus \bar{C}\) ?

Table 5: Question 8’s five candidate truth tables, transcribed one under the other. Each option is its own eight-row table on the paper.
A B C X
(a) 0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0
1 1 1 1
(b) 0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0
1 1 1 0
(c) 0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 0
(d) 0 0 0 1
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 1
(e) 0 0 0 1
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 0

(e)

XOR has a useful property: inverting two of its inputs leaves the result unchanged, because the two inversions cancel. Inverting an odd number of inputs inverts the output. Here all three inputs are inverted, so

\[\bar{A} \oplus \bar{B} \oplus \bar{C} = \overline{A \oplus B \oplus C}\]

and \(A \oplus B \oplus C\) is the odd-parity function — 1 when an odd number of the inputs is 1. Its complement is even parity, so \(X = 1\) exactly when the row contains an even number of 1s:

A B C number of 1s X
0 0 0 0 1
0 0 1 1 0
0 1 0 1 0
0 1 1 2 1
1 0 0 1 0
1 0 1 2 1
1 1 0 2 1
1 1 1 3 0

That column is 1 0 0 1 0 1 1 0, which is option (e). Option (a) is the exact complement of it — odd parity, i.e. the answer you get if you forget that three inversions do not cancel.

The paper writes the question as “corresponding to \(= \bar{A} \oplus \bar{B} \oplus \bar{C}\)”, with a stray equals sign; the function is clearly meant to be \(X = \bar{A} \oplus \bar{B} \oplus \bar{C}\). See logic-gates.

Q9 — Sum of products from a table

Consider the logic function represented by the following truth table:

A B C X
0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1

Which of the following expressions is equivalent to the function represented by this table?

  1. \(\bar{A}.B + A.C\)

  2. \(A.C + (B + C)\)

  3. \(\bar{A}.B + C\)

  4. \(\bar{A}.B + B.C + \bar{A}.C\)

  5. None of the above

(c)

Read off the rows where \(X = 1\): 001, 010, 011, 101, 111. As a sum of products,

\[X = \bar{A}\bar{B}C + \bar{A}B\bar{C} + \bar{A}BC + A\bar{B}C + ABC\]

Four of those five minterms — 001, 011, 101, 111 — are every row with \(C = 1\), and together they simplify to just \(C\). That leaves 010, i.e. \(\bar{A}B\bar{C}\):

\[X = C + \bar{A}B\bar{C}\]

and \(C + \bar{A}B\bar{C} = C + \bar{A}B\) by absorption (adding \(\bar{A}B\) where \(C\) is already 1 changes nothing). So \(X = \bar{A}.B + C\), which is (c).

Checking (c) against all eight rows: it is 1 whenever \(C = 1\) (four rows) and, among the \(C = 0\) rows, only for \(A=0, B=1\) — exactly the five rows above. See boolean-algebra.

Q10 — XOR identities

Which of the following logic functions is identical to \(\bar{A} \oplus \bar{B}\)?

  1. \(A.\bar{B} + \bar{A}.B\)

  2. \(\bar{A}.\bar{B} + \bar{B}.\bar{A}\)

  3. \(\bar{A} + \bar{B}\)

  4. \(\overline{A \oplus B}\)

  5. None of the above

(a)

Inverting both inputs of a two-input XOR leaves it unchanged — the two inversions cancel, as in Q8:

\[\bar{A} \oplus \bar{B} = A \oplus B\]

and the definition of XOR is \(A \oplus B = A\bar{B} + \bar{A}B\), which is (a) as written.

The others: (b) is \(\bar{A}\bar{B} + \bar{A}\bar{B} = \bar{A}\bar{B}\), i.e. NOR, since the two product terms are the same term written in the opposite order. (c) is NAND, by De Morgan. (d) is XNOR — the complement of the right answer, and the trap for treating the two bars as if they inverted the result once rather than twice. See boolean-algebra.

Q11 — NAND as a universal gate

Which of the following implements a 3-input NAND gate \((\overline{A.B.C})\) using only 2-input NAND gates?

Figure 246: Question 11’s five candidate NAND-only circuits. Where a NAND’s two inputs are tied together it is acting as an inverter.

(b)

A NAND with both inputs tied together is an inverter, since \(\overline{X \cdot X} = \bar{X}\). That is the only extra building block needed, because the target \(\overline{ABC}\) is “AND the three, then invert”, and a NAND followed by an inverter is an AND.

Working through (b): the first NAND gives \(\overline{AB}\); the second has its inputs tied, so it inverts that back to \(AB\); the third NANDs \(AB\) with \(C\):

\[\overline{(A \cdot B) \cdot C} = \overline{A.B.C} \;✓\]

The others:

  • (a) \(\overline{\overline{AB} \cdot C}\) — no inverter between the stages, so the first NAND’s inversion is still in the expression.
  • (c) inverts at the end instead: \(\overline{\overline{\overline{AB} \cdot C}} = \overline{AB} \cdot C\).
  • (d) inverts C rather than the first NAND’s output: \(\overline{\overline{AB} \cdot \bar{C}}\).
  • (e) is (b) with one more inverter tacked on, so it produces \(A.B.C\) — the AND, not the NAND.

See logic-gates for why NAND is a universal (complete) gate.

Q12 — Multiplexer as function generator

Consider the following multiplexer. What must the inputs A,B,C,D be so that the multiplexer implements the function \(X = S_0 + (S_1 \oplus G)\)?

Figure 247: Question 12’s 4-to-1 multiplexer: data inputs A, B, C, D on lines 0 to 3, select lines \(S_1\) and \(S_0\), and output X.

  1. A=1 B=\(G\) C=1 D=\(\bar{G}\)

  2. A=\(G\) B=\(\bar{G}\) C=1 D=1

  3. A=\(\bar{G}\) B=1 C=\(G\) D=1

  4. A=\(G\) B=1 C=\(\bar{G}\) D=1

  5. None of the above

(d)

A 4-to-1 multiplexer passes input \(S_1S_0\) through to the output, so each data input only has to be right for its own select combination. Substitute each combination into the target function and see what is left, treating \(G\) as an ordinary variable rather than a select line:

\(S_1\) \(S_0\) selected input \(X = S_0 + (S_1 \oplus G)\) so the input must be
0 0 A \(0 + (0 \oplus G) = G\) \(G\)
0 1 B \(1 + \ldots = 1\) 1
1 0 C \(0 + (1 \oplus G) = \bar{G}\) \(\bar{G}\)
1 1 D \(1 + \ldots = 1\) 1

So A=\(G\), B=1, C=\(\bar{G}\), D=1 — option (d). The two rows with \(S_0 = 1\) are constants because the OR is already satisfied, and the two with \(S_0 = 0\) reduce to \(S_1 \oplus G\) evaluated at that value of \(S_1\). See combinational-logic-blocks.

Q13 — Two’s complement addition

What is the result of adding the 6-bit two’s complement numbers 101111 and 101001?

  1. 010000

  2. 010111

  3. 011000

  4. 111000

  5. None of the above

(c)

Addition in two’s complement is plain binary addition with the carry out of the top bit discarded:

\[\begin{array}{r} 101111 \\ +\; 101001 \\ \hline 1\,011000 \end{array}\]

Column by column from the right: \(1+1 = 0\) carry 1; \(1+0+1 = 0\) carry 1; \(1+0+1 = 0\) carry 1; \(1+1+1 = 1\) carry 1; \(0+0+1 = 1\); \(1+1 = 0\) carry 1 out of the word. Keeping six bits gives 011000.

It is worth noticing that this result is wrong as arithmetic: \(101111\) is \(-17\) and \(101001\) is \(-23\), so the true sum is \(-40\), which does not fit in the range \(-32\) to \(31\). Two negatives have produced a positive result (\(011000 = +24\)), which is the overflow signature. The question asks only what the adder produces, and that is (c). See binary-number-representations.

Q14 — D flip-flop timing

Consider the flip-flop circuit shown below and the associated CLK and output (Q) signals. Which timing diagram shows input (A) values over time which would have resulted in the given output (Q).

Figure 248: Question 14’s positive-edge-triggered D flip-flop, the given CLK and Q waveforms, and the five candidate A waveforms.

(b)

The flip-flop is positive-edge triggered (the wedge on the clock input, with no bubble), so Q takes the value A had just before each rising edge of CLK, and holds it until the next one. There are four rising edges. Reading Q:

rising edge Q before Q after so A must have been
1st 1 0 0
2nd 0 1 1
3rd 1 1 1
4th 1 0 0

So the required pattern of A, sampled at the four rising edges, is 0, 1, 1, 0. Checking each candidate at those four instants:

  • (a) 0, 1, 0, — : fails at the third edge, where Q stays high but A has just gone low. Note also that (a) changes exactly on the clock edges, which is what a real design goes out of its way to avoid.
  • (b) 0, 1, 1, 0 ✓ — and every one of its transitions sits comfortably away from an edge, so there is no ambiguity about which value is sampled.
  • (c) 0, 1, 1, 1 : fails at the fourth edge, where Q falls but A is still high.
  • (d) 0, 1, 0, 1 : fails at the third and fourth edges.
  • (e) 0, 1, 1, 1 : the single wide pulse is still high at the fourth edge, so Q would not fall.

The third edge is the interesting one — Q does not change there, which does not mean A was ignored; it means A happened to equal the value already stored. See flip-flops-and-latches and timing-diagrams.

Q15 — NOR SR latch behaviour

Which truth table correctly captures the behaviour of the following latch circuit?

Figure 249: Question 15’s cross-coupled NOR latch. The top gate takes M and the Q feedback and drives \(\overline{Q}\); the bottom gate takes N and the \(\overline{Q}\) feedback and drives Q.

Table 6: Question 15’s four candidate truth tables, transcribed one under the other. Each option is its own four-row table on the paper.
M N Q \(\overline{Q}\)
(a) 0 0 Q \(\overline{Q}\)
0 1 1 0
1 0 0 1
1 1 0 0
(b) 0 0 Q \(\overline{Q}\)
0 1 0 1
1 0 1 0
1 1 1 1
(c) 0 0 Q \(\overline{Q}\)
0 1 0 1
1 0 1 0
1 1 0 0
(d) 0 0 0 0
0 1 1 0
1 0 0 1
1 1 Q \(\overline{Q}\)
  1. None of the above

(c)

This is the standard cross-coupled NOR SR latch, with M in the set position and N in the reset position. A NOR outputs 1 only when both its inputs are 0, so any input driven to 1 forces that gate’s output to 0 regardless of the feedback — which is what makes the analysis easy.

  • M=1, N=0. The top NOR sees a 1, so \(\overline{Q} = 0\). The bottom NOR then sees \(0\) and \(0\), so \(Q = 1\). Set.
  • M=0, N=1. The bottom NOR sees a 1, so \(Q = 0\). The top NOR then sees \(0\) and \(0\), so \(\overline{Q} = 1\). Reset.
  • M=0, N=0. Neither gate is forced. Each output feeds the other’s input, so whichever state the latch was already in satisfies both gates and persists. Hold.
  • M=1, N=1. Both gates are forced, so \(Q = 0\) and \(\overline{Q} = 0\). The two outputs are no longer complementary — this is the forbidden combination, and it is why the pair of names Q and \(\overline{Q}\) stops being honest here.

That gives hold, reset, set, 0 0 — option (c). Option (a) has set and reset swapped; (b) puts 1 1 in the forbidden row, which is what a NAND latch would do; (d) puts the hold row in the wrong place entirely. See flip-flops-and-latches.

Q16 — Shift register with function select

Which of the following statements about this shift register circuit is false?

Figure 250: Question 16’s two-stage register. Each stage is a 2-to-1 multiplexer feeding a D flip-flop; input 1 of each multiplexer is that stage’s own \(\overline{Q}\), so FN=1 makes both flip-flops toggle.

  1. If FN is 0, the value of A will be transferred to OUT after two rising clock edges

  2. If FN is 1, OUT will toggle on each rising clock edge

  3. If FN is 0, data is shifted to the right on each rising clock edge

  4. If FN is 1, the value of A is irrelevant

  5. All of the above are true

(e)

Trace what FN selects. Each multiplexer’s input 0 is the data coming from the left (A for the first stage, the first flip-flop’s Q for the second), and each input 1 is a feedback wire from that same stage’s own \(\overline{Q}\). FN drives both select lines together, so:

  • FN = 0 — every flip-flop’s D is the value to its left: \(D_1 = A\) and \(D_2 = Q_1\). That is a two-bit shift register.
  • FN = 1 — every flip-flop’s D is its own \(\overline{Q}\), so each one inverts itself on every rising edge. That is a toggle, and the A input is disconnected from the datapath entirely.

Now each statement:

  • (a) With FN=0, A is clocked into the first flip-flop on one edge and out to OUT on the next — two rising edges. True.
  • (b) With FN=1, \(D_2 = \overline{Q_2}\), so OUT toggles every rising edge. True.
  • (c) Data moves from A through the first stage to the second, which is left-to-right as drawn. True.
  • (d) With FN=1 both multiplexers select input 1, so A reaches nothing. True.

Nothing among (a) to (d) is false, so the answer is the option that says so: (e). See shift-registers.

The wording is a little awkward — the question asks which statement is false, and (e) is not itself a candidate false statement but a summary of the other four. Selecting it is the paper’s way of saying “none of them is false”.

Q17 — Synchronous counter sequence

What sequence will the following synchronous counter count through, if it starts at \(Q_1Q_0 = 00\)?

Figure 251: Question 17’s two-flip-flop synchronous counter. The OR gate is drawn mirrored, as on the paper: its output faces left into the first flip-flop’s D input, and its two inputs are fed from \(Q_0\) and \(\overline{Q_1}\).

  1. \(Q_1Q_0\): 00 → 01 → 11 → 10 → 10 → …

  2. \(Q_1Q_0\): 00 → 01 → 11 → 00 → …

  3. \(Q_1Q_0\): 00 → 11 → 01 → 00 → …

  4. \(Q_1Q_0\): 00 → 11 → 10 → 00 → …

  5. None of the above

(d)

First read the excitation equations off the schematic. The left flip-flop holds \(Q_1\) (its Q output runs down to the \(Q_1\) label) and the right one holds \(Q_0\). The left flip-flop’s \(\overline{Q}\) output is the wire that goes right and then splits: it feeds the second flip-flop’s D input and, going up, one input of the OR gate. The OR gate’s other input comes from the long wire across the top, which runs to the \(Q_0\) node. The OR gate’s output goes back left into the first flip-flop’s D. So:

\[D_1 = Q_0 + \overline{Q_1} \qquad\qquad D_0 = \overline{Q_1}\]

Both flip-flops share one clock, so both D values are computed from the present state and land together on the edge. Tabulating:

\(Q_1 Q_0\) \(\overline{Q_1}\) \(D_1 = Q_0 + \overline{Q_1}\) \(D_0 = \overline{Q_1}\) next \(Q_1Q_0\)
0 0 1 1 1 1 1
1 1 0 1 0 1 0
1 0 0 0 0 0 0
0 1 1 1 1 1 1

Starting from 00 the sequence is \(00 \to 11 \to 10 \to 00 \to \dots\), a three-state cycle — option (d). The fourth row shows the unused state 01 drops into the cycle on the next edge, so the counter cannot lock up outside it.

The mirrored OR gate is the thing to get right when reading the paper’s drawing: the single wire on its pointed left-hand side is the output, and the two wires on its curved right-hand side are the inputs. See [counters] and sequential-circuits.

Q18 — Overflow detection

Which of the following operations will result in an overflow in 4-bit two’s complement arithmetic?

  1. 0111+0111

  2. 1111+1111

  3. 1010+0110

  4. All of the above result in overflow

  5. None of the above

(a)

The rule for two’s complement is that overflow happens only when both operands have the same sign and the result has the other one. Adding numbers of opposite signs can never overflow, because the result lies between them. Four bits cover \(-8\) to \(+7\).

  • (a) \(0111 + 0111 = 7 + 7 = 14\). In binary \(0111 + 0111 = 1110\), which reads as \(-2\). Two positives gave a negative: overflow.
  • (b) \(1111 + 1111 = (-1) + (-1) = -2\). In binary \(1111 + 1111 = 1\,1110\); discarding the carry out leaves \(1110 = -2\) ✓. Two negatives gave a negative, and \(-2\) is in range: no overflow. The carry out of the top bit is not itself overflow.
  • (c) \(1010 + 0110 = (-6) + 6 = 0\). In binary \(1010 + 0110 = 1\,0000 \to 0000\) ✓. Opposite signs, so it cannot overflow: no overflow.

Only (a) overflows, so (d) and (e) are both out. See binary-number-representations, and Beyond the paper below for the gate circuit that decides this same question from the sign bits alone.

Q19 — Overflow in a signed addition

Consider the binary addition operation 1011 + 1111. Which of the following statements is true if the numbers are interpreted as two’s complement?

  1. The result is negative and no overflow occurs

  2. The result should be negative but overflow occurs

  3. The result is positive and no overflow occurs

  4. The result should be positive but overflow occurs

  5. The result is zero

(a)

Decode both operands. \(1011\): invert and add one gives \(0100 + 1 = 0101 = 5\), so \(1011 = -5\). \(1111\): invert and add one gives \(0000 + 1 = 0001\), so \(1111 = -1\). The true sum is \(-6\), which is comfortably inside the 4-bit range \(-8\) to \(+7\), so no overflow is possible.

Doing the addition:

\[\begin{array}{r} 1011 \\ +\; 1111 \\ \hline 1\,1010 \end{array}\]

Discarding the carry out leaves \(1010\), which decodes as \(-(0101 + 1) = -6\) ✓ — negative, correct, and matching the sign of both operands, which is the overflow test passing.

The carry out of the most significant bit is 1 here, and that is the trap: in two’s complement a carry out is normal and is simply discarded. Overflow is a sign condition, not a carry condition. See binary-number-representations — and Beyond the paper below, where the carry-based rule \(V = C_3 \oplus C_4\) has to be rewritten because a real 4-bit adder chip never brings \(C_3\) out to a pin.

Q20 — State table to state diagram

Consider the following state table:

Current State Next State (A=0) Next State (A=1) Outputs (X,Y)
SA SA SB 0 0
SB SA SC 0 0
SC SA SD 0 1
SD SD SE 1 0
SE SA SE 1 1

Which of the following state diagrams is an equivalent representation of this state table? (Input: A, Outputs: XY)

Figure 252: Question 20’s four candidate state diagrams, laid out (a) to (d) as on the paper. Option (e) is None of the above.

  1. None of the above

(c)

Check the two things the table specifies — the output written under each state name, and where each of the two arrows out of each state goes.

Outputs. The table gives SA=00, SB=00, SC=01, SD=10, SE=11. Options (a) and (d) both label SC as 10 and SD as 01, i.e. the two are swapped, so both are out immediately. That leaves (b) and (c), which have the outputs right.

Transitions. The table’s five rows are: SA self-loops on 0 and goes to SB on 1; SB returns to SA on 0 and goes to SC on 1; SC returns to SA on 0 and goes to SD on 1; SD self-loops on 0 and goes to SE on 1; SE returns to SA on 0 and self-loops on 1.

Diagram (b) has SD’s 0-transition going back to SA rather than staying in SD, which contradicts the SD row. Diagram (c) has the self-loop on SD, and matches every other row as well, so (c) is the answer.

Worth checking completeness while you are there: each state in (c) has exactly two arrows out, one labelled 0 and one labelled 1, which is what a one-input machine needs — no missing case and no ambiguity. See state-machines.

Q21 — Flip-flops needed for a machine

Consider the state machine represented by the state table in question 20 above (see Q20). What is the minimum number of flip-flops needed to implement this state machine?

  1. 2

  2. 3

  3. 4

  4. 5

  5. 7

(b)

\(N\) flip-flops hold \(N\) bits, so they can encode at most \(2^N\) distinct states. The machine has five states (SA to SE), so the requirement is

\[2^N \ge 5 \quad\Rightarrow\quad N \ge \log_2 5 = 2.32\ldots \quad\Rightarrow\quad N = \lceil \log_2 5 \rceil = 3\]

Two flip-flops give only four codes, one short. Three give eight, so five states fit with three codes left unused.

The distractors are the two other plausible counting rules: (d) 5 is one flip-flop per state, which is the one-hot encoding — legal, and often the one that makes the combinational logic simplest, but not the minimum. (c) 4 and (e) 7 do not correspond to anything. See state-machines for the encoding choices.

Q22 — Tracing a state machine

Consider the state machine represented by the state diagram below:

Figure 253: Question 22’s state machine: one input A, outputs X and Y, and five states each with an A and an \(\overline{A}\) transition.

What sequence of states is traversed if the machine starts in state S0 and A goes through the sequence 11110000 (i.e. four 1’s followed by four 0’s)?

  1. S0→S1→S1→S1→S1→S2→S3→S0→S0

  2. S0→S1→S3→S1→S3→S0→S0→S0→S0

  3. S0→S1→S1→S1→S2→S3→S2→S0→S0

  4. S0→S1→S1→S1→S1→S2→S4→S3→S0

  5. None of the above

(a)

Read the transitions off the diagram first:

State on \(\overline{A}\) (0) on \(A\) (1)
S0 S0 (self-loop) S1
S1 S2 S1 (self-loop)
S2 S3 S4
S3 S0 S1
S4 S3 S0

Now walk the eight inputs from S0, one clock edge per input:

step input from to
1 1 S0 S1
2 1 S1 S1
3 1 S1 S1
4 1 S1 S1
5 0 S1 S2
6 0 S2 S3
7 0 S3 S0
8 0 S0 S0

Including the starting state, that is S0→S1→S1→S1→S1→S2→S3→S0→S0 — nine entries for a start state plus eight inputs, which is option (a). Note that each of the listed options has nine entries, so the count itself is not a discriminator here; the run of self-loops on S1 while A stays at 1, and the fact that S0 self-loops once the input has gone to 0 and the machine has come home, are what pick (a) out. See state-machines.

Q23 — ALU control for NOR

Consider the ALU bit slice below (not the same as seen previously).

Figure 254: Question 23’s ALU bit slice. The gates at the left condition A and B into the internal signals routed on the two vertical rails; the eight function blocks compute in parallel; the 8-to-1 multiplexer picks one under F2 F1 F0. Carry out is the AND of the two conditioned inputs, ORed with a propagate term gated by the function select.

For an ALU made up of 8 of the bit slices above, which of the following control input settings will result in the ALU output being \(\overline{A + B}\) (bitwise)? (The “Right Shift In” control input refers to that for the most significant bit; the “Carry in” control input refers to that for the least significant bit.)

  1. ENA=1 ENB=1 INVA=0 F2=0 F1=0 F0=1 Right Shift In=1 Carry in=1

  2. ENA=1 ENB=1 INVA=0 F2=0 F1=1 F0=0 Right Shift In=1 Carry in=1

  3. ENA=1 ENB=1 INVA=1 F2=0 F1=0 F0=1 Right Shift In=1 Carry in=1

  4. ENA=1 ENB=1 INVA=1 F2=0 F1=1 F0=0 Right Shift In=1 Carry in=1

  5. None of the above

(b)

Read the slice in two halves, exactly as in arithmetic-logic-unit.

Input conditioning. The left-hand gates produce two internal signals:

\[X = (A \cdot \text{ENA}) \oplus \text{INVA} \qquad\qquad Y = B \cdot \text{ENB}\]

These are what every function block actually sees. \(X\) is also what leaves the slice as Right Shift Out.

Function select. \(F_2 F_1 F_0\) is the select code of the 8-to-1 multiplexer, so reading the blocks down the middle of the drawing from the top:

\(F_2 F_1 F_0\) mux input Output
000 0 \(X \cdot Y\)
001 1 \(X + Y\)
010 2 \(\overline{X + Y}\)
011 3 \(X \oplus Y\)
100 4 Carry In
101 5 Right Shift In
110 6 \(\overline{Y}\)
111 7 \(X \oplus Y \oplus C_{in}\) (the sum)

The target is \(\overline{A + B}\), a bitwise NOR. So the conditioning must pass both operands through untouched — ENA=1, INVA=0 gives \(X = A\), and ENB=1 gives \(Y = B\) — and the select must pick the NOR block, which is \(F_2F_1F_0 = 010\).

That is option (b). Checking the others: (a) selects 001, the plain OR, giving \(A + B\) rather than its complement; (c) selects 001 with INVA=1, giving \(\overline{A} + B\); (d) has the right select but INVA=1, so it computes \(\overline{\overline{A} + B}\). The Right Shift In and Carry in values are irrelevant once a purely logical function is selected, which is why all four options can share them.

Q24 — ALU control for NOT B

For an ALU made up of 8 of the bit slices shown in question 23 above (see Q23), which of the following control input settings will NOT result in the ALU output being \(\overline{B}\) (bitwise)?

  1. ENA=0 ENB=1 INVA=0 F2=0 F1=1 F0=0 Right Shift In=0 Carry in=0

  2. ENA=0 ENB=1 INVA=1 F2=0 F1=1 F0=1 Right Shift In=0 Carry in=0

  3. ENA=0 ENB=1 INVA=1 F2=1 F1=1 F0=0 Right Shift In=0 Carry in=0

  4. ENA=0 ENB=1 INVA=1 F2=1 F1=1 F0=1 Right Shift In=0 Carry in=0

  5. All of the above result in the ALU output being \(\overline{B}\) (bitwise)

(d)

Every option has ENA=0 and ENB=1, so from the conditioning equations in Q23:

\[X = (A \cdot 0) \oplus \text{INVA} = \text{INVA} \qquad\qquad Y = B\]

That is, the A side is forced to a constant — all zeros when INVA=0, all ones when INVA=1 — and the B side passes through. Now take each option’s select code:

  • (a) 010 selects \(\overline{X + Y}\). With INVA=0, \(X\) is all zeros, and \(\overline{0 + B} = \overline{B}\) ✓.
  • (b) 011 selects \(X \oplus Y\). With INVA=1, \(X\) is all ones, and \(1 \oplus B = \overline{B}\) ✓. This is the “XOR with all ones inverts” trick.
  • (c) 110 selects \(\overline{Y} = \overline{B}\) ✓. INVA does not matter here, because the inverter block never looks at \(X\).
  • (d) 111 selects the adder: \(X \oplus Y \oplus C_{in}\), with the carry rippling from slice to slice. With \(X\) all ones and the external carry in 0, the machine computes \((-1) + B\), i.e. \(B - 1\) — not \(\overline{B}\).

So (d) is the odd one out. The distinction between (b) and (d) is the whole point of the question: mux input 3 is a bitwise XOR with no carry involved, so it really does produce \(\overline{B}\), whereas mux input 7 is the same XOR plus the carry chain, and once carries propagate the result is arithmetic rather than bitwise. Adding all-ones to \(B\) decrements it; only \(B = 0\) (and, in eight bits, \(B = -128\)) happens to satisfy \(B - 1 = \overline{B}\).

The question does not depend on which way round the select bits go, which is a small mercy. The four codes offered are 010, 011, 110 and 111; reversing the bit order maps that set onto itself, swapping (b) and (c) with each other and leaving (a) and (d) where they are. So (d) is still the only failure if \(F_0\) is read as the most significant bit — the answer is the same either way. See arithmetic-logic-unit.

Q25 — Half adder from multiplexers

Consider the half-adder shown below:

In the multiplexer circuit below, what values do the multiplexer inputs X0,X1,X2,X3 and Y0,Y1,Y2,Y3 need to take on in order for the circuit to implement a half-adder?

(Both drawings the question refers to are combined into Figure 255: the half-adder block on top, the two multiplexers underneath.)

Figure 255: Question 25’s half adder block and the pair of 4-to-1 multiplexers meant to implement it, one for Sum and one for \(C_{out}\), both selected by A and B.

Table 7: Question 25’s four candidate settings, transcribed one per row. On the paper each option is drawn as a pair of four-cell boxes.
X0 X1 X2 X3 Y0 Y1 Y2 Y3
(a) 0 0 0 1 0 1 1 0
(b) 0 1 1 0 0 0 1 1
(c) 0 1 1 0 0 0 0 1
(d) 0 1 1 0 1 0 0 0
  1. None of the above

(c)

A half adder is just the truth table of two bits added:

A B Sum \(= A \oplus B\) \(C_{out} = A \cdot B\)
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1

Both multiplexers are selected by the same pair of lines, with A on \(S_1\) and B on \(S_0\), so input \(n\) of each multiplexer is the one reached when \(AB\) is the two-bit number \(n\): input 0 for \(AB = 00\), input 1 for \(01\), input 2 for \(10\), input 3 for \(11\). Using a multiplexer this way turns it into a direct lookup of a truth table — the data inputs are the output column, in row order.

Reading the Sum column down gives \(X_0X_1X_2X_3 = 0, 1, 1, 0\), and reading the \(C_{out}\) column gives \(Y_0Y_1Y_2Y_3 = 0, 0, 0, 1\). That is option (c).

The distractors are the same two columns misassigned: (a) has them swapped between the two multiplexers, (b) has \(C_{out}\) set for \(AB = 10\) as well as \(11\), and (d) has the \(C_{out}\) column reversed. See combinational-logic-blocks.

Beyond the paper — building the overflow detector

Q18 and Q19 are both answered on paper the same way: decode the operands into decimal, look at the signs, decide. Learning Lab 3 (Binary Arithmetic) asks the same question the way hardware has to answer it — with gates, on a real adder chip, where nothing is in decimal and not every carry is even visible.

This is the extension to Task 2 of Learning Lab 3 (Binary Arithmetic). Both circuits below are derived from the constraint and checked against the truth table. week2-lab-binary-arithmetic covers the rest of that lab.

The constraint the chip imposes

Task 2 of the lab builds a 4-bit adder from a 74HCT283 — a single 16-pin part holding four full adders with the intermediate carries \(C_1\), \(C_2\) and \(C_3\) wired stage to stage inside the package, so only \(C_0\) (carry in) and \(C_4\) (carry out) come out on pins. See device-pinouts for the pinout and symbol.

The rule Q19’s answer appeals to is usually written in terms of the carries around the sign bit:

\[V = C_3 \oplus C_4\]

— overflow exactly when the carry into the sign column differs from the carry out of it. The lab’s extension task kills that formula in one line: “you don’t have access to C3 which is an internal signal. Therefore, you need the overflow output expressed in terms of available information (i.e. A3, B3, S3, C4).”

So the detector has to be built from the sign bit of each operand, the sign bit of the result, and the carry out.

Two detectors that use only pins

Figure 256: Two gate-level answers to Lab 3’s extension task, both using only signals the 74HCT283 brings out to pins. (a) compares signs directly: the inverted XOR is true when the two operands agree in sign, the second XOR is true when the result disagrees with them, and overflow is the AND of the two. (b) rebuilds the hidden carry: since stage 3 is a full adder, \(C_3 = A_3 \oplus B_3 \oplus S_3\), so the textbook \(V = C_3 \oplus C_4\) becomes a chain of three XORs. Both are derived here — the lab poses the task and gives no solution.

(a) compares signs directly. Overflow means the two operands agreed in sign and the answer came out with the other one, which as a sum of products is

\[V = A_3 B_3 \overline{S_3} + \overline{A_3}\,\overline{B_3}\,S_3 = \overline{(A_3 \oplus B_3)} \cdot (A_3 \oplus S_3)\]

(b) rebuilds the carry the chip hid. Stage 3 is a full adder, so \(S_3 = A_3 \oplus B_3 \oplus C_3\); XOR is its own inverse, so \(C_3 = A_3 \oplus B_3 \oplus S_3\). Substituting into \(V = C_3 \oplus C_4\):

\[V = A_3 \oplus B_3 \oplus S_3 \oplus C_4\]

That is why \(C_4\) is listed among the available signals: it is the only one of the four that (a) does not use, and its presence in the list is the hint that a carry-based answer exists.

Form (b) is the one to build. Its three gates are all the same type, so they come out of one 74HCT86 with a gate spare; form (a) as drawn mixes three types and so needs three packages. (Form (a) can be squeezed onto fewer, since an XOR with one input tied to logic high is an inverter and the pinout sheet gives a symbol for logic high — but it is still four gates against three, and two chips against one.) See device-pinouts for the parts and circuit-schematics for what turns either of these logic diagrams into a buildable schematic.

Checking both against the truth table

\(C_3\) and \(C_4\) below are what the top stage of the adder must have been doing for that combination of \(A_3\), \(B_3\) and \(S_3\) (\(C_3 = A_3 \oplus B_3 \oplus S_3\), and \(C_4\) is the majority of \(A_3\), \(B_3\) and \(C_3\)):

\(A_3\) \(B_3\) \(S_3\) \(C_3\) \(C_4\) \(V\)
0 0 0 0 0 0
0 0 1 1 0 1
0 1 0 1 1 0
0 1 1 0 0 0
1 0 0 1 1 0
1 0 1 0 0 0
1 1 0 0 1 1
1 1 1 1 1 0

\(V\) is 1 in exactly two rows — two positives giving a negative, and two negatives giving a positive — which is the rule Q18 applies by hand. Both expressions reproduce that column.

The detector reproduces the paper answers

Run the four sign patterns from Q18 and Q19 through the table. Only the top bits matter:

From Sum \(A_3 B_3 S_3\) \(V\) Matches
Q18 (a) \(0111 + 0111\) \(1110\) 0 0 1 1 overflow ✓
Q18 (b) \(1111 + 1111\) \(1110\) 1 1 1 0 no overflow, despite \(C_4 = 1\) ✓
Q18 (c) \(1010 + 0110\) \(0000\) 1 0 0 0 opposite signs cannot overflow ✓
Q19 \(1011 + 1111\) \(1010\) 1 1 1 0 negative, no overflow ✓

Row two is the whole point of Q19’s last paragraph, now visible as wiring: \(C_4\) is 1 there, but \(C_4\) is not an input to the sign comparison at all in form (a), and in form (b) it is cancelled by \(C_3\), which is also 1. A carry out is not an overflow — the detector is built so that it cannot confuse the two, which is exactly why the LED for it is a separate output from the carry LED. See binary-number-representations and combinational-logic-blocks.

Your score

Reload the page to clear your answers.

Sample Mid-semester Exam #3

This is the third of UQ’s published sample mid-semester papers for CSSE2010/CSSE7201 Introduction to Computer Systems (see csse2010 for the course note). The cover sheet is dated Semester One Mid-semester Examinations, 2020, for St Lucia campus students. It allows 60 minutes of working time plus 10 minutes of reading time, and it is an open book examination — no electronic aids, but a Casio FX82-series or other UQ-approved calculator is permitted. There are 25 multiple-choice questions answered on a supplied answer sheet; a correct answer scores one mark, and an incorrect, missing or multiple answer scores zero. There is no penalty for guessing, so leaving a question blank is never the right move.

WarningAnswers are derived, not official

The source paper ships without an answer key, so every answer below was worked out during transcription rather than taken from UQ. Each one shows its reasoning so it can be checked rather than trusted; anything uncertain is flagged. Treat a disagreement between your working and the answer here as a reason to check both.

How to use this

Two ways. The first is a timed run: 25 questions in 60 minutes is a little over two minutes each, and on the website every answer is collapsed behind a disclosure triangle, so you can work the whole paper without seeing anything. The second is targeted practice — the index table below gives the week and the concept note for each question, so you can pick out just the questions covering one topic.

Note that the PDF build of this note has every answer expanded, because a PDF cannot hide them. Practise from the site version.

Question index

Q Topic Week Concept notes
1 Excess-256 representation 1 binary-number-representations
2 Hexadecimal, binary and octal 1 binary-number-representations
3 Signed magnitude range 1 binary-number-representations
4 Two’s to one’s complement 1 binary-number-representations
5 Reading a gate circuit 1 logic-gates
6 Boolean simplification 2 boolean-algebra
7 Building a sum of products 2 logic-gates · boolean-algebra
8 Expression from a truth table 2 boolean-algebra
9 NAND-only implementation 2 logic-gates · boolean-algebra
10 NAND latch behaviour 3 flip-flops-and-latches
11 Which circuit is a latch 3 flip-flops-and-latches
12 Timing diagram of a function 2 timing-diagrams · logic-gates
13 Multiplexer as a function 2 combinational-logic-blocks
14 Two’s complement addition 2 binary-number-representations
15 Detecting overflow 2 binary-number-representations
16 Interpreting an overflow 2 binary-number-representations
17 D flip-flop timing 3 flip-flops-and-latches · timing-diagrams
18 Load-or-swap register pair 3 sequential-circuits · shift-registers
19 Flip-flops for a sequence 4 [counters] · state-machines
20 Tracing a synchronous counter 4 [counters]
21 Counter width 4 [counters]
22 State diagram to state table 4 state-machines
23 Tracing a state machine 4 state-machines
24 ALU control settings 5 arithmetic-logic-unit
25 What the ALU cannot do 5 arithmetic-logic-unit

Q1 — Excess-256 representation

What is \(-57_{10}\) expressed in 9-bit excess-256 format?

  1. 000111001

  2. 011000111

  3. 100111001

  4. 111000111

  5. None of the above

(b)

Excess-\(K\) stores a value \(v\) as the plain unsigned binary of \(v + K\). With \(K = 256\):

\[-57 + 256 = 199\]

and \(199 = 128 + 64 + 4 + 2 + 1 = 11000111_2\). Padded to nine bits that is \(011000111\).

The distractors are the recognisable wrong turns: (d) is the same magnitude bits with a leading 1 (as if the bias had been applied and then a sign bit added), and (a) and (c) are \(+57 = 00111001\) dressed up. See binary-number-representations.

Q2 — Hexadecimal, binary and octal

0xB9 is equal to

  1. \(11001001_2\)

  2. \(10101001_2\)

  3. \(169_{10}\)

  4. \(201_{10}\)

  5. \(271_8\)

(e)

Hex digits map straight onto nibbles: \(\mathrm{B} = 1011\) and \(9 = 1001\), so \(\mathrm{0xB9} = 10111001_2 = 185_{10}\).

None of (a)–(d) is 185: \(11001001_2 = 201\), \(10101001_2 = 169\), and (c) and (d) name those same two decimal values. So the paper has cross-paired its distractors — each wrong binary answer has its own decimal value sitting next to it as a separate option.

Octal groups the bits in threes from the right: \(10\,111\,001 \to 2, 7, 1\), so \(\mathrm{0xB9} = 271_8\). Checking, \(2 \times 64 + 7 \times 8 + 1 = 128 + 56 + 1 = 185\). See binary-number-representations.

Q3 — Signed magnitude range

A 6-bit binary number in signed magnitude representation can represent integers from

  1. -32 to 32

  2. -32 to 31

  3. -31 to 31

  4. 0 to 31

  5. None of the above

(c)

Signed magnitude spends the most significant bit on the sign and leaves the remaining five bits as an ordinary unsigned magnitude, so the magnitude runs \(0\) to \(2^5 - 1 = 31\) and each magnitude gets both signs. The range is therefore \(-31\) to \(+31\).

Option (b) is the two’s complement range for six bits, which is the trap: two’s complement gets one extra negative value because it has no separate \(-0\). Signed magnitude wastes a code on \(100000 = -0\), which is why its range is symmetric and one value shorter. See binary-number-representations.

Q4 — Two’s to one’s complement

How can any n-bit binary number in two’s complement representation (other than \(-2^{n-1}\)) be converted to n-bit one’s complement representation?

  1. By subtracting 1

  2. By subtracting 1 and flipping all the bits

  3. By subtracting the value of the most-significant bit

  4. By adding the value of the most-significant bit

  5. By flipping all the bits and subtracting the value of the most-significant bit

(c)

Write the bit pattern as \(a_{n-1} a_{n-2} \dots a_0\). The two representations differ only in what the top bit is worth:

\[V_{2\text{'s}} = -a_{n-1}2^{n-1} + \sum_{i<n-1} a_i 2^i \qquad V_{1\text{'s}} = -a_{n-1}\left(2^{n-1}-1\right) + \sum_{i<n-1} a_i 2^i\]

So for a given bit pattern, \(V_{1\text{'s}} = V_{2\text{'s}} + a_{n-1}\). To keep the value the same while switching representation you therefore have to move the pattern down by \(a_{n-1}\) — that is, subtract the value of the most significant bit: 1 when the number is negative, 0 when it is positive.

Checking on 8 bits with \(-57\): two’s complement is \(11000111\), and subtracting 1 gives \(11000110\), which is indeed \(\overline{00111001}\), the one’s complement of \(-57\). And for \(+57 = 00111001\) the top bit is 0, so nothing is subtracted and the pattern is unchanged — which is right, because the two representations agree on positive numbers.

That last point is what rules out (a): “subtract 1” is correct for negatives but would corrupt every positive. The exclusion of \(-2^{n-1}\) in the question is because one’s complement cannot represent it at all. See binary-number-representations.

Q5 — Reading a gate circuit

What function does the following circuit implement?

Figure 257: Question 5’s circuit: a three-input NAND on A, B and C, whose output is NORed with D.

  1. \(A.B.C + \overline{D}\)

  2. \(\overline{A.B.C} \oplus D\)

  3. \(\overline{\overline{A.B.C} \oplus D}\)

  4. \(\overline{\overline{A}.\overline{B}.\overline{C} + D}\)

  5. \(\overline{\overline{A.B.C} + D}\)

(e)

Read it inside out. The first gate is a three-input AND with a bubble, i.e. a NAND, so its output is \(\overline{A.B.C}\). That feeds one input of the second gate, which is an OR with a bubble — a NOR — with \(D\) on its other input. So the output is

\[\overline{\overline{A.B.C} + D}\]

which is exactly option (e), written with no simplification at all.

It is worth pushing it one step further to see what the circuit actually does, because that also disposes of (a) and (d). By De Morgan,

\[\overline{\overline{A.B.C} + D} = \overline{\overline{A.B.C}} \cdot \overline{D} = A.B.C.\overline{D}\]

so the circuit is “all three of A, B, C are 1 and D is 0”. Option (a) is \(A.B.C + \overline{D}\), an OR where the circuit has an AND, and option (d) simplifies to \((A+B+C).\overline{D}\), which is true whenever any of A, B, C is 1. Neither matches. See logic-gates.

Q6 — Boolean simplification

Which of the following logic functions is equivalent to \((A.\overline{B} + C).(\overline{\overline{A.C} + B})\) ?

  1. \(A.\overline{B}\)

  2. \(A.\overline{B}.C\)

  3. \(A.\overline{B} + \overline{B}.C\)

  4. \(A.\overline{B}.\overline{C} + \overline{A}.\overline{B}.C\)

  5. None of the above

(a)

Disputed by review. The question stem was mis-transcribed and has now been corrected: the source prints an inner bar over the whole product \(A.C\), so the second factor is \(\overline{\overline{A.C} + B}\), not \(\overline{\overline{A}.C + B}\). With the corrected stem I make the answer (b), not (a):

\[\overline{\overline{A.C} + B} = A.C.\overline{B} \qquad\text{so}\qquad \left(A.\overline{B} + C\right).A.C.\overline{B} = A.\overline{B}.C\]

since both products of the expansion collapse to \(A.\overline{B}.C\). The reasoning below is internally sound but solves the mis-transcribed expression, which is why it lands on (a). Work it yourself before trusting either, and check the bar placement in the PDF.

Deal with the complemented bracket first, using De Morgan twice:

\[\overline{\overline{A}.C + B} = \overline{\overline{A}.C} \cdot \overline{B} = \left(A + \overline{C}\right).\overline{B}\]

So the whole expression is

\[\left(A.\overline{B} + C\right)\left(A + \overline{C}\right)\overline{B}\]

Multiply out the first two brackets:

\[\left(A.\overline{B} + C\right)\left(A + \overline{C}\right) = A.\overline{B}.A + A.\overline{B}.\overline{C} + C.A + C.\overline{C}\]

\(C.\overline{C} = 0\) and \(A.A = A\), so this is \(A.\overline{B} + A.\overline{B}.\overline{C} + A.C\). The middle term is absorbed by the first (\(X + X.Y = X\)), leaving \(A.\overline{B} + A.C\).

Now bring back the trailing \(\overline{B}\):

\[\left(A.\overline{B} + A.C\right)\overline{B} = A.\overline{B} + A.\overline{B}.C = A.\overline{B}\]

again by absorption. See boolean-algebra.

Q7 — Building a sum of products

Which of the following circuits implements the function \(A.B + C.D\) ?

Figure 258: Question 7’s four candidate circuits, laid out as in the paper: (a) top left, (b) top right, (c) bottom left, (d) bottom right. All four invert every input first; they differ only in the pair of second-stage gates (NOR or OR) and in the output gate (NAND or AND).

  1. None of the above

(d)

Every option starts by inverting all four inputs, so the second-stage gates always see \(\overline{A}, \overline{B}, \overline{C}, \overline{D}\). That makes the two useful De Morgan identities the whole question:

\[\overline{\overline{A} + \overline{B}} = A.B \qquad \overline{A} + \overline{B} = \overline{A.B}\]

The first says a NOR fed with inverted inputs is an AND; the second says a plain OR fed with inverted inputs is a NAND. Working the four options through:

second stage output gate function
(a) NOR, so \(A.B\) and \(C.D\) NAND \(\overline{A.B \cdot C.D}\)
(b) OR, so \(\overline{A.B}\) and \(\overline{C.D}\) AND \(\overline{A.B}\cdot\overline{C.D} = \overline{A.B + C.D}\)
(c) NOR, so \(A.B\) and \(C.D\) AND \(A.B.C.D\)
(d) OR, so \(\overline{A.B}\) and \(\overline{C.D}\) NAND \(\overline{\overline{A.B}\cdot\overline{C.D}} = A.B + C.D\)

Only (d) gives the required \(A.B + C.D\), and it does it the standard way: a sum of products built entirely from inverting gates, with the final NAND undoing the double complement. Note that (b) is the exact complement of the answer — an easy option to pick if you forget the final bubble. See logic-gates and boolean-algebra.

Q8 — Expression from a truth table

Consider the logic function represented by the following truth table:

A B C X
0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0
1 1 1 0

Which of the following expressions is equivalent to the function represented by this table?

  1. \((A \oplus B).\overline{C} + (\overline{A + B}).C\)

  2. \((A \oplus B) + C\)

  3. \((A \oplus B) + \overline{A}.\overline{B}.C\)

  4. \(\overline{A}.\overline{B}.C + \overline{A}.B.\overline{C} + A.B.\overline{C}\)

  5. None of the above

(a)

The function is 1 for exactly three input combinations — \(001\), \(010\) and \(100\) — so it is “exactly one of A, B, C is 1”. Its canonical sum of products is

\[X = \overline{A}.\overline{B}.C + \overline{A}.B.\overline{C} + A.\overline{B}.\overline{C}\]

Option (a) splits that on the value of C. When \(C = 0\) the second term vanishes and the first leaves \(A \oplus B\), which is 1 for exactly \(01\) and \(10\) — the minterms \(010\) and \(100\). When \(C = 1\) the first term vanishes and \(\overline{A + B}.C = \overline{A}.\overline{B}.C\) picks out \(001\) alone. Together that is exactly the three rows, so (a) matches.

Checking the others against the table is quick. (b) \((A \oplus B) + C\) is 1 at \(011\), where the table says 0. (c) is 1 at \(011\) for the same reason. (d) is the canonical form with its third term mistyped: it has \(A.B.\overline{C}\) (row \(110\), where the table says 0) instead of \(A.\overline{B}.\overline{C}\) (row \(100\), where the table says 1). See boolean-algebra.

Q9 — NAND-only implementation

Which of the following circuits is a NAND-gate only implementation of the following function:

Figure 259: The function question 9 asks you to rebuild: NOR(A,B) ORed with NOR(C,D).

Figure 260: Question 9’s four candidate NAND-only circuits: (a) top left, (b) top right, (c) bottom left, (d) bottom right. A NAND with both inputs tied to the same signal — drawn here as a short fork with a junction dot — is a NAND used as an inverter.

  1. None of the above

(d)

First write down what the target circuit computes. The two first-stage gates are NORs and the output gate is a plain OR, so

\[F = \overline{A+B} + \overline{C+D} = \overline{A}.\overline{B} + \overline{C}.\overline{D}\]

Now convert. A sum becomes a NAND of the two complemented terms, \(P + Q = \overline{\overline{P}\cdot\overline{Q}}\), so with \(P = \overline{A}.\overline{B}\) and \(Q = \overline{C}.\overline{D}\) the output gate must be a NAND fed with \(\overline{P}\) and \(\overline{Q}\). And \(\overline{P} = \overline{\overline{A}.\overline{B}}\) is itself just a NAND on \(\overline{A}\) and \(\overline{B}\). So:

\[F = \mathrm{NAND}\big(\mathrm{NAND}(\overline{A},\overline{B}),\ \mathrm{NAND}(\overline{C},\overline{D})\big)\]

The four inverters are NANDs with their inputs tied together, giving seven NAND gates in total — which is exactly circuit (d).

The others are all recognisable near-misses:

  • (a) is \(\overline{\overline{A.B}\cdot\overline{C.D}} = A.B + C.D\) — the inputs are not inverted, so it computes the sum of the un-complemented products.
  • (b) is (a) with an inverter, i.e. \(\overline{A.B + C.D}\). Try \(A=1, B=0, C=1, D=0\): the target gives \(0\), (b) gives \(1\).
  • (c) inverts all four inputs correctly but then feeds them into a single four-input NAND, giving \(\overline{\overline{A}.\overline{B}.\overline{C}.\overline{D}}\) — an AND of all four where the target wants an OR of two pairs.

See logic-gates and boolean-algebra.

Q10 — NAND latch behaviour

Which truth table correctly captures the behaviour of the following latch circuit?

Figure 261: Question 10’s latch: two cross-coupled NAND gates, with M into the top gate (whose output is labelled Q-bar) and N into the bottom gate (whose output is labelled Q).

M N Q \(\overline{\mathrm{Q}}\)
0 0 Q \(\overline{\mathrm{Q}}\)
0 1 1 0
1 0 0 1
1 1 0 0
M N Q \(\overline{\mathrm{Q}}\)
0 0 1 1
0 1 0 1
1 0 1 0
1 1 Q \(\overline{\mathrm{Q}}\)
M N Q \(\overline{\mathrm{Q}}\)
0 0 1 1
0 1 1 0
1 0 0 1
1 1 Q \(\overline{\mathrm{Q}}\)
M N Q \(\overline{\mathrm{Q}}\)
0 0 0 0
0 1 1 0
1 0 0 1
1 1 Q \(\overline{\mathrm{Q}}\)
  1. None of the above

(b)

This is the standard cross-coupled NAND latch, so both inputs are active low. Call the top gate’s output \(P\) (the one the paper labels \(\overline{\mathrm{Q}}\)) and the bottom gate’s output \(Q\). Then

\[P = \overline{M \cdot Q} \qquad Q = \overline{P \cdot N}\]

Work the four input combinations:

  • M = 0, N = 0. A 0 on a NAND input forces its output to 1, so both gates output 1: \(Q = 1\) and \(\overline{\mathrm{Q}} = 1\). This is the forbidden combination — the two outputs are not complements.
  • M = 0, N = 1. The top gate is forced, \(P = 1\). Then \(Q = \overline{1 \cdot 1} = 0\). So \(Q = 0\), \(\overline{\mathrm{Q}} = 1\) — a clear.
  • M = 1, N = 0. The bottom gate is forced, \(Q = 1\). Then \(P = \overline{1 \cdot 1} = 0\). So \(Q = 1\), \(\overline{\mathrm{Q}} = 0\) — a set.
  • M = 1, N = 1. Neither gate is forced, so \(P = \overline{Q}\) and \(Q = \overline{P}\), which is satisfied by either stored value. This is the hold state.

That is exactly table (b): \(1,1\) then \(0,1\) then \(1,0\) then hold.

The traps are worth naming. Table (a) puts the hold row at \(00\) and the forbidden row at \(11\) — that is the cross-coupled NOR latch, which has active-high inputs. Tables (c) and (d) get the hold row right but flip the set and clear rows, or write the forbidden state as \(0,0\) instead of \(1,1\) (NANDs cannot both output 0). See flip-flops-and-latches.

Q11 — Which circuit is a latch

Which of the following circuits is capable of acting as a latch? i.e. it has combinations of inputs (M,N) which allow a bit (0 or 1) to be stored, the latch to be set (Q=1) with a single input transition, and the latch to be cleared (Q=0) with a single input transition?

Figure 262: Question 11’s four candidate circuits, wired identically and differing only in the two gate types: (a) NOR over XOR, (b) XOR over AND, (c) NAND over OR, (d) NAND over XOR. In each, M feeds the top gate whose output is Q, N feeds the bottom gate, and the two are cross-coupled.

  1. None of the above

(e)

All four circuits are wired the same way. Writing \(P\) for the bottom gate’s output, each is \(Q = g_{\text{top}}(M, P)\) and \(P = g_{\text{bot}}(Q, N)\), so the whole question is which pair of gate types gives a working memory element. For each circuit, substitute both equations into each other for all four \((M,N)\) and see whether the result is consistent (a stable state), forced (set or clear), or self-contradictory (the circuit oscillates).

(a) NOR over XOR — \(Q = \overline{M + P}\), \(P = Q \oplus N\).

M N working result
0 0 \(P = Q\), so \(Q = \overline{Q}\) oscillates
0 1 \(P = \overline{Q}\), so \(Q = Q\) hold
1 0 \(Q = 0\), \(P = 0\) clear
1 1 \(Q = 0\), \(P = 1\) clear

From the hold state \(01\), changing M gives \(11\) (a clear) but changing N gives \(00\) (oscillation). It can be cleared but never set.

(b) XOR over AND — \(Q = M \oplus P\), \(P = Q.N\). States: \(00\) clear, \(01\) hold, \(10\) set, \(11\) oscillates. The hold state \(01\) can reach the clear at \(00\) in one transition, but reaching the set at \(10\) needs two. Fails.

(c) NAND over OR — \(Q = \overline{M.P}\), \(P = Q + N\). With \(M = 0\) the NAND is forced, so \(Q = 1\) regardless of N; with \(M = 1, N = 1\) we get \(Q = 0\); with \(M = 1, N = 0\) it oscillates. There is no hold state at all, so this circuit has no memory.

(d) NAND over XOR — \(Q = \overline{M.P}\), \(P = Q \oplus N\). States: \(00\) and \(01\) both set (\(Q = 1\)), \(10\) oscillates, \(11\) holds. From the hold state \(11\), changing M gives a set, but changing N gives oscillation. It can be set but never cleared.

So none of the four does all three jobs, and the answer is (e). This is the point of the question: the classic latches are cross-coupled NOR pairs (hold at \(00\), set and clear on either input alone) or cross-coupled NAND pairs (hold at \(11\), as in Q10), and none of these four mixed pairs reproduces that. See flip-flops-and-latches.

Check this one. All eight gate symbols have now been read twice, independently, at high magnification against the source PDF, and both readings agree with the identifications above. The whole answer still turns on them, though: read the bottom gate of (a) as a NOR rather than an XOR and (a) becomes the textbook NOR latch, making it the answer instead.

Q12 — Timing diagram of a function

Which of the following timing diagrams represents the function \(A.B.C + \overline{B}.C\) ?

Figure 263: Question 12’s timing diagrams. The top three traces are the inputs C, B and A, which between them count 000 to 111 over the first eight slots and return to 000 in the ninth; the bottom four are the candidate outputs.

  1. None of the above

(a)

The three input traces are a binary counter: C toggles every slot, B every two, A every four, so over the nine slots \(A B C\) runs \(000, 001, 010, 011, 100, 101, 110, 111\) and then back to \(000\). That turns the timing diagram into a truth table read left to right.

Evaluating \(F = A.B.C + \overline{B}.C\) slot by slot:

slot A B C \(A.B.C\) \(\overline{B}.C\) F
1 000 0 0 0
2 001 0 1 1
3 010 0 0 0
4 011 0 0 0
5 100 0 0 0
6 101 0 1 1
7 110 0 0 0
8 111 1 0 1
9 000 0 0 0

So the output is high in slots 2, 6 and 8 and low everywhere else, which is trace (a).

The other traces are each a different function of the same inputs: (d) is simply C, which would be the answer if the \(B\) terms were missing; (c) is high only in slots 2 and 8, i.e. it drops the \(101\) case; and (b) is high in slots 4, 7 and 8, which is a different function entirely. See timing-diagrams and logic-gates.

Q13 — Multiplexer as a function

Consider the following multiplexer. What must the inputs A,B,C,D be so that the multiplexer implements the function \(X = S_1 + S_0.G\)?

Figure 264: Question 13’s four-to-one multiplexer: inputs A, B, C and D on lines 0 to 3, selected by S1 S0, with output X.

  1. A=0 B=G C=1 D=1

  2. A=1 B=1 C=0 D=G

  3. A=1 B=1 C=G D=0

  4. A=G B=G C=1 D=1

  5. A=G B=0 C=1 D=1

(a)

A multiplexer whose select lines are the function’s own variables is just a lookup table: input \(n\) is passed through when \(S_1 S_0\) is the binary encoding of \(n\), so input \(n\) must carry whatever the function evaluates to for that combination of selects. Any variable not used as a select — here \(G\) — is allowed to appear on the data inputs.

Evaluating \(X = S_1 + S_0.G\) for each select value:

\(S_1 S_0\) line \(X = S_1 + S_0.G\) required input
00 0 \(0 + 0 \cdot G = 0\) A = 0
01 1 \(0 + 1 \cdot G = G\) B = \(G\)
10 2 \(1 + 0 \cdot G = 1\) C = 1
11 3 \(1 + 1 \cdot G = 1\) D = 1

So A=0, B=\(G\), C=1, D=1, which is option (a). Note how \(S_1 = 1\) makes the function true whatever \(S_0\) and \(G\) are, which is why both of the bottom two lines are hard-wired to 1. See combinational-logic-blocks.

Q14 — Two’s complement addition

What is the result of adding the 6-bit two’s complement numbers 010110 and 110011?

  1. 000001

  2. 001001

  3. 100101

  4. 101001

  5. 110111

(b)

Add the bit patterns as if they were unsigned, then throw away anything past the sixth bit — that is the whole trick of two’s complement, and it is why the same adder works for signed and unsigned:

\[\begin{array}{r} 010110 \\ +\;110011 \\ \hline 1\,001001 \end{array}\]

Column by column from the right: \(0+1 = 1\); \(1+1 = 0\) carry 1; \(1+0+1 = 0\) carry 1; \(0+0+1 = 1\); \(1+1 = 0\) carry 1; \(0+1+1 = 0\) carry 1. Discarding the carry out of the top bit leaves \(001001\).

Sanity check in decimal: \(010110 = 22\), and \(110011\) is negative, with magnitude \(\overline{110011} + 1 = 001100 + 1 = 001101 = 13\), so it is \(-13\). And \(22 - 13 = 9 = 001001\). The result is positive and within range, so the discarded carry is not an overflow. See binary-number-representations.

Q15 — Detecting overflow

Which of the following operations will result in an overflow in 4-bit two’s complement arithmetic?

  1. 0100+0101

  2. 0100–0101

  3. 1001–0001

  4. 1001+0001

  5. None of the above

(a)

Four-bit two’s complement covers \(-8\) to \(+7\). Overflow means the true mathematical result falls outside that range; equivalently, it happens only when the two operands have the same sign and the result has the opposite sign.

decimal result in range?
(a) \(0100 + 0101\) \(4 + 5\) \(9\) no — overflow
(b) \(0100 - 0101\) \(4 - 5\) \(-1\) yes
(c) \(1001 - 0001\) \(-7 - 1\) \(-8\) yes, just
(d) \(1001 + 0001\) \(-7 + 1\) \(-6\) yes

Only (a) escapes. Its bit sum is \(0100 + 0101 = 1001\), which reads as \(-7\) — two positives adding to a negative, the classic signature of overflow.

Option (c) is the near miss worth checking carefully: \(-8\) is representable in four bits (it is the one asymmetry of two’s complement), so \(1001 - 0001 = 1000 = -8\) is a legitimate result. Note also that (b) and (d) can never overflow at all, since adding numbers of opposite signs always produces a result no larger in magnitude than the larger operand. See binary-number-representations.

These same four operations also come up in Learning Lab 3 (Binary Arithmetic), in a different order and with the same answer, so this is a question the course drills rather than a one-off. See week2-lab-binary-arithmetic.

Q16 — Interpreting an overflow

Consider the binary addition operation 1001 + 1110. Which of the following statements is true if the numbers are interpreted as two’s complement?

  1. The result is negative and no overflow occurs

  2. The result should be negative but overflow occurs

  3. The result is positive and no overflow occurs

  4. The result should be positive but overflow occurs

  5. The result is zero

(b)

As two’s complement values, \(1001 = -7\) and \(1110 = -2\), so the true answer is \(-9\) — outside the \(-8\) to \(+7\) range, hence an overflow. The correct answer “should be negative”, which rules out (d).

Doing the addition confirms it:

\[\begin{array}{r} 1001 \\ +\;1110 \\ \hline 1\,0111 \end{array}\]

Discarding the carry leaves \(0111 = +7\): two negatives have produced a positive, which is precisely the overflow signature and is why (a) and (c) are wrong. The carry out of the top bit is not itself the overflow flag here — a two’s complement addition can produce a carry out with no overflow at all (as in Q14). See binary-number-representations.

Q17 — D flip-flop timing

Consider the flip-flop circuit shown below and the associated CLK and output (Q) signals. Which timing diagram shows input (A) values over time which would have resulted in the given output (Q).

Figure 265: Question 17’s positive-edge-triggered D flip-flop, the given CLK and Q traces, and the five candidate A inputs.

(d)

The clock triangle on the symbol has no bubble, so this is a positive-edge-triggered D flip-flop: at each rising clock edge, Q takes the value D had just before that edge, and between edges Q holds. There are four rising edges in the diagram. Reading the Q trace against them:

edge Q before Q after so A just before the edge must be
1 0 1 1
2 1 1 1
3 1 0 0
4 0 1 1

So the requirement is \(A = 1, 1, 0, 1\) at the four edges. Checking each candidate:

  • (a) goes low right at the first edge and only comes back high at the second, so it reads \(1, 0, \dots\) — wrong at edge 2. (Its transitions also land exactly on the clock edges, which would be a setup-time violation in real hardware.)
  • (b) is high at edges 1, 2 and 3, so Q would stay high at edge 3 instead of falling.
  • (c) gets edges 1, 2 and 3 right but is low at edge 4, so Q would not rise again.
  • (d) is high until part-way through the third clock cycle and low until part-way through the fifth, giving \(1, 1, 0, 1\) — a match, and with every transition comfortably away from a clock edge.
  • (e) has already gone low before edge 2, so Q would fall there.

Only (d) works. The useful habit here is to ignore the shape of A between edges entirely: a D flip-flop samples, so only the four instants matter. See flip-flops-and-latches and timing-diagrams.

Q18 — Load-or-swap register pair

Consider the following circuit. If \(A_1\) is 1 and \(A_0\) is 0, what will be the values of \(Q_1\) and \(Q_0\) after three rising clock edges if FN is 0 for one rising clock edge then 1 for two rising clock edges?

Figure 266: Question 18’s circuit: two D flip-flops, each fed by a multiplexer selected by FN. With FN=0 each flip-flop loads its own A input; with FN=1 each loads the other flip-flop’s output, so the pair swaps.

  1. \(Q_1 = 0\) \(Q_0 = 0\)

  2. \(Q_1 = 0\) \(Q_0 = 1\)

  3. \(Q_1 = 1\) \(Q_0 = 0\)

  4. \(Q_1 = 1\) \(Q_0 = 1\)

  5. Insufficient information is provided to determine the values

(c)

Read the two multiplexers first. Both take their select from FN, so FN picks one of two behaviours for the whole circuit:

  • FN = 0 selects line 0 on each multiplexer, which is \(A_1\) for the left flip-flop and \(A_0\) for the right one. This is a parallel load.
  • FN = 1 selects line 1. The left multiplexer’s line 1 comes from the long feedback rail running back from \(Q_0\), and the right multiplexer’s line 1 comes from \(Q_1\). So \(D_1 = Q_0\) and \(D_0 = Q_1\) — the two bits swap.

Both flip-flops share the clock, so the swap happens simultaneously and there is no race: each captures the other’s old value.

Now trace the three edges with \(A_1 A_0 = 10\):

edge FN action \(Q_1 Q_0\) after
1 0 load \(A_1 A_0\) 1 0
2 1 swap 0 1
3 1 swap 1 0

After three edges \(Q_1 = 1\) and \(Q_0 = 0\), which is option (c). Two swaps cancel, so the pair is back to what the load put there — which is the real point of the question.

Option (e) is the trap for anyone who worries about the initial contents of the flip-flops, but the first edge loads both of them from \(A_1\) and \(A_0\), so whatever they held beforehand is irrelevant. See sequential-circuits and shift-registers.

Q19 — Flip-flops for a sequence

A sequential circuit has four outputs (\(X_3,X_2,X_1,X_0\)) which advance through the following repeating sequence:

\[X_3X_2X_1X_0: \quad 0000 \to 0001 \to 0011 \to 0111 \to 1111 \to 1100 \to 0000 \to \dots\]

What is the minimum number of flip-flops needed to implement this circuit?

  1. 2

  2. 3

  3. 4

  4. 6

  5. 8

(b)

Count the distinct values in the cycle: \(0000\), \(0001\), \(0011\), \(0111\), \(1111\), \(1100\) — six of them, and then it repeats. The flip-flops have to hold the state, not the outputs, and \(n\) flip-flops give \(2^n\) states, so we need the smallest \(n\) with \(2^n \ge 6\):

\[2^2 = 4 < 6 \le 8 = 2^3\]

so three flip-flops, which is (b).

The obvious answer is (c), four — one flip-flop per output bit. That works, and it is what you would build if you wanted the outputs straight off the flip-flops with no extra logic. But the question asks for the minimum, and with only six states in the cycle you can encode the state in three bits and derive the four outputs combinationally from that encoding. The cost is a block of output logic; the saving is a flip-flop.

Note that two would not do: four states cannot distinguish six points in the cycle, and each state must have a unique successor, so distinct steps need distinct encodings. See [counters] and state-machines.

Q20 — Tracing a synchronous counter

What sequence will the following synchronous counter count through, if it starts at \(Q_1Q_0 = 00\)?

Figure 267: Question 20’s counter. The XOR is drawn mirrored, as in the paper: its output faces left into the first flip-flop’s D input and its two inputs face right onto the Q1 and Q0 lines. The NAND takes the same two signals and drives the second flip-flop.

  1. \(Q_1Q_0\): \(00 \to 01 \to 10 \to 11 \to 00 \to \dots\)

  2. \(Q_1Q_0\): \(00 \to 01 \to 11 \to 00 \to \dots\)

  3. \(Q_1Q_0\): \(00 \to 01 \to 11 \to 10 \to 00 \to \dots\)

  4. \(Q_1Q_0\): \(00 \to 10 \to 11 \to 00 \to \dots\)

  5. \(Q_1Q_0\): \(00 \to 11 \to 00 \to \dots\)

(b)

Both gates see the same two signals — the top rail carries \(Q_0\) back from the second flip-flop, and the vertical line carries \(Q_1\) from the first — so the excitation equations are

\[D_1 = Q_1 \oplus Q_0 \qquad D_0 = \overline{Q_1 \cdot Q_0}\]

Both flip-flops share the clock, so on each edge they update together from the current state. Building the state table:

\(Q_1Q_0\) \(D_1 = Q_1 \oplus Q_0\) \(D_0 = \overline{Q_1.Q_0}\) next
00 0 1 01
01 1 1 11
11 0 0 00
10 1 1 11

Starting at \(00\) the counter goes \(00 \to 01 \to 11 \to 00\), a three-state cycle, which is option (b).

The fourth row is the unused state. It is worth checking because a counter that can lock up in an unused state is broken: \(10 \to 11\), which is inside the main cycle, so the circuit self-corrects within one clock. See [counters].

Q21 — Counter width

What’s the minimum number of flip-flops needed to build a synchronous binary counter capable of counting from 0 to 16 (inclusive)?

  1. 3

  2. 4

  3. 5

  4. 16

  5. 17

(c)

“0 to 16 inclusive” is seventeen values, not sixteen — that is the whole question. With \(n\) flip-flops a binary counter has \(2^n\) distinct states, so we need \(2^n \ge 17\):

\[2^4 = 16 < 17 \le 32 = 2^5\]

so five flip-flops. Four would get to 15 and no further.

Option (b) is what you get by reading “16” as the count of values rather than the last value, and options (d) and (e) confuse flip-flops with states — a one-hot ring counter would need one flip-flop per state, but a binary counter encodes the count in binary, which is exactly why it only needs \(\lceil \log_2 17 \rceil = 5\). See [counters].

Q22 — State diagram to state table

Consider the state diagram below.

Figure 268: Question 22’s state diagram. Three states, each labelled with its name over its X,Y output pair; every arc carries the condition on the inputs A and B under which it is taken.

Which of the following is an equivalent state table?

Current State AB=00 AB=01 AB=10 AB=11 Outputs (X,Y)
S0 S0 S0 S1 S1 11
S1 S0 S2 S1 S2 10
S2 S0 S2 S1 S2 01
Current State AB=00 AB=01 AB=10 AB=11 Outputs (X,Y)
S0 S0 S1 S0 S1 11
S1 S0 S2 S1 S1 10
S2 S0 S1 S2 S2 01
Current State AB=00 AB=01 AB=10 AB=11 Outputs (X,Y)
S0 S0 S1 S0 S1 00
S1 S0 S2 S1 S1 01
S2 S0 S2 S1 S2 10
Current State AB=00 AB=01 AB=10 AB=11 Outputs (X,Y)
S0 S0 S0 S1 S1 11
S1 S0 S2 S1 S1 10
S2 S0 S2 S1 S2 01
  1. None of the above

(d)

Take each state’s outgoing arcs and expand their conditions into the four values of \(AB\). Note that the diagram’s labels do not all name both inputs — \(A\) on its own covers \(AB = 10\) and \(AB = 11\), and \(B\) on its own covers \(01\) and \(11\) — which is where most of the difference between the options lives.

S0 has two arcs: a self-loop on \(\overline{A}\) and an arc to S1 on \(A\). So \(AB = 00, 01 \to\) S0 and \(AB = 10, 11 \to\) S1.

S1 has three arcs: a self-loop on \(A\), an arc to S0 on \(\overline{A}.\overline{B}\), and an arc to S2 on \(\overline{A}.B\). So \(AB = 00 \to\) S0, \(01 \to\) S2, and \(10, 11 \to\) S1 (both covered by the bare \(A\)).

S2 has three arcs: a self-loop on \(B\), an arc to S1 on \(A.\overline{B}\), and an arc to S0 on \(\overline{A}.\overline{B}\). So \(AB = 01, 11 \to\) S2 (both covered by the bare \(B\)), \(10 \to\) S1 and \(00 \to\) S0.

Each state’s arcs cover all four combinations exactly once, which is the completeness check worth doing before comparing anything. The outputs are read straight off the bottom half of each circle: S0 is 11, S1 is 10, S2 is 01.

That gives table (d). The near-miss is (a), which is identical except that it sends S1 to S2 on \(AB = 11\) — that would be right if S1’s self-loop were labelled \(A.\overline{B}\) rather than plain \(A\). Table (b) mangles S0’s row (sending it to S1 on \(01\) instead of \(10\)), and (c) has the outputs shifted onto the wrong states. See state-machines.

The table you have just built is the 2-dimensional state table of the lab’s design pipeline — one row per state, one next-state column per input combination. It is step 2 of six; Beyond the paper below walks the remaining four on a machine of the same size, ending in the waveforms that circuit produces.

Q23 — Tracing a state machine

Consider the state machine represented by the state diagram shown in question 22 (see Q22). What sequence of states is traversed if the machine starts in state S0 and A goes through the sequence 1010101 and B is always the inverse of A?

  1. S0→S0→S1→S2→S1→S2→S1→S2

  2. S0→S1→S1→S2→S1→S2→S1→S2

  3. S0→S1→S2→S2→S1→S2→S1→S2

  4. S0→S1→S2→S1→S2→S1→S2→S1

  5. None of the above

(d)

B is the inverse of A, so the input pairs alternate between \(AB = 10\) and \(AB = 01\): seven values of A give the sequence \(10, 01, 10, 01, 10, 01, 10\).

From the state table derived in Q22, only two columns are ever used:

  • \(AB = 10\): S0 → S1, S1 → S1, S2 → S1
  • \(AB = 01\): S0 → S0, S1 → S2, S2 → S2

Starting in S0:

step AB from to
1 10 S0 S1
2 01 S1 S2
3 10 S2 S1
4 01 S1 S2
5 10 S2 S1
6 01 S1 S2
7 10 S2 S1

So the machine goes S0→S1→S2→S1→S2→S1→S2→S1, which is (d) — eight states listed, being the start state plus one per input.

The trap is (a), which begins S0→S0 as if the first input left the machine where it was; but the first input has \(A = 1\), and S0 only stays put on \(\overline{A}\). Options (b) and (c) each stutter once in the middle, which cannot happen because the input never repeats. See state-machines. For what a traced machine looks like once it is built out of flip-flops and gates, see Beyond the paper below.

Q24 — ALU control settings

Consider the ALU bit slice below (not the same as seen previously).

Figure 269: Question 24’s ALU bit slice. ENA/ENB/INVB condition A and B into the internal X and Y rails; five gates and the adder compute their functions in parallel, and the eight-way multiplexer picks one under F2 F1 F0. Right Shift Out is the X rail itself, so selecting input 6 (Right Shift In) hands each slice the bit from the slice to its left.

For an ALU made up of 8 of the bit slices above, which of the following control input settings will result in the ALU output being \(\overline{A}.B\) (bitwise)? (The “Right Shift In” control input refers to that for the most significant bit; the “Carry in” control input refers to that for the least significant bit.)

  1. ENA=1 ENB=1 INVB=0 \(F_2\)=0 \(F_1\)=0 \(F_0\)=0 Right Shift In=1 Carry in=1

  2. ENA=1 ENB=1 INVB=0 \(F_2\)=0 \(F_1\)=0 \(F_0\)=1 Right Shift In=1 Carry in=1

  3. ENA=1 ENB=1 INVB=1 \(F_2\)=0 \(F_1\)=0 \(F_0\)=1 Right Shift In=1 Carry in=1

  4. ENA=1 ENB=1 INVB=0 \(F_2\)=0 \(F_1\)=1 \(F_0\)=1 Right Shift In=1 Carry in=1

  5. ENA=1 ENB=1 INVB=1 \(F_2\)=1 \(F_1\)=0 \(F_0\)=1 Right Shift In=1 Carry in=1

(e)

Two things have to be read off the figure: what the conditioning gates do to A and B, and which function each value of \(F_2F_1F_0\) selects.

Conditioning. A goes through one AND gate with ENA and nothing else — note there is no INVA on this slice — so the internal signal is

\[X = A \cdot \text{ENA}\]

B goes through an AND with ENB and then an XOR with INVB, and XORing with 1 is inversion, so

\[Y = (B \cdot \text{ENB}) \oplus \text{INVB}\]

Every option sets ENA = ENB = 1, so \(X = A\) and \(Y = B \oplus \text{INVB}\); INVB is the only thing left that can change the data.

Function select. Following each mux input back to its source in the figure gives:

\(F_2F_1F_0\) input function
000 0 \(X \oplus Y\)
001 1 \(X \cdot Y\)
010 2 \(X + Y\)
011 3 \(\overline{X \cdot Y}\)
100 4 Carry In
101 5 \(\overline{X + Y}\)
110 6 Right Shift In
111 7 \(X \oplus Y \oplus C_{in}\) (the sum)

Now, how do you get \(\overline{A}.B\) from a slice that cannot invert A? Push the complement onto the other side with De Morgan:

\[\overline{A}.B = \overline{A + \overline{B}}\]

So take \(X = A\) and \(Y = \overline{B}\) (which needs INVB = 1) and select the NOR, which is \(F_2F_1F_0 = 101\). That is option (e).

Checking the others: (a) is INVB = 0 with the XOR, giving \(A \oplus B\); (b) is INVB = 0 with the AND, giving \(A.B\); (c) is INVB = 1 with the AND, giving \(A.\overline{B}\) — the mirror image of what was asked, and the most tempting wrong answer; (d) is INVB = 0 with the NAND (\(F_2F_1F_0 = 011\)), giving \(\overline{A.B}\), which is the complement of (b) rather than anything with a single complemented variable.

Right Shift In and Carry in are set to 1 in every option, so they cannot distinguish the answers — and neither reaches the output anyway once \(F_2F_1F_0\) selects a logic function. See arithmetic-logic-unit.

Q25 — What the ALU cannot do

For an ALU made up of 8 of the bit slices shown in question 24 above (see Q24), which of the following control input function settings can NOT be used to output \(\overline{B}\) (bitwise) — assuming other control inputs are chosen appropriately?

  1. \(F_2\)=0 \(F_1\)=0 \(F_0\)=0 XOR

  2. \(F_2\)=0 \(F_1\)=1 \(F_0\)=0 OR

  3. \(F_2\)=0 \(F_1\)=1 \(F_0\)=1 NAND

  4. \(F_2\)=1 \(F_1\)=0 \(F_0\)=1 NOR

  5. None of the above

(c)

The question hands you the function each select code picks, so the work is in what the conditioning gates can produce. From Q24, the two internal signals are \(X = A \cdot \text{ENA}\) and \(Y = (B \cdot \text{ENB}) \oplus \text{INVB}\), so the reachable values are:

ENA \(X\) ENB INVB \(Y\)
0 \(0\) 0 0 \(0\)
1 \(A\) 0 1 \(1\)
1 0 \(B\)
1 1 \(\overline{B}\)

The critical asymmetry is that X can be forced to 0 but never to 1, because there is no INVA on this slice. Y, having the INVB stage, can be forced to either constant.

With that in hand:

  • (a) XOR, \(X \oplus Y\). Set ENA = 0 so \(X = 0\), and ENB = INVB = 1 so \(Y = \overline{B}\). Then \(0 \oplus \overline{B} = \overline{B}\), so this one works.
  • (b) OR, \(X + Y\). Same settings: \(0 + \overline{B} = \overline{B}\), so this one works too.
  • (d) NOR, \(\overline{X + Y}\). Set \(X = 0\) and \(Y = B\) (ENB = 1, INVB = 0). Then \(\overline{0 + B} = \overline{B}\), which works.
  • (c) NAND, \(\overline{X \cdot Y}\). To get \(\overline{B}\) out of a NAND you need \(X \cdot Y = B\), which requires \(X = 1\) with \(Y = B\) (or \(X = B\), which is not available either — A and B cannot be swapped). But \(X \in \{0, A\}\), so \(X\) can never be a constant 1. Every reachable combination fails: \(X = 0\) gives a constant 1; \(X = A\) gives \(\overline{A.B}\), \(\overline{A.\overline{B}}\), \(\overline{A}\) or 1, none of which is \(\overline{B}\). This is the one that cannot be done.

So (c) is the setting that cannot produce \(\overline{B}\). The general lesson is the one from arithmetic-logic-unit: forcing a data input to a constant is what lets one ALU compute unary functions, and here that trick works on the B side but only half-works on the A side.

Beyond the paper — from state diagram to wired circuit

Q22 asks for one step of a longer road — state diagram to state table — and Q23 asks you to walk the machine along it. Learning Lab 8 (State Machines) names the whole road and makes you travel all of it: “do hand design first — state diagram → state table → next state logic and output logic”, and then “enter the circuit into Logisim and simulate it”.

This follows the design task of Learning Lab 8 (State Machines). Its Design Task 1, a detector for the sequence 001, is worked through state diagram, state tables, encoding, Boolean expressions and logic diagram in week5-lab-state-machines. This section maps the lab’s design steps onto this paper’s questions and adds a timing diagram of the finished design, using the encoding and expressions from that note.

The pipeline, and where this paper cuts into it

Step What Lab 8 asks for Tested here by
1 Draw the state diagram — one circle per state, name over output, an arrow per input condition Q22 reads one; Q23 walks one
2 Write the 2-dimensional state table — one row per state, one next-state column per input combination Q22, which is exactly this conversion
3 Choose a state encoding — the number of flip-flops and their values in each state. “Examine different options for state encoding!” Q19, Q21 — both are the “how many flip-flops” half of this step
4 Write the 1-dimensional state table — one row per (state, input) combination, with the D inputs spelled out not examined directly; it is the working for step 5
5 Derive Boolean expressions for the outputs and the flip-flop D inputs, in terms of the Q outputs and the inputs Q20 runs this backwards, reading a counter’s next-state logic off its circuit
6 Enter the circuit and simulate the timing diagram below is what that simulation shows

Step 3 is the one the lab shouts about, and it is worth seeing why. For the 001 detector, the obvious binary assignment \(S_0S_1S_2S_3 = 00,01,10,11\) leaves several product terms in each next-state expression and nothing collapses; the assignment week5-lab-state-machines settles on instead —

\[S_0 = 01 \qquad S_1 = 00 \qquad S_2 = 10 \qquad S_3 = 11\]

— makes one flip-flop input collapse to a bare wire. Nothing about the state diagram changed; only the numbers written on the states did.

What the machine does on a clock

\[D_0 = S \qquad D_1 = \overline{Q_0}\,(Q_1 + \overline{S}) = \overline{Q_0} \cdot \overline{\overline{Q_1}\,.\,S} \qquad X = Q_1 . Q_0\]

Three chips build that: a 74HCT74 for the two flip-flops, one NAND of a 74HCT00, and two ANDs of a 74HCT08 — which is the lab’s “are you a bad enough dude to implement a sequence detector with just three chips?” challenge, answered. The logic diagram is drawn in week5-lab-state-machines; what is worth adding here is the other view of the same machine, because it is the one Q23 and Q17 are really asking about — where each value sits in time.

Figure 270: The 001 detector running on the first ten bits of the input sequence from Lab 8’s Design Task 1. Read it in columns: the dashed verticals are the ten rising clock edges, the number under the S track is which input bit is being presented, and each of Q1, Q0 and X holds the value it took at the previous edge. The offset is the whole point. Bit 3 completes the first 001 while it sits in the interval before edge 3, but X only goes high after edge 3 has been taken, so the pulse on X appears one column to the right of the bit that caused it - even though the lab’s S and X strings are written aligned by index. Q0 is a delayed copy of S, which is what D0 = S means in the time domain, and X is high exactly where Q1 and Q0 are both high. The two blue notes are added here, not on the slide.

Three things come off that picture, and each is an exam trap somewhere:

  • The input is sampled, not watched. Nothing happens to \(Q_1\) or \(Q_0\) between edges, however \(S\) wriggles. This is the whole content of Q17, where the question is which candidate \(A\) waveform could have produced the given \(Q\) — and the answer only ever depends on what \(A\) was doing at the edges.
  • A Moore output lags the input that caused it. Bit 3 completes the first 001, but the machine is only in \(S_3\) after edge 3 has happened, so \(X\) rises after that edge and stays up for one clock period. The lab’s two bit strings are aligned by index, not by time.
  • \(Q_0\) is \(S\) delayed by one clock, which is exactly what \(D_0 = S\) means once the flip-flop is in the path. Encoding choices that make a D input equal an existing signal turn a gate into a wire, and that is why step 3 of the pipeline is worth the effort.

Two more questions the same design answers

  • “How many flip-flops does this machine need?” — Q19 and Q21. Count the states, then count the flip-flops: \(N\) flip-flops hold \(2^N\) distinct patterns, so \(N = \lceil \log_2(\text{number of states}) \rceil\). Four states here, hence the two tracks \(Q_1\) and \(Q_0\) in the waveform.
  • “Moore or Mealy?” — \(X = Q_1 . Q_0\) mentions the state and nothing else, which is what makes this Moore. A Mealy output would have \(S\) in its expression too, and would then be free to change part-way through a clock period rather than only just after an edge — the flat-topped one-period-wide pulses on the \(X\) track are the visible signature of Moore. CSSE2010 sticks to Moore; see state-machines.

Your score

Reload the page to clear your answers.

Sample Mid-semester Exam #4

This is the fourth of UQ’s published sample mid-semester papers for CSSE2010/CSSE7201 Introduction to Computer Systems — the Semester One 2020 St Lucia paper, run as a 60-minute open-book examination with 10 minutes of reading time. The only aids permitted are a Casio FX82-series or UQ-approved calculator; no laptops or phones. There are 25 multiple-choice questions, each worth one mark, with zero marks for an incorrect, missing or multiple answer, so there is no penalty for guessing. The course note is csse2010.

WarningAnswers are derived, not official

The source paper ships without an answer key, so every answer below was worked out during transcription rather than taken from UQ. Each one shows its reasoning so it can be checked rather than trusted; anything uncertain is flagged. Treat a disagreement between your working and the answer here as a reason to check both.

How to use this

Two ways. For a timed run, work through all 25 questions in 60 minutes without opening any of the answer callouts — on the website they stay collapsed until clicked, so the paper reads as a clean exam. For targeted practice, use the question index to pick out only the questions for one week or one concept, and read the working straight away.

Note that the PDF build renders every callout expanded, so the answers are always visible there. The site version is the one to practise from.

Question index

Q Topic Week Concept notes
1 Excess-64 representation 1 binary-number-representations
2 Radix conversion 1 binary-number-representations
3 Ones’ complement range 1 binary-number-representations
4 Properties of representations 1 binary-number-representations
5 Reading a gate circuit 1 logic-gates
6 Boolean simplification 2 boolean-algebra
7 Circuit for an expression 1 logic-gates
8 Truth table for an expression 2 boolean-algebra
9 Function from a timing diagram 2 timing-diagrams
10 NAND built from NOR gates 2 boolean-algebra · logic-gates
11 Equivalent expressions 2 boolean-algebra
12 D flip-flop input from output 3 flip-flops-and-latches · timing-diagrams
13 Two’s complement addition 2 binary-number-representations
14 Overflow detection 2 binary-number-representations
15 Overflow and a zero result 2 binary-number-representations
16 Full adder from multiplexers 2 combinational-logic-blocks
17 Synchronous counter sequence 4 [counters] · flip-flops-and-latches
18 Multiplexer-fed register pair 3 sequential-circuits · combinational-logic-blocks
19 Tracing a state machine 4 state-machines
20 State diagram to state table 4 state-machines
21 Flip-flops for a state machine 4 state-machines
22 Multiplexer as a logic function 2 combinational-logic-blocks
23 Which circuit is a latch 3 flip-flops-and-latches
24 ALU control settings 5 arithmetic-logic-unit
25 ALU operation coverage 5 arithmetic-logic-unit

Q1 — Excess-64 representation

What is \(-34_{10}\) expressed in 7-bit excess-64 format?

  1. 0011110

  2. 0100010

  3. 1011101

  4. 1011110

  5. 1100010

(a)

In excess-\(k\) (biased) representation the stored bit pattern is the unsigned binary of \(\text{value} + k\). Here \(k = 64\), so

\[-34 + 64 = 30\]

and \(30_{10} = 16 + 8 + 4 + 2 = 11110_2\), which padded to seven bits is \(0011110\).

A quick sanity check on the other options: \(0100010_2 = 34\), which is the unsigned 34 rather than the biased \(-34\); \(1011110_2 = 94 = 30 + 64\), i.e. the pattern you get if you add the bias twice. See binary-number-representations.

Q2 — Radix conversion

\(95_{16}\) is equal to

  1. \(10100101_2\)

  2. \(137_8\)

  3. \(141_{10}\)

  4. \(225_8\)

  5. None of the above

(d)

\(95_{16} = 9 \times 16 + 5 = 149_{10}\). In binary that is \(1001\,0101_2\) (each hex digit expands to four bits: \(9 \to 1001\), \(5 \to 0101\)).

Regrouping those bits in threes from the right for octal: \(010\;010\;101 \to 225_8\). Checking: \(2 \times 64 + 2 \times 8 + 5 = 128 + 16 + 5 = 149\). ✓

The distractors are all near misses: \(10100101_2 = 165\), \(137_8 = 95\) (the digits of the hex number read as a decimal value), and \(141_{10}\) is simply wrong.

Q3 — Ones’ complement range

A 4-bit number in ones’ complement format can represent integers from

  1. -15 to 15

  2. -8 to 7

  3. -7 to 7

  4. -7 to 8

  5. 0 to 15

(c)

In ones’ complement the negative of a value is its bit-by-bit complement, so the positive patterns \(0000 \ldots 0111\) cover \(0 \ldots 7\) and their complements \(1111 \ldots 1000\) cover \(-0 \ldots -7\). The range is therefore \(-7\) to \(+7\), with two representations of zero (\(0000\) and \(1111\)) — which is exactly why ones’ complement has one fewer distinct value than two’s complement’s \(-8\) to \(+7\) (option (b)). See binary-number-representations.

Q4 — Properties of representations

Which of the following statements about number representations is false?

  1. The 8-bit number 01100110 is even when considered to be in unsigned, signed-magnitude, ones’ complement, two’s complement or excess-128 formats

  2. An n-bit excess \(2^{n-1}\) number can be converted to two’s complement representation by inverting the most significant bit

  3. An 8-bit ones’ complement number can be converted to 9-bit ones’ complement representation by prepending a copy of the most significant bit

  4. An 8-bit two’s complement number can be converted to 9-bit two’s complement representation by prepending a copy of the most significant bit

  5. None of the above

(e)

All four statements are true, so the answer is “none of the above”.

(a) \(01100110\) has a 0 in the least significant bit. Unsigned it is \(102\); as signed-magnitude the sign bit is 0 so it is \(+102\); in ones’ complement and two’s complement the leading 0 again means \(+102\); in excess-128 it is \(102 - 128 = -26\). All five values are even. (Parity of the interpreted value is really just the LSB in the first four formats, and biasing by the even number 128 cannot change parity either.)

(b) For an \(n\)-bit excess-\(2^{n-1}\) number the stored pattern is \(v + 2^{n-1}\), and in two’s complement it is \(v \bmod 2^n\). Adding \(2^{n-1}\) modulo \(2^n\) flips exactly the most significant bit and leaves the rest alone, so inverting the MSB converts between the two.

(c) and (d) are both sign extension. Copying the sign bit preserves the value in ones’ complement (\(-3 = 11111100 \to 111111100\), still the complement of \(000000011\)) and in two’s complement (\(-3 = 11111101 \to 111111101 = 512 - 3\)). Only unsigned and signed-magnitude would break under this rule.

Q5 — Reading a gate circuit

What function is implemented by the following circuit?

Figure 271: Question 5’s circuit: an XOR on A and B feeding a three-input NOR together with C and D.

  1. \((A \oplus B) + C + D\)

  2. \(\overline{A \oplus B} + \overline{C} + \overline{D}\)

  3. \(\overline{(A \oplus B) + (C + D)}\)

  4. \((A \oplus B) . \overline{C} . \overline{D}\)

  5. \(\overline{\overline{A \oplus B} . (C + D)}\)

(c)

Read it left to right. The first gate has the extra curved bar across its inputs, so it is an XOR: its output is \(A \oplus B\). The second gate has the same curved back but a bubble on its output and three inputs, so it is a three-input NOR fed by \(A \oplus B\), \(C\) and \(D\):

\[X = \overline{(A \oplus B) + C + D}\]

Option (c) is that expression with \(C + D\) merely bracketed, and OR is associative, so (c) is the same function.

The near misses are worth checking. Option (a) drops the inversion. Option (b), \(\overline{A \oplus B} + \overline{C} + \overline{D}\), is by De Morgan \(\overline{(A \oplus B) . C . D}\) — the three-input NAND, not the NOR. Option (d) has the right form for De Morgan applied to (c) except that the first term is not inverted; the correct expansion is \(\overline{A \oplus B} . \overline{C} . \overline{D}\). Option (e) inverts the wrong subexpression.

Q6 — Boolean simplification

Which of the following logic functions is identical to \(\overline{\overline{\overline{A + B} + C} + \overline{B . C}}\) ?

  1. 0

  2. \(B . C\)

  3. \(A . B . C\)

  4. \(\overline{B} + \overline{C}\)

  5. None of the above

(b)

The bars in the printed expression nest three deep on the left-hand term: innermost \(\overline{A + B}\), then \(\overline{\overline{A + B} + C}\), and the whole thing is NORed with \(\overline{B . C}\).

Name the two operands of the outer bar \(P = \overline{\overline{A+B} + C}\) and \(R = \overline{B.C}\), so the function is \(\overline{P + R}\). By De Morgan that is \(\overline{P} . \overline{R}\), and both complements collapse a level of bars:

\[ \begin{aligned} \overline{P} &= \overline{A + B} + C \\ \overline{R} &= B . C \end{aligned} \]

so

\[ \begin{aligned} X &= \left( \overline{A + B} + C \right) . B . C \\ &= \left( \overline{A} . \overline{B} + C \right) . B . C && \text{(De Morgan)} \\ &= \overline{A} . \overline{B} . B . C + C . B . C && \text{(distribute)} \\ &= 0 + B . C && \text{($\overline{B} . B = 0$, $C . C = C$)} \\ &= B . C \end{aligned} \]

The \(\overline{B} . B\) term is what kills the \(A\) dependence, which is why the answer has no \(A\) in it at all. See boolean-algebra.

Q7 — Circuit for an expression

Which of the following logic circuits is an implementation of the function \((A \oplus B) + C + \overline{D}\)?

Figure 272: Question 7’s five candidate circuits, drawn side by side as in the paper. Small open circles on an input or output lead are inversion bubbles.

(b)

The target is an OR of three terms: \(A \oplus B\), \(C\), and \(\overline{D}\). Every candidate starts with \(A \oplus B\), so the question is what the rest of each circuit does with \(C\) and \(D\).

In (b) the lower gate is an AND with a bubble on its output (a NAND) and a bubble on its \(C\) input, so it computes \(\overline{\overline{C} . D}\). De Morgan turns that into \(C + \overline{D}\), and the final OR adds \(A \oplus B\):

\[(A \oplus B) + \left(C + \overline{D}\right) = (A \oplus B) + C + \overline{D} \quad ✓\]

The others fail:

  • (a) the lower gate is an XOR, giving \((A \oplus B) + (C \oplus \overline{D})\). Try \(C = 1, D = 0\): the target is 1 but \(C \oplus \overline{D} = 1 \oplus 1 = 0\), so the two differ whenever \(A \oplus B = 0\).
  • (c) ends in a NOR, so the whole result is inverted: \(\overline{(A \oplus B) + C + D}\).
  • (d) is \(\overline{(A \oplus B) + C} + \overline{D}\) — the NOR is in the middle, so the first two terms come out inverted.
  • (e) cascades XORs: \(\left((A \oplus B) \oplus C\right) + \overline{D}\), which is not the same as ORing \(C\) in.

Q8 — Truth table for an expression

Which of the following truth tables is equivalent to the function \(X = (A . \overline{B} + C) . \overline{(B + A . \overline{C})}\)

A B C X
0 0 0 1
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 0
A B C X
0 0 0 1
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 0
A B C X
0 0 0 0
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 0
A B C X
0 0 0 0
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 0
  1. None of the above

(d)

Evaluate the two factors separately. Write \(P = A . \overline{B} + C\) and \(Q = \overline{B + A . \overline{C}}\), so \(X = P . Q\):

A B C \(A.\overline{B}\) \(P\) \(A.\overline{C}\) \(B + A.\overline{C}\) \(Q\) \(X\)
0 0 0 0 0 0 0 1 0
0 0 1 0 1 0 0 1 1
0 1 0 0 0 0 1 0 0
0 1 1 0 1 0 1 0 0
1 0 0 1 1 1 1 0 0
1 0 1 1 1 0 0 1 1
1 1 0 0 0 1 1 0 0
1 1 1 0 1 0 1 0 0

\(X\) is 1 for \(ABC = 001\) and \(101\) only, which is table (d). Note that \(Q\) forces \(X = 0\) whenever \(B = 1\), so only the four \(B = 0\) rows can ever be 1, and of those the two with \(C = 0\) fail — at \(000\) because \(P = 0\), and at \(100\) because \(A.\overline{C} = 1\) makes \(Q = 0\).

Simplified, \(X = \overline{B} . C\), which is a neater way to check the table.

Q9 — Function from a timing diagram

What logic function does the following timing diagram represent?

Figure 273: Question 9’s timing diagram. A, B and C step through all eight input combinations with A as the fastest signal, and X is the output to be identified.

  1. \(A \oplus B \oplus C\)

  2. \(A . \overline{B} . \overline{C} + \overline{A} . B . \overline{C} + \overline{A} . \overline{B} . C\)

  3. \(A . B . \overline{C} + A . \overline{B} . C + \overline{A} . B . C\)

  4. \(A . \overline{B} . \overline{C} + \overline{A} . B . C + \overline{A} . \overline{B} . C\)

  5. None of the above

(b)

A timing diagram is a truth table drawn sideways (see timing-diagrams). Reading the eight time slots left to right, \(A\) toggles every slot, \(B\) every two and \(C\) every four, so the slots walk through all eight combinations with \(A\) as the least significant bit:

Slot A B C X
0 0 0 0 0
1 1 0 0 1
2 0 1 0 1
3 1 1 0 0
4 0 0 1 1
5 1 0 1 0
6 0 1 1 0
7 1 1 1 0

\(X\) is 1 in exactly the three slots where precisely one input is 1, so as a sum of minterms

\[X = A . \overline{B} . \overline{C} + \overline{A} . B . \overline{C} + \overline{A} . \overline{B} . C\]

which is option (b) — an “exactly one input is high” detector.

Option (a) is tempting because \(A \oplus B \oplus C\) is also 1 for those three combinations, but three-input XOR is odd parity, so it is 1 for \(ABC = 111\) as well, and the diagram shows \(X = 0\) there. Options (c) and (d) each pick the wrong three minterms.

Q10 — NAND built from NOR gates

Which of the following circuits implements a 3 input NAND gate (\(\overline{A . B . C}\)) using only 2-input NOR gates?

Figure 274: Question 10’s five candidate NOR-only circuits. A NOR gate with both inputs tied together (marked by a junction dot) is being used as an inverter.

(e)

The target is \(\overline{A.B.C} = \overline{A} + \overline{B} + \overline{C}\). A NOR with its inputs tied together is an inverter, since \(\overline{x + x} = \overline{x}\), and a NOR of two inverted signals is an AND, since \(\overline{\overline{x} + \overline{y}} = x . y\). Those two facts decide every option.

Working each circuit through:

  • (a) \(\overline{A+B}\), inverted back to \(A + B\), NORed with \(C\) to give \(\overline{A+B+C}\), then inverted again: the output is \(A + B + C\).

  • (b) \(\overline{A}\), \(\overline{B}\), \(\overline{C}\); then \(\overline{\overline{A} + \overline{B}} = A.B\); then \(\overline{A.B + \overline{C}} = \overline{A.B} . C\). At \(A = B = C = 0\) this gives 0, but the NAND should give 1.

  • (c) the same up to \(A.B\), then an inverter making \(\overline{A.B}\), then \(\overline{\overline{A.B} + \overline{C}} = A.B.C\) — the AND, not the NAND.

  • (d) \(A.B\), then \(\overline{A.B + \overline{C}} = \overline{A.B}.C\), then an inverter giving \(A.B + \overline{C}\). At \(A = B = C = 1\) that is 1, but the NAND should give 0.

  • (e) \(A.B\), invert to \(\overline{A.B}\), NOR with \(\overline{C}\) to get \(\overline{\overline{A.B} + \overline{C}} = A.B.C\), then invert once more:

    \[\overline{A.B.C} \quad ✓\]

Circuit (e) is (c) with one extra inverter on the end, which is exactly the difference between AND and NAND — worth noticing, because (c) is the obvious trap.

Q11 — Equivalent expressions

Consider the logic function represented by the following truth table:

A B C X
0 0 0 1
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 0

Which of the following expressions is NOT equivalent to this function?

  1. \(\overline{B} + \overline{A} . \overline{C}\)

  2. \(\overline{A} . \overline{B} + \overline{A} . \overline{C} + A . \overline{B}\)

  3. \(\overline{A} . \overline{B} . \overline{C} + \overline{B}\)

  4. \(\overline{B} . C + \overline{A} . \overline{C} + \overline{B} . \overline{C}\)

  5. \(\overline{A} . \overline{B} . \overline{C} + \overline{A} . B . \overline{C} + A . \overline{B} . \overline{C} + \overline{A} . \overline{B} . C + A . \overline{B} . C\)

(c)

First get a canonical form. \(X = 1\) on the rows \(000\), \(001\), \(010\), \(100\), \(101\). Grouping the four rows with \(B = 0\) collapses them completely, leaving one extra term for row \(010\):

\[ \begin{aligned} X &= \overline{A}.\overline{B}.\overline{C} + \overline{A}.\overline{B}.C + A.\overline{B}.\overline{C} + A.\overline{B}.C + \overline{A}.B.\overline{C} \\ &= \overline{B} + \overline{A}.B.\overline{C} && \text{(the four $B=0$ rows are all of $\overline{B}$)} \\ &= \overline{B} + \overline{A}.\overline{C} && \text{($x + \overline{x}y = x + y$ with $x = \overline{B}$)} \end{aligned} \]

So the function is \(\overline{B} + \overline{A}.\overline{C}\), which is option (a) verbatim. Checking the rest:

  • (b) \(\overline{A}.\overline{B} + A.\overline{B} = \overline{B}\), leaving \(\overline{B} + \overline{A}.\overline{C}\). Equivalent.
  • (c) \(\overline{A}.\overline{B}.\overline{C}\) is contained in \(\overline{B}\), so by absorption the whole expression is just \(\overline{B}\). That loses row \(010\) (\(A=0\), \(B=1\), \(C=0\)), where the table says \(X = 1\) but \(\overline{B} = 0\). Not equivalent — this is the answer.
  • (d) \(\overline{B}.C + \overline{B}.\overline{C} = \overline{B}(C + \overline{C}) = \overline{B}\), leaving \(\overline{B} + \overline{A}.\overline{C}\). Equivalent.
  • (e) is the sum of exactly the five minterms where \(X = 1\). Equivalent by construction.

Q12 — D flip-flop input from output

Consider the flip-flop circuit shown below and the associated CLK and output (Q) signals. Which timing diagram shows input (A) values over time which would have resulted in the given output (Q).

Figure 275: Question 12’s given CLK and Q waveforms and the positive-edge-triggered D flip-flop that produced them, with the five candidate A waveforms below.

(e)

The triangle on the clock input makes this a positive-edge-triggered D flip-flop, so the only thing that matters is the value of A at the instant of each rising clock edge; everything A does between edges is invisible. There are four rising edges in the diagram, and Q tells us what A must have been at each:

Rising edge Q after the edge so A at the edge
1st 0 (unchanged) 0
2nd 1 1
3rd 0 0
4th 1 1

So A must read 0, 1, 0, 1 at the four rising edges. Checking each candidate at those four instants:

  • (a) is high at the first rising edge — needs 0. ✗
  • (b) gives 0, 1, 1, … — wrong at the third edge, where its pulse has not yet fallen. ✗
  • (c) gives 0, 0, … — it is low across the second rising edge. ✗
  • (d) gives 0, 1, 0, 0 — its single pulse has long finished by the fourth edge. ✗
  • (e) gives 0, 1, 0, 1 at the four edges. ✓

Waveform (e) is deliberately full of narrow glitches, and that is the point of the question: none of them land on a rising clock edge, so the flip-flop never sees them. See flip-flops-and-latches.

Q13 — Two’s complement addition

What’s the result of adding the 6-bit two’s complement numbers 101101 and 110011?

  1. 000000

  2. 010000

  3. 100000

  4. 111110

  5. 111111

(c)

Add the bit patterns as plain binary and discard the carry out of the top bit, which is what two’s complement addition amounts to:

    101101
  + 110011
  --------
  1 100000

Every column from the least significant up produces a carry, and the carry out of the top bit is dropped, so the result in six bits is \(100000\).

Checking in decimal: \(101101\) has its MSB set, so its magnitude is the two’s complement \(\overline{101101} + 1 = 010010 + 1 = 010011 = 19\), i.e. the value is \(-19\). Likewise \(110011 \to 001100 + 1 = 001101 = 13\), i.e. \(-13\). The sum is \(-32\), and \(-32\) in 6-bit two’s complement is \(100000\). ✓

Two negatives adding to a negative means no overflow, so the six-bit answer is valid. See binary-number-representations, and Beyond the paper below for the single chip that does this addition in hardware — the same chip whether you read the operands as signed or unsigned.

Q14 — Overflow detection

Which of the following operations will result in an overflow in 6-bit two’s complement arithmetic?

  1. 011111 – 010010

  2. 101011 – 111000

  3. 110100 – 000111

  4. 010101 + 111111

  5. None of the above

(e)

Six-bit two’s complement covers \(-32\) to \(+31\). Overflow happens exactly when the true mathematical result falls outside that window, so convert each operand and check:

operands (decimal) result in range?
(a) \(011111 = 31\), \(010010 = 18\) \(31 - 18 = 13\) yes
(b) \(101011 = -21\), \(111000 = -8\) \(-21 - (-8) = -13\) yes
(c) \(110100 = -12\), \(000111 = 7\) \(-12 - 7 = -19\) yes
(d) \(010101 = 21\), \(111111 = -1\) \(21 + (-1) = 20\) yes

None of them overflows, so the answer is (e).

The structural shortcut gets there faster in three of the four cases: subtracting two values of the same sign, or adding two values of opposite sign, can never overflow, because the result lies between the two operands. That immediately clears (a) (positive minus positive), (b) (negative minus negative) and (d) (positive plus negative). Only (c) — negative minus positive — can overflow in principle, and \(-19\) comfortably fits.

The same decision made in gates, from the sign bits of the operands and of the result, is the overflow LED of Beyond the paper below.

Q15 — Overflow and a zero result

Consider the binary addition operation 1010 + 0110. Which of the following statements is true if the numbers are interpreted as two’s complement?

  1. The result is negative and no overflow occurs

  2. The result should be negative but overflow occurs

  3. The result is positive and no overflow occurs

  4. The result should be positive but overflow occurs

  5. The result is zero

(e)

As 4-bit two’s complement, \(1010\) has its sign bit set so its magnitude is \(\overline{1010} + 1 = 0101 + 1 = 0110 = 6\), i.e. the value is \(-6\); and \(0110 = +6\). The sum is \(-6 + 6 = 0\).

The bit-level addition agrees:

  1010
+ 0110
------
 10000

The carry out of the top bit is discarded, leaving \(0000\). Note that the carry out being 1 does not mean overflow here — for two’s complement, overflow is signalled by the carry into the sign bit differing from the carry out of it, and here both are 1. Adding a positive and a negative number can never overflow anyway, since the result always lies between them.

So the result is exactly zero, which is neither the “negative” of (a) nor the “positive” of (c), and no overflow occurs, ruling out (b) and (d).

On the board this is two lit indicators that mean opposite things: the carry-out LED on and the overflow LED off. Beyond the paper below shows why they are separate outputs.

Q16 — Full adder from multiplexers

Consider the full-adder shown below:

In the multiplexer circuit below, what values do the multiplexer inputs X0,X1,X2,X3 and Y0,Y1,Y2,Y3 need to take on in order for the circuit to implement a full-adder?

Figure 276: Question 16’s full-adder block and the two 4-to-1 multiplexers that are to implement it, with A on the \(S_1\) select and B on \(S_0\).

  1. X0 = 0, X1 = 1, X2 = 1, X3 = 0; Y0 = 0, Y1 = 0, Y2 = 0, Y3 = 1

  2. X0 = \(C_{in}\), X1 = \(\overline{C_{in}}\), X2 = \(\overline{C_{in}}\), X3 = \(C_{in}\); Y0 = 0, Y1 = \(C_{in}\), Y2 = \(C_{in}\), Y3 = 1

  3. X0 = 0, X1 = \(\overline{C_{in}}\), X2 = \(\overline{C_{in}}\), X3 = 1; Y0 = 0, Y1 = \(C_{in}\), Y2 = \(C_{in}\), Y3 = 1

  4. X0 = \(C_{in}\), X1 = 1, X2 = 1, X3 = \(C_{in}\); Y0 = 0, Y1 = \(\overline{C_{in}}\), Y2 = \(\overline{C_{in}}\), Y3 = \(C_{in}\)

  5. None of the above

(b)

Both multiplexers are steered by the same select pair, \(S_1 = A\) and \(S_0 = B\), so input \(n\) of each multiplexer is the one selected when \(AB\) is the two-bit number \(n\). Each data input therefore has to be the full-adder output as a function of \(C_{in}\) alone, for that one combination of A and B. This is the standard “multiplexer as a function generator” trick — see combinational-logic-blocks.

The full adder is \(\text{Sum} = A \oplus B \oplus C_{in}\) and \(\text{C}_{out} = A.B + C_{in}.(A \oplus B)\), so:

\(S_1 S_0 = AB\) input \(A \oplus B\) Sum \(= (A \oplus B) \oplus C_{in}\) \(C_{out}\)
00 X0 / Y0 0 \(C_{in}\) 0
01 X1 / Y1 1 \(\overline{C_{in}}\) \(C_{in}\)
10 X2 / Y2 1 \(\overline{C_{in}}\) \(C_{in}\)
11 X3 / Y3 0 \(C_{in}\) 1

That is exactly option (b). The pattern is easy to remember: the Sum multiplexer gets \(C_{in}\) where \(A \oplus B = 0\) and \(\overline{C_{in}}\) where \(A \oplus B = 1\); the carry multiplexer gets the constants 0 and 1 where A and B agree, and \(C_{in}\) where they differ.

This is one bit slice. Four of them chained carry-to-carry are what a 74HCT283 holds in a single package — see Beyond the paper below.

Q17 — Synchronous counter sequence

What sequence will the following synchronous counter count through, if it starts at \(Q_1Q_0 = 00\)?

Figure 277: Question 17’s counter. Note which flip-flop output feeds the XOR: the wire from FF1’s \(\overline{Q}\) turns up to the gate, while FF1’s Q crosses it and carries on to the \(Q_1\) label.

  1. \(Q_1Q_0\): \(00 \to 11 \to 10 \to 01 \to 00 \to \ldots\)

  2. \(Q_1Q_0\): \(00 \to 11 \to 10 \to 11 \to 10 \to \ldots\)

  3. \(Q_1Q_0\): \(00 \to 01 \to 10 \to 11 \to 00 \to \ldots\)

  4. \(Q_1Q_0\): \(00 \to 01 \to 00 \to \ldots\)

  5. \(Q_1Q_0\): \(00 \to 11 \to 00 \to \ldots\)

(a)

Read the excitation equations off the wiring. The right-hand flip-flop has its own \(\overline{Q}\) routed back round to its D input, so it toggles every clock:

\[D_0 = \overline{Q_0}\]

The XOR feeding the left-hand flip-flop takes \(Q_0\) along the long top wire and — this is the detail the question turns on — \(\overline{Q_1}\), not \(Q_1\): the wire that turns up into the gate leaves FF1’s \(\overline{Q}\) pin, and FF1’s Q wire merely crosses it on its way to the \(Q_1\) output. So

\[D_1 = Q_0 \oplus \overline{Q_1}\]

Both flip-flops share CLK, so the counter is synchronous and both update from the current state. Tracing from \(Q_1Q_0 = 00\):

\(Q_1 Q_0\) \(D_1 = Q_0 \oplus \overline{Q_1}\) \(D_0 = \overline{Q_0}\) next
00 \(0 \oplus 1 = 1\) 1 11
11 \(1 \oplus 0 = 1\) 0 10
10 \(0 \oplus 0 = 0\) 1 01
01 \(1 \oplus 1 = 0\) 0 00

So \(00 \to 11 \to 10 \to 01 \to 00 \to \ldots\), which is option (a) — a down-counter.

Had the XOR been fed \(Q_1\) instead, \(D_1\) would be \(Q_1 \oplus Q_0\) and the sequence would be the ordinary up-count \(00 \to 01 \to 10 \to 11\) of option (c), so the two answers differ by exactly which flip-flop pin that wire leaves from. See [counters].

Q18 — Multiplexer-fed register pair

Consider the circuit below. If \(A_1\) is 0 and \(A_0\) is 1, what are the values of \(Q_1\) and \(Q_0\) after four rising clock edges if FN is 0 for one rising clock edge then 1 for three rising clock edges?

Figure 278: Question 18’s circuit: each flip-flop is fed by a 2-to-1 multiplexer that selects between an external input and the other flip-flop’s output, under the common FN control.

  1. \(Q_1 = 0\), \(Q_0 = 0\)

  2. \(Q_1 = 0\), \(Q_0 = 1\)

  3. \(Q_1 = 1\), \(Q_0 = 0\)

  4. \(Q_1 = 1\), \(Q_0 = 1\)

  5. Insufficient information is provided to determine the values

(c)

Both multiplexers share the select line FN, and each takes the external input on its “0” leg and the other flip-flop’s output on its “1” leg — \(Q_0\) comes back along the bottom rail into the left multiplexer, and \(Q_1\) crosses over into the right one. So

\[ \begin{aligned} D_1 &= \begin{cases} A_1 & \text{FN} = 0 \\ Q_0 & \text{FN} = 1 \end{cases} &\qquad D_0 &= \begin{cases} A_0 & \text{FN} = 0 \\ Q_1 & \text{FN} = 1 \end{cases} \end{aligned} \]

FN = 0 is a parallel load of \(A_1A_0\); FN = 1 swaps the two bits. With \(A_1 = 0\), \(A_0 = 1\):

Edge FN \(Q_1 Q_0\) after
1 0 \(01\) (load \(A_1A_0\))
2 1 \(10\) (swap)
3 1 \(01\) (swap)
4 1 \(10\) (swap)

After the fourth edge \(Q_1 = 1\) and \(Q_0 = 0\), which is option (c). Note that the initial contents of the flip-flops never matter, because the first edge loads them both — so (e) is wrong.

Q19 — Tracing a state machine

Consider the state machine represented by the state diagram below:

Figure 279: Question 19’s five-state machine. Each circle carries the state name above the rule and its X,Y output below.

What sequence of states is traversed if the machine starts in state S1 and A goes through the sequence 101010101?

  1. S1\(\to\)S2\(\to\)S4\(\to\)S3\(\to\)S1\(\to\)S2\(\to\)S4\(\to\)S3\(\to\)S1\(\to\)S2

  2. S1\(\to\)S1\(\to\)S2\(\to\)S3\(\to\)S1\(\to\)S2\(\to\)S4\(\to\)S3\(\to\)S1\(\to\)S2

  3. S1\(\to\)S1\(\to\)S2\(\to\)S4\(\to\)S3\(\to\)S1\(\to\)S2\(\to\)S4\(\to\)S3\(\to\)S1

  4. S1\(\to\)S1\(\to\)S2\(\to\)S4\(\to\)S0\(\to\)S0\(\to\)S1\(\to\)S2\(\to\)S4\(\to\)S3

  5. None of the above

(c)

First read the transitions off the diagram:

State on \(\overline{A}\) on \(A\)
S0 S0 S1
S1 S2 S1
S2 S3 S4
S3 S0 S1
S4 S3 S0

Now walk the input \(1,0,1,0,1,0,1,0,1\) from S1, listing the starting state and then the state after each input:

\[\mathrm{S1} \xrightarrow{1} \mathrm{S1} \xrightarrow{0} \mathrm{S2} \xrightarrow{1} \mathrm{S4} \xrightarrow{0} \mathrm{S3} \xrightarrow{1} \mathrm{S1} \xrightarrow{0} \mathrm{S2} \xrightarrow{1} \mathrm{S4} \xrightarrow{0} \mathrm{S3} \xrightarrow{1} \mathrm{S1}\]

Ten states for nine inputs, which is option (c). The machine falls into the four-state loop S1 → S2 → S4 → S3 → S1 and never visits S0 for this input, because S0 is only reachable from S3 on \(\overline{A}\) or S4 on \(A\), and neither happens here.

Option (a) is the same walk with the first (self-loop) step omitted, so it is the trap for forgetting that the initial 1 leaves the machine in S1. See state-machines.

Q20 — State diagram to state table

Consider the state diagram below.

Figure 280: Question 20’s four-state machine, with each state’s X,Y,Z output printed under its name.

Which of the following is an equivalent state table?

Current State Input (A) Next State Outputs (X,Y,Z)
S0 0 S0 111
S0 1 S1 111
S1 0 S1 101
S1 1 S2 101
S2 0 S3 001
S2 1 S2 001
S3 0 S0 110
S3 1 S1 110
Current State Input (A) Next State Outputs (X,Y,Z)
S0 0 S0 111
S0 1 S1 111
S1 0 S2 101
S1 1 S1 101
S2 0 S3 001
S2 1 S2 001
S3 0 S1 110
S3 1 S0 110
Current State Next State A=0 Next State A=1 Outputs (X,Y,Z)
S0 S0 S1 111
S1 S2 S1 101
S2 S2 S3 001
S3 S0 S1 110
Current State Next State A=0 Next State A=1 Outputs (X,Y,Z)
S0 S0 S1 111
S1 S2 S1 101
S2 S3 S2 001
S3 S0 S1 110
  1. None of the above

(d)

Read the diagram into a table. Every state has one arrow for \(A\) and one for \(\overline{A}\), and the outputs are printed inside the circles, so this is a Moore machine:

Current State \(A = 0\) \(A = 1\) Outputs
S0 S0 (self-loop \(\overline{A}\)) S1 111
S1 S2 S1 (self-loop \(A\)) 101
S2 S3 S2 (self-loop \(A\)) 001
S3 S0 S1 110

That is exactly table (d). The three wrong tables each get one row backwards:

  • (a) sends S1 to itself on \(A = 0\) and to S2 on \(A = 1\), i.e. S1’s two arrows swapped.
  • (b) swaps S3’s two arrows, sending it to S1 on \(\overline{A}\) and S0 on \(A\).
  • (c) swaps S2’s, so the self-loop lands on \(A = 0\) instead of \(A = 1\).

Q21 — Flip-flops for a state machine

What’s the minimum number of flip-flops needed to build the state machine shown in question 20?

  1. 1

  2. 2

  3. 3

  4. 4

  5. 5

(b)

The flip-flops hold the state, not the outputs. The machine of Q20 has four states, and \(n\) flip-flops give \(2^n\) distinct state encodings, so the minimum is

\[n = \lceil \log_2 4 \rceil = 2\]

The three outputs X, Y and Z are a combinational function of the two state bits — that is what makes it a Moore machine — so they cost gates, not flip-flops. Answer (c) is the trap for counting the three output bits, and (d) for using one flip-flop per state (a valid one-hot encoding, but not the minimum). See state-machines.

Q22 — Multiplexer as a logic function

Consider the following multiplexer. What must the inputs A,B,C,D be so that the multiplexer implements the function \(X = \overline{S_0} + S_1\)?

Figure 281: Question 22’s 4-to-1 multiplexer, with its four data inputs A, B, C, D and the select pair \(S_1 S_0\).

  1. A=0, B=1, C=0, D=0

  2. A=0, B=1, C=1, D=1

  3. A=1, B=0, C=1, D=1

  4. A=1, B=1, C=0, D=1

  5. None of the above

(c)

The select pair \(S_1 S_0\) read as a two-bit number picks the data input of that number, so A is chosen for \(S_1S_0 = 00\), B for \(01\), C for \(10\) and D for \(11\). Each data input therefore just has to be the value the function takes for that one select combination — with no variables left over, the inputs are all constants:

\(S_1\) \(S_0\) input chosen \(X = \overline{S_0} + S_1\)
0 0 A \(1 + 0 = 1\)
0 1 B \(0 + 0 = 0\)
1 0 C \(1 + 1 = 1\)
1 1 D \(0 + 1 = 1\)

So A = 1, B = 0, C = 1, D = 1, which is option (c). Reading the data inputs top to bottom gives the function’s truth-table column directly — that is the whole trick to using a multiplexer as a function generator, see combinational-logic-blocks.

Q23 — Which circuit is a latch

Which of the following circuits is capable of acting as a latch? i.e. it has combinations of inputs (M,N) which allow a bit (0 or 1) to be stored, the latch to be set (Q=1) with a single input transition, and the latch to be cleared (Q=0) with a single input transition?

Figure 282: Question 23’s four candidate cross-coupled circuits. In each one Q is the top gate’s output, and it is fed back to the bottom gate whose output returns to the top gate.

  1. None of the above

(a)

Each circuit is the same feedback loop with different gates, so write the loop equation and look for a hold state.

(a) — AND on top, OR underneath: \(Q = M . (Q + N)\).

M N \(Q = M.(Q+N)\) behaviour
0 0 \(0\) clear
0 1 \(0\) clear
1 0 \(Q\) hold
1 1 \(1\) set

Sitting in the hold state \((M,N) = (1,0)\), taking N to 1 sets it and taking M to 0 clears it — one input transition each, and both return to holding when the input goes back. This is the classic AND–OR latch (N is set, M is an active-low reset), so (a) is the answer.

(b) — XOR on top, NOR underneath: \(Q = M \oplus \overline{Q + N}\). At \((1,0)\) this is \(1 \oplus \overline{Q} = Q\), so it holds; at \((1,1)\) it forces \(Q = 1\); but the only clearing combination is \((0,1)\), which is two transitions away from the hold state, and \((0,0)\) gives \(Q = \overline{Q}\), which oscillates rather than settling.

(c) — XOR on top and bottom: \(Q = M \oplus Q \oplus N\). That is stable only when \(M \oplus N = 0\), and then \(Q = Q\) for both \((0,0)\) and \((1,1)\) — it can hold but can never be forced to a value, so it can be neither set nor cleared. When \(M \neq N\) it oscillates.

(d) — NAND on top, NOR underneath: \(Q = \overline{M . \overline{Q + N}}\). With \(M = 0\) the output is forced to 1; with \(M = 1\) it reduces to \(Q + N\), which holds at \(N = 0\) and sets at \(N = 1\). There is no combination that forces \(Q = 0\), so it can never be cleared.

See flip-flops-and-latches for the standard NOR and NAND cross-coupled latches this question is testing against.

Q24 — ALU control settings

Consider the ALU bit slice below.

Figure 283: Question 24’s ALU bit slice. The ENA/ENB/INVB gates on the left condition A and B into internal lines X and Y; five logic gates and the full adder compute candidate results from them, and the 8-way multiplexer picks one under \(F_2 F_1 F_0\). Note that the conditioned A line is also what leaves as Right Shift Out.

For an ALU made up of 8 of the bit slices above, which of the following control input settings will result in the ALU output being \(\overline{A} . B\) ? (The “Right Shift In” control input refers to that for the most significant bit; the “Carry in” control input refers to that for the least significant bit.)

  1. ENA = 1, ENB = 1, INVB = 0, \(F_2\) = 0, \(F_1\) = 0, \(F_0\) = 0, Right Shift In = 0, Carry in = 0

  2. ENA = 1, ENB = 1, INVB = 1, \(F_2\) = 0, \(F_1\) = 1, \(F_0\) = 1, Right Shift In = 0, Carry in = 1

  3. ENA = 1, ENB = 1, INVB = 0, \(F_2\) = 0, \(F_1\) = 1, \(F_0\) = 1, Right Shift In = 0, Carry in = 1

  4. ENA = 1, ENB = 1, INVB = 1, \(F_2\) = 1, \(F_1\) = 0, \(F_0\) = 1, Right Shift In = 0, Carry in = 0

  5. ENA = 1, ENB = 1, INVB = 1, \(F_2\) = 1, \(F_1\) = 1, \(F_0\) = 1, Right Shift In = 0, Carry in = 1

(d)

Start from the conditioning gates. Writing \(X\) for the conditioned A line and \(Y\) for the conditioned B line,

\[X = A . \text{ENA} \qquad Y = (B . \text{ENB}) \oplus \text{INVB}\]

so with ENA = ENB = 1, \(X = A\) and \(Y\) is \(B\) when INVB = 0 or \(\overline{B}\) when INVB = 1. Note there is no INVA on this slice, so \(\overline{A}\) is never available directly — that is the crux of the question.

Tracing each multiplexer input back to the gate that drives it gives the function table:

\(F_2 F_1 F_0\) multiplexer input Output
000 0 \(X . Y\)
001 1 \(X + Y\)
010 2 \(X \oplus Y\)
011 3 \(\overline{X . Y}\)
100 4 Carry In
101 5 \(\overline{X + Y}\)
110 6 Right Shift In
111 7 \(X \oplus Y \oplus C_{in}\) (the adder sum)

Since \(\overline{A}\) cannot be produced by the input conditioning, the inversion has to come from a gate. De Morgan supplies it:

\[\overline{A} . B = \overline{A + \overline{B}}\]

which is the NOR of \(A\) and \(\overline{B}\) — i.e. set INVB = 1 so \(Y = \overline{B}\), and select the NOR at input 5, \(F_2F_1F_0 = 101\). That is option (d), and its Right Shift In and Carry in are irrelevant to a purely logical operation.

Checking the others: (a) selects the AND with \(Y = B\), giving \(A . B\); (b) and (c) both select the NAND (\(F_2F_1F_0 = 011\)) and differ only in INVB, giving \(\overline{A . \overline{B}} = \overline{A} + B\) and \(\overline{A . B}\) respectively; (e) selects the adder with \(Y = \overline{B}\) and carry in 1, giving \(A \oplus \overline{B} \oplus 1 = A \oplus B\). See arithmetic-logic-unit.

Q25 — ALU operation coverage

For the ALU in question 24, which of the following bitwise logical operations can NOT be performed?

  1. \(\overline{A} + B\)

  2. \(A \oplus \overline{B}\)

  3. \(\overline{A} \oplus B\)

  4. \(\overline{A . B}\)

  5. All of the above operations can be performed

(e)

Using the same reading of the slice as Q24: \(X\) can be \(A\) or \(0\), \(Y\) can be \(B\), \(\overline{B}\), \(0\) or \(1\), and the five logic functions available are AND, OR, XOR, NAND and NOR of \(X\) and \(Y\). Setting ENA = ENB = 1 and choosing INVB and \(F_2F_1F_0\):

Wanted Rewrite Settings
(a) \(\overline{A} + B\) \(\overline{A . \overline{B}}\) INVB = 1, NAND (\(F = 011\))
(b) \(A \oplus \overline{B}\) as written INVB = 1, XOR (\(F = 010\))
(c) \(\overline{A} \oplus B\) \(= A \oplus \overline{B}\) INVB = 1, XOR (\(F = 010\))
(d) \(\overline{A . B}\) as written INVB = 0, NAND (\(F = 011\))

All four are reachable, so the answer is (e).

The one worth pausing on is (c). Complementing either operand of an XOR complements the result, so \(\overline{A} \oplus B\) and \(A \oplus \overline{B}\) are the same function — both are \(\overline{A \oplus B}\), i.e. XNOR — and the slice can produce it even though it has no INVA. The absence of INVA restricts less than it looks like it should: De Morgan and the XOR identity between them let the missing complement be pushed onto B.

Beyond the paper — the adder as a real chip

Q13, Q14 and Q15 all run the same adder by hand, and Q16 builds one out of multiplexers. Learning Lab 3 (Binary Arithmetic) builds it out of a single part instead, and the schematic is worth having in front of you, because three of this paper’s traps are visible in it as separate wires.

This is Task 2 of Learning Lab 3 (Binary Arithmetic), drawn to the rules in circuit-schematics with the symbol and pin numbers from the Device Pinouts and Symbols sheet. The particular signal-to-pin assignments on the IO board are a free choice. The sheet fixes the ranges (switches on pins 25–32, buttons on 12–15, LEDs on 17–24) but not which switch carries which bit. See week2-lab-binary-arithmetic for the rest of the lab.

The task

Add two 4-bit numbers set on switches, show the 4-bit result and the carry out on LEDs, and put the carry in on a push button. One chip does all the arithmetic: the 74HCT283, four full adders in a 16-pin package with the intermediate carries \(C_1\), \(C_2\), \(C_3\) joined stage to stage inside it, so only \(C_0\) and \(C_4\) appear on pins.

Figure 284: Lab 3 Task 2 as a circuit schematic: a 74HCT283 adding two 4-bit numbers from IO-board switches, with the carry in on a push button and the sum and carry out on LEDs. Everything a schematic is required to carry is here — a unique name on every input and output, the device identifier U1 with its type underneath, a pin number at both ends of every wire, the IO board labelled once per group rather than once per signal, and a power block giving Vcc and GND for the device type. The 74HCT283 is a 16-pin part, so its supply pins are 16 and 8 — not the 14 and 7 of the quad gate packages, which is the mistake this schematic exists to prevent. The input pentagons attach their wire at the point and the output pentagons at the flat back; getting that round the wrong way is one of the errors the drawing guide lists.

One adder, two interpretations

The lab’s instruction after building it is “try some unsigned and two’s complement test cases — are the results as you expect?”, and the answer is the point of the whole exercise: the chip does not know which you meant. It adds bit patterns. Nothing inside it changes between Q13’s two’s complement reading and an unsigned one; the same eight switches and the same five LEDs serve both. What changes is only which condition means the answer on the LEDs is wrong:

Reading Range in 4 bits The answer is wrong when
Unsigned 0 to 15 \(C_4 = 1\) — the true sum needed a fifth bit
Two’s complement \(-8\) to \(+7\) the operands’ sign bits agreed and \(S_3\) disagrees with them

That is why \(C_4\) gets its own LED separate from the sum. It is also precisely the trap in Q15: \(1010 + 0110\) produces \(C_4 = 1\), and the answer is still exactly right, because the reading is two’s complement and the carry out is discarded rather than consulted.

The extension, and what it needs

The lab then asks for an overflow LED as well, with a constraint that changes the problem: “you don’t have access to C3 which is an internal signal. Therefore, you need the overflow output expressed in terms of available information (i.e. A3, B3, S3, C4).” Reading the schematic explains why — \(C_3\) is joined to the next full adder inside the package and never reaches a pin, so the familiar \(V = C_3 \oplus C_4\) cannot be wired.

The two expressions that can be wired from pins are

\[V = A_3 B_3 \overline{S_3} + \overline{A_3}\,\overline{B_3}\,S_3 \qquad\text{and}\qquad V = A_3 \oplus B_3 \oplus S_3 \oplus C_4\]

both of which are derived and drawn in csse2010-sample-midsem-2. The second is the cheaper build — three XOR gates, one 74HCT86 — and it is the reason \(C_4\) is among the signals you are allowed to use. Either one, driven onto an LED, turns Q14 from a decimal calculation into something the board tells you.

Where Q16 fits

Q16’s pair of multiplexers implements one of the four full adders inside this package. Cascading four of them, carry to carry, is what the 74HCT283 has done for you — see combinational-logic-blocks for the ripple-carry structure and device-pinouts for the chip’s internals as the source sheet draws them.

Your score

Reload the page to clear your answers.

Sample Mid-semester Exam #5

This is UQ’s fifth sample mid-semester paper for CSSE2010/CSSE7201 Introduction to Computer Systems, printed for the Semester One mid-semester examinations, 2020, and set for St Lucia campus students. It runs for 60 minutes with 10 minutes of reading time, under open-book conditions — no electronic aids beyond a Casio FX82-series or UQ-approved calculator — and answers go on a supplied True/False and Multiple Choice answer sheet. There are 25 questions; each correct answer scores one mark, and an incorrect, missing or multiple answer scores zero, so there is no penalty for guessing. See csse2010 for the course note.

WarningAnswers are derived, not official

The source paper ships without an answer key, so every answer below was worked out during transcription rather than taken from UQ. Each one shows its reasoning so it can be checked rather than trusted; anything uncertain is flagged. Treat a disagreement between your working and the answer here as a reason to check both.

How to use this

Two ways. The first is a timed run: 25 questions in 60 minutes, working straight down the paper. On the site every answer is collapsed behind a disclosure triangle, so nothing is spoiled until you click it — that is the version to practise from. The second is targeted practice: use the question index below to pick out only the questions for one week or one concept, do those, and follow the concept link when the working does not make sense.

In the PDF build the collapsed callouts are always open, so the PDF is an answer key rather than a practice paper.

Question index

Q Topic Week Concept notes
1 Excess-128 representation 1 binary-number-representations · week1-lab-number-representations
2 Hexadecimal to octal 1 binary-number-representations · week1-lab-number-representations
3 Two’s complement range 1 binary-number-representations · week1-lab-number-representations
4 Converting between representations 1 binary-number-representations · week1-lab-number-representations
5 XNOR gate chain 1 logic-gates
6 Boolean simplification 2 boolean-algebra
7 Gate circuit for an expression 1 logic-gates
8 Expression to truth table 2 boolean-algebra
9 Timing diagram to expression 2 timing-diagrams
10 Sum-of-products form 2 boolean-algebra
11 3-input NOR from 2-input NANDs 1 logic-gates
12 D flip-flop timing 3 flip-flops-and-latches
13 Two’s complement addition 2 binary-number-representations
14 Overflow detection 2 binary-number-representations
15 Overflow and result sign 2 binary-number-representations
16 Multiplexer as function generator 2 combinational-logic-blocks
17 Multiplexer output function 2 combinational-logic-blocks
18 Multiplexer-fed flip-flops 3 flip-flops-and-latches
19 Synchronous counter trace 4 [counters]
20 Flip-flops for a count sequence 4 state-machines
21 State diagram to state table 4 state-machines
22 State encoding width 4 state-machines
23 Tracing a state sequence 4 state-machines
24 ALU function select 5 arithmetic-logic-unit
25 ALU constant generation 5 arithmetic-logic-unit

Q1 — Excess-128 representation

What is \(-75_{10}\) expressed in 8-bit excess-128 format?

  1. 00110101

  2. 01001011

  3. 10110100

  4. 10110101

  5. 11001011

(a)

Excess-128 stores a value \(N\) as the plain unsigned binary of \(N + 128\). So

\[-75 + 128 = 53\]

and \(53 = 32 + 16 + 4 + 1\), which in 8 bits is \(00110101\).

Sanity check against the two’s complement form: \(-75\) in 8-bit two’s complement is \(10110101\) (option (d)), and excess-128 is exactly two’s complement with the sign bit flipped — flipping the leading 1 to 0 gives \(00110101\) again. See binary-number-representations.

Q2 — Hexadecimal to octal

What is the minimum number of octal digits needed to represent the number \(1ACED2010_{16}\)?

  1. 7

  2. 9

  3. 11

  4. 12

  5. None of the above

(c)

Go via binary, since both bases are powers of two. The number has nine hex digits, and each expands to four bits:

\[1\,A\,C\,E\,D\,2\,0\,1\,0 \;\to\; 0001\;1010\;1100\;1110\;1101\;0010\;0000\;0001\;0000\]

That is 36 bits with three leading zeros, so 33 significant bits. Octal digits take three bits each, and \(\lceil 33/3 \rceil = 11\).

Regrouping the 36 bits into twelve groups of three from the right confirms it — the first group is \(000\) and drops away:

\[000\;110\;101\;100\;111\;011\;010\;010\;000\;000\;010\;000 \;=\; 65473220020_8\]

which is 11 digits.

Q3 — Two’s complement range

A 5-bit number in two’s complement format can represent integers from

  1. −32 to 31

  2. −31 to 31

  3. −16 to 15

  4. −15 to 15

  5. 0 to 31

(c)

An \(n\)-bit two’s complement number covers \(-2^{n-1}\) to \(2^{n-1}-1\). With \(n = 5\) that is \(-16\) to \(15\): \(10000\) is the most negative value and \(01111\) the most positive. The asymmetry is the giveaway — two’s complement has one more negative value than positive, which rules out (b) and (d) immediately, and (a) is the 6-bit range. See binary-number-representations.

Q4 — Converting between representations

Which of the following statements about binary number representations is FALSE?

  1. Any 8-bit two’s complement number can be converted to excess-128 representation by inverting the sign-bit

  2. Any negative n-bit two’s complement number can be converted to ones’ complement representation by subtracting 1

  3. Any negative n-bit ones’ complement number can be converted to two’s complement representation by adding 1

  4. Any negative n-bit ones’ complement number can be converted to signed-magnitude representation by inverting all bits except the sign-bit

  5. None of the above

(e) — all four statements are true, so none of them is the false one.

  1. For a value \(v\) in \([-128, 127]\), two’s complement stores \(v \bmod 256\) and excess-128 stores \(v + 128\). For \(v \ge 0\) the stored patterns differ by exactly \(+128\), which sets a bit 7 that was 0; for \(v < 0\) they differ by exactly \(-128\), which clears a bit 7 that was 1. Either way, flip the sign bit. Q1 is a worked instance: \(-75\) is \(10110101\) in two’s complement and \(00110101\) in excess-128.

  2. A negative \(v\) is stored as \(2^n + v\) in two’s complement and \(2^n - 1 + v\) in ones’ complement, a difference of exactly 1. Example with \(n=4\): \(-3\) is \(1101\) two’s complement, and \(1101 - 1 = 1100\), which is ones’ complement \(-3\). The one value this misses is \(-2^{n-1}\), which two’s complement can hold and ones’ complement cannot, so strictly nothing converts it; read as the standard conversion rule, which is how the paper means it, (b) is true.

  3. The same identity read backwards, so it is true too: \(1100 + 1 = 1101\).

  4. Ones’ complement represents \(-m\) as the bitwise complement of the pattern for \(+m\). Since \(+m\) has a 0 sign bit, the magnitude bits of \(-m\) are the complement of the magnitude of \(m\); inverting them back recovers \(m\) and leaves the 1 sign bit in place, which is exactly signed-magnitude. Example with \(n=4\): \(-3\) is \(1100\) in ones’ complement, and inverting the low three bits gives $1011 = $ signed-magnitude \(-3\).

Figure 285: The four statements as one map, worked on a single value. Options (d), (b)/(c) and (a) are the three links in the chain, read from left to right; each arrow is one of the paper’s four claims. The bit patterns are 4-bit representations of \(-3\), so you can check every arrow by eye: invert the magnitude bits, subtract or add one, flip the sign bit. The two left-hand links hold for negative values only, which is not a limitation in practice because all four formats already agree on the positives — the right-hand link is the one that works either way.

See binary-number-representations and week1-lab-number-representations for all four formats side by side.

Q5 — XNOR gate chain

What function is implemented by the following circuit?

Figure 286: Question 5’s circuit: A and B into an XNOR gate, whose output goes with C into a second XNOR gate.

  1. \(\overline{A \oplus B} \oplus C\)

  2. \(A \oplus B \oplus \overline{C}\)

  3. \(\overline{A} \oplus \overline{B} \oplus \overline{C}\)

  4. \(A \oplus B \oplus C\)

  5. None of the above

(d)

Both gates are XNORs — XOR bodies with an inversion bubble on the output. The first produces \(\overline{A \oplus B}\), and the second XNORs that with \(C\):

\[X = \overline{\;\overline{A \oplus B} \oplus C\;}\]

Now use the fact that complementing one input of an XOR complements its output, i.e. \(\overline{x} \oplus y = \overline{x \oplus y}\). Applying it to the inner term:

\[\overline{A \oplus B} \oplus C = \overline{(A \oplus B) \oplus C}\]

so the outer inversion cancels it and \(X = A \oplus B \oplus C\).

The other three options are all the same function as each other, and all equal \(\overline{A \oplus B \oplus C}\) — the complement of the answer. That is worth noticing: (a), (b) and (c) each apply an odd number of complements to an XOR chain, so they must agree with one another and disagree with (d). Two XNORs in series apply two complements, which cancel. See logic-gates.

Q6 — Boolean simplification

Which of the following logic functions is identical to \(\overline{\overline{A \cdot \overline{B}} \cdot C} \cdot (C + \overline{A} \cdot B)\)?

  1. \(\overline{A} \cdot C + B \cdot C\)

  2. \(A \cdot \overline{B} \cdot C + \overline{A} \cdot B \cdot \overline{C}\)

  3. \(A \oplus B \oplus C\)

  4. \(C\)

  5. 0 (False)

(b)

Read the overbars carefully: in the source there are two bars over \(A\), three over \(B\) and one over \(C\) in the first factor, which parses as \(\overline{\overline{A \cdot \overline{B}} \cdot C}\).

Take the inner term first and push the complement in with De Morgan:

\[\overline{A \cdot \overline{B}} = \overline{A} + B\]

so the first factor is

\[\overline{(\overline{A} + B) \cdot C} = \overline{(\overline{A}+B)} + \overline{C} = A\overline{B} + \overline{C}\]

Now multiply out against the second factor:

\[(A\overline{B} + \overline{C})(C + \overline{A}B) = A\overline{B}C + A\overline{B}\,\overline{A}B + \overline{C}C + \overline{C}\,\overline{A}B\]

The middle two products each contain a variable and its complement, so they vanish, leaving

\[A \cdot \overline{B} \cdot C + \overline{A} \cdot B \cdot \overline{C}\]

which is option (b). See boolean-algebra.

Q7 — Gate circuit for an expression

Which of the following logic circuits is an implementation of the function \(A + \overline{B} \cdot \overline{C} + D\)?

Figure 287: Question 7’s five candidate circuits, (a) to (e), each taking A, B, C and D.

  1. — the circuit labelled (a) above

  2. — the circuit labelled (b) above

  3. — the circuit labelled (c) above

  4. — the circuit labelled (d) above

  5. — the circuit labelled (e) above

(b)

The target has one product term, \(\overline{B} \cdot \overline{C}\), ORed with the two bare literals \(A\) and \(D\). A NOR gate is that product term — \(\overline{B + C} = \overline{B} \cdot \overline{C}\) by De Morgan — so the circuit wanted is a 2-input NOR on B and C feeding a 3-input OR along with A and D. That is (b).

The others:

    1. uses a NAND instead of a NOR, giving \(A + \overline{B \cdot C} + D = A + \overline{B} + \overline{C} + D\). Same shape, wrong gate.
    1. gives \((A + \overline{B}) \cdot (\overline{C} + D)\) — a product of sums, not the right function (it is 0 when \(A=1, C=1, D=0\), where the target is 1).
    1. gives \((A \oplus \overline{B}\,\overline{C}) \oplus D\); XOR is not OR, so e.g. \(A = D = 1\) gives 0 rather than 1.
    1. gives \((A + \overline{B}) \cdot \overline{C} + D\), which is 0 when \(A = 1, C = 1, D = 0\).

See logic-gates.

Q8 — Expression to truth table

Which of the following truth tables is equivalent to the function \(X = A \cdot \left(B \cdot \overline{C} + \overline{A \cdot (B + \overline{C})}\right)\)?

A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1
A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 1
A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 1
1 1 1 0
A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 0
  1. None of the above

(d)

The whole expression is ANDed with \(A\), so \(X = 0\) whenever \(A = 0\) — that kills the top half of every table and is true of all four candidates, so it does not discriminate. Set \(A = 1\) and simplify:

\[A \cdot (B + \overline{C}) = B + \overline{C} \qquad\text{so}\qquad \overline{A \cdot (B + \overline{C})} = \overline{B + \overline{C}} = \overline{B} \cdot C\]

and therefore

\[X = B\overline{C} + \overline{B}C = B \oplus C\]

So the function is \(X = A \cdot (B \oplus C)\): 1 exactly when \(A = 1\) and \(B\) and \(C\) differ. That is rows \(101\) and \(110\), and nothing else:

A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 0

which is table (d). Table (c) differs only in the \(101\) row and (b) only in the \(111\) row, so read those two rows carefully. See boolean-algebra.

Q9 — Timing diagram to expression

Which of the following expressions is NOT equivalent to the following timing diagram?

Figure 288: Question 9’s timing diagram: A, B and C step through all eight input combinations (A is the fastest-changing signal) and X is the resulting output.

  1. \(\overline{B} \cdot (\overline{A} + \overline{C}) + A \cdot B \cdot C\)

  2. \(\overline{B} \cdot \overline{C} + C \cdot (\overline{A} \oplus B)\)

  3. \(\overline{A} \cdot \overline{B} + A \cdot (\overline{B} \oplus C)\)

  4. \(\overline{A} \cdot \overline{B} + \overline{C} \cdot \overline{B} + A \cdot (B \oplus \overline{C})\)

  5. None of the above

(e) — every one of (a) to (d) is equivalent, so none of them is the odd one out.

First read the diagram off. A toggles every slot, B every two, C every four, so the nine intervals shown are the eight input combinations in binary counting order (with A as the least significant bit) plus a repeat of the first. X is high over slots 0, 1, 4 and 7:

A B C X
0 0 0 1
1 0 0 1
0 1 0 0
1 1 0 0
0 0 1 1
1 0 1 0
0 1 1 0
1 1 1 1

So \(X = 1\) on exactly \(\{\overline{A}\,\overline{B}\,\overline{C},\; A\overline{B}\,\overline{C},\; \overline{A}\,\overline{B}C,\; ABC\}\) — writing the combinations as \(ABC\) bit strings, \(\{000, 100, 001, 111\}\).

Now test each option on that set:

    1. \(\overline{B}(\overline{A} + \overline{C})\) covers \(\overline{A}\,\overline{B}\) (that is 000 and 001) and \(\overline{B}\,\overline{C}\) (000 and 100); adding \(ABC\) (111) gives \(\{000, 001, 100, 111\}\). ✓
    1. \(\overline{B}\,\overline{C}\) covers \(\{000, 100\}\). \(\overline{A} \oplus B\) is 1 when \(A = B = 0\) or \(A = B = 1\), so \(C(\overline{A} \oplus B)\) covers \(\{001, 111\}\). Union is the same set. ✓
    1. \(\overline{A}\,\overline{B}\) covers \(\{000, 001\}\). \(\overline{B} \oplus C\) is 1 when \(B = 0, C = 0\) or \(B = 1, C = 1\), so \(A(\overline{B} \oplus C)\) covers \(\{100, 111\}\). ✓
    1. \(\overline{A}\,\overline{B}\) gives \(\{000, 001\}\), \(\overline{C}\,\overline{B}\) gives \(\{000, 100\}\), and \(B \oplus \overline{C}\) is 1 when \(B = 0, C = 0\) or \(B = 1, C = 1\), so \(A(B \oplus \overline{C})\) gives \(\{100, 111\}\). ✓

All four match, so the answer is (e). See timing-diagrams.

Q10 — Sum-of-products form

Which of the following is a sum-of-products expression equivalent to \((\overline{A} + B) \cdot \overline{(C + B \cdot D)}\)?

  1. \(\overline{A} \cdot \overline{B} \cdot \overline{C} + \overline{A} \cdot \overline{C} \cdot \overline{D} + B \cdot \overline{C} \cdot \overline{D}\)

  2. \(\overline{A} \cdot \overline{B} \cdot \overline{C} + \overline{A} \cdot \overline{C} \cdot \overline{D}\)

  3. \(\overline{A} \cdot \overline{C} + B \cdot \overline{C} + \overline{A} \cdot \overline{B} \cdot \overline{D}\)

  4. \(\overline{A} \cdot \overline{C} \cdot \overline{BD} + B \cdot \overline{C} \cdot \overline{BD}\)

  5. None of the above

(a)

Push the complement in with De Morgan, twice:

\[\overline{C + B \cdot D} = \overline{C} \cdot \overline{BD} = \overline{C} \cdot (\overline{B} + \overline{D})\]

so the whole expression is

\[(\overline{A} + B) \cdot \overline{C} \cdot (\overline{B} + \overline{D})\]

Multiply out the two sums:

\[(\overline{A} + B)(\overline{B} + \overline{D}) = \overline{A}\,\overline{B} + \overline{A}\,\overline{D} + B\overline{B} + B\overline{D} = \overline{A}\,\overline{B} + \overline{A}\,\overline{D} + B\overline{D}\]

since \(B\overline{B} = 0\). Distributing the \(\overline{C}\) gives

\[\overline{A}\,\overline{B}\,\overline{C} + \overline{A}\,\overline{C}\,\overline{D} + B\,\overline{C}\,\overline{D}\]

which is (a). Option (d) is also algebraically equal to the original, but it is not a sum of products — \(\overline{BD}\) is a complemented product, not a literal — and the question asks specifically for sum-of-products form. Option (b) is (a) with the last term missing, so it drops the case \(A = 1, B = 1, C = 0, D = 0\). See boolean-algebra.

Q11 — 3-input NOR from 2-input NANDs

Which of the following implements a 3-input NOR gate \((\overline{A + B + C})\) using only 2-input NAND gates?

Figure 289: Question 11’s five candidate NAND-only networks, (a) to (e). A NAND with its two inputs tied together — shown by the junction dot on its input lead — acts as an inverter.

  1. — the circuit labelled (a) above

  2. — the circuit labelled (b) above

  3. — the circuit labelled (c) above

  4. — the circuit labelled (d) above

  5. — the circuit labelled (e) above

(e)

Start from De Morgan: \(\overline{A + B + C} = \overline{A} \cdot \overline{B} \cdot \overline{C}\). So the network must invert all three inputs, AND them together, and a 2-input NAND only gives the AND complemented, so each AND needs a following inverter. A NAND with both inputs tied is an inverter, which is what the junction dots on the input leads mean.

Trace each option:

  • (a) \(\text{NAND}(A,B)\), inverted, gives \(A \cdot B\); NANDed with \(C\) that is \(\overline{A \cdot B \cdot C}\) — a 3-input NAND, not a NOR.
  • (b) Inverts A, B and C, then \(\text{NAND}(\overline{A}, \overline{B}) = A + B\), then NANDs that with \(\overline{C}\): \(\overline{(A+B) \cdot \overline{C}}\). Wrong.
  • (c) Same as (b) but with an inverter after the first NAND, so the second NAND sees \(\overline{A}\,\overline{B}\) and \(\overline{C}\) and gives \(\overline{\overline{A}\,\overline{B}\,\overline{C}} = A + B + C\). That is a 3-input OR — one inversion short.
  • (d) \(A \cdot B\) NANDed with \(\overline{C}\), i.e. \(\overline{A B \overline{C}}\). Wrong.
  • (e) Exactly (c) with a seventh NAND wired as an inverter on the output, turning \(A + B + C\) into \(\overline{A + B + C}\). ✓

Counting gates is a quick filter: any correct answer needs at least three inverters (one per input), one NAND, one inverter to undo it, one more NAND and a final inverter — seven gates. Only (e) has seven. See logic-gates.

Q12 — D flip-flop timing

Consider the flip-flop circuit shown below and the associated CLK and output (Q) signals. Which timing diagram shows input (A) values over time which would have resulted in the given output (Q)?

Figure 290: Question 12’s given CLK and Q waveforms and the D flip-flop they belong to, with the five candidate A waveforms (a) to (e) below.

  1. — the A waveform labelled (a) above

  2. — the A waveform labelled (b) above

  3. — the A waveform labelled (c) above

  4. — the A waveform labelled (d) above

  5. — the A waveform labelled (e) above

(c)

The flip-flop is a plain D type with a triangle and no bubble on the clock input, so it samples D on each rising edge and holds in between. There are four rising edges in the CLK waveform. Reading Q against them:

Rising edge Q before Q after So A must have been
1st 0 1 1
2nd 1 0 0
3rd 0 0 0
4th 0 1 1

So the required A is 1, 0, 0, 1 at the four rising edges, and completely unconstrained everywhere else — which is why several candidates look plausible until you check all four.

    1. is 1 at edge 1 but has risen again before edge 2, so Q would stay 1. ✗
    1. is right for the first three edges but has fallen again before edge 4, so Q would stay 0. ✗
    1. is 1, 0, 0, 1 at the four edges. ✓
    1. is 1, 0, then back to 1 before edge 3, which would set Q high a clock early. ✗
    1. is 1, 0, then 1 before edge 3 — same failure as (d). ✗

See flip-flops-and-latches and timing-diagrams.

Q13 — Two’s complement addition

What is the result of adding the 7-bit two’s complement numbers 1011001 and 0101111?

  1. 0000000

  2. 0001000

  3. 1110110

  4. 1110111

  5. None of the above

(b)

Add the bit patterns as unsigned binary and throw away the carry out of the top bit, which is what two’s complement addition always is:

   1111111   <- carries
   1011001
 + 0101111
 ---------
  10001000

Discarding the ninth-column carry leaves \(0001000\).

Check in decimal: \(1011001\) has its sign bit set, so it is \(89 - 128 = -39\); \(0101111 = 47\). Then \(-39 + 47 = 8 = 0001000\). The signs of the operands differ, so overflow is impossible and the result is trustworthy. See binary-number-representations.

Q14 — Overflow detection

Which of the following operations will result in overflow in 5-bit two’s complement arithmetic?

  1. 01000 + 01000

  2. 11111 + 00001

  3. 11000 + 01111

  4. 11101 + 11010

  5. None of the above

(a)

5-bit two’s complement covers \(-16\) to \(+15\) (see Q3), and overflow means the true sum falls outside that. Adding operands of opposite sign can never overflow, so only (a) and (d) are even candidates.

    1. \(8 + 8 = 16\), which is one past the top of the range. The bit sum is \(01000 + 01000 = 10000\), which reads as \(-16\) — two positives producing a negative, the classic overflow signature. ✓
    1. \(-1 + 1 = 0\); signs differ, no overflow.
    1. \(-8 + 15 = 7\); signs differ, no overflow.
    1. \(-3 + (-6) = -9\), comfortably inside the range. The bit sum is \(11101 + 11010 = 110111\); dropping the carry gives \(10111 = -9\). Two negatives giving a negative, so no overflow.

See binary-number-representations.

Q15 — Overflow and result sign

Consider the binary addition operation 110111 + 101001. Which of the following statements is true if the numbers are interpreted as two’s complement?

  1. The result is negative and no overflow occurs

  2. The result should be negative but overflow occurs

  3. The result is positive and no overflow occurs

  4. The result is positive but overflow occurs

  5. The result is zero

(a)

These are 6-bit numbers, so the representable range is \(-32\) to \(+31\).

\[110111_2 = 55 \;\to\; 55 - 64 = -9 \qquad 101001_2 = 41 \;\to\; 41 - 64 = -23\]

and \(-9 + (-23) = -32\), which is exactly the most negative representable value — inside the range, so no overflow.

The bit-level addition agrees:

   111111   <- carries
   110111
 + 101001
 --------
  1100000

Dropping the carry out leaves \(100000 = -32\). Both operands are negative and the result is negative, so no overflow; equivalently, the carry into the sign column and the carry out of it are both 1, and overflow is their XOR, which is 0. See binary-number-representations.

Q16 — Multiplexer as function generator

Consider the following multiplexer. What must the inputs A,B,C,D be so that the multiplexer implements the function \(X = S_1 \oplus S_0 \oplus (G \cdot S_1)\)?

Figure 291: Question 16’s 4-to-1 multiplexer, with data inputs A, B, C and D on lines 0 to 3 and select inputs S1 and S0.

  1. A= 1    B= 1    C= \(G\)    D= \(\overline{G}\)

  2. A= 0    B= 1    C= \(G\)    D= \(\overline{G}\)

  3. A= 1    B= 0    C= \(\overline{G}\)    D= \(G\)

  4. A= 0    B= 1    C= \(\overline{G}\)    D= \(G\)

  5. None of the above

(d)

A multiplexer routes input \(i\) to the output when the select lines hold \(i\), so each data input is just the value the function takes for that one combination of \(S_1 S_0\). Evaluate \(X = S_1 \oplus S_0 \oplus (G \cdot S_1)\) four times:

\(S_1 S_0\) selected input \(X\)
00 A \(0 \oplus 0 \oplus (G \cdot 0) = 0\)
01 B \(0 \oplus 1 \oplus (G \cdot 0) = 1\)
10 C \(1 \oplus 0 \oplus (G \cdot 1) = 1 \oplus G = \overline{G}\)
11 D \(1 \oplus 1 \oplus (G \cdot 1) = 0 \oplus G = G\)

So A = 0, B = 1, C = \(\overline{G}\), D = \(G\), which is (d). The \(G \cdot S_1\) term is what makes only the bottom half depend on \(G\), and the \(S_1 \oplus S_0\) part is what flips \(\overline{G}\) into \(G\) between lines 2 and 3. See combinational-logic-blocks.

Q17 — Multiplexer output function

Consider the following multiplexer. Which of the following statements is TRUE? (+ indicates the logical OR operation)

Figure 292: Question 17’s 8-to-1 multiplexer, with the eight data lines hard-wired to constants and the select inputs S2, S1 and S0 driven by A, B and C.

  1. If A is 0, \(X = \overline{B + C}\)      If A is 1, \(X = B \cdot C\)

  2. If A is 0, \(X = \overline{B \cdot C}\)      If A is 1, \(X = \overline{B + C}\)

  3. If A is 0, \(X = B + C\)      If A is 1, \(X = \overline{B \cdot C}\)

  4. If A is 0, \(X = \overline{B \cdot C}\)      If A is 1, \(X = B + C\)

  5. None of the above

(d)

The select lines are \(S_2 S_1 S_0 = A\,B\,C\), so the selected line number is \(4A + 2B + C\) and A picks which half of the input list is in play.

With \(A = 0\) the mux can only reach lines 0–3, whose values are 1, 1, 1, 0:

B C line X
0 0 0 1
0 1 1 1
1 0 2 1
1 1 3 0

which is 0 only when both B and C are 1 — that is \(X = \overline{B \cdot C}\).

With \(A = 1\) it reaches lines 4–7, whose values are 0, 1, 1, 1:

B C line X
0 0 4 0
0 1 5 1
1 0 6 1
1 1 7 1

which is 1 whenever either is 1 — that is \(X = B + C\).

So (d). This is the standard trick of using an \(n\)-select mux as a lookup table for an \(n\)-variable function. See combinational-logic-blocks.

Q18 — Multiplexer-fed flip-flops

Consider the circuit below. If A1 is 0 and A0 is 1, what are the values of Q1 and Q0 after five rising clock edges if FN is 0 for two rising clock edges then 1 for three rising clock edges?

Figure 293: Question 18’s circuit: two D flip-flops, each fed by a 2-to-1 multiplexer selected by FN — line 0 loads A1/A0, line 1 cross-couples the two Q outputs.

  1. Q1 = 0      Q0 = 0

  2. Q1 = 0      Q0 = 1

  3. Q1 = 1      Q0 = 0

  4. Q1 = 1      Q0 = 1

  5. Insufficient information is provided to determine the values

(c)

Read the multiplexers first. Each flip-flop’s D input comes from its own mux, and both muxes are selected by FN:

  • FN = 0 selects line 0 on both, so \(D_1 = A_1\) and \(D_0 = A_0\) — a parallel load.
  • FN = 1 selects line 1, and the wiring is crossed: \(D_1\) comes from \(Q_0\) and \(D_0\) comes from \(Q_1\) — a swap.

Now clock it. Note that the two load cycles wipe out whatever the flip-flops held beforehand, which is why (e) is not needed.

Edge FN \(D_1 D_0\) \(Q_1 Q_0\) after
start — — unknown
1 0 \(A_1 A_0 = 01\) 0 1
2 0 \(A_1 A_0 = 01\) 0 1
3 1 \(Q_0 Q_1 = 10\) 1 0
4 1 \(Q_0 Q_1 = 01\) 0 1
5 1 \(Q_0 Q_1 = 10\) 1 0

After five edges, \(Q_1 = 1\) and \(Q_0 = 0\). The swap has odd parity — three swaps is the same as one — which is the whole point of the question. See flip-flops-and-latches and combinational-logic-blocks.

Q19 — Synchronous counter trace

What sequence will the following synchronous counter count through, if it starts at Q1Q0 = 00?

Figure 294: Question 19’s synchronous counter. The OR gate is drawn mirrored, with its output pointing left back to D1; it takes Q0 and Q1-bar. The NAND takes Q0 and Q1 and drives D0.

  1. Q1Q0: 00 → 01 → 11 → 10 → 11 → …

  2. Q1Q0: 00 → 10 → 00 → …

  3. Q1Q0: 00 → 11 → 01 → 11 → …

  4. Q1Q0: 00 → 11 → 10 → 01 → 00 → …

  5. Q1Q0: 00 → 11 → 10 → 01 → 11 → …

(e)

Read the two next-state equations off the schematic. The OR gate is drawn mirrored — its output points left, back to the D input of the left flip-flop — and its two inputs are the \(Q_0\) rail running along the top and the \(\overline{Q}\) of the left flip-flop. The NAND takes the same \(Q_0\) rail and \(Q_1\), and drives the right flip-flop’s D. So

\[D_1 = Q_0 + \overline{Q_1} \qquad\qquad D_0 = \overline{Q_1 \cdot Q_0}\]

Both flip-flops share the clock, so evaluate both from the current state each cycle:

\(Q_1 Q_0\) \(D_1 = Q_0 + \overline{Q_1}\) \(D_0 = \overline{Q_1 Q_0}\) next
00 \(0 + 1 = 1\) \(\overline{0} = 1\) 11
11 \(1 + 0 = 1\) \(\overline{1} = 0\) 10
10 \(0 + 0 = 0\) \(\overline{0} = 1\) 01
01 \(1 + 1 = 1\) \(\overline{0} = 1\) 11

So from 00 the machine runs 00 → 11 → 10 → 01 → 11 → 10 → 01 → …, settling into a three-state loop and never returning to 00. That is (e); (d) has the same first four states but wrongly loops back to 00. See [counters].

Q20 — Flip-flops for a count sequence

What is the minimum number of flip-flops needed to implement a state machine which counts through the sequence 00000→00001→00011→11000→00001→… ?

  1. 2

  2. 3

  3. 4

  4. 5

  5. 32

(a)

The five-bit patterns are the machine’s outputs, not necessarily its state encoding. Count the distinct patterns: 00000, 00001, 00011, 11000 — four of them, since the 00001 at the end of the sequence is the same state it was the first time round (the machine loops 00001 → 00011 → 11000 → 00001 forever after leaving 00000).

Four states need \(\lceil \log_2 4 \rceil = 2\) flip-flops, with combinational output logic decoding the two state bits into the five output bits. So (a).

Option (d) is the trap: five flip-flops is what you would need if you insisted on storing the output pattern directly in the register, which is the natural but not the minimal design. See state-machines.

Q21 — State diagram to state table

Consider the state diagram below.

Figure 295: Question 21’s Moore state diagram. Each bubble shows the state name above and its X,Y outputs below; the S4 to S8 transition carries no label, so it is taken for either value of A.

Which of the following is an equivalent state table?

Current State Input (A) Next State Outputs (X,Y)
S1 0 S1 01
S1 1 S2 01
S2 0 S2 00
S2 1 S4 00
S4 0 S8 10
S4 1 S8 10
S8 0 S16 11
S8 1 S1 11
S16 0 S1 01
S16 1 S2 01
Current State Input (A) Next State Outputs (X,Y)
S1 0 S1 01
S1 1 S2 01
S2 0 S2 00
S2 1 S4 00
S4 0 S8 10
S4 1 S8 10
S8 0 S1 11
S8 1 S16 11
S16 0 S1 01
S16 1 S2 01
Current State Next State (A=0) Next State (A=1) Outputs (X,Y)
S1 S1 S2 01
S2 S2 S4 00
S4 S4 S8 10
S8 S16 S1 11
S16 S1 S2 01
Current State Next State (A=0) Next State (A=1) Outputs (X,Y)
S1 S1 S2 01
S2 S2 S4 00
S4 S8 S8 01
S8 S16 S1 11
S16 S1 S2 01
  1. None of the above

(a)

Read the ten transitions off the diagram. The outputs sit inside the bubbles, so this is a Moore machine and the output column depends only on the current state:

From On To
S1 \(\overline{A}\) S1 (self-loop)
S1 A S2
S2 \(\overline{A}\) S2 (self-loop)
S2 A S4
S4 (unlabelled) S8
S8 \(\overline{A}\) S16
S8 A S1
S16 \(\overline{A}\) S1
S16 A S2

The S4 → S8 arrow carries no label, which means it is taken regardless of A — S4 has no other outgoing arrow, so it must be unconditional. Table (a) matches all of this line for line.

The other three each break in exactly one place:

    1. swaps S8’s two destinations: it sends S8 to S1 on A = 0 and to S16 on A = 1, the reverse of the diagram.
    1. gives S4 a self-loop on A = 0 instead of the unconditional move to S8.
    1. has the right transitions but prints S4’s outputs as 01 when the bubble says 10.

See state-machines.

Q22 — State encoding width

What is the minimum number of flip-flops needed to build the state machine shown in question 21?

  1. 1

  2. 2

  3. 3

  4. 4

  5. 5

(c)

The diagram in Q21 has five states — S1, S2, S4, S8 and S16. A register of \(n\) flip-flops distinguishes \(2^n\) states, so \(n = \lceil \log_2 5 \rceil = 3\): two flip-flops would only cover four states, and three cover eight, leaving three encodings unused.

The state names are a distraction — they look like one-hot codes (1, 2, 4, 8, 16), and one-hot encoding really would need five flip-flops, which is option (e). But the question asks for the minimum, and nothing forces one-hot. See state-machines.

Q23 — Tracing a state sequence

Consider the state machine represented by the state diagram in question 21 above. What sequence of states is traversed if the machine starts in state S1 and A goes through the sequence 110011 (i.e. two 1’s followed by two 0’s followed by two 1’s)?

  1. S1→S1→S2→S4→S8→S16→S2

  2. S1→S2→S4→S8→S1→S2→S4

  3. S1→S2→S2→S2→S4→S8→S16

  4. S1→S2→S4→S8→S16→S2→S4

  5. None of the above

(d)

Six input values means six transitions, so the answer is a list of seven states starting at S1. Walk the table from Q21:

Step A From To
1 1 S1 S2
2 1 S2 S4
3 0 S4 S8  (unconditional)
4 0 S8 S16
5 1 S16 S2
6 1 S2 S4

giving S1→S2→S4→S8→S16→S2→S4, which is (d).

The step that separates the options is step 3: S4 moves on to S8 whatever A is, so the first 0 does not hold the machine still. Option (b) makes the mistake of sending S8 to S1 on A = 0, and (c) parks the machine in S2. See state-machines.

Q24 — ALU function select

Consider the ALU bit slice below.

Figure 296: Question 24’s ALU bit slice. ENA and ENB/INVB condition A and B into two internal rails; five logic blocks, the carry in, the right shift in and the full adder sum feed the eight inputs of a multiplexer selected by F2 F1 F0. The conditioned A rail is also the Right Shift Out.

For an ALU made up of 8 of the bit slices above, which of the following control input settings will result in the ALU output being \(A \oplus B\) ? (The “Right Shift In” control input refers to that for the most significant bit; the “Carry in” control input refers to that for the least significant bit.)

  1. ENA = 1, ENB = 1, INVB = 0, F2 = 0, F1 = 0, F0 = 0, Right Shift In = 0, Carry in = 0

  2. ENA = 1, ENB = 1, INVB = 1, F2 = 0, F1 = 0, F0 = 0, Right Shift In = 0, Carry in = 0

  3. ENA = 1, ENB = 1, INVB = 1, F2 = 0, F1 = 1, F0 = 0, Right Shift In = 0, Carry in = 0

  4. ENA = 1, ENB = 1, INVB = 0, F2 = 1, F1 = 1, F0 = 1, Right Shift In = 0, Carry in = 0

  5. None of the above

(e)

First read the slice. Two internal rails carry the conditioned inputs:

\[X = A \cdot \text{ENA} \qquad\qquad Y = (B \cdot \text{ENB}) \oplus \text{INVB}\]

and the \(X\) rail is also what leaves as Right Shift Out. Eight things feed the multiplexer, which is selected by \(F_2 F_1 F_0\) as a 3-bit number:

\(F_2 F_1 F_0\) mux line Output
000 0 \(\overline{X + Y}\)
001 1 \(X \cdot Y\)
010 2 \(X + Y\)
011 3 \(\overline{X \cdot Y}\)
100 4 Carry In
101 5 \(\overline{X}\)
110 6 Right Shift In
111 7 \(X \oplus Y \oplus C_{in}\) (the adder sum)

and the carry out is \(X \cdot Y + F_2 F_1 F_0 \cdot (X \oplus Y) \cdot C_{in}\) — an ordinary full-adder carry, with the propagate term switched off unless the adder is actually selected.

Now the options. All four set ENA = ENB = 1, so \(X = A\) throughout.

    1. INVB = 0 gives \(Y = B\), and \(F = 000\) selects NOR: \(\overline{A + B}\). ✗
    1. INVB = 1 gives \(Y = \overline{B}\), and \(F = 000\) selects NOR: \(\overline{A + \overline{B}} = \overline{A} \cdot B\). ✗
    1. \(Y = \overline{B}\) and \(F = 010\) selects OR: \(A + \overline{B}\). ✗
    1. \(Y = B\) and \(F = 111\) selects the adder. The per-bit output is \(A_i \oplus B_i \oplus C_i\), which looks like XOR, and for bit 0 (where Carry in = 0 is given) it is. But \(F = 111\) also switches the carry chain on, so bit 0 sends \(A_0 \cdot B_0\) into bit 1, bit 1 sends its carry into bit 2, and so on. What the 8-bit ALU computes is \(A + B\), not \(A \oplus B\); the two agree only when no pair of bits is 1 together. ✗

No mux line produces XOR without the carry chain, and there is no way to select the sum while stopping the carries, so the answer is (e).

Check this one. The intended answer may well be (d) if the examiner meant only the per-slice sum expression \(A \oplus B \oplus C_{in}\) — but in an 8-bit ALU the carries into slices 1–7 are not zero, so (d) really computes addition. The parenthetical note that Carry in refers only to the least significant bit is the hint that the ripple is meant to be taken seriously.

See arithmetic-logic-unit.

Q25 — ALU constant generation

For the ALU in Q24, which of the following control input settings will NOT result in the ALU output being the constant value –1 (negative one)?

  1. ENA = 0, ENB = 0, INVB = 0, F2 = 0, F1 = 0, F0 = 0, Right Shift In = 1, Carry in = 0

  2. ENA = 0, ENB = 0, INVB = 1, F2 = 0, F1 = 1, F0 = 0, Right Shift In = 0, Carry in = 1

  3. ENA = 1, ENB = 0, INVB = 0, F2 = 0, F1 = 1, F0 = 1, Right Shift In = 0, Carry in = 1

  4. ENA = 1, ENB = 1, INVB = 1, F2 = 0, F1 = 1, F0 = 1, Right Shift In = 0, Carry in = 0

  5. ENA = 0, ENB = 1, INVB = 1, F2 = 1, F1 = 0, F0 = 1, Right Shift In = 0, Carry in = 1

(d)

In two’s complement, \(-1\) is all ones, so the question is really: which setting fails to force every bit of the output to 1 regardless of the data in A and B? Use the rails and the mux table from Q24: \(X = A \cdot \text{ENA}\) and \(Y = (B \cdot \text{ENB}) \oplus \text{INVB}\).

    1. ENA = ENB = INVB = 0, so \(X = 0\) and \(Y = 0\). \(F = 000\) selects NOR: \(\overline{0 + 0} = 1\) on every bit. ✓ gives \(-1\).
    1. \(X = 0\); ENB = 0 with INVB = 1 gives \(Y = 0 \oplus 1 = 1\). \(F = 010\) selects OR: \(0 + 1 = 1\). ✓
    1. ENA = 1 so \(X = A\); ENB = 0, INVB = 0 so \(Y = 0\). \(F = 011\) selects NAND: \(\overline{A \cdot 0} = \overline{0} = 1\) whatever A is. ✓
    1. ENA = ENB = 1 and INVB = 1, so \(X = A\) and \(Y = \overline{B}\). \(F = 011\) selects NAND: \(\overline{A \cdot \overline{B}}\), which is 0 whenever \(A = 1\) and \(B = 0\). Data-dependent, so not the constant \(-1\). ✗
    1. ENA = 0 so \(X = 0\); \(F = 101\) selects \(\overline{X} = \overline{0} = 1\). ✓

Only (d) leaves the output depending on the data, so it is the one that will not give \(-1\).

The general lesson is the point of the question: ENA and ENB let the ALU force a rail to a constant 0, and INVB (or the NOT/NAND/NOR lines) turns that into a constant 1 across the whole word. That is how an ALU with no dedicated constant hardware still manages to produce \(-1\), and by extension \(B - 1\) and \(B - A\). See arithmetic-logic-unit.

Your score

Reload the page to clear your answers.

Sample Mid-semester Exam #6

This is UQ’s sixth sample mid-semester paper for csse2010 — CSSE2010/CSSE7201 Introduction to Computer Systems — printed for the Semester One mid-semester examinations of 2020, St Lucia campus. It runs for 60 minutes with 10 minutes of reading time, is an open book examination (calculators limited to the Casio FX82 series or a UQ-approved labelled model, no electronic aids), and is answered entirely on a supplied True/False and Multiple Choice answer sheet. There are 25 questions, each worth one mark; incorrect, missing or multiple answers score zero, so there is no penalty for guessing.

The paper covers the first five weeks of the course: number representations and binary arithmetic, logic gates and Boolean simplification, combinational blocks, flip-flops and counters, state machines, and the ALU bit slice.

WarningAnswers are derived, not official

The source paper ships without an answer key, so every answer below was worked out during transcription rather than taken from UQ. Each one shows its reasoning so it can be checked rather than trusted; anything uncertain is flagged. Treat a disagreement between your working and the answer here as a reason to check both.

How to use this

Two ways. Timed run — do all 25 questions in 60 minutes without looking at anything; on the website the answers are collapsed, so they stay hidden until you click them. Targeted practice — use the index table below to pick out only the questions for one week or one concept, and read the working straight away.

Note that in the PDF build every answer is expanded and visible, so the site version is the one to practise from.

Question index

Q Topic Week Concept notes
1 Two’s complement of a negative 1 binary-number-representations · week1-lab-number-representations
2 Octal to hexadecimal width 1 binary-number-representations · week1-lab-number-representations
3 Excess-32 range 1 binary-number-representations · week1-lab-number-representations
4 Ones’ to two’s complement 1 binary-number-representations · week1-lab-number-representations
5 Reading a two-gate circuit 1 logic-gates
6 Simplifying a product of sums 2 boolean-algebra
7 Circuit for an XOR expression 1 logic-gates
8 Truth table for an expression 2 boolean-algebra
9 Timing diagram to expression 2 timing-diagrams
10 Simplifying a complemented product 2 boolean-algebra
11 3-input NOR from 2-input NORs 2 boolean-algebra
12 D flip-flop input from its output 3 flip-flops-and-latches
13 Two’s complement addition 2 binary-number-representations
14 Detecting overflow 2 binary-number-representations
15 Overflow on an addition 2 binary-number-representations
16 Multiplexer as function generator 2 combinational-logic-blocks
17 Reading an 8-input multiplexer 2 combinational-logic-blocks
18 Load/shift register trace 3 shift-registers
19 Synchronous counter sequence 4 [counters]
20 Flip-flops for an output sequence 4 state-machines
21 State diagram to state table 4 state-machines
22 Flip-flops for a state machine 4 state-machines
23 Tracing a state machine 4 state-machines
24 ALU control settings 5 arithmetic-logic-unit
25 ALU control settings 5 arithmetic-logic-unit

Q1 — Two’s complement of a negative

What is \(-73_{10}\) expressed in 8-bit two’s complement format?

  1. 01001000

  2. 01001001

  3. 10110110

  4. 10110111

  5. 11001001

(d)

Start from the magnitude. \(73 = 64 + 8 + 1\), so

\[73_{10} = 0100\,1001_2\]

which is option (b) — the positive value, offered as a distractor. Negate it the usual way (see binary-number-representations): invert every bit, then add one.

\[\overline{0100\,1001} = 1011\,0110 \qquad 1011\,0110 + 1 = 1011\,0111\]

So \(-73_{10} = 1011\,0111_2\). Option (c) is the one’s complement — the inversion without the \(+1\) — which is the usual slip here.

Checking: \(1011\,0111\) as two’s complement is \(-128 + 32 + 16 + 4 + 2 + 1 = -128 + 55 = -73\). ✓

Q2 — Octal to hexadecimal width

What is the minimum number of hexadecimal digits needed to represent the octal number 120105?

  1. 4

  2. 5

  3. 6

  4. 18

  5. None of the above

(a)

Go through binary, since one octal digit is exactly three bits and one hex digit is exactly four:

\[120105_8 = \underbrace{001}_{1}\ \underbrace{010}_{2}\ \underbrace{000}_{0}\ \underbrace{001}_{1}\ \underbrace{000}_{0}\ \underbrace{101}_{5}\]

That is 18 bits, but the leading two are zeros, so the value is really 16 significant bits. Regroup from the right in fours:

\[1010\ 0000\ 0100\ 0101_2 = \mathrm{A}045_{16}\]

Four hex digits. Option (d), 18, is the bit count rather than the digit count; option (c), 6, is the octal digit count.

Checking in decimal: \(120105_8 = 8^5 + 2\cdot 8^4 + 8^2 + 5 = 32768 + 8192 + 64 + 5 = 41029\), and \(\mathrm{A}045_{16} = 10 \cdot 4096 + 4 \cdot 16 + 5 = 41029\). ✓

Q3 — Excess-32 range

A 6-bit number in excess-32 format can represent integers from

  1. –32 to 31

  2. –31 to 32

  3. –32 to 32

  4. 0 to 63

  5. None of the above

(a)

In excess-\(K\) (biased) notation the stored bit pattern is read as an ordinary unsigned number and then \(K\) is subtracted to get the value it represents:

\[\text{value} = \text{unsigned}(b) - K\]

Six bits give unsigned values \(0\) to \(2^6 - 1 = 63\), and here \(K = 32\), so the representable values run from \(0 - 32 = -32\) up to \(63 - 32 = 31\).

Option (d) is the unsigned range before the bias is applied; option (c) has 65 values, which six bits cannot hold.

Q4 — Ones’ to two’s complement

How can any n-bit ones’ complement number be converted to an (n+1)-bit two’s complement representation?

  1. By prepending 0 and adding 1

  2. By prepending the sign-bit, flipping all the bits and then adding 1

  3. By prepending the sign-bit

  4. By prepending the sign-bit and adding 1

  5. By prepending the sign-bit and adding the value of the sign-bit

(e)

The word any is what the question turns on: the recipe has to work for positive and negative values alike, and the four wrong options each work for only one sign.

Write the \(n\)-bit ones’ complement number as sign bit \(s\) over the remaining bits, whose unsigned value is \(M\). Its value is

\[V = -s\,(2^{n-1} - 1) + M\]

because a negative ones’ complement number is the bitwise inverse of its magnitude. Now prepend a copy of the sign bit, giving an \((n+1)\)-bit pattern \(s\,s\,b_{n-2}\ldots b_0\), and read it as two’s complement:

\[-s\,2^{n} + s\,2^{n-1} + M = -s\,2^{n-1} + M\]

That is short of \(V\) by exactly \(s\). Adding \(s\) — “the value of the sign-bit” — closes the gap:

\[-s\,2^{n-1} + M + s = -s\,(2^{n-1} - 1) + M = V\]

Concretely, with \(n = 4\):

Ones’ complement Value Prepend sign Add \(s\) Two’s complement value
0011 \(+3\) 00011 \(+0\) = 00011 \(+3\) ✓
1010 \(-5\) 11010 \(+1\) = 11011 \(-5\) ✓
1000 \(-7\) 11000 \(+1\) = 11001 \(-7\) ✓
1111 \(-0\) 11111 \(+1\) = 00000 \(0\) ✓

Figure 297: The first two rows of that table drawn out. Prepending the sign bit is the same move in both cases, but it lands in the right place only for the positive value: reading the widened negative pattern as two’s complement gives \(-6\), one too low, because ones’ complement’s top bit is worth \(-(2^{n-1}-1)\) while two’s complement’s is worth \(-2^{n-1}\). The correction is exactly that difference of 1, and it is needed precisely when the sign bit is 1 — which is what makes ‘add the value of the sign-bit’ the only option that works for both signs. The prepended bit is shaded.

Option (d) adds 1 unconditionally, which is right for negatives and one too many for positives (it would turn \(+3\) into \(+4\)); option (c) never adds, which is right for positives and one too few for negatives.

See week1-lab-number-representations for the two formats’ bit-position weights side by side, which is where the difference of 1 comes from.

Q5 — Reading a two-gate circuit

What function is implemented by the following circuit?

Figure 298: Question 5’s circuit: a two-input NOR on A and B, whose output is one input of a two-input NAND with C.

  1. \(\overline{A . B . C}\)

  2. \(\overline{\overline{A + B} . C}\)

  3. \(\overline{\overline{A} + \overline{B} . C}\)

  4. \(\overline{(\overline{A} + \overline{B}) . C}\)

  5. \(\overline{\overline{A . B} + C}\)

(b)

Read the circuit gate by gate. The first gate is an OR body with an output bubble — a NOR — so its output is

\[\overline{A + B}\]

That feeds one input of an AND body with an output bubble — a NAND — whose other input is \(C\). A NAND of \(P\) and \(C\) is \(\overline{P \cdot C}\), so the whole circuit is

\[\overline{\overline{A + B} \cdot C}\]

which is option (b) exactly as printed.

The distractors are all plausible readings of a two-gate circuit: option (d) is what you get if the first gate is misread as a NAND (\(\overline{A \cdot B} = \overline{A} + \overline{B}\) into a NAND with \(C\)), and option (e) swaps the two gate types over entirely. Options (a) and (c) do not have the right shape at all — (a) is a single three-input NAND, (c) has the outer bar covering an OR rather than the AND with \(C\).

Q6 — Simplifying a product of sums

Which of the following logic functions is identical to \(\overline{(A+B).(\overline{A}+B+C)}\)?

  1. \(\overline{B}\)

  2. \(\overline{A}.\overline{B}.\overline{C}\)

  3. \(\overline{A}.\overline{B} + \overline{B}.\overline{C}\)

  4. \(\overline{A}+\overline{B}+\overline{C}\)

  5. None of the above

(c)

Simplify what is inside the bar first, by multiplying the two sums out:

\[ \begin{aligned} (A+B)(\overline{A}+B+C) &= A\overline{A} + AB + AC + \overline{A}B + BB + BC \\ &= 0 + AB + AC + \overline{A}B + B + BC \\ &= B\,(A + \overline{A} + 1 + C) + AC \\ &= B + AC \end{aligned} \]

Everything with a \(B\) in it collapses into the bare \(B\) term, leaving \(AC\) beside it. Now complement, using De Morgan twice (see boolean-algebra):

\[ \begin{aligned} \overline{B + AC} &= \overline{B} \cdot \overline{AC} \\ &= \overline{B}\,(\overline{A} + \overline{C}) \\ &= \overline{A}\,\overline{B} + \overline{B}\,\overline{C} \end{aligned} \]

which is option (c).

Spot-check a row: \(A=1, B=0, C=0\) gives \((1+0)(0+0+0) = 1 \cdot 0 = 0\), so the complement is 1; and \(\overline{A}\overline{B} + \overline{B}\overline{C} = 0 \cdot 1 + 1 \cdot 1 = 1\). ✓

Q7 — Circuit for an XOR expression

Which of the following logic circuits is an implementation of the function \((\overline{A.B}) \oplus (\overline{C+D})\)?

Figure 299: Question 7’s five candidate circuits, laid out as one figure: (a), (b) and (c) on the top row, (d) and (e) on the bottom. Small circles on a gate’s inputs in (b) are inversion bubbles; a circle on the output is the usual NAND/NOR/XNOR bubble.

(e)

The trap here is that the target expression complements both halves before the XOR, and XOR is blind to complementing both of its inputs:

\[\overline{P} \oplus \overline{Q} = \overline{P}\,Q + P\,\overline{Q} \dots\]

more directly, \(\overline{P} \oplus \overline{Q} = (\overline{P} \oplus Q) \oplus 1 \oplus 1 \cdots\) — easiest just to check the four rows:

\(P\) \(Q\) \(P \oplus Q\) \(\overline{P} \oplus \overline{Q}\)
0 0 0 0
0 1 1 1
1 0 1 1
1 1 0 0

They are the same column. So with \(P = A.B\) and \(Q = C+D\),

\[(\overline{A.B}) \oplus (\overline{C+D}) = (A.B) \oplus (C+D)\]

and the circuit that draws that literally is (e): a plain AND on \(A,B\), a plain OR on \(C,D\), and an XOR joining them.

Checking the others, in the same \(P \oplus Q\) terms:

  • (a) has no XOR at all — it is \(C + \overline{A.B} + D\).
  • (b) is \((\overline{A}.\overline{B}) \oplus (\overline{C}+\overline{D}) = \overline{A+B} \oplus \overline{C.D} = (A+B) \oplus (C.D)\) — the AND and OR the wrong way round.
  • (c) is \(\overline{\overline{A.B} \oplus \overline{C \oplus D}}\) — an XNOR of an XNOR, nothing like it.
  • (d) is \(\overline{A+B} \oplus \overline{C.D}\), the same function as (b), which is another reason neither can be the answer.

Q8 — Truth table for an expression

Which of the following truth tables is equivalent to the function

\[X = \left(\overline{\overline{A} . \overline{C}}\right) . \left(\overline{\overline{A} . B} + \overline{C} . B\right)\]

A B C X
0 0 0 0
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1
A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 0
1 1 0 1
1 1 1 0
A B C X
0 0 0 0
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1
A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1
  1. None of the above

(a)

Simplify before tabulating — it is much less error-prone than eight substitutions. De Morgan turns both complemented products into sums:

\[\overline{\overline{A}\,\overline{C}} = A + C \qquad\qquad \overline{\overline{A}\,B} = A + \overline{B}\]

so

\[X = (A + C)\,\bigl(A + \overline{B} + \overline{C}\,B\bigr)\]

The second bracket absorbs: \(\overline{B} + B\,\overline{C} = \overline{B} + \overline{C}\) (the classic \(P + \overline{P}Q = P + Q\) with \(P = \overline{B}\), \(Q = \overline{C}\)). That leaves

\[X = (A + C)\,(A + \overline{B} + \overline{C})\]

Multiply out. Every term containing \(A\) collapses into a single \(A\), and \(C \cdot \overline{C} = 0\):

\[X = A + C\,\overline{B} + C\,\overline{C} = A + \overline{B}\,C\]

Tabulating \(A + \overline{B}C\):

A B C \(\overline{B}C\) X
0 0 0 0 0
0 0 1 1 1
0 1 0 0 0
0 1 1 0 0
1 0 0 0 1
1 0 1 1 1
1 1 0 0 1
1 1 1 0 1

That is 0, 1, 0, 0, 1, 1, 1, 1 — option (a). Option (d) is just \(X = A\), i.e. what you get if you drop the \(\overline{B}C\) term.

Q9 — Timing diagram to expression

Which of the following expressions is NOT equivalent to the following timing diagram?

Figure 300: Question 9’s timing diagram. A toggles every interval, B every two and C every four, so the eight intervals cover all eight combinations of A, B and C once each; X is the function being described. All four signals return to 0 in the tail at the right.

  1. \(A.\overline{C} + B.\overline{C} + \overline{A}.B + \overline{A}.C\)

  2. \((A \oplus C) + \overline{A}.B.\overline{C}\)

  3. \(A.\overline{B}.\overline{C} + B.\overline{C} + \overline{A}.C\)

  4. \(A.\overline{B}.\overline{C} + A.B.\overline{C} + \overline{A}.B + \overline{A}.\overline{B}.C\)

  5. All of the above are equivalent to the timing diagram

(e)

First read the diagram off as a truth table. \(A\) toggles every interval, \(B\) every second interval and \(C\) every fourth, so the eight intervals are the eight combinations of \(ABC\) — but note they arrive in the order \(C B A\) counting up, not \(ABC\). Reading the level of each track in each interval:

Interval A B C X
1 0 0 0 0
2 1 0 0 1
3 0 1 0 1
4 1 1 0 1
5 0 0 1 1
6 1 0 1 0
7 0 1 1 1
8 1 1 1 0

Sorted into \(ABC\) order, \(X\) is 1 for \(ABC \in \{001, 010, 011, 100, 110\}\) and 0 for \(\{000, 101, 111\}\). Grouping the minterms:

\[X = \overline{A}\,\overline{B}\,C + \overline{A}B\overline{C} + \overline{A}BC + A\overline{B}\,\overline{C} + AB\overline{C} = \overline{A}B + A\overline{C} + \overline{A}\,\overline{B}C = \overline{A}B + \overline{A}C + A\overline{C}\]

Now evaluate all four options on those eight rows. Writing the \(X\) column as the string \(X_{000}X_{001}\ldots X_{111}\), the diagram gives 01111010, and:

Option \(X\) column Matches?
(a) \(A\overline{C} + B\overline{C} + \overline{A}B + \overline{A}C\) 01111010 yes
(b) \((A \oplus C) + \overline{A}B\overline{C}\) 01111010 yes
(c) \(A\overline{B}\,\overline{C} + B\overline{C} + \overline{A}C\) 01111010 yes
(d) \(A\overline{B}\,\overline{C} + AB\overline{C} + \overline{A}B + \overline{A}\,\overline{B}C\) 01111010 yes

All four are the same function, written four ways: (d) is the raw minterm list with two terms merged, (a) adds the redundant \(B\overline{C}\) cover, (c) splits \(A\overline{C}\) against \(B\), and (b) notices that everything except \(\overline{A}B\overline{C}\) is exactly \(A \ne C\). So nothing on the list fails, and the answer is (e).

Worth noticing as a sanity check: since (a)–(d) are all identical to each other, the answer could only ever be “all of them” or “none of them”, and there is no “none” option — so the diagram had to match.

Q10 — Simplifying a complemented product

Which of the following logic functions is identical to \(\overline{(A + \overline{C}).(\overline{A} + B.\overline{C})}\) ?

  1. \(A.\overline{B} + C\)

  2. \(\overline{A}.B + C\)

  3. \(A.\overline{B} + A.C\)

  4. \(\overline{A}.C + B.\overline{C}\)

  5. None of the above

(a)

Multiply out the inside first:

\[ \begin{aligned} (A + \overline{C})(\overline{A} + B\overline{C}) &= A\overline{A} + AB\overline{C} + \overline{A}\,\overline{C} + B\overline{C}\,\overline{C} \\ &= 0 + AB\overline{C} + \overline{A}\,\overline{C} + B\overline{C} \\ &= \overline{A}\,\overline{C} + B\overline{C} \end{aligned} \]

\(AB\overline{C}\) is absorbed by \(B\overline{C}\) (it is a subset of it), and \(\overline{C}\,\overline{C} = \overline{C}\). Factor:

\[= \overline{C}\,(\overline{A} + B)\]

Now complement with De Morgan (see boolean-algebra):

\[\overline{\overline{C}\,(\overline{A}+B)} = C + \overline{\overline{A}+B} = C + A\overline{B}\]

which is option (a).

Spot-check: \(A=1, B=0, C=0\) gives \((1+1)(0+0) = 0\) inside, so the answer should be 1; and \(A\overline{B} + C = 1 \cdot 1 + 0 = 1\). ✓ And \(A=0,B=1,C=0\) gives \((0+1)(1+1) = 1\) inside, so 0 out; \(A\overline{B}+C = 0 + 0 = 0\). ✓

Q11 — 3-input NOR from 2-input NORs

Which of the following circuits implements a 3 input NOR gate (\(\overline{A + B + C}\)) using only 2-input NOR gates?

Figure 301: Question 11’s five candidate NOR-only circuits. A gate whose two inputs are tied together (the bracket and dot on its left) is being used as an inverter.

(b)

Writing \(\text{NOR}(P,Q) = \overline{P+Q}\), note that a NOR with both inputs tied together is an inverter: \(\text{NOR}(P,P) = \overline{P}\). That is the only extra trick needed.

The target is \(\overline{A+B+C}\). The obvious first move — NOR \(A\) with \(B\), then NOR that with \(C\) — does not work, because the first NOR has already complemented \(A+B\):

\[\text{NOR}(\text{NOR}(A,B),\,C) = \overline{\overline{A+B} + C} = (A+B)\,\overline{C}\]

which is option (a). The fix is to un-complement in between. Take \(\text{NOR}(A,B) = \overline{A+B}\), feed it into a tied-input NOR to get \(A+B\) back, then NOR that with \(C\):

\[\text{NOR}\bigl(\overline{\overline{A+B}},\,C\bigr) = \overline{(A+B) + C} = \overline{A+B+C}\]

Three gates, and that is exactly the arrangement drawn in (b).

The others:

  • (c) inverts all three inputs first, then NORs \(\overline{A}\) with \(\overline{B}\) to get \(\overline{\overline{A}+\overline{B}} = A.B\), then NORs that with \(\overline{C}\): \(\overline{A.B + \overline{C}}\).
  • (d) is (b) with \(C\) inverted on the way in, giving \(\overline{A + B + \overline{C}}\).
  • (e) is (c) with an extra inverter after the \(A.B\) stage, giving \(\overline{\overline{A.B} + \overline{C}} = A.B.C\).

Only (b) leaves all three variables uncomplemented under one bar.

Q12 — D flip-flop input from its output

Consider the flip-flop circuit shown below and the associated CLK and output (Q) signals. Which timing diagram shows input (A) values over time which would have resulted in the given output (Q).

Figure 302: Question 12’s flip-flop and waveforms: the D flip-flop symbol, then the given CLK and Q traces, then the five candidate A traces (a)–(e) on the same time axis.

  1. A

  2. A

  3. A

  4. A

  5. A

(c)

The symbol has a triangle on the clock input and no bubble, so it is a positive-edge-triggered D flip-flop: \(Q\) takes the value \(D\) had immediately before each rising CLK edge, and does nothing at any other time (see flip-flops-and-latches).

There are four rising edges. Reading \(Q\) across them:

Rising edge \(Q\) before \(Q\) after So \(A\) must have been
1 1 0 0
2 0 1 1
3 1 1 1
4 1 0 0

The requirement is therefore \(A = 0, 1, 1, 0\) at the four edges, and what \(A\) does between edges is irrelevant. Checking each candidate at the four edge times:

edge 1 edge 2 edge 3 edge 4
required 0 1 1 0
(a) 0 1 0 1 fails at edge 3
(b) 0 1 0 0 fails at edge 3
(c) 0 1 1 0 matches
(d) 0 1 0 0 fails at edge 3
(e) 0 1 1 1 fails at edge 4

So (c). It is the busy, rapidly toggling trace, which is the point of the question: a flip-flop ignores everything except the value present at the clock edge, so a wildly active input can produce a placid output.

Trace (e) is the near miss — it is right for the first three edges and only falls too late, just after the fourth rising edge, so \(Q\) would have stayed high.

Q13 — Two’s complement addition

What is the result of adding the 6-bit two’s complement numbers 101010 and 110011?

  1. 011100

  2. 011101

  3. 011110

  4. 111011

  5. None of the above

(b)

Add the bit patterns as if they were unsigned — two’s complement addition is ordinary binary addition — and throw away any carry out of the top bit:

\[ \begin{array}{r} \texttt{\ 101010} \\ + \texttt{110011} \\ \hline \texttt{1011101} \end{array} \]

Column by column from the right: \(0+1 = 1\); \(1+1 = 10\) so write 0 carry 1; \(0+0+1 = 1\); \(1+0 = 1\); \(0+1 = 1\); \(1+1 = 10\) so write 0 and carry 1 out of the word. Six bits of result: 011101.

As a decimal check, \(101010 = -32+8+2 = -22\) and \(110011 = -32+16+2+1 = -13\), so the true sum is \(-35\). That is outside the 6-bit two’s complement range \([-32, 31]\), so this addition overflows — two negatives producing a positive-looking \(011101 = +29\), and indeed \(-35 + 64 = 29\). The question only asks what the adder produces, though, and that is 011101.

Option (d) is what you get by ORing the two operands rather than adding them.

Q14 — Detecting overflow

Which of the following operations will result in an overflow in 5-bit two’s complement arithmetic?

  1. 01010 – 01110

  2. 10111 – 11100

  3. 11010 – 00111

  4. 01011 + 11111

  5. None of the above

(e)

Two’s complement overflow can only happen when the two values being added have the same sign and the result comes out with the other sign. A subtraction \(P - Q\) is really \(P + (-Q)\), so what matters is the sign of \(P\) and of \(-Q\). The 5-bit range is \([-16, +15]\).

Take each in turn, converting to decimal and also checking the sign rule.

(a) 01010 – 01110 \(= 10 - 14 = -4\). Adding a positive to a negative can never overflow, and \(-4\) is in range. In binary: \(01010 + 10010 = 11100 = -4\). ✓ No overflow.

(b) 10111 – 11100 \(= -9 - (-4) = -5\). Again opposite signs going into the adder (\(-9\) and \(+4\)). \(10111 + 00100 = 11011 = -5\). ✓ No overflow.

(c) 11010 – 00111 \(= -6 - 7 = -13\). Here both addends are negative (\(-6\) and \(-7\)), so overflow is possible — but \(-13\) still fits in \([-16,15]\). \(11010 + 11001 = 1\,10011\); discard the carry out and \(10011 = -13\), which is negative as expected. ✓ No overflow.

(d) 01011 + 11111 \(= 11 + (-1) = 10\). Opposite signs. \(01011 + 11111 = 1\,01010\); discard the carry and \(01010 = 10\). ✓ No overflow.

Note that (d) is a good reminder that a carry out is not overflow — the carry out of the top bit here is 1, yet the answer is perfectly correct. None of the four overflows, so the answer is (e).

Q15 — Overflow on an addition

Consider the binary addition operation 010111 + 001001. Which of the following statements is true if the numbers are interpreted as two’s complement?

  1. The result is positive and no overflow occurs

  2. The result should be positive but overflow occurs

  3. The result is negative and no overflow occurs

  4. The result should be negative but overflow occurs

  5. The result is zero

(b)

Both operands have a 0 in the sign position, so both are positive: \(010111 = 16+4+2+1 = 23\) and \(001001 = 8+1 = 9\). The true sum is \(32\), and the 6-bit two’s complement range is only \([-32, +31]\) — so \(32\) does not fit.

Doing the addition:

\[ \begin{array}{r} \texttt{010111} \\ + \texttt{001001} \\ \hline \texttt{100000} \end{array} \]

The result pattern \(100000\) has a 1 in the sign position, so the adder is reporting \(-32\). Two positives producing a negative is the definition of two’s complement overflow, which makes (b) the right description: the result should have been positive, but overflow occurred.

Note that no carry came out of the word here, which again shows carry-out and overflow are different things (compare Q14).

Q16 — Multiplexer as function generator

Consider the following multiplexer. What must the inputs A,B,C,D be so that the multiplexer implements the function \(X = S_1 \oplus S_0 \oplus \overline{G}\) ?

Figure 303: Question 16’s 4-to-1 multiplexer: data inputs A, B, C and D on lines 0 to 3, select inputs S1 and S0, output X.

  1. A= 0 B= 1 C= 1 D= 0

  2. A= \(G\) B= \(\overline{G}\) C= \(\overline{G}\) D= \(G\)

  3. A= \(\overline{G}\) B= 1 C= 1 D= 1

  4. A= \(\overline{G}\) B= \(G\) C= \(G\) D= \(\overline{G}\)

  5. None of the above

(d)

A multiplexer used this way is a lookup table: whatever is wired to input \(n\) appears at \(X\) whenever the select lines hold \(n\). So for each of the four values of \(S_1 S_0\), evaluate the required function and wire that expression to the matching input (see combinational-logic-blocks).

\[X = S_1 \oplus S_0 \oplus \overline{G}\]

\(S_1 S_0\) Input selected \(S_1 \oplus S_0\) Required \(X = (S_1 \oplus S_0) \oplus \overline{G}\)
00 A 0 \(0 \oplus \overline{G} = \overline{G}\)
01 B 1 \(1 \oplus \overline{G} = G\)
10 C 1 \(1 \oplus \overline{G} = G\)
11 D 0 \(0 \oplus \overline{G} = \overline{G}\)

using \(0 \oplus P = P\) and \(1 \oplus P = \overline{P}\). So \(A = \overline{G}\), \(B = G\), \(C = G\), \(D = \overline{G}\) — option (d).

Option (b) is the same pattern inverted throughout, which is what you get by dropping the bar on \(G\) in the target function.

Q17 — Reading an 8-input multiplexer

Consider the following multiplexer. Which of the following statements is TRUE? (+ indicates the logical OR operation)

Figure 304: Question 17’s 8-to-1 multiplexer. The eight data inputs are hardwired to the constants 1, 0, 1, 0, 1, 1, 1, 0 on lines 0 to 7; the select inputs S2, S1 and S0 are driven by A, B and C respectively.

  1. If A is 0, \(X = \overline{C}\) If A is 1, \(X = \overline{B + C}\)

  2. If A is 0, \(X = \overline{B}\) If A is 1, \(X = \overline{B + C}\)

  3. If A is 0, \(X = \overline{C}\) If A is 1, \(X = \overline{B.C}\)

  4. If A is 0, \(X = C\) If A is 1, \(X = \overline{B.C}\)

  5. None of the above

(c)

\(A\) is the most significant select bit, so it splits the eight constants into two halves: \(A = 0\) selects among inputs 0–3, \(A = 1\) among inputs 4–7. Within each half, \(BC\) picks the row.

With \(A = 0\) the four constants are, for \(BC = 00, 01, 10, 11\):

\(B\) \(C\) Input Value
0 0 0 1
0 1 1 0
1 0 2 1
1 1 3 0

\(X\) is 1 exactly when \(C = 0\), whatever \(B\) does — so \(X = \overline{C}\).

With \(A = 1\) the constants are:

\(B\) \(C\) Input Value
0 0 4 1
0 1 5 1
1 0 6 1
1 1 7 0

\(X\) is 0 only when \(B\) and \(C\) are both 1 — so \(X = \overline{B.C}\).

Both halves match option (c). Option (a) has the right first half but reads the second half as a NOR rather than a NAND, which would need the last three constants to be 0 rather than just the last one.

Q18 — Load/shift register trace

Consider the circuit below. If A1 is 1 and A0 is 0, what are the values of Q1 and Q0 after four rising clock edges if FN is 0 for one rising clock edge then 1 for three rising clock edges?

Figure 305: Question 18’s circuit: two D flip-flops, each fed by a 2-to-1 multiplexer under the shared select FN. On FN = 0 the flip-flops load A1 and A0; on FN = 1 the left one takes Q0-bar and the right one takes Q1, which makes the pair a twisted-ring counter.

  1. \(Q_1 = 0\) \(Q_0 = 0\)

  2. \(Q_1 = 0\) \(Q_0 = 1\)

  3. \(Q_1 = 1\) \(Q_0 = 0\)

  4. \(Q_1 = 1\) \(Q_0 = 1\)

  5. Insufficient information is provided to determine the values

(a)

First read the two multiplexers. Both have FN on their select input, so:

\[D_1 = \begin{cases} A_1 & \text{FN} = 0 \\ \overline{Q_0} & \text{FN} = 1\end{cases} \qquad\qquad D_0 = \begin{cases} A_0 & \text{FN} = 0 \\ Q_1 & \text{FN} = 1\end{cases}\]

The \(\overline{Q_0}\) feedback is the long run along the bottom, from the right flip-flop’s \(\overline{Q}\) pin all the way back to the left multiplexer’s input 1. With FN = 1 this is a twisted-ring (Johnson) counter: the pair shifts left-to-right and the complement of the last bit re-enters at the front.

Now trace the four edges. Both flip-flops are clocked together, so both take their new values from the old \(Q\) values at each edge.

Edge FN \(D_1\) \(D_0\) New \(Q_1 Q_0\)
— — — — starting value unknown
1 0 \(A_1 = 1\) \(A_0 = 0\) 1 0
2 1 \(\overline{Q_0} = \overline{0} = 1\) \(Q_1 = 1\) 1 1
3 1 \(\overline{Q_0} = \overline{1} = 0\) \(Q_1 = 1\) 0 1
4 1 \(\overline{Q_0} = \overline{1} = 0\) \(Q_1 = 0\) 0 0

After four edges \(Q_1 = 0\) and \(Q_0 = 0\) — option (a).

Option (e) is the trap: the starting contents of the flip-flops genuinely are unknown, but the first edge is a parallel load that overwrites both of them, so the answer is fully determined from edge 1 onwards.

Q19 — Synchronous counter sequence

What sequence will the following synchronous counter count through, if it starts at Q1Q0 = 00?

Figure 306: Question 19’s synchronous counter. Both gates see the same two feedback lines: Q0 comes back along the upper run and Q1 along the lower one, so D1 is the XOR of the two state bits and D0 their NAND. The source paper draws the XOR mirrored, with its output on the left; it is drawn the usual way round here, and the connections are unchanged.

  1. Q1Q0: 00 → 10 → 01 → 11 → 00 → …

  2. Q1Q0: 00 → 10 → 11 → 00 → …

  3. Q1Q0: 00 → 01 → 10 → 11 → 00 → …

  4. Q1Q0: 00 → 01 → 11 → 00 → …

  5. None of the above

(d)

Read the excitation equations off the circuit. Both gates take the same pair of inputs — the two state bits fed back — so:

\[D_1 = Q_1 \oplus Q_0 \qquad\qquad D_0 = \overline{Q_1 . Q_0}\]

Now build the state table (see [counters]):

\(Q_1 Q_0\) \(D_1 = Q_1 \oplus Q_0\) \(D_0 = \overline{Q_1 Q_0}\) Next state
00 0 1 01
01 1 1 11
11 0 0 00
10 1 1 11

Starting from 00 the counter runs

\[00 \rightarrow 01 \rightarrow 11 \rightarrow 00 \rightarrow \dots\]

a three-state cycle, which is option (d). State 10 is outside the cycle; it drops into 11 on the next edge and joins the loop, so the counter is self-correcting.

The near miss is (b), \(00 \rightarrow 10 \rightarrow 11 \rightarrow 00\): the same three-state cycle with the two bits swapped over, which is what you get if \(Q_1\) and \(Q_0\) are mixed up when reading the circuit.

Q20 — Flip-flops for an output sequence

What is the minimum number of flip-flops needed to implement a state machine whose outputs always go through the sequence: 00001→00011→00111→11000→10000→00000→00001→… ?

  1. 3

  2. 4

  3. 5

  4. 6

  5. None of the above

(a)

The outputs are five bits wide, which is the distractor — it tempts option (c), one flip-flop per output bit. But the flip-flops hold the state, not the output; the output is whatever combinational logic decodes from the state (see state-machines).

So count the states. The sequence visits

\[00001,\ 00011,\ 00111,\ 11000,\ 10000,\ 00000\]

and then repeats. All six patterns are distinct, and because the machine “always” goes through this sequence, each output value identifies exactly one state — six states.

\(N\) flip-flops give \(2^N\) states, so we need the smallest \(N\) with \(2^N \ge 6\):

\[2^2 = 4 < 6 \qquad 2^3 = 8 \ge 6\]

Three flip-flops, option (a). The five output bits are then produced by output logic decoding those three, which is exactly the Moore-machine structure.

Q21 — State diagram to state table

Consider the state diagram below.

Figure 307: Question 21’s state diagram. Each state shows its name above the rule and its X,Y outputs below; the single input is A, and every state has one arrow for A and one for A-bar.

Which of the following is an equivalent state table?

Current State Input (A) Next State Outputs (X,Y)
S0 0 S0 01
S0 1 S1 01
S1 0 S2 01
S1 1 S1 01
S2 0 S3 00
S2 1 S4 00
S3 0 S0 10
S3 1 S1 10
S4 0 S0 11
S4 1 S3 11
Current State Input (A) Next State Outputs (X,Y)
S0 0 S0 01
S0 1 S1 01
S1 0 S2 01
S1 1 S2 01
S2 0 S3 00
S2 1 S4 00
S3 0 S0 10
S3 1 S1 10
S4 0 S3 11
S4 1 S0 11
Current State Next State (A=0) Next State (A=1) Outputs (X,Y)
S0 S0 S1 01
S1 S2 S1 01
S2 S3 S4 00
S3 S0 S1 10
S4 S3 S0 11
Current State Next State (A=0) Next State (A=1) Outputs (X,Y)
S0 S0 S1 01
S1 S2 S1 10
S2 S3 S4 00
S3 S0 S1 10
S4 S3 S0 11
  1. None of the above

(c)

Read the ten arrows off the diagram, remembering that a label \(A\) means the transition is taken when \(A = 1\) and \(\overline{A}\) when \(A = 0\), and that this is a Moore machine so the outputs belong to the state, not the transition (see state-machines).

Current state \(A = 0\) \(A = 1\) Outputs \(X,Y\)
\(S_0\) \(S_0\) (self loop, \(\overline{A}\)) \(S_1\) (top arc, \(A\)) 01
\(S_1\) \(S_2\) (down the right, \(\overline{A}\)) \(S_1\) (self loop, \(A\)) 01
\(S_2\) \(S_3\) (\(\overline{A}\)) \(S_4\) (bottom arc, \(A\)) 00
\(S_3\) \(S_0\) (\(\overline{A}\)) \(S_1\) (\(A\)) 10
\(S_4\) \(S_3\) (\(\overline{A}\)) \(S_0\) (\(A\)) 11

Each state has exactly two arrows leaving it, one per value of \(A\), so the diagram is complete. This table is option (c) exactly.

The other three each differ in one place:

  • (a) swaps \(S_4\)’s two destinations — it has \(S_4 \to S_0\) on \(A=0\) and \(S_4 \to S_3\) on \(A=1\), the wrong way round.
  • (b) sends \(S_1\) to \(S_2\) on both input values, losing \(S_1\)’s self loop.
  • (d) is (c) with \(S_1\)’s output changed from 01 to 10.

Q22 — Flip-flops for a state machine

What is the minimum number of flip-flops needed to build the state machine shown in question 21?

  1. 1

  2. 2

  3. 3

  4. 4

  5. 5

(c)

The diagram in Q21 has five states: \(S_0\), \(S_1\), \(S_2\), \(S_3\) and \(S_4\). With \(N\) flip-flops there are \(2^N\) possible codes, so we need the smallest \(N\) with \(2^N \ge 5\):

\[2^2 = 4 < 5 \qquad 2^3 = 8 \ge 5\]

so three flip-flops, with three of the eight codes left unused.

Option (e), five, is the one-hot encoding — legal and often convenient, but not the minimum. Option (b), two, would only stretch to four states.

Q23 — Tracing a state machine

Consider the state machine represented by the state diagram in question 21 above. What sequence of states is traversed if the machine starts in state S3 and A goes through the sequence 10001 (i.e. 1 followed by three 0s followed by a 1)?

  1. S3→S0→S0→S0→S0→S1

  2. S3→S1→S2→S3→S0→S1

  3. S3→S1→S2→S4→S3→S1

  4. S3→S0→S1→S2→S3→S1

  5. None of the above

(b)

Walk the table from Q21 one input bit at a time, starting in \(S_3\):

Step Current state \(A\) Next state
1 \(S_3\) 1 \(S_1\)
2 \(S_1\) 0 \(S_2\)
3 \(S_2\) 0 \(S_3\)
4 \(S_3\) 0 \(S_0\)
5 \(S_0\) 1 \(S_1\)

so the machine visits

\[S_3 \rightarrow S_1 \rightarrow S_2 \rightarrow S_3 \rightarrow S_0 \rightarrow S_1\]

which is option (b).

Option (c) goes wrong at step 3 by taking \(S_2\)’s \(A = 1\) arrow instead of its \(A = 0\) one; option (a) takes \(S_3\)’s \(\overline{A}\) arrow on the first bit, which is 1.

Q24 — ALU control settings

Consider the ALU bit slice below.

Figure 308: Question 24’s ALU bit slice. The ENA/INVA and ENB/INVB gates on the left condition A and B into the two internal rails X and Y; the five logic blocks and the full adder all work from those rails, and the 8-input multiplexer under F2 F1 F0 picks which result reaches the output. Right Shift Out is the X rail itself. The carry logic at the bottom points downwards as in the source: an AND on the two rails for the generate term, and a five-input AND for the propagate term, whose extra three inputs are F2, F1 and F0 — so a carry only travels when the adder is the selected function.

For an ALU made up of 8 of the bit slices above, which of the following control input settings will NOT result in the ALU output being \(\overline{B}\) ? (The “Right Shift In” control input refers to that for the most significant bit; the “Carry in” control input refers to that for the least significant bit.)

  1. ENA=0 INVA=0 ENB=1 INVB=0 F2=0 F1=1 F0=1 Right Shift In=0 Carry in=0

  2. ENA=0 INVA=0 ENB=1 INVB=1 F2=0 F1=0 F0=1 Right Shift In=0 Carry in=0

  3. ENA=0 INVA=1 ENB=1 INVB=0 F2=0 F1=1 F0=0 Right Shift In=0 Carry in=0

  4. ENA=0 INVA=1 ENB=1 INVB=1 F2=0 F1=0 F0=0 Right Shift In=0 Carry in=0

  5. All of the above result in the ALU output being \(\overline{B}\)

(e)

Start by writing down what the slice actually computes. The conditioning gates give the two internal rails

\[X = (A \cdot \text{ENA}) \oplus \text{INVA} \qquad\qquad Y = (B \cdot \text{ENB}) \oplus \text{INVB}\]

and the multiplexer, selected by \(F_2 F_1 F_0\) read as a binary number, chooses between:

\(F_2 F_1 F_0\) Input Output
000 0 \(X . Y\)
001 1 \(X + Y\)
010 2 \(\overline{X . Y}\)
011 3 \(\overline{X + Y}\)
100 4 Carry In
101 5 \(\overline{X}\)
110 6 Right Shift In
111 7 \(X \oplus Y \oplus C_{in}\) (the adder’s sum)

Every option here has \(\text{ENB} = 1\), so \(Y\) is \(B\) or \(\overline{B}\); and every option has \(\text{ENA} = 0\), so \(X\) is a constant — 0 when \(\text{INVA} = 0\) and 1 when \(\text{INVA} = 1\). Feeding a constant into one side of a two-input gate is exactly how this ALU turns a logic block into a pass-through or an inverter.

(a) \(X = 0\), \(Y = B\), select 011 = NOR: \(\overline{0 + B} = \overline{B}\). ✓

(b) \(X = 0\), \(Y = \overline{B}\), select 001 = OR: \(0 + \overline{B} = \overline{B}\). ✓

(c) \(X = 1\), \(Y = B\), select 010 = NAND: \(\overline{1 \cdot B} = \overline{B}\). ✓

(d) \(X = 1\), \(Y = \overline{B}\), select 000 = AND: \(1 \cdot \overline{B} = \overline{B}\). ✓

All four produce \(\overline{B}\), so the answer is (e). Note that none of them selects input 4, 6 or 7, which is why the Right Shift In and Carry In settings never matter — they are there to make the options look longer than they are.

The paper does not label which select pin of the multiplexer carries which weight, but two things settle it. First, the figure routes \(F_2\) to the leftmost of the three select pins and \(F_0\) to the rightmost, and everywhere else in this paper — the multiplexers in Q16 and Q17 — the leftmost select pin is the most significant (\(S_1\) then \(S_0\); \(S_2\) then \(S_1\) then \(S_0\)). Second, reading \(F_2\) as the most significant bit is what makes all four settings land on \(\overline{B}\); any other assignment sends at least one of them to the Carry In or Right Shift In input instead, which would give a question with three wrong answers rather than none.

The four settings are the four ways of getting \(\overline{B}\) out of the four two-input logic blocks: complement the function (NOR/NAND) or complement the operand (\(\text{INVB}\)), and choose the constant that makes the other input transparent.

Q25 — ALU control settings

For the ALU in question 24, which of the following control input settings will result in the ALU output being \(A.B\)?

  1. ENA=1 INVA=0 ENB=1 INVB=0 F2=0 F1=0 F0=1 Right Shift In=0 Carry in=0

  2. ENA=1 INVA=0 ENB=1 INVB=0 F2=0 F1=1 F0=0 Right Shift In=0 Carry in=0

  3. ENA=1 INVA=0 ENB=1 INVB=0 F2=0 F1=1 F0=1 Right Shift In=0 Carry in=0

  4. ENA=1 INVA=1 ENB=1 INVB=1 F2=0 F1=1 F0=1 Right Shift In=0 Carry in=0

  5. None of the above

(d)

Same slice as Q24, same two steps: work out \(X\) and \(Y\), then look up what \(F_2 F_1 F_0\) selects.

(a) \(\text{ENA} = \text{ENB} = 1\) with both INV inputs 0, so \(X = A\) and \(Y = B\). Select \(001 = 1\) is the OR block: \(A + B\). ✗

(b) Same \(X\) and \(Y\); select \(010 = 2\) is the NAND block: \(\overline{A.B}\). ✗ — the complement of what is wanted, which is the tempting wrong answer.

(c) Same \(X\) and \(Y\); select \(011 = 3\) is the NOR block: \(\overline{A + B}\). ✗

(d) \(\text{INVA} = \text{INVB} = 1\), so \(X = \overline{A}\) and \(Y = \overline{B}\); select \(011 = 3\) is the NOR block:

\[\overline{\overline{A} + \overline{B}} = \overline{\overline{A}} \cdot \overline{\overline{B}} = A . B\]

by De Morgan. ✓

So (d) — the slice has no AND-with-uncomplemented-inputs route selected here, and instead reaches \(A.B\) the De Morgan way, by inverting both operands into a NOR. Selecting the AND block (000) with \(\text{INVA} = \text{INVB} = 0\) would have done it directly, but that combination is not on the list.

Your score

Reload the page to clear your answers.

Device Pinouts

Pin numbers for the 74-series logic chips and IO board used in circuit-schematics. All quad 2-input gate chips (74HCT00, 08, 32, 86) share the same pin layout — only the gate function differs.

Source: CSSE2010/CSSE7201 Device Pinouts and Symbols (Blackboard, v4). This is the whole parts list: every gate chip in it is 2-input (plus the hex inverter), so a design needing a 3-or-more-input gate has to be built up from 2-input ones. There is no 3-input AND/OR/NAND in the kit.

The source sheet gives up to three things per device, and they are not interchangeable:

Column What it is Where it is used
Device pinout the physical package: which signal is on which numbered pin wiring the breadboard; checking a schematic’s pin numbers
Logic diagram symbol the hardware-independent shape logic-gates and logic diagrams
Circuit schematic symbol the shape plus device ID, device type and pin numbers circuit-schematics

Power and ground

Power and ground connections for devices are shown separately from the gate pins on a schematic, once per device type. The symbols below are also what you use to tie a device input directly to logic low or logic high.

Figure 309: The four non-gate symbols. Logic high and logic low are a bare 1 or 0 on a logic diagram, and a VCC bar or a ground symbol (either of the two accepted forms) on a circuit schematic. The IO board input and output symbols are the same pentagon; the difference is that an input’s wire leaves the point and an output’s wire arrives at the flat back.

Quad 2-input gates (74HCT00 / 08 / 32 / 86)

Figure 310: The 14-pin DIP pinout, drawn for the 74HCT00 but identical for the 08, 32 and 86 — only the gate shape inside changes. The notch marks the pin-1 end; pins run 1-7 along the bottom and 14-8 along the top. Reading the internal wiring is what tells you the gates pair pins 1,2 to 3, 4,5 to 6, 9,10 to 8 and 12,13 to 11, and that Vcc (14) and GND (7) are the two pins with no gate on them.

Chip Function Gate A Gate B Gate C Gate D VCC GND
74HCT00 Quad 2-input NAND in 1,2 → out 3 in 4,5 → out 6 in 9,10 → out 8 in 12,13 → out 11 14 7
74HCT08 Quad 2-input AND in 1,2 → out 3 in 4,5 → out 6 in 9,10 → out 8 in 12,13 → out 11 14 7
74HCT32 Quad 2-input OR in 1,2 → out 3 in 4,5 → out 6 in 9,10 → out 8 in 12,13 → out 11 14 7
74HCT86 Quad 2-input XOR in 1,2 → out 3 in 4,5 → out 6 in 9,10 → out 8 in 12,13 → out 11 14 7

The letters A–D are yours to assign — the chip does not label its own gates. What is fixed is which pins belong to the same gate. Whichever slot you call U1:A, its pin numbers must be one of the four sets above.

Figure 311: The four gates of a 74HCT00 as circuit schematic symbols: device ID, device type, and a pin number on every terminal. For a 74HCT08, 74HCT32 or 74HCT86 the pin numbers are exactly these; only the gate body changes to AND, OR or XOR.

74HCT04 — Hex inverter

Six independent NOT gates. VCC = pin 14, GND = pin 7.

Gate A B C D E F
in → out 1→2 3→4 5→6 9→8 11→10 13→12

Figure 312: All six inverters of a 74HCT04. The numbering is not a simple run: the first three gates go low-to-high (1 to 2, 3 to 4, 5 to 6) but the last three run the other way (9 to 8, 11 to 10, 13 to 12), because the package is symmetric about its centre.

Note the direction reversal in the second half of the package — U1:D is pin 9 in, 8 out, not 8 in, 9 out. Getting this backwards is an easy way to lose marks on a schematic.

74HCT74 — Dual D-type flip-flop (14-pin)

Pin 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Signal CLR1 D1 CLK1 SET1 Q1 \(\overline{Q1}\) GND \(\overline{Q2}\) Q2 SET2 CLK2 D2 CLR2 VCC

Figure 313: The two flip-flops of a 74HCT74 as circuit schematic symbols. Unlike the 74HCT175 below, each flip-flop has its own clock, its own set and its own clear — nothing is shared. SET and CLR carry bubbles, and the wedge on the left-hand lower input marks the clock.

Set and clear inputs can be omitted from the schematic if not needed — the source sheet says so explicitly, and its own logic-diagram symbol is drawn without them.

74HCT157 — Quad 2-input multiplexer (16-pin)

Pin 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Signal SEL A0 B0 Y0 A1 B1 Y1 GND Y2 B2 A2 Y3 B3 A3 \(\overline{\text{ENABLE}}\) VCC

Figure 314: The 74HCT157 as one circuit schematic symbol — the multiplexer trapezoid, tall edge for the eight data inputs and short edge for the four outputs. It is four 2-to-1 multiplexers sharing a single SEL line and a single active-low ENABLE, so it selects between two whole 4-bit words rather than between two individual bits: one value of SEL puts A0-A3 on Y0-Y3 and the other puts B0-B3 there.

SEL (pin 1) and ENABLE (pin 15) are common to all four multiplexers — one select line for the whole package. That is what makes this chip a 4-bit-wide 2-to-1 mux rather than four independent ones. ENABLE is active low — the source sheet writes it \(\overline{\text{ENABLE}}\) and draws a bubble on that pin.

At the logic-diagram level the source sheet allows several options: one wide block with A, B, Y buses and slashes marking the 4-bit widths, or four separate 2-to-1 mux symbols drawn side by side, with the enable input added only if it is needed. See combinational-logic-blocks for what a multiplexer does.

74HCT175 — Quad D-type flip-flop (16-pin)

Pin 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Signal \(\overline{\text{CLR}}\) Q0 \(\overline{Q0}\) D0 D1 \(\overline{Q1}\) Q1 GND CLK Q2 \(\overline{Q2}\) D2 D3 \(\overline{Q3}\) Q3 VCC

The ordering is not uniform — check it before wiring. The package is mirror-symmetric about each D-pair, so the true outputs sit at pins 2, 7, 10, 15 and the complements at 3, 6, 11, 14. Reading “Q then \(\overline{Q}\)” left-to-right across all four flip-flops gets flip-flops 1 and 3 backwards. The source’s own schematic symbol settles it: D1 (pin 5) → Q1 (pin 7), D3 (pin 13) → Q3 (pin 15).

Figure 315: The 74HCT175 as one circuit schematic symbol. CLK (pin 9) and CLR (pin 1) enter once and serve all four flip-flops, which is exactly what a flat pin table hides: this is a 4-bit register, not four independent flip-flops.

CLK (pin 9) and CLR (pin 1) are common to all four flip-flops — one clock and one clear for the whole package. The source sheet’s logic-diagram column shows this two ways: as a single D flip-flop with 4-bit-wide D and Q buses, or as four separate flip-flops whose clock inputs are all tied together.

74HCT283 — 4-bit full adder (16-pin)

Pin 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Signal S1 B1 A1 S0 A0 B0 C0 GND C4 S3 B3 A3 S2 A2 B2 VCC

\(C0\) is the carry-in, \(C4\) the carry-out; \(A_i, B_i\) are the two 4-bit operands and \(S_i\) the 4-bit sum.

Figure 316: The 74HCT283 as one circuit schematic symbol. Internally it is four full adders with C1, C2 and C3 wired stage to stage inside the package, so only C0 and C4 are brought out to pins.

The source sheet’s logic-diagram column shows the internals as four cascaded full adders, with the intermediate carries \(C_1\), \(C_2\), \(C_3\) entirely inside the chip. It also offers a compact alternative symbol with \(A\), \(B\) and \(S\) drawn as 4-bit buses. This chip is the adder half of the adder-subtractor in combinational-logic-blocks.

IO board

Pins Function
1 TX
2 RX
3 SSD cathode
4 SSD decimal point
5–11 SSD segments G to A
12–15 Buttons B3 to B0
16 Logic probe
17–24 LEDs L0 to L7
25–32 Switches S0 to S7

On a schematic the IO board is labelled IO1 (IO2 for a second board), with inputs using the point-attached symbol and outputs the back-attached symbol — see Figure 309 and circuit-schematics. Use sensible signal names rather than the raw pin labels where possible: the source sheet’s own example names buttons B3–B0 on pins 12–15, switches A–H on pins 25–32, and LED outputs X0–X5, COUT, OFLOW on pins 17–24. There is no need to show power supply connections for the IO board.

Buttons and switches are inputs to your circuit; LEDs and the seven-segment display are outputs. See io-board for what the board does electrically.

Fetch-Decode-Execute Cycle

What the control unit actually does: a continuous cycle over the datapath, issuing control signals in the right order for whatever instruction it just read. See cpu-organisation for the blocks involved and arithmetic-logic-unit for the one being driven.

The cycle

The control unit operates in a continuous cycle on the datapath:

Stage What happens
Fetch Fetch an instruction from memory and bring it inside the CPU. Two special purpose registers involved — PC and IR
Decode Resolve the operation (opcode) and operands (variables)
Execute Control signals are issued and the operation takes place in the datapath

Stated as steps:

  1. Fetch the next instruction from memory into the Instruction Register (IR).
  2. Change the Program Counter (PC) to point to the next instruction.
  3. Determine the type of (decode) the instruction just fetched — i.e. look at the opcode.
  4. Execute the instruction.
  5. Return to step 1.

Figure 317: The cycle as a loop: a three-stage pipeline. Each box holds a one-line description of its stage, each arrow carries what the stage leaves behind for the next one, and the notes under the boxes summarise steps 1–4 above.

Step 2 advances the PC before the instruction executes, which is why a jump instruction works by overwriting the PC rather than by suppressing the increment.

The datapath

Figure 318: The datapath the cycle runs on. The control unit holds PC and IR and talks to memory; below it, the register file puts two values onto the A and B buses, the ALU combines them, and the result returns on the destination bus to be written back into a register.

The question this raises — and the one the control unit exists to answer — is how do we control this? Specifically:

  • How do we tell the ALU what to do?
  • How do we choose what register values are placed on the A and B buses?
  • How do we choose which register receives the result from the destination bus?
  • How do we know when to read or write memory?

Control signals

Each of those questions is answered by a bundle of wires out of the control unit. For a machine with 8 registers and the ALU of arithmetic-logic-unit:

Signal Width Answers
A register select 3 which register drives the A bus (\(2^3 = 8\) registers)
B register select 3 which register drives the B bus
Destination select 3 which register the result is written back into
ALU control 6 what the ALU does — \(F_1\), \(F_0\), ENA, INVA, ENB, INC
Memory read/write 1 whether this is a read or a write

Figure 319: The same datapath with every control signal named. Added to the previous figure: the memory block, the Address, Data and Mem R/W labels, the five bundles with their widths, and the ALU status path back into the control unit. The bundles are drawn as labelled stubs: A/B/Dest select drive the register file, ALU control drives the ALU. Widths are marked with a slash and a number; the course also letters the width beside a plain arrow, and neither is fixed as the standard. Everything except the memory block sits inside the CPU.

Plus the address and data connections to memory itself. The widths are not arbitrary: three bits because there are eight registers, and six bits because the ALU has exactly six control inputs.

Control signals come from the control unit, which must generate them in the right order for a given instruction — and which instruction that is, is determined by the contents of the Instruction Register.

So a line of high-level code like r5 = r0 + r2 becomes: A select = 0, B select = 2, destination select = 5, ALU control = the \(A + B\) row of the combinations table, memory read/write idle.

Data influencing control

The IR is not enough. The control unit can’t operate without knowing something about the data — for example, if a for-loop variable is supposed to count from 10 down to 0, how does the control unit know when it gets there?

The answer is the status register: determined by ALU operations, it stores the status of the last ALU operation and is available to the control unit. This closes the loop — the ALU’s results feed back into the control unit and change what it does next, which is what makes conditional branching possible at all. It is the return path drawn in Figure 319, and it is what a source-level if (x < 0) compiles down to.

ALU status flags

The ALU emits, alongside its result, a summary of what happened during the last operation. Typically stored in a special purpose register called the STATUS register:

Figure 320: The ALU’s second output. The result goes back to the register file; alongside it the ALU reports what happened, and those flags land in the STATUS register where the control unit can read them. The ALU is drawn as a notched trapezoid here; the block diagram in the ALU note draws the same block as a plain rectangle, and the course uses both shapes. The register is drawn as four named cells at the right-hand end of a wider register. That is shorthand, not a bit-position claim — the AVR’s own SREG orders and numbers its bits differently, see the AVR architecture note.

Flag Name Asks
Z zero was the last result 0?
V overflow did the last addition/subtraction overflow, assuming it was a two’s complement operation?
C carry was a carry out generated?
N negative was the result negative if considered as two’s complement — i.e. what is the sign bit?

V and N both presuppose a two’s complement interpretation while C does not — the hardware computes all four regardless, and it is the program’s business to read the ones that mean something for the operation it just did. See binary-number-representations, and 2026-08-04-binary-arithmetic for the overflow rules V implements.

Worked example

What values are in the status register flags after the operation \(8_{10} - 9_{10}\) on a 5-bit ALU?

First, \(-9\) in 5-bit two’s complement: \(9 = 01001\), invert to \(10110\), add one to get \(10111\). Then add, tracking the carry into and out of the sign column:

\[\begin{array}{crl} \text{carry into MSB} \rightarrow & 0\phantom{0000} & \\ & 01000 & \\ + & 10111 & \\ \hline \text{carry out} = 0 \rightarrow & 11111 & \end{array}\]

The result is \(11111\), with no carry out of the top bit. So:

Flag Value Why
Z 0 the result \(11111\) is not zero
C 0 no carry out of the most significant bit
V 0 the carry into the sign column and the carry out of it agree, both 0 — and indeed \(8 + (-9) = -1\) is comfortably in range for 5-bit two’s complement
N 1 the sign bit is 1 — the result is negative

And indeed \(11111\) read as two’s complement is \(-1\), which is \(8 - 9\).

See also

File Systems

How an operating system turns a disk full of numbered sectors into named files. This note covers the file as the common I/O abstraction, what a file system does and the tables it keeps, low-level and high-level formatting, why deleting a file does not erase it, allocation in blocks and the trade-off in choosing a block size, and contiguous against fragmented allocation. The sectors, tracks and cylinders underneath are in magnetic-disks. First met in 2026-10-22-memory-disks-and-files.

The file: a sequence of bytes

Nobody writing a program wants to deal with drive unit numbers, heads, cylinders and sectors, or with timeout errors and retries when a read fails. The operating system hides all of that behind one abstraction, the file.

To the operating system, a file is just a sequence of bytes. It can be read from, written to and extended, and it has a current position where the next read or write happens. Any structure inside it is up to the application program: a C source file is lines of text, an image file has a header and pixel data, but the OS sees bytes in both cases. The same read and write work on all of them.

What a file system does

Computers are far easier to use, and to program, when files have names: FinalReport.doc rather than “cylinder 412, head 3, sectors 17 to 40”. A file system provides this. It associates files, which are collections of sectors, with names and directories.

To do that it divides the disk’s sectors into two kinds:

  • index sectors, holding the file system’s own tables: which names exist, in which directories, and which sectors belong to each file. The File Allocation Table (FAT) of the FAT file systems is one such table;
  • data sectors, which store the files themselves.

The OS maintains a map from each file name to a set of blocks (below), and each block to its sectors. To help users, names are organised in a hierarchy of directories, or folders.

Figure 321: The layers between a program and the disk. The program reads and writes a file as a single sequence of bytes, at a current position. The operating system’s file system keeps a map from the file’s name to the blocks that hold it, and each block is one or more consecutive sectors on the disk. Neither the blocks nor the sectors need be next to one another: the map is what makes a scattered set of sectors look like one file.

There are many file systems, which differ in how they lay out their tables and what they record: FAT, FAT32, exFAT (memory cards, USB sticks), NTFS (Windows), EXT2, EXT3, EXT4 (Linux), APFS, HFS+ (macOS), UFS (BSD Unix), ZFS, and more.

Formatting

Formatting comes at two levels.

Low-level format High-level format
What it does reinitialises every sector: writes each one’s preamble, empty data and ECC creates an empty file system
What it writes the whole disk only the index (table) sectors
File system afterwards none an empty one
Old data afterwards gone still in the data sectors, unreferenced

A low-level format lays out the sector structure of magnetic-disks, so it touches every sector and takes a long time. A high-level format, what an operating system does when it is asked to “format” a disk, only writes fresh, empty tables, so it is quick, and it leaves the old files’ bytes where they were.

Deleting does not erase

Deleting a file does not mean it is gone. To delete a file, the OS may just delete its index entry and mark its blocks as free. It does not overwrite the sectors where the data is stored: that would cost a write to every sector for no benefit to the user.

The bytes stay on the disk until new files happen to be given those blocks and overwrite them. That is how undelete and data-recovery tools work, and why a disk being given away should be overwritten, not just emptied or quickly formatted.

Figure 322: What deleting a file and the two kinds of format each change. The disk has index sectors, holding the file system’s tables, and data sectors, holding the files. Deleting a file removes its entry from the index and frees its blocks, but its bytes stay in the data sectors until something else is written there. A high-level format writes fresh, empty tables and leaves the data sectors alone. Only a low-level format rewrites every sector.

Blocks

File storage is allocated in blocks, also called allocation units or clusters. A block can be as small as one sector, or several consecutive sectors. Typical block sizes run from 512 bytes to 32 kB.

A file always occupies a whole number of blocks. The last block is usually only partly filled, and the rest of it is wasted: no other file can use it. So the choice of block size is a trade-off.

  • Larger blocks mean fewer blocks per file, so a smaller map from names to blocks, and less work to find and read a file’s blocks; but more wasted space at the end of each file (at the EOF, end of file).
  • Smaller blocks waste less at the end of each file, but the map is larger and a file is split into more pieces.

On average, a file wastes half a block. A file’s length is very unlikely to be an exact number of blocks. If the amount it spills into its last block is equally likely to be anything from nothing to a whole block, the unused part of that block is, on average,

\[\text{wasted space per file} \approx \tfrac12 \times \text{block size}.\]

Figure 323: One file stored with small blocks and with large ones. The file’s bytes fill whole blocks until the last, which is only partly used; the rest of that block, hatched, is wasted, because no other file can use it. With small blocks the waste is small but the file needs many blocks and the map must list them all. With large blocks the map is short but the waste can approach a whole block. On average the waste is half a block per file.

Worked: choosing a block size

A 10,000-byte source file is stored on a disk formatted with 512-byte, 4 kB or 32 kB blocks (kB here meaning 1024 bytes). For each block size, how many blocks does the file take, how much space is wasted at its end, and how many blocks must the map track for a 1 GiB volume? On a disk of 10,000 files, how much space is wasted on average?

Blocks for the file is the file size divided by the block size, rounded up: a file cannot use part of a block.

Block size Blocks Space taken Wasted at the end Waste as share of the space taken
512 B \(\lceil 10000/512 \rceil = 20\) 10,240 B 240 B 2.3 %
4 kB = 4096 B \(\lceil 10000/4096 \rceil = 3\) 12,288 B 2,288 B 18.6 %
32 kB = 32,768 B \(\lceil 10000/32768 \rceil = 1\) 32,768 B 22,768 B 69.5 %

Map size. A 1 GiB volume is \(2^{30}\) bytes, so it has \(2^{30}/512 = 2{,}097{,}152\) blocks of 512 B, \(2^{30}/4096 = 262{,}144\) blocks of 4 kB, and \(2^{30}/32768 = 32{,}768\) blocks of 32 kB. The map must track every one of them, so the largest blocks give a map 64 times smaller than the smallest.

Waste across the disk. At half a block per file, 10,000 files waste about

Block size Average waste per file For 10,000 files
512 B 256 B 2,560,000 B \(\approx\) 2.44 MiB
4 kB 2 kB 20,480,000 B \(\approx\) 19.53 MiB
32 kB 16 kB 163,840,000 B \(\approx\) 156.25 MiB

So small blocks suit a disk of many small files, where large blocks would waste much of the space. Large blocks suit a disk of a few large files, where half a block per file is nothing and the short map and fewer pieces per file pay off.

Contiguous and fragmented allocation

Where a file’s blocks are placed on the disk decides how fast it can be read.

  • Contiguous allocation puts the blocks one after another along a track, then on the next track of the same or the adjacent cylinder. Reading the file costs one seek and one rotational wait to reach its first block, after which the sectors stream past the head in order. Moving on to the next track costs only a step to the adjacent track (or none at all, if it is another surface of the same cylinder, which is just a switch of head) and a wait for the next block to come round.
  • Fragmented allocation scatters the blocks over different tracks and sectors. Every jump to a different track costs a seek, and every jump to a sector that is not the next one along costs rotational latency (magnetic-disks).

Contiguous allocation is ideal, but over time it becomes unlikely: as files are created, grown and deleted, the free space breaks up into small scattered pieces, and a new file has to be put in whatever pieces are free. The disk becomes fragmented, and fragmentation makes access slow. Defragmenting moves each file’s blocks back together. (An SSD has no seek or rotation, so fragmentation costs it far less.)

Figure 324: Two ways the same 15-block file can be stored, one block to a sector, on a surface with five tracks of twelve sectors. Sectors are numbered clockwise from the top and the disk turns so that they pass the head in that order. In (a) the blocks are contiguous: 0 to 11 fill one track in order and 12 to 14 continue on the next. One seek and one wait reach block 0, a single turn reads blocks 0 to 11, and then the head steps out to the adjacent track and waits for block 12 to come round before reading the last three. In (b) the disk is fragmented and the blocks are scattered over every track, so reading them in order needs a seek almost every time and a wait for the next block to come round.

Common mistakes

  • Thinking delete or a quick format erases data. Both rewrite only the index; the bytes remain until overwritten.
  • Rounding the block count down. A 10,000-byte file in 4096-byte blocks needs 3 blocks, not 2: \(\lceil 10000/4096 \rceil = 3\).
  • Assuming bigger blocks are always better. They shrink the map but waste half a block per file on average, which adds up on a disk of small files.
  • Confusing a block with a sector. The sector is the disk’s unit; the block is the file system’s, one or more consecutive sectors.
  • Thinking the OS sees structure in a file. To the OS a file is bytes. Lines, records and headers are the application’s business.

See also

Fixed-Point Numbers

How a fixed number of bits can hold a fraction: put a binary point at an agreed place and give the bits to its right the weights \(\tfrac12, \tfrac14, \tfrac18, \dots\) This note covers the binary point and its place values, converting a decimal value such as 4.375 into bits, the \(m.n\) format names, reading a bit pattern in a given format, unsigned and two’s complement fixed point, and the trade-off between range and precision as the point moves across a byte. The way round that trade-off, letting the point float, is in floating-point-numbers. Whole numbers and the signed formats this builds on are in binary-number-representations. First met in 2026-10-19-floating-point-numbers.

The binary point

Binary place values carry on to the right of the point exactly as decimal ones do. In decimal the column after the point is worth \(10^{-1}\); in binary it is worth \(2^{-1} = \tfrac12\), the next \(2^{-2} = \tfrac14\), then \(\tfrac18\), \(\tfrac1{16}\), and so on, each half the one before.

Position \(2^3\) \(2^2\) \(2^1\) \(2^0\) . \(2^{-1}\) \(2^{-2}\) \(2^{-3}\) \(2^{-4}\)
Worth 8 4 2 1 . 0.5 0.25 0.125 0.0625

The point is not stored anywhere. The bits are an ordinary 8-bit pattern, and where the point sits is an agreement, made by whoever writes the program, in the same way that “this byte is two’s complement” is an agreement (binary-number-representations). Because the agreed place never moves, the scheme is called fixed point.

Figure 325: Eight bits with the binary point agreed to sit after the fourth. The four bits to the left are worth 8, 4, 2 and 1 as usual; the four to the right carry on halving, to 1/2, 1/4, 1/8 and 1/16. The value 4.375 is 4 + 1/4 + 1/8, so the bits worth 4, 1/4 and 1/8 are set and every other bit is 0, giving 0100.0110. Nothing in the byte marks where the point is: the same eight bits read as a whole number are 70, which is 4.375 times 16.

Converting a decimal value

Two methods, both worked on 4.375 into a format with 4 bits after the point.

Method 1: whole part and fraction separately. The whole part converts as usual: \(4 = 100_2\). The fraction converts by repeated doubling: double it, the digit before the point is the next bit, and carry on with what is after the point. Stop when the fraction reaches 0 or the bits run out.

Fraction \(\times 2\) Bit Carry on with
0.375 0.75 0 0.75
0.75 1.5 1 0.5
0.5 1.0 1 0

The bits come out left to right, starting just after the point: \(0.375 = 0.011_2\). So \(4.375 = 100.011_2\), and padded to four bits each side, 0100.0110.

Doubling is the mirror image of the repeated division for whole numbers (binary-number-representations): division pulls bits off the right-hand end, doubling pulls them off the left-hand end of the fraction. The fraction can also be taken apart by subtraction, as with Method 1 for whole numbers: \(0.375 - 0.25 = 0.125\), and \(0.125 = \tfrac18\), so the bits worth \(\tfrac14\) and \(\tfrac18\) are set.

Method 2: scale to a whole number. With \(n\) bits after the point, every value is a whole number of \(2^{-n}\) steps. Multiply by \(2^n\), convert the whole number, and put the point back \(n\) places from the right. With \(n = 3\): \(4.375 \times 8 = 35 = 100011_2\), so \(4.375 = 100.011_2\). With \(n = 4\) it is \(4.375 \times 16 = 70 = 1000110_2\), the same bits with one more 0 on the end.

If the product is not a whole number, the value has no exact representation with \(n\) fractional bits (below).

Format names: \(m.n\)

A fixed-point format is named by how the bits are split: \(m.n\) means \(m\) integer bits before the point and \(n\) fractional bits after it, \(m + n\) bits in all. Every 8-bit format has \(m + n = 8\):

  • 8.0 is an ordinary unsigned byte, the point after the last bit;
  • 5.3 has five integer bits and three fractional bits, xxxxx.xxx;
  • 0.8 has the point before the first bit, so every value is below 1.

The same value sits in different formats with the point in different places. \(4.375\) is 0100.0110 in 4.4, 00100.011 in 5.3, and 100.01100 in 3.5. Moving the point one place right with the bits fixed doubles the value; so to keep the value the same, the bits have to move the other way.

Reading a pattern

To find the value of a bit pattern in a given format, either add the place values of the 1 bits, or read the bits as a whole number and divide by \(2^n\). The second is quicker when the pattern is long.

10110101 as unsigned 5.3: the whole number is \(181\), and \(181 / 2^3 = 22.625\). By place values, \(10110.101_2 = 16 + 4 + 2 + \tfrac12 + \tfrac18 = 22.625\), the same.

Two’s complement fixed point

Signed fixed point uses two’s complement in the same way as signed whole numbers (binary-number-representations). The MSB’s weight is negated: in an \(m.n\) format it is worth \(-2^{m-1}\) instead of \(+2^{m-1}\), and every other bit keeps its place value. So in 5.3 the bits are worth

\[-16,\ 8,\ 4,\ 2,\ 1\ .\ \tfrac12,\ \tfrac14,\ \tfrac18\]

and in 4.4 they are worth \(-8, 4, 2, 1, \tfrac12, \tfrac14, \tfrac18, \tfrac1{16}\).

Negating works as for integers: invert every bit and add 1 at the last place, which is now worth \(2^{-n}\), not 1. Equivalently, the value is the unsigned reading minus \(2^m\) whenever the MSB is 1, which is the divide-by-\(2^n\) rule with \(256\) subtracted first: 10110101 is \((181 - 256)/8 = -75/8 = -9.375\) in two’s complement 5.3. The same question with the two tempting wrong answers, \(-10.625\) and \(-9.625\), explained is 2026-10-19-floating-point-numbers.

Figure 326: Two’s complement fixed point in the 4.4 format. The only change from unsigned is the MSB, whose weight becomes minus 8 instead of plus 8; the fraction bits keep their positive weights. So 1101.1000 is minus 8 plus 4 plus 1 plus 1/2, which is minus 2.5. Negating it still means inverting every bit and adding one, but the one is added in the last place, which is worth 1/16: 0010.0111 plus 0.0001 is 0010.1000, which is plus 2.5.

Range against precision

Eight bits give 256 patterns whatever the format. The format only decides how far apart the 256 values are and so how far they reach. For an unsigned \(m.n\) format:

  • the precision, the gap between neighbouring values, is the weight of the last bit, \(2^{-n}\);
  • the maximum is all ones, \((2^8 - 1) \times 2^{-n} = 255 \times 2^{-n}\), one step short of \(2^m\);
  • the minimum is 0.

Two’s complement \(m.n\) has the same precision and runs from \(-2^{m-1}\) to \(2^{m-1} - 2^{-n}\).

Format Unsigned maximum Precision Two’s complement range
“10.$-$2” 1020 4 \(-512\) to \(508\)
“9.$-$1” 510 2 \(-256\) to \(254\)
8.0 255 1 \(-128\) to \(127\)
7.1 127.5 0.5 \(-64\) to \(63.5\)
6.2 63.75 0.25 \(-32\) to \(31.75\)
5.3 31.875 0.125 \(-16\) to \(15.875\)
4.4 15.9375 0.0625 \(-8\) to \(7.9375\)
3.5 7.96875 0.03125 \(-4\) to \(3.96875\)
2.6 3.984375 0.015625 \(-2\) to \(1.984375\)
1.7 1.9921875 0.0078125 \(-1\) to \(0.9921875\)
0.8 0.99609375 0.00390625 \(-0.5\) to \(0.49609375\)

Each place the point moves right doubles the maximum and doubles the step. Range and precision trade against each other one for one, and no 8-bit format gets both.

“9.$-\(1" and "10.\)-$2” carry the pattern past 8.0. The point is now to the right of the byte: one or two invisible bits, always 0, sit between the last stored bit and the point. The stored bits are worth \(2^8\) down to \(2^1\) (or \(2^9\) down to \(2^2\)), so every value is a multiple of 2 (or 4), and the maximum is \(255 \times 2 = 510\) (or \(255 \times 4 = 1020\)). The “\(-1\)” counts fractional bits that are missing: \(n = -1\) means the last bit is worth \(2^{-(-1)} = 2\). The quote marks are there because the name stretches the \(m.n\) idea past where it reads naturally, but the formulas above still hold with negative \(n\).

Figure 327: The binary point moving across the same eight bits. The highest bit is worth 2 to the m minus 1 and the lowest is worth 2 to the minus n, so each step of the point to the right doubles both the maximum value and the gap between neighbouring values. At 8.0 the byte is an ordinary unsigned integer. Past that, in the 9.-1 and 10.-2 formats, the point lies beyond the byte, with one or two bits that are always 0 between them (drawn dashed), so only even numbers or multiples of 4 can be held, up to 510 or 1020. At the other end, 0.8 holds only values below 1, in steps of 1/256.

Worked examples

Worked: 4.375 in three formats

Write 4.375 in the 8-bit unsigned formats 4.4, 5.3 and 3.5.

\(4.375 = 100.011_2\) (Method 1 or 2 above). It needs 3 integer bits and 3 fractional bits, so it fits all three formats exactly; only the padding changes.

Format Bits Check
4.4 0100.0110 \(70 / 16 = 4.375\)
5.3 00100.011 \(35 / 8 = 4.375\)
3.5 100.01100 \(140 / 32 = 4.375\)

In 2.6 it would not fit: 4 needs a bit worth 4, and 2.6’s highest bit is worth 2.

Worked: choosing a format

A byte must hold a percentage, 0 to 100, as precisely as possible. Which unsigned format? And for a signed value between \(-3\) and \(+3\)?

Percentage. The maximum must reach 100. Going down the table, 7.1 reaches 127.5 and 6.2 only 63.75, so 7.1, with a precision of 0.5.

\(\pm 3\). In two’s complement, 3.5 runs from \(-4\) to \(3.96875\) and 2.6 from \(-2\) to \(1.984375\). So two’s complement 3.5, with a precision of \(\tfrac1{32}\).

In both cases the rule is: take the smallest \(m\) that still reaches the largest value, because every integer bit not needed is a fractional bit lost.

Worked: 0.1 has no exact form

Store 0.1 in unsigned 4.4.

Method 2: \(0.1 \times 16 = 1.6\), not a whole number, so 0.1 cannot be stored exactly. The nearest step is \(2/16 = 0.125\) (0000.0010); truncating gives \(1/16 = 0.0625\) (0000.0001). Repeated doubling shows why no number of bits is enough: \(0.1 \to 0.2 \to 0.4 \to 0.8 \to 1.6 \to 1.2 \to 0.4 \to \dots\) gives \(0.000110011\ldots_2\), with 0011 repeating for ever. A fraction is finite in binary only when its denominator is a power of 2, so 0.375 (\(\tfrac38\)) is exact and 0.1 (\(\tfrac1{10}\)) is not.

Why use it

Fixed point needs no new hardware. Two values in the same \(m.n\) format add and subtract with the ordinary integer adder, because the points line up; only the reading changes. That makes it the natural choice for fractions on a small processor like the AVR, which has integer instructions only (instruction-set-architecture). The price is the trade-off above: the range and the precision are fixed once the format is chosen, and a value too large or too small for it simply cannot be held. floating-point-numbers stores the position of the point alongside the digits so that it can move.

Common mistakes

  • Reading the fraction bits as a whole number. .011 is \(\tfrac14 + \tfrac18 = 0.375\), not “0.3”.
  • Forgetting that the point is an agreement. A byte has no point in it; the same 10110101 is 181, 22.625 or \(-9.375\) depending on the format chosen.
  • Giving the MSB a positive weight in two’s complement. In two’s complement 5.3, the first bit is worth \(-16\); only that bit is negative, and the fraction bits still add.
  • Negating by adding 1 to the integer part. The 1 is added in the last place, \(2^{-n}\).
  • Taking the maximum as \(2^m\). It is one step short: \(2^m - 2^{-n}\) (31.875 for 5.3, not 32).
  • Reading the doubling remainders in the wrong order. For a fraction the bits come out left to right, the first one just after the point. That is the opposite of repeated division for a whole number.
  • Expecting every decimal fraction to be exact. Only fractions with a power-of-2 denominator are.

See also

Flip-Flops and Latches

Flip-flops and latches are the storage elements — the circuits that let a design remember a value even after the input that produced it has changed. They’re what turns a combinational circuit into a sequential circuit.

Introduced in Lecture 5, 2026-08-10-introduction-to-sequential-circuits.

The D flip-flop

The D flip-flop is the only flip-flop type covered in this course. Its symbol is a rectangle with:

  • D — the data input, on the left.
  • Q — the output, on the right.
  • CLK — the clock, a control input on the left, drawn with a small triangular wedge where it meets the box.

How it works: Q copies the value of D (and remembers it) whenever CLK goes from 0 to 1 — the rising edge. In between clock edges the flip-flop is not responsive, so it holds the stored value. Q changes only on that 0→1 transition.

Summary: a D flip-flop remembers a single bit — either a “1” or a “0”. It keeps that value until the next clock edge, at which point the D input is transferred to output Q.

  • To remember \(n\) bits you need \(n\) D flip-flops.
  • An \(n\)-bit register is (by definition) \(n\) D flip-flops. See shift-registers.
  • Flip-flops can themselves be made out of logic gates — see the SR latch and A real D flip-flop below.

Characteristic table

A characteristic table defines the operation of a flip-flop in tabular form. The left column is the input; the right column, \(Q(t+1)\), is the next value of Q: what the output will be on the next clock edge (i.e. when CLK goes 0→1).

D Q(t+1)
0 0 Reset
1 1 Set

That is the whole behaviour: the flip-flop is reset (to 0) or set (to 1) according to D, at the clock edge.

A flip-flop’s next-state column is written \(Q(t+1)\) here. The state tables of state-machines and [counters] call the same thing Next State. The course uses both names (see csse2010-diagram-notation).

Worked waveform

D is 0, 0, then 1, 1 across a clock with two rising edges. CLK starts low, pulses high, goes low, then pulses high again after D has risen.

Figure 328: A D flip-flop waveform. The dashed verticals are the two rising clock edges, and the arrows mark them. Q is undefined (drawn dashed, with a cross) until the first edge. The point of the figure is the middle: D rises well before the second edge, and Q does not follow until that edge arrives.

Clock edge D at that edge Q after
(before the first edge) — unknown/undefined
1st rising edge 0 0
2nd rising edge 1 1

Before the first rising edge Q is undefined, because nothing has been clocked in yet; an “X” marks that stretch. Between the two rising edges Q stays 0 even though D has already risen to 1: the flip-flop is only sensitive at the edge. Remember: Q changes only when the clock (CLK) goes from 0 to 1.

A second, harder worked waveform — four clock edges, with D both rising and falling between them — is in 2026-08-10-introduction-to-sequential-circuits.

Other flip-flop types

Other types exist — JK flip-flops and T flip-flops — but they are not covered in this course. Only the D flip-flop is used.

Latches vs flip-flops

  • Latches are level triggered devices — they latch the output and respond to changes of logic levels on the inputs.
  • A latch circuit can be modified so that it becomes sensitive to an edge (a momentary transition) of a control input, i.e. a clock signal. Such circuits are called flip-flops.
  • A flip-flop can store 1 bit of information while being sensitive to a clock edge — it changes its output only at the clock edges, based on the inputs.
  • So: latches are level triggered; flip-flops are edge triggered.

A clock signal has two edges:

Edge Transition
Positive (rising) edge 0 → 1
Negative (falling) edge 1 → 0

A D flip-flop can therefore be positive edge triggered or negative edge triggered. In a positive edge triggered D flip-flop, D is copied to Q at the positive edge of the clock; in between clock edges the flip-flop is not responsive, thus stores the value.

The state of a flip-flop is the value it is storing. Flip-flops are more useful than latches in practice.

Symbols used

Four related symbols, all drawn as a rectangle with D in at the top left, Q out at the top right, and a clock input CK at the bottom left. What distinguishes them is the marking on that CK input.

Figure 329: The four latch and flip-flop symbols, with the clock pin labelled CK (the course writes this pin CLK elsewhere). The wedge and the bubble read independently: the wedge says edge-triggered, therefore flip-flop; the bubble says inverted, therefore falling edge or low level. The reading under each symbol follows from those two rules.

Symbol CK input marking Device Triggered on
(a) plain input Latch High level of CK
(b) bubble (inversion circle) Latch Low level of CK
(c) triangle/wedge Flip-flop Rising (positive) edge of the clock
(d) bubble + triangle Flip-flop Falling (negative) edge of the clock

The two markings read independently and are the whole key to the notation:

  • The triangle indicates edge-triggered, and therefore that the device is a flip-flop rather than a latch. No triangle means level-triggered, i.e. a latch.
  • The bubble indicates inversion, i.e. the falling edge (or the low level) rather than the rising edge (or the high level).

The SR latch (cross-coupled NOR gates)

Structure: two 2-input NOR gates cross-coupled.

  • The top NOR gate takes \(S\) as one input and the bottom gate’s output as its other input; its output is \(\bar Q\).
  • The bottom NOR gate takes \(R\) as one input and the top gate’s output (\(\bar Q\)) as its other input; its output is \(Q\).

So each gate’s output feeds back into the other gate’s input — that feedback loop is what stores the bit.

Figure 330: The SR latch: two cross-coupled NOR gates, with the NOR truth table to remember and the two special cases the analysis needs. Between them they are the whole analysis: a NOR with a 0 on one input passes the other input inverted, and a NOR with a 1 on one input is pinned to 0. Where the two feedback wires cross there is no junction dot, so it is two wires passing, not a connection.

The analysis needs both identities in the figure. Together they are what makes each row fall out in a line. Both are just De Morgan applied to a NOR (see boolean-algebra): \(\overline{A+B} = \bar A \cdot \bar B\).

The truth table:

S R Q \(\bar Q\) Meaning
0 0 \(Q_{n-1}\) — Storage / remember
0 1 0 1 Reset
1 0 1 0 Set
1 1 — — Invalid \(\times\)

\(Q_{n-1}\) means “whatever \(Q\) was before” — the hold row’s entry is not a bit but a reference to the previous value. Three cells are left blank: \(\bar Q\) in the hold row, and both outputs in the last row, which is Invalid.

Reasoning for each row, using the two identities above:

  • \(S=0, R=0\): each gate has a 0 on its external input, so each is an inverter of the other’s output — \(\bar Q = \overline{Q}\) and \(Q = \overline{\bar Q}\). Both \(Q=1\) and \(Q=0\) satisfy that, so the latch simply holds whatever it already had. This row is the whole point of the circuit: it is the row in which the latch remembers.
  • \(S=1, R=0\): the top gate has a 1 on an input, so \(\bar Q = 0\) regardless. The bottom gate then sees \(R=0\) and \(\bar Q=0\), so \(Q=1\). \(S\) sets the latch.
  • \(S=0, R=1\): mirror image — the bottom gate has a 1 on an input, so \(Q=0\); the top gate then sees \(S=0\) and \(Q=0\), so \(\bar Q=1\). \(R\) resets the latch.
  • \(S=1, R=1\): both gates have a 1 on an input, so both outputs are 0: \(Q = 0\) and \(\bar Q = 0\). That result is what condemns the combination: the two outputs are supposed to be complements and here they are equal, so the labels \(Q\) and \(\bar Q\) stop meaning anything. Worse, what happens after both inputs return to 0 simultaneously is not uniquely determined (the two gates race), so the resulting state is indeterminate. Hence invalid — a combination you must not apply.

This circuit is the active high SR latch: the inputs do their job when driven to 1, and the resting/hold condition is \(S=R=0\). That name is what distinguishes it from the NAND version below.

The SR latch from NAND gates (active low)

Exercise: analyse the SR latch circuit when the NOR gates are replaced with NAND gates, and complete the truth table. The answer circuit is below. The gate symbols are not merely swapped: the inputs are relabelled \(\bar S\) and \(\bar R\), and which gate’s output is called \(Q\) is swapped, so that the set/reset roles survive the change.

Figure 331: The NAND SR latch, the active low SR latch, with the NAND truth table and the two identities that drive the analysis. Compare against the NOR version: the gate outputs have swapped names, so the top gate now produces Q, and the inputs are drawn overlined because they are active low.

Worked through with the two NAND identities in the figure:

\(\bar S\) \(\bar R\) Q \(\bar Q\) Meaning
0 0 1 1 Invalid — outputs not complementary
0 1 1 0 Set (\(\bar S\) asserted)
1 0 0 1 Reset (\(\bar R\) asserted)
1 1 \(Q_{n-1}\) — Storage / remember

(Rows in ascending binary order of the inputs, which is what every truth table in the course does — see csse2010-diagram-notation.)

  • \(\bar S = \bar R = 1\): each gate has a 1 on its external input, so each inverts the other’s output — the same self-consistent pair as the NOR latch’s \(S=R=0\) row. Hold.
  • \(\bar S = 0\): the top gate is pinned to 1, so \(Q = 1\); the bottom gate then sees \(\bar R = 1\) and \(Q = 1\), so \(\bar Q = 0\). Set.
  • \(\bar R = 0\): mirror image — \(\bar Q = 1\), and the top gate then gives \(Q = 0\). Reset.
  • \(\bar S = \bar R = 0\): both gates pinned to 1, so \(Q = \bar Q = 1\). Same objection as before, so invalid.

The headline result, and the reason the inputs are drawn overlined: with NAND gates the inputs become active low. The latch rests (holds) at \(\bar S = \bar R = 1\) instead of at \(S=R=0\), and the forbidden combination moves from both-high to both-low. Everything else — set, reset, hold, one invalid corner — is the same circuit doing the same job.

This active-low convention is general: it is why the 74HCT74’s asynchronous pins are \(\overline{\text{SET}}\) and \(\overline{\text{CLR}}\) (see device-pinouts). The SET and CLR inputs are typically active low.

A real D flip-flop

A real D flip-flop is built from cross-coupled NAND gates — six NAND gates in three cross-coupled pairs: two input latches driven by D and CLK, and a third pair forming the output latch that carries \(Q\) and \(\bar Q\). That is the same storage idea as the SR latch above, wrapped in enough extra gating to make it respond to an edge rather than a level.

As well as D, CLK and the outputs \(Q\) and \(\bar Q\), it has two extra inputs:

  • \(\overline{\text{PRE}}\) (Preset) — forces \(Q\) to 1.
  • \(\overline{\text{CLR}}\) (Clear) — forces \(Q\) to 0.

Both are drawn with overbars and with a bubble on the pin, i.e. they are active low, and both are asynchronous: they act on the latch directly, independent of the clock, rather than waiting for a clock edge. They run straight into the NAND gates of the latches, bypassing the D/CLK path entirely — \(\overline{\text{PRE}}\) reaches the gate that produces \(Q\) and \(\overline{\text{CLR}}\) the gate that produces \(\bar Q\), which is exactly how each forces its output.

The two things to remember about these pins: they are active low inputs and asynchronous inputs.

Figure 332: The D flip-flop symbol with its asynchronous pins, CLR on top and PRE underneath. The 74HCT74 in device-pinouts is drawn the other way up (SET on top, CLR below), which is the course’s usual order; the course is also inconsistent about the naming (PRE/CLR against SET/CLR). The three consequences of the pins being asynchronous and active low are on the right.

Both pins being asserted at once (\(\overline{\text{PRE}} = \overline{\text{CLR}} = 0\)) is the same kind of contradiction as \(S=R=1\) on the NOR latch — it demands \(Q=1\) and \(Q=0\) simultaneously — and is likewise a combination to avoid. It follows from the SR-latch analysis above.

When neither is needed they can simply be omitted from a drawing: the course’s Device Pinouts and Symbols sheet says so in words, and its own logic-diagram symbol for a D flip-flop leaves them off. See device-pinouts and circuit-schematics.

D flip-flop chips

  • 74HCT74 — dual D flip-flop (two independent D flip-flops in a 14-pin package), each with its own clock, its own CLR and its own PR (preset), and \(Q\)/\(\bar Q\) outputs. Pinout and schematic symbol in device-pinouts.
  • 74HCT273 — eight D flip-flops in a 20-pin package, so it can hold one byte (8 bits) of information. It is not in the course’s device-symbols document, so there is no pinout for it here.

The full symbol set is in the device symbols PDF on Blackboard.

See also

Floating-Point Numbers

How a computer holds numbers as large as \(6 \times 10^{23}\) and as small as \(3.6 \times 10^{-4}\) in the same few bytes: store the digits and the position of the point separately, as scientific notation in binary. This note covers why a fixed point is not enough, scientific notation and normalisation, where the word “mantissa” comes from, the IEEE 754 single and double precision formats (sign, excess-127 or excess-1023 exponent, mantissa with an implicit leading 1, and why the fields are in that order), converting in both directions, the special values (zero, subnormal numbers, infinity and NaN), what finite precision does to arithmetic, the family of formats from quarter to octuple precision with every quarter-precision value listed, and floating point in C and on the AVR. Fixed point, the alternative this improves on, is in fixed-point-numbers. The excess notation behind the exponent is in binary-number-representations. First met in 2026-10-19-floating-point-numbers.

Why the point has to float

A fixed-point format spends its bits once and for all between range and precision (fixed-point-numbers). Real quantities do not cooperate.

  • Avogadro’s number is \(6.02214076 \times 10^{23}\), written out 602214076000000000000000. As a whole number it needs 79 bits (\(\log_2 \approx 78.99\)), and only its first nine digits carry any information.
  • The volume of a cup is about \(0.00036\ \text{m}^3\). In fixed point its first 1 is in the 12th place after the point (\(2^{-12} \approx 0.000244\)), so it needs at least 12 fractional bits just to be non-zero, and more for any precision.

To hold both in one format, a fixed-point number would need about 79 integer bits and a few dozen fractional bits, nearly all of them zero in any given value. The way out is the one people already use: write the significant digits once and say separately where the point goes.

Scientific notation

Everyday language already lets the point move. SI prefixes do it in words: a kilometre is \(10^3\) m, a milligram \(10^{-3}\) g, and the scale runs out to femto (\(10^{-15}\)), yocto (\(10^{-24}\)) and beyond. The number in front stays a convenient size and the prefix carries the scale.

Scientific notation does it in symbols:

\[\text{value} = \text{significant digits} \times \text{base}^{\text{exponent}}\]

so Avogadro’s number is \(6.02 \times 10^{23}\) and the cup is \(3.6 \times 10^{-4}\ \text{m}^3\). The digits say what the number is and the exponent says how big. Moving the point one place left and adding 1 to the exponent leaves the value unchanged, which is exactly the freedom fixed point lacks.

Normalisation

That freedom means one value has many spellings: \(602 \times 10^{21} = 60.2 \times 10^{22} = 6.02 \times 10^{23} = 0.602 \times 10^{24}\). A normalised number picks one of them: exactly one non-zero digit before the point. In decimal that puts the digits in the range \([1, 10)\), and \(6.02 \times 10^{23}\) is the normalised form.

In binary the same rule gives the range \([1, 2)\). The only non-zero binary digit is 1, so a normalised binary number always looks like \(1.xxxx_2 \times 2^e\). Something like \(3.985 \times 2^{77}\) is not normalised in binary, even though 3.985 would be fine in front of a power of 10: it should be \(1.993 \times 2^{78}\). Halving the digits and adding one to the exponent, or doubling and subtracting one, moves between the spellings.

Normalising gives every value a single representation, so no bit patterns are wasted on duplicates, and it guarantees no precision is spent on leading zeros. In binary it does one more thing, used below: the first digit is always 1, so it need not be stored.

Why “mantissa”

The digits part of a floating-point number is called the mantissa (the IEEE standard’s own term is significand). The word comes from logarithm tables.

Before calculators, multiplication was done with \(\log(a \times b) = \log a + \log b\): look up two logarithms, add them, and look up the antilog. A printed table only needs the logarithms of 1.00 to 9.99, because scaling by 10 only adds 1 to the logarithm:

\(x\) \(\log_{10} x\) Integer part Fractional part
0.123 \(-0.9101\) \(-1\) \(0.0899\)
1.23 \(0.0899\) 0 \(0.0899\)
12.3 \(1.0899\) 1 \(0.0899\)
123 \(2.0899\) 2 \(0.0899\)

The fractional part, the same 0.0899 for all four, depends only on the significant digits 1, 2, 3, and it was called the mantissa. The integer part, which only says where the point goes, was the characteristic. A four-figure table lists the mantissas: the row for 12 and the column for 3 give 0899, meaning \(\log_{10} 1.23 = 0.0899\). (For 0.123 the log is \(0.0899 - 1 = -0.9101\); tables wrote it \(\bar{1}.0899\) to keep the mantissa visible.)

A floating-point number splits the same way: digits that say what, an exponent that says where the point goes. The digits inherited the name, although strictly the old mantissa was a logarithm and the new one is the digits themselves.

IEEE 754

Almost every computer stores floating point in the formats of the IEEE 754 standard. A number is stored as three fields, sign, exponent and mantissa, and stands for

\[(-1)^S \times 1.M_2 \times 2^{E - \text{bias}}\]

Format Bits Sign Exponent Mantissa Bias
Single precision 32 1 8 23 127
Double precision 64 1 11 52 1023

Figure 333: The IEEE 754 single and double precision layouts, MSB on the left, with the bit number at each field boundary. The sign bit is 0 for plus and 1 for minus. The exponent field E holds the true exponent plus the bias, 127 or 1023. The mantissa field M holds only the bits after the point, because a normalised binary mantissa always starts with a 1 that does not need storing. Reading a pattern means putting those three back together as (-1) to the S, times 1.M, times 2 to the E minus the bias. The exponent and mantissa are drawn to scale within each row, double precision at half the scale of single; the sign bit is drawn wider than one bit so it can be labelled.

The biased exponent

The exponent can be negative, so it needs a signed format. IEEE uses excess (biased) notation: the field holds the true exponent plus a fixed bias,

\[E = e + \text{bias}, \qquad \text{bias} = 2^{k-1} - 1 \text{ for a } k\text{-bit exponent}.\]

So single precision is excess-127 and double precision excess-1023. A true exponent of 4 is stored as \(4 + 127 = 131 = 10000011_2\); a true exponent of \(-2\) as \(125 = 01111101_2\).

This is the excess notation of binary-number-representations, with one difference to watch: the bias there is \(2^{k-1}\) (excess-128 for 8 bits), while IEEE uses one less, 127. The stored values 0 and 255 are kept for the special values, so the normal true exponents run from \(1 - 127 = -126\) to \(254 - 127 = +127\).

The implicit leading 1

A normalised binary mantissa is always \(1.xxxx_2\) (normalisation). A bit that is always 1 carries no information, so IEEE does not store it. The mantissa field holds only the bits after the point, and the 1 is put back when the number is read. Single precision therefore has 24 significant bits for the price of 23. The one exception is the subnormal numbers, where the hidden bit is 0.

Why sign, exponent, mantissa

The order is chosen so that floating-point numbers sort like integers. Compare \(1 \times 2^{100}\) with \(3 \times 2^{20}\): the first is far larger, even though its mantissa is smaller, because the exponent decides the scale and the mantissa only refines it. Putting the exponent in the high bits, above the mantissa, means that comparing two patterns as plain integers compares exponents first and mantissas only when the exponents are equal, which is exactly numeric order.

The biased exponent is what makes this work. In excess form a larger exponent is always a larger unsigned field, negative exponents included, so no two’s complement sign gets in the way. The result: for two non-negative floats, the one whose bit pattern is the larger unsigned integer is the larger number, and the integer comparison hardware can sort floats. The quarter-precision table shows it: reading the patterns in counting order reads the values in increasing order. The sign bit comes first so that sign alone splits positive from negative; negative numbers are sign and magnitude, so among them the order reverses.

Encoding: decimal to IEEE

  1. Convert to binary scientific notation, normalised: \(\pm 1.xxxx_2 \times 2^e\) (fixed-point-numbers for the fraction bits).
  2. Store the sign: \(+\) gives 0, \(-\) gives 1.
  3. Store the biased exponent: \(e + 127\) in 8 bits (single) or \(e + 1023\) in 11 bits (double).
  4. Store the mantissa: drop the leading 1 and pad with zeros on the right to 23 (or 52) bits. Right, because these are fraction bits: zeros after the last 1 do not change the value.
  5. Group into nibbles and write the 32 bits as 8 hex digits.

And beware of special values: zero, infinity and NaN do not follow these steps (below).

\(-23.25\) worked through these steps to 0xC1BA0000 is in 2026-10-19-floating-point-numbers.

Worked: 5.75 to single precision

Write 5.75 as an IEEE single-precision number in hexadecimal.

  1. \(5.75 = 101.11_2 = 1.0111_2 \times 2^2\).
  2. Positive: \(S = 0\).
  3. \(E = 2 + 127 = 129 = 10000001_2\).
  4. \(M\) = 0111 followed by 19 zeros.
  5. 0 10000001 01110000000000000000000 = 0100 0000 1011 1000 0000 0000 0000 0000 = 0x40B80000.

Worked: \(-0.375\) to single precision

Write \(-0.375\) as an IEEE single-precision number in hexadecimal.

  1. \(0.375 = 0.011_2 = 1.1_2 \times 2^{-2}\). The point moves right, so the exponent is negative.
  2. Negative: \(S = 1\).
  3. \(E = -2 + 127 = 125 = 01111101_2\).
  4. \(M\) = 1 followed by 22 zeros.
  5. 1 01111101 10000000000000000000000 = 1011 1110 1100 0000 0000 … = 0xBEC00000.

Worked: 0.1 to single precision

Write 0.1 as an IEEE single-precision number. Is it exact?

\(0.1 = 0.0\,0011\,0011\,0011\ldots_2\) repeating (fixed-point-numbers), which normalises to \(1.1001\,1001\,1001\ldots_2 \times 2^{-4}\). So \(S = 0\) and \(E = -4 + 127 = 123 = 01111011_2\). The mantissa should be 1001 repeated for ever. Only 23 bits fit:

10011001100110011001100 | 1100… (the bits that do not fit)

What is cut off starts with a 1 followed by more 1s, so it is more than half a unit in the last place, and the stored mantissa rounds up to 10011001100110011001101. The pattern is 0 01111011 10011001100110011001101 = 0x3DCCCCCD, and it stands for \(0.100000001490116\ldots\), not 0.1. 0.1 has no exact binary floating-point form, for the same reason \(\tfrac13\) has no exact decimal one.

Decoding: IEEE to decimal

  1. Write the hex as 32 bits and split 1 / 8 / 23.
  2. Sign: 0 is \(+\), 1 is \(-\).
  3. Exponent: check for all 0s or all 1s (special values); otherwise \(e = E - 127\).
  4. Mantissa: put back the hidden 1, giving \(1.M_2\).
  5. Shift the point \(e\) places (right if \(e > 0\)) and convert.

0x422F0000 decoded this way to 43.75 is in 2026-10-19-floating-point-numbers.

Figure 334: Encoding and decoding are the same four stages walked in opposite directions, shown with 5.75. Encoding (down the left) writes the value in binary and moves the point until one 1 is left in front of it; the sign becomes S, the power of 2 plus 127 becomes E, and the bits after the leading 1 become M, padded with zeros on the right; the 32 bits are then grouped in fours for hex. Decoding (up the right) undoes each step: expand every hex digit to four bits, cut the bits 1 / 8 / 23, take 127 off E and put the hidden 1 back, and shift the point. The one extra step is on the way up: an exponent field of all 0s or all 1s is not a normal number and has to be read as a special value instead.

Worked: 0x41200000

What decimal value does the single-precision pattern 0x41200000 hold?

0100 0001 0010 0000 … splits as \(S = 0\), \(E = 10000010_2 = 130\), \(M = 0100\ldots\). So the value is \(+1.01_2 \times 2^{130-127} = 1.01_2 \times 2^3 = 1010_2 = \mathbf{10}\).

Worked: two special patterns

What do 0x80000000 and 0x7F800000 hold?

  • 0x80000000 is 1 00000000 000…0: exponent all 0s and mantissa 0, with the sign set. It is \(-0\), which compares equal to \(+0\).
  • 0x7F800000 is 0 11111111 000…0: exponent all 1s and mantissa 0, sign clear. It is \(+\infty\). Following steps 4 and 5 blindly would give \(1.0 \times 2^{128}\), which is the mistake the special-value check is there to catch.

Special values

The smallest and largest exponent fields are reserved. What a pattern means then depends on whether the mantissa field is zero. The exponent here is the raw field as stored, with no bias taken off, so the reserved values are 0 (all 0s) and the maximum (all 1s, 255 in single precision):

Exponent field (as stored) Mantissa \(= 0\) Mantissa \(\neq 0\)
0 \(\to\) all 0s \(\pm 0\) subnormal numbers
anything else normal numbers normal numbers
maximum \(\to\) all 1s (255 for single, 2047 for double) \(\pm\) infinity \(\pm\) NaN (not a number)

This raw field is often called the unbiased exponent, in the sense that the bias has not yet been subtracted; the true exponent of a normal number is the field minus 127 (or 1023).

Figure 335: What a floating-point pattern means, decided by the stored exponent field (rows) and whether the mantissa field is zero (columns). Every exponent except all 0s and all 1s gives an ordinary normalised number, with the hidden 1 in front of the mantissa. All 0s gives zero, or a subnormal number with a hidden 0 instead of a 1 and the smallest normal exponent, which is 2 to the minus 126 in single precision. All 1s gives infinity, or NaN when any mantissa bit is set. The sign bit applies in every cell, so there are two zeros, two infinities, and NaNs of either sign.

Zero

Zero cannot be normalised (it has no leading 1), so it gets its own pattern: every exponent and mantissa bit 0. Because the sign bit is separate there are two of them, \(+0\) (0x00000000) and \(-0\) (0x80000000). They compare equal; the sign survives only in things like \(1 / -0 = -\infty\).

Subnormal numbers

With an all-0s exponent and a non-zero mantissa, the number is subnormal (also called denormal):

\[(-1)^S \times 0.M_2 \times 2^{-126} \quad \text{(single precision)}\]

Two rules differ from normal numbers.

  • The hidden bit is 0, not 1. This breaks the scientific-notation rule of one non-zero digit before the point, on purpose: it lets values smaller than the smallest normal number be held, with fewer significant bits as they shrink.
  • The exponent is \(2^{-126}\), the same as the smallest normal numbers, not \(2^{0-127} = 2^{-127}\) as the excess rule would give. With \(2^{-126}\) the subnormals continue the smallest normal binade at exactly the same spacing, \(2^{-149}\), all the way down to 0, with no gap and no overlap. With \(2^{-127}\) they would be spaced twice as finely and leave a gap below \(2^{-126}\).

The smallest normal single is \(2^{-126} \approx 1.18 \times 10^{-38}\), and the smallest subnormal is \(2^{-23} \times 2^{-126} = 2^{-149} \approx 1.4 \times 10^{-45}\). The effect is easiest to see in quarter precision (figure below).

Infinity

All-1s exponent, zero mantissa: \(\pm\infty\). It is the result when

  • a number is too big to store: anything past the largest finite value (about \(3.4 \times 10^{38}\) for single) overflows to \(\infty\);
  • a calculation is mathematically infinite: \(1 \div 0 = +\infty\), \(-\log 0 = +\infty\) (\(\log 0 = -\infty\)), \(\tan(\pi/2)\).

On the last: in practice tan(M_PI/2) returns a large finite number, about \(1.6 \times 10^{16}\) in double, because \(\pi/2\) itself cannot be stored exactly and the tangent of the stored value is merely huge.

Infinity behaves sensibly in further arithmetic: \(\infty + 1 = \infty\), \(1 / \infty = 0\), $-< $ every finite number.

NaN

All-1s exponent, non-zero mantissa: NaN, not a number. It is the result of an operation with no meaningful answer:

  • \(0 \div 0\), \(0 \times \infty\), \(\infty - \infty\);
  • \(\sqrt{-1}\), \(\log(-1)\), \(\sin^{-1} 20\) (no real angle has a sine of 20);
  • \(0^0\), as an indeterminate form. IEEE 754’s powr(0, 0) gives NaN; C’s pow(0, 0) returns 1 by convention.

A NaN propagates: any arithmetic with a NaN operand gives NaN, so one bad step poisons everything computed from it, and the NaN at the end shows something went wrong. There are a few exceptions, functions whose answer does not depend on the missing value: pow(NaN, 0) is 1, and fmax(NaN, 3) is 3. Comparisons do not produce NaN at all; they return false. In particular x == x is false when x is NaN, which is the standard test for one (or isnan(x) in C). With 23 mantissa bits there are \(2^{23} - 1\) different NaN patterns per sign, all meaning NaN.

Figure 336: How one NaN poisons a calculation, in the quadratic formula with a = b = c = 1, which has no real root. Arrows show which results feed which operation. The discriminant b squared minus 4ac is -3, an ordinary number. Its square root has no real answer, so that operation creates a NaN. Every operation that then takes the NaN as an operand gives NaN too, so the sum and the final division are NaN. The branch that never touches it, 2a, is still 2. The NaN that comes out at the top is the signal that something went wrong further down. Comparisons are the exception: they do not give NaN but false, so result == result is false for a NaN.

Finite precision

A float has a fixed number of mantissa bits, so most real numbers cannot be represented exactly and are rounded to the nearest value that can (ties go to the neighbour whose last mantissa bit is 0, “round half to even”). The error is relative: single precision keeps 24 significant bits, about 7 decimal digits, wherever the point is; double keeps 53, about 16.

Rounding happens after every operation, and that changes the arithmetic rules.

Division and multiplication need not undo each other. \(10 \div 3 = 3.333\ldots = 11.010101\ldots_2\), which repeats for ever and has to be cut short. In 3-digit decimal the same thing gives \(10 \div 3 = 3.33\) and \(3.33 \times 3 = 9.99 \neq 10\). Whether the binary version lands back on 10 depends on how the roundings fall: for \(10 \div 3 \times 3\) they happen to cancel in single and double, but \((1 \div 41) \times 41 = 0.99999994\) in single, and \((1 \div 49) \times 49 = 0.9999999999999999\) in double. So \((x \div y) \times y\) may not equal \(x\), and code should never test floats for exact equality after arithmetic; it should test whether they are within a tolerance.

The order of operations matters. This is often put loosely as floating point being occasionally non-commutative. Strictly, addition is still commutative (\(a + b = b + a\) always); what fails is associativity: \((A + B) + C\) need not equal \(A + (B + C)\), because the two orders round different intermediate results. In double, \((0.1 + 0.2) + 0.3 = 0.6000000000000001\) while \(0.1 + (0.2 + 0.3) = 0.6\). The order of a long sum changes its answer.

Absorption

If \(X \gg \delta\), then \((X + \delta) - X\) can be 0. Near \(X\) the representable values are spaced by about \(X \times 2^{-23}\) (single). If \(\delta\) is less than half that gap (or exactly half, when the tie goes to \(X\)), \(X + \delta\) rounds straight back to \(X\), and subtracting \(X\) leaves nothing: \(\delta\) has been absorbed.

  • Single precision: \(2^{24} = 16\,777\,216\), and the gap there is 2. So \(2^{24} + 1\) is a tie between \(16\,777\,216\) and \(16\,777\,218\), rounds to the even one, and \((2^{24} + 1) - 2^{24} = 0\). The same happens with \(10^8 + 1 - 10^8\).
  • It also breaks associativity: \((2^{24} + 1) + 1 = 2^{24}\), since each 1 is absorbed in turn, but \(2^{24} + (1 + 1) = 2^{24} + 2\).

So adding many small numbers to a large total can lose them all; adding the small ones together first keeps them.

Figure 337: Absorption, shown on the quarter-precision values between 8 and 24. Between 8 and 16 neighbouring values are 1 apart, so 8 + 1 = 9 is exact. Between 16 and 32 they are 2 apart, and 16 + 1 = 17 falls exactly halfway between 16 and 18. The tie goes to the neighbour whose last mantissa bit is 0: 16 has mantissa field 000 and 18 has 001, so 16 + 1 rounds back to 16 and (16 + 1) - 16 = 0. The same thing happens in any format whenever the number added is less than half the gap at the size of the larger number, or exactly half with the tie going back down.

The formats compared

IEEE 754 defines a family of binary formats that differ only in field widths. Each follows the same rules: bias \(2^{k-1} - 1\) for a \(k\)-bit exponent, hidden 1, the same special values. With \(k\) exponent bits and \(m\) mantissa bits:

  • the next value after 1 is \(1 + 2^{-m}\), the precision near 1;
  • the largest finite value is \((2 - 2^{-m}) \times 2^{\text{bias}}\): all-1s mantissa, the exponent field one below all 1s.
Quarter Half Single Double Quadruple Octuple
Total bits 8 16 32 64 128 256
Sign bits 1 1 1 1 1 1
Exponent bits 4 5 8 11 15 19
Mantissa bits 3 10 23 52 112 236
Bias 7 15 127 1023 16383 262143
Next after 1 \(1 + \tfrac18 = 1.125\) \(1 + \tfrac1{1024} \approx 1.001\) \(1 + 2^{-23}\) \(\approx 1 + 1.2 \times 10^{-7}\) \(1 + 2^{-52}\) \(\approx 1 + 2.2 \times 10^{-16}\) \(1 + 2^{-112}\) \(\approx 1 + 1.9 \times 10^{-34}\) \(1 + 2^{-236}\) \(\approx 1 + 9.1 \times 10^{-72}\)
Maximum 240 65504 \(\approx 3.4 \times 10^{38}\) \(\approx 1.8 \times 10^{308}\) \(\approx 1.2 \times 10^{4932}\) \(\approx 1.6 \times 10^{78913}\)
Use ultra rare rare common common rare ultra rare

Quarter precision is not one of the standard’s formats. It is an 8-bit format built by the same rules (1 sign, 4 exponent, 3 mantissa bits, bias 7), small enough to list every value (below). Half precision appears in graphics and machine learning, where memory matters more than digits; single and double are what ordinary code uses.

The maximum grows with the exponent width and the precision with the mantissa width. Each extra exponent bit doubles the bias and so roughly squares the maximum: \(2^{8} \to 2^{16} \to 2^{128} \to 2^{1024}\) as the exponent goes 4, 5, 8, 11 bits. The quarter maximum is \(1.875 \times 2^7 = 240\) and the half maximum \((2 - 2^{-10}) \times 2^{15} = 65504\).

Figure 338: The six formats drawn to one scale, one bit per unit of length, with the sign in red, the exponent in green and the mantissa in blue. As the formats double in size, nearly all of the new bits go to the mantissa: the exponent only grows from 4 to 19 bits while the mantissa grows from 3 to 236. A few exponent bits already give an enormous range, because each one doubles the largest power of 2; the precision needs many more bits, because each mantissa bit only halves the gap between neighbouring values.

Every quarter-precision value

Quarter precision has only 256 patterns, so every value can be listed. Each row is a sign bit (0 here) and a 4-bit exponent field; each column is the 3-bit mantissa field. A normal row with stored exponent \(E\) holds \(1.M_2 \times 2^{E-7}\). The first row (in italics) is the subnormals, \(0.M_2 \times 2^{-6}\), and the last row is infinity and NaN. The negative values are the same table with the sign bit set.

Sign, exponent …000 …001 …010 …011 …100 …101 …110 …111
0 0000 0 0.001953125 0.00390625 0.005859375 0.0078125 0.009765625 0.01171875 0.013671875
0 0001 0.015625 0.017578125 0.01953125 0.021484375 0.0234375 0.025390625 0.02734375 0.029296875
0 0010 0.03125 0.03515625 0.0390625 0.04296875 0.046875 0.05078125 0.0546875 0.05859375
0 0011 0.0625 0.0703125 0.078125 0.0859375 0.09375 0.1015625 0.109375 0.1171875
0 0100 0.125 0.140625 0.15625 0.171875 0.1875 0.203125 0.21875 0.234375
0 0101 0.25 0.28125 0.3125 0.34375 0.375 0.40625 0.4375 0.46875
0 0110 0.5 0.5625 0.625 0.6875 0.75 0.8125 0.875 0.9375
0 0111 1 1.125 1.25 1.375 1.5 1.625 1.75 1.875
0 1000 2 2.25 2.5 2.75 3 3.25 3.5 3.75
0 1001 4 4.5 5 5.5 6 6.5 7 7.5
0 1010 8 9 10 11 12 13 14 15
0 1011 16 18 20 22 24 26 28 30
0 1100 32 36 40 44 48 52 56 60
0 1101 64 72 80 88 96 104 112 120
0 1110 128 144 160 176 192 208 224 240
0 1111 Inf NaN NaN NaN NaN NaN NaN NaN

What the table shows:

  • Each row is a binade, the values from one power of 2 up to the next, and it holds eight equally spaced values. The spacing doubles from each row to the next: \(\tfrac18\) between 1 and 2, \(\tfrac14\) between 2 and 4, and 16 between 128 and 240. The relative precision is the same in every row, which is the whole point of floating point.
  • Exponent field 0111 is the row of 1, because \(7\) is the bias: \(2^{7-7} = 1\).
  • Counting up through the patterns counts up through the values, row by row (why this order).
  • The subnormal row has the same spacing as the row after it, \(\tfrac1{512}\), and reaches down to 0. That is the effect of giving subnormals the exponent \(2^{-6}\) rather than \(2^{-7}\).
  • The largest finite value is 240, and the next pattern up is infinity. Anything at or above 248, halfway from 240 to the next step, overflows.
  • Not every whole number is here. 17, 19 and 33 are missing; between 16 and 32 only the even numbers can be held.

Figure 339: The positive quarter-precision values on a number line. Top: 0 to 16 to scale. Every binade from one power of 2 to the next holds eight evenly spaced values, so the gap doubles at each power of 2, from 1/8 between 1 and 2 to 1 between 8 and 16, and the values crowd together towards 0. Bottom: the stretch from 0 to 1/16 magnified 256 times, so that 1/16 lands directly under 16. The subnormals (exponent field 0000) fill the space below the smallest normal value, 1/64, with the same gap of 1/512 as the first normal binade, so the spacing carries on evenly down to 0 instead of leaving a hole.

Worked: rounding in quarter precision

In quarter precision, what are \(16 + 1\), \(13 \div 3\), and then that quotient times 3?

  • \(16 + 1\). Between 16 and 32 the values are 2 apart. 17 is exactly halfway between 16 (mantissa 000) and 18 (mantissa 001); the tie goes to the even mantissa, 16. The 1 has been absorbed.
  • \(13 \div 3 = 4.333\ldots\) Between 4 and 8 the values are 0.5 apart, and 4.333 is nearer 4.5 than 4. So the quotient is 4.5.
  • \(4.5 \times 3 = 13.5\). Between 8 and 16 the values are 1 apart, and 13.5 is a tie between 13 (101) and 14 (110); it goes to the even mantissa, 14. So \((13 \div 3) \times 3 = 14\), not 13.

Floating point in C and on the AVR

C has two floating-point types, float and double. They are usually IEEE single and double precision, but the C standard only sets minimums. Simplified:

  • float must represent numbers up to \(10^{37}\) while keeping 6 decimal digits of accuracy;
  • double must represent numbers up to \(10^{37}\) while keeping 10 decimal digits, and must not be less accurate than float.

Single precision meets the first easily (about 7 digits, up to \(3.4 \times 10^{38}\)), and double the second (about 16 digits).

On the AVR, avr-gcc makes double the same as float: 32-bit single precision. That is strictly against the standard, since single precision has about 7 digits, not 10. A program that moves to the AVR from a desktop and relies on double silently loses half its digits (c-language-basics).

GCC also offers _Float16 and __float128, for half and quadruple precision, on targets that support them. There is no C type for quarter or octuple precision.

Prefer integer arithmetic

The AVR has no floating-point hardware. Its only data type in hardware is the 8-bit integer (instruction-set-architecture), so every float operation is a call to a library routine that unpacks the fields, aligns, adds or multiplies the mantissas with integer instructions, renormalises, rounds and checks for special values. Compare two lines that give the same result for every input:

PORTB = PINA / 3;        /* integer division:  about 8 instructions, no branches */
PORTB = PINA * 0.334f;   /* floating point:    300+ instructions, with branches   */

The second converts the byte to a float, calls the software multiply, and converts the result back, and each of those steps is a routine full of tests and loops. Its running time also varies with the input, which matters in an interrupt handler or a timing loop. The first needs no library at all: a compiler turns division by a constant into a multiplication by a fixed-point reciprocal and a shift. One way for a byte: \(x \div 3 = (x \times 171) \gg 9\), since \(171/512 = 0.33398\ldots\) is just above \(\tfrac13\), and this gives exactly \(\lfloor x/3 \rfloor\) for every \(x\) from 0 to 255. (Checking all 256 inputs also confirms that truncating PINA * 0.334f gives the same answers.)

Figure 340: Why the two lines differ so much in cost on the AVR. Dividing a byte by 3 can be done with the hardware 8-by-8 multiply and a shift: multiply by 171 and shift right 9 places, which is the same as taking the high byte of the product and shifting it once more. That is a few instructions with no branches, taking the same time for every input. The float version has no hardware to use. The byte is first converted to a float, which means finding its leading 1 and building the sign, exponent and mantissa fields. The multiply is a library routine that unpacks both operands, tests for special values, multiplies the 24-bit mantissas with 8-bit multiplies, adds the exponents and takes off one bias, then normalises, rounds and packs the result. A third routine converts back to an integer. Each step is a loop or a chain of tests, so the time also depends on the value.

So on a small microcontroller, work in integers or fixed-point-numbers wherever the result can be the same: scale a value so that the fraction becomes whole numbers (millivolts instead of volts, tenths of a degree), and divide or shift at the end.

Common mistakes

  • Normalising binary to \([1, 10)\). In binary the mantissa must be in \([1, 2)\): \(3.985 \times 2^{77}\) is not normalised; \(1.993 \times 2^{78}\) is.
  • Storing the hidden 1. The mantissa field holds only the bits after the point.
  • Using a bias of 128. IEEE single is excess-127 and double excess-1023, one less than the \(2^{k-1}\) of plain excess notation.
  • Forgetting the bias when decoding. An exponent field of 132 means \(2^5\), not \(2^{132}\).
  • Padding the mantissa on the left. The zeros go on the right; they are fraction bits.
  • Decoding special patterns as normal numbers. Check the exponent for all 0s or all 1s first: 0x7F800000 is infinity, not \(2^{128}\).
  • Treating a subnormal’s exponent as \(2^{-127}\). It is \(2^{-126}\), with a hidden 0.
  • Testing floats for equality. After any arithmetic, compare with a tolerance; 0.1 is not exactly 0.1 to begin with.
  • Assuming addition is associative. The order of a sum can change its result, and a small term can vanish into a large one.
  • Expecting 64 bits from double on the AVR. It is 32.
  • Using floats on the AVR where integers would do. It costs hundreds of instructions per operation.

See also

Instruction Set Architecture

The layer where software meets hardware: what a machine instruction is, what an ISA specifies, and why assembly language exists. See cpu-organisation for the hardware below this line and avr-instructions for a real instruction set.

Machine instructions

A machine instruction is a pattern of bits. 0000 1101 0111 0111 is a valid Atmel AVR instruction. Instructions typically consist of two things:

  • Opcode (operation code) — defines the operation, e.g. addition.
  • Operands — what is being operated on, e.g. particular registers or a memory address.

So one word of machine code says what to do and what to do it to, packed into fixed bit fields. Which bits mean which is entirely a matter of convention — and that convention is the ISA.

The ISA

An Instruction Set Architecture is a specification — i.e. a document. It specifies the interface between hardware and software.

Figure 341: The ISA as an interface. Software above the line is written and compiled without knowing how the hardware works; hardware below the line is designed without knowing what program will run. The only thing both sides must agree on is which bit patterns mean what — and that agreement is a document, not a circuit.

The point of drawing it as a line is that the ISA is the only thing the two sides have to agree on. A compiler writer needs the ISA and nothing else about the chip; a chip designer needs the ISA and nothing else about the programs that will run.

Microarchitecture

Microarchitecture = the architecture of the control unit — i.e. the state machine (gates and flip-flops etc.) that implements the control unit.

This is the same state-machines material from earlier in the course, applied at the scale of a whole processor: the control unit is a state machine whose job is to emit the right control signals, in the right order, for whatever the instruction register holds.

ISA vs microarchitecture

One ISA can be implemented by many different microarchitectures. The specification says what the bit patterns mean; it does not say how a chip must go about honouring them.

ISA Implemented by
8086 many processors, in different ways
Pentium Pentium … Pentium IV … Core2Duo … i7 (each in different ways), various AMD devices, and other manufacturers

This is why a program compiled decades ago still runs: the ISA held still while the microarchitecture beneath it was rebuilt many times over.

What makes an ISA?

Four things:

  1. Memory models
  2. Registers
  3. Instructions
  4. Data types

If you know all these details, you can write machine code that runs on the CPU and build the CPU.

This is the completeness test for a specification: both sides of the line in Figure 341 have to be constructible from the document alone, and nothing else about the chip may be needed by either.

1. Memory models

How does memory look to the CPU? Four issues decide it — addressable cell size, alignment, address spaces and endianness — treated in full in memory-models.

2. Registers

Two types of register:

  • General purpose — used for temporary results etc. On AVR, r0–r31.
  • Special purpose, e.g.
    • Program Counter (PC)
    • Stack pointer (SP)
    • Input/Output registers — 224 of them on the ATmega324A, see avr-io-ports
    • Status register — N, Z, C, V among others. Tanenbaum calls this the Program Status Word.

Some other registers are part of the microarchitecture, NOT the ISA — e.g. the Instruction Register (IR). The programmer doesn’t need to know about these, and can’t directly change or use them.

That distinction is the cleanest illustration of what an ISA actually is. The IR unquestionably exists and holds the instruction being executed (fetch-decode-execute-cycle) — but no instruction names it, so it is invisible to software and a chip designer is free to change or remove it. The PC is the opposite case: jmp writes it, so it has to be in the specification. Existing in the hardware is not the criterion; being reachable from an instruction is.

Figure 342: The same interface line as in the previous figure, with the machine’s registers sorted across it. The five above the line are part of the ISA; four of them carry an example of an instruction that names the register, and the SP box carries none. The single box below, the IR, is part of the microarchitecture only. Nothing about a register’s size or importance decides which side it lands on — only whether some instruction can refer to it.

The AVR’s own answer to this pillar — the regularity of r0–r31, the r16–r31 exception, and the X/Y/Z pointer pairs — is in avr-architecture.

3. Instructions

This is the main feature of an ISA. Instruction types include:

Type Does
Input/Output communicate with I/O devices/ports
Load/Store move data from/to memory
Move copy data between registers
Arithmetic addition, subtraction, …
Logical Boolean operations
Branching for deciding which instruction to perform next

The Input/Output row is the one where the AVR’s answer is least obvious. The ATmega324A’s 224 I/O registers are all reachable by ld/st at their data-memory addresses 32 to 255 ($20 to $FF), but only the first 64 also get the short in rd, P / out P, rr form that names an I/O register by its own number P — because P is a six-bit field and \(2^6 = 64\). The other 160, the “extended” I/O registers, can only be reached the long way. The mechanics, the numbering offset and the register list are in avr-io-ports.

With arithmetic and logical merged, the same set can be cut the other way instead — by how many operands an instruction takes:

  • Dyadic — two operands, one result
  • Monadic — one operand, one result

And instructions use various addressing modes: how an operand says where its value is, covered in addressing-modes.

The AVR instructions met so far, sorted into these boxes, are in avr-instructions.

4. Data types

Numeric

  • Integers of different lengths (8, 16, 32, 64 bits), possibly signed or unsigned
  • Floating point numbers, e.g. 32 bits (single precision) or 64 bits (double precision)
  • Many others not listed

Non-numeric

  • Boolean (0 means false, 1 means true) — stored in a whole byte or word
  • Bit-map (collection of Booleans, e.g. 8 in a byte)
  • Characters
  • Pointers (memory addresses)

Different machines provide hardware support for different data types. Two ends of the range:

Intel-64 Architecture

Data type 8 bits 16 bits 32 bits 64 bits 128 bits
Signed integer \(\checkmark\) \(\checkmark\) \(\checkmark\) \(\checkmark\)
Unsigned integer \(\checkmark\) \(\checkmark\) \(\checkmark\) \(\checkmark\)
BCD integer \(\checkmark\)
Floating point \(\checkmark\) \(\checkmark\)

Atmel AVR

Data type 8 bits 16 bits 32 bits 64 bits 128 bits
Signed integer \(\checkmark\)
Unsigned integer \(\checkmark\)
BCD integer
Floating point

The only data type an AVR supports in hardware is an 8-bit integer, signed or unsigned. There is no 16-bit integer type, no floating point, no BCD.

Other data types can be supported through software! e.g. 16-bit integer operations can be built out of 8-bit operations, using a sequence of instructions — which is exactly what the two-instruction 16-bit addition in avr-instructions does. So the hardware/software line here is about cost, not possibility: anything missing from the table can still be computed, it just takes more instructions and more cycles. Floating point is the costly case: one float multiply is hundreds of instructions (floating-point-numbers), which is why fractions on the AVR are usually kept as fixed-point-numbers.

Assembly language

Machine code is too hard to program in. Assembly language is used instead:

  • Human readable (just!).
  • Converted into machine code by software called an assembler.

Two Atmel AVR examples:

Assembly Meaning
add r3,r4 r3 ← r3 + r4
inc r22 r22 ← r22 + 1

The important structural detail is in the arrows of Figure 341: a high-level language compiles one-to-many — one line of C becomes however many instructions it takes — whereas assembly assembles one-to-one. Each assembly instruction is one machine instruction, written in a form a person can read. That is the whole of what an assembler buys you, and it is why assembly is still “programming the machine” in a way C is not.

The toolchain

For CSSE2010 the assembler is Microchip Studio, and two supplied tutorials walk through it end to end: Intro to Microchip Studio (create an assembler project, pick the device, edit, build, and step through the simulator) and Microchip Studio C Tutorial (the same for a GCC C project). Both are click-through guides to follow at the machine rather than material to learn — they are on Blackboard, and the labs are where they get used.

See also

The I/O Board

The I/O board in the lab kit carries the input and output devices you wire your breadboard circuits to, for experimenting with simple digital circuits. It plugs directly onto the breadboard, and adds a logic probe for debugging and a UART serial interface for talking to other devices.

It is powered from a single USB connection and has current-sense circuitry that detects short circuits and protects your designs.

Pin numbers for every device are in device-pinouts; the kit itself is loaned out in week3-lab-logisim-and-flip-flops. Two more parts of the kit that are used alongside the board, the joystick and the LED matrix, are described at the end.

What’s on it

1. USB connector 2. Power LED 3. Power switch 4. 7-segment display
5. Switches 6. LEDs 7. Buttons 8. UART transmit/receive LEDs
9. Logic probe indicator LEDs 10. Fault LED 11. VCC / GND headers 12. I/O device headers
13. Auxiliary power connector 14. High current mode jumper

Items 13 and 14 are the auxiliary power connector and the high-current-mode jumper. The one extra power connection the labs use is connector J1, which powers the LED matrix in Lab 16 (below).

The board at a glance

The board is a C shape: a left-hand spine carrying the USB connector, the power switch, the two status LEDs and the seven-segment display, plus a top arm and a bottom arm that straddle the breadboard’s central channel. All the I/O devices come out on the two 16-pin headers on the inner edges of those arms, and every device is reached through the column of breadboard holes directly above or below its printed label.

Figure 343: A plan view of the board, not to scale, with the parts on the left spine placed roughly. Each I/O device sits on one pin of one of the two 16-pin headers, and the column of breadboard holes at that pin is how you reach it. The board itself prints only the two end markers, a bold 32 at the left of the top header and a bold 1 at the left of the bottom one. The small numbers at the other pins are their pin numbers, the ones a schematic uses. The connection drawn in the notch is an example: switch S0 to pin 13 of a chip, LED L0 to pin 11.

Two things about the numbering are worth fixing in your head before you wire anything:

  • The top header counts down, left to right. Its leftmost pin is 32 and its rightmost is 17, so the switches run S7…S0 and then the LEDs L7…L0 as you read left to right. That is the opposite of the reading order you would guess from the pin numbers alone.
  • The bottom header counts up, left to right, pin 1 to pin 16: TX RX CC DP G F E D C B A B3 B2 B1 B0 PR. The middle nine of those are the seven-segment display — CC its common cathode, DP its decimal point, and G down to A its seven segments — which is why nine consecutive pins carry single-letter names.

VCC and GND pads sit at the far right of both arms, which is where the breadboard’s power rails get fed from.

Setup

Insert the board into the breadboard, aligning the downward-facing headers with the right holes.

If aligned correctly, the I/O board should not require excessive force to insert.

Connect a micro-USB cable to the connector at the top-left corner.

DO NOT STORE THE BOARD WITH THE USB CABLE ATTACHED — THIS MAY CAUSE THE USB CONNECTOR TO BREAK OFF!!

The USB connector is the part people break.

Turn the board on by sliding the PWR switch up to ON; the red power LED should light. Then check the orange FAULT LED does not light. If it does, power off immediately.

The fault LED

The board uses a current-limited power switch to protect itself and anything it powers from short circuits. A short lights the orange FAULT LED.

If it’s on: push PWR down to OFF immediately, and check your design for shorts before restoring power.

WARNING! In the case of a short circuit, the current-limiting switch may become extremely hot.

Switches, LEDs and buttons

All the I/O devices are reached through the breadboard holes directly above or below the printed label on the board:

  • Switches — S0 … S7 (pins 25–32)
  • LEDs — L0 … L7 (pins 17–24)
  • Buttons — B0 … B3 (pins 15 down to 12)

Connect one by running a wire from the column of breadboard terminals above/below the label to wherever it’s needed. An example, drawn into the notch of Figure 343: S0 to pin 13 of an external device, L0 to pin 11.

Switches and buttons are inputs to your circuit, LEDs and the seven-segment display are outputs from it — which is the distinction the pentagon symbols in circuit-schematics make, and getting it backwards is one of the common errors listed there.

The logic probe

Attach a wire to the column of terminals above the PR label — pin 16, the rightmost pin of the bottom header. Touch the free end to any point in the circuit and the HI / LO LEDs show the logic state there.

As circuits increase in complexity, so does the necessity of having a clear strategy — probing random points in a large circuit rarely reveals the location of errors.

Suggested troubleshooting strategy

  1. Check the FAULT light is not on, which would indicate a short circuit.
  2. Probe VCC and GND at every device in your circuit, to confirm each one is actually powered.
  3. Start at the inputs and move logically through to the outputs. Pen and paper helps: write down the expected state at each point first, then verify it with the probe. A schematic and a truth table are great for this.

The key to any successful debugging strategy is to assume nothing, know what to expect before you begin testing, and have a plan.

Step 2 is the one worth internalising — an unpowered chip looks exactly like a wrong-logic chip until you probe its power pins, and grouped VCC/GND entries on a schematic (see circuit-schematics) make it easy to forget one.

Electrical characteristics

VCC 5 V
GND 0 V
Logic high > 3.5 V
Logic low < 1.5 V

The gap between 1.5 V and 3.5 V is undefined, which is why a floating pin can read as either (week3-lab-logisim-and-flip-flops). What the logic probe shows for a voltage inside that band is not documented.

The joystick

The kit’s two-axis joystick is a small board of its own, made to sit in the breadboard next to the I/O board. Each axis is a potentiometer between its own supply pin and ground, and the stick moves the wiper. So each axis gives a voltage that follows the stick across its travel, from 0 V at one side to 5 V at the other, for the A/D converter to read (analog-to-digital-conversion).

Pin What it is Connect to
L/R+ top of the left-right potentiometer VCC
U/D+ top of the up-down potentiometer VCC
GND ×2 bottom of both GND, either one
L/R ×2 x: 0 V with the stick to the left, 5 V to the right an analog input, either one
U/D ×2 y: 0 V at the bottom, 5 V at the top an analog input, either one
  • The doubled pins are joined on the board. One wire to each of L/R, U/D and GND is enough.
  • The two + pins are separate. Both have to go to VCC, or one axis has nothing to divide.
  • Left, right, up and down are the joystick’s own, marked by the X and Y arrows printed on it. Placed at the right-hand end of the breadboard, with room for the microcontroller board and programmer to its left, the X arrow points to the top of the breadboard and the Y arrow to the left.
  • A potentiometer’s wiper is a weak source. Anything that draws current from it, an LED for instance, pulls its voltage away from the stick’s position. LEDs make a quick wiring test, but they must come off before the converter is used.
  • Keep the black foam that protects the pins when the joystick is put away.

Figure 344: The joystick’s eight pins, seen from above with the board placed as it sits in the breadboard, its X arrow pointing to the top. The pins near each corner come in twos. The dashed lines join the pins that are connected on the board itself: the two L/R pins, the two U/D pins and the two GND pins, so one wire to each pair is enough. The two supply pins, U/D+ at the top left and L/R+ at the bottom left, are not joined, and both go to VCC. L/R carries x and U/D carries y to the analog inputs.

The LED matrix

The LED matrix is a display of 16 columns by 8 rows, each pixel a red LED and a green LED together. It is driven over SPI: the AVR is the master and the matrix a slave that takes commands one byte at a time (avr-spi).

Connecting it

It has two headers:

  • K1, two pins, is its power. A two-wire lead joins it to the I/O board’s connector J1, VCC on J1’s left pin and GND on its right.
  • K2, four pins, is the SPI connection, to the AVR’s SPI port on PB7 to PB4: SCK on PB7, MISO on PB6, MOSI on PB5 and \(\overline{\text{SS}}\) on PB4. Match the order of the pins on K2 against the datasheet before plugging the lead in.

The Err state. PB7 to PB5 are also the pins the programmer uses to load the AVR, so programming sends the matrix a stream of what look to it like garbage commands, and it can show Err. Holding the AVR’s reset button down for at least half a second after programming clears it before the program starts.

What to send it

Every message starts with a command byte. Two commands are enough to draw anything:

Command Bytes Does
clear 0x0F every pixel off
set one pixel 0x01, position, colour sets one pixel to a colour
  • Position byte: (y << 4) | x. The row y, from 0 at the bottom to 7 at the top, is the high nibble. The column x, from 0 at the left to 15 at the right, is the low nibble.
  • Colour byte: (green << 4) | red. Each nibble is a brightness from 0 to 15. Red alone is 0x0F, green alone 0xF0, both full is yellow, 0xFF, and full red with half green is orange, 0x7F.

The matrix’s reference manual is the full description of the commands it accepts.

Figure 345: How a pixel is addressed and coloured. The matrix is 16 columns, x from 0 to 15 left to right, by 8 rows, y from 0 to 7 bottom to top. A position byte puts y in its high nibble and x in its low one, so the pixel at x = 4, y = 2 is 0x24. A colour byte puts the green brightness in its high nibble and the red in its low one, each 0 to 15. The swatches show what some colour bytes look like: the colours here are the light from the red and green LEDs mixed.

Lab 16 works through the commands and uses them for a demo, a scrolling marquee across two matrices and an Etch-A-Sketch (week10-lab-adc-and-spi).

See also

Logic Gates

Every logic gate has one or more inputs and exactly one output, and can be described four equivalent ways: logic symbol, truth table, Boolean expression, timing diagram (see timing-diagrams for the last of these, and for real-gate propagation delay / rise / fall times).

Gates sit at the bottom of the abstraction stack — the digital logic level, level 0 (see 2026-07-27-course-intro-bits-bytes-binary). A digital circuit only ever carries two logic levels: logic ‘0’ is usually a small voltage (around 0 V) and logic ‘1’ a larger one (e.g. 0.8 V to 5 V, depending on the logic family — the type and size of the transistors the gate is built from). Because inputs and outputs have only these two states, they can equivalently be called true and false.

The 7 basic gate types

Figure 346: The seven basic gates, with the distinguishing symbol and Boolean expression for each. NOT, AND and OR are the three base shapes; NAND, NOR and XNOR are those same bodies with an inversion bubble on the output, and XOR/XNOR add a second arc across the back of the OR body.

Gate Behaviour Truth table (\(A,B \to X\))
NOT (inverter) Inverts the input 0→1, 1→0
AND Output is HIGH when all inputs are HIGH 00→0, 01→0, 10→0, 11→1
OR Output is HIGH when at least one input is HIGH 00→0, 01→1, 10→1, 11→1
NAND Output is HIGH when at least one input is LOW 00→1, 01→1, 10→1, 11→0
NOR Output is HIGH when all inputs are LOW 00→1, 01→0, 10→0, 11→0
XOR Output is HIGH when exactly one input is HIGH 00→0, 01→1, 10→1, 11→0
XNOR Output is HIGH when the inputs are the same 00→1, 01→0, 10→0, 11→1

Useful to remember: XOR is the odd function, XNOR is the even function.

Deriving the inverting gates from the base gates

The quickest way to fill in a NAND/NOR/XNOR truth table is not to memorise it, but to write the underlying AND/OR/XOR column first and then invert it row by row — the “N” prefix is exactly one inversion on the output:

\(A\) \(B\) AND NAND OR NOR XOR XNOR
0 0 0 1 0 1 0 1
0 1 0 1 1 0 1 0
1 0 0 1 1 0 1 0
1 1 1 0 1 0 0 1

More than two inputs

A gate of \(n\) inputs has a truth table of \(2^n\) rows — two inputs give \(2 \times 2 = 4\) rows, three inputs give 8. The “at least one / all” wordings above carry over unchanged to more inputs; the XOR/XNOR wordings do not, and must be restated in terms of parity:

  • XOR output is HIGH when an odd number of inputs are HIGH (the odd function). For two inputs this collapses to “exactly one”, which is why the 2-input wording works.
  • XNOR output is HIGH when an even number of inputs are HIGH (the even function).
\(A\) \(B\) \(C\) 3-input AND 3-input NAND 3-input XOR
0 0 0 0 1 0
0 0 1 0 1 1
0 1 0 0 1 1
0 1 1 0 1 0
1 0 0 0 1 1
1 0 1 0 1 0
1 1 0 0 1 0
1 1 1 1 0 1

Note that the kit of parts used for practicals has no 3-or-more-input gate chips (see device-pinouts) — a 3-input function has to be built from 2-input gates.

Universal (complete) gates

All circuits can be constructed from NAND-only or NOR-only gates — these are called complete (or universal) gates, because NOT, AND, and OR can each be built purely from one gate type:

Figure 347: Why NAND and NOR are complete gates: NOT, AND and OR built from each one alone. Tying both inputs of a NAND or NOR together turns it into an inverter, and everything else follows — AND is NAND then invert, OR is invert-both-inputs then NAND (and the NOR row is the mirror image of that).

  • NOT: a NAND (or NOR) gate with both inputs tied together — \(\overline{A \cdot A} = \bar A\), and \(\overline{A + A} = \bar A\).
  • AND from NAND: a NAND followed by a second NAND wired as an inverter. AND from NOR: invert both inputs first, then NOR them (\(\overline{\bar A + \bar B} = AB\), by De Morgan — see boolean-algebra).
  • OR from NOR: a NOR followed by a NOR-as-inverter. OR from NAND: invert both inputs first, then NAND them (\(\overline{\bar A \cdot \bar B} = A+B\)).

The two rows are De Morgan’s law drawn twice: whenever you push an inversion through a gate, AND and OR swap. NAND and NOR are preferred in practice because they are easier to build from transistors than AND/OR directly.

Gates on ICs

Gates are sold packaged several to an integrated circuit (IC). The 74HCT00 is four independent 2-input NAND gates in one 14-pin DIP package.

Figure 348: Inside the 74HCT00: four independent 2-input NAND gates in a 14-pin package, with the pin each gate terminal is wired to. Pin 14 is Vcc (power, e.g. 5 V) and pin 7 is GND (0 V) — shared by all four gates, so nothing works if either is left unconnected. Gate letters A-D are the labels a schematic uses as U1:A … U1:D.

  • Vcc = power (e.g. 5 V), GND = ground (0 V). One Vcc/GND pair supplies all four gates.
  • Physically: pin spacing is 0.1” along the package and 0.3” across it; the chip is about 15 mm long.
  • The drawing above is the chip’s internal schematic, not a picture of the part — see circuit-schematics for how a chip like this is drawn (and labelled U1:A … U1:D) on a schematic you can actually build from, and device-pinouts for the pinouts of every chip in the course kit.

Magnetic Disks

How a hard disk drive stores data and why reaching it takes milliseconds. This note covers platters, surfaces, heads, tracks, sectors and cylinders; what a sector holds besides data, and how much of a disk is left for files; and the access time of a disk, the sum of the seek time, the rotational latency and the transfer time, with the average worked out for a 7200 rpm disk. Where disks sit among the other memories is in memory-hierarchy-and-cache, and how files are laid out on sectors is in file-systems. First met in 2026-10-22-memory-disks-and-files.

How a hard disk stores data

A hard disk drive (HDD) is a stack of rotating platters, each with a magnetised coating on both faces. A bit is stored as the direction in which a tiny patch of the coating is magnetised: one direction for 1, the other for 0, north pole up or south pole up.

  • The platters spin together on one spindle, continuously, at a fixed speed: 5400, 7200 or 10,000 revolutions per minute are common.
  • Data is written in concentric circles called tracks.
  • A read/write head for each surface floats above it on a cushion of air dragged along by the spinning platter, a few nanometres (of the order of 5 nm) off the surface. It never touches the surface in normal running; if it does, the result is a head crash.
  • Both sides of each platter are usually used, so a disk with \(p\) platters has \(2p\) surfaces and \(2p\) heads.

Figure 349: A cross-section along one track, nowhere near to scale. The magnetised coating is divided into tiny patches, and each stores one bit as the direction it is magnetised: north pole up for a 1, south pole up for a 0. The head flies on a cushion of air about 5 nm above the surface and never touches it. As the platter carries the patches past, the head reads each bit by sensing the direction of its field, or writes one by setting it. The underside of the platter has its own coating and its own head; only the top is drawn.

All the heads are mounted on one arm assembly and move in and out together. Only one head reads or writes at a time.

Figure 350: A disk with four platters seen from the side. Each platter has two recording surfaces, so there are eight, numbered 0 to 7 from the bottom, and one read/write head for each. The heads are all on one comb-shaped arm, so they move in and out together: when one head is over a track, every other head is over the track at the same radius on its own surface. Those eight tracks, outlined by the dashed cylinder, form one cylinder.

Tracks, sectors and cylinders

  • A track is one circle of data on one surface, at one radius.
  • Each track is divided into fixed-length sectors. A sector is the smallest unit of data: the disk always reads or writes a whole sector at a time, typically 512 bytes (4096 on newer disks).
  • A cylinder is the set of tracks at a given radial position, one on each surface.

Cylinders

Because the heads move together, they are always positioned over a whole cylinder. Assuming both sides of every platter are used,

\[\text{tracks per cylinder} = 2 \times \text{number of platters}.\]

The four-platter disk above has \(2 \times 4 = 8\) tracks in each cylinder. Data the disk will need together is best placed in one cylinder: switching between its tracks only means switching heads, electronically, with no arm movement at all.

Figure 351: One surface seen from above. The tracks are concentric circles, and each is divided into sectors, here twelve to a track, which are the smallest units the disk reads or writes. The highlighted ring is one track and the dark patch one sector of it. The head sits on its arm over one track at a time, here the highlighted one; the platter turns beneath it, carrying each sector of that track past in turn. The same track on every surface makes up a cylinder.

What a sector holds

A sector is more than its data. Along the track it is laid out as:

  1. Preamble: a known pattern that lets the head synchronise to the data, finding where the sector starts and the timing of its bits.
  2. Data: the sector’s payload, typically 512 bytes.
  3. Error correction code (ECC): extra bits computed from the data that let small read errors be detected and corrected.
  4. Inter-sector gap: blank space before the next sector’s preamble, a margin for the head and for small speed variations.

The layout follows the same idea as a UART frame (serial-communication): there is no separate clock on the wire or the platter, so something has to announce the start and fix the timing (the start bit; the preamble), the data follows, some redundancy checks it (the parity bit; the much stronger ECC), and a guaranteed idle stretch separates one unit from the next (the stop bits; the gap).

Figure 352: The format of a sector along a track, with a UART frame beneath it for comparison. The preamble lets the head lock on to the timing, the data is the payload, the error-correcting code lets damaged bits be repaired, and the gap separates this sector from the next. A UART frame solves the same problem of sending self-timed data with no clock line, with a start bit, data bits, a parity bit and stop bits; the sector’s ECC is far stronger than parity, which can only detect a single flipped bit.

How much of a disk holds data

The preambles, ECCs and gaps take space on every sector, and the file system’s own tables take more:

  • about 85 % of the raw disk capacity is usable by the operating system; the rest is sector overhead;
  • about 95 % of that is usable for user data; the remaining ~5 % is file-system overhead (file-systems).

So user data gets about \(0.85 \times 0.95 = 0.8075\), roughly 81 % of the raw capacity, and the file system takes \(0.85 \times 0.05 = 4.25\,\%\) of it.

Figure 353: Where a disk’s raw capacity goes. About 15 per cent is spent on each sector’s preamble, error-correcting code and gap, leaving 85 per cent that the operating system can use. The file system’s tables take about 5 per cent of that, 4.25 per cent of the raw capacity, leaving roughly 81 per cent for the files themselves.

Access time

Reading a sector takes three steps, one after another, so

\[\text{access time} = \text{seek time} + \text{rotational latency} + \text{transfer time}.\]

  1. Seek time: the time to move the heads to the right cylinder. It depends on how far the arm has to travel.
  2. Rotational latency: the time spent waiting for the sector to arrive under the head, once the head is on the right track. It depends on where the sector happened to be when the head arrived.
  3. Transfer time: the time for the sector to pass under the head while it is read. One sector is a small fraction of a track, so this is negligible compared with the other two.

Figure 354: Where the three parts of an access come from, on one surface. The head starts over the wrong track. First the arm moves it in or out to the track that holds the wanted sector (1, the seek). The head is then over the right track, but the sector is somewhere else on the circle, so the head waits while the platter turns the sector round to it (2, the rotational latency): anything from no time to a whole turn, half a turn on average. Then the sector passes under the head as it is read (3, the transfer), a small fraction of a turn. The seek is a movement of the arm and the latency a movement of the platter, and the second cannot start being useful until the first has finished, so the times add.

Figure 355: The three parts of a disk access in time order, drawn to scale for the average access of a 7200 rpm disk with a 10 ms edge-to-edge seek. First the arm moves to the right cylinder, 3.33 ms on average; then the head waits for the sector to come round, half a rotation, 4.17 ms on average; then the sector passes under the head, which takes only microseconds and is too thin to see at this scale. Both of the large parts are mechanical, which is why a disk is thousands of times slower than main memory.

Average rotational latency

Let \(T\) be the time for one rotation. When the head arrives on the track, the wanted sector may be just arriving (wait 0) or may have just gone past (wait almost \(T\)), and every position in between is equally likely. The average of a wait spread evenly between 0 and \(T\) is the midpoint,

\[\text{average rotational latency} = \frac{T + 0}{2} = \frac{T}{2},\]

half a rotation.

Average seek time

The edge-to-edge seek time is the time to move from the outermost cylinder to the innermost, the longest possible seek. If seek time is proportional to the number of tracks crossed, the average seek depends on the average distance between where the heads are and where they need to go.

Measure positions as a fraction of the way across the disk, from 0 at one edge to 1 at the other. Take the starting position \(x\) and the target \(y\) as independent and both uniformly random. The distance is \(|x - y|\), and its average is

\[\int_0^1\!\!\int_0^1 |x - y|\,dx\,dy = 2\int_0^1\!\!\int_0^x (x - y)\,dy\,dx = 2\int_0^1 \frac{x^2}{2}\,dx = \frac13.\]

The factor 2 is the symmetry: the region \(y > x\) contributes the same as \(y < x\). So

\[\text{average seek time} = \frac13 \times \text{edge-to-edge seek time}.\]

It is not one half. Half would be right if the heads always started at one edge, but the start is random too. Two random points on a line are on average a third of its length apart: short seeks are much commoner than long ones, because a long seek needs both ends near opposite edges.

Figure 356: Why the average seek is a third of the edge-to-edge seek. If the start and the target are independent and each uniform across the disk, the distance d between them has density 2(1 - d): short seeks are common and a full edge-to-edge seek is rare, because it needs both ends at opposite edges. The balance point of that triangle is at d = 1/3, not 1/2. One half would be the average only if every seek began at an edge.

Worked: average access time of a 7200 rpm disk

What is the average access time for a hard disk which rotates at 7200 rpm and has an edge-to-edge seek time of 10 ms? Assume that seek time is proportional to the number of tracks to seek.

The rotation period. \(7200\) revolutions per minute is

\[\frac{7200}{60} = 120 \text{ revolutions per second}, \qquad T = \frac{1}{120}\text{ s} = \frac{1000}{120}\text{ ms} = 8.33\text{ ms}.\]

Average seek. Seek time is proportional to distance, so the average seek is a third of the edge-to-edge time: \(\frac13 \times 10 = 3.33\) ms.

Average rotational latency. Half a rotation: \(\frac12 \times 8.33 = 4.17\) ms.

Transfer time. Negligible. As a check, if a track held 1000 sectors, one sector would pass in \(8.33\text{ ms} / 1000 = 8.3\ \mu\)s, under 0.2 % of the total.

Total.

\[\text{average access time} = \frac13(10\text{ ms}) + \frac12\left(\frac{1000}{120}\text{ ms}\right) + \text{negligible} = 3.33 + 4.17 = \mathbf{7.5\ ms}.\]

The convention matters. Taking the average seek as half the edge-to-edge time would give \(5 + 4.17 = 9.17\) ms. These notes use one third, because the question says seek time is proportional to the tracks crossed and both the start and the target position are random, and for that the average distance is exactly a third of the way across (Figure 356). Half is the average only for seeks that start from one edge.

A faster disk. At 10,000 rpm, \(T = 60/10{,}000\) s \(= 6\) ms, the average latency is 3 ms, and with the same seek the average access time is \(3.33 + 3 = 6.33\) ms. Spinning faster only shortens the latency; the seek is the arm’s job.

Common mistakes

  • Using the full rotation as the latency. On average the sector is half a turn away: \(T/2\), not \(T\).
  • Using half the edge-to-edge seek as the average. With random start and end positions the average distance is a third of the way across, so the average seek is a third of the edge-to-edge time.
  • Forgetting to convert rpm. Divide by 60 for revolutions per second, then invert for the period, then multiply by 1000 for milliseconds: 7200 rpm is 8.33 ms per turn.
  • Counting a cylinder’s tracks as the number of platters. Each platter has two surfaces, so a cylinder has \(2 \times\) platters tracks.
  • Thinking a disk can read part of a sector. The sector is the smallest unit read or written; changing one byte means rewriting the whole sector.
  • Taking the raw capacity as space for files. About 85 % is usable by the operating system, and about 95 % of that by files.

See also

Memory Hierarchy and Cache

Why a computer has several layers of memory rather than one, and how a cache makes a slow main memory look fast. This note covers the memory hierarchy from registers down to tape, how speed, capacity and cost per bit change from one level to the next, what a cache is and why it works, the three cache levels, and the average access time with a cache. The technologies at each level are in memory-technologies, and the disk level in magnetic-disks. First met in 2026-10-22-memory-disks-and-files.

The memory hierarchy

No single memory is fast, large and cheap at once. Fast memory costs more per bit, so it is built small. Cheap memory is slow, so it is built large. A computer therefore stacks several kinds, with the fastest and smallest next to the processor and the largest and cheapest furthest away.

Level Built from Typical capacity Cost per bit Access time, order of magnitude
Registers (r0 to r31 on the AVR) flip-flops, inside the CPU under a kB highest ~1 ns
Cache (L1, L2, L3) SRAM ~MB high ~10 ns
Main memory DRAM ~GB moderate up to ~1 µs
Magnetic disk (and SSD) magnetic platters, or flash ~TB low ~1 to 10 ms
Tape, optical disk magnetic tape, optical discs ~PB, across a library of them lowest ~100 ms and up; a tape that must wind takes seconds

Going down the hierarchy:

  • capacity grows, from bytes to petabytes;
  • cost per bit falls, from the most expensive to the cheapest;
  • access time grows, by roughly a factor of 10 to 1000 per level.

The CPU works directly only with the top. Data moves up the levels as it is needed and back down when it is not.

Figure 357: The memory hierarchy, with the CPU at the apex. Each level is larger, cheaper per bit and slower than the one above it: registers are under a kilobyte and answer in about a nanosecond, while a tape or optical library holds petabytes and takes a tenth of a second or more. The width of each band suggests its capacity. The cache is itself a small hierarchy of three levels, L1 to L3, drawn as a pyramid within its band. The figures on the right are orders of magnitude, not specifications.

Cache memory

CPUs are faster than main memory. A processor can execute an instruction in well under a nanosecond, while DRAM takes tens to hundreds of nanoseconds or more to answer. Memory as fast as the CPU exists (SRAM), but very fast memory is expensive, so it cannot be the whole of main memory. If the CPU always had to wait for main memory, performance would suffer badly: most of its time would be spent idle.

A cache is the compromise: a small amount of very fast memory combined with the larger, slower main memory. The most commonly used memory words are kept in the cache. On every access the CPU looks in the cache first:

  • if the word is there, a hit, it is returned at cache speed;
  • if not, a miss, it is fetched from main memory over the bus, and a copy is kept in the cache in case it is wanted again.

The average access time is greatly reduced if many words are found in the cache.

Figure 358: A cache between the CPU and the bus. The CPU asks the cache first; only on a miss does the request travel along the bus to the much slower main memory. A loop counter i is the typical resident: the first read of i misses and brings a copy into the cache, and every later read of it, once per iteration, is a hit that never touches the bus.

Why a cache works

A cache only helps if the words a program uses next are mostly the ones it used recently. They are, because programs are repetitive:

  • The same data is used again soon. A loop such as for (i = 0; i < N; i++) { ... } reads and writes i on every iteration. If the loop runs \(10^{20}\) times, i is accessed at least \(10^{20}\) times; only the first of those can miss. Variables in use, the top of the stack, and the loop’s own instructions all behave like this.
  • Neighbouring data is used soon after. Instructions are fetched in sequence, and arrays are walked element by element. A cache fetches a small block of neighbouring words on a miss, so the next few accesses hit.

The first is called temporal locality and the second spatial locality. Together they mean that a cache holding a tiny fraction of main memory can still answer the large majority of accesses.

Cache levels

There are often several levels of cache, each larger and slower than the one before:

Level Where Typical size Speed
L1 inside the CPU itself 32 kB to 128 kB runs at the same speed as the CPU
L2 a separate chip (possibly in the same module), or on the same chip as the CPU 256 kB to 16 MB may be slightly slower than the CPU
L3 on some machines, a third level, usually shared by all the cores 2 MB to 256 MB slower again, still much faster than DRAM

The CPU looks in L1, then L2, then L3, and only then in main memory. The cache is a hierarchy within the hierarchy. Sizes here are in bytes: B is a byte and b is a bit, so 32 kB is \(32 \times 1024 \times 8 = 262{,}144\) bits.

Figure 359: Three levels of cache between the CPU core and main memory. L1 sits inside the core and keeps up with it; L2 is larger and may be slightly slower; L3, on machines that have it, is larger still and usually shared by every core on the chip. A request falls through the levels in order and goes out to DRAM only if all three miss. Each level is roughly ten times the size of the one above it.

Average access time with a cache

Let the cache take \(t_c\), main memory \(t_m\), and let \(h\) be the hit rate, the fraction of accesses found in the cache. The CPU looks in the cache first, so every access pays \(t_c\), and the fraction \(1 - h\) that miss pay \(t_m\) as well:

\[t_{\text{avg}} = t_c + (1 - h)\, t_m.\]

The same thing weighted hit by miss: a hit costs \(t_c\) and a miss \(t_c + t_m\), so \(t_{\text{avg}} = h\,t_c + (1-h)(t_c + t_m)\), which expands to the line above.

If the cache and main memory are searched at the same time instead, a miss costs only \(t_m\) and \(t_{\text{avg}} = h\,t_c + (1-h)\,t_m\). The two differ by \(h\,t_c\), which is small whenever \(t_c \ll t_m\); the first form is used below.

Worked: how much a cache saves

A cache answers in 10 ns and main memory in 1 µs. What is the average access time with no cache, and with a cache whose hit rate is 90 %, 95 % and 99 %?

No cache. Every access goes to main memory: 1000 ns.

With the cache, \(t_{\text{avg}} = 10 + (1 - h) \times 1000\) ns:

Hit rate \(h\) Misses \(t_{\text{avg}}\) Faster than no cache by
90 % 1 in 10 \(10 + 0.10 \times 1000 = \mathbf{110}\) ns 9.1 times
95 % 1 in 20 \(10 + 0.05 \times 1000 = \mathbf{60}\) ns 16.7 times
99 % 1 in 100 \(10 + 0.01 \times 1000 = \mathbf{20}\) ns 50 times

Two things to notice. The misses dominate: at 95 % the cache contributes 10 ns and the misses 50 ns. And every extra per cent of hit rate near the top is worth a lot, which is why caches are made as large as cost allows and stacked in levels. For the loop above, reading i a thousand times with one miss gives \(h = 0.999\) and \(t_{\text{avg}} = 10 + 0.001 \times 1000 = 11\) ns, close to the speed of the cache itself.

Figure 360: Average access time against hit rate, for a 10 ns cache in front of a 1 µs main memory. With no hits every access costs the full microsecond plus the wasted look in the cache; as the hit rate rises the average falls in a straight line towards the cache’s own 10 ns. The marked points are the worked hit rates: 90, 95 and 99 per cent give 110, 60 and 20 ns. Most of the benefit arrives only at high hit rates, where the line approaches the cache speed.

Common mistakes

  • Reading the hierarchy as “faster is better, so use only the top”. The top is fast precisely because it is small and expensive. The hierarchy exists because no level can do every job.
  • Forgetting the lookup cost on a miss. With a look-in-the-cache-first design, a miss costs \(t_c + t_m\), not \(t_m\).
  • Weighting by the wrong fraction. \(1 - h\) multiplies the main-memory time; a 95 % hit rate means 5 % of accesses go to main memory.
  • Mixing B and b. Cache sizes are in bytes: 32 kB of L1 is 256 kibibits.
  • Thinking a cache adds capacity. A cache holds copies of words that are also in main memory. It makes memory faster, not larger.

See also

Memory Models

The first of the four things that make up an ISA (instruction-set-architecture): how memory looks to the CPU. Four issues decide that — addressable cell size, alignment, address spaces and endianness — and every one of them is a decision the specification has to make, not something the hardware settles on its own.

Memory as addressable cells

Computer memory is conceptually a set of addressable cells:

  • Each cell has a unique address (or cell number).
  • Cells are usually 8 bits wide (i.e. hold one byte).
  • Various cell widths have been used in the past — 8 bits is a convention, not a law.

Drawn as a table, the address indexes the rows and the cell width is how wide each row is:

Address ← cell width →
0
1
2
3
…

A “4 × 3 memory” in that notation means 4 addresses of 3-bit cells — and \(4 = 2^2\), so two address bits. Built at gate level, it shows that “memory” at this level is nothing more exotic than flip-flops-and-latches and combinational-logic-blocks arranged into storage.

Figure 361: A 4 × 3 memory at gate level — four addresses of three-bit cells. Twelve D flip-flops in four rows of three: one row is one addressable cell. The decoder turns A1 A0 into exactly one row-select (word) line. Writing: the word line ANDed with WRITE clocks that row’s three flip-flops, so DATA IN (I2 I1 I0) — which is wired to every row’s D inputs all the time — is captured only by the selected row. Reading: each flip-flop’s Q is ANDed with its own word line and the three cells of a column are OR’d together, so the unselected rows contribute 0 and DATA OUT (O2 O1 O0) carries the selected row alone. The decoder is drawn as a trapezoid with the wide edge on the right, and the flip-flops as plain rectangles with a clock wedge on the lower-left edge, per this course’s conventions (csse2010-diagram-notation). The most significant bit, I2/O2, is the leftmost column.

A. Addressable cell size

Most common cell size is 8 bits (1 byte) — but not always.

The AVR is the counterexample sitting on the bench:

AVR memory Cell width
Data memory 8 bits
Instruction (program) memory 16 bits

Which is why an AVR instruction is “one word” rather than “two bytes” — a program-memory address counts 16-bit cells.

The bus transports the content of a cell, but the data bus may be wider than one cell: it can retrieve several cells (addresses) at once. When it does, the address bus does not need to be as wide.

Bus sizes

For every doubling of the data bus width, remove the least significant bit of the address bus.

For a memory of \(2^n\) cells at 8 bits per cell — so an address size of \(n\) bits:

Data bus Address bus Cells per transfer
8 bits \(n\) bits one cell at a time
16 bits \(n-1\) bits two cells at a time
32 bits \(n-2\) bits four cells at a time

The reason is that a wide transfer always moves an aligned group of cells. With a 16-bit data bus the memory only ever hands over cell pairs \((0,1), (2,3), (4,5), \dots\) — so the bottom address bit never selects anything, and naming the pair takes one bit fewer than naming the cell.

Worked example. A memory of 64 cells, 8 bits each, addressed 000000 … 111111:

\[64 = 2^6 \text{ cells} \implies 6\text{-bit addresses}\]

Data bus Address bus
8 6
16 5
32 4

Read the two buses as a pair, not separately: widening one narrows the other by exactly as much.

Word addresses and byte addresses

The AVR’s 16-bit program-memory cells have one practical consequence. The program counter, jmp, call and every code label count words. But a table of constant bytes kept in flash is read a byte at a time by lpm, load program memory, and lpm takes a byte address in the Z register. Word \(w\) holds bytes \(2w\) and \(2w + 1\), with the low byte at the even address, which is the AVR being little endian (section D).

So turning a code label into a byte address means doubling it. Take the string Hello stored at word 2 by mesg: .db 72,101,108,108,111 (assembly-process):

Figure 362: One region of program memory addressed two ways. Each row is a 16-bit word, numbered on the right, and each half is a byte, numbered inside its cell. The label mesg has the value 2 because labels in the code segment count words. Byte addressing counts the halves, low byte first, so word 2 starts at byte 4. That is why lpm is pointed at mesg*2: with Z = 4 it loads 72, the H. The five bytes of the string take two and a half words, and the last half word is a zero pad. Grey marks the jmp, blue the string and red the byte that lpm reads.

        ldi  ZH, high(mesg*2)   ; Z = 4: byte address of word 2
        ldi  ZL, low(mesg*2)
        lpm                     ; r0 <- 72, the H

Leaving out the *2 points Z at byte 2, the low byte of word 1, which is half of the jmp.

B. Alignment

Many architectures require natural alignment, e.g.

  • 4-byte words starting at addresses 0, 4, 8, …
  • 8-byte words starting at addresses 0, 8, 16, …

i.e. an \(n\)-byte value must start at an address that is a multiple of \(n\).

Taking an 8-byte word on a machine that fetches 8 bytes at a time:

Where it sits Reads needed
Aligned bytes 8–15, i.e. an 8-byte word at address 8 1 — it is exactly one fetched block
Non-aligned bytes 12–19, i.e. an 8-byte word at address 12 2 — the top half of block 8–15, plus the bottom half of block 16–23

Figure 363: An aligned and a non-aligned 8-byte word. Four blocks of eight bytes; grey marks the bytes of the 8-byte word. On the left the word starts at address 8, so it is one block — one read. On the right it starts at address 12, so it takes the top half of the block at 8 and the bottom half of the block at 16 — two reads, marked R1 and R2. Two things about the drawing: addresses increase upward (unlike every other memory figure in the course, where they increase downward — see csse2010-diagram-notation on that inconsistency), and byte numbers within a row run high-to-low left to right. The × marks a byte in the fetched block that is not part of the word.

Alignment is often required because it is more efficient — the aligned case is always one read, the non-aligned case sometimes two, and the hardware that stitches two blocks together and extracts the middle is hardware that a machine demanding alignment simply does not need.

When alignment is not required — the Pentium IV

  • Fetches 8 bytes at a time from memory (64-bit wide data bus).
  • Alignment is NOT required, so the processor stays backwards compatible with earlier processors.
  • A 4-byte word stored at address 4 takes 1 read (bytes 0 to 7).
  • A 4-byte word stored at address 6 must read bytes 0 to 7 (one read) and bytes 8 to 15 (second read), then extract the 4 required bytes from the 16 bytes read.

Counting reads in general

A data bus \(w\) bytes wide delivers one aligned \(w\)-byte block per read. An \(n\)-byte value starting at address \(a\) therefore costs

\[\left\lceil \frac{(a \bmod w) + n}{w} \right\rceil \text{ reads}\]

The best case is \(n/w\) (rounded up), when the value starts on a block boundary; every other starting offset can push it one block further. So a value read from an arbitrary address costs either \(\lceil n/w \rceil\) or one more than that — which is why questions of this shape almost always answer “\(k\) or \(k+1\)” rather than a single number.

Worked example: an 8-byte value on a 16-bit data bus, no natural alignment required. Here \(w = 2\) and \(n = 8\):

Starting address Spans Reads
Even 4 aligned 2-byte blocks 4
Odd 9 byte-positions, so 5 aligned blocks 5

so the answer is 4 or 5. The odd case is the one to picture: one byte of the value sits alone at the top of the first block and one byte alone at the bottom of the last, and each of those still costs a whole read.

C. Address spaces

Many microprocessors have a single linear memory address space — the von Neumann architecture:

  • e.g. \(2^{32}\) bytes numbered from 0 to \(2^{32} - 1\).
  • (These may not be bytes — it depends on the addressable cell size.)
  • Program and data share the one space.

However, the Harvard architecture has separate address spaces for instructions and data. The same numeric address means a different location depending on which space you are in, and an instruction says which one it means by what instruction it is.

Figure 364: The two address-space models. Above: von Neumann — one linear space, so program and data are separated only by convention and address 0 names exactly one cell. Below: Harvard, in the AVR ATmega324A’s shape — two spaces, each starting at its own 0, with different sizes and different cell widths — and the cell width under each box is the whole reason the arithmetic below works out the way it does: 32 kB of program memory is \(2^{15}\) bytes but only \(2^{14}\) addresses, because each address there names a 16-bit cell. The end addresses follow from the sizes, so the data box ends at 0x07FF (\(2^{11}-1\), for 2048 bytes) rather than the 0x08FF of Figure 365, which is that 2 kB plus the 256 locations in front of it.

AVR ATmega324A is Harvard:

Space Size Address width
Data \(2^{11}\) (2048) bytes 11 bits
Instruction \(2^{14}\) 16-bit words — 16,384 instruction words = 32,768 bytes 14 bits

The arithmetic — convert to cells first, then take the logarithm:

\[\text{data: } 2\,\text{kB} = 2 \cdot 2^{10}\,\text{B} = 2^{11} \text{ cells (8-bit)} \implies 11 \text{ bits}\] \[\text{program: } 32\,\text{kB} = 2^{5} \cdot 2^{10}\,\text{B} = 2^{15}\,\text{B} = 2^{14} \text{ cells (16-bit)} \implies 14 \text{ bits}\]

The program-memory step is the one that catches people: 32 kB of flash is only \(2^{14}\) addresses, not \(2^{15}\), because each address names a 16-bit cell. Halve the byte count before taking the log whenever the cells are not bytes.

Laid out as a memory map (see avr-architecture for the rest of the chip):

Figure 365: The ATmega324A’s two address spaces. Lowest address at the top, hex addresses outside on the right, grey fill on the coarsely-described regions, and the diagonal break across the flash meaning not to scale: that is this course’s memory-map convention (csse2010-diagram-notation). Marked in red: the register file is r0–r31, the 64 I/O plus 160 extended I/O registers are the 224 of avr-io-ports, the SRAM is 2 kB and the flash 32 kB.

Two details worth pinning down. 0x3FFF \(= 2^{14} - 1\), which is the 14 bits above. And the data space runs to 0x08FF — that is the 2 kB of SRAM plus the 256 locations (0x0000–0x00FF) that the register file and I/O registers occupy in front of it; the “\(2^{11}\) bytes” above is the SRAM itself, which is what the 11 bits size.

The assembler’s view: segments

An assembler treats each address space as a segment with its own location counter (assembly-process). On the ATmega324A there are three, because the EEPROM is a third address space alongside the two above:

Segment Directive Address space Cell Counter starts at The assembler can
code .cseg program memory, flash, 32 kB 16-bit word 0x0000 place instructions and constants
data .dseg data memory, SRAM byte 0x0100 only reserve space
EEPROM .eseg EEPROM, 1 kB byte 0x0000 place constants

Three consequences of separate spaces:

  • The same number means different places. Address 0 is the reset jmp in the code segment, register r0 in data memory and the first EEPROM byte in the EEPROM segment.
  • The units differ. .org 0x0100 in the code segment is word 256, which is bytes 512 and 513 of flash. In the data segment it is byte 0x0100.
  • The data counter does not start at 0. The first 256 data addresses are the registers and I/O registers of Figure 365, so the first variable lands at 0x0100.

The data segment can only be reserved, not filled, because the assembler’s output is programmed into flash and EEPROM, which keep their contents, while SRAM starts empty at every power-up.

The memory behind each space

The three spaces are three different kinds of memory, and the kind explains how each is used (memory-technologies):

Space Technology Volatile? Erased and rewritten
Program memory flash no electrically, a block at a time
Data memory SRAM, flip-flops yes written a byte at a time, freely
EEPROM EEPROM no electrically, one cell (byte) at a time

The flash is divided into two blocks, the Application Flash Section and the Boot Flash Section of Figure 365. Because flash is erased a block at a time, a boot loader in the boot section can erase and rewrite the application section without erasing itself. Other AVR devices have one flash block, and some have more.

The register file and the SRAM sit at the top of the memory hierarchy. Unlike a desktop processor, the AVR has no cache: its SRAM is small enough and fast enough to keep up with the CPU directly.

D. Endianness

Different machines may support different byte orderings for a multi-byte value.

Which end goes first (at the lowest address) Used by
Little endian the little end — least significant byte Intel microprocessors (Pentium etc.), and AVR
Big endian the big end — most significant byte SPARC, Freescale (formerly Motorola) microprocessors

Most desktop/workstation/server CPUs produced since ~1992 are “bi-endian” (support both) — some switchable at boot time, others at run time, i.e. they can change dynamically.

Endianness only ever matters when a value spans more than one cell: reassembling it means knowing which cell was the low-order one.

Worked example

Given this memory:

Address Contents
0 00001111
1 00110011
2 11011101
3 00101100
Read Value Why
the 1-byte word at address 1 00110011 one cell — endianness does not apply
the 2-byte word at address 0, big endian 00001111 00110011 big end first, so address 0 holds the most significant byte
the 2-byte word at address 2, little endian 00101100 11011101 little end first, so address 2 holds the least significant byte and address 3 the most

The mechanical way to do these without getting turned around: write the addresses the value occupies in increasing order, then assemble the answer most-significant-byte first. Big endian reads the addresses forwards; little endian reads them backwards.

See also

Memory Technologies

The kinds of memory a computer is built from, and how big they are. This note covers why a computer needs memory at all, the five ways memory is classified and where SRAM, DRAM, ROM, flash, SSDs and hard disks fall on each, how a static cell differs from a dynamic one, what “RAM” means now, the ROM family from ROM to flash, the ATmega324A’s three memories, the generations of DRAM, and the units capacity is quoted in, where “1 MB” can mean three different numbers. How these memories are arranged by speed is in memory-hierarchy-and-cache, and disks and files are in magnetic-disks and file-systems. First met in 2026-10-22-memory-disks-and-files.

Why a computer needs memory

A processor on its own holds a few dozen registers. Everything else has to live somewhere, and there are three distinct jobs:

  1. Temporary results. Intermediate values, variables, the stack: things a running program needs for a while and then discards.
  2. Programs. The instructions themselves have to be stored somewhere the processor can fetch them from (fetch-decode-execute-cycle).
  3. Settings that survive power-off. A calibration constant, a high score, the last channel a TV was on. These must still be there when the power comes back.

The first job wants memory that is fast and can be rewritten endlessly. The third wants memory that keeps its contents with no power. No single technology is best at all three, which is why there are many types.

Five ways to classify memory

Each axis asks one question about a memory.

Axis The question The two answers
Access Can any cell be reached directly, in the same time? random access: the address selects the cell directly. Sequential access: the data has to be passed over in order to reach a cell, like a tape
Static or dynamic Does a stored bit stay put by itself while powered? static: held by a flip-flop or latch. Dynamic: held as charge that leaks away and must be refreshed
Volatility Does it keep its contents when the power is off? volatile: forgets. Non-volatile: remembers
Read-only Can the processor write it in normal use? read/write, or read-only (written once, or only by a special process)
Primary or secondary Does the processor address it directly? primary: on the processor’s address bus, holding the running program and its data. Secondary: reached through I/O, holding files

Random access is what an address decoder gives you. In the gate-level memory of memory-models, the address bits drive a decoder that selects exactly one row, and it takes the same time whichever row it is. A tape has to wind past everything in front of the data first.

Where the common technologies fall:

Figure 366: Six memory technologies against the five ways of classifying memory. Each row is one technology and each column one axis; a filled dot means the left-hand answer in the column heading, an open circle the right-hand one. SRAM and DRAM are both random-access, volatile, read/write primary memory, and differ only in being static or dynamic. ROM and flash are non-volatile; ROM is read-only, while flash is rewritten electrically, in blocks. SSDs (built from flash) and hard disks are secondary storage, reached through I/O rather than the address bus. All six are random access, in that any location can be reached directly by its address; the sequential case is tape. A hard disk’s access time does still depend on where the data is, because it must wait for the head to move and the disk to turn. The static/dynamic distinction only applies to the semiconductor RAMs, so it is left blank for the rest.

Two entries need a word. Flash is used both as primary memory (the program memory of a microcontroller like the AVR, which the processor fetches instructions from directly) and, packaged as an SSD, as secondary storage. And a hard disk counts as random access (sometimes called direct access) because the head can go straight to any track without reading what lies in between, unlike a tape. Reaching a sector still means moving the head and waiting for the sector to rotate underneath, though, so unlike a memory chip its access time depends on where the data is (magnetic-disks).

Static and dynamic memory

Static memory (SRAM) stores each bit in a flip-flop or latch: a loop of gates that holds its state for as long as the power is on (flip-flops-and-latches). Nothing needs doing to keep the bit. A typical cell is two cross-coupled inverters plus two switches to connect it to the bit lines, about six transistors per bit, so SRAM is fast but expensive per bit.

Dynamic memory (DRAM) stores each bit as charge on a capacitor, with a transistor as a switch that connects the capacitor to its bit line when the row is selected. One transistor and one capacitor per bit is far smaller than a flip-flop, so many more bits fit on a chip and each costs less. The price is that the charge leaks away. A DRAM cell forgets its contents within milliseconds unless it is refreshed, meaning read and written back, which the memory does to every row every few tens of milliseconds (of the order of 20 ms). Reading is slower too, because the small charge has to be sensed and amplified.

Figure 367: One bit of static and one bit of dynamic memory. Left: the static cell is two inverters in a loop. Whatever value sits at one side, the other inverter feeds its complement back, so the pair holds the bit for as long as there is power. Raising the word line closes both switches and connects the two sides to the bit line and its complement, for reading or writing. Right: the dynamic cell is a single switch (a transistor) and a capacitor. Raising the word line connects the capacitor to the bit line; a charged capacitor is a 1 and an empty one a 0. The charge leaks away through the switch, so the cell has to be read and rewritten, refreshed, every few tens of milliseconds.

SRAM DRAM
Bit stored in a flip-flop or latch charge on a capacitor, behind a transistor switch
Keeps its bit while powered? yes only if refreshed every few tens of ms
Cell size large (about six transistors) small (one transistor, one capacitor)
Bits per chip fewer many more
Speed faster slower
Cost per bit high low
Volatile? yes yes
Typical use registers, cache, small microcontroller RAM (the ATmega324A’s 2 kB) a computer’s main memory

What “RAM” means

RAM stands for random access memory. Originally that meant exactly the first axis above: any cell can be accessed directly, as opposed to sequential access. By that definition ROM and flash are random access too.

In current use “RAM” means volatile read/write memory, and SRAM and DRAM are the two kinds. So “RAM” and “ROM” are treated as opposites even though the original meaning of RAM covers both.

Volatile and non-volatile memory

Volatile memory forgets its contents when the power goes off. Both SRAM and DRAM are volatile. DRAM is volatile even with the power on, in the sense that it forgets within milliseconds if it is not refreshed.

Non-volatile memory remembers its contents with the power off. There are several kinds, and they differ in how, and how easily, they can be rewritten. Hard disks and optical disks are non-volatile too, but they are secondary storage; the next section is about non-volatile chips.

From ROM to flash

  • ROM, read-only memory. The contents are hardwired into the silicon by the chip’s manufacturer. They can never be changed.
  • EPROM, erasable programmable ROM. Programmed electrically by the user, and erased by ultraviolet light. An EPROM package has a small quartz window over the die. Shining a UV lamp through it for some minutes erases the whole chip, which can then be programmed again.
  • EEPROM, electrically erasable PROM. Erased by applying a certain voltage, so it can be erased and rewritten in the circuit, with no lamp, one cell (byte) at a time.
  • Flash. A newer form of EEPROM. The two used to be different technologies and have been converging. The main difference that remains is that flash is written and erased in blocks, where EEPROM is written and erased one cell at a time. Erasing a large block at once is what makes flash dense and cheap, and it is why flash holds programs and files while EEPROM holds a few bytes of settings that change one at a time.

Figure 368: The family of non-volatile memory chips, from least to most easily rewritten. Each step keeps the contents with the power off and changes how they are erased. ROM cannot be erased at all: the bits are fixed when the chip is made. An EPROM is erased whole, by ultraviolet light shining through a window in the package. An EEPROM is erased electrically, in the circuit, a single cell at a time. Flash is erased electrically too, but a block of many cells at a time, which is what lets it be so dense.

The ATmega324A’s three memories

The ATmega324A has one of each of the three common kinds on the chip, and each is a separate address space with its own assembler segment (memory-models, assembly-process).

Memory Technology Size Holds Volatile? Assembler segment
Flash flash (block-erased EEPROM) 32 kB, as 16-bit words the program and constant tables no .cseg
SRAM static RAM 2 kB variables, the stack, the heap yes .dseg
EEPROM EEPROM (cell-erased) 1 kB settings that must survive power-off no .eseg

The flash is divided into two blocks: an application section, where the program normally lives, and a boot loader section at the top of program memory. A boot loader is a small program that can receive a new program, over a serial link for instance, and write it into the application section. Because flash is erased a block at a time, having the program in a separate block from the boot loader means the application can be erased and rewritten while the boot loader that is doing the rewriting stays intact. Other AVR devices have one flash block, and some have more.

Figure 369: The ATmega324A’s three memories as technologies: what each holds, the unit it is erased or written in (dark), and whether it survives power-off. Flash holds the program and keeps it with the power off, but it can only be erased a block at a time, so it is split into two blocks: a boot loader in the small block can erase and rewrite the program in the large one without erasing itself. SRAM holds the variables and the stack; any byte can be written at any time, at full speed, but all of it is lost at power-off. EEPROM keeps its bytes with the power off and, unlike flash, erases and rewrites them one at a time, which suits a few settings that change one by one.

The table is the answer to a common question: which memory should this value go in? Code goes in flash. A variable the program changes goes in SRAM. A value the program changes and that must still be there after a reset goes in EEPROM.

Generations of DRAM

Every DRAM stores bits as charge on a capacitor, not in flip-flops. Its cells are smaller than a static cell, so a chip packs in more bits, and it is slower than static memory. What has changed over the generations is the interface, the way rows and columns are addressed and data is moved out:

Generation What it changed
FPM DRAM, fast page mode once a row is open, further columns in that row can be read without re-sending the row
EDO DRAM, extended data out keeps the output valid while the next column address is sent, so successive reads overlap; a refinement of FPM
SDRAM, synchronous DRAM runs from a clock shared with the memory controller, so transfers happen on clock edges and can be pipelined
RDRAM, Rambus DRAM a narrow, very fast proprietary bus
DDR SDRAM, double data rate, generations 1 to 5 transfers data on both the rising and falling clock edges; each generation raises the rate
GDDR, graphics DDR, up to GDDR7 a DDR variant tuned for the bandwidth of graphics cards

FPM and EDO belong together as the asynchronous generations. SDRAM is the break: from there on, DRAM is clocked, and DDR4 and DDR5 are what current machines use.

Capacity units: powers of 2 or of 10

In SI units, kilo, mega and giga mean powers of 10: \(10^3\), \(10^6\), \(10^9\). In computing they have conventionally, or at least historically, meant the nearest powers of 2: \(2^{10} = 1024\), \(2^{20}\), \(2^{30}\). The two agree to within a few per cent, and the gap grows with every prefix.

Prefix Power of 10 Power of 2 Power of 2 is larger by
kilo (k) \(10^3\) = 1,000 \(2^{10}\) = 1,024 2.4 %
mega (M) \(10^6\) = 1,000,000 \(2^{20}\) = 1,048,576 4.86 %
giga (G) \(10^9\) = 1,000,000,000 \(2^{30}\) = 1,073,741,824 7.37 %
tera (T) \(10^{12}\) \(2^{40}\) = 1,099,511,627,776 9.95 %

The percentages are measured against the power of 10: \((2^{30} - 10^9)/10^9 = 0.0737\).

Figure 370: The decimal and binary meanings of each prefix side by side, on a log scale. Each step up the decimal ladder multiplies by 1000 and each step up the binary ladder by 1024, so the binary value pulls a little further ahead at every step: 2.4 per cent at kilo, 4.86 at mega, 7.37 at giga and almost 10 at tera. That is why the ambiguity is a rounding error for a kilobyte but a real difference for a terabyte disk.

Why main memory comes in powers of 2

A memory chip is addressed by address lines, and \(n\) lines can name exactly \(2^n\) cells: one line selects between 2 cells, two lines between 4, three between 8. A memory that used only 1,000,000 of the 1,048,576 addresses its 20 lines can name would waste the rest, so main memory is built in powers of 2 and its size is quoted that way: a “4 GB” module holds \(4 \times 2^{30}\) bytes.

Figure 371: Why memory sizes are powers of 2. With one address line a decoder can select one of 2 cells, with two lines one of 4, and with three lines one of 8: every extra line doubles the number of cells that can be named. So n address lines give exactly 2 to the n cells, and a memory is built to fill that number.

Which convention is used where

Context Convention Example
Main memory capacity always powers of 2 1 GB \(= 1024 \times 1024 \times 1024\) B \(= 2^{30}\) B
Hard disk capacity, as sold powers of 10 1 GB \(= 1000 \times 1000 \times 1000\) B \(= 10^9\) B
Operating systems (e.g. Windows) reporting sizes powers of 2 a “500 GB” disk shows as about 465.66 GB
Data speeds, transfer rates usually powers of 10 1 Gbps (gigabit per second) \(= 10^9\) bits per second
Occasionally, a mixture one of each the 1.44 MB floppy disk: \(1.44 \times 1000 \times 1024\) bytes

Disk makers’ powers of 10 make a disk seem bigger. A disk sold as 500 GB holds \(500 \times 10^9\) bytes, and an operating system that divides by \(2^{30}\) reports \(500 \times 10^9 / 2^{30} = 465.66\) “GB”. Nothing is missing; the two numbers use different gigabytes.

Note the case of the b: B is a byte and b is a bit. 1 Gbps is a rate in bits, so it moves \(10^9 / 8 = 125 \times 10^6\) bytes per second at most.

Binary prefixes: KiB, MiB, GiB

To avoid the confusion, standard names were created for the binary meanings:

Name Symbol Value
kibibyte KiB 1024 bytes
mebibyte MiB 1024 KiB \(= 2^{20}\) bytes
gibibyte GiB 1024 MiB \(= 2^{30}\) bytes

With these, kB, MB and GB can keep their SI meanings. Few people use them, though, and these notes use kilo, mega and giga as everyone does, with the meaning depending on the context. When the difference matters, say which one is meant.

Worked: what is a megabyte, and a gigabyte?

How many bytes is 1 MB? How many is 1 GB? How different are the meanings, and how many bytes does a “1.44 MB” floppy disk hold?

1 MB, three ways.

  • Conventionally: \(1\text{ MB} = 2^{10}\text{ kB} = 1024\text{ kB} = 2^{20}\text{ B} = \mathbf{1{,}048{,}576}\) B.
  • Sometimes, the SI meaning: \(1\text{ MB} = 10^6\text{ B} = \mathbf{1{,}000{,}000}\) B.
  • Or in between, with a decimal mega of binary kilobytes: \(1000\text{ kB} = 1000 \times 1024 = \mathbf{1{,}024{,}000}\) B.

1 GB, three ways.

  • Conventionally: \(1\text{ GB} = 2^{10}\text{ MB} = 2^{20}\text{ kB} = 2^{30}\text{ B} = \mathbf{1{,}073{,}741{,}824}\) B.
  • Sometimes: \(1\text{ GB} = 10^9\text{ B} = \mathbf{1{,}000{,}000{,}000}\) B.
  • Or in between: \(1000 \times 2^{20} = \mathbf{1{,}048{,}576{,}000}\) B, a thousand binary megabytes.

How different. The binary gigabyte exceeds the decimal one by \(1{,}073{,}741{,}824 - 1{,}000{,}000{,}000 = 73{,}741{,}824\) bytes, and

\[\frac{73{,}741{,}824}{1{,}000{,}000{,}000} = 0.0737 \approx 7.4\,\%.\]

That 7.4 % is measured against the decimal gigabyte. Measured against the binary one it is \(73{,}741{,}824 / 1{,}073{,}741{,}824 = 6.87\,\%\): the decimal gigabyte is 6.87 % smaller. For the megabyte the gap is \(48{,}576 / 1{,}000{,}000 = 4.86\,\%\). The in-between gigabyte, 1,048,576,000 B, is 4.86 % above \(10^9\) and 2.34 % below \(2^{30}\) (equivalently, \(2^{30}\) is 2.4 % above it).

The floppy disk. Its “1.44 MB” is 1.44 thousand binary kilobytes:

\[1.44 \times 1000 \times 1024 = \mathbf{1{,}474{,}560}\ \textbf{bytes} = 1440\text{ KiB}.\]

That is 1.40625 MiB in binary megabytes and 1.47456 MB in decimal ones. The label is right in neither, which is the point: it mixes a decimal thousand with a binary kilobyte.

Common mistakes

  • Calling SRAM “dynamic” because it can be rewritten. Static and dynamic are about how a bit is held, a flip-flop against a leaking capacitor, not about whether it can change. Both are read/write.
  • Thinking non-volatile means read-only. Flash and EEPROM are non-volatile and rewritable. ROM is the only one here that can never be rewritten.
  • Thinking SRAM keeps its contents at power-off because it does not need refreshing. Static means no refresh while powered. Both SRAM and DRAM are volatile.
  • Mixing up flash and EEPROM. Both are electrically erasable; flash erases a block at a time, EEPROM one cell at a time. On the AVR the program goes in flash and individual settings in EEPROM.
  • Assuming “MB” has one meaning. Memory sizes are powers of 2, disk sizes and data rates are powers of 10, and some figures mix the two. Say which, or use KiB, MiB, GiB.
  • Getting the 7.4 % backwards. \(2^{30}\) is 7.37 % more than \(10^9\), but \(10^9\) is 6.87 % less than \(2^{30}\). The base of a percentage matters.
  • Confusing B and b. A 1 Gbps link is about 125 MB/s, not 1 GB/s.

See also

Polling and Interrupts

How a CPU finds out that an I/O device needs attention: by asking (polling) or by being told (interrupts). This note covers what an interrupt does to the flow of control, the three problems any interrupt mechanism has to solve, the fourteen steps from a device’s request to the resumed program, transparency, what to do about a second interrupt, and traps, the software counterpart. First met in 2026-09-21-interrupts. How the AVR implements it (its vector table, the ISR in assembly and in C, and the registers that switch an interrupt on) is avr-interrupts.

The problem

The CPU is fast, and I/O is slow and asynchronous. At 8 MHz the AVR completes an instruction every one or two clock cycles, while a key is pressed, a character arrives or a timer matches on its own schedule. That schedule has no relation to the clock or to which instruction the program is on. The CPU needs to know two things:

  • when data is available from an input device, and
  • when an output device is ready to accept data.

There are two ways to find out: polling-driven I/O and interrupt-driven I/O.

Polling

The processor periodically asks each device whether it is ready, and waits for the answer. On the AVR, asking is reading a register: a pin in PINx (avr-io-ports), or a flag in a timer’s TIFRn (avr-timers-and-counters). A polling program is a main loop that asks each device in turn:

while (1) {
    if (PINC & (1<<0)) {            /* is the button pressed?  */
        /* ... handle the button ... */
    }
    if (TIFR1 & (1<<OCF1A)) {       /* has the timer matched?  */
        TIFR1 = (1<<OCF1A);         /* clear the flag          */
        /* ... handle the tick ... */
    }
    /* ... everything else the program does ... */
}

It is inefficient, in two ways:

  • Time spent asking. Most asks find nothing, and every one of them costs instructions.
  • Time spent waiting. An event is noticed only at the next ask, so the delay before it is handled can be as long as one pass of the loop. Every piece of work added to the loop lengthens that pass, and so slows the response to every device.

But it may be fine if the processor has nothing else to do. A program whose only job is to wait for a button and then act gains nothing from anything cleverer. Polling is also simple: the program always knows exactly where it is, and nothing happens behind its back.

Interrupts

The device tells the CPU when it is ready. The three kinds of ready:

Kind Example
Device ready to accept more output the serial transmit buffer is empty
Device has input ready a key pressed on a keyboard
A regular interrupt a timer generating an interrupt every, say, 20 ms

When the request arrives, the CPU finishes its current instruction, sets the running program aside, and runs a routine for that device, the interrupt handler or interrupt service routine (ISR). When the handler completes, control returns to where the program left off. The interrupted program does not ask, wait, or even know.

Figure 372: The same three device events handled both ways. Polling: the CPU breaks off its own work at fixed intervals to ask whether the device is ready. Most asks find nothing (hatched), and an event waits for the next ask before it is noticed, so how quickly it is handled depends on how often the program asks. Interrupts: the CPU does its work without asking, and each event diverts it into the handler within a few cycles. No time is spent asking, and the response does not depend on how long the main loop is. The work done is the same in both rows; what differs is the time wasted asking and the delay before each event is handled.

Interrupts are more efficient for the CPU, and they change the flow of control, which is where their cost lies.

A fourth way to leave the sequence

Normally the PC just increments. avr-branches-and-jumps and procedures-and-the-stack cover the instructions that change it. An interrupt changes it too, but without any instruction asking:

Triggered by Where the new PC comes from Comes back?
Branch an instruction, if a flag says so an offset in the instruction no
Jump an instruction the instruction no
Procedure call an instruction (call) the instruction yes: ret pops the return address call pushed
Interrupt a device, between any two instructions a table, indexed by which device yes: the return-from-interrupt instruction pops the address the hardware pushed
Trap an instruction that produces an exceptional result a table, indexed by which error not always

The useful way to see an interrupt is as a procedure call that the hardware makes. The mechanism is the same: push the return address, load the PC, and pop it back at the end. The difference is that the program never asked for it, and that one difference produces all three of the issues below.

The three issues

Any interrupt mechanism has to answer three questions.

  1. How does the CPU know where the ISR is? A call names its target, but an interrupt does not, so the address must be found from the source. The CPU looks in an interrupt vector table, often at the beginning of memory. The table holds either the address of each handler, which the CPU loads into the PC, or a jump instruction to each handler, in which case the CPU loads the PC with the entry’s own address and executes the jump. The AVR does the second. Vector is used both for the interrupt’s number (its index in the table) and for the address of its handler, and it is worth checking which is meant.
  2. How are the registers preserved? All of them, including the status register. The handler must save copies of any register it uses before using it, and restore them before it returns. Many CPUs save the status register automatically; the AVR does not, so the handler must save it itself if it would change it. The result is transparency, below.
  3. What happens if another interrupt arrives while one is being serviced? Either it waits, or it interrupts the handler. See Nesting and priority, below.

The sequence of actions

From the device’s request to the resumed program there are fourteen steps, shared between the hardware and the ISR:

Figure 373: The fourteen steps of an interrupt, in the three phases the hardware and the ISR take turns at, with the state of the machine after each phase underneath. The hardware does the first six: it saves only the return address, finds and enters the handler, and turns interrupts off. The ISR saves what it will use, does the I/O and restores what it saved. The return-from-interrupt instruction then hands back to the hardware, which turns interrupts on and pops the return address. The notes in italics are the AVR’s version of each step. The shaded steps 11 to 13 are a single AVR instruction, reti, and step 8 rarely arises on the AVR (dashed), because every source has its own vector and so the ISR knows which one fired; only a pin-change handler, whose vector covers a whole port, still has to find which pin changed. The stack after step 14 is exactly as it was before step 1, and that is what transparency requires.

Three things in the sequence are worth holding on to:

  • The hardware saves as little as it can. It pushes only the return address, and everything else is the ISR’s job. That keeps the entry fast, and it means an ISR that uses nothing need save nothing.
  • Interrupts are off from step 6 to step 12. That is the default answer to issue 3: a second request simply waits until the handler has returned. On the AVR, off is the I bit of the status register being 0 (avr-architecture).
  • Return from interrupt is not the same as return from procedure. It has to undo step 6 as well as step 3. A handler that ends with a plain ret goes back to the right place but leaves interrupts disabled for good.

Transparency

When the ISR finishes, the computer is in the same state as it was before the interrupt. That is transparency, and it is the answer to issue 2. It matters more for an ISR than for a procedure because the interrupted code has no chance to prepare. A caller knows where its calls are and can agree with the procedure which registers it may use. An interrupt can land between any two instructions, including these two:

    cp   r16, r17        ; sets Z if r16 == r17
                         ; <- an interrupt here
    breq equal           ; reads Z

If the ISR does anything that sets flags — a dec, an andi, a cp of its own — and does not restore the status register, breq reads the ISR’s Z instead of the one cp produced. The program then takes the wrong branch, but only on the rare occasions the interrupt lands in that one gap. A bug like that can survive a great deal of testing. So the status register is the one register a handler must always consider, even if it touches nothing else. Whether an instruction changes it is listed per instruction in the instruction set reference (avr-instructions).

Nesting and priority

For an interrupt that arrives while an ISR is running, there are three policies:

  • Disable interrupts during an ISR. The simplest: the second request waits (its flag stays set) and is serviced after the first handler returns. On CPUs that save the status register automatically, the global interrupt enable flag is among the bits the return-from-interrupt instruction restores, so it comes back on by itself. This is the AVR’s default.
  • Prioritise. Higher-priority interrupts may interrupt lower-priority handlers, but not the other way round and not at the same level. Urgent devices are never kept waiting behind unimportant ones, and an unimportant device can never delay an urgent one. Many CPUs support this; the AVR does not.
  • Re-enable interrupts inside the ISR. Any interrupt may then interrupt the handler, regardless of priority. The AVR allows this if the handler executes sei.

Figure 374: The three policies for an interrupt that arrives while another is being handled, in the two cases that tell them apart. In each panel, code on a higher lane has interrupted the code below it, and a dashed box is a request that is waiting. With interrupts disabled during an ISR, whichever handler started first finishes first, and the other waits for it in both cases. With priority nesting, the urgent request (H) cuts into the less urgent handler (L) but never the reverse, which is the behaviour one would want and the one the AVR does not provide. With interrupts re-enabled inside the handler, any request cuts in immediately, so in the right-hand case the urgent handler is itself held up by the less urgent one.

On the AVR, then, priority only decides the order in which waiting interrupts are serviced. It matters only when two or more are waiting at once, for instance because they arrived during another handler. The highest-priority one, the one with the lowest vector, goes first. It never lets an urgent interrupt cut into a running handler. The one way to get nesting is to re-enable interrupts inside the handler, and then priority plays no part at all. Both cases are traced, with the I bit, in 2026-09-21-interrupts.

The practical consequence is a rule: keep ISRs short. While any handler runs, every other interrupt waits. A handler that busy-waits for 10 ms delays every other device by 10 ms, and a timer tick that arrives twice during that time is serviced only once, because a flag can record that an event happened but not how many times.

Traps

Traps are software interrupts: interrupts caused by events in the software rather than in the hardware, and specifically by exceptional events, such as

  • overflow,
  • divide by zero, and
  • an undefined opcode.

They relate to error checking the way interrupts relate to polling. Without traps, a program that must not overflow has to test after every arithmetic instruction, which is polling for errors. With them, the hardware watches, and the program is diverted only when the error actually happens. Traps save continually checking for errors.

Trap handlers don’t always return to the original program. After a division by zero or an undefined opcode, there is often no sensible instruction to continue with. Under an operating system the usual outcome is that the program is ended.

Interrupt Trap
Caused by a device, outside the program the instruction being executed
When at an unpredictable point in the program, asynchronously at the same instruction every time, given the same data
Returns? always, to the interrupted instruction’s successor not always

The AVR does not provide traps. Overflow sets V in the status register and it is up to the program to branch on it (avr-branches-and-jumps), and the AVR has no divide instruction to fail. But it is possible to generate hardware interrupts from software, by writing to an external interrupt pin configured as an output (avr-interrupts).

Pitfalls

  • Assuming priority means pre-emption. On the AVR it does not: a higher-priority interrupt waits for a lower-priority handler to finish, like any other.
  • Not saving the status register in a handler that changes flags. The symptom is an interrupted comparison going the wrong way, rarely and irreproducibly.
  • Long handlers. Every other interrupt waits while one runs, and repeated events during the wait are merged into one.
  • Variables shared between a handler and the main program that the compiler is allowed to cache. In C they must be volatile (avr-interrupts).
  • Returning with ret instead of the return-from-interrupt instruction: the program continues, and interrupts never come back on.

See also

Procedures and the Stack

What a procedure is at the machine level, how call and ret get into it and back out, and the stack — the structure that makes returning possible from any depth of nesting, holds saved registers and arguments, and has to be set up before any of that works. First met in 2026-09-14-flow-of-control; branches and jumps are in avr-branches-and-jumps, and data memory, where the stack lives, is in memory-models and avr-architecture.

Procedures

A procedure is a group of instructions that performs some task, which

  • may have operands — arguments or parameters,
  • may produce result(s),
  • can be invoked (called) from multiple places in a program — even from within itself, a recursive procedure — and
  • after invocation, control returns to the statement after the call.

It is the same thing as a C function (c-language-basics), a Python function, a Java method, or a subroutine; the names differ by language, the mechanism does not. Good use of procedures is most of what makes a program of any size readable, and the AVR C compiler turns every function into exactly what follows.

The return is the part with machinery behind it. A jump goes somewhere; a call goes somewhere and remembers where it came from, so that a ret at the far end can come back — to a different place each time, depending on who called.

call and ret

Instruction Size Cycles
call label direct call — target is an absolute address 32-bit 4
rcall label relative call — target is PC ± 2 K words 16-bit 3
icall indirect call — target is the address in Z 16-bit 3
ret return to the instruction after the most recent call 16-bit 4

The three calls mirror jmp, rjmp and ijmp exactly — same reach, same sizes — and each costs one cycle more than its jump. That cycle is the push. What a call does, in order:

  1. compute the return address — the address of the instruction after the call;
  2. push it onto the stack;
  3. load the PC with the target.

And ret undoes it: pop the top of the stack into the PC. Nothing in the procedure needs to know who called it, because the address to go back to was left on the stack by the caller.

Figure 375: A call and its return, followed through the three registers involved. The PC, the stack pointer and the top of the stack are shown before the call, during the procedure and after the return, with example addresses. call records the address of its own successor on the stack and lowers the stack pointer by two, because a program-memory address needs two bytes; then it loads the PC with the procedure’s address. ret reverses both steps and execution resumes at the recorded address, which is the instruction after the call. The procedure body never touches the return address, so it does not matter what the procedure does in between, provided it leaves the stack as it found it.

Why a stack

The return address has to be stored somewhere. There are three candidates:

Where Fails when
A single fixed register or memory address for all calls a procedure calls another procedure — the second call overwrites the first’s return address, and the outer procedure can never return
One memory location per procedure a procedure calls itself — recursion needs two live return addresses for one procedure
A stack never, until memory runs out

A stack is a last-in, first-out store: push puts a value on top, pop takes the top value off. Calls and returns nest — the most recent call is always the first to return — so a stack of return addresses always has the right one on top. Nested calls are drawn step by step in 2026-09-14-flow-of-control.

The AVR stack

On the AVR the stack is simply a region of data memory (memory-models), and the stack pointer is a 16-bit address held in two I/O registers, SPH:SPL, that says where the top currently is. Two conventions fix how it works:

  • The stack grows downward. A push stores at the address in SP and then decrements SP; a pop increments SP and then loads from it. So SP always points at the next free cell, just below the most recently pushed byte.
  • It starts at the top of SRAM. Program variables are allocated from the bottom of SRAM upward; the stack is started at the last address, RAMEND (0x08FF on the ATmega324A), and grows down toward them. Neither has to know in advance how much room the other needs.

Figure 376: Where the stack lives in the ATmega324A’s data memory. The general-purpose registers and I/O registers occupy the first 256 addresses; SRAM begins at 0x0100. Global variables are laid out from the bottom of SRAM upward, and the stack starts at the top, RAMEND, and grows downward toward them, with SPH:SPL holding the address of the next free cell. The gap between them is the free memory, and it shrinks from both ends: every nested call, every push and every local variable of a running function takes cells off the top, and the stack overflows when it reaches the variables — silently, since nothing checks. That is why the stack pointer must be set to RAMEND before the first call: the reset value would put it somewhere else entirely.

Initialising the stack pointer

An assembly program must initialise the stack before using it. These four lines belong at the top of RESET: in any program that calls anything:

.def temp=r16
    ldi  temp, low(RAMEND)
    out  SPL, temp
    ldi  temp, high(RAMEND)
    out  SPH, temp

RAMEND is defined by the device include file (avr-io-ports), and low()/high() split the 16-bit value because SPL and SPH are two separate 8-bit I/O registers. In C the compiler emits this itself as part of the start-up code that runs before main; it is one of the things a C program on the AVR gets for free and an assembly program does not. The RESET template in avr-program-structure does not include it only because nothing in the Lab 10 programs made a call.

push and pop

The two stack instructions are also available directly:

Cycles
push rr store rr at SP, then SP ← SP − 1 2
pop rd SP ← SP + 1, then load rd from SP 2

Their main use is saving registers a procedure is about to clobber, so that the caller gets them back unchanged:

TEST:
    push r16           ; save what the caller had in r16 and r17
    push r17
    ...                ; use r16, r17 freely
    pop  r17           ; restore — in REVERSE order
    pop  r16
    ret

The order matters because the stack is LIFO: the last register pushed is the first one back. And the count matters even more — every push must be matched by a pop before the ret, because ret pops whatever is on top and treats it as the return address. One push too many and the procedure returns to an address made of a register’s contents; one too few and it returns into the middle of the saved data.

Figure 377: Saving and restoring registers around a procedure body, with the stack drawn after each instruction. The return address is already on the stack when the procedure starts; the two pushes go on top of it, and the two pops must come off in the reverse order to land in the right registers. When ret runs the return address is back on top, exactly as call left it. If the pops were in the same order as the pushes, r16 and r17 would come back swapped; if one pop were missing, ret would pop the saved r16 and jump to whatever address that byte pair happened to spell.

Arguments and results

Arguments are passed and results returned in one of two ways: in registers, or on the stack.

  • Registers are the fast way for a few small values: the caller puts the argument in an agreed register before the call, the procedure reads it there and leaves its result in an agreed register for the caller to pick up. Agreement is the whole trick — both sides must use the same register, and a procedure that uses registers for arguments cannot also expect them preserved.
  • The stack is the general way: the caller pushes the arguments, then calls; the procedure finds them on the stack just above the return address, and results can be returned the same way or in registers. The return address, the arguments and any saved registers and locals together are the procedure’s stack frame. It costs pushes and pops, but it works for any number of arguments and for recursion, since every live call has its own frame.

The AVR C compiler uses both: the first few arguments of a function travel in registers, r24 down, and the rest on the stack, and a function’s local variables live in its stack frame. Those details are the compiler’s convention, and they are why a C function call is not free — see the main costs in c-language-basics.

A C function’s stack frame

A C compiler puts a function’s local variables in its stack frame, next to the return address and any arguments passed on the stack. The frame is pushed when the function is called and popped when it returns. A local therefore exists only while its call is running, and each call, including each level of a recursion, gets its own copy at its own address. An optimising compiler keeps a small local in a register when it can. The frame is where it goes when it needs memory, and the lifetime is the same either way.

In address order, from high to low, which is the order they are pushed:

  1. arguments, pushed by the caller before the call, if any are passed on the stack;
  2. the return address, pushed by call;
  3. locals, made by the function itself when it starts.

A static local is not in the frame. It is stored with the globals, at a fixed address, so it outlives the call and still holds its value the next time the function runs. Globals sit at the bottom of SRAM, the heap grows up above them, and the stack grows down from RAMEND. A stack that grows far enough to meet the heap has overflowed. How the compiler lays out the whole data memory is in compilation-and-linking.

Figure 378: The stack frame of a C function while it runs, with the lowest address at the top as in the course’s memory maps. The caller pushed any stack arguments, call pushed the return address, and the function made room for its locals a and b above that. SP points at the next free cell, just above the frame. When the function returns, the whole frame is popped and SP goes back to where it was before the call, so a and b no longer exist. The static local c is not in the frame at all. It is stored among the globals at a fixed address, which is why it keeps its value from one call to the next.

The stack and interrupts

An interrupt uses the same stack in the same way. The hardware pushes the return address exactly as call would, and the handler’s reti pops it, like ret (avr-interrupts, 2026-09-21-interrupts). Three things follow:

  • The stack pointer must be set before interrupts are enabled, not merely before the first call. An assembly program with no procedures at all still needs SP initialised once it uses an interrupt.
  • A handler’s pushes and pops must balance, and it must restore every register it uses. This is the same rule as for a procedure, but stricter: an interrupt can arrive between any two instructions, so there is no caller to agree anything with (polling-and-interrupts).
  • Every interrupt that is being handled holds stack space: two bytes of return address plus whatever its handler pushes, and more again if handlers are allowed to nest.

Pitfalls

  • Forgetting to initialise SP in an assembly program. The first call pushes to wherever the reset value points; the ret then reads garbage. In C, not a concern.
  • Unbalanced push/pop inside a procedure — see Figure 377. ret does not check what it pops.
  • Stack overflow. Deep recursion, or big local arrays in C, walk the stack down into the heap and the variables. Nothing on the chip detects it; the symptom is variables changing value for no visible reason.
  • Returning a pointer to a local. The local’s frame is popped by the return, so the pointer points at stack space that the next call will reuse.
  • Clobbering the caller’s registers. A procedure that uses r16 without saving it changes r16 for whoever called it. Either save and restore, or document which registers the procedure destroys — and be consistent.

See also

Pulse Width Modulation

Pulse width modulation (PWM): making a digital output behave like an adjustable analog one by switching it on and off quickly and controlling what fraction of the time it is on. What the duty cycle is, why a fast pulse train has an average value, what that is good for, and how the AVR’s timer/counters generate it in hardware in their two fast PWM modes. From 2026-09-17-pulse-width-modulation; the timers themselves are in avr-timers-and-counters.

Duty cycle

A PWM signal is a periodic pulse — high for part of each period, low for the rest — and it is described by two numbers:

Period \(T\) (s), or equivalently the frequency \(f = 1/T\) (Hz) how often the pulse repeats
On-time \(T_{ON}\) (s) how long the output is high in each period

\[\text{duty cycle} = \frac{T_{ON}}{T} \times 100\%\]

The duty cycle is the percentage of the time the signal is on (high). 0 % is a constant low, 100 % a constant high, 50 % a square wave; modulating the pulse width means changing \(T_{ON}\) while \(T\) stays fixed. The five duty cycles are drawn in 2026-09-17-pulse-width-modulation.

Average value

If the pulses are fast enough, the signal looks like its average. The average of a periodic voltage is the area under one period divided by the period, and for a pulse between 0 and \(V\) the area is a rectangle:

\[V_{avg} = \frac{1}{T}\int_0^{T} v(t)\,dt = \frac{1}{T}\int_0^{T_{ON}} V\,dt = V \cdot \frac{T_{ON}}{T}\]

so the average voltage is the supply voltage times the duty cycle — 1.25 V at 25 % of 5 V, 2.5 V at 50 %. That is the whole point: a pin that can only ever be at 0 V or 5 V delivers, on average, any voltage between, set by a number in a register.

Fast enough means fast compared with the load. A motor’s inertia, a lamp’s thermal mass, the eye’s persistence or an explicit low-pass filter each smooth the pulses into their average; if the period is long enough for the load to follow the pulses, it sees pulses. So the frequency is chosen for the load once, and the duty cycle is the only thing varied afterwards.

Figure 379: A PWM signal and what a slow load makes of it. Above, the pin’s actual voltage: pulses at a fixed period whose width steps up and then down. Below, the same signal after a low-pass filter — a motor’s inertia, an LED as the eye sees it, or a real RC network before a speaker — which cannot follow individual pulses and settles at their running average. The filtered output tracks the duty cycle and not the pulses, with a small ripple left over from the switching, and moving the duty cycle from period to period moves the output smoothly: an analog waveform out of a digital pin. The higher the PWM frequency relative to the load’s response, the smaller the ripple.

What it is for

Generating signals that look analog from a purely digital source. The AVR has no digital-to-analog converter, and PWM plus the load’s own smoothing is how it gets an analog-looking output:

  • Varying the brightness of lights and LEDs — fading is ramping the duty cycle; the eye averages
  • Motor control — the average voltage sets the speed of a DC motor; the inertia averages
  • Generating audio, with appropriate filtering — vary the width from period to period so the average traces a waveform, filter off the pulses, and what is left is the tone

PWM on the AVR: fast PWM

A timer/counter (avr-timers-and-counters) generates PWM with no software involvement at all. The mechanism is the same in every mode: the count is a sawtooth, a compare register draws a horizontal line across it, and the pin changes state where they cross — once at the match and once more when the count wraps. Moving the compare value moves the crossing along the ramp, which moves one edge of the pulse. That is the modulation.

The waveform generation mode bits pick what the top of the sawtooth is, and the compare output mode bits pick which way the pin switches at the crossing.

Mode 3 — top fixed at 255 (WGM[2:0] = 011)

The count runs 0 to 255 and wraps: every period is exactly 256 ticks, so

\[T_{tick} = \frac{1}{CLK/PRE} \qquad T = \frac{256}{CLK/PRE} \qquad f = \frac{CLK}{256 \cdot PRE}\]

and the frequency is set entirely by the prescaler. Both compare registers are free to make pulses, so one timer gives two independent PWM outputs at the same frequency, OCnA and OCnB. With the compare value at 191 the pin is high for 64 of the 256 ticks in inverting mode, a 25 % duty cycle — the worked example in 2026-09-17-pulse-width-modulation.

Mode 7 — top in OCRnA (WGM[2:0] = 111)

The count wraps when it reaches OCRnA instead of 255: the period is OCRnA + 1 ticks and can be chosen,

\[T = \frac{1 + OCRnA}{CLK/PRE} \qquad f = \frac{CLK}{(1 + OCRnA) \cdot PRE}\]

The pulse is then made on the other compare unit, OCRnB against the shorter ramp. The price of choosing the frequency is that compare unit A is spent on it: one PWM output per timer, and OCnA can at most toggle on each wrap. With OCRnA = 127 and OCRnB = 95 the period is 128 ticks and the inverting output is high for 32 of them — again 25 %.

Both are cases of the master formula \(f = CLK / (PRE \cdot (TOP + 1))\) with \(TOP = 255\) or \(TOP = OCRnA\).

Inverting and non-inverting

The compare output mode bits COMnx1:0 decide what the crossing does to the pin in fast PWM:

COMnx1:0 On compare match At the wrap (BOTTOM) Pulse is high for Duty cycle
10 — non-inverting clear OCnx set OCnx OCRnx + 1 ticks, from the wrap to the match \(\dfrac{OCRnx + 1}{TOP + 1}\)
11 — inverting set OCnx clear OCnx \(TOP - OCRnx\) ticks, from the match to the wrap \(\dfrac{TOP - OCRnx}{TOP + 1}\)
01 toggle OCnA — mode 7 only, and only unit A a square wave at half the wrap rate 50 %
00 pin disconnected — ordinary port pin

The two outputs are complements: the same crossing, opposite polarity, and their on-times add to a full period. Non-inverting is the natural choice — a bigger number means a wider pulse — and is what duty cycle = (OCR + 1) / 256 refers to.

Figure 380: How the compare value maps to duty cycle in mode 3, for the two polarities. In non-inverting mode the pulse runs from the wrap to the match, so it is \(OCR + 1\) ticks of 256 and the duty rises linearly with the register from just under 0.4,% at 0 to 100,% at 255. In inverting mode the pulse runs from the match to the wrap, so it is \(255 - OCR\) ticks: the same line reflected, 100,% at 0 down to 0,% at 255. The two always sum to 100,%. Neither polarity reaches both ends: non-inverting cannot give a true 0,% (a compare value of 0 still gives one tick high) and inverting cannot give 100,%; a program that needs the output fully off disconnects the pin instead.

Setting it up

Four registers, all from the header names (c-preprocessor-and-avr-headers, bit-masking) — timer 0, mode 3, non-inverting on OC0B (PB4), clock ÷ 64, 25 % duty:

DDRB   |= (1<<4);                              /* OC0B is PB4: the timer decides what, DDR decides whether */
TCCR0A  = (1<<COM0B1) | (1<<WGM01) | (1<<WGM00); /* non-inverting on B; fast PWM, TOP = 255 */
TCCR0B  = (1<<CS01) | (1<<CS00);               /* clock / 64: 8 MHz / (256 * 64) = 488 Hz */
OCR0B   = 63;                                  /* (63 + 1) / 256 = 25 % */

After this the CPU never touches the pin; changing the duty cycle is one assignment to OCR0B, and it takes effect at the next wrap. The compare registers are double buffered in the PWM modes: a value written is held back and loaded when the count wraps, so a pulse already under way is never cut short. The frequencies mode 3 can produce at 8 MHz are one per prescaler tap:

Prescaler \(f = 8\,\text{MHz} / (256 \cdot N)\)
1 31.25 kHz
8 3.91 kHz
64 488 Hz
256 122 Hz
1024 30.5 Hz

For an LED anything from 122 Hz up is flicker-free; for audio the 31.25 kHz setting is the one above hearing. If a frequency between the taps is needed, mode 7 with an OCR0A chosen from the master formula.

Phase correct PWM

The other family of PWM modes has the counter count up and then down — a triangle rather than a sawtooth — and switch the pin at the compare value on both slopes. The pulse is then symmetric about the peak of the triangle, so the centre of every pulse stays at the same point in the period as the width changes, instead of the leading edge staying fixed and only the trailing edge moving. That is smoother for motor control, where the timing of the current pulse relative to the period matters; the cost is a period twice as long for the same top, so half the frequency. Timer 1 adds a phase and frequency correct variant on top. The two families are drawn side by side in 2026-09-17-pulse-width-modulation. This course uses fast PWM only.

See also

Sequential Circuits

A sequential circuit is a circuit whose output depends not only on the current inputs but also on the values it is currently storing. The storage is done with flip-flops — see flip-flops-and-latches for the storage elements themselves.

The output of any logic gate or combinational circuit depends on the current value of the inputs only, so if an input changes, the output can change too and the previous value is lost forever. A circuit with memory can remember a value even when the input changes. First met in 2026-08-10-introduction-to-sequential-circuits.

Combinational vs sequential

Combinational Sequential
Contents Logic gates only (no flip-flops) Includes flip-flops as well as logic gates
Output determined by The inputs alone — uniquely Current inputs and current state
Repeatability Same inputs always give the same output Same inputs can give different outputs, depending on state
When output changes Whenever an input changes Only when the clock ‘ticks’
Examples Adders, multiplexers, decoders, demultiplexers, encoders (see combinational-logic-blocks) Counters, registers (see [counters], shift-registers)

The two example lists are worth memorising as the dividing line: the blocks built earlier in the course are all combinational, and the ones that follow — registers, counters, state machines — are all sequential.

A combinational example from earlier in the course: \(A\) into one input of an AND gate, \(B\) and \(C\) into an OR gate whose output feeds the AND gate’s other input, giving \(X = A(B+C)\). Nothing in that circuit remembers anything — change \(A\), \(B\) or \(C\) and the output follows immediately (after propagation delay; see timing-diagrams).

The key contrast: if an input to a combinational circuit changes, the output can change too and the previous value is lost forever. A sequential circuit can hold onto a value even after the input that produced it has gone away.

State

  • State = the value stored in the flip-flops.
  • Output depends on the inputs and the state.
  • Next state depends on the inputs and the (present) state.

“Present state” is what the flip-flops hold right now; “next state” is what they will hold after the next clock edge. The combinational logic computes the next state from the present state and the inputs; the flip-flops only adopt it when the clock edge arrives.

General structure of a sequential circuit

The standard block diagram has two blocks and a feedback loop.

Figure 381: The general sequential circuit (after Mano, Digital Design, 3rd edition). Two things carry the whole idea: the loop running from the flip-flops back into the combinational block, which is what makes the circuit sequential, and the clock stub, which enters the flip-flops and nothing else. The ‘Logic Gates’ callout marks the combinational block as gates only.

  • A combinational circuit block (just logic gates). It takes the external inputs plus the feedback from the flip-flops, and produces the external outputs plus the values to be loaded into the flip-flops.
  • A flip-flops block (the storage elements). Its data inputs come from the combinational circuit; it also takes clock pulses as a separate control input.
  • A feedback path runs from the flip-flops’ outputs back around into the combinational circuit’s inputs. That loop is what makes the circuit sequential — the stored state is fed back in and influences the next output and the next state.

The clock pulses go only to the flip-flops, not to the combinational logic. Cut the feedback wire and what is left is a plain combinational circuit with a register bolted on the end; it is the loop that makes the difference.

This same block diagram reappears in shift-registers, [counters] and state-machines — those are all just specific choices of what goes in the combinational block.

Synchronous sequential circuits

In a synchronous sequential circuit the storage elements can only change at discrete instants of time, set by a common clock signal.

Figure 382: A clock signal. The five arrows all point at rising edges: these are the only instants at which any storage element in a synchronous circuit is allowed to change. Everywhere else on the axis the flip-flops are inert, however much their inputs move — which is exactly the opposite of a logic gate, whose output changes whenever its input does.

  • Assume a clock signal — a regularly repeating train of pulses alternating between 0 and 1.
  • The outputs of the storage elements change only on the edges of that control signal.
  • Contrast with logic gates, whose outputs change whenever their inputs change.

Because every flip-flop shares the same clock, the whole circuit’s state changes in one step at each clock edge, which is what makes such circuits tractable to design and analyse.

It also means the clock period sets the pace of the design: everything the combinational block has to compute must settle within one tick. This follows from the propagation delays of timing-diagrams.

See also

Serial Communication

Sending data between devices one bit at a time, and how the receiving end makes sense of what arrives: serial against parallel, synchronous against asynchronous, the UART frame, parity, how a receiver samples the line, and baud rate. Then the synchronous serial buses, where one master clocks data to and from several slaves: SPI and I²C, compared with the UART, and bit bashing for when there is no hardware for a standard. The AVR’s hardware is in avr-usart and avr-spi. First met in 2026-09-24-serial-io and 2026-10-05-more-io.

Serial and parallel

Parallel Serial
Wires carrying data one per bit one
How a byte travels all 8 bits at once 8 bits one after another
Cost many pins and wires time: a byte takes 8 bit times

Inside a chip, data moves in parallel: a port is eight pins, a register is eight flip-flops. Between devices, pins and wires are what is scarce, so nearly every link is serial. The conversion at each end is the job of a shift register (shift-registers): load a byte in parallel and shift it out one bit at a time to send, shift bits in and read the byte out in parallel to receive.

By convention the sending end of a link is Tx and the receiving end is Rx. A device that does both has one of each, and two such devices are joined crossed over: each one’s Tx goes to the other’s Rx.

Synchronous and asynchronous

A receiver has to know when to look at the data wire, as well as what is on it. There are two ways to tell it.

Synchronous: one end sends a clock on a second wire. The receiver reads the data wire on each clock edge. Nothing has to be agreed in advance about speed, beyond the fastest the receiver can follow. SPI, the Serial Peripheral Interface, and I²C both work this way (below).

Asynchronous: there is no clock wire. Each end has its own clock, the two agree on the speed beforehand, and the receiver recovers the exact timing from the data stream itself. That only works if the stream is guaranteed to contain edges to time against, so the data is encoded:

Encoding How it guarantees edges Used by
start and stop bits every character begins with a fall from 1 to 0 UART
4B/5B, 8B/10B every 4 or 8 bits are replaced by a 5- or 10-bit code that never has a long run fast network links
bit stuffing an opposite bit is inserted after a run of identical bits USB at low and full speed

A UART is a Universal Asynchronous Receiver and Transmitter. A USART can also work synchronously. The pictures of all four cases are in 2026-09-24-serial-io.

The UART frame

A UART sends data in frames. Between frames the line rests at 1, the idle level. A frame is:

Order Field How many Value
1 start bit 1 always 0
2 data bits 5 to 9 the data, least significant bit first
3 parity bit 0 or 1 chosen to make the count of 1s even or odd
4 stop bits 1 or 2 always 1

Why each part is there:

  • The start bit is 0 because the idle line is 1. The fall from 1 to 0 is the one event the receiver can be sure of, and everything else is timed from it.
  • The stop bit is 1 so that the line is back at the idle level when the frame ends. Whatever the last data bit was, the next start bit is then a fall again.
  • The data bits go least significant first. A receiver that assumes the opposite reads every byte bit-reversed.

The format is usually written as three items: data bits, parity (N for none, E for even, O for odd), stop bits. 8N1 is 8 data bits, no parity, 1 stop bit, and is by far the commonest.

Worked: the letter s

A character is sent as its ASCII code (c-language-basics). The letter s is 115, 0x73, 0111 0011. In 8N1 the line carries, in time order:

start b0 b1 b2 b3 b4 b5 b6 b7 stop
0 1 1 0 0 1 1 1 0 1

Read left to right, the data bits are 1100 1110, the byte written backwards.

Figure 383: The letter s, 0x73, on the wire as an 8N1 frame. Time runs left to right and each cell is one bit time. The line idles at 1, falls for the start bit, carries the eight data bits least significant first, and returns to 1 for the stop bit. Written most significant bit first the byte is 0111 0011; the wire carries it in the opposite order.

Parity

The parity bit lets the receiver detect that a frame was damaged. The two ends agree on the kind:

  • Even parity: the number of 1s in the data bits and the parity bit together is even.
  • Odd parity: that number is odd.

To send: count the 1s in the data. Choose the parity bit that makes the total the agreed kind.

To check: count the 1s in the data and the parity bit as received. If the total is the wrong kind, there was an error.

Data 1s in the data Even parity bit Odd parity bit
0xA7 = 1010 0111 5 1 0
0xA9 = 1010 1001 4 0 1
0x73 = 0111 0011 5 1 0
0x00 = 0000 0000 0 0 1

The even parity bit is the XOR of the data bits (logic-gates): XOR is 1 exactly when an odd number of its inputs are 1, which is exactly when a 1 is needed to make the total even. The odd parity bit is its complement.

Worked check. 0xA9 arrives with parity bit 1 on an even-parity link. The data has four 1s, and the parity bit makes five. Five is odd, so the frame is in error.

What parity cannot do:

  • It cannot say which bit is wrong, so it cannot correct anything. The frame has to be discarded or sent again.
  • It misses any even number of flipped bits. Two flips cancel and the count comes out right.

Detecting and correcting needs several check bits arranged so that the pattern of failed checks points at the wrong bit. That is a Hamming code, and it is not part of a UART frame.

Sampling: finding the bits without a clock

The receiver knows the bit time from the agreed baud rate. What it does not know is when a frame will start. It finds out by watching:

  1. It samples the line many times per bit: 16 on the AVR.
  2. While the line is idle, every sample is 1. A sample of 0 means a start bit may have begun, and the receiver starts counting samples from there.
  3. It reads the three samples at the centre of each bit time and takes the majority. For the first bit time the answer must be 0, or the fall was only noise and the receiver goes back to waiting.
  4. It carries on, one bit time after another, for the data bits, the parity bit if there is one, and the stop bit.
  5. The stop bit must read 1. If it reads 0 the frame is wrong: a framing error, usually a sign that the two ends disagree about the baud rate or the format.

The picture is in 2026-09-24-serial-io.

Why the clocks need not match exactly. Suppose the receiver’s clock is slightly slow. Each sampling point is then a little later within its bit than the one before, and by the last bit of the frame the lateness has added up. As long as the total stays under half a bit time, every sample still lands inside the right bit. A 10-symbol frame gives the error about ten bit times to build up, so the two clocks have to agree to within a few percent. At the next start bit the count starts again from the new falling edge and the accumulated error is gone. That re-timing on every frame is what the start bit is for.

Baud rate and bit rate

Baud rate = symbols per second. Bit rate = useful data bits per second.

On a UART line a symbol is one bit time, and start, parity and stop bits are symbols that carry no data. So the bit rate is always lower than the baud rate, by the fraction of the frame that is data.

Format Symbols per frame Data bits Data fraction At 9600 baud
8N1 10 8 80 % 7680 bit/s, 960 bytes/s
8E1 or 8O1 11 8 73 % 6982 bit/s, 873 bytes/s
8N2 11 8 73 % 6982 bit/s, 873 bytes/s
7E1 10 7 70 % 6720 bit/s, 960 characters/s

The method: frames per second is the baud rate divided by the symbols per frame, and bits per second is that times the data bits per frame. For 8N1 at 9600 baud, \(9600 / 10 = 960\) frames per second and \(960 \times 8 = 7680\) bits per second.

Figure 384: Three frame formats, one cell per symbol. Shaded cells carry data and white cells are framing. Every format here carries eight data bits, so adding a parity bit or a second stop bit makes the frame eleven symbols long instead of ten, and at the same baud rate fewer frames fit into a second.

The standard baud rates are 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600 and 115200.

Both ends must agree

Four settings define a UART link, and none of them is sent over it:

  1. the baud rate;
  2. the number of data bits;
  3. the parity: none, even or odd;
  4. the number of stop bits.

A terminal program on a PC asks for all four, plus which serial port to use. If the two ends differ, the receiver still samples the line and still produces bytes. They are just the wrong bytes, sometimes with framing or parity errors flagged and sometimes not. Garbled characters on a terminal almost always mean a mismatch here, most often the baud rate.

RS232

A serial standard more than 40 years old and still in use, typically on a 9-pin D-sub connector. Its frames are UART frames. Its voltages are not the microcontroller’s:

Microcontroller pin RS232 line
logical 1 5 V negative, −3 V to −15 V
logical 0 0 V positive, +3 V to +15 V

So RS232 is inverted and uses larger voltages of both signs. A level-converter chip such as the MAX-232 goes between an AVR pin and an RS232 line. Connecting the two directly does not work and can damage the pin.

RS232 is full duplex: there is a separate wire for each direction, so both ends can transmit at once. The standard defines many signals, and the smallest useful set is three: TxD, RxD and ground. Ground is needed because a voltage only has meaning against a reference both ends share.

Buses: masters and slaves

A UART joins exactly two devices. A bus is a set of wires shared by several, and that raises the question of who decides when a transfer happens.

  • The master initiates and controls the transfer of data: it decides when a transfer starts, which device it is with and which way the data goes, and on a synchronous bus it drives the clock.
  • A slave waits for requests and responds to the master. It never starts a transfer.

Some devices can be both, at different times. The AVR’s SPI and TWI ports can each be set up as a master or as a slave, and on an I²C bus more than one device may take a turn at being master. Memory can never be a bus master: all a memory can do is answer a read or a write of an address that something else has chosen. On a processor’s memory bus the CPU is the master.

Synchronous serial buses

Both buses here send a clock from the master alongside the data, so neither needs start and stop bits or an agreed baud rate. They differ in how the master picks which slave it is talking to.

SPI

The Serial Peripheral Interface has four signals: the clock SCK, a data wire each way, MOSI (master out, slave in) and MISO (master in, slave out), and an active-low select \(\overline{\text{SS}}\) for each slave. The master and the slave each hold an 8-bit shift register, and MOSI and MISO join them into a ring, so on every clock pulse one bit goes each way. Eight pulses swap the two bytes: every transfer is an exchange. Several slaves either get a select line each, or are daisy-chained on one select with the data passing through each in turn. All of this, with the AVR’s SPI port, is in avr-spi.

I²C and TWI

I²C, the Inter-Integrated Circuit bus, was created by Philips Semiconductor, now NXP. TWI, the Two-wire Interface, is Atmel’s name for it. There are two wires, and every device connects to both:

  • SDA, serial data, which carries data in either direction, one way at a time;
  • SCL, serial clock, driven by the master.

Figure 385: An I²C bus. Every device connects to the same two wires: SDA carries the data, in either direction, and SCL carries the clock from the master. No device ever drives a line high. Each can only pull a line low or let go of it, and the two pull-up resistors hold a line at 1 while nobody is pulling, so two devices can never fight over a line. Because every device hears every transfer, the master begins each one with the address of the slave it is for. A dot is a connection; where a lead crosses SDA without a dot there is no connection.

Why the pull-ups. Every output on the bus is open drain: it can connect its line to ground or leave it alone, and never connects it to \(V_{CC}\). A line is 1 when nobody is pulling it down and 0 when anybody is. Any number of devices can share a wire that way without two outputs ever fighting.

Addresses instead of select lines. Every device sees every transfer, so the master starts each one by sending the address of the slave it wants, and only that slave answers. Adding a device adds no wires.

On the ATmega324A the TWI uses PC0 as SCL and PC1 as SDA, and the datasheet describes it on pages 211 to 239 (2026-10-05-more-io).

UART, SPI and I²C compared

UART SPI I²C / TWI
Clock none: both ends agree a baud rate SCK, from the master SCL, from the master
Data wires TxD and RxD, one each way MOSI and MISO, one each way SDA, shared by both directions
Both directions at once? yes yes: every transfer is an exchange no
Devices two one master, many slaves many, some able to be master
Choosing a slave no need: only two ends a select line per slave, or a daisy chain an address sent on the bus
Wires, besides ground 2 3, plus a select per slave 2
On the ATmega324A USART0 (PD0, PD1), USART1 (PD2, PD3) one SPI port, PB4 to PB7 one TWI port, PC0 and PC1

Bit bashing

Sometimes a microcontroller has no hardware support for a bus standard, or not enough interfaces of it. The standard can still be used by simulating it on general purpose port pins: the program sets and clears the output pins and reads the input pins itself, in exactly the order the standard lays down. That is bit bashing, also called bit banging.

Figure 386: Who does the work. Above, with an SPI port: the program writes one byte to the data register and the port’s own clock generator and shift register produce all eight clock pulses and move all sixteen bits, while the CPU is free. Below, bit bashing the same transfer on three ordinary pins of port D: the CPU runs a loop that puts each bit on the MOSI pin, raises and lowers the SCK pin and reads the MISO pin, eight times over, through the port’s PORTD and PIND registers. The slave cannot tell the difference. The CPU is busy for the whole transfer, and the clock can go no faster than the loop.

Worked: an SPI master in software

Three spare pins of port D, plus one for the select, can be an SPI master in mode 0, most significant bit first, with nothing but the set, clear and test idioms of bit-masking:

#define BB_SS    4                 /* port D pins used for the software SPI */
#define BB_SCK   5
#define BB_MOSI  6
#define BB_MISO  7

void bb_init(void) {
    DDRD  |= (1<<BB_SS) | (1<<BB_SCK) | (1<<BB_MOSI);   /* outputs; MISO stays an input */
    PORTD |= (1<<BB_SS);                                /* nothing selected             */
    PORTD &= ~(1<<BB_SCK);                              /* the clock rests low          */
}

uint8_t bb_exchange(uint8_t out) {
    uint8_t in = 0;
    uint8_t i;

    for (i = 0; i < 8; i++) {
        if (out & 0x80) {                    /* put the top bit on MOSI           */
            PORTD |= (1<<BB_MOSI);
        } else {
            PORTD &= ~(1<<BB_MOSI);
        }
        out <<= 1;
        PORTD |= (1<<BB_SCK);                /* rising edge: both ends read       */
        in = (in << 1) | ((PIND >> BB_MISO) & 1);
        PORTD &= ~(1<<BB_SCK);               /* falling edge: the slave moves on  */
    }
    return in;
}

Used like the hardware version: pull BB_SS low, call bb_exchange once per byte, raise BB_SS. Reading MISO straight after raising SCK is safe, because the slave put that bit out on the previous falling edge, or when it was selected, and it stays put until the next falling edge.

What it costs.

  • The CPU does everything. Each bit is several instructions, so the clock runs far slower than the 4 MHz the SPI port can make, and the program does nothing else meanwhile.
  • Synchronous standards bash easily. The master makes the clock, so if the loop is held up between two edges, by an interrupt for instance, the transfer simply pauses. The slave waits for the next edge however long it takes.
  • Asynchronous standards are harder. A bit-bashed UART has no clock to wait for, so every bit time has to be produced exactly, and an interrupt landing in the middle of a frame can wreck it.

Common mistakes

  • Tx to Tx. The link is crossed: one end’s transmit pin goes to the other’s receive pin.
  • Treating baud rate as bit rate. 9600 baud in 8N1 moves 7680 data bits a second, not 9600.
  • Reading the bits most significant first. A UART sends bit 0 first.
  • Leaving the parity bit out of the count. The rule is about the data bits and the parity bit together.
  • Expecting parity to fix or locate an error, or to catch every error.
  • Drawing the idle line at 0. Idle is 1, the start bit is 0, the stop bit is 1.
  • Forgetting ground between two boards.
  • Crossing SPI’s data wires. MOSI goes to MOSI and MISO to MISO: the names already say which end drives.
  • Leaving out the pull-ups on an I²C bus. Nothing ever drives the lines high, so without them they never return to 1.
  • Thinking memory could start a transfer. Memory is always a slave.

See also

  • avr-usart — the ATmega324A’s USART: registers, baud-rate values, code and interrupts
  • avr-spi — the ATmega324A’s SPI port: the exchange, timing, several slaves, registers, clock rate, code
  • bit-masking — the set, clear and test idioms the bit-bashing code is made of
  • shift-registers — parallel in, serial out, and the reverse
  • logic-gates — XOR, which computes a parity bit
  • timing-diagrams — how the waveforms here are drawn and read
  • magnetic-disks — a disk sector, framed like a UART frame: preamble, data, ECC, gap
  • io-board — the USB-serial device that joins the breadboard to a PC
  • 2026-09-24-serial-io — Lecture 18 · 2026-10-05-more-io — Lecture 19

Seven-Segment Display

How a digit is shown on the IO board’s seven-segment display: the segment lettering, the byte that lights a pattern, the lookup table for all ten digits, and the common-cathode line that selects which of the two digits is lit. First met in 2026-09-10-more-c-programming-on-the-avr; the board’s header is in io-board and the port registers in avr-io-ports.

Segments

Seven bars lettered a to g, plus a decimal point dp:

Segment Position
a top
b upper right
c lower right
d bottom
e lower left
f upper left
g middle
dp the dot, lower right

— clockwise from the top for a to f, then g across the middle. Each segment is an LED; a 1 on its line lights it.

The byte

The display is driven from one 8-bit port, one bit per segment, in this order:

bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
dp g f e d c b a

So the byte for a digit is read off by asking, segment by segment, whether it is lit. Two worked examples:

Digit Lit dp g f e d c b a Sum Decimal
0 a b c d e f 0 0 1 1 1 1 1 1 \(32 + 16 + 15\) 63
2 a b g e d 0 1 0 1 1 0 1 1 \(64 + 16 + 8 + 3\) 91

PORTA = 63; shows a 0; PORTA = 91; shows a 2. The 2 and both bytes are drawn in 2026-09-10-more-c-programming-on-the-avr.

All ten digits

The lookup table from the program below, decoded:

Digit Decimal Binary (dp g f e d c b a) Segments lit
0 63 0011 1111 a b c d e f
1 6 0000 0110 b c
2 91 0101 1011 a b d e g
3 79 0100 1111 a b c d g
4 102 0110 0110 b c f g
5 109 0110 1101 a c d f g
6 125 0111 1101 a c d e f g
7 7 0000 0111 a b c
8 127 0111 1111 a b c d e f g
9 111 0110 1111 a b c d f g

Displays differ on whether 6 lights segment a, the top bar, and whether 9 lights segment d, the bottom bar. This table lights both, giving a hooked 6 and an underlined 9.

Figure 387: All sixteen values a nibble can hold, as seven-segment patterns, with the byte that produces each one in decimal underneath — the sixteen entries of the lookup table in order. Heavy segments are lit; the bit order is dp g f e d c b a with a at bit 0, so each number is read straight off the lit segments: 63 is every segment but g, 6 is b and c alone. The hex letters b and d are lowercase because their capitals would be indistinguishable from 8 and 0 on seven segments; A, C, E and F have no such clash.

Hex digits A–F

Four input bits hold 0–15, and the six values past 9 can be shown too, as hex letters. Two of them have to be lowercase: an uppercase B on seven segments is an 8, and an uppercase D is a 0.

Value Shows Segments lit dp g f e d c b a Decimal
10 A a b c e f g 0111 0111 119
11 b c d e f g 0111 1100 124
12 C a d e f 0011 1001 57
13 d b c d e g 0101 1110 94
14 E a d e f g 0111 1001 121
15 F a e f g 0111 0001 113

With these appended the table has sixteen entries and every value a masked nibble can produce is a valid index, so the guard in the program below can go:

uint8_t seven_seg[16] = { 63,6,91,79,102,109,125,7,127,111,
                          119,124,57,94,121,113 };

This is Lab 11’s Task 2 (week8-lab-avr-c-programming), and the same table drives the hex adder of its Task 3.

The program

#include <avr/io.h>

/* Seven segment display values */
uint8_t seven_seg[10] = { 63,6,91,79,102,109,125,7,127,111};

int main(void) {
  uint8_t digit;

  /* Set port A pins to be outputs, port C pins to be inputs */
  DDRA = 0xFF;
  DDRC = 0;    /* This is the default, could omit. */
  while(1) {
    /* Read in a digit from lower half of port C pins */
    /* We read the whole byte and mask out upper bits */
    digit = PINC & 0x0F;
    /* Write out seven segment display value to port A */
    if(digit < 10) {
      PORTA = seven_seg[digit];
    } else {
      PORTA = 0;
    }
  }
}

Port A drives the eight segment lines; the low four bits of port C are the input digit. The loop reads the digit, masks off the upper nibble (bit-masking), looks the pattern up and writes it. The if guards the table — four bits can be 10–15, and seven_seg[10] is past the end of the array (c-pointers-and-arrays); those inputs blank the display instead.

Lookup table, not arithmetic. There is no formula that turns a digit into its segment pattern, so the program does not try: the ten answers are precomputed and indexed. It is the general pattern for any input-to-output mapping that is small and irregular, and it is what the array is for.

Two digits, one set of lines: CC

On the IO board the display has two digits but the header carries one set of segment pins — DP, G … A — plus one more, CC, the common cathode (io-board). The segment lines go to both digits; CC decides which one is actually lit:

CC Lit
1 left digit
0 right digit

Figure 388: Why one port can drive two digits. The eight segment lines are wired to both digits in parallel, so both always receive the same pattern; the CC line selects which digit’s common cathode is connected to ground, and only that digit lights. One byte and one select bit therefore describe the whole display at any instant. To show two different digits the program alternates — left pattern with CC = 1, then right pattern with CC = 0 — fast enough that the eye sees both at once.

Writing a digit therefore takes two outputs: the segment byte on port A, and CC on whichever pin it is wired to. The program above drives a single digit and never touches CC; in Lab 11 CC is simply jumpered to a button, so pressing it moves the same digit across.

Display multiplexing

Showing a two-digit number means time-sharing the segment lines: write the tens pattern with CC = 1, wait, write the ones pattern with CC = 0, wait, repeat. Alternate fast enough — every millisecond, say — and persistence of vision merges the two into a steady two-digit display, each digit at half brightness because it is lit half the time. Slow the alternation to a few times a second and the trick becomes visible, with the digits taking turns. The waiting is a timer’s job (avr-timers-and-counters); the whole program, and a timing diagram of the two digits taking turns, is Lab 12’s Task 2 (week8-lab-avr-timers). Two things the ordering has to get right: write the segments before switching CC, so the newly selected digit never flashes the other digit’s pattern, and keep the tick regular, or one digit will look brighter than the other.

See also

Shift Registers

Registers and shift registers are the simplest useful sequential circuits — groups of D flip-flops sharing a common clock.

Registers

  • A register is a group of flip-flops. An \(n\)-bit register consists of \(n\) flip-flops and is capable of storing \(n\) bits.
  • A register is a sequential circuit without any combinational logic — it is just the storage elements and their shared control lines.
  • Registers are used to store binary information (data/instructions) inside a processor.

A 4-bit register:

Figure 389: A 4-bit register (Mano, Digital Design, 3rd ed.). Four flip-flops, four parallel inputs, four parallel outputs, and exactly two shared control lines — no gate anywhere, which is what makes a register a sequential circuit without combinational logic. The pin labelling is Mano’s, which differs from the rest of the course: the clock input is lettered C rather than CLK and the asynchronous clear is lettered R, marked active-low by the bubble on the pin. The course uses several labellings for both (see the diagram-notation note).

Signal Connection
\(I_0 \ldots I_3\) the four parallel data inputs, one to each flip-flop’s \(D\) input
\(A_0 \ldots A_3\) the four parallel outputs, taken from each flip-flop’s \(Q\)
Clock a single common line driven to the \(C\) (clock) input of all four flip-flops
Clear a single common line driven to the \(R\) (reset) input of all four flip-flops, drawn active-low (bubble on the input)

So on each rising clock edge all four flip-flops simultaneously capture their \(I\) inputs; asserting Clear forces all four outputs to 0 asynchronously (see flip-flops-and-latches for asynchronous SET/CLR).

Shift registers

A shift register is a register which is capable of shifting its binary information in one or both directions.

The 4-bit shift register example is built as a chain: the serial input \(SI\) feeds the \(D\) input of the first flip-flop; each flip-flop’s \(Q\) output feeds the next flip-flop’s \(D\) input; the last flip-flop’s \(Q\) is the serial output \(SO\). All four flip-flops share a common \(CLK\) line.

Figure 390: The 4-bit shift register (Mano’s Fig. 6-3). The whole device is four D flip-flops and one wire each: the only structural difference from the register above is where each D input comes from. The grey stage names Q0 to Q3 are there so the trace table below can be read against the drawing.

On each rising clock edge every stored bit moves one place along the chain, the bit currently on \(SI\) enters the first stage, and the bit that was in the last stage leaves at \(SO\).

The common clock is what makes the shift well-defined. Every flip-flop samples its \(D\) input at the same instant, so each stage captures its neighbour’s old value, not the new one the neighbour is simultaneously taking on; the whole word moves exactly one place per edge rather than racing along the chain. This is the point of the rule that in a synchronous sequential circuit all the sequential elements share a common clock signal — see sequential-circuits.

Worked through by hand, with stages labelled \(Q_0\) (nearest \(SI\)) through \(Q_3\) (= \(SO\)), starting from all zeros and shifting in the bit sequence 1, 0, 1, 1:

Clock edge \(SI\) \(Q_0\) \(Q_1\) \(Q_2\) \(Q_3\) (\(=SO\))
(initial) — 0 0 0 0
1 1 1 0 0 0
2 0 0 1 0 0
3 1 1 0 1 0
4 1 1 1 0 1

After 4 clock edges the 4 serially-supplied bits sit in the 4 flip-flops, and one further edge would push the first of them out of \(SO\).

Serial ↔︎ parallel conversion

Shift registers can be used to do serial-to-parallel conversion, and vice versa. This is the reason they show up everywhere data has to travel over a single wire but be used a word at a time.

  • Serial in, parallel out: drive the bits one per clock edge into \(SI\); after \(n\) edges, the \(n\) flip-flop \(Q\) outputs — read as a group — are the parallel word. This is exactly the table above: clock 4 bits in, then read \(Q_0 Q_1 Q_2 Q_3\) in parallel.
  • Parallel in, serial out: load the \(n\) bits into the flip-flops in one clock edge (a parallel load — see Figure 391), then read them off \(SO\) one bit per edge — the first bit is sitting at \(SO\) as soon as the load edge lands, and \(n-1\) further edges bring the rest.
Note

The parallel outputs are simply the \(Q\) pins of the flip-flops already present in Figure 390, brought out as a group. Nothing extra is added to the circuit for serial-in/parallel-out at all.

Parallel load vs serial shift

A plain shift register can only be filled one bit per clock. To also allow parallel load — all \(n\) bits written at once from \(n\) parallel inputs — each flip-flop’s \(D\) input is fed from a 2-to-1 multiplexer (see combinational-logic-blocks) instead of directly from the previous stage:

Mux select Mux data input chosen Effect on that stage
“shift” the previous stage’s \(Q\) (or \(SI\) for the first stage) serial shift by one place
“load” that stage’s parallel data input \(I_i\) parallel load of the whole word in one clock edge

The select line is common to all the muxes, so on each clock edge the register either shifts by one place or loads the whole parallel word.

Figure 391: The parallel-load shift register: one 2-to-1 multiplexer in front of every flip-flop’s D input, with a single LOAD line steering all four at once. Follow the top mux input across and it is the plain chain of the previous figure; follow the bottom input and every stage is loaded from its own I pin in one edge. The Q pins do double duty as the parallel output. Which mux input is which is a free choice: here LOAD equals 0 for shift and 1 for load.

Adding a hold. The same trick gives a register an enable: widen each mux by one input and wire that input to the stage’s own \(Q\), so on a “hold” edge every flip-flop reloads the value it already has and the word does not move. This is the standard way to stop a register without gating the clock — gating the clock risks glitching it — and it is what a “recirculating” input means. It follows from the mux construction, and a past-paper question turns on it (csse2010-sample-midsem-1 Q18, where each mux’s input 0 is its own stage’s \(Q\) looped back, so the control line chooses shift or hold).

The mux-based bidirectional shift element

A single building block makes a shift register that shifts in either direction (drawn in the lecture note):

  • a 2-to-1 multiplexer whose output drives the \(D\) input of one D flip-flop;
  • the mux’s select line is a control signal called DIRN;
  • DIRN = 0 selects mux input 0 → left shift;
  • DIRN = 1 selects mux input 1 → right shift;
  • the flip-flop’s \(Q\) is that stage’s output, and the flip-flop is clocked from the common clock.

Chaining \(n\) of these elements and wiring, for each stage, mux input 0 to the neighbour on the left-shift side and mux input 1 to the neighbour on the right-shift side gives an \(n\)-bit bidirectional shift register: one shared DIRN line decides which way the whole register shifts on the next clock edge.

Figure 392: A 3-bit bidirectional shift register: three copies of the DIRN element, one shared DIRN line and one shared clock. Q2 is the most significant bit, on the left. Mux input 0 of every stage comes from the stage on its right (left shift, bits moving towards Q2); mux input 1 comes from the stage on its left (right shift). The two ends need a serial input each, because on each direction one end has no neighbour to take a bit from. Wires that cross without a dot are not connected.

For a 3-bit register with bits \(Q_2 Q_1 Q_0\) (\(Q_2\) most significant), taking left shift to mean bits move towards the more-significant end:

Stage Mux input 0 (DIRN=0, left shift) Mux input 1 (DIRN=1, right shift)
\(Q_2\) \(Q_1\) \(SI_R\) (serial input for right shifts)
\(Q_1\) \(Q_0\) \(Q_2\)
\(Q_0\) \(SI_L\) (serial input for left shifts) \(Q_1\)

One clock edge applied to a 3-bit register holding \(Q_2 Q_1 Q_0 = 110\), with both serial inputs held at 0:

DIRN Operation Before (\(Q_2Q_1Q_0\)) After (\(Q_2Q_1Q_0\))
0 left shift 110 100
1 right shift 110 011

See 2026-08-13-shift-registers for the exercise that asks for this register.

The configurations a shift register can be wired into

There are seven named configurations, parts (a) to (g) of a figure from Floyd, recapped at the start of Lecture 7:

  • serial in / shift right / serial out
  • serial in / shift left / serial out
  • parallel in / serial out
  • serial in / parallel out
  • parallel in / parallel out
  • rotate right
  • rotate left

The first six are all the same flip-flop chain differing only in where each \(D\) comes from and which pins are brought out: adding a mux per stage buys the parallel input, tapping the \(Q\) pins buys the parallel output, and swapping the direction of the chain buys left instead of right. The last two, the rotates, are the chain with its serial output wired back to its serial input, so no bit is lost and the word cycles.

Universal shift register

A universal shift register is the combination of all of the above capabilities in one device: it can hold its value, shift left, shift right, and be parallel-loaded, with the operation selected by control inputs.

Structurally it is the two constructions above stacked: four operations need a 4-to-1 mux per flip-flop and two select lines, with the four mux inputs being the stage’s own \(Q\) (hold), its left neighbour, its right neighbour, and its parallel input \(I_i\).

Wide (multi-bit) shift registers

A shift register does not have to shift one bit at a time — it can shift a whole multi-bit word per clock edge. An example is an 8-bit wide, 4-stage queue:

Figure 393: The 4-stage 8-bit queue. Each block is a whole 8-bit register rather than a single flip-flop: the vertical line between A and H, and between Q1 and Q8, is shorthand for the six pins in between. Functionally identical to the 1-bit chain — one stage’s outputs are the next stage’s inputs, everything on one clock — but each stage now holds a byte, so a byte presented at Input reaches Output four clock edges later.

  • four registers in a row, each 8 bits wide (inputs labelled \(A\) through \(H\), outputs labelled \(Q_1\) through \(Q_8\));
  • the 8-bit Input bus feeds the first register’s 8 data inputs;
  • each register’s 8 \(Q\) outputs feed the next register’s 8 data inputs, as a bus;
  • the last register’s outputs are the 8-bit Output;
  • all four registers share a common clock line, and each has an ENB (enable) input.

Functionally this is the same chain as the 1-bit shift register, but each “stage” holds a byte rather than a bit — so it behaves as a 4-deep queue of bytes: a byte presented at Input appears at Output four clock edges later.

This is also the shape the Lab 06 combination lock takes, at a smaller size: a two-stage, 4-bit-wide shift register, so that each press of the “enter” button moves a whole digit from the first stage to the second. See the lecture note and week4-lab-sequential-circuits-shift-registers.

Software Timers

Keeping time for many things with one hardware timer. One timer interrupt counts ticks since reset, and every part of the program that cares about time reads that count. The stopwatch of week9-lab-avr-interrupts is its simplest relative. It replaces the delay macros of week9-lab-avr-pwm.

Delays that block

The quickest way to make a program wait is a delay macro:

#define F_CPU 8000000UL        /* the clock frequency, before the include */
#include <util/delay.h>

_delay_ms(500);                /* do nothing for 500 ms */
_delay_us(20);                 /* do nothing for 20 microseconds */
  • F_CPU must be defined before the include. The macros turn a time into a number of wasted instructions, and they need the clock frequency to do it. If it is missing the header only warns and assumes 1 MHz, so on an 8 MHz board every delay runs 8 times too short.
  • The argument must be a constant, known when the program is compiled.

This is busy waiting. The processor spends the whole delay counting down in a loop, and while it does:

  • no button is read and no input is noticed, so a press shorter than the delay is missed;
  • nothing else is updated, so a multiplexed display freezes on one digit;
  • only one delay can be running, so two things with different periods cannot both be timed this way;
  • the loop’s real period is the delay plus however long the rest of the loop takes, so the timing drifts.

Interrupts still happen during a delay, which makes it longer than asked for.

A delay macro is fine for a quick experiment. It does not scale to a program that has more than one thing to do.

One clock for the whole program

The ATmega324A has three timer/counters (avr-timers-and-counters). A program with more than three timed jobs would run out if each took one, and usually some are already taken for PWM or for counting.

A software timer uses one of them for everything:

  1. One timer/counter raises an interrupt at a fixed interval, the tick.
  2. The handler adds 1 to a global count. That count is the time since reset, the program’s clock.
  3. To mark the moment something happens, copy the count into a variable.
  4. To measure a duration, subtract two such copies. The answer is in ticks, so with a 1 ms tick it is in milliseconds.
  5. To do something later or regularly, keep checking whether enough ticks have passed, and get on with other things in between.

Figure 394: A software timer. The tick count goes up by one at every timer interrupt and never stops. Copying it when something begins gives start, here 3, and reading it again later gives now, here 9. The difference is the time between them in ticks. Any number of start values can be kept at once, which is how a single hardware timer serves every timing job in the program.

The clock in C

A 1 ms tick from timer/counter 0. With the 8 MHz clock divided by 64 the timer counts at 125 kHz, and clearing on a compare match at 124 gives \(8\,000\,000 / (64 \times 125) = 1000\) matches a second.

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint32_t clock_ticks;            /* milliseconds since reset */

ISR(TIMER0_COMPA_vect) {
    clock_ticks++;
}

void init_clock(void) {
    OCR0A  = 124;                         /* 125 counts per tick           */
    TCCR0A = (1<<WGM01);                  /* clear on compare match (CTC)  */
    TCCR0B = (1<<CS01) | (1<<CS00);       /* clock / 64                    */
    TIMSK0 = (1<<OCIE0A);                 /* enable the interrupt          */
    TIFR0  = (1<<OCF0A);                  /* clear its flag by writing 1   */
}

The handler is as short as a handler can be. The count is volatile because it changes outside the main program’s control (avr-interrupts).

Reading the count safely

The count is 32 bits and the processor is 8-bit, so reading it takes four instructions, one byte each. If the tick interrupt arrives between them, the bytes come from two different values. Going from 0x000000FF to 0x00000100, a read that is interrupted halfway can come out as 0x000001FF or as 0x00000000. Both are wrong by hundreds of ticks.

The cure is to turn interrupts off for the few instructions of the read:

uint32_t get_time(void) {
    uint32_t t;
    uint8_t sreg = SREG;       /* remember whether interrupts were on  */
    cli();                     /* nothing can change the count now     */
    t = clock_ticks;
    SREG = sreg;               /* put the I bit back as it was         */
    return t;
}

Saving SREG and putting it back, instead of calling sei(), means the function is safe to call from anywhere, including from code where interrupts are meant to be off.

The same applies to writing a shared variable of more than one byte from the main program. A single-byte variable needs none of this for a plain read or a plain write, since one instruction does all of it. Changing one in place is different: x++ or flags |= 1 in the main program reads, changes and writes back in separate instructions, and a handler that writes the same variable in between has its change lost. Inside a handler interrupts are already off.

Doing several things at once

With a clock to read, the main loop never waits. On each pass it checks which jobs are due:

void refresh_display(void);                   /* written elsewhere */
void check_buttons(void);

int main(void) {
    uint32_t now, last_blink = 0, last_refresh = 0;

    DDRB |= (1<<0);
    init_clock();
    sei();

    while (1) {
        now = get_time();

        if (now - last_blink >= 500) {        /* every half second */
            last_blink = now;
            PORTB ^= (1<<0);                  /* toggle an LED */
        }

        if (now - last_refresh >= 5) {        /* every 5 ms */
            last_refresh = now;
            refresh_display();                /* show the other digit */
        }

        check_buttons();                      /* every pass: nothing is missed */
    }
}

Each job has its own “last time” variable and its own interval. Adding a job means adding a variable and an if, and no more hardware.

Figure 395: The same job, blinking an LED every half second while also watching a button, written two ways. With a blocking delay the processor is stuck inside the delay almost all the time, and a button press that comes and goes during it is never seen. With a software timer the loop goes round thousands of times a second, looking at the clock and the button on every pass, so the press is caught straight away and the LED still toggles on time.

Measuring a duration

To find how long something took, note the time at the start and subtract at the end:

uint32_t start, held;

start = get_time();                 /* the button went down */
/* ... carry on with the main loop until it comes up ... */
held = get_time() - start;          /* how long it was held, in ms */

A stopwatch that is started once and read later is exactly this. One that can be stopped and restarted keeps a count of its own instead, advanced by the tick handler only while it is running, which is how the stopwatch of week9-lab-avr-interrupts works.

Limits

Resolution. Nothing can be timed more finely than one tick. A duration measured with a 1 ms tick can be out by up to 1 ms, depending on where in a tick it began and ended. A shorter tick is more precise, but the handler runs more often and takes more of the processor’s time.

Wrap-around. The count has a fixed number of bits and eventually goes back to 0.

Count Tick Wraps after
16 bits 10 ms 655 s, about 11 minutes
16 bits 1 ms 65.5 s
32 bits 1 ms about 49.7 days

Unsigned subtraction still gives the right answer across a wrap, as long as the real interval is shorter than one whole trip round. If start was 0xFFFFFFFA and the count is now 0x00000004, then now - start is 10, which is correct. This is why the test is written

if (now - last >= INTERVAL)         /* right, even across a wrap */

and not

if (now >= last + INTERVAL)         /* wrong when last + INTERVAL wraps */

This relies on the count being 16 or 32 bits wide. With an 8-bit count C does the subtraction as an int, the wrap is lost, and the result needs a cast: (uint8_t)(now - last).

Common mistakes

  • Waiting in a loop for the time to pass. while (get_time() - start < 500) { } is busy waiting again, only with a better clock. The check belongs in an if inside the main loop, so that everything else keeps running.
  • Reading a multi-byte count with interrupts on. It works nearly every time and then, rarely, gives a wildly wrong value.
  • Forgetting volatile. The compiler may then read the count once and never look again.
  • Doing slow work in the tick handler. The handler counts, and may do something quick such as lighting the next display digit. Anything that takes time belongs in the main loop, which decides what is due and does it.
  • Comparing with >= on the sum. Compare the difference with the interval, as above.
  • Expecting exact intervals. A job runs on the first pass of the loop after it falls due. If another job is slow, this one is late.

See also

State Machines

A state machine — equivalently a finite state machine (FSM) — is another name for a sequential circuit, viewed in terms of the states it can be in rather than the gates and flip-flops that implement it. See sequential-circuits for the circuit-level view and flip-flops-and-latches for the storage elements the state lives in.

What a state machine is

A state machine has:

  • a finite number of possible states — \(N\) flip-flops give at most \(2^N\) of them;
  • only one current state at any moment;
  • the ability to transition to other states, based on the inputs and the current state.

The state is exactly the value held in the flip-flops (see sequential-circuits), so the flip-flop count bounds the state count. It does not fix it: how many flip-flops a given number of states actually costs is an encoding choice, made at the state-encoding step below.

Naming the two blocks of logic

The standard sequential-circuit structure has one combinational block computing two different things, and it is worth naming them separately:

\[\text{OUT} = g(\text{IN}, Q) \qquad\qquad D = f(\text{IN}, Q)\]

  • \(Q\) is the present state (PS) — what the flip-flops hold right now.
  • \(D\) is the next state (NS) — what they will hold after the next clock edge.
  • \(g\) is the output logic; \(f\) is the transition logic (also called next-state logic).

Designing an FSM comes down to finding Boolean expressions for \(f\) and \(g\).

Defining the states from the problem

States are not handed to you — they come from the problem, and the useful question is what does the circuit need to remember?

Vending machine. A machine accepts 5c and 10c coins and dispenses a candy when it has received 15 cents in total. What are the states?

What the machine must remember is the running total inserted so far:

Total inserted 0 5 10 15 20 50
Dispense candy? no no no yes yes, plus change —

So the states are the totals 0, 5 and 10, with 15 and 20 being the ones that dispense (20 arises from inserting 10c on top of 10c, and needs change). A total of 50 is not a state at all: with only 5c and 10c coins the machine dispenses and resets long before it could get there, so it is unreachable.

Moore and Mealy machines

There are two types, differing only in what the output logic is allowed to see:

  • Mealy machine — outputs depend on the current state and the inputs.
  • Moore machine — outputs depend only on the current state (the flip-flop values). Consequently, outputs can only change when the state changes.

A Moore machine is a special case of a Mealy machine — the one where the output logic simply ignores its input connections. CSSE2010 sticks to Moore machines.

Figure 396: Mealy (top) and Moore (bottom). ① is the state, held in the flip-flops; ② is the transition logic; ③ is the output logic. The only structural difference is the branch drawn in bold: in a Mealy machine the inputs reach the output logic directly, so the outputs are a function of IN and Q; in a Moore machine the output logic sees Q alone.

State diagram notation

A state diagram draws the states as circles and the transitions as labelled arrows.

States are drawn as a circle split in two: the state name on top, the output value(s) underneath. So \(S_0\) over \(101\) is a state called \(S_0\) whose outputs are 101; the name is arbitrary and need not be \(S_n\) (a state called Alex over \(01\) is just as legal).

Transitions are arrows labelled with a logic expression over the inputs — if the expression is true, that transition is taken. Examples of labels: \(Z\), \(\overline{\text{RESET}}\), \(A + B\cdot\overline{C}\).

Two conventions worth knowing:

  • No label means “true” — the transition is always taken on the next clock edge. This is what the arrows in a plain counter’s diagram look like.
  • With only one input, the label may be written as just 0 or 1 instead of a Boolean expression. This is a special case of the general form; \(1\) means the same as \(Z\) and \(0\) the same as \(\overline{Z}\).

Completeness

Each possible combination of inputs should be addressed exactly once for each state.

That is, the transition arrows leaving each state must encompass all possibilities, without overlap and without gaps. With \(N\) inputs there are \(2^N\) input combinations, so every state needs \(2^N\) transitions accounted for — though several combinations leading to the same next state can be merged onto one arrow with an OR’d label.

This is a checkable property, and checking it is the cheapest way to catch a half-finished design: if the labels on the arrows out of a state do not OR together to 1, some input combination has no defined behaviour; if any two of them can be true at once, the machine is ambiguous.

A counter is a state machine with no inputs

The design method for counters — write the sequence as a present-state/next-state table, read each \(D\) column off as a Boolean function of the \(Q\)’s, draw the gates — is steps 3, 5 and 6 of the pipeline below, applied to the degenerate case where the machine has no external inputs at all. A counter may or may not have external inputs.

Three things collapse when \(\text{IN}\) is empty:

  • Transition logic. \(D = f(\text{IN}, Q)\) becomes \(D = f(Q)\), so the state table needs no input column and the excitation equations are functions of the \(Q\)’s alone.
  • Output logic. A counter’s output is its state, so \(g\) is the identity and there is no second block of gates. That also makes every counter trivially a Moore machine.
  • Completeness. With \(N = 0\) inputs there are \(2^0 = 1\) input combinations, so the completeness rule reduces to exactly one arrow out of each state — and by the “no label means true” convention, that arrow is unlabelled.

The state encoding step also disappears, or rather it is made for you: the states of a counter are already bit patterns, and the sequence you were given is the encoding.

Figure 397: The 2-bit counter for \(00 \to 10 \to 01 \to 00\) drawn as a state diagram. Every arrow is unlabelled because the machine has no inputs, so each transition is taken unconditionally on the next clock edge; each state’s output half carries the count value, since a counter’s output is its state. \(S_3\) is the unused state: three states cannot fill a two-flip-flop machine, so its next state is a don’t-care, and choosing \(11 \to 01\) for it is what makes the design self-correcting.

Figure 397 read as a state table, with the unused row carrying the don’t-cares:

Current state Next state \(Q_1\) \(Q_0\)
\(S_0\) \(S_1\) 0 0
\(S_1\) \(S_2\) 1 0
\(S_2\) \(S_0\) 0 1
\(S_3\) (don’t care) 1 1

The unused state is where the FSM framing pays for itself. A don’t-care is a free choice of transition, not an absence of one: the circuit will do something in state \(S_3\), and the only question is whether the arrow you have implicitly drawn leads back into the cycle or loops onto itself. An arrow from \(S_3\) to itself is a trap state — the machine leaves the intended cycle and never returns. There are two candidate simplifications for \(D_1\). The tidier one, \(D_1 = \overline{Q_1 \oplus Q_0}\), puts a self-loop on \(S_3\) and is rejected. The other sends \(11 \to 01\), back into the cycle, and is the robust design. See [counters] and 2026-08-17-counters for that working.

State tables

The same information as a state diagram, in tabular form. Two layouts, both in use.

One-dimensional — one row for every combination of state and inputs:

Current State Input \(U\) Next State \(Q_1\) \(Q_0\)
\(S_0\) 0 \(S_3\) 0 0
\(S_0\) 1 \(S_1\) 0 0
\(S_1\) 0 \(S_0\) 0 1
\(S_1\) 1 \(S_2\) 0 1
\(S_2\) 0 \(S_1\) 1 0
\(S_2\) 1 \(S_3\) 1 0
\(S_3\) 0 \(S_2\) 1 1
\(S_3\) 1 \(S_0\) 1 1

Two-dimensional — one row per state, with a next-state column for every combination of inputs:

Current State Next State (\(\overline{U}\)) Next State (\(U\)) \(Q_1\) \(Q_0\)
\(S_0\) \(S_3\) \(S_1\) 0 0
\(S_1\) \(S_0\) \(S_2\) 0 1
\(S_2\) \(S_1\) \(S_3\) 1 0
\(S_3\) \(S_2\) \(S_0\) 1 1

Both describe the same machine (a 2-bit up/down counter, \(U = 1\) counts up). The 2D form is more compact and makes completeness visually obvious — every input combination is a column, so a missing case is a missing column. The 1D form grows as \(2^N \times\) (number of states) but maps directly onto a truth table, which is what the next design step needs. In a Moore machine the output columns depend only on the current state, which is why they can sit in a per-state row at all.

State encoding

Each state must be encoded into flip-flop values before the design can become a circuit. Two choices to make:

  • the number of flip-flops, and
  • the bit patterns representing each state.

Ideally, choose the encoding that makes the combinational logic simple — for both the output logic and the next-state logic. Different encodings of the same machine give genuinely different gate counts.

Three common schemes, on a four-state machine:

State Binary Gray One-hot
\(S_0\) 00 00 0001
\(S_1\) 01 01 0010
\(S_2\) 10 11 0100
\(S_3\) 11 10 1000
  • Binary — the obvious count; \(\lceil \log_2 n \rceil\) flip-flops for \(n\) states.
  • Gray — same width, but consecutive states differ in exactly one bit (see binary-number-representations).
  • One-hot — one flip-flop per state, with only one flip-flop holding 1 at any time. Far more flip-flops, but the next-state and output logic often collapses to almost nothing, since “am I in state \(S_k\)” is just a single flip-flop’s output rather than a decoded combination.

Steps involved in FSM design

  1. Defining state based on the problem definition.
  2. Drawing the state diagram.
  3. Completing the state table (1D or 2D).
  4. State encoding, and re-doing the state table with encoded states.
  5. Obtaining the Boolean expressions for the next-state logic (i.e. the \(D\)’s) and for the outputs.
  6. Drawing the logic diagram.
  7. Simulating in Logisim to verify functionality.
  8. Building and testing the circuit in hardware.

Steps 1–6 are the pen-and-paper design; steps 7–8 are what the learning labs do with it. Steps 5 and 6 are the same techniques used to build a counter by hand — see [counters] and circuit-schematics.

See also

Timing Diagrams

A timing diagram is the fourth of the four equivalent ways to describe a logic function, alongside the logic diagram, the truth table, and the Boolean expression (see logic-gates).

Timing diagram as a logic representation

It is like a truth table, but in graphical format: time runs left to right along the horizontal axis, and each signal gets its own horizontal track that steps between the logic 0 and logic 1 levels (drawn as two dashed reference lines).

Worked example — an inverter. The input waveform starts at logic 0, rises to logic 1 for a period, then falls back to logic 0. The output waveform is the mirror image: it starts at logic 1, falls to logic 0 for exactly that period, then returns to logic 1. Each change in the input causes the output to change.

Figure 398: An inverter drawn as a timing diagram. Reading the four intervals off the input gives 0, 1, 1, 0 and off the output gives 1, 0, 0, 1 — which is the inverter’s truth table, just laid out along a time axis instead of down a page. The two dashed lines per track are the logic 0 and logic 1 reference levels.

At this idealised level the output changes at exactly the same instant as the input; the transitions are drawn as vertical lines. That is a convenient fiction, corrected at the bottom of this note.

Convention for drawing the input waveforms

The input waveforms must be drawn so that all possible input combinations are covered — that is what makes the diagram equivalent to the full truth table.

The standard construction for a 2-input gate divides the time axis into four equal intervals and drives the inputs like a binary count:

  • \(A\) is low for the first half of the diagram, then high for the second half.
  • \(B\) toggles at twice that rate: low, high, low, high.

Reading the four intervals left to right therefore gives \(AB = 00, 01, 10, 11\) — every combination, once each, in truth-table order. For \(n\) inputs the same scheme generalises: input \(i\) toggles at half the rate of input \(i+1\), and the diagram is \(2^n\) intervals wide.

To read a gate’s output off the diagram, work interval by interval: identify the \(AB\) combination in that interval, look up the gate’s truth table row, and draw the output at that level for the width of the interval.

Figure 399: The convention on a 2-input example, with the AND output filled in. The vertical rules divide the four intervals; the digits under each track are the truth-table row for that interval. Because the inputs count 00, 01, 10, 11, the output track is literally the output column of the truth table, drawn left to right.

Going the other way — being given the output track and asked which gate it is — is the standard exam form of this. Read the output value in each interval, write it beside the corresponding \(AB\) row, and compare the resulting column with the gates you know. A worked instance is in 2026-08-06-combinational-logic.

Real gates aren’t perfect: the reality of timing

The idealised diagrams above show instantaneous, perfectly square transitions. Real gates do not behave that way — real waveforms have sloped edges, and the output changes some time after the input does. Three quantities describe this:

Term Definition
Propagation delay Time for a change in the input to affect the output.
Fall time Time taken for the output to fall from 1 to 0.
Rise time Time for the output to rise from 0 to 1.

Figure 400: The same inverter drawn honestly. The input’s edges slope instead of jumping; the output does not begin to move until the propagation delay has elapsed; and once moving, its downward edge takes the fall time and its later upward edge takes the rise time. Rise and fall times are properties of one edge of one signal — the propagation delay is the gap between two signals.

Measured on an inverter: the input ramps up, and only after the propagation delay does the output begin to move; the output’s downward edge then takes the fall time to complete, and its later upward edge takes the rise time.

The three quantities are measured differently, and it is worth keeping them apart. Rise time and fall time are properties of a single edge of a single waveform — how long that edge takes to get from one level to the other. Propagation delay is the gap between two waveforms — how long the output takes to react at all. All three are marked on the same pair of inverter waveforms above.