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