tabby/avr/recv.c
2016-06-06 19:16:05 -05:00

131 lines
2.3 KiB
C

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <tabby/printer.h>
#include <tabby/avr/uart.h>
#include <tabby/avr.h>
static volatile tabby_printer_packet header;
static volatile uint16_t i, b;
/*
* SPI byte receipt interrupt vector
*/
ISR(SPI_STC_vect) {
uint8_t in = SPDR,
out = 0;
uart_putchar(in, NULL);
switch (i) {
case 0: {
if (in == TABBY_PRINTER_SYNC_1) {
header.preamble[0] = in;
i++;
b = 0;
}
break;
}
case 1: {
if (in == TABBY_PRINTER_SYNC_2) {
header.preamble[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++;
if (header.size > TABBY_PRINTER_PACKET_MAX_SIZE) {
i = 0;
}
break;
}
default: {
if (b <= header.size) {
b++;
} else if (b == header.size + 1) {
b++;
out = TABBY_PRINTER_DEVICE_ID;
} else if (b == header.size + 2) {
b++;
out = TABBY_PRINTER_OK;
} else if (b == header.size + 3) {
i = 0;
}
}
}
SPDR = out;
}
static void spi_init() {
SS_INPUT();
SC_INPUT();
SI_INPUT();
SO_OUTPUT();
/*
* Set SPI slave mode, and shift in/out most significant bit first
*/
SPCR &= ~((1 << MSTR) | (1 << DORD));
/*
* Enable SPI in Mode 3 with interrupts, clock nominally high, output on
* falling edge, input on rising edge
*/
SPCR |= (1 << CPOL) | (1 << CPHA) | (1 << SPIE) | (1 << SPE);
/*
* Initialize the SPI Data Register and serial buffer
*/
SPDR = 0;
}
int main() {
uart_init();
spi_init();
sei();
while (1) {
sleep_mode();
}
return 0;
}