#define F_CPU 8000000UL
#define UART_BAUD 9600

#include <avr/io.h>
#include <avr/interrupt.h>
#include "uart.h"
#include "util.h"

/* AVR313: Interfacing the PC AT Keyboard */
unsigned char edge, bitcount;

ISR(INT0_vect) {
    static unsigned char data;
    
    if (!edge) { /* falling edge */
	if (bitcount < 11 && bitcount > 2) {
	    data = (data >> 1);
	    if (PINB & _BV(PB1)) {
		data |= 0x80;
	    }
	}
	MCUCR = _BV(ISC01) | _BV(ISC00); /* int0 on rising edge */
	edge = 1;
    } else {
	if (--bitcount == 0) {
	    print_bits(data);
	    uart_putchar('\r');
	    uart_putchar('\n');
	    bitcount = 11;
	}
	MCUCR = _BV(ISC01); /* int0 on falling edge */
	edge = 0;
    }
}

int main(void) {
    uart_init();
    uart_putchar('i');
    DDRB &= ~_BV(PB1); /* kbd_data in */
    DDRD &= ~_BV(PD2); /* kbd_clock in */
    PORTB |= _BV(PB1); /* pull up kbd_data */
    PORTD |= _BV(PD2); /* pull up kbd_clock */
    MCUCR = _BV(ISC01); /* int0 on falling edge */
    GIMSK = _BV(INT0); /* enable int0 */
    bitcount = 11;
    edge = 0;
    sei();
    uart_putchar('I');

    for (;;) {
    }
    
}
