tabby/avr/recv.c
2016-06-01 22:30:12 -05:00

144 lines
2.5 KiB
C

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <tabby/printer.h>
#include <tabby/avr/uart.h>
static volatile tabby_printer_packet header = {
.type = 0,
.compression = 0,
.size = 0
};
static volatile uint16_t i = 0,
b = 0;
/*
* SPI byte receipt interrupt vector
*/
ISR(SPI_STC_vect) {
uint8_t in = SPDR,
out = 0x00;
uart_putchar(in, NULL);
switch (i) {
case 0: {
if (in == 0x88) {
header.data[0] = in;
i++;
b = 0;
}
break;
}
case 1: {
if (in == 0x33) {
header.data[1] = in;
i++;
} else {
i = 0;
}
break;
}
case 2: {
header.type = in;
i++;
break;
}
case 3: {
header.compression = in;
i++;
break;
}
case 4: {
header.size = in;
i++;
break;
}
case 5: {
header.size |= in << 8;
i++;
break;
}
default: {
if (b <= header.size) {
b++;
} else if (b == header.size + 1) {
b++;
out = 0x81;
} else if (b == header.size + 2) {
b++;
} else if (b == header.size + 3) {
i = 0;
}
}
}
SPDR = out;
}
static void setup_clock_external() {
/*
* Configure MISO as output
*/
DDRB |= (1 << DDB4);
/*
* Configure SS as input
*/
DDRB &= ~(1 << DDB2);
/*
* Set SPI slave mode, and shift in/out most significant bit first
*/
SPCR &= ~((1 << MSTR) | (1 << DORD));
/*
* Enable SPI in Mode 3 with interrupts
*/
SPCR |= (1 << CPOL) | (1 << CPHA) | (1 << SPIE) | (1 << SPE);
/*
* Initialize the SPI Data Register and serial buffer
*/
SPDR = 0;
}
int main() {
/*
* Best turn on the serial UART!
*/
uart_init();
/*
* By default, the Game Boy link port is configured to monitor for external
* clock pulses, so we'll go ahead and do that in this case.
*/
setup_clock_external();
/*
* We do actually want to globally enable interrupts here, so here's that
* one assembly instruction to do so.
*/
sei();
while (1) {
sleep_mode();
}
return 0;
}