spi_master.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. SPI Master driver
  2. =================
  3. Overview
  4. --------
  5. The ESP32 has four SPI peripheral devices, called SPI0, SPI1, HSPI and VSPI. SPI0 is entirely dedicated to
  6. the flash cache the ESP32 uses to map the SPI flash device it is connected to into memory. SPI1 is
  7. connected to the same hardware lines as SPI0 and is used to write to the flash chip. HSPI and VSPI
  8. are free to use. SPI1, HSPI and VSPI all have three chip select lines, allowing them to drive up to
  9. three SPI devices each as a master.
  10. The spi_master driver
  11. ^^^^^^^^^^^^^^^^^^^^^
  12. The spi_master driver allows easy communicating with SPI slave devices, even in a multithreaded environment.
  13. It fully transparently handles DMA transfers to read and write data and automatically takes care of
  14. multiplexing between different SPI slaves on the same master
  15. Terminology
  16. ^^^^^^^^^^^
  17. The spi_master driver uses the following terms:
  18. * Host: The SPI peripheral inside the ESP32 initiating the SPI transmissions. One of SPI, HSPI or VSPI. (For
  19. now, only HSPI or VSPI are actually supported in the driver; it will support all 3 peripherals
  20. somewhere in the future.)
  21. * Bus: The SPI bus, common to all SPI devices connected to one host. In general the bus consists of the
  22. miso, mosi, sclk and optionally quadwp and quadhd signals. The SPI slaves are connected to these
  23. signals in parallel.
  24. - miso - Also known as q, this is the input of the serial stream into the ESP32
  25. - mosi - Also known as d, this is the output of the serial stream from the ESP32
  26. - sclk - Clock signal. Each data bit is clocked out or in on the positive or negative edge of this signal
  27. - quadwp - Write Protect signal. Only used for 4-bit (qio/qout) transactions.
  28. - quadhd - Hold signal. Only used for 4-bit (qio/qout) transactions.
  29. * Device: A SPI slave. Each SPI slave has its own chip select (CS) line, which is made active when
  30. a transmission to/from the SPI slave occurs.
  31. * Transaction: One instance of CS going active, data transfer from and/or to a device happening, and
  32. CS going inactive again. Transactions are atomic, as in they will never be interrupted by another
  33. transaction.
  34. SPI transactions
  35. ^^^^^^^^^^^^^^^^
  36. A transaction on the SPI bus consists of five phases, any of which may be skipped:
  37. * The command phase. In this phase, a command (0-16 bit) is clocked out.
  38. * The address phase. In this phase, an address (0-64 bit) is clocked out.
  39. * The write phase. The master sends data to the slave.
  40. * The dummy phase. The phase is configurable, used to meet the timing requirements.
  41. * The read phase. The slave sends data to the master.
  42. In full duplex mode, the read and write phases are combined, and the SPI host reads and
  43. writes data simultaneously. The total transaction length is decided by
  44. ``command_bits + address_bits + trans_conf.length``, while the ``trans_conf.rx_length``
  45. only determins length of data received into the buffer.
  46. While in half duplex mode, the host have independent write and read phases. The length of write phase and read phase are
  47. decided by ``trans_conf.length`` and ``trans_conf.rx_length`` respectively.
  48. The command and address phase are optional in that not every SPI device will need to be sent a command
  49. and/or address. This is reflected in the device configuration: when the ``command_bits`` or ``address_bits``
  50. fields are set to zero, no command or address phase is done.
  51. Something similar is true for the read and write phase: not every transaction needs both data to be written
  52. as well as data to be read. When ``rx_buffer`` is NULL (and SPI_USE_RXDATA) is not set) the read phase
  53. is skipped. When ``tx_buffer`` is NULL (and SPI_USE_TXDATA) is not set) the write phase is skipped.
  54. GPIO matrix and native pins
  55. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  56. Most peripheral pins in ESP32 can directly connect to a GPIO, which is called *native pin*. When the peripherals are
  57. required to work with other pins than the native pins, ESP32 use a *GPIO matrix* to realize this. If one of the pins is
  58. not native, the driver automatically routes all the signals to the GPIO matrix, which works under 80MHz. The signals are
  59. sampled and sent to peripherals or the GPIOs.
  60. When the GPIO matrix is used, signals cannot propogate to the peripherals over 40MHz, and the setup time of MISO is very
  61. likely violated. Hence the clock frequency limitation is a little lower than the case without GPIO matrix.
  62. Native pins for SPI controllers are as below:
  63. +----------+------+------+
  64. | Pin Name | HSPI | VSPI |
  65. + +------+------+
  66. | | GPIO Number |
  67. +==========+======+======+
  68. | CS0* | 15 | 5 |
  69. +----------+------+------+
  70. | SCLK | 14 | 18 |
  71. +----------+------+------+
  72. | MISO | 12 | 19 |
  73. +----------+------+------+
  74. | MOSI | 13 | 23 |
  75. +----------+------+------+
  76. | QUADWP | 2 | 22 |
  77. +----------+------+------+
  78. | QUADHD | 4 | 21 |
  79. +----------+------+------+
  80. note * Only the first device attaching to the bus can use CS0 pin.
  81. Using the spi_master driver
  82. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  83. - Initialize a SPI bus by calling ``spi_bus_initialize``. Make sure to set the correct IO pins in
  84. the ``bus_config`` struct. Take care to set signals that are not needed to -1.
  85. - Tell the driver about a SPI slave device connected to the bus by calling spi_bus_add_device.
  86. Make sure to configure any timing requirements the device has in the ``dev_config`` structure.
  87. You should now have a handle for the device, to be used when sending it a transaction.
  88. - To interact with the device, fill one or more spi_transaction_t structure with any transaction
  89. parameters you need. Either queue all transactions by calling ``spi_device_queue_trans``, later
  90. quering the result using ``spi_device_get_trans_result``, or handle all requests synchroneously
  91. by feeding them into ``spi_device_transmit``.
  92. - Optional: to unload the driver for a device, call ``spi_bus_remove_device`` with the device
  93. handle as an argument
  94. - Optional: to remove the driver for a bus, make sure no more drivers are attached and call
  95. ``spi_bus_free``.
  96. Command and address phases
  97. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  98. During the command and address phases, ``cmd`` and ``addr`` field in the
  99. ``spi_transaction_t`` struct are sent to the bus, while nothing is read at the
  100. same time. The default length of command and address phase are set in the
  101. ``spi_device_interface_config_t`` and by ``spi_bus_add_device``. When the the
  102. flag ``SPI_TRANS_VARIABLE_CMD`` and ``SPI_TRANS_VARIABLE_ADDR`` are not set in
  103. the ``spi_transaction_t``,the driver automatically set the length of these
  104. phases to the default value as set when the device is initialized respectively.
  105. If the length of command and address phases needs to be variable, declare a
  106. ``spi_transaction_ext_t`` descriptor, set the flag ``SPI_TRANS_VARIABLE_CMD``
  107. or/and ``SPI_TRANS_VARIABLE_ADDR`` in the ``flags`` of ``base`` member and
  108. configure the rest part of ``base`` as usual. Then the length of each phases
  109. will be ``command_bits`` and ``address_bits`` set in the ``spi_transaction_ext_t``.
  110. Write and read phases
  111. ^^^^^^^^^^^^^^^^^^^^^
  112. Normally, data to be transferred to or from a device will be read from or written to a chunk of memory
  113. indicated by the ``rx_buffer`` and ``tx_buffer`` members of the transaction structure.
  114. When DMA is enabled for transfers, these buffers are highly recommended to meet the requirements as below:
  115. 1. allocated in DMA-capable memory using ``pvPortMallocCaps(size, MALLOC_CAP_DMA)``;
  116. 2. 32-bit aligned (start from the boundary and have length of multiples of 4 bytes).
  117. If these requirements are not satisfied, efficiency of the transaction will suffer due to the allocation and
  118. memcpy of temporary buffers.
  119. .. note:: Half duplex transactions with both read and write phases are not supported when using DMA. See
  120. :ref:`spi_known_issues` for details and workarounds.
  121. Sometimes, the amount of data is very small making it less than optimal allocating a separate buffer
  122. for it. If the data to be transferred is 32 bits or less, it can be stored in the transaction struct
  123. itself. For transmitted data, use the ``tx_data`` member for this and set the ``SPI_USE_TXDATA`` flag
  124. on the transmission. For received data, use ``rx_data`` and set ``SPI_USE_RXDATA``. In both cases, do
  125. not touch the ``tx_buffer`` or ``rx_buffer`` members, because they use the same memory locations
  126. as ``tx_data`` and ``rx_data``.
  127. Speed and Timing Considerations
  128. -------------------------------
  129. Transferring speed
  130. ^^^^^^^^^^^^^^^^^^
  131. There're two factors limiting the transferring speed: (1) The transaction interval, (2) The SPI clock frequency used.
  132. When large transactions are used, the clock frequency determines the transferring speed; while the interval effects the
  133. speed a lot if small transactions are used.
  134. 1. Transaction interval: The interval mainly comes from the cost of FreeRTOS queues and the time switching between
  135. tasks and the ISR. It also takes time for the software to setup spi peripheral registers as well as copy data to
  136. FIFOs, or setup DMA links. Depending on whether the DMA is used, the interval of an one-byte transaction is around
  137. 25us typically.
  138. 1. The CPU is blocked and switched to other tasks when the
  139. transaction is in flight. This save the cpu time but increase the interval.
  140. 2. When the DMA is enabled, it needs about 2us per transaction to setup the linked list. When the master is
  141. transferring, it automatically read data from the linked list. If the DMA is not enabled,
  142. CPU has to write/read each byte to/from the FIFO by itself. Usually this is faster than 2us, but the
  143. transaction length is limited to 32 bytes for both write and read.
  144. Typical transaction interval with one byte data is as below:
  145. +-----------------------+---------+
  146. | Transaction Time (us) | Typical |
  147. +=======================+=========+
  148. | DMA | 24 |
  149. +-----------------------+---------+
  150. | No DMA | 22 |
  151. +-----------------------+---------+
  152. 2. SPI clock frequency: Each byte transferred takes 8 times of the clock period *8/fspi*. If the clock frequency is
  153. too high, some functions may be limited to use. See :ref:`timing_considerations`.
  154. For a normal transaction, the overall cost is *20+8n/Fspi[MHz]* [us] for n bytes tranferred
  155. in one transaction. Hence the transferring speed is : *n/(20+8n/Fspi)*. Example of transferring speed under 8MHz
  156. clock speed:
  157. +-----------+----------------------+--------------------+------------+-------------+
  158. | Frequency | Transaction Interval | Transaction Length | Total Time | Total Speed |
  159. | | | | | |
  160. | [MHz] | [us] | [bytes] | [us] | [kBps] |
  161. +===========+======================+====================+============+=============+
  162. | 8 | 25 | 1 | 26 | 38.5 |
  163. +-----------+----------------------+--------------------+------------+-------------+
  164. | 8 | 25 | 8 | 33 | 242.4 |
  165. +-----------+----------------------+--------------------+------------+-------------+
  166. | 8 | 25 | 16 | 41 | 490.2 |
  167. +-----------+----------------------+--------------------+------------+-------------+
  168. | 8 | 25 | 64 | 89 | 719.1 |
  169. +-----------+----------------------+--------------------+------------+-------------+
  170. | 8 | 25 | 128 | 153 | 836.6 |
  171. +-----------+----------------------+--------------------+------------+-------------+
  172. When the length of transaction is short, the cost of transaction interval is really high. Please try to squash data
  173. into one transaction if possible to get higher transfer speed.
  174. .. _timing_considerations:
  175. Timing considerations
  176. ^^^^^^^^^^^^^^^^^^^^^
  177. Due to the input delay of MISO pin, ESP32 SPI master cannot read data at very high speed. The frequency allowed is
  178. rather low when the GPIO matrix is used. Currently only frequency not greater than 8.8MHz is fully supported. When the
  179. frequency is higher, you have to use the native pins or the *dummy bit workaround*.
  180. .. _dummy_bit_workaround:
  181. **Dummy bit workaround:** We can insert dummy clocks (during which the host does not read data) before the read phase
  182. actually begins. The slave still sees the dummy clocks and gives out data, but the host does not read until the read
  183. phase. This compensates the lack of setup time of MISO required by the host, allowing the host reading at higher
  184. frequency.
  185. The maximum frequency (in MHz) host can read (or read and write) under different conditions is as below:
  186. +-------------+-------------+-----------+-----------------------------+
  187. | Frequency Limit | Dummy Bits| Comments |
  188. +-------------+-------------+ Used + +
  189. | GPIO matrix | Native pins | By Driver | |
  190. +=============+=============+===========+=============================+
  191. | 8.8 | N.M. | 0 | |
  192. +-------------+-------------+-----------+-----------------------------+
  193. | N.M. | N.M. | 1 | Half Duplex, no DMA allowed |
  194. +-------------+-------------+-----------+ +
  195. | N.M. | N.M. | 2 | |
  196. +-------------+-------------+-----------+-----------------------------+
  197. N.M.: Not Measured Yet.
  198. And if the host only writes, the *dummy bit workaround* is not used and the frequency limit is as below:
  199. +-------------+----------------------+
  200. | GPIO matrix | Native pins |
  201. +=============+======================+
  202. | 40 | 80 |
  203. +-------------+----------------------+
  204. Thread Safety
  205. -------------
  206. The SPI driver API is thread safe when multiple SPI devices on the same bus are accessed from different tasks. However, the driver is not thread safe if the same SPI device is accessed from multiple tasks.
  207. In this case, it is recommended to either refactor your application so only a single task accesses each SPI device, or to add mutex locking around access of the shared device.
  208. .. _spi_known_issues:
  209. Known Issues
  210. ------------
  211. 1. Half duplex mode is not compatible with DMA when both writing and reading phases exist.
  212. If such transactions are required, you have to use one of the alternative solutions:
  213. 1. use full-duplex mode instead.
  214. 2. disable the DMA by setting the last parameter to 0 in bus initialization function just as below:
  215. ``ret=spi_bus_initialize(VSPI_HOST, &buscfg, 0);``
  216. this may prohibit you from transmitting and receiving data longer than 32 bytes.
  217. 3. try to use command and address field to replace the write phase.
  218. 2. Full duplex mode is not compatible with the *dummy bit workaround*, hence the frequency is limited. See :ref:`dummy
  219. bit speed-up workaround <dummy_bit_workaround>`.
  220. Application Example
  221. -------------------
  222. Display graphics on the 320x240 LCD of WROVER-Kits: :example:`peripherals/spi_master`.
  223. API Reference - SPI Common
  224. --------------------------
  225. .. include:: /_build/inc/spi_common.inc
  226. API Reference - SPI Master
  227. --------------------------
  228. .. include:: /_build/inc/spi_master.inc