root / branches / simulator / projects / libdragonfly / spi.c @ 1089
History | View | Annotate | Download (1.78 KB)
1 | 868 | justin | /**
|
---|---|---|---|
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 | void spi_init (spi_fun_recv_t recv_func, spi_fun_recv_complete_t recv_complete_func)
|
||
18 | { |
||
19 | /* Enable Interrupt, Enable SPI Module, MSB First, Master Mode, Clock div = 64 */
|
||
20 | SPCR = _BV(SPE) | _BV(SPIE) /*| _BV(DORD)*/ | _BV(MSTR) | _BV(SPR1) | _BV(SPR0);
|
||
21 | SPSR = _BV(SPI2X); |
||
22 | |||
23 | /* Set SCLK, SS, MOSI as outputs. MISO as input */
|
||
24 | DDRB |= MOSI | SCLK | SS; |
||
25 | DDRB &= ~MISO; |
||
26 | |||
27 | /* Keep SS high until transmit */
|
||
28 | PORTB |= SS; |
||
29 | |||
30 | /* set function to be executed when we receive a byte */
|
||
31 | spi_recv_func = recv_func; |
||
32 | spi_recv_complete_func = recv_complete_func; |
||
33 | spi_bytes = 0;
|
||
34 | //usb_puts("\tspi.c Debug: SPI INITIALIZED\n");
|
||
35 | } |
||
36 | |||
37 | void spi_transfer(char bytes) |
||
38 | { |
||
39 | spi_bytes = bytes; |
||
40 | PORTB &= ~SS; /* Set SS low to initiate transmission */
|
||
41 | SPDR = 0xff; /* Initiate data transmision */ |
||
42 | } |
||
43 | |||
44 | ISR(SIG_SPI) |
||
45 | { |
||
46 | //usb_puts("Interrupt");
|
||
47 | /* only handle intterupt when we are expecting data */
|
||
48 | if(spi_bytes > 0){ |
||
49 | /* process byte */
|
||
50 | spi_recv_func(SPDR); |
||
51 | /* if we've read all the bytes, set SS high to end transmission,
|
||
52 | * otherwise get the next byte */
|
||
53 | if(--spi_bytes == 0){ |
||
54 | //usb_puts("Read all bytes\r\n");
|
||
55 | PORTB |= SS; |
||
56 | if(spi_recv_complete_func)
|
||
57 | spi_recv_complete_func(); |
||
58 | }else {
|
||
59 | //usb_puts("There are this many bytes left: "); usb_puti(spi_bytes);usb_puts("\r\n");
|
||
60 | SPDR = 0xff;
|
||
61 | } |
||
62 | } |
||
63 | } |