spi.c


1
#include "spi.h"
2
3
void spi_init(unsigned char mode)
4
{
5
   switch (mode)
6
   {
7
      //Beide SPI-Interfaces initialisieren...
8
      case 0:
9
         DDRD |= (1<<PD7); //Slave-Select-Pin
10
         PORTD |= (1<<PD7); //Deselect-Slave
11
         UBRR0 = 0;
12
         //Setting the XCKn port pin as output, enables master mode
13
         DDRD |= (1<<PD4)|(1<<PD1);
14
         PORTB |= (1<<PD0);
15
         /* Set MSPI mode of operation and SPI data mode 0. */
16
         UCSR0C = (1<<UMSEL01)|(1<<UMSEL00);
17
         /* Enable receiver and transmitter. */
18
         UCSR0B = (1<<TXEN0)|(1<<RXEN0);
19
         //Set baud rate
20
         //IMPORTANT: The Baud Rate must be set after the transmitter is enabled
21
         UBRR0 = 1;
22
23
      //SPI Interface initialisieren...
24
      case 1:
25
         // Set SCK,MOSI,/SS as output, all others input
26
         DDRB = (1<<PB5)|(1<<PB3)|(1<<PB2);
27
         PORTB |= (1<<PB2); // /SS Held high
28
         //Master-Mode, SPI enabled, LSB first
29
         SPCR = (1<<MSTR)|(1<<SPE);
30
         break;
31
      default:
32
         break;
33
   }
34
}
35
36
int spi_write(unsigned char id, unsigned char cData)
37
{
38
   switch (id)
39
   {
40
      //Write on SPI-Interface
41
      case 0:
42
         //Writing the register starts the transmission
43
         SPDR = cData;
44
         //Wait for transmission complete
45
         while(!(SPSR & (1<<SPIF)));
46
         break;
47
48
      //Write on USART-Interface in SPI-Mode
49
      case 1:
50
         //Wait for empty transmit buffer
51
         while ( !( UCSR0A & (1<<UDRE0)) );
52
         UCSR0A |= (1<<TXC0); //Clear Transmit Flag
53
         //Put data into buffer (sends the data)
54
         UDR0 = cData;
55
         //Wait for transmit complete
56
         while ( !( UCSR0A & (1<<TXC0)) );
57
         break;
58
59
      default:
60
         break;
61
   }
62
   return 0;
63
}
64
65
66
int spi_read(unsigned char id, unsigned char *cData)
67
{
68
   switch (id)
69
   {
70
      //Read from SPI-Interface
71
      case 0:
72
         //Reading the register starts the transmission
73
         SPSR |= (1<<SPIF);
74
         SPDR = 0x00;
75
         //Wait for transmit complete
76
         while(!(SPSR & (1<<SPIF)));
77
         *cData = SPDR;
78
         break;
79
80
      //Read from USART-Interface in SPI-Mode
81
      case 1:
82
         while(!(UCSR0A & (1<<UDRE0)));
83
         UDR0 = 0x00;
84
         UCSR0A |= (1<<RXC0); //Clear Receive Flag
85
         //Wait for receive complete
86
         while ( !(UCSR0A & (1<<RXC0)) );
87
         //Get received data from buffer
88
         *cData = UDR0;
89
         break;
90
      default:
91
         break;
92
   }
93
   return 0;
94
}