1 | #include "spi.h"
|
2 |
|
3 | #include <avr/io.h>
|
4 | #include <avr/interrupt.h>
|
5 |
|
6 | #define PORT_SPI PORTB
|
7 | #define DDR_SPI DDRB
|
8 | #define DD_MISO DDB4
|
9 | #define DD_MOSI DDB3
|
10 | #define DD_SS DDB2
|
11 | #define DD_SCK DDB5
|
12 |
|
13 |
|
14 | void spi_init()
|
15 | // Initialize pins for spi communication
|
16 | {
|
17 | //Intialise the SPI-USI Communication
|
18 | DDRB |= (1<<DD_SS) | (1<<DD_SCK) | (1<<DD_MISO);
|
19 | DDRB &= ~(1<<DD_MOSI);
|
20 | PORTB |= (1<<DD_MOSI);
|
21 |
|
22 | USICR |= (1<<USIWM0) | (1<<USICS1) | (1<<USICLK); // Three-Wire Mode - Uses DO, DI, and USCK pins;
|
23 | SETBIT(PORTB,DD_SS);
|
24 | }
|
25 |
|
26 | void spi_transfer_sync (uint8_t * dataout, uint8_t * datain, uint8_t len)
|
27 | // Shift full array through target device
|
28 | {
|
29 | uint8_t i;
|
30 | for (i = 0; i < len; i++) {
|
31 | USIDR = dataout[i];
|
32 | while(!(USISR & (1<<USIOIF))){
|
33 | USICR |= (1<<USIWM0)|(1<<USICS1)|(1<<USICLK)|(1<<USITC);
|
34 | }
|
35 | datain[i] = USIDR;
|
36 | }
|
37 | }
|
38 |
|
39 | void spi_transmit_sync (uint8_t * dataout, uint8_t len)
|
40 | // Shift full array to target device without receiving any byte
|
41 | {
|
42 | uint8_t i;
|
43 | for (i = 0; i < len; i++) {
|
44 | USIDR = dataout[i];
|
45 | while(!(USISR & (1<<USIOIF))){
|
46 | USICR |= (1<<USIWM0)|(1<<USICS1)|(1<<USICLK)|(1<<USITC);
|
47 | }
|
48 | }
|
49 | }
|
50 |
|
51 | uint8_t spi_fast_shift (uint8_t data)
|
52 | {
|
53 | // load USI Data Register with data to transmit
|
54 | USIDR = data;
|
55 | while(!(USISR & (1<<USIOIF))){
|
56 | USICR |= (1<<USIWM0)|(1<<USICS1)|(1<<USICLK)|(1<<USITC);
|
57 | }
|
58 | return USIDR;
|
59 | }
|