Talking to devices
I/O means input and output: how a CPU swaps data with devices such as a keyboard or a timer. Devices are much slower than the CPU, and they need attention at moments the CPU cannot predict, such as when you press a key.
A port is a numbered doorway to a device. TINY-8 has one input port: IN r3 copies the value the keyboard puts there into r3. No key is down, so it reads 0. OUT does the reverse, sending a register to the output port.
Polling means checking again and again. This loop reads the port, tests it (ADDI r3, 0 sets the Z flag when r3 is 0) and jumps back while it is 0. In 30 instructions TINY-8 checked 10 times and got 0 every time.
An interrupt
With interrupts the CPU does real work instead, here counting in r0. When a key goes down, the keyboard raises its interrupt line, a wire to the CPU that goes from 0 to 1. Nobody had to ask.
The CPU never stops halfway through an instruction. It finishes ADDI r0, 1, so r0 becomes 5 and the PC moves on to 4. Only between two instructions does it check the line, and the line is 1.
First the hardware copies the PC, 4, into a saved-PC register, so it can find its way back. Then it loads 32, the handler's address, into the PC. A handler is a short routine that serves one device.
The handler's first instruction is an ordinary IN r3. This time the port holds 65, the code for A. Reading it tells the keyboard it has been served, so the keyboard lowers its line back to 0.
ST r3, [200] stores the key in memory at address 200, where a program can pick it up later. That is the handler's whole job, done in two instructions.
The saved 4 goes back into the PC, and the main program carries on with JMP 2 as if nothing happened. Real CPUs do this with a return instruction (RETI on AVR, IRET on x86). TINY-8 has none, so the figure does it.
Timers and DMA
A timer is a device that raises its line at a steady rate, every few milliseconds. Its handler belongs to the operating system: it lets the OS take the CPU back from a program that never stops, and share it between programs.
Copying a big block with one IN per byte would keep the CPU busy. A DMA (direct memory access) controller copies the network card's bytes straight into memory by itself, then raises one interrupt when the whole block is done.
The working
;; step 1/11 · devices ;; about: TINY-8 CPU, Keyboard, Timer I/O = input/output input devices: keyboard, network card other devices: timer, disk, screen The CPU runs one instruction after another. A device needs attention at times the CPU cannot predict. Two ways to find out: polling the CPU keeps asking interrupts the device speaks up
A lit wire with moving dashes is carrying the value the step is about; the white tags riding on it are those values. The round lamps show each interrupt line: glowing means 1. The Python mirrors the hardware's check between instructions: if the line is up, keep the PC in 'saved' and load the handler's address.