+ idle();
+
+ /* wait start bit */
+ wait_clock_lo(2000);
+ data = recv_data();
+
+ inhibit();
+ return data;
+}
+
+#ifndef PS2_INT_VECT
+uint8_t ps2_host_recv(void)
+{
+ return ps2_host_recv_response();
+}
+#else
+/* ring buffer to store ps/2 key data */
+#define PBUF_SIZE 8
+static uint8_t pbuf[PBUF_SIZE];
+static uint8_t pbuf_head = 0;
+static uint8_t pbuf_tail = 0;
+static inline void pbuf_enqueue(uint8_t data)
+{
+ if (!data)
+ return;
+
+ uint8_t sreg = SREG;
+ cli();
+ uint8_t next = (pbuf_head + 1) % PBUF_SIZE;
+ if (next != pbuf_tail) {
+ pbuf[pbuf_head] = data;
+ pbuf_head = next;
+ } else {
+ debug("pbuf: full\n");
+ }
+ SREG = sreg;
+}
+static inline uint8_t pbuf_dequeue(void)
+{
+ uint8_t val = 0;
+
+ uint8_t sreg = SREG;
+ cli();
+ if (pbuf_head != pbuf_tail) {
+ val = pbuf[pbuf_tail];
+ pbuf_tail = (pbuf_tail + 1) % PBUF_SIZE;
+ }
+ SREG = sreg;
+
+ return val;
+}
+
+/* get data received by interrupt */
+uint8_t ps2_host_recv(void)
+{
+ if (ps2_error) {
+ print("x");
+ phex(ps2_error);
+ ps2_host_send(0xFE); // request to resend
+ ps2_error = PS2_ERR_NONE;
+ }
+ idle();
+ return pbuf_dequeue();
+}
+
+#if 0
+#define DEBUGP_INIT() do { DDRC = 0xFF; } while (0)
+#define DEBUGP(x) do { PORTC = x; } while (0)
+#else
+#define DEBUGP_INIT()
+#define DEBUGP(x)
+#endif
+ISR(PS2_INT_VECT)
+{
+ static enum {
+ INIT,
+ START,
+ BIT0, BIT1, BIT2, BIT3, BIT4, BIT5, BIT6, BIT7,
+ PARITY,
+ STOP,
+ } state = INIT;
+ static uint8_t data = 0;
+ static uint8_t parity = 1;
+
+ // TODO: abort if elapse 100us from previous interrupt
+
+ // return unless falling edge
+ if (clock_in()) {
+ goto RETURN;
+ }
+
+ state++;
+ DEBUGP(state);
+ switch (state) {
+ case START:
+ if (data_in())
+ goto ERROR;
+ break;
+ case BIT0:
+ case BIT1:
+ case BIT2:
+ case BIT3:
+ case BIT4:
+ case BIT5:
+ case BIT6:
+ case BIT7:
+ data >>= 1;
+ if (data_in()) {
+ data |= 0x80;
+ parity++;
+ }
+ break;
+ case PARITY:
+ if (data_in()) {
+ if (!(parity & 0x01))
+ goto ERROR;
+ } else {
+ if (parity & 0x01)
+ goto ERROR;
+ }
+ break;
+ case STOP:
+ if (!data_in())
+ goto ERROR;
+ pbuf_enqueue(data);
+ goto DONE;
+ break;
+ default:
+ goto ERROR;
+ }
+ goto RETURN;
+ERROR:
+ DEBUGP(0x0F);
+ inhibit();
+ ps2_error = state;
+DONE:
+ state = INIT;
+ data = 0;
+ parity = 1;
+RETURN:
+ return;
+}
+#endif
+
+
+static void ps2_reset(void)
+{
+ ps2_host_send(0xFF);
+}
+
+/* send LED state to keyboard */
+void ps2_host_set_led(uint8_t led)
+{
+ ps2_host_send(0xED);
+ ps2_host_send(led);
+}
+
+
+/* called after start bit comes */
+static uint8_t recv_data(void)
+{
+ uint8_t data = 0;
+ bool parity = true;
+ ps2_error = PS2_ERR_NONE;