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