root / branches / encoders / code / lib / src / libdragonfly / spi.c @ 752
History | View | Annotate | Download (1.81 KB)
1 |
/**
|
---|---|
2 |
* @file spi.c
|
3 |
* @brief Basic SPI module to handle encoders
|
4 |
* @author Colony Project, CMU Robotics Club
|
5 |
* @bug Not tested
|
6 |
* Need to move spi.h include into dragonfly_lib.h when stable
|
7 |
**/
|
8 |
|
9 |
#include <avr/interrupt.h> |
10 |
#include <dragonfly_lib.h> |
11 |
#include "spi.h" |
12 |
|
13 |
|
14 |
static volatile char spi_bytes; /* number of bytes to read */ |
15 |
static spi_fun_recv_t spi_recv_func; /* byte handler */ |
16 |
static spi_fun_recv_complete_t spi_recv_complete_func; /*transmission completion handler */ |
17 |
|
18 |
void spi_init (spi_fun_recv_t recv_func, spi_fun_recv_complete_t recv_complete_func)
|
19 |
{ |
20 |
/* Enable Interrupt, Enable SPI Module, MSB First, Master Mode, Clock div = 64 */
|
21 |
SPCR = _BV(SPE) | _BV(SPIE) /*| _BV(DORD)*/ | _BV(MSTR) | _BV(SPR1) | _BV(SPR0);
|
22 |
SPSR = _BV(SPI2X); |
23 |
|
24 |
/* Set SCLK, SS, MOSI as outputs. MISO as input */
|
25 |
DDRB |= MOSI | SCLK | SS; |
26 |
DDRB &= ~MISO; |
27 |
|
28 |
/* Keep SS high until transmit */
|
29 |
PORTB |= SS; |
30 |
|
31 |
/* set function to be executed when we receive a byte */
|
32 |
spi_recv_func = recv_func; |
33 |
spi_recv_complete_func = recv_complete_func; |
34 |
spi_bytes = 0;
|
35 |
} |
36 |
|
37 |
/* Transfer a given byte to slave and receive a byte */
|
38 |
void spi_transfer(char bytes) |
39 |
{ |
40 |
spi_bytes = bytes; |
41 |
PORTB &= ~SS; /* Set SS low to initiate transmission */
|
42 |
SPDR = 0xff; /* Initiate data transmision */ |
43 |
} |
44 |
|
45 |
ISR(SIG_SPI) |
46 |
{ |
47 |
//usb_puts("Interrupt");
|
48 |
/* only handle intterupt when we are expecting data */
|
49 |
if(spi_bytes > 0){ |
50 |
/* process byte */
|
51 |
spi_recv_func(SPDR); |
52 |
/* if we've read all the bytes, set SS high to end transmission,
|
53 |
* otherwise get the next byte */
|
54 |
if(--spi_bytes == 0){ |
55 |
//usb_puts("Read all bytes\r\n");
|
56 |
PORTB |= SS; |
57 |
if(spi_recv_complete_func)
|
58 |
spi_recv_complete_func(); |
59 |
}else {
|
60 |
//usb_puts("There are this many bytes left: "); usb_puti(spi_bytes);usb_puts("\r\n");
|
61 |
SPDR = 0xff;
|
62 |
} |
63 |
} |
64 |
} |