# Interfacing a PS/2 keyboard

Collapse OS needs a way to input commands and keyboards are one
of the most straightforward ways to proceed. The PS/2 protocol
is very widespread and relatively simple.

We explain here how to interface a PS/2 keyboard with a RC2014.

# Gathering parts

* A RC2014 Classic that could install the base recipe
* A PS/2 keyboard. A USB keyboard + adapter also works, if it's
  not too recent (if it still speaks PS/2).
* A PS/2 female connector.
* ATtiny85/45/25 (main MCU for the device)
* 74xx595 (shift register)
* 40106 inverter gates
* Diodes for A*, IORQ, RO.
* Proto board, RC2014 header pins, wires, IC sockets, etc.
* AVRA (https://github.com/hsoft/avra). The code for this recipe
  hasn't been translated to Collapse OS' AVR assembler yet.

# Building the PS/2 interface

Let's start with the PS/2 connector (see img/ps2-conn.png),
which has two pins.

Both are connected to the ATtiny45, CLK being on PB2 to have
INT0 on it.

The DATA line is multi-use. That is, PB1 is connected both to
the PS/2 data line and to the 595's SER. This saves us a
precious pin.

The ATtiny 45 (img/ps2-t45.png) hooks everything together. CE
comes from the z80 bus (img/ps2-z80.png).

The 595 (img/ps2-595.png) allows us to supply the z80 bus with
data within its 375ns limits. SRCLR is hooked to the CE line so
that whenever a byte is read, the 595 is zeroed out as fast as
possible so that the z80 doesn't read "false doubles".

The 595, to have its SRCLR becoming effective, needs a RCLK
trigger, which doesn't happen immediately. It's the ATtiny45, in
its PCINT interrupt, that takes care of doing that trigger (as
fast as possible).

Our device is read only, on one port. That makes the "Chip
Enable" (CE) selection rather simple. In my design, I chose the
IO port 8, so I inverted A3. I chose a 40106 inverter to do
that, do as you please for your own design.

I wanted to hook CE to a flip flop so that the MCU could relax a
bit more w.r.t. reacting to its PB4 pin changes, but I didn't
have NAND gates that are fast enough in stock, so I went with
this design. But otherwise, I would probably have gone the
flip-flop way. Seems more solid.

Then, all you need to do is to assemble code/ps2ctl.asm and load
it onto your ATtiny.

# Using the PS/2 interface

To use this interface, you have to build a new Collapse OS
binary. This binary needs two things.

First, we need a "(ps2kc)" routine (see doc/protocol.txt). In
this case, it's easy, it's ": (ps2kc) 8 PC@ ;". Then, we can
load PS/2 subsystem. You add "411 414 LOADR". Then, at
initialization, you add "PS2$".  You also need to define PS2_MEM
at the top. You can probably use "SYSVARS + 0x7a".

The PS/2 subsystem provides "(key)" from "(ps2kc)".

For debugging purposes, you might not want to go straight to
plugging PS/2 "(key)" into the system. What I did myself was to
load the PS/2 subsystem *before* ACIA (which overrides with its
own "(key)") and added a dummy word in between to access PS/2's
key.
