Arduino-SPI
Serial Peripheral Interface (SPI) library for Arduino
SPI.h
Go to the documentation of this file.
1 
19 #ifndef SOFTWARE_SPI_H
20 #define SOFTWARE_SPI_H
21 
22 #include "GPIO.h"
23 #include "SPI.h"
24 
25 #ifndef CHARBITS
26 #define CHARBITS 8
27 #endif
28 
35 namespace Software {
36 template<BOARD::pin_t MOSI_PIN,
37  BOARD::pin_t MISO_PIN,
38  BOARD::pin_t SCK_PIN>
39 class SPI : public ::SPI {
40 public:
45  SPI() :
46  ::SPI()
47  {
48  m_sck.output();
49  m_mosi.output();
50  m_miso.input();
51  }
52 
60  virtual void acquire(uint8_t mode, uint8_t bitorder, uint8_t scale)
61  {
62  (void) scale;
63  lock();
64  m_sck = mode & 2;
65  m_cpha = mode & 1;
66  m_bitorder = bitorder;
67  }
68 
73  virtual void release()
74  {
75  m_mosi = LOW;
76  unlock();
77  }
78 
85  virtual uint8_t transfer(uint8_t value)
86  {
87  const bool cpha = m_cpha;
88  uint8_t bits = CHARBITS;
89  if (m_bitorder == MSBFIRST) {
90  do {
91  if (cpha) m_sck.toggle();
92  m_mosi = value & 0x80;
93  m_sck.toggle();
94  value <<= 1;
95  value |= m_miso;
96  if (!cpha) m_sck.toggle();
97  } while (--bits);
98  }
99  else {
100  do {
101  if (cpha) m_sck.toggle();
102  m_mosi = value & 0x01;
103  m_sck.toggle();
104  value >>= 1;
105  value |= (m_miso ? 0x80 : 0x00);
106  if (!cpha) m_sck.toggle();
107  } while (--bits);
108  }
109  return (value);
110  }
111 
112  using ::SPI::transfer;
113 
114 protected:
116  GPIO<SCK_PIN> m_sck;
117 
119  GPIO<MOSI_PIN> m_mosi;
120 
122  GPIO<MISO_PIN> m_miso;
123 
125  bool m_cpha;
126 
128  uint8_t m_bitorder;
129 };
130 
131 };
132 #endif
GPIO< MOSI_PIN > m_mosi
Definition: SPI.h:119
GPIO< SCK_PIN > m_sck
Definition: SPI.h:116
#define MOSI_PIN
Definition: ShiftIn.ino:39
#define CHARBITS
Definition: SPI.h:26
uint8_t m_bitorder
Definition: SPI.h:128
virtual void acquire(uint8_t mode, uint8_t bitorder, uint8_t scale)
Definition: SPI.h:60
Definition: SPI.h:35
GPIO< MISO_PIN > m_miso
Definition: SPI.h:122
virtual void release()
Definition: SPI.h:73
bool m_cpha
Definition: SPI.h:125
void lock()
Definition: SPI.h:252
void unlock()
Definition: SPI.h:262
#define MISO_PIN
Definition: ShiftIn.ino:40
#define SCK_PIN
Definition: ShiftIn.ino:41
virtual uint8_t transfer(uint8_t value)
Definition: SPI.h:85