ESPHome  2024.6.1
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 class SPIDelegateDummy;
167 
168 // represents a device attached to an SPI bus, with a defined clock rate, mode and bit order. On Arduino this is
169 // a thin wrapper over SPIClass.
170 class SPIDelegate {
171  friend class SPIClient;
172 
173  public:
174  SPIDelegate() = default;
175 
176  SPIDelegate(uint32_t data_rate, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin)
177  : bit_order_(bit_order), data_rate_(data_rate), mode_(mode), cs_pin_(cs_pin) {
178  if (this->cs_pin_ == nullptr)
179  this->cs_pin_ = NullPin::NULL_PIN;
180  this->cs_pin_->setup();
181  this->cs_pin_->digital_write(true);
182  }
183 
184  virtual ~SPIDelegate(){};
185 
186  // enable CS if configured.
187  virtual void begin_transaction() { this->cs_pin_->digital_write(false); }
188 
189  // end the transaction
190  virtual void end_transaction() { this->cs_pin_->digital_write(true); }
191 
192  // transfer one byte, return the byte that was read.
193  virtual uint8_t transfer(uint8_t data) = 0;
194 
195  // transfer a buffer, replace the contents with read data
196  virtual void transfer(uint8_t *ptr, size_t length) { this->transfer(ptr, ptr, length); }
197 
198  virtual void transfer(const uint8_t *txbuf, uint8_t *rxbuf, size_t length) {
199  for (size_t i = 0; i != length; i++)
200  rxbuf[i] = this->transfer(txbuf[i]);
201  }
202 
208  virtual void write(uint16_t data, size_t num_bits) {
209  esph_log_e("spi_device", "variable length write not implemented");
210  }
211 
212  virtual void write_cmd_addr_data(size_t cmd_bits, uint32_t cmd, size_t addr_bits, uint32_t address,
213  const uint8_t *data, size_t length, uint8_t bus_width) {
214  esph_log_e("spi_device", "write_cmd_addr_data not implemented");
215  }
216  // write 16 bits
217  virtual void write16(uint16_t data) {
218  if (this->bit_order_ == BIT_ORDER_MSB_FIRST) {
219  uint16_t buffer;
220  buffer = (data >> 8) | (data << 8);
221  this->write_array(reinterpret_cast<const uint8_t *>(&buffer), 2);
222  } else {
223  this->write_array(reinterpret_cast<const uint8_t *>(&data), 2);
224  }
225  }
226 
227  virtual void write_array16(const uint16_t *data, size_t length) {
228  for (size_t i = 0; i != length; i++) {
229  this->write16(data[i]);
230  }
231  }
232 
233  // write the contents of a buffer, ignore read data (buffer is unchanged.)
234  virtual void write_array(const uint8_t *ptr, size_t length) {
235  for (size_t i = 0; i != length; i++)
236  this->transfer(ptr[i]);
237  }
238 
239  // read into a buffer, write nulls
240  virtual void read_array(uint8_t *ptr, size_t length) {
241  for (size_t i = 0; i != length; i++)
242  ptr[i] = this->transfer(0);
243  }
244 
245  // check if device is ready
246  virtual bool is_ready();
247 
248  protected:
250  uint32_t data_rate_{1000000};
251  SPIMode mode_{MODE0};
253  static SPIDelegate *const NULL_DELEGATE; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
254 };
255 
261  public:
262  SPIDelegateDummy() = default;
263 
264  uint8_t transfer(uint8_t data) override { return 0; }
265  void end_transaction() override{};
266 
267  void begin_transaction() override;
268 };
269 
275  public:
276  SPIDelegateBitBash(uint32_t clock, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin, GPIOPin *clk_pin,
277  GPIOPin *sdo_pin, GPIOPin *sdi_pin)
278  : SPIDelegate(clock, bit_order, mode, cs_pin), clk_pin_(clk_pin), sdo_pin_(sdo_pin), sdi_pin_(sdi_pin) {
279  // this calculation is pretty meaningless except at very low bit rates.
280  this->wait_cycle_ = uint32_t(arch_get_cpu_freq_hz()) / this->data_rate_ / 2ULL;
281  this->clock_polarity_ = Utility::get_polarity(this->mode_);
282  this->clock_phase_ = Utility::get_phase(this->mode_);
283  }
284 
285  uint8_t transfer(uint8_t data) override;
286 
287  void write(uint16_t data, size_t num_bits) override;
288 
289  void write16(uint16_t data) override { this->write(data, 16); };
290 
291  protected:
292  GPIOPin *clk_pin_;
295  uint32_t last_transition_{0};
296  uint32_t wait_cycle_;
299 
300  void HOT cycle_clock_() {
301  while (this->last_transition_ - arch_get_cpu_cycle_count() < this->wait_cycle_)
302  continue;
303  this->last_transition_ += this->wait_cycle_;
304  }
305  uint16_t transfer_(uint16_t data, size_t num_bits);
306 };
307 
308 class SPIBus {
309  public:
310  SPIBus() = default;
311 
312  SPIBus(GPIOPin *clk, GPIOPin *sdo, GPIOPin *sdi) : clk_pin_(clk), sdo_pin_(sdo), sdi_pin_(sdi) {}
313 
314  virtual SPIDelegate *get_delegate(uint32_t data_rate, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin) {
315  return new SPIDelegateBitBash(data_rate, bit_order, mode, cs_pin, this->clk_pin_, this->sdo_pin_, this->sdi_pin_);
316  }
317 
318  virtual bool is_hw() { return false; }
319 
320  protected:
321  GPIOPin *clk_pin_{};
322  GPIOPin *sdo_pin_{};
323  GPIOPin *sdi_pin_{};
324 };
325 
326 class SPIClient;
327 
328 class SPIComponent : public Component {
329  public:
330  SPIDelegate *register_device(SPIClient *device, SPIMode mode, SPIBitOrder bit_order, uint32_t data_rate,
331  GPIOPin *cs_pin);
332  void unregister_device(SPIClient *device);
333 
334  void set_clk(GPIOPin *clk) { this->clk_pin_ = clk; }
335 
336  void set_miso(GPIOPin *sdi) { this->sdi_pin_ = sdi; }
337 
338  void set_mosi(GPIOPin *sdo) { this->sdo_pin_ = sdo; }
339  void set_data_pins(std::vector<uint8_t> pins) { this->data_pins_ = std::move(pins); }
340 
341  void set_interface(SPIInterface interface) {
342  this->interface_ = interface;
343  this->using_hw_ = true;
344  }
345 
346  void set_interface_name(const char *name) { this->interface_name_ = name; }
347 
348  float get_setup_priority() const override { return setup_priority::BUS; }
349 
350  void setup() override;
351  void dump_config() override;
352 
353  protected:
354  GPIOPin *clk_pin_{nullptr};
355  GPIOPin *sdi_pin_{nullptr};
356  GPIOPin *sdo_pin_{nullptr};
357  std::vector<uint8_t> data_pins_{};
358 
359  SPIInterface interface_{};
360  bool using_hw_{false};
361  const char *interface_name_{nullptr};
362  SPIBus *spi_bus_{};
363  std::map<SPIClient *, SPIDelegate *> devices_;
364 
365  static SPIBus *get_bus(SPIInterface interface, GPIOPin *clk, GPIOPin *sdo, GPIOPin *sdi,
366  const std::vector<uint8_t> &data_pins);
367 };
368 
373 class SPIClient {
374  public:
375  SPIClient(SPIBitOrder bit_order, SPIMode mode, uint32_t data_rate)
376  : bit_order_(bit_order), mode_(mode), data_rate_(data_rate) {}
377 
378  virtual void spi_setup() {
379  esph_log_d("spi_device", "mode %u, data_rate %ukHz", (unsigned) this->mode_, (unsigned) (this->data_rate_ / 1000));
380  this->delegate_ = this->parent_->register_device(this, this->mode_, this->bit_order_, this->data_rate_, this->cs_);
381  }
382 
383  virtual void spi_teardown() {
384  this->parent_->unregister_device(this);
385  this->delegate_ = SPIDelegate::NULL_DELEGATE;
386  }
387 
388  bool spi_is_ready() { return this->delegate_->is_ready(); }
389 
390  protected:
392  SPIMode mode_{MODE0};
393  uint32_t data_rate_{1000000};
394  SPIComponent *parent_{nullptr};
395  GPIOPin *cs_{nullptr};
397 };
398 
407 template<SPIBitOrder BIT_ORDER, SPIClockPolarity CLOCK_POLARITY, SPIClockPhase CLOCK_PHASE, SPIDataRate DATA_RATE>
408 class SPIDevice : public SPIClient {
409  public:
410  SPIDevice() : SPIClient(BIT_ORDER, Utility::get_mode(CLOCK_POLARITY, CLOCK_PHASE), DATA_RATE) {}
411 
412  SPIDevice(SPIComponent *parent, GPIOPin *cs_pin) {
413  this->set_spi_parent(parent);
414  this->set_cs_pin(cs_pin);
415  }
416 
417  void spi_setup() override { SPIClient::spi_setup(); }
418 
419  void spi_teardown() override { SPIClient::spi_teardown(); }
420 
421  void set_spi_parent(SPIComponent *parent) { this->parent_ = parent; }
422 
423  void set_cs_pin(GPIOPin *cs) { this->cs_ = cs; }
424 
425  void set_data_rate(uint32_t data_rate) { this->data_rate_ = data_rate; }
426 
427  void set_bit_order(SPIBitOrder order) { this->bit_order_ = order; }
428 
429  void set_mode(SPIMode mode) { this->mode_ = mode; }
430 
431  uint8_t read_byte() { return this->delegate_->transfer(0); }
432 
433  void read_array(uint8_t *data, size_t length) { return this->delegate_->read_array(data, length); }
434 
440  void write(uint16_t data, size_t num_bits) { this->delegate_->write(data, num_bits); };
441 
442  /* Write command, address and data. Command and address will be written as single-bit SPI,
443  * data phase can be multiple bit (currently only 1 or 4)
444  * @param cmd_bits Number of bits to write in the command phase
445  * @param cmd The command value to write
446  * @param addr_bits Number of bits to write in addr phase
447  * @param address Address data
448  * @param data Plain data bytes
449  * @param length Number of data bytes
450  * @param bus_width The number of data lines to use for the data phase.
451  */
452  void write_cmd_addr_data(size_t cmd_bits, uint32_t cmd, size_t addr_bits, uint32_t address, const uint8_t *data,
453  size_t length, uint8_t bus_width = 1) {
454  this->delegate_->write_cmd_addr_data(cmd_bits, cmd, addr_bits, address, data, length, bus_width);
455  }
456 
457  void write_byte(uint8_t data) { this->delegate_->write_array(&data, 1); }
458 
464  void transfer_array(uint8_t *data, size_t length) { this->delegate_->transfer(data, length); }
465 
466  uint8_t transfer_byte(uint8_t data) { return this->delegate_->transfer(data); }
467 
470  void write_byte16(uint16_t data) { this->delegate_->write16(data); }
471 
478  void write_array16(const uint16_t *data, size_t length) { this->delegate_->write_array16(data, length); }
479 
480  void enable() { this->delegate_->begin_transaction(); }
481 
482  void disable() { this->delegate_->end_transaction(); }
483 
484  void write_array(const uint8_t *data, size_t length) { this->delegate_->write_array(data, length); }
485 
486  template<size_t N> void write_array(const std::array<uint8_t, N> &data) { this->write_array(data.data(), N); }
487 
488  void write_array(const std::vector<uint8_t> &data) { this->write_array(data.data(), data.size()); }
489 
490  template<size_t N> void transfer_array(std::array<uint8_t, N> &data) { this->transfer_array(data.data(), N); }
491 };
492 
493 } // namespace spi
494 } // 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:478
virtual void spi_teardown()
Definition: spi.h:383
void transfer_array(uint8_t *data, size_t length)
Write the array data, replace with received data.
Definition: spi.h:464
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:240
SPIClockPolarity clock_polarity_
Definition: spi.h:297
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:196
void spi_setup() override
Definition: spi.h:417
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:338
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:363
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:276
The most significant bit is transmitted/received first.
Definition: spi.h:42
virtual bool is_hw()
Definition: spi.h:318
virtual void write(uint16_t data, size_t num_bits)
write a variable length data item, up to 16 bits.
Definition: spi.h:208
void set_cs_pin(GPIOPin *cs)
Definition: spi.h:423
void end_transaction() override
Definition: spi.h:265
uint8_t transfer_byte(uint8_t data)
Definition: spi.h:466
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:488
void write_byte(uint8_t data)
Definition: spi.h:457
bool spi_is_ready()
Definition: spi.h:388
void spi_teardown() override
Definition: spi.h:419
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:452
SPIClockPolarity
The SPI clock signal polarity,.
Definition: spi.h:48
uint8_t read_byte()
Definition: spi.h:431
static int get_pin_no(GPIOPin *pin)
Definition: spi.h:130
The SPIDevice is what components using the SPI will create.
Definition: spi.h:408
bool digital_read() override
Definition: spi.h:117
virtual void spi_setup()
Definition: spi.h:378
void write_array(const std::array< uint8_t, N > &data)
Definition: spi.h:486
void read_array(uint8_t *data, size_t length)
Definition: spi.h:433
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:440
void setup() override
Definition: spi.h:113
BedjetMode mode
BedJet operating mode.
Definition: bedjet_codec.h:181
virtual void transfer(const uint8_t *txbuf, uint8_t *rxbuf, size_t length)
Definition: spi.h:198
SPIMode
Modes mapping to clock phase and polarity.
Definition: spi.h:76
void set_mode(SPIMode mode)
Definition: spi.h:429
uint32_t arch_get_cpu_freq_hz()
Definition: core.cpp:61
uint8_t transfer(uint8_t data) override
Definition: spi.h:264
virtual void end_transaction()
Definition: spi.h:190
void set_miso(GPIOPin *sdi)
Definition: spi.h:336
Base class for SPIDevice, un-templated.
Definition: spi.h:373
virtual void begin_transaction()
Definition: spi.h:187
SPIClient(SPIBitOrder bit_order, SPIMode mode, uint32_t data_rate)
Definition: spi.h:375
virtual void write16(uint16_t data)
Definition: spi.h:217
void set_bit_order(SPIBitOrder order)
Definition: spi.h:427
virtual ~SPIDelegate()
Definition: spi.h:184
const uint32_t flags
Definition: stm32flash.h:85
static SPIClockPolarity get_polarity(SPIMode mode)
Definition: spi.h:155
static SPIDelegate *const NULL_DELEGATE
Definition: spi.h:253
virtual SPIDelegate * get_delegate(uint32_t data_rate, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin)
Definition: spi.h:314
void set_data_pins(std::vector< uint8_t > pins)
Definition: spi.h:339
SPIClockPhase clock_phase_
Definition: spi.h:298
An implementation of SPI that relies only on software toggling of pins.
Definition: spi.h:274
void transfer_array(std::array< uint8_t, N > &data)
Definition: spi.h:490
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:341
A dummy SPIDelegate that complains if it&#39;s used.
Definition: spi.h:260
void write_array(const uint8_t *data, size_t length)
Definition: spi.h:484
uint16_t length
Definition: tt21100.cpp:12
SPIDelegate(uint32_t data_rate, SPIBitOrder bit_order, SPIMode mode, GPIOPin *cs_pin)
Definition: spi.h:176
virtual void write_array(const uint8_t *ptr, size_t length)
Definition: spi.h:234
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
friend class SPIComponent
Definition: spi.h:106
The least significant bit is transmitted/received first.
Definition: spi.h:40
void set_spi_parent(SPIComponent *parent)
Definition: spi.h:421
SPIClockPhase
The SPI clock signal phase.
Definition: spi.h:64
SPIBus(GPIOPin *clk, GPIOPin *sdo, GPIOPin *sdi)
Definition: spi.h:312
void set_interface_name(const char *name)
Definition: spi.h:346
void write_byte16(uint16_t data)
Write 16 bit data.
Definition: spi.h:470
void set_data_rate(uint32_t data_rate)
Definition: spi.h:425
void digital_write(bool value) override
Definition: spi.h:119
void set_clk(GPIOPin *clk)
Definition: spi.h:334
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:289
SPIDevice(SPIComponent *parent, GPIOPin *cs_pin)
Definition: spi.h:412
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:212
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:227
float get_setup_priority() const override
Definition: spi.h:348