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