digiwleeaLearn
Open the lab →

Build logic from the transistor up

A from-the-ground-up guide to designing digital circuits: what the signals mean, why CMOS gates are shaped the way they are, and how to compose them into adders, latches, and a register. Read the theory here, then build it in the lab.

Start from the beginning →How a CPU works: the big picture →

Number & logic

Binary numbersCounting with two symbolsA wire holds one of two values, so computers count in base 2. Place value, counting up, and the byte: the number system every later lesson is written in.HexadecimalBinary in a readable shorthandHex is base 16: one hex digit packs exactly four bits. It is how we write bytes and addresses without drowning in long strings of 0s and 1s.OctalThree bits to a digitOctal packs three bits into one base-8 digit (0 to 7), an older binary shorthand still seen in file permissions and some machine encodings.Number bases and base conversionTurning any number into any base by handConvert between decimal, binary, octal, and hexadecimal by hand: subtract powers or divide by 2, group bits by 3 or 4, handle fractions, and even solve for an unknown base.Bits, bytes, and KiB vs KBCounting storage, and the 1024 versus 1000 gapA byte is 8 bits, and storage prefixes come in a binary flavor (KiB = 1024) and a decimal flavor (KB = 1000), which is why a 500 GB drive shows less capacity in the operating system.Two's complementHow hardware stores negative numbersTwo's complement encodes a signed number by giving the top bit a negative weight, so one adder handles both addition and subtraction. To negate a value, invert every bit and add one.Sign extensionWidening a signed number without changing itSign extension copies a signed number's top bit into every new high bit when widening it, so a negative value stays the same negative value instead of turning into a large positive one.From counting in binary to addingThe carry rule you already knowBinary addition follows the same column-and-carry rule as decimal, and turning that paper procedure into gates is exactly what an adder does.Boolean algebraThe math of true and falseAND, OR, and NOT obey an algebra, with identities and De Morgan's laws that let you rewrite any logic expression. Reshaping expressions is exactly how you choose a circuit.De Morgan's lawsPushing a NOT through a gateThe inverse of an AND is an OR of the inverses, and the inverse of an OR is an AND of the inverses. These two laws are how you move a NOT across a gate and convert freely between AND, OR, NAND, and NOR forms.Boolean identities and dualityThe laws that simplify an expression by handThe identity, null, idempotent, complement, and absorption laws, plus the duality principle that swaps AND with OR and 0 with 1, let you shrink a Boolean expression algebraically before you ever draw a K-map.Truth tablesSpecifying logic, completelyA truth table lists the output for every possible input. It is the unambiguous specification of any logic function, the thing you verify against and the starting point for designing a gate.A bit is a number and a truth valueThe bridge from counting to logicThe same 0 and 1 that spell a number in binary also mean false and true, so arithmetic and logic run on the exact same wires.Gray codeCounting with one bit changing at a timeGray code reorders the binary count so that each step flips exactly one bit. That single-bit-change property avoids the transient wrong readings you get when several bits switch at once, which is why encoders and counters use it.Binary-coded decimal (BCD)Storing decimal digits one nibble eachBCD stores each decimal digit in its own 4-bit group using the 8421 weights, so 0 to 9 map to 0000 to 1001. It keeps numbers exactly decimal for money and displays, at the cost of six wasted codes and harder arithmetic.ASCII and character encodingHow text becomes numbersA computer only stores numbers, so text is stored by assigning every character a code. ASCII is the classic 7-bit table: 'A' is 65, '0' is 48, 'a' is 97, and the tidy gaps between those ranges make case conversion and digit reading a single subtraction.Error detection and correctionParity, Hamming distance, and ECCAdding redundant bits lets hardware catch and even repair bit flips: a parity bit detects any single error, and a Hamming code locates and corrects one. The cost is extra storage or bandwidth.Fixed-point fractionsPutting a binary point at a fixed columnFixed-point notation places an imaginary binary point at an agreed column so a whole-number circuit can represent fractions, the simpler cousin of floating point.Floating point (IEEE-754)Scientific notation in binaryFloating point stores a real number as a sign, a biased exponent, and a fractional mantissa, so a fixed number of bits can hold both huge and tiny values. IEEE-754 is the universal standard, with a hidden leading 1, reserved patterns for zero, infinity, and NaN, and round-to-nearest-even.

Fundamentals

From logic to silicon

Logic as switchesThe atom every gate is made ofA switch is the atom of logic: switches in series compute AND, switches in parallel compute OR, and that is the whole idea a transistor automates.The MOSFET switchGate, source, drain, and the insulated handleA MOSFET is the voltage-controlled switch of digital chips: an insulated gate whose voltage builds or removes a conducting channel between the source and drain.NMOS: the strong-0 switchCloses on a gate 1, and pulls firmly to groundAn NMOS conducts when its gate is 1 and passes a full-strength 0 but only a weak, threshold-dropped 1, which is why it always belongs in the pull-down network.PMOS: the strong-1 switchCloses on a gate 0, and pulls firmly to powerA PMOS conducts when its gate is 0 and passes a full-strength 1 but only a weak, threshold-lifted 0, which is why it always belongs in the pull-up network.Pull-down networksWiring NMOS to detect when the output should be 0A pull-down network is NMOS transistors wired between the output and ground so that they conduct for exactly the input rows where the output must be 0, using series for AND and parallel for OR.Pull-up networksThe PMOS dual that drives the output to 1A pull-up network is PMOS transistors wired from power to the output as the exact structural dual of the pull-down, so it conducts on precisely the rows where the pull-down does not.The complementary pairWhy exactly one network is ever onStacking a PMOS pull-up over a dual NMOS pull-down makes a complementary gate: for every input exactly one network conducts, so the output is always driven to a full-strength 0 or 1.Why CMOS sips powerNo steady path from power to groundA static CMOS gate draws almost no power when idle because exactly one network is on, leaving no path from power to ground; nearly all its energy is spent only while switching.Build the inverterTwo transistors, traced row by rowThe inverter is one PMOS pull-up over one NMOS pull-down sharing an input; tracing both input values shows exactly one transistor conducting and the output landing on the opposite rail.Build NAND and NORFour transistors each, and exact mirror imagesNAND is series NMOS with parallel PMOS and NOR is its exact mirror (parallel NMOS with series PMOS); both use four transistors and both are naturally inverting.AND and OR: the price of not invertingWhy the friendly gates cost an extra stageStatic CMOS gates are naturally inverting, so AND is a NAND followed by an inverter and OR is a NOR followed by an inverter, each costing six transistors and two stages instead of four and one.The transmission gateAn NMOS and PMOS in parallel that pass any valueA transmission gate wires an NMOS and a PMOS in parallel with opposite control signals so it passes a full-strength 0 and 1 in either direction, or switches to high-Z when off.XOR at the transistor levelThe gate with no simple series-parallel networkXOR has no compact single-stage CMOS network, so it is built either from a handful of NAND gates or, more compactly, from transmission gates that select between A and NOT A using B.Transistor count and sizingHow many transistors, and how wideA static gate takes two transistors per input, and designers widen the slower PMOS and any series-stacked transistors so the gate charges and discharges its load at balanced, predictable speed.From transistors to gate symbolsWhen to stop drawing switchesOnce a gate is built and verified from transistors, we hide the transistors behind a single gate symbol and reason with truth tables, which is the abstraction that makes designing large circuits possible.

Gates

NOTThe inverterThe simplest gate: output is always the opposite of the input. Two transistors, one PMOS and one NMOS, working in perfect opposition.NANDThe universal gate0 only when both inputs are 1. Every other gate can be built from it.ANDNAND, then invertedOutput is 1 only when both inputs are 1. Built by canceling the inversion of a NAND gate with a NOT gate from your library.NORNAND's mirror imageOutput is 1 only when both inputs are 0. Series PMOS pulls up, parallel NMOS pulls down: the exact complement of NAND's topology.ORNOR, then invertedOutput is 1 when at least one input is 1. Built by canceling the inversion of a NOR gate, mirroring exactly how AND is built from NAND.XORThe odd one outOutput is 1 exactly when the inputs differ. No single CMOS gate does this, so you combine NAND gates. XOR is also the core of binary addition.XNOR and the equality comparatorThe gate that tests for samenessXNOR outputs 1 exactly when its two inputs are equal, making it a one-bit equality detector. AND a row of XNORs together and you get a comparator that tells you whether two whole numbers are equal.Reading a multi-gate schematicFrom one gate to a blockA block is made by feeding one gate's output into another's input; reading a schematic means tracing each net from its source to the gates that consume it.Canonical forms: minterms and maxtermsThe two standard ways to write any truth table as gatesEvery truth table has two canonical expressions: a sum of minterms (OR the 1-rows) and a product of maxterms (AND the 0-rows). Each maps directly to a two-level gate circuit, and either becomes an all-NAND or all-NOR build.From a truth table to a real circuitThe recipe that turns a spec into gatesAny truth table becomes a circuit by writing one AND term per output-1 row and OR-ing those terms, connecting what it should do to what to build.The multiplexer as a universal logic elementAny function, read straight out of a muxA 2^n-to-1 multiplexer with the n input variables on its select lines can implement any n-variable boolean function: tie each data input to that row's truth-table output and the mux becomes a direct lookup table. Shannon expansion does the same job with a mux half the size.NOR is universal tooEvery gate from NOR aloneLike NAND, a NOR gate alone can build every other gate and therefore any logic function, and some historic machines (including the Apollo Guidance Computer) were built entirely from NOR.Karnaugh mapsReading the simplest circuit off a tableA Karnaugh map rearranges a truth table so adjacent cells differ in one bit. Grouping the 1s by sight gives the minimal AND-OR expression, fewer gates than the raw table.Hazards and glitchesThe momentary wrong answer a correct circuit can still produceUnequal gate delays can make a logically correct circuit flash the wrong value for an instant during an input change. A static-1 hazard is fixed by adding the redundant consensus term that bridges two non-overlapping K-map groups.The consensus theoremThe redundant term that kills a glitchThe consensus theorem says A·B + A'·C + B·C = A·B + A'·C, so the third term is logically redundant, yet adding it back is exactly the extra gate that removes a static-1 hazard.Quine-McCluskey minimizationThe algorithm that minimizes when a K-map cannotQuine-McCluskey is a tabular, exhaustive method for minimizing a boolean function. It combines minterms that differ in one bit to find every prime implicant, then uses a prime-implicant chart to pick a minimum cover, working where Karnaugh maps run out past five or six variables.

Arithmetic

When logic starts to countThe moment gates do mathAdding two bits is just XOR for the sum and AND for the carry, the moment logic gates stop being abstract and start doing arithmetic.Half adderAdding two bitsA half adder adds two single bits and produces a Sum and a Carry. It is the first arithmetic circuit you build from the logic gates you already have.Full adderHow a computer really addsA full adder adds three bits, A, B, and a carry-in, producing a Sum and a carry-out. Chaining full adders in a row is exactly how a CPU adds multi-bit numbers.Carry-lookahead addersComputing every carry at onceA ripple-carry adder is slow because each bit waits for the carry below it. A carry-lookahead adder derives generate and propagate signals per bit, then computes every carry directly from the inputs in parallel, trading more gates for far less delay.Binary multiplicationShift, add, and the array multiplierBinary multiplication is longhand multiply with the easiest times table there is: each partial product is the multiplicand shifted, or zero. An array multiplier forms all the partial products with a grid of AND gates and sums them with an adder array.ComparatorsGreater, equal, or lessA comparator reports whether one number is greater than, equal to, or less than another. Equality is XNOR per bit ANDed together; magnitude resolves from the most significant bit down, the first differing bit deciding the order.Carry versus overflowTwo flags for two ways of reading the same bitsCarry-out means the unsigned result did not fit; overflow means the signed result did not fit. The same adder bits are read as one or the other depending on whether you meant the numbers as unsigned or signed.The barrel shifterShifting a word in one combinational stepA combinational shifter moves a word's bits left or right by a chosen amount in a single pass of logic. A barrel shifter does a variable shift with a tree of multiplexers, and the three flavors are logical shift (fill with 0), arithmetic shift (right-shift copies the sign bit), and rotate (bits wrap around).Binary divisionShift, subtract, and the quotientDivision is the fourth arithmetic operation and the hardest: hardware does it as long division in binary, shifting the divisor down the dividend and subtracting wherever it fits. Each step produces one quotient bit, and what is left over is the remainder.

Memory

The clock and sequential logicThe heartbeat that lets a circuit rememberEverything so far has been combinational: outputs depend only on the present inputs. Sequential logic adds memory, and a clock is the shared signal that tells every memory element when to update, so the whole machine changes in lockstep.How a circuit remembersThe one idea that turns logic into memoryFeeding an output back into an input lets a circuit hold a value after its inputs change, the single idea that turns logic into memory.Two kinds of circuitCombinational versus sequentialA combinational circuit's output depends only on current inputs; a sequential one also depends on stored history, and the difference tells you whether you need a clock.SR latchThe first memoryEvery combinational circuit forgets the moment its inputs change. The SR latch breaks that rule by feeding its output back into its own input, giving it a state that persists after the inputs return to zero.Gated D latchOne data input, one enableThe SR latch has a forbidden input combination and two inputs to manage. The gated D latch fixes both with a single Data line and an Enable gate. While EN is high the output follows D; when EN falls the last value is held.The transparency problemWhy a latch is not enoughA latch passes changes through the whole time it is enabled (transparent), so to capture a value at one precise instant you chain two latches into an edge-triggered flip-flop.D flip-flopMaster and slaveA D latch is transparent while enabled, which lets glitches on D corrupt the stored value. Chain two latches in opposite phases and you get a flip-flop: D is captured at exactly one instant, the rising clock edge, and held until the next one.Flip-flop types: D, JK, T, SRFour ways to clock a bit, and the tables that design themThe four standard edge-triggered flip-flops differ only in what their inputs mean: D loads a value, T toggles, JK does everything with no illegal input, and SR sets or resets but forbids both at once. Each is captured by a characteristic table (next state from the inputs) and an excitation table (the inputs a desired transition needs), and that excitation table is the tool you use to design sequential logic.JK flip-flopThe flip-flop with no illegal inputThe SR flip-flop can set or reset a bit but breaks if you assert both inputs at once. The JK flip-flop keeps set and reset (now called J and K) and turns that forbidden corner into a useful fourth operation: with J = K = 1 it toggles. So all four input combinations are legal (hold, reset, set, toggle), which made JK the universal flip-flop of the discrete-logic era.T flip-flopOne input that flips a bitA T (toggle) flip-flop has a single input: with T = 0 it holds its bit, and with T = 1 it flips the bit on every clock edge. Holding T = 1 makes the output a clean square wave at half the clock frequency, a divide-by-2, and chaining T flip-flops so each drives the next is exactly how a binary counter is built.Register bitA flip-flop with a write enableA bare flip-flop overwrites its stored value on every clock edge. A register bit adds a write enable so you can choose when to load new data and when to hold, using feedback from Q to itself.Widening a 1-bit circuitThe just replicate it patternTo handle a whole byte you place eight copies of a 1-bit circuit side by side sharing their control lines, the replicate-it pattern behind every multi-bit block.Shift registersMarching a bit along a chainA shift register is a row of flip-flops where each one's output feeds the next one's input, so on every clock edge the stored bits march one position along the chain. It moves data serially, converts between serial and parallel, and is the basis of the control unit's ring counter.Timing: delay and the clock speed limitWhy a chip can only be clocked so fastReal gates take time to switch, so a signal needs a moment to settle through a chain of logic. That propagation delay, summed along the slowest path between flip-flops, sets the minimum clock period: clock faster than the logic can settle and you capture wrong values.Metastability and synchronizersWhat happens when an input misses the setup windowSample a flip-flop while its input is changing and it can hang at an in-between voltage and resolve to 0 or 1 only after an unpredictable extra delay. The chance it is still undecided falls off exponentially with time, so the standard fix for an asynchronous input is a two-flip-flop synchronizer that gives the first flop a full clock period to settle before any logic sees it.Reset: starting from a known stateWhy every sequential circuit needs a resetA reset input forces flip-flops to a known value on power-up, because a circuit that starts in a random state is unpredictable; synchronous reset acts on the clock edge, asynchronous reset acts immediately.SRAM vs DRAMTwo ways to store a bit, and why both existSRAM stores each bit in a 6-transistor latch (fast, used for caches and registers) while DRAM stores it as charge on a tiny capacitor (dense and cheap but must be refreshed), which is why main memory is DRAM and caches are SRAM.ROM and PLA: logic as a lookupBuilding a function from memory instead of gatesAny combinational function is just its truth table, so you can build it as memory instead of gates: a ROM stores the output at every input address, a PLA stores only the product terms you actually need. This is how lookup tables and FPGAs work.The memory hierarchyRegisters, cache, RAM, and disk, from fastest to biggestFaster memory is smaller and costs more per bit, so a computer stacks several kinds: a few fast registers on top, then cache, then main memory (RAM), then huge slow disk. Locality lets a little fast memory in front of a lot of slow memory serve almost every access.

Processor

BusesMoving a whole byteA bus is just several wires carrying one bit each, grouped so they move a whole multi-bit number together. It is the notation and plumbing the rest of the CPU is built on.The multiplexerChoosing a signalA multiplexer is a data selector: a SEL input picks which of several data inputs is passed to the output. It is the switch that decides what travels on a bus, and you have already built one.DecodersOne-hot addressingA decoder turns a small binary address into one-hot select lines: exactly one output goes high, the one named by the address. It is how an address picks a single register or memory cell.Encoders and demultiplexersThe duals of the decoder and muxAn encoder is the reverse of a decoder: it turns a one-hot set of lines back into a binary address. A demultiplexer is the reverse of a multiplexer: it routes one input to one of several outputs chosen by a select code. Together with the decoder and mux they complete the data-routing toolkit.The priority encoderHighest request winsA priority encoder outputs the binary index of the highest-numbered active input even when several inputs are high at once, plus a 'valid' output that is 1 whenever any input is active. It fixes the wrong answer a plain encoder gives on non-one-hot inputs, which is why interrupt controllers use it.The seven-segment display decoderTurning a 4-bit digit into a numeralA seven-segment display decoder maps a 4-bit BCD digit (0 to 9) to seven segment outputs a to g, each lighting one bar of the numeral. It is a decoder built as seven boolean functions of the same four input bits, one per segment.An 8-bit registerStoring a whole byteAn 8-bit register is eight register bits sharing one clock and one write-enable. It loads a byte off the bus when enabled and holds it otherwise. It is the basic storage box of the CPU.Adding 8-bit numbersThe ripple-carry adderChain eight full adders, each carry feeding the next, and you can add two 8-bit numbers in one shot. This ripple-carry adder is the arithmetic core the ALU is built around.Negative numbers and subtractionTwo's complement, and one block that does bothTwo's complement lets the same 8 wires represent negatives, and makes subtraction into addition: to compute A - B, add A to the bit-flipped B and carry in 1. One XOR per bit turns the adder into an adder/subtractor.Overflow and the carry flagWhen the answer does not fitFixed-width arithmetic can produce a result too big for its bits. The carry flag catches that for unsigned numbers; the separate overflow flag catches it for signed two's-complement numbers, where adding two positives can wrongly land on a negative.The ALUThe arithmetic and logic coreAn ALU performs one of several operations on two bytes, chosen by a function code, and reports a zero flag. It bundles the adder/subtractor with bitwise logic behind a multiplexer: the CPU's compute unit.The accumulatorThe one register the machine computes intoThe accumulator is the single working register an accumulator-machine CPU (like the one this course builds) keeps its running result in, so ADD means add memory to the accumulator.Tri-state buffers and the shared busMany drivers, one wire, one at a timeA tri-state buffer can drive a wire high, drive it low, or let go entirely (high-Z). That third state is what lets many components take turns driving one shared bus, which is how a CPU moves data between blocks.The program counterCounting through addresses, and the counters behind itA counter steps through values on each clock. Ripple counters chain toggle flip-flops (simple, but the count settles with a cumulative delay); synchronous counters clock every bit together (bit k toggles when all lower bits are 1); a mod-N counter wraps after N states; and a program counter is a synchronous up-counter with a load path so it can also jump.The program counterThe register that points at the next instructionThe program counter is a register holding the address of the next instruction, incrementing each cycle so the CPU walks through memory in order, and loadable so a jump can redirect it.Synchronous countersOne shared clock, a count-enable chain, and clean cascadingA synchronous counter clocks every flip-flop from one common clock so all bits update on the same edge, and a count-enable AND chain toggles bit k only when the enable and every lower bit are 1. A ripple-carry-out cascades counters, a direction line makes it count up or down, and a decoded synchronous clear or load makes it count modulo N.Finite state machinesA circuit that steps through statesA finite state machine is a state register plus next-state logic: it sits in one of a fixed set of states and, each clock edge, moves to the next state decided by the current state and inputs. It is the pattern behind any controller, including the CPU's control unit.Designing a sequence detectorFSM design from a spec: Moore vs MealyDesigning a finite state machine from a word specification means drawing a state diagram, filling a state-transition and output table, encoding the states in flip-flops, and reading the next-state and output equations off the table. A Moore machine's output depends on the state alone; a Mealy machine's depends on the state and the current input.Algorithmic state machines (ASM charts)A flowchart notation for state machinesAn ASM chart is a flowchart-style notation for a finite state machine, built from a rectangular state box, a diamond decision box, and a rounded conditional-output box, where one ASM block is everything that happens in a single clock cycle. It is the bridge from a state diagram toward register-transfer-level coding.State minimization and encodingFewer states, and the codes you give themTwo refinements turn a rough state diagram into efficient hardware. Merging equivalent states (states no observer can tell apart) cuts the number of flip-flops, and the state assignment (the binary code you give each state) sets the cost of the next-state and output logic, where one-hot, binary, and Gray encodings trade flip-flop count against speed and glitches.Analyzing a sequential circuitReverse engineering: from an unknown netlist back to behaviorSequential analysis recovers an unknown clocked circuit's behavior: read each flip-flop's input equations off the gates, substitute them into the flip-flop's characteristic equation to get the next-state bits, build the state table, draw the state diagram, and describe what the machine does. It is finite-state-machine synthesis run backwards, the skill for reverse-engineering or verifying a design.Memory: RAMAddressable storage on a busRAM is a bank of registers plus an address decoder. The address selects one cell; a write stores the data bus into it, a read drives that cell's value back onto the bus through a tri-state. It is where a program and its data live.The register fileThe CPU's fast scratch storageA register file is a small array of registers with addressed read and write ports, so a datapath can read two source operands and write one result in the same clock cycle. It is built from registers, a decoder for the write port, and a multiplexer per read port, and it is the fast working storage a CPU computes on.Caches and the memory hierarchyKeeping the data you need within reachMain memory is far slower than the CPU, so processors keep a small, fast cache of recently and nearby-used data. The memory hierarchy stacks registers, cache levels, DRAM, and disk so that most accesses are served by a fast copy near the top, and locality is what makes that bet pay off.The instruction registerHolding and splitting an instructionThe instruction register latches the byte fetched from memory and holds it steady while the CPU acts on it, exposing it split into an opcode (what to do) and an operand (what to do it to).Machine codeInstructions as numbersA program is just bytes in memory. Each instruction byte splits into an opcode (what to do) and an operand (what to do it to). Defining that mapping is defining the instruction set.An opcode becomes control linesHow an instruction turns into actionThe control unit is a lookup table from opcode to the exact enable, load, and function lines to raise, so decoding an instruction just means picking the right row of signals.The control unitThe sequencer that pulls the leversThe control unit steps through micro-operations and raises the control lines that gate values onto the bus and enable loads. A ring counter provides the steps; the opcode chooses which lines fire on each step.Wiring blocks into a data pathFrom parts to a working circuitA datapath is registers and an ALU connected by a shared bus, where control lines decide which block drives the bus and which reads it each cycle.The datapathHanging the blocks on a shared busThe datapath is every storage and compute block wired to one shared bus, each gated on by a control line. Data flows from a source, through the ALU if needed, into a destination, one transfer per step.The control signal matrixOne row per instruction, one column per leverA control matrix is a table with one row per instruction and one column per control line; a 1 marks each line the instruction asserts, and filling it in completely specifies a hardwired control unit.FetchReading the next instruction from memoryThe fetch phase reads the byte at the program counter's address out of RAM into the instruction register, then increments the program counter, the first step of every instruction.DecodeSplitting the instruction and choosing what to doThe decode phase splits the fetched instruction into its opcode and operand and looks up which control lines that opcode needs, choosing what the execute phase will do.ExecuteDoing what the instruction saysThe execute phase raises the decoded control lines so the datapath actually performs the operation (load, add, or store) and the result lands where the opcode dictates.Fetch, decode, executeThe whole machine, running a programA CPU repeats one loop forever: fetch the next instruction from memory, decode its opcode, and execute it on the datapath. Those three steps, driven by the control unit's clock, are a working computer.MicrocodeControl lines stored as firmware, not gatesMicrocode replaces hardwired control logic with a small ROM whose words are the control-line settings, so the instruction set becomes reprogrammable firmware instead of fixed gates.Von Neumann vs HarvardOne memory or two?A von Neumann machine keeps instructions and data in one memory (simple, but they compete for one bus) while a Harvard machine splits them into two (faster, used in DSPs and caches).Virtual memoryGiving each program its own address spaceVirtual memory gives each program its own large address space that a page table maps onto the smaller physical RAM, with a TLB caching recent translations, so programs need not know where they really live.Memory-mapped I/OTalking to devices with LOAD and STOREMemory-mapped I/O wires a peripheral's registers to specific memory addresses, so the same LOAD and STORE instructions that touch RAM also read a sensor or drive an output.PipeliningOverlapping instructions for throughputA pipeline splits the datapath into stages separated by registers, so several instructions are in flight at once: while one decodes, the next is fetched. Throughput rises toward one instruction per cycle even though each instruction still takes several cycles end to end, as long as hazards between instructions are handled.Measuring CPU performanceThe iron law and Amdahl's lawA processor's runtime is the instruction count times the average cycles per instruction times the clock period. Every design choice moves one of those three terms, often at the expense of another, so clock speed alone is a poor measure, and Amdahl's law caps how much speeding up one part can help.Tracing a programFour instructions, step by stepHand-execute a tiny LOAD / ADD / STORE / HALT program on the accumulator CPU, following fetch-decode-execute and watching the registers change until it computes a sum.Assembly languageHuman-readable machine codeWriting programs as raw hex bytes is error-prone. Assembly language replaces each instruction byte with a short mnemonic (LOAD, ADD, STORE, HALT), and an assembler translates the mnemonics one-to-one back into the opcode bytes the CPU runs.Labels and dataNaming addresses so you don't count bytesHardcoding memory addresses is fragile: insert one instruction and every address shifts. A label names an address, and the assembler's symbol table fills in the real number, so you write LOAD x and reserve data with x: .byte 5.Writing a programA complete program, and the limit that grows the ISAPutting it together: a straight-line program that sums three numbers, assembled to bytes and traced to the answer. Then the honest limit, with only LOAD/ADD/STORE/HALT the machine runs top to bottom once and cannot loop or choose, which is exactly what a jump instruction adds.Addressing modesHow an instruction names its operandOur LOAD, ADD, and STORE always mean 'the operand is a memory address, read the value there,' which is called direct addressing. Real instruction sets add more rules: immediate (the value is in the instruction), indirect (the operand points to the address), and indexed (a base plus an offset, for arrays and loops). This lesson names our machine's single mode and honestly contrasts it with the modes x86, ARM, and RISC-V provide.

HDL

What is an HDL?Describing hardware in textA hardware description language like VHDL or Verilog is text that DESCRIBES a circuit, not a program that runs step by step. A synthesis tool turns that description into real gates on an FPGA or ASIC.Entity and architectureThe interface and the insidesA VHDL design has two halves: the entity declares the black-box interface (the named input and output ports), and the architecture describes what is inside it. It is the same split as a custom part's pins versus its internal circuit.Signals and std_logicThe four values a wire can carryVHDL's std_logic type is a wire that can carry the same four values you already meter on the canvas: 0, 1, Z (floating), and X (contention). Ports cross the boundary; internal signals are the wires inside.Concurrent assignmentsCombinational logic as equationsA concurrent signal assignment (F <= ...) is a standing piece of combinational logic: a boolean equation that is always live. You can read one straight off a truth table as the sum of the rows where the output is 1.Processes and rising_edgeDescribing logic that remembersConcurrent assignments describe combinational logic; a clocked process describes sequential logic. The pattern if rising_edge(clk) captures a value on the clock edge, which is precisely a D flip-flop.Testbenches: simulating a designDriving inputs and checking outputsA testbench is VHDL that wraps your design, drives its inputs over time, and checks its outputs with assert. It is the textual version of the waveform/timing view you use in the lab to verify a circuit.Verilog: the other HDLDescribing hardware in a C-like languageVerilog is a hardware description language, like VHDL, but with a terser C-like syntax. It is the dominant HDL in US chip design. The basic unit is the module: a named block with a port list, exactly the entity/architecture idea you saw in VHDL.Continuous assignmentCombinational logic with assignA Verilog continuous assignment (assign F = ...) is a standing piece of combinational logic: a boolean equation that is always live, written with & (AND), | (OR), ~ (NOT), and ^ (XOR). You read one straight off a truth table as the sum of the rows where the output is 1.always @(posedge clk)Describing logic that remembersContinuous assignments describe combinational logic; a clocked always block describes sequential logic. The pattern always @(posedge clk) with a nonblocking <= captures a value on the clock edge, which is precisely a D flip-flop.Wires, registers, and vectorswire vs reg, and multi-bit busesA Verilog wire carries a continuously-driven value; a reg holds a value assigned in a procedural block (and is NOT necessarily a hardware register). Both can be one bit or a vector like [7:0] for a bus, and each bit is 4-state: 0, 1, x (unknown), z (high-impedance).TestbenchesDriving inputs and checking outputsA Verilog testbench is a port-less module that instantiates the design under test, drives its inputs over time in an initial block with # delays, and prints or checks the outputs with $monitor/$display and $finish. It is how you verify logic in simulation before it becomes hardware.FPGAs and programmable logicA blank chip that becomes your circuitProgrammable logic devices (ROMs, PLAs, PALs, CPLDs, and FPGAs) are generic chips you configure to behave like any circuit. An FPGA's core trick is the look-up table: a tiny truth table stored in SRAM, so the same silicon becomes whatever function you load into it.