-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspi.c
68 lines (54 loc) · 1.37 KB
/
spi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <avr/io.h>
#include <util/delay.h>
#include "spi.h"
#define DDR_SPI DDRB
#define DD_SS DDB2
#define DD_MOSI DDB3
#define DD_MISO DDB4
#define DD_SCK DDB5
void SPI_Clear() {
// LE high
PORTC |= _BV(PC2);
SPDR = 0x00;
// Wait for transmission complete
while (!(SPSR & (1 << SPIF)));
SPDR = 0x00;
// Wait for transmission complete
while (!(SPSR & (1 << SPIF)));
// LE low
PORTC &= ~_BV(PC2);
}
void SPI_MasterInit(void) {
DDRC |= _BV(PC1); // OE as an output
DDRC |= _BV(PC2); // LE as an output
// OE and LE low
PORTC &= ~_BV(PC1);
PORTC &= ~_BV(PC2);
// Set MOSI and SCK output, all others input
DDR_SPI = (1 << DD_MOSI) | (1 << DD_SCK) | (1 << DD_SS);
// Enable SPI, Master, set clock rate fck/16
SPCR = (1 << SPE) | (1 << MSTR);
SPI_Clear();
}
void uint16ToChar(uint16_t value, char cData[2]){
cData[0] = (value >> 8);
cData[1] = value;
}
void SPI_MasterTransmit(const uint16_t data) {
// OE high
PORTC |= _BV(PC1);
SPI_Clear();
char cData[2];
uint16ToChar(data, cData);
// LE high
PORTC |= _BV(PC2);
SPDR = cData[0];
// Wait for transmission complete
while (!(SPSR & (1 << SPIF)));
SPDR = cData[1];
// Wait for transmission complete
while (!(SPSR & (1 << SPIF)));
// LE and OE low
PORTC &= ~_BV(PC2);
PORTC &= ~_BV(PC1);
}