root / branches / encoders / code / projects / libdragonfly / spi.c @ 694
History | View | Annotate | Download (1.58 KB)
1 |
/* @file spi.c
|
---|---|
2 |
* @brief
|
3 |
* SPI module
|
4 |
* @bug broken
|
5 |
*/
|
6 |
|
7 |
#include <avr/interrupt.h> |
8 |
#include "ring_buffer.h" |
9 |
#include "spi.h" |
10 |
#include <dragonfly_lib.h> |
11 |
|
12 |
|
13 |
/*
|
14 |
SS = PB0
|
15 |
SCK = PB1
|
16 |
MOSI = PB2
|
17 |
MISO = PB3
|
18 |
*/
|
19 |
/* Controls clock freq. see Table 72 of specs*/
|
20 |
|
21 |
#define DOUBLE_SCK 1 |
22 |
#define SPR0_BIT 1 |
23 |
#define SPR1_BIT 0 |
24 |
#define LSB 1 |
25 |
#define MSB 0 |
26 |
#define FIRST_BYTE 1 |
27 |
#define SECOND_BYTE 2 |
28 |
|
29 |
RING_BUFFER_NEW(spi_buffer, 16, char, spi_send_buff, spi_rec_buff); |
30 |
volatile char spi_status; |
31 |
char spi_mode;
|
32 |
static spi_fun_recv_t spi_recv_function;
|
33 |
//static spi_fun_send_t spi_send_function;
|
34 |
static volatile uint16_t i; |
35 |
|
36 |
void spi_init(spi_fun_recv_t recv_func) {
|
37 |
usb_puts("spi_init: start\n");
|
38 |
|
39 |
|
40 |
spi_recv_function = recv_func; |
41 |
//spi_send_function = send_func;
|
42 |
|
43 |
/* Enables the SPI module
|
44 |
* Enable Interrupt, Enable SPI Module, LSB First, Master Mode, Clock div = 64
|
45 |
*/
|
46 |
SPCR = _BV(SPE) | _BV(SPIE)|_BV(DORD) | _BV(MSTR)| _BV(SPR1) | _BV(SPR0); |
47 |
SPSR = _BV(SPI2X); |
48 |
|
49 |
spi_status = SPI_VOID; |
50 |
|
51 |
/* Set SCLK, SS, MOSI as outputs. MISO as input */
|
52 |
DDRB = MOSI | SCLK | SS; |
53 |
DDRB &= ~MISO; |
54 |
PORTB |= SS; //Keep SS High until transmit
|
55 |
|
56 |
//sei();
|
57 |
usb_puts("spi_init: end\n");
|
58 |
} |
59 |
|
60 |
void spi_transfer(char c){ |
61 |
|
62 |
spi_mode = FIRST_BYTE; |
63 |
PORTB &= ~SS; |
64 |
SPDR = c; |
65 |
} |
66 |
|
67 |
ISR(SIG_SPI) { |
68 |
// usb_puts("ISR: start\n\r");
|
69 |
//char c=SPDR;
|
70 |
//PORTB |= SS;
|
71 |
if(spi_mode == FIRST_BYTE){
|
72 |
i = (uint16_t)SPDR; |
73 |
spi_recv_function(SPDR); |
74 |
spi_mode = SECOND_BYTE; |
75 |
SPDR = 'c';
|
76 |
SPDR = 'c';
|
77 |
} else {
|
78 |
usb_puts("second byte\r\n");
|
79 |
i = (uint16_t)SPDR << 8;
|
80 |
spi_mode = 4;
|
81 |
PORTB |= SS; |
82 |
} |
83 |
|
84 |
//usb_puts("ISR: end\n");
|
85 |
} |