1 /*
2  * SPDX-FileCopyrightText: 2010-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #pragma once
8 
9 #include "esp_err.h"
10 #include "freertos/FreeRTOS.h"
11 #include "hal/spi_types.h"
12 //for spi_bus_initialization functions. to be back-compatible
13 #include "driver/spi_common.h"
14 
15 /**
16  * @brief SPI common used frequency (in Hz)
17  * @note SPI peripheral only has an integer divider, and the default clock source can be different on other targets,
18  *       so the actual frequency may be slightly different from the desired frequency.
19  */
20 #define SPI_MASTER_FREQ_8M      (80 * 1000 * 1000 / 10)   ///< 8MHz
21 #define SPI_MASTER_FREQ_9M      (80 * 1000 * 1000 / 9)    ///< 8.89MHz
22 #define SPI_MASTER_FREQ_10M     (80 * 1000 * 1000 / 8)    ///< 10MHz
23 #define SPI_MASTER_FREQ_11M     (80 * 1000 * 1000 / 7)    ///< 11.43MHz
24 #define SPI_MASTER_FREQ_13M     (80 * 1000 * 1000 / 6)    ///< 13.33MHz
25 #define SPI_MASTER_FREQ_16M     (80 * 1000 * 1000 / 5)    ///< 16MHz
26 #define SPI_MASTER_FREQ_20M     (80 * 1000 * 1000 / 4)    ///< 20MHz
27 #define SPI_MASTER_FREQ_26M     (80 * 1000 * 1000 / 3)    ///< 26.67MHz
28 #define SPI_MASTER_FREQ_40M     (80 * 1000 * 1000 / 2)    ///< 40MHz
29 #define SPI_MASTER_FREQ_80M     (80 * 1000 * 1000 / 1)    ///< 80MHz
30 
31 #ifdef __cplusplus
32 extern "C"
33 {
34 #endif
35 
36 #define SPI_DEVICE_TXBIT_LSBFIRST          (1<<0)  ///< Transmit command/address/data LSB first instead of the default MSB first
37 #define SPI_DEVICE_RXBIT_LSBFIRST          (1<<1)  ///< Receive data LSB first instead of the default MSB first
38 #define SPI_DEVICE_BIT_LSBFIRST            (SPI_DEVICE_TXBIT_LSBFIRST|SPI_DEVICE_RXBIT_LSBFIRST) ///< Transmit and receive LSB first
39 #define SPI_DEVICE_3WIRE                   (1<<2)  ///< Use MOSI (=spid) for both sending and receiving data
40 #define SPI_DEVICE_POSITIVE_CS             (1<<3)  ///< Make CS positive during a transaction instead of negative
41 #define SPI_DEVICE_HALFDUPLEX              (1<<4)  ///< Transmit data before receiving it, instead of simultaneously
42 #define SPI_DEVICE_CLK_AS_CS               (1<<5)  ///< Output clock on CS line if CS is active
43 /** There are timing issue when reading at high frequency (the frequency is related to whether iomux pins are used, valid time after slave sees the clock).
44   *     - In half-duplex mode, the driver automatically inserts dummy bits before reading phase to fix the timing issue. Set this flag to disable this feature.
45   *     - In full-duplex mode, however, the hardware cannot use dummy bits, so there is no way to prevent data being read from getting corrupted.
46   *       Set this flag to confirm that you're going to work with output only, or read without dummy bits at your own risk.
47   */
48 #define SPI_DEVICE_NO_DUMMY                (1<<6)
49 #define SPI_DEVICE_DDRCLK                  (1<<7)
50 #define SPI_DEVICE_NO_RETURN_RESULT        (1<<8)  ///< Don't return the descriptor to the host on completion (use post_cb to notify instead)
51 
52 /** @cond */
53 typedef struct spi_transaction_t spi_transaction_t;
54 /** @endcond */
55 typedef void(*transaction_cb_t)(spi_transaction_t *trans);
56 
57 /**
58  * @brief This is a configuration for a SPI slave device that is connected to one of the SPI buses.
59  */
60 typedef struct {
61     uint8_t command_bits;           ///< Default amount of bits in command phase (0-16), used when ``SPI_TRANS_VARIABLE_CMD`` is not used, otherwise ignored.
62     uint8_t address_bits;           ///< Default amount of bits in address phase (0-64), used when ``SPI_TRANS_VARIABLE_ADDR`` is not used, otherwise ignored.
63     uint8_t dummy_bits;             ///< Amount of dummy bits to insert between address and data phase
64     uint8_t mode;                   /**< SPI mode, representing a pair of (CPOL, CPHA) configuration:
65                                          - 0: (0, 0)
66                                          - 1: (0, 1)
67                                          - 2: (1, 0)
68                                          - 3: (1, 1)
69                                      */
70     spi_clock_source_t clock_source;///< Select SPI clock source, `SPI_CLK_SRC_DEFAULT` by default.
71     uint16_t duty_cycle_pos;        ///< Duty cycle of positive clock, in 1/256th increments (128 = 50%/50% duty). Setting this to 0 (=not setting it) is equivalent to setting this to 128.
72     uint16_t cs_ena_pretrans;       ///< Amount of SPI bit-cycles the cs should be activated before the transmission (0-16). This only works on half-duplex transactions.
73     uint8_t cs_ena_posttrans;       ///< Amount of SPI bit-cycles the cs should stay active after the transmission (0-16)
74     int clock_speed_hz;             ///< Clock speed, divisors of the SPI `clock_source`, in Hz
75     int input_delay_ns;             /**< Maximum data valid time of slave. The time required between SCLK and MISO
76         valid, including the possible clock delay from slave to master. The driver uses this value to give an extra
77         delay before the MISO is ready on the line. Leave at 0 unless you know you need a delay. For better timing
78         performance at high frequency (over 8MHz), it's suggest to have the right value.
79         */
80     int spics_io_num;               ///< CS GPIO pin for this device, or -1 if not used
81     uint32_t flags;                 ///< Bitwise OR of SPI_DEVICE_* flags
82     int queue_size;                 ///< Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_device_queue_trans but not yet finished using spi_device_get_trans_result) at the same time
83     transaction_cb_t pre_cb;   /**< Callback to be called before a transmission is started.
84                                  *
85                                  *  This callback is called within interrupt
86                                  *  context should be in IRAM for best
87                                  *  performance, see "Transferring Speed"
88                                  *  section in the SPI Master documentation for
89                                  *  full details. If not, the callback may crash
90                                  *  during flash operation when the driver is
91                                  *  initialized with ESP_INTR_FLAG_IRAM.
92                                  */
93     transaction_cb_t post_cb;  /**< Callback to be called after a transmission has completed.
94                                  *
95                                  *  This callback is called within interrupt
96                                  *  context should be in IRAM for best
97                                  *  performance, see "Transferring Speed"
98                                  *  section in the SPI Master documentation for
99                                  *  full details. If not, the callback may crash
100                                  *  during flash operation when the driver is
101                                  *  initialized with ESP_INTR_FLAG_IRAM.
102                                  */
103 } spi_device_interface_config_t;
104 
105 
106 #define SPI_TRANS_MODE_DIO            (1<<0)  ///< Transmit/receive data in 2-bit mode
107 #define SPI_TRANS_MODE_QIO            (1<<1)  ///< Transmit/receive data in 4-bit mode
108 #define SPI_TRANS_USE_RXDATA          (1<<2)  ///< Receive into rx_data member of spi_transaction_t instead into memory at rx_buffer.
109 #define SPI_TRANS_USE_TXDATA          (1<<3)  ///< Transmit tx_data member of spi_transaction_t instead of data at tx_buffer. Do not set tx_buffer when using this.
110 #define SPI_TRANS_MODE_DIOQIO_ADDR    (1<<4)  ///< Also transmit address in mode selected by SPI_MODE_DIO/SPI_MODE_QIO
111 #define SPI_TRANS_VARIABLE_CMD        (1<<5)  ///< Use the ``command_bits`` in ``spi_transaction_ext_t`` rather than default value in ``spi_device_interface_config_t``.
112 #define SPI_TRANS_VARIABLE_ADDR       (1<<6)  ///< Use the ``address_bits`` in ``spi_transaction_ext_t`` rather than default value in ``spi_device_interface_config_t``.
113 #define SPI_TRANS_VARIABLE_DUMMY      (1<<7)  ///< Use the ``dummy_bits`` in ``spi_transaction_ext_t`` rather than default value in ``spi_device_interface_config_t``.
114 #define SPI_TRANS_CS_KEEP_ACTIVE      (1<<8)  ///< Keep CS active after data transfer
115 #define SPI_TRANS_MULTILINE_CMD       (1<<9)  ///< The data lines used at command phase is the same as data phase (otherwise, only one data line is used at command phase)
116 #define SPI_TRANS_MODE_OCT            (1<<10) ///< Transmit/receive data in 8-bit mode
117 #define SPI_TRANS_MULTILINE_ADDR      SPI_TRANS_MODE_DIOQIO_ADDR ///< The data lines used at address phase is the same as data phase (otherwise, only one data line is used at address phase)
118 
119 /**
120  * This structure describes one SPI transaction. The descriptor should not be modified until the transaction finishes.
121  */
122 struct spi_transaction_t {
123     uint32_t flags;                 ///< Bitwise OR of SPI_TRANS_* flags
124     uint16_t cmd;                   /**< Command data, of which the length is set in the ``command_bits`` of spi_device_interface_config_t.
125                                       *
126                                       *  <b>NOTE: this field, used to be "command" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF 3.0.</b>
127                                       *
128                                       *  Example: write 0x0123 and command_bits=12 to send command 0x12, 0x3_ (in previous version, you may have to write 0x3_12).
129                                       */
130     uint64_t addr;                  /**< Address data, of which the length is set in the ``address_bits`` of spi_device_interface_config_t.
131                                       *
132                                       *  <b>NOTE: this field, used to be "address" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF3.0.</b>
133                                       *
134                                       *  Example: write 0x123400 and address_bits=24 to send address of 0x12, 0x34, 0x00 (in previous version, you may have to write 0x12340000).
135                                       */
136     size_t length;                  ///< Total data length, in bits
137     size_t rxlength;                ///< Total data length received, should be not greater than ``length`` in full-duplex mode (0 defaults this to the value of ``length``).
138     void *user;                     ///< User-defined variable. Can be used to store eg transaction ID.
139     union {
140         const void *tx_buffer;      ///< Pointer to transmit buffer, or NULL for no MOSI phase
141         uint8_t tx_data[4];         ///< If SPI_TRANS_USE_TXDATA is set, data set here is sent directly from this variable.
142     };
143     union {
144         void *rx_buffer;            ///< Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used.
145         uint8_t rx_data[4];         ///< If SPI_TRANS_USE_RXDATA is set, data is received directly to this variable
146     };
147 } ;        //the rx data should start from a 32-bit aligned address to get around dma issue.
148 
149 /**
150  * This struct is for SPI transactions which may change their address and command length.
151  * Please do set the flags in base to ``SPI_TRANS_VARIABLE_CMD_ADR`` to use the bit length here.
152  */
153 typedef struct {
154     struct spi_transaction_t base;  ///< Transaction data, so that pointer to spi_transaction_t can be converted into spi_transaction_ext_t
155     uint8_t command_bits;           ///< The command length in this transaction, in bits.
156     uint8_t address_bits;           ///< The address length in this transaction, in bits.
157     uint8_t dummy_bits;             ///< The dummy length in this transaction, in bits.
158 } spi_transaction_ext_t ;
159 
160 
161 typedef struct spi_device_t *spi_device_handle_t;  ///< Handle for a device on a SPI bus
162 /**
163  * @brief Allocate a device on a SPI bus
164  *
165  * This initializes the internal structures for a device, plus allocates a CS pin on the indicated SPI master
166  * peripheral and routes it to the indicated GPIO. All SPI master devices have three CS pins and can thus control
167  * up to three devices.
168  *
169  * @note While in general, speeds up to 80MHz on the dedicated SPI pins and 40MHz on GPIO-matrix-routed pins are
170  *       supported, full-duplex transfers routed over the GPIO matrix only support speeds up to 26MHz.
171  *
172  * @param host_id SPI peripheral to allocate device on
173  * @param dev_config SPI interface protocol config for the device
174  * @param handle Pointer to variable to hold the device handle
175  * @return
176  *         - ESP_ERR_INVALID_ARG   if parameter is invalid or configuration combination is not supported (e.g.
177  *                                 `dev_config->post_cb` isn't set while flag `SPI_DEVICE_NO_RETURN_RESULT` is enabled)
178  *         - ESP_ERR_INVALID_STATE if selected clock source is unavailable or spi bus not initialized
179  *         - ESP_ERR_NOT_FOUND     if host doesn't have any free CS slots
180  *         - ESP_ERR_NO_MEM        if out of memory
181  *         - ESP_OK                on success
182  */
183 esp_err_t spi_bus_add_device(spi_host_device_t host_id, const spi_device_interface_config_t *dev_config, spi_device_handle_t *handle);
184 
185 
186 /**
187  * @brief Remove a device from the SPI bus
188  *
189  * @param handle Device handle to free
190  * @return
191  *         - ESP_ERR_INVALID_ARG   if parameter is invalid
192  *         - ESP_ERR_INVALID_STATE if device already is freed
193  *         - ESP_OK                on success
194  */
195 esp_err_t spi_bus_remove_device(spi_device_handle_t handle);
196 
197 
198 /**
199  * @brief Queue a SPI transaction for interrupt transaction execution. Get the result by ``spi_device_get_trans_result``.
200  *
201  * @note Normally a device cannot start (queue) polling and interrupt
202  *      transactions simultaneously.
203  *
204  * @param handle Device handle obtained using spi_host_add_dev
205  * @param trans_desc Description of transaction to execute
206  * @param ticks_to_wait Ticks to wait until there's room in the queue; use portMAX_DELAY to
207  *                      never time out.
208  * @return
209  *         - ESP_ERR_INVALID_ARG   if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while
210  *                                 the bus was not acquired (`spi_device_acquire_bus()` should be called first)
211  *         - ESP_ERR_TIMEOUT       if there was no room in the queue before ticks_to_wait expired
212  *         - ESP_ERR_NO_MEM        if allocating DMA-capable temporary buffer failed
213  *         - ESP_ERR_INVALID_STATE if previous transactions are not finished
214  *         - ESP_OK                on success
215  */
216 esp_err_t spi_device_queue_trans(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait);
217 
218 
219 /**
220  * @brief Get the result of a SPI transaction queued earlier by ``spi_device_queue_trans``.
221  *
222  * This routine will wait until a transaction to the given device
223  * succesfully completed. It will then return the description of the
224  * completed transaction so software can inspect the result and e.g. free the memory or
225  * re-use the buffers.
226  *
227  * @param handle Device handle obtained using spi_host_add_dev
228  * @param trans_desc Pointer to variable able to contain a pointer to the description of the transaction
229         that is executed. The descriptor should not be modified until the descriptor is returned by
230         spi_device_get_trans_result.
231  * @param ticks_to_wait Ticks to wait until there's a returned item; use portMAX_DELAY to never time
232                         out.
233  * @return
234  *         - ESP_ERR_INVALID_ARG   if parameter is invalid
235  *         - ESP_ERR_NOT_SUPPORTED if flag `SPI_DEVICE_NO_RETURN_RESULT` is set
236  *         - ESP_ERR_TIMEOUT       if there was no completed transaction before ticks_to_wait expired
237  *         - ESP_OK                on success
238  */
239 esp_err_t spi_device_get_trans_result(spi_device_handle_t handle, spi_transaction_t **trans_desc, TickType_t ticks_to_wait);
240 
241 
242 /**
243  * @brief Send a SPI transaction, wait for it to complete, and return the result
244  *
245  * This function is the equivalent of calling spi_device_queue_trans() followed by spi_device_get_trans_result().
246  * Do not use this when there is still a transaction separately queued (started) from spi_device_queue_trans() or polling_start/transmit that hasn't been finalized.
247  *
248  * @note This function is not thread safe when multiple tasks access the same SPI device.
249  *      Normally a device cannot start (queue) polling and interrupt
250  *      transactions simutanuously.
251  *
252  * @param handle Device handle obtained using spi_host_add_dev
253  * @param trans_desc Description of transaction to execute
254  * @return
255  *         - ESP_ERR_INVALID_ARG   if parameter is invalid
256  *         - ESP_OK                on success
257  */
258 esp_err_t spi_device_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc);
259 
260 
261 /**
262  * @brief Immediately start a polling transaction.
263  *
264  * @note Normally a device cannot start (queue) polling and interrupt
265  *      transactions simutanuously. Moreover, a device cannot start a new polling
266  *      transaction if another polling transaction is not finished.
267  *
268  * @param handle Device handle obtained using spi_host_add_dev
269  * @param trans_desc Description of transaction to execute
270  * @param ticks_to_wait Ticks to wait until there's room in the queue;
271  *              currently only portMAX_DELAY is supported.
272  *
273  * @return
274  *         - ESP_ERR_INVALID_ARG   if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while
275  *                                 the bus was not acquired (`spi_device_acquire_bus()` should be called first)
276  *         - ESP_ERR_TIMEOUT       if the device cannot get control of the bus before ``ticks_to_wait`` expired
277  *         - ESP_ERR_NO_MEM        if allocating DMA-capable temporary buffer failed
278  *         - ESP_ERR_INVALID_STATE if previous transactions are not finished
279  *         - ESP_OK                on success
280  */
281 esp_err_t spi_device_polling_start(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait);
282 
283 
284 /**
285  * @brief Poll until the polling transaction ends.
286  *
287  * This routine will not return until the transaction to the given device has
288  * succesfully completed. The task is not blocked, but actively busy-spins for
289  * the transaction to be completed.
290  *
291  * @param handle Device handle obtained using spi_host_add_dev
292  * @param ticks_to_wait Ticks to wait until there's a returned item; use portMAX_DELAY to never time
293                         out.
294  * @return
295  *         - ESP_ERR_INVALID_ARG   if parameter is invalid
296  *         - ESP_ERR_TIMEOUT       if the transaction cannot finish before ticks_to_wait expired
297  *         - ESP_OK                on success
298  */
299 esp_err_t spi_device_polling_end(spi_device_handle_t handle, TickType_t ticks_to_wait);
300 
301 
302 /**
303  * @brief Send a polling transaction, wait for it to complete, and return the result
304  *
305  * This function is the equivalent of calling spi_device_polling_start() followed by spi_device_polling_end().
306  * Do not use this when there is still a transaction that hasn't been finalized.
307  *
308  * @note This function is not thread safe when multiple tasks access the same SPI device.
309  *      Normally a device cannot start (queue) polling and interrupt
310  *      transactions simutanuously.
311  *
312  * @param handle Device handle obtained using spi_host_add_dev
313  * @param trans_desc Description of transaction to execute
314  * @return
315  *         - ESP_ERR_INVALID_ARG   if parameter is invalid
316  *         - ESP_OK                on success
317  */
318 esp_err_t spi_device_polling_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc);
319 
320 
321 /**
322  * @brief Occupy the SPI bus for a device to do continuous transactions.
323  *
324  * Transactions to all other devices will be put off until ``spi_device_release_bus`` is called.
325  *
326  * @note The function will wait until all the existing transactions have been sent.
327  *
328  * @param device The device to occupy the bus.
329  * @param wait Time to wait before the the bus is occupied by the device. Currently MUST set to portMAX_DELAY.
330  *
331  * @return
332  *      - ESP_ERR_INVALID_ARG : ``wait`` is not set to portMAX_DELAY.
333  *      - ESP_OK : Success.
334  */
335 esp_err_t spi_device_acquire_bus(spi_device_handle_t device, TickType_t wait);
336 
337 /**
338  * @brief Release the SPI bus occupied by the device. All other devices can start sending transactions.
339  *
340  * @param dev The device to release the bus.
341  */
342 void spi_device_release_bus(spi_device_handle_t dev);
343 
344 /**
345  * @brief Calculate working frequency for specific device
346  *
347  * @param handle SPI device handle
348  * @param[out] freq_khz output parameter to hold calculated frequency in kHz
349  *
350  * @return
351  *      - ESP_ERR_INVALID_ARG : ``handle`` or ``freq_khz`` parameter is NULL
352  *      - ESP_OK : Success
353  */
354 esp_err_t spi_device_get_actual_freq(spi_device_handle_t handle, int *freq_khz);
355 
356 /**
357  * @brief Calculate the working frequency that is most close to desired frequency.
358  *
359  * @param fapb The frequency of apb clock, should be ``APB_CLK_FREQ``.
360  * @param hz Desired working frequency
361  * @param duty_cycle Duty cycle of the spi clock
362  *
363  * @return Actual working frequency that most fit.
364  */
365 int spi_get_actual_clock(int fapb, int hz, int duty_cycle) __attribute__((deprecated("Please use spi_device_get_actual_freq instead")));
366 
367 /**
368   * @brief Calculate the timing settings of specified frequency and settings.
369   *
370   * @param gpio_is_used True if using GPIO matrix, or False if iomux pins are used.
371   * @param input_delay_ns Input delay from SCLK launch edge to MISO data valid.
372   * @param eff_clk Effective clock frequency (in Hz) from `spi_get_actual_clock()`.
373   * @param dummy_o Address of dummy bits used output. Set to NULL if not needed.
374   * @param cycles_remain_o Address of cycles remaining (after dummy bits are used) output.
375   *         - -1 If too many cycles remaining, suggest to compensate half a clock.
376   *         - 0 If no remaining cycles or dummy bits are not used.
377   *         - positive value: cycles suggest to compensate.
378   *
379   * @note If **dummy_o* is not zero, it means dummy bits should be applied in half duplex mode, and full duplex mode may not work.
380   */
381 void spi_get_timing(bool gpio_is_used, int input_delay_ns, int eff_clk, int *dummy_o, int *cycles_remain_o);
382 
383 /**
384   * @brief Get the frequency limit of current configurations.
385   *         SPI master working at this limit is OK, while above the limit, full duplex mode and DMA will not work,
386   *         and dummy bits will be aplied in the half duplex mode.
387   *
388   * @param gpio_is_used True if using GPIO matrix, or False if native pins are used.
389   * @param input_delay_ns Input delay from SCLK launch edge to MISO data valid.
390   * @return Frequency limit of current configurations.
391   */
392 int spi_get_freq_limit(bool gpio_is_used, int input_delay_ns);
393 
394 /**
395  * @brief Get max length (in bytes) of one transaction
396  *
397  * @param       host_id    SPI peripheral
398  * @param[out]  max_bytes  Max length of one transaction, in bytes
399  *
400  * @return
401  *        - ESP_OK:               On success
402  *        - ESP_ERR_INVALID_ARG:  Invalid argument
403  */
404 esp_err_t spi_bus_get_max_transaction_len(spi_host_device_t host_id, size_t *max_bytes);
405 
406 #ifdef __cplusplus
407 }
408 #endif
409