spi_master.rst 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. SPI Master Driver
  2. =================
  3. :link_to_translation:`zh_CN:[中文]`
  4. SPI Master driver is a program that controls {IDF_TARGET_NAME}'s General Purpose SPI (GP-SPI) peripheral(s) when it functions as a master.
  5. .. only:: esp32
  6. .. note::
  7. SPI1 is not a GP-SPI. SPI Master driver also supports SPI1 but with quite a few limitations, see :ref:`spi_master_on_spi1_bus`.
  8. For more hardware information about the GP-SPI peripheral(s), see **{IDF_TARGET_NAME} Technical Reference Manual** > **SPI Controller** [`PDF <{IDF_TARGET_TRM_EN_URL}#spi>`__].
  9. Terminology
  10. -----------
  11. The terms used in relation to the SPI Master driver are given in the table below.
  12. .. list-table::
  13. :widths: 30 70
  14. :header-rows: 1
  15. * - Term
  16. - Definition
  17. * - Host
  18. - The SPI controller peripheral inside {IDF_TARGET_NAME} initiates SPI transmissions over the bus and acts as an SPI Master.
  19. * - Device
  20. - SPI slave Device. An SPI bus may be connected to one or more Devices. Each Device shares the MOSI, MISO, and SCLK signals but is only active on the bus when the Host asserts the Device's individual CS line.
  21. * - Bus
  22. - A signal bus, common to all Devices connected to one Host. In general, a bus includes the following lines: MISO, MOSI, SCLK, one or more CS lines, and, optionally, QUADWP and QUADHD. So Devices are connected to the same lines, with the exception that each Device has its own CS line. Several Devices can also share one CS line if connected in a daisy-chain manner.
  23. * - MOSI
  24. - Master Out, Slave In, a.k.a. D. Data transmission from a Host to Device. Also data0 signal in Octal/OPI mode.
  25. * - MISO
  26. - Master In, Slave Out, a.k.a. Q. Data transmission from a Device to Host. Also data1 signal in Octal/OPI mode.
  27. * - SCLK
  28. - Serial Clock. The oscillating signal generated by a Host keeps the transmission of data bits in sync.
  29. * - CS
  30. - Chip Select. Allows a Host to select individual Device(s) connected to the bus in order to send or receive data.
  31. * - QUADWP
  32. - Write Protect signal. Used for 4-bit (qio/qout) transactions. Also for the data2 signal in Octal/OPI mode.
  33. * - QUADHD
  34. - Hold signal. Used for 4-bit (qio/qout) transactions. Also for the data3 signal in Octal/OPI mode.
  35. * - DATA4
  36. - Data4 signal in Octal/OPI mode.
  37. * - DATA5
  38. - Data5 signal in Octal/OPI mode.
  39. * - DATA6
  40. - Data6 signal in Octal/OPI mode.
  41. * - DATA7
  42. - Data7 signal in Octal/OPI mode.
  43. * - Assertion
  44. - The action of activating a line.
  45. * - De-assertion
  46. - The action of returning the line back to inactive (back to idle) status.
  47. * - Transaction
  48. - One instance of a Host asserting a CS line, transferring data to and from a Device, and de-asserting the CS line. Transactions are atomic, which means they can never be interrupted by another transaction.
  49. * - Launch Edge
  50. - Edge of the clock at which the source register **launches** the signal onto the line.
  51. * - Latch Edge
  52. - Edge of the clock at which the destination register **latches in** the signal.
  53. Driver Features
  54. ---------------
  55. The SPI Master driver governs the communications between Hosts and Devices. The driver supports the following features:
  56. - Multi-threaded environments
  57. - Transparent handling of DMA transfers while reading and writing data
  58. - Automatic time-division multiplexing of data coming from different Devices on the same signal bus, see :ref:`spi_bus_lock`.
  59. .. warning::
  60. The SPI Master driver allows multiple Devices to be connected on a same SPI bus (sharing a single {IDF_TARGET_NAME} SPI peripheral). As long as each Device is accessed by only one task, the driver is thread-safe. However, if multiple tasks try to access the same SPI Device, the driver is **not thread-safe**. In this case, it is recommended to either:
  61. - Refactor your application so that each SPI peripheral is only accessed by a single task at a time. You can use :cpp:member:`spi_bus_config_t::isr_cpu_id` to register the SPI ISR to the same core as SPI peripheral-related tasks to ensure thread safety.
  62. - Add a mutex lock around the shared Device using :c:macro:`xSemaphoreCreateMutex`.
  63. .. toctree::
  64. :hidden:
  65. SPI Features <spi_features>
  66. SPI Transactions
  67. ----------------
  68. An SPI bus transaction consists of five phases which can be found in the table below. Any of these phases can be skipped.
  69. {IDF_TARGET_ADDR_LEN:default="32", esp32="64"}
  70. .. list-table::
  71. :widths: 30 70
  72. :header-rows: 1
  73. * - Phase
  74. - Description
  75. * - Command
  76. - In this phase, a command (0-16 bit) is written to the bus by the Host.
  77. * - Address
  78. - In this phase, an address (0-{IDF_TARGET_ADDR_LEN} bit) is transmitted over the bus by the Host.
  79. * - Dummy
  80. - This phase is configurable and is used to meet the timing requirements.
  81. * - Write
  82. - Host sends data to a Device. This data follows the optional command and address phases and is indistinguishable from them at the electrical level.
  83. * - Read
  84. - Device sends data to its Host.
  85. .. todo::
  86. Add a package diagram.
  87. The attributes of a transaction are determined by the bus configuration structure :cpp:type:`spi_bus_config_t`, Device configuration structure :cpp:type:`spi_device_interface_config_t`, and transaction configuration structure :cpp:type:`spi_transaction_t`.
  88. An SPI Host can send full-duplex transactions, during which the Read and Write phases occur simultaneously. The total transaction length is determined by the sum of the following members:
  89. - :cpp:member:`spi_device_interface_config_t::command_bits`
  90. - :cpp:member:`spi_device_interface_config_t::address_bits`
  91. - :cpp:member:`spi_transaction_t::length`
  92. While the member :cpp:member:`spi_transaction_t::rxlength` only determines the length of data received into the buffer.
  93. In half-duplex transactions, the Read and Write phases are not simultaneous (one direction at a time). The lengths of the Write and Read phases are determined by :cpp:member:`spi_transaction_t::length` and :cpp:member:`spi_transaction_t::rxlength` respectively.
  94. The Command and Address phases are optional, as not every SPI Device requires a command and/or address. This is reflected in the Device's configuration: if :cpp:member:`spi_device_interface_config_t::command_bits` and/or :cpp:member:`spi_device_interface_config_t::address_bits` are set to zero, no Command or Address phase will occur.
  95. The Read and Write phases can also be optional, as not every transaction requires both writing and reading data. If :cpp:member:`spi_transaction_t::rx_buffer` is ``NULL`` and :c:macro:`SPI_TRANS_USE_RXDATA` is not set, the Read phase is skipped. If :cpp:member:`spi_transaction_t::tx_buffer` is ``NULL`` and :c:macro:`SPI_TRANS_USE_TXDATA` is not set, the Write phase is skipped.
  96. The driver supports two types of transactions: interrupt transactions and polling transactions. The programmer can choose to use a different transaction type per Device. If your Device requires both transaction types, see :ref:`mixed_transactions`.
  97. .. _interrupt_transactions:
  98. Interrupt Transactions
  99. ^^^^^^^^^^^^^^^^^^^^^^
  100. Interrupt transactions blocks the transaction routine until the transaction completes, thus allowing the CPU to run other tasks.
  101. An application task can queue multiple transactions, and the driver automatically handles them one by one in the interrupt service routine (ISR). It allows the task to switch to other procedures until all the transactions are complete.
  102. .. _polling_transactions:
  103. Polling Transactions
  104. ^^^^^^^^^^^^^^^^^^^^
  105. Polling transactions do not use interrupts. The routine keeps polling the SPI Host's status bit until the transaction is finished.
  106. All the tasks that use interrupt transactions can be blocked by the queue. At this point, they need to wait for the ISR to run twice before the transaction is finished. Polling transactions save time otherwise spent on queue handling and context switching, which results in smaller transaction duration. The disadvantage is that the CPU is busy while these transactions are in progress.
  107. The :cpp:func:`spi_device_polling_end` routine needs an overhead of at least 1 µs to unblock other tasks when the transaction is finished. It is strongly recommended to wrap a series of polling transactions using the functions :cpp:func:`spi_device_acquire_bus` and :cpp:func:`spi_device_release_bus` to avoid the overhead. For more information, see :ref:`bus_acquiring`.
  108. .. _transaction-line-mode:
  109. Transaction Line Mode
  110. ^^^^^^^^^^^^^^^^^^^^^
  111. Supported line modes for {IDF_TARGET_NAME} are listed as follows, to make use of these modes, set the member ``flags`` in the struct :cpp:type:`spi_transaction_t` as shown in the ``Transaction Flag`` column. If you want to check if corresponding IO pins are set or not, set the member ``flags`` in the :cpp:type:`spi_bus_config_t` as shown in the ``Bus IO setting Flag`` column.
  112. .. only:: not SOC_SPI_SUPPORT_OCT
  113. .. list-table::
  114. :widths: 30 40 40 40 50 50
  115. :header-rows: 1
  116. * - Mode name
  117. - Command Line Width
  118. - Address Line Width
  119. - Data Line Width
  120. - Transaction Flag
  121. - Bus IO Setting Flag
  122. * - Normal SPI
  123. - 1
  124. - 1
  125. - 1
  126. - 0
  127. - 0
  128. * - Dual Output
  129. - 1
  130. - 1
  131. - 2
  132. - SPI_TRANS_MODE_DIO
  133. - SPICOMMON_BUSFLAG_DUAL
  134. * - Dual I/O
  135. - 1
  136. - 2
  137. - 2
  138. - SPI_TRANS_MODE_DIO
  139. SPI_TRANS_MULTILINE_ADDR
  140. - SPICOMMON_BUSFLAG_DUAL
  141. * - Quad Output
  142. - 1
  143. - 1
  144. - 4
  145. - SPI_TRANS_MODE_QIO
  146. - SPICOMMON_BUSFLAG_QUAD
  147. * - Quad I/O
  148. - 1
  149. - 4
  150. - 4
  151. - SPI_TRANS_MODE_QIO
  152. SPI_TRANS_MULTILINE_ADDR
  153. - SPICOMMON_BUSFLAG_QUAD
  154. .. only:: SOC_SPI_SUPPORT_OCT
  155. .. list-table::
  156. :widths: 30 40 40 40 50 50
  157. :header-rows: 1
  158. * - Mode name
  159. - Command Line Width
  160. - Address Line Width
  161. - Data Line Width
  162. - Transaction Flag
  163. - Bus IO Setting Flag
  164. * - Normal SPI
  165. - 1
  166. - 1
  167. - 1
  168. - 0
  169. - 0
  170. * - Dual Output
  171. - 1
  172. - 1
  173. - 2
  174. - SPI_TRANS_MODE_DIO
  175. - SPICOMMON_BUSFLAG_DUAL
  176. * - Dual I/O
  177. - 1
  178. - 2
  179. - 2
  180. - SPI_TRANS_MODE_DIO
  181. SPI_TRANS_MULTILINE_ADDR
  182. - SPICOMMON_BUSFLAG_DUAL
  183. * - Quad Output
  184. - 1
  185. - 1
  186. - 4
  187. - SPI_TRANS_MODE_QIO
  188. - SPICOMMON_BUSFLAG_QUAD
  189. * - Quad I/O
  190. - 1
  191. - 4
  192. - 4
  193. - SPI_TRANS_MODE_QIO
  194. SPI_TRANS_MULTILINE_ADDR
  195. - SPICOMMON_BUSFLAG_QUAD
  196. * - Octal Output
  197. - 1
  198. - 1
  199. - 8
  200. - SPI_TRANS_MODE_OCT
  201. - SPICOMMON_BUSFLAG_OCTAL
  202. * - OPI
  203. - 8
  204. - 8
  205. - 8
  206. - SPI_TRANS_MODE_OCT
  207. SPI_TRANS_MULTILINE_ADDR
  208. SPI_TRANS_MULTILINE_CMD
  209. - SPICOMMON_BUSFLAG_OCTAL
  210. Command and Address Phases
  211. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  212. During the Command and Address phases, the members :cpp:member:`spi_transaction_t::cmd` and :cpp:member:`spi_transaction_t::addr` are sent to the bus, nothing is read at this time. The default lengths of the Command and Address phases are set in :cpp:type:`spi_device_interface_config_t` by calling :cpp:func:`spi_bus_add_device`. If the flags :c:macro:`SPI_TRANS_VARIABLE_CMD` and :c:macro:`SPI_TRANS_VARIABLE_ADDR` in the member :cpp:member:`spi_transaction_t::flags` are not set, the driver automatically sets the length of these phases to default values during Device initialization.
  213. If the lengths of the Command and Address phases need to be variable, declare the struct :cpp:type:`spi_transaction_ext_t`, set the flags :c:macro:`SPI_TRANS_VARIABLE_CMD` and/or :c:macro:`SPI_TRANS_VARIABLE_ADDR` in the member :cpp:member:`spi_transaction_ext_t::base` and configure the rest of base as usual. Then the length of each phase will be equal to :cpp:member:`spi_transaction_ext_t::command_bits` and :cpp:member:`spi_transaction_ext_t::address_bits` set in the struct :cpp:type:`spi_transaction_ext_t`.
  214. If the Command and Address phase need to have the same number of lines as the data phase, you need to set ``SPI_TRANS_MULTILINE_CMD`` and/or ``SPI_TRANS_MULTILINE_ADDR`` to the ``flags`` member in the struct :cpp:type:`spi_transaction_t`. Also see :ref:`transaction-line-mode`.
  215. Write and Read Phases
  216. ^^^^^^^^^^^^^^^^^^^^^
  217. Normally, the data that needs to be transferred to or from a Device is read from or written to a chunk of memory indicated by the members :cpp:member:`spi_transaction_t::rx_buffer` and :cpp:member:`spi_transaction_t::tx_buffer`. If DMA is enabled for transfers, the buffers are required to be:
  218. 1. Allocated in DMA-capable internal memory (MALLOC_CAP_DMA), see :ref:`DMA-Capable Memory <dma-capable-memory>`.
  219. 2. 32-bit aligned (starting from a 32-bit boundary and having a length of multiples of 4 bytes).
  220. If these requirements are not satisfied, the transaction efficiency will be affected due to the allocation and copying of temporary buffers.
  221. If using more than one data line to transmit, please set ``SPI_DEVICE_HALFDUPLEX`` flag for the member ``flags`` in the struct :cpp:type:`spi_device_interface_config_t`. And the member ``flags`` in the struct :cpp:type:`spi_transaction_t` should be set as described in :ref:`transaction-line-mode`.
  222. .. only:: esp32
  223. .. note::
  224. Half-duplex transactions with both Read and Write phases are not supported when using DMA. For details and workarounds, see :ref:`spi_known_issues`.
  225. .. only:: not SOC_SPI_HD_BOTH_INOUT_SUPPORTED
  226. .. note::
  227. Half-duplex transactions with both Read and Write phases are not supported. Please use full duplex mode.
  228. .. _bus_acquiring:
  229. Bus Acquiring
  230. ^^^^^^^^^^^^^
  231. Sometimes you might want to send SPI transactions exclusively and continuously so that it takes as little time as possible. For this, you can use bus acquiring, which helps to suspend transactions (both polling or interrupt) to other Devices until the bus is released. To acquire and release a bus, use the functions :cpp:func:`spi_device_acquire_bus` and :cpp:func:`spi_device_release_bus`.
  232. Driver Usage
  233. ------------
  234. .. todo::
  235. Organize the Driver Usage into subsections that will reflect the general user experience of the users, e.g.,
  236. Configuration
  237. Add stuff about the configuration API here, the various options in configuration (e.g., configure for interrupt vs. polling), and optional configuration
  238. Transactions
  239. Describe how to execute a normal transaction (i.e., where data is larger than 32 bits). Describe how to configure between big and little-endian.
  240. - Add a sub-sub section on how to optimize when transmitting less than 32 bits
  241. - Add a sub-sub section on how to transmit mixed transactions to the same Device
  242. - Initialize an SPI bus by calling the function :cpp:func:`spi_bus_initialize`. Make sure to set the correct I/O pins in the struct :cpp:type:`spi_bus_config_t`. Set the signals that are not needed to ``-1``.
  243. - Register a Device connected to the bus with the driver by calling the function :cpp:func:`spi_bus_add_device`. Make sure to configure any timing requirements the Device might need with the parameter ``dev_config``. You should now have obtained the Device's handle which will be used when sending a transaction to it.
  244. - To interact with the Device, fill one or more :cpp:type:`spi_transaction_t` structs with any transaction parameters required. Then send the structs either using a polling transaction or an interrupt transaction:
  245. - :ref:`Interrupt <interrupt_transactions>`
  246. Either queue all transactions by calling the function :cpp:func:`spi_device_queue_trans` and, at a later time, query the result using the function :cpp:func:`spi_device_get_trans_result`, or handle all requests synchronously by feeding them into :cpp:func:`spi_device_transmit`.
  247. - :ref:`Polling <polling_transactions>`
  248. Call the function :cpp:func:`spi_device_polling_transmit` to send polling transactions. Alternatively, if you want to insert something in between, send the transactions by using :cpp:func:`spi_device_polling_start` and :cpp:func:`spi_device_polling_end`.
  249. - (Optional) To perform back-to-back transactions with a Device, call the function :cpp:func:`spi_device_acquire_bus` before sending transactions and :cpp:func:`spi_device_release_bus` after the transactions have been sent.
  250. - (Optional) To remove a certain Device from the bus, call :cpp:func:`spi_bus_remove_device` with the Device handle as an argument.
  251. - (Optional) To remove the driver from the bus, make sure no more devices are attached and call :cpp:func:`spi_bus_free`.
  252. The example code for the SPI Master driver can be found in the :example:`peripherals/spi_master` directory of ESP-IDF examples.
  253. Transactions with Data Not Exceeding 32 Bits
  254. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  255. When the transaction data size is equal to or less than 32 bits, it will be sub-optimal to allocate a buffer for the data. The data can be directly stored in the transaction struct instead. For transmitted data, it can be achieved by using the :cpp:member:`spi_transaction_t::tx_data` member and setting the :c:macro:`SPI_TRANS_USE_TXDATA` flag on the transmission. For received data, use :cpp:member:`spi_transaction_t::rx_data` and set :c:macro:`SPI_TRANS_USE_RXDATA`. In both cases, do not touch the :cpp:member:`spi_transaction_t::tx_buffer` or :cpp:member:`spi_transaction_t::rx_buffer` members, because they use the same memory locations as :cpp:member:`spi_transaction_t::tx_data` and :cpp:member:`spi_transaction_t::rx_data`.
  256. Transactions with Integers Other than ``uint8_t``
  257. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  258. An SPI Host reads and writes data into memory byte by byte. By default, data is sent with the most significant bit (MSB) first, as LSB is first used in rare cases. If a value of fewer than 8 bits needs to be sent, the bits should be written into memory in the MSB first manner.
  259. For example, if ``0b00010`` needs to be sent, it should be written into a ``uint8_t`` variable, and the length for reading should be set to 5 bits. The Device will still receive 8 bits with 3 additional "random" bits, so the reading must be performed correctly.
  260. On top of that, {IDF_TARGET_NAME} is a little-endian chip, which means that the least significant byte of ``uint16_t`` and ``uint32_t`` variables is stored at the smallest address. Hence, if ``uint16_t`` is stored in memory, bits [7:0] are sent first, followed by bits [15:8].
  261. For cases when the data to be transmitted has a size differing from ``uint8_t`` arrays, the following macros can be used to transform data to the format that can be sent by the SPI driver directly:
  262. - :c:macro:`SPI_SWAP_DATA_TX` for data to be transmitted
  263. - :c:macro:`SPI_SWAP_DATA_RX` for data received
  264. .. _mixed_transactions:
  265. Notes on Sending Mixed Transactions to the Same Device
  266. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  267. To reduce coding complexity, send only one type of transaction (interrupt or polling) to one Device. However, you still can send both interrupt and polling transactions alternately. The notes below explain how to do this.
  268. The polling transactions should be initiated only after all the polling and interrupt transactions are finished.
  269. Since an unfinished polling transaction blocks other transactions, please do not forget to call the function :cpp:func:`spi_device_polling_end` after :cpp:func:`spi_device_polling_start` to allow other transactions or to allow other Devices to use the bus. Remember that if there is no need to switch to other tasks during your polling transaction, you can initiate a transaction with :cpp:func:`spi_device_polling_transmit` so that it will be ended automatically.
  270. In-flight polling transactions are disturbed by the ISR operation to accommodate interrupt transactions. Always make sure that all the interrupt transactions sent to the ISR are finished before you call :cpp:func:`spi_device_polling_start`. To do that, you can keep calling :cpp:func:`spi_device_get_trans_result` until all the transactions are returned.
  271. To have better control of the calling sequence of functions, send mixed transactions to the same Device only within a single task.
  272. .. only:: esp32
  273. .. _spi_master_on_spi1_bus:
  274. Notes on Using the SPI Master Driver on SPI1 Bus
  275. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  276. .. note::
  277. Though the :ref:`spi_bus_lock` feature makes it possible to use SPI Master driver on the SPI1 bus, it is still tricky and needs a lot of special treatment. It is a feature for advanced developers.
  278. To use SPI Master driver on SPI1 bus, you have to take care of two problems:
  279. 1. The code and data should be in the internal memory when the driver is operating on SPI1 bus.
  280. SPI1 bus is shared among Devices and the cache for data (code) in the flash as well as the PSRAM. The cache should be disabled when other drivers are operating on the SPI1 bus. Hence the data (code) in the flash as well as the PSRAM cannot be fetched while the driver acquires the SPI1 bus by:
  281. - Explicit bus acquiring between :cpp:func:`spi_device_acquire_bus` and :cpp:func:`spi_device_release_bus`.
  282. - Implicit bus acquiring between :cpp:func:`spi_device_polling_start` and :cpp:func:`spi_device_polling_end` (or inside :cpp:func:`spi_device_polling_transmit`).
  283. During the time above, all other tasks and most ISRs will be disabled (see :ref:`iram-safe-interrupt-handlers`). Application code and data used by the current task should be placed in internal memory (DRAM or IRAM), or already in the ROM. Access to external memory (flash code, const data in the flash, and static/heap data in the PSRAM) will cause a ``Cache disabled but cached memory region accessed`` exception. For differences between IRAM, DRAM, and flash cache, please refer to the :ref:`application memory layout <memory-layout>` documentation.
  284. To place functions into the IRAM, you can either:
  285. 1. Add ``IRAM_ATTR`` (include ``esp_attr.h``) to the function like:
  286. IRAM_ATTR void foo(void) { }
  287. Please note that when a function is inlined, it will follow its caller's segment, and the attribute will not take effect. You may need to use ``NOLINE_ATTR`` to avoid this. Please also note that the compiler may transform some code into a lookup table in the const data, so ``noflash_text`` is not safe.
  288. 2. Use the ``noflash`` placement in the ``linker.lf``. See more in :doc:`../../api-guides/linker-script-generation`. Please note that the compiler may transform some code into a lookup table in the const data, so ``noflash_text`` is not safe.
  289. Please do take care that the optimization level may affect the compiler behavior of inline, or transform some code into a lookup table in the const data, etc.
  290. To place data into the DRAM, you can either:
  291. 1. Add ``DRAM_ATTR`` (include ``esp_attr.h``) to the data definition like:
  292. DRAM_ATTR int g_foo = 3;
  293. 2. Use the ``noflash`` placement in the linker.lf. See more in :doc:`../../api-guides/linker-script-generation`.
  294. Please also see the example :example:`peripherals/spi_master/hd_eeprom`.
  295. GPIO Matrix and IO_MUX
  296. ^^^^^^^^^^^^^^^^^^^^^^
  297. .. only:: esp32
  298. Most of ESP32's peripheral signals have a direct connection to their dedicated IO_MUX pins. However, the signals can also be routed to any other available pins using the less direct GPIO matrix. If at least one signal is routed through the GPIO matrix, then all signals will be routed through it.
  299. The GPIO matrix introduces flexibility of routing but also brings the following disadvantages:
  300. - Increases the input delay of the MISO signal, which makes MISO setup time violations more likely. If SPI needs to operate at high speeds, use dedicated IO_MUX pins.
  301. - Allows signals with clock frequencies only up to 40 MHz, as opposed to 80 MHz if IO_MUX pins are used.
  302. .. note::
  303. For more details about the influence of the MISO input delay on the maximum clock frequency, see :ref:`timing_considerations`.
  304. The IO_MUX pins for SPI buses are given below.
  305. .. list-table::
  306. :widths: 40 20 20
  307. :header-rows: 1
  308. * - Pin Name
  309. - SPI 2 (GPIO Number)
  310. - SPI 3 (GPIO Number)
  311. * - CS0 [1]_
  312. - 15
  313. - 5
  314. * - SCLK
  315. - 14
  316. - 18
  317. * - MISO
  318. - 12
  319. - 19
  320. * - MOSI
  321. - 13
  322. - 23
  323. * - QUADWP
  324. - 2
  325. - 22
  326. * - QUADHD
  327. - 4
  328. - 21
  329. .. only:: not esp32
  330. {IDF_TARGET_SPI2_IOMUX_PIN_CS:default="N/A", esp32s2="10", esp32s3="10", esp32c2="10", esp32c3="10", esp32c6="16", esp32h2="1", esp32p4="7"}
  331. {IDF_TARGET_SPI2_IOMUX_PIN_CLK:default="N/A", esp32s2="12", esp32s3="12", esp32c2="6", esp32c3="6", esp32c6="6", esp32h2="4", esp32p4="9"}
  332. {IDF_TARGET_SPI2_IOMUX_PIN_MOSI:default="N/A", esp32s2="11" esp32s3="11", esp32c2="7" esp32c3="7", esp32c6="7", esp32h2="5", esp32p4="8"}
  333. {IDF_TARGET_SPI2_IOMUX_PIN_MISO:default="N/A", esp32s2="13" esp32s3="13", esp32c2="2" esp32c3="2", esp32c6="2", esp32h2="0", esp32p4="10"}
  334. {IDF_TARGET_SPI2_IOMUX_PIN_HD:default="N/A", esp32s2="9" esp32s3="9", esp32c2="4" esp32c3="4", esp32c6="4", esp32h2="3", esp32p4="6"}
  335. {IDF_TARGET_SPI2_IOMUX_PIN_WP:default="N/A", esp32s2="14" esp32s3="14", esp32c2="5" esp32c3="5", esp32c6="5", esp32h2="2", esp32p4="11"}
  336. Most of the chip's peripheral signals have a direct connection to their dedicated IO_MUX pins. However, the signals can also be routed to any other available pins using the less direct GPIO matrix. If at least one signal is routed through the GPIO matrix, then all signals will be routed through it.
  337. When an SPI Host is set to 80 MHz or lower frequencies, routing SPI pins via the GPIO matrix will behave the same compared to routing them via IOMUX.
  338. The IO_MUX pins for SPI buses are given below.
  339. .. list-table::
  340. :widths: 40 30
  341. :header-rows: 1
  342. * - Pin Name
  343. - GPIO Number (SPI2)
  344. * - CS0 [1]_
  345. - {IDF_TARGET_SPI2_IOMUX_PIN_CS}
  346. * - SCLK
  347. - {IDF_TARGET_SPI2_IOMUX_PIN_CLK}
  348. * - MISO
  349. - {IDF_TARGET_SPI2_IOMUX_PIN_MISO}
  350. * - MOSI
  351. - {IDF_TARGET_SPI2_IOMUX_PIN_MOSI}
  352. * - QUADWP
  353. - {IDF_TARGET_SPI2_IOMUX_PIN_WP}
  354. * - QUADHD
  355. - {IDF_TARGET_SPI2_IOMUX_PIN_HD}
  356. .. [1] Only the first Device attached to the bus can use the CS0 pin.
  357. .. _speed_considerations:
  358. Transfer Speed Considerations
  359. -----------------------------
  360. There are three factors limiting the transfer speed:
  361. - Transaction interval
  362. - SPI clock frequency
  363. - Cache miss of SPI functions, including callbacks
  364. The main parameter that determines the transfer speed for large transactions is clock frequency. For multiple small transactions, the transfer speed is mostly determined by the length of transaction intervals.
  365. Transaction Duration
  366. ^^^^^^^^^^^^^^^^^^^^
  367. {IDF_TARGET_TRANS_TIME_INTR_DMA:default="N/A", esp32="28", esp32s2="23", esp32c3="28", esp32s3="26", esp32c2="42", esp32c6="34", esp32h2="58"}
  368. {IDF_TARGET_TRANS_TIME_POLL_DMA:default="N/A", esp32="10", esp32s2="9", esp32c3="10", esp32s3="11", esp32c2="17", esp32c6="17", esp32h2="28"}
  369. {IDF_TARGET_TRANS_TIME_INTR_CPU:default="N/A", esp32="25", esp32s2="22", esp32c3="27", esp32s3="24", esp32c2="40", esp32c6="32", esp32h2="54"}
  370. {IDF_TARGET_TRANS_TIME_POLL_CPU:default="N/A", esp32="8", esp32s2="8", esp32c3="9", esp32s3="9", esp32c2="15", esp32c6="15", esp32h2="24"}
  371. Transaction duration includes setting up SPI peripheral registers, copying data to FIFOs or setting up DMA links, and the time for SPI transactions.
  372. Interrupt transactions allow appending extra overhead to accommodate the cost of FreeRTOS queues and the time needed for switching between tasks and the ISR.
  373. For **interrupt transactions**, the CPU can switch to other tasks when a transaction is in progress. This saves CPU time but increases the transaction duration. See :ref:`interrupt_transactions`. For **polling transactions**, it does not block the task but allows to do polling when the transaction is in progress. For more information, see :ref:`polling_transactions`.
  374. If DMA is enabled, setting up the linked list requires about 2 µs per transaction. When a master is transferring data, it automatically reads the data from the linked list. If DMA is not enabled, the CPU has to write and read each byte from the FIFO by itself. Usually, this is faster than 2 µs, but the transaction length is limited to 64 bytes for both write and read.
  375. The typical transaction duration for one byte of data is given below.
  376. - Interrupt Transaction via DMA: {IDF_TARGET_TRANS_TIME_INTR_DMA} µs.
  377. - Interrupt Transaction via CPU: {IDF_TARGET_TRANS_TIME_INTR_CPU} µs.
  378. - Polling Transaction via DMA: {IDF_TARGET_TRANS_TIME_POLL_DMA} µs.
  379. - Polling Transaction via CPU: {IDF_TARGET_TRANS_TIME_POLL_CPU} µs.
  380. Note that these data are tested with :ref:`CONFIG_SPI_MASTER_ISR_IN_IRAM` enabled. SPI transaction related code are placed in the internal memory. If this option is turned off (for example, for internal memory optimization), the transaction duration may be affected.
  381. SPI Clock Frequency
  382. ^^^^^^^^^^^^^^^^^^^
  383. The clock source of the GPSPI peripherals can be selected by setting :cpp:member:`spi_device_handle_t::cfg::clock_source`. You can refer to :cpp:type:`spi_clock_source_t` to know the supported clock sources.
  384. By default driver sets :cpp:member:`spi_device_handle_t::cfg::clock_source` to ``SPI_CLK_SRC_DEFAULT``. This usually stands for the highest frequency among GPSPI clock sources. Its value is different among chips.
  385. The actual clock frequency of a Device may not be exactly equal to the number you set, it is re-calculated by the driver to the nearest hardware-compatible number, and not larger than the clock frequency of the clock source. You can call :cpp:func:`spi_device_get_actual_freq` to know the actual frequency computed by the driver.
  386. The theoretical maximum transfer speed of the Write or Read phase can be calculated according to the table below:
  387. .. only:: not SOC_SPI_SUPPORT_OCT
  388. .. list-table::
  389. :widths: 40 30
  390. :header-rows: 1
  391. * - Line Width of Write/Read phase
  392. - Speed (Bps)
  393. * - 1-Line
  394. - *SPI Frequency / 8*
  395. * - 2-Line
  396. - *SPI Frequency / 4*
  397. * - 4-Line
  398. - *SPI Frequency / 2*
  399. .. only:: SOC_SPI_SUPPORT_OCT
  400. .. list-table::
  401. :widths: 40 30
  402. :header-rows: 1
  403. * - Line Width of Write/Read phase
  404. - Speed (Bps)
  405. * - 1-Line
  406. - *SPI Frequency / 8*
  407. * - 2-Line
  408. - *SPI Frequency / 4*
  409. * - 4-Line
  410. - *SPI Frequency / 2*
  411. * - 8-Line
  412. - *SPI Frequency*
  413. The transfer speed calculation of other phases (Command, Address, Dummy) is similar.
  414. .. only:: esp32
  415. If the clock frequency is too high, the use of some functions might be limited. See :ref:`timing_considerations`.
  416. Cache Missing
  417. ^^^^^^^^^^^^^
  418. The default config puts only the ISR into the IRAM. Other SPI-related functions, including the driver itself and the callback, might suffer from cache misses and need to wait until the code is read from flash. Select :ref:`CONFIG_SPI_MASTER_IN_IRAM` to put the whole SPI driver into IRAM and put the entire callback(s) and its callee functions into IRAM to prevent cache missing.
  419. .. note::
  420. SPI driver implementation is based on FreeRTOS APIs, to use :ref:`CONFIG_SPI_MASTER_IN_IRAM`, you should not enable :ref:`CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH`.
  421. For an interrupt transaction, the overall cost is **20+8n/Fspi[MHz]** [µs] for n bytes transferred in one transaction. Hence, the transferring speed is: **n/(20+8n/Fspi)**. An example of transferring speed at 8 MHz clock speed is given in the following table.
  422. .. list-table::
  423. :widths: 30 45 40 30 30
  424. :header-rows: 1
  425. * - Frequency (MHz)
  426. - Transaction Interval (µs)
  427. - Transaction Length (bytes)
  428. - Total Time (µs)
  429. - Total Speed (KBps)
  430. * - 8
  431. - 25
  432. - 1
  433. - 26
  434. - 38.5
  435. * - 8
  436. - 25
  437. - 8
  438. - 33
  439. - 242.4
  440. * - 8
  441. - 25
  442. - 16
  443. - 41
  444. - 490.2
  445. * - 8
  446. - 25
  447. - 64
  448. - 89
  449. - 719.1
  450. * - 8
  451. - 25
  452. - 128
  453. - 153
  454. - 836.6
  455. When a transaction length is short, the cost of the transaction interval is high. If possible, try to squash several short transactions into one transaction to achieve a higher transfer speed.
  456. Please note that the ISR is disabled during flash operation by default. To keep sending transactions during flash operations, enable :ref:`CONFIG_SPI_MASTER_ISR_IN_IRAM` and set :c:macro:`ESP_INTR_FLAG_IRAM` in the member :cpp:member:`spi_bus_config_t::intr_flags`. In this case, all the transactions queued before starting flash operations are handled by the ISR in parallel. Also note that the callback of each Device and their ``callee`` functions should be in IRAM, or your callback will crash due to cache missing. For more details, see :ref:`iram-safe-interrupt-handlers`.
  457. .. only:: esp32
  458. .. _timing_considerations:
  459. Timing Considerations
  460. ---------------------
  461. As shown in the figure below, there is a delay on the MISO line after the SCLK launch edge and before the signal is latched by the internal register. As a result, the MISO pin setup time is the limiting factor for the SPI clock speed. When the delay is too long, the setup slack is < 0, which means the setup timing requirement is violated and the reading might be incorrect.
  462. .. image:: /../_static/spi_miso.png
  463. :scale: 40 %
  464. :align: center
  465. .. wavedrom:: /../_static/diagrams/spi/miso_timing_waveform.json
  466. The maximum allowed frequency is dependent on:
  467. - :cpp:member:`spi_device_interface_config_t::input_delay_ns` - maximum data valid time on the MISO bus after a clock cycle on SCLK starts
  468. - If the IO_MUX pin or the GPIO Matrix is used
  469. When the GPIO matrix is used, the maximum allowed frequency is reduced to about 33 ~ 77% in comparison to the existing **input delay**. To retain a higher frequency, you have to use the IO_MUX pins or the **dummy bit workaround**. You can obtain the maximum reading frequency of the master by using the function :cpp:func:`spi_get_freq_limit`.
  470. .. _dummy_bit_workaround:
  471. **Dummy bit workaround**: Dummy clocks, during which the Host does not read data, can be inserted before the Read phase begins. The Device still sees the dummy clocks and sends out data, but the Host does not read until the Read phase comes. This compensates for the lack of the MISO setup time required by the Host and allows the Host to do reading at a higher frequency.
  472. In the ideal case, if the Device is so fast that the input delay is shorter than an APB clock cycle - 12.5 ns - the maximum frequency at which the Host can read (or read and write) in different conditions is as follows:
  473. .. list-table::
  474. :widths: 30 45 40 30
  475. :header-rows: 1
  476. * - Frequency Limit (MHz)
  477. - Frequency Limit (MHz)
  478. - Dummy Bits Used by Driver
  479. - Comments
  480. * - GPIO Matrix
  481. - IO_MUX Pins
  482. -
  483. -
  484. * - 26.6
  485. - 80
  486. - No
  487. -
  488. * - 40
  489. - --
  490. - Yes
  491. - Half-duplex, no DMA allowed
  492. If the Host only writes data, the **dummy bit workaround** and the frequency check can be disabled by setting the bit ``SPI_DEVICE_NO_DUMMY`` in the member :cpp:member:`spi_device_interface_config_t::flags`. When disabled, the output frequency can be 80 MHz, even if the GPIO matrix is used.
  493. :cpp:member:`spi_device_interface_config_t::flags`
  494. The SPI Master driver still works even if the :cpp:member:`spi_device_interface_config_t::input_delay_ns` in the structure :cpp:type:`spi_device_interface_config_t` is set to 0. However, setting an accurate value helps to:
  495. - Calculate the frequency limit for full-duplex transactions
  496. - Compensate the timing correctly with dummy bits for half-duplex transactions
  497. You can approximate the maximum data valid time after the launch edge of SPI clocks by checking the statistics in the AC characteristics chapter of your Device's specification or measure the time using an oscilloscope or logic analyzer.
  498. Please note that the actual PCB layout design and excessive loads may increase the input delay. It means that non-optimal wiring and/or a load capacitor on the bus will most likely lead to input delay values exceeding the values given in the Device specification or measured while the bus is floating.
  499. Some typical delay values are shown in the following table. These data are retrieved when the slave Device is on a different physical chip.
  500. .. list-table::
  501. :widths: 40 20
  502. :header-rows: 1
  503. * - Device
  504. - Input Delay (ns)
  505. * - Ideal Device
  506. - 0
  507. * - ESP32 slave using IO_MUX
  508. - 50
  509. * - ESP32 slave using GPIO_MATRIX
  510. - 75
  511. The MISO path delay (valid time) consists of a slave's **input delay** plus the master's **GPIO matrix delay**. The delay determines the above frequency limit for full-duplex transfers. Once exceeding, full-duplex transfers will not work as well as the half-duplex transactions that use dummy bits. The frequency limit is:
  512. *Freq limit [MHz] = 80 / (floor(MISO delay[ns]/12.5) + 1)*
  513. The figure below shows the relationship between frequency limit and input delay. Two extra APB clock cycle periods should be added to the MISO delay if the master uses the GPIO matrix.
  514. .. image:: /../_static/spi_master_freq_tv.png
  515. Corresponding frequency limits for different Devices with different **input delay** times are shown in the table below.
  516. When the master is IO_MUX (0 ns):
  517. .. list-table::
  518. :widths: 20 40 40
  519. :header-rows: 1
  520. * - Input Delay (ns)
  521. - MISO Path Delay (ns)
  522. - Freq. Limit (MHz)
  523. * - 0
  524. - 0
  525. - 80
  526. * - 50
  527. - 50
  528. - 16
  529. * - 75
  530. - 75
  531. - 11.43
  532. When the master is GPIO_MATRIX (25 ns):
  533. .. list-table::
  534. :widths: 20 40 40
  535. :header-rows: 1
  536. * - Input Delay (ns)
  537. - MISO Path Delay (ns)
  538. - Freq. Limit (MHz)
  539. * - 0
  540. - 25
  541. - 26.67
  542. * - 50
  543. - 75
  544. - 11.43
  545. * - 75
  546. - 100
  547. - 8.89
  548. .. _spi_known_issues:
  549. Known Issues
  550. ------------
  551. 1. Half-duplex transactions are not compatible with DMA when both the Write and Read phases are used.
  552. If such transactions are required, you have to use one of the alternative solutions:
  553. 1. Use full-duplex transactions instead.
  554. 2. Disable DMA by setting the bus initialization function's last parameter to 0 as follows:
  555. ``ret=spi_bus_initialize(VSPI_HOST, &buscfg, 0);``
  556. This can prohibit you from transmitting and receiving data longer than 64 bytes.
  557. 3. Try using the command and address fields to replace the Write phase.
  558. 2. Full-duplex transactions are not compatible with the **dummy bit workaround**, hence the frequency is limited. See :ref:`dummy bit speed-up workaround <dummy_bit_workaround>`.
  559. 3. ``dummy_bits`` in :cpp:type:`spi_device_interface_config_t` and :cpp:type:`spi_transaction_ext_t` are not available when SPI Read and Write phases are both enabled (regardless of full duplex or half duplex mode).
  560. 4. ``cs_ena_pretrans`` is not compatible with the Command and Address phases of full-duplex transactions.
  561. Application Example
  562. -------------------
  563. The code example for using the SPI master half duplex mode to read/write an AT93C46D EEPROM (8-bit mode) can be found in the :example:`peripherals/spi_master/hd_eeprom` directory of ESP-IDF examples.
  564. The code example for using the SPI master full duplex mode to drive a SPI_LCD (e.g. ST7789V or ILI9341) can be found in the :example:`peripherals/spi_master/lcd` directory of ESP-IDF examples.
  565. API Reference - SPI Common
  566. --------------------------
  567. .. include-build-file:: inc/spi_types.inc
  568. .. include-build-file:: inc/spi_common.inc
  569. API Reference - SPI Master
  570. --------------------------
  571. .. include-build-file:: inc/spi_master.inc