-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSPISlave.cpp
60 lines (50 loc) · 1.24 KB
/
SPISlave.cpp
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
/*
SPISlave.cpp - Library for using the Arduino as an SPI slave.
Based on the forum post of Nick Gammon (2011)
Designed mainly for the UNO board or a bare ATMEGA328P.
Created by Calvin Ng, June 2019
Released under MIT License
*/
#include "Arduino.h"
#include "SPISlave.h"
SPISlaveClass SPISlave;
void SPISlaveClass::begin(uint8_t spie, uint8_t dord, uint8_t cpol, uint8_t cpha)
{
pinMode(SCK, INPUT);
pinMode(MOSI, INPUT);
pinMode(MISO, OUTPUT);
pinMode(SS, INPUT);
SPCR = 0;
SPCR |= bit(SPE);
if(spie) SPCR |= bit(SPIE);
if(dord) SPCR |= bit(DORD);
if(cpol) SPCR |= bit(CPOL);
if(cpha) SPCR |= bit(CPHA);
}
void SPISlaveClass::end()
{
pinMode(MISO, INPUT);
SPCR = 0;
}
uint8_t SPISlaveClass::transferByte(uint8_t data)
{
//sends byte to master and waits for reply
SPDR = data;
while(!(SPSR & bit(SPIF)));
return SPDR;
}
void SPISlaveClass::transferString(void *buf, size_t count)
{
if (count == 0) return;
uint8_t *p = (uint8_t *)buf;
SPDR = *p;
while (--count > 0) {
uint8_t out = *(p + 1);
while (!(SPSR & _BV(SPIF))) ;
uint8_t in = SPDR;
SPDR = out;
*p++ = in;
}
while (!(SPSR & _BV(SPIF))) ;
*p = SPDR;
}