ESPHome  2024.11.0
spi.h
Go to the documentation of this file.
1 #pragma once
2 
5 #include "esphome/core/hal.h"
6 #include "esphome/core/log.h"
7 #include <map>
8 #include <utility>
9 #include <vector>
10 
11 #ifdef USE_ARDUINO
12 
13 #include <SPI.h>
14 
15 #ifdef USE_RP2040
16 using SPIInterface = SPIClassRP2040 *;
17 #else
18 using SPIInterface = SPIClass *;
19 #endif
20 
21 #endif
22 
23 #ifdef USE_ESP_IDF
24 
25 #include "driver/spi_master.h"
26 
27 using SPIInterface = spi_host_device_t;
28 
29 #endif // USE_ESP_IDF
30 
34 namespace esphome {
35 namespace spi {
36 
43 };
59 };
69 };
70 
76 enum SPIMode {
77  MODE0 = 0,
78  MODE1 = 1,
79  MODE2 = 2,
80  MODE3 = 3,
81 };
87 enum SPIDataRate : uint32_t {
89  DATA_RATE_75KHZ = 75000,
90  DATA_RATE_200KHZ = 200000,
91  DATA_RATE_1MHZ = 1000000,
92  DATA_RATE_2MHZ = 2000000,
93  DATA_RATE_4MHZ = 4000000,
94  DATA_RATE_5MHZ = 5000000,
95  DATA_RATE_8MHZ = 8000000,
96  DATA_RATE_10MHZ = 10000000,
97  DATA_RATE_20MHZ = 20000000,
98  DATA_RATE_40MHZ = 40000000,
99  DATA_RATE_80MHZ = 80000000,
100 };
101 
105 class NullPin : public GPIOPin {
106  friend class SPIComponent;
107 
108  friend class SPIDelegate;
109 
110  friend class Utility;
111 
112  public:
113  void setup() override {}
114 
115  void pin_mode(gpio::Flags flags) override {}
116 
117  bool digital_read() override { return false; }
118 
119  void digital_write(bool value) override {}
120 
121  std::string dump_summary() const override { return std::string(); }
122 
123  protected:
124  static GPIOPin *const NULL_PIN; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
125  // https://bugs.llvm.org/show_bug.cgi?id=48040
126 };
127 
128 class Utility {
129  public:
130  static int get_pin_no(GPIOPin *pin) {
131  if (pin == nullptr || !pin->is_internal())
132  return -1;
133  if (((InternalGPIOPin *) pin)->is_inverted())
134  return -1;
135  return ((InternalGPIOPin *) pin)->get_pin();
136  }
137 
138  static SPIMode get_mode(SPIClockPolarity polarity, SPIClockPhase phase) {
139  if (polarity == CLOCK_POLARITY_HIGH) {
140  return phase == CLOCK_PHASE_LEADING ? MODE2 : MODE3;
141  }
142  return phase == CLOCK_PHASE_LEADING ? MODE0 : MODE1;
143  }
144 
146  switch (mode) {
147  case MODE0:
148  case MODE2:
149  return CLOCK_PHASE_LEADING;
150  default:
151  return CLOCK_PHASE_TRAILING;
152  }
153  }
154 
156  switch (mode) {
157  case MODE0:
158  case MODE1:
159  return CLOCK_POLARITY_LOW;
160  default:
161  return CLOCK_POLARITY_HIGH;
162  }
163  }
164 };
165 
166 // represents a device attached to an SPI bus, with a defined clock rate, mode and bit order. On Arduino this is
167 // a thin wrapper over SPIClass.
168 class SPIDelegate {
169  friend class SPIClient;
170 
171  public:
172  SPIDelegate() = default;
173 
174  SPIDelegate(uint32_t data_rate, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin)
175  : bit_order_(bit_order), data_rate_(data_rate), mode_(mode), cs_pin_(cs_pin) {
176  if (this->cs_pin_ == nullptr)
177  this->cs_pin_ = NullPin::NULL_PIN;
178  this->cs_pin_->setup();
179  this->cs_pin_->digital_write(true);
180  }
181 
182  virtual ~SPIDelegate(){};
183 
184  // enable CS if configured.
185  virtual void begin_transaction() { this->cs_pin_->digital_write(false); }
186 
187  // end the transaction
188  virtual void end_transaction() { this->cs_pin_->digital_write(true); }
189 
190  // transfer one byte, return the byte that was read.
191  virtual uint8_t transfer(uint8_t data) = 0;
192 
193  // transfer a buffer, replace the contents with read data
194  virtual void transfer(uint8_t *ptr, size_t length) { this->transfer(ptr, ptr, length); }
195 
196  virtual void transfer(const uint8_t *txbuf, uint8_t *rxbuf, size_t length) {
197  for (size_t i = 0; i != length; i++)
198  rxbuf[i] = this->transfer(txbuf[i]);
199  }
200 
206  virtual void write(uint16_t data, size_t num_bits) {
207  esph_log_e("spi_device", "variable length write not implemented");
208  }
209 
210  virtual void write_cmd_addr_data(size_t cmd_bits, uint32_t cmd, size_t addr_bits, uint32_t address,
211  const uint8_t *data, size_t length, uint8_t bus_width) {
212  esph_log_e("spi_device", "write_cmd_addr_data not implemented");
213  }
214  // write 16 bits
215  virtual void write16(uint16_t data) {
216  if (this->bit_order_ == BIT_ORDER_MSB_FIRST) {
217  uint16_t buffer;
218  buffer = (data >> 8) | (data << 8);
219  this->write_array(reinterpret_cast<const uint8_t *>(&buffer), 2);
220  } else {
221  this->write_array(reinterpret_cast<const uint8_t *>(&data), 2);
222  }
223  }
224 
225  virtual void write_array16(const uint16_t *data, size_t length) {
226  for (size_t i = 0; i != length; i++) {
227  this->write16(data[i]);
228  }
229  }
230 
231  // write the contents of a buffer, ignore read data (buffer is unchanged.)
232  virtual void write_array(const uint8_t *ptr, size_t length) {
233  for (size_t i = 0; i != length; i++)
234  this->transfer(ptr[i]);
235  }
236 
237  // read into a buffer, write nulls
238  virtual void read_array(uint8_t *ptr, size_t length) {
239  for (size_t i = 0; i != length; i++)
240  ptr[i] = this->transfer(0);
241  }
242 
243  // check if device is ready
244  virtual bool is_ready();
245 
246  protected:
248  uint32_t data_rate_{1000000};
249  SPIMode mode_{MODE0};
251 };
252 
258  public:
259  SPIDelegateBitBash(uint32_t clock, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin, GPIOPin *clk_pin,
260  GPIOPin *sdo_pin, GPIOPin *sdi_pin)
261  : SPIDelegate(clock, bit_order, mode, cs_pin), clk_pin_(clk_pin), sdo_pin_(sdo_pin), sdi_pin_(sdi_pin) {
262  // this calculation is pretty meaningless except at very low bit rates.
263  this->wait_cycle_ = uint32_t(arch_get_cpu_freq_hz()) / this->data_rate_ / 2ULL;
264  this->clock_polarity_ = Utility::get_polarity(this->mode_);
265  this->clock_phase_ = Utility::get_phase(this->mode_);
266  }
267 
268  uint8_t transfer(uint8_t data) override;
269 
270  void write(uint16_t data, size_t num_bits) override;
271 
272  void write16(uint16_t data) override { this->write(data, 16); };
273 
274  protected:
275  GPIOPin *clk_pin_;
278  uint32_t last_transition_{0};
279  uint32_t wait_cycle_;
282 
283  void HOT cycle_clock_() {
284  while (this->last_transition_ - arch_get_cpu_cycle_count() < this->wait_cycle_)
285  continue;
286  this->last_transition_ += this->wait_cycle_;
287  }
288  uint16_t transfer_(uint16_t data, size_t num_bits);
289 };
290 
291 class SPIBus {
292  public:
293  SPIBus() = default;
294 
295  SPIBus(GPIOPin *clk, GPIOPin *sdo, GPIOPin *sdi) : clk_pin_(clk), sdo_pin_(sdo), sdi_pin_(sdi) {}
296 
297  virtual SPIDelegate *get_delegate(uint32_t data_rate, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin) {
298  return new SPIDelegateBitBash(data_rate, bit_order, mode, cs_pin, this->clk_pin_, this->sdo_pin_, this->sdi_pin_);
299  }
300 
301  virtual bool is_hw() { return false; }
302 
303  protected:
304  GPIOPin *clk_pin_{};
305  GPIOPin *sdo_pin_{};
306  GPIOPin *sdi_pin_{};
307 };
308 
309 class SPIClient;
310 
311 class SPIComponent : public Component {
312  public:
313  SPIDelegate *register_device(SPIClient *device, SPIMode mode, SPIBitOrder bit_order, uint32_t data_rate,
314  GPIOPin *cs_pin);
315  void unregister_device(SPIClient *device);
316 
317  void set_clk(GPIOPin *clk) { this->clk_pin_ = clk; }
318 
319  void set_miso(GPIOPin *sdi) { this->sdi_pin_ = sdi; }
320 
321  void set_mosi(GPIOPin *sdo) { this->sdo_pin_ = sdo; }
322  void set_data_pins(std::vector<uint8_t> pins) { this->data_pins_ = std::move(pins); }
323 
324  void set_interface(SPIInterface interface) {
325  this->interface_ = interface;
326  this->using_hw_ = true;
327  }
328 
329  void set_interface_name(const char *name) { this->interface_name_ = name; }
330 
331  float get_setup_priority() const override { return setup_priority::BUS; }
332 
333  void setup() override;
334  void dump_config() override;
335 
336  protected:
337  GPIOPin *clk_pin_{nullptr};
338  GPIOPin *sdi_pin_{nullptr};
339  GPIOPin *sdo_pin_{nullptr};
340  std::vector<uint8_t> data_pins_{};
341 
342  SPIInterface interface_{};
343  bool using_hw_{false};
344  const char *interface_name_{nullptr};
345  SPIBus *spi_bus_{};
346  std::map<SPIClient *, SPIDelegate *> devices_;
347 
348  static SPIBus *get_bus(SPIInterface interface, GPIOPin *clk, GPIOPin *sdo, GPIOPin *sdi,
349  const std::vector<uint8_t> &data_pins);
350 };
351 
356 class SPIClient {
357  public:
358  SPIClient(SPIBitOrder bit_order, SPIMode mode, uint32_t data_rate)
359  : bit_order_(bit_order), mode_(mode), data_rate_(data_rate) {}
360 
361  virtual void spi_setup() {
362  esph_log_d("spi_device", "mode %u, data_rate %ukHz", (unsigned) this->mode_, (unsigned) (this->data_rate_ / 1000));
363  this->delegate_ = this->parent_->register_device(this, this->mode_, this->bit_order_, this->data_rate_, this->cs_);
364  }
365 
366  virtual void spi_teardown() {
367  this->parent_->unregister_device(this);
368  this->delegate_ = nullptr;
369  }
370 
371  bool spi_is_ready() { return this->delegate_->is_ready(); }
372 
373  protected:
375  SPIMode mode_{MODE0};
376  uint32_t data_rate_{1000000};
377  SPIComponent *parent_{nullptr};
378  GPIOPin *cs_{nullptr};
379  SPIDelegate *delegate_{nullptr};
380 };
381 
390 template<SPIBitOrder BIT_ORDER, SPIClockPolarity CLOCK_POLARITY, SPIClockPhase CLOCK_PHASE, SPIDataRate DATA_RATE>
391 class SPIDevice : public SPIClient {
392  public:
393  SPIDevice() : SPIClient(BIT_ORDER, Utility::get_mode(CLOCK_POLARITY, CLOCK_PHASE), DATA_RATE) {}
394 
395  SPIDevice(SPIComponent *parent, GPIOPin *cs_pin) {
396  this->set_spi_parent(parent);
397  this->set_cs_pin(cs_pin);
398  }
399 
400  void spi_setup() override { SPIClient::spi_setup(); }
401 
402  void spi_teardown() override { SPIClient::spi_teardown(); }
403 
404  void set_spi_parent(SPIComponent *parent) { this->parent_ = parent; }
405 
406  void set_cs_pin(GPIOPin *cs) { this->cs_ = cs; }
407 
408  void set_data_rate(uint32_t data_rate) { this->data_rate_ = data_rate; }
409 
410  void set_bit_order(SPIBitOrder order) { this->bit_order_ = order; }
411 
412  void set_mode(SPIMode mode) { this->mode_ = mode; }
413 
414  uint8_t read_byte() { return this->delegate_->transfer(0); }
415 
416  void read_array(uint8_t *data, size_t length) { return this->delegate_->read_array(data, length); }
417 
423  void write(uint16_t data, size_t num_bits) { this->delegate_->write(data, num_bits); };
424 
425  /* Write command, address and data. Command and address will be written as single-bit SPI,
426  * data phase can be multiple bit (currently only 1 or 4)
427  * @param cmd_bits Number of bits to write in the command phase
428  * @param cmd The command value to write
429  * @param addr_bits Number of bits to write in addr phase
430  * @param address Address data
431  * @param data Plain data bytes
432  * @param length Number of data bytes
433  * @param bus_width The number of data lines to use for the data phase.
434  */
435  void write_cmd_addr_data(size_t cmd_bits, uint32_t cmd, size_t addr_bits, uint32_t address, const uint8_t *data,
436  size_t length, uint8_t bus_width = 1) {
437  this->delegate_->write_cmd_addr_data(cmd_bits, cmd, addr_bits, address, data, length, bus_width);
438  }
439 
440  void write_byte(uint8_t data) { this->delegate_->write_array(&data, 1); }
441 
447  void transfer_array(uint8_t *data, size_t length) { this->delegate_->transfer(data, length); }
448 
449  uint8_t transfer_byte(uint8_t data) { return this->delegate_->transfer(data); }
450 
453  void write_byte16(uint16_t data) { this->delegate_->write16(data); }
454 
461  void write_array16(const uint16_t *data, size_t length) { this->delegate_->write_array16(data, length); }
462 
463  void enable() { this->delegate_->begin_transaction(); }
464 
465  void disable() { this->delegate_->end_transaction(); }
466 
467  void write_array(const uint8_t *data, size_t length) { this->delegate_->write_array(data, length); }
468 
469  template<size_t N> void write_array(const std::array<uint8_t, N> &data) { this->write_array(data.data(), N); }
470 
471  void write_array(const std::vector<uint8_t> &data) { this->write_array(data.data(), data.size()); }
472 
473  template<size_t N> void transfer_array(std::array<uint8_t, N> &data) { this->transfer_array(data.data(), N); }
474 };
475 
476 } // namespace spi
477 } // namespace esphome
void write_array16(const uint16_t *data, size_t length)
Write an array of data as 16 bit values, byte-swapping if required.
Definition: spi.h:461
virtual void spi_teardown()
Definition: spi.h:366
void transfer_array(uint8_t *data, size_t length)
Write the array data, replace with received data.
Definition: spi.h:447
const char * name
Definition: stm32flash.h:78
SPIClassRP2040 * SPIInterface
Definition: spi.h:16
virtual void read_array(uint8_t *ptr, size_t length)
Definition: spi.h:238
SPIClockPolarity clock_polarity_
Definition: spi.h:280
SPIDataRate
The SPI clock signal frequency, which determines the transfer bit rate/second.
Definition: spi.h:87
virtual void transfer(uint8_t *ptr, size_t length)
Definition: spi.h:194
void spi_setup() override
Definition: spi.h:400
friend class SPIDelegate
Definition: spi.h:108
The data is sampled on a leading clock edge. (CPHA=0)
Definition: spi.h:66
void set_mosi(GPIOPin *sdo)
Definition: spi.h:321
std::string dump_summary() const override
Definition: spi.h:121
The clock signal idles on HIGH.
Definition: spi.h:58
A pin to replace those that don&#39;t exist.
Definition: spi.h:105
static SPIMode get_mode(SPIClockPolarity polarity, SPIClockPhase phase)
Definition: spi.h:138
std::map< SPIClient *, SPIDelegate * > devices_
Definition: spi.h:346
void pin_mode(gpio::Flags flags) override
Definition: spi.h:115
SPIDelegateBitBash(uint32_t clock, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin, GPIOPin *clk_pin, GPIOPin *sdo_pin, GPIOPin *sdi_pin)
Definition: spi.h:259
The most significant bit is transmitted/received first.
Definition: spi.h:42
virtual bool is_hw()
Definition: spi.h:301
virtual void write(uint16_t data, size_t num_bits)
write a variable length data item, up to 16 bits.
Definition: spi.h:206
void set_cs_pin(GPIOPin *cs)
Definition: spi.h:406
uint8_t transfer_byte(uint8_t data)
Definition: spi.h:449
The clock signal idles on LOW.
Definition: spi.h:53
virtual void setup()=0
void write_array(const std::vector< uint8_t > &data)
Definition: spi.h:471
void write_byte(uint8_t data)
Definition: spi.h:440
bool spi_is_ready()
Definition: spi.h:371
void spi_teardown() override
Definition: spi.h:402
void write_cmd_addr_data(size_t cmd_bits, uint32_t cmd, size_t addr_bits, uint32_t address, const uint8_t *data, size_t length, uint8_t bus_width=1)
Definition: spi.h:435
SPIClockPolarity
The SPI clock signal polarity,.
Definition: spi.h:48
uint8_t read_byte()
Definition: spi.h:414
static int get_pin_no(GPIOPin *pin)
Definition: spi.h:130
The SPIDevice is what components using the SPI will create.
Definition: spi.h:391
bool digital_read() override
Definition: spi.h:117
virtual void spi_setup()
Definition: spi.h:361
void write_array(const std::array< uint8_t, N > &data)
Definition: spi.h:469
void read_array(uint8_t *data, size_t length)
Definition: spi.h:416
const float BUS
For communication buses like i2c/spi.
Definition: component.cpp:16
The data is sampled on a trailing clock edge. (CPHA=1)
Definition: spi.h:68
virtual bool is_internal()
Definition: gpio.h:62
void write(uint16_t data, size_t num_bits)
Write a single data item, up to 32 bits.
Definition: spi.h:423
void setup() override
Definition: spi.h:113
BedjetMode mode
BedJet operating mode.
Definition: bedjet_codec.h:183
virtual void transfer(const uint8_t *txbuf, uint8_t *rxbuf, size_t length)
Definition: spi.h:196
SPIMode
Modes mapping to clock phase and polarity.
Definition: spi.h:76
void set_mode(SPIMode mode)
Definition: spi.h:412
uint32_t arch_get_cpu_freq_hz()
Definition: core.cpp:61
virtual void end_transaction()
Definition: spi.h:188
void set_miso(GPIOPin *sdi)
Definition: spi.h:319
Base class for SPIDevice, un-templated.
Definition: spi.h:356
virtual void begin_transaction()
Definition: spi.h:185
SPIClient(SPIBitOrder bit_order, SPIMode mode, uint32_t data_rate)
Definition: spi.h:358
virtual void write16(uint16_t data)
Definition: spi.h:215
void set_bit_order(SPIBitOrder order)
Definition: spi.h:410
virtual ~SPIDelegate()
Definition: spi.h:182
const uint32_t flags
Definition: stm32flash.h:85
static SPIClockPolarity get_polarity(SPIMode mode)
Definition: spi.h:155
virtual SPIDelegate * get_delegate(uint32_t data_rate, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin)
Definition: spi.h:297
void set_data_pins(std::vector< uint8_t > pins)
Definition: spi.h:322
SPIClockPhase clock_phase_
Definition: spi.h:281
An implementation of SPI that relies only on software toggling of pins.
Definition: spi.h:257
void transfer_array(std::array< uint8_t, N > &data)
Definition: spi.h:473
SPIBitOrder
The bit-order for SPI devices. This defines how the data read from and written to the device is inter...
Definition: spi.h:38
void set_interface(SPIInterface interface)
Definition: spi.h:324
void write_array(const uint8_t *data, size_t length)
Definition: spi.h:467
uint16_t length
Definition: tt21100.cpp:12
SPIDelegate(uint32_t data_rate, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin)
Definition: spi.h:174
virtual void write_array(const uint8_t *ptr, size_t length)
Definition: spi.h:232
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
friend class SPIComponent
Definition: spi.h:106
The least significant bit is transmitted/received first.
Definition: spi.h:40
uint8_t address
Definition: bl0906.h:211
void set_spi_parent(SPIComponent *parent)
Definition: spi.h:404
SPIClockPhase
The SPI clock signal phase.
Definition: spi.h:64
SPIBus(GPIOPin *clk, GPIOPin *sdo, GPIOPin *sdi)
Definition: spi.h:295
void set_interface_name(const char *name)
Definition: spi.h:329
void write_byte16(uint16_t data)
Write 16 bit data.
Definition: spi.h:453
void set_data_rate(uint32_t data_rate)
Definition: spi.h:408
void digital_write(bool value) override
Definition: spi.h:119
void set_clk(GPIOPin *clk)
Definition: spi.h:317
static GPIOPin *const NULL_PIN
Definition: spi.h:124
uint32_t arch_get_cpu_cycle_count()
Definition: core.cpp:57
void write16(uint16_t data) override
Definition: spi.h:272
SPIDevice(SPIComponent *parent, GPIOPin *cs_pin)
Definition: spi.h:395
virtual void write_cmd_addr_data(size_t cmd_bits, uint32_t cmd, size_t addr_bits, uint32_t address, const uint8_t *data, size_t length, uint8_t bus_width)
Definition: spi.h:210
stm32_cmd_t * cmd
Definition: stm32flash.h:96
static SPIClockPhase get_phase(SPIMode mode)
Definition: spi.h:145
virtual void write_array16(const uint16_t *data, size_t length)
Definition: spi.h:225
float get_setup_priority() const override
Definition: spi.h:331