-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspi.hpp
72 lines (61 loc) · 1.55 KB
/
spi.hpp
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
69
70
71
72
#pragma once
#include <avr/io.h>
#define SPI_DDR DDRB
#if defined(__AVR_ATmega328P__)
#define SPI_SCK PB5
#define SPI_MISO PB4
#define SPI_MOSI PB3
#elif defined(__AVR_ATmega2560__)
#define SPI_SCK PB1
#define SPI_MISO PB3
#define SPI_MOSI PB2
#endif
/**
* SPI implements an interface to the SPI bus.
*/
class SPI {
public:
/**
* Default constructor which enables SPI.
*/
SPI() {
// Source: _C Code Example_ on page 137 in the datasheet
// Set MOSI and SCK output, all others input
SPI_DDR = (1<<SPI_MOSI) | (1<<SPI_SCK);
// Enable SPI, Master, set clock rate fck/16
SPCR = (1<<SPE) | (1<<MSTR);
};
/**
* Start starts the transfer by setting the CS pin to _low_.
* \param port The port of the pin.
* \param pin The pin.
*/
void start(volatile uint8_t *port, const uint8_t pin) {
*port &= ~(1<<pin);
}
/**
* Read reads one byte from the SPI bus.
* \return Returns the byte.
*/
uint8_t read() {
SPDR = 0x00;
while (!(SPSR & (1<<SPIF)));
return SPDR;
}
/**
* Write writes one byte to the SPI bus.
* \param byte The byte to send.
*/
void write(const uint8_t byte) {
SPDR = byte;
while (!(SPSR & (1<<SPIF)));
}
/**
* Stop stops the transfer by setting the CS pin to _high_.
* \param port The port of the pin.
* \param pin The pin.
*/
void stop(volatile uint8_t *port, const uint8_t pin) {
*port |= (1<<pin);
}
};