1 /*
2  * Copyright (c) 2015 - 2025, Nordic Semiconductor ASA
3  * All rights reserved.
4  *
5  * SPDX-License-Identifier: BSD-3-Clause
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright notice, this
11  *    list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the copyright holder nor the names of its
18  *    contributors may be used to endorse or promote products derived from this
19  *    software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #ifndef NRFX_TWIM_H__
35 #define NRFX_TWIM_H__
36 
37 #include <nrfx.h>
38 #include <nrfx_twi_twim.h>
39 #include <haly/nrfy_twim.h>
40 
41 #ifdef __cplusplus
42 extern "C" {
43 #endif
44 
45 /**
46  * @defgroup nrfx_twim TWIM driver
47  * @{
48  * @ingroup nrf_twim
49  * @brief   Two Wire Interface Master with EasyDMA (TWIM) peripheral driver.
50  */
51 
52 /** @brief Structure for the TWIM driver instance. */
53 typedef struct
54 {
55     NRF_TWIM_Type * p_twim;       ///< Pointer to a structure with TWIM registers.
56     uint8_t         drv_inst_idx; ///< Index of the driver instance. For internal use only.
57 } nrfx_twim_t;
58 
59 /** @brief Macro for creating a TWIM driver instance. */
60 #define NRFX_TWIM_INSTANCE(id)                               \
61 {                                                            \
62     .p_twim       = NRFX_CONCAT(NRF_, TWIM, id),             \
63     .drv_inst_idx = NRFX_CONCAT(NRFX_TWIM, id, _INST_IDX),   \
64 }
65 
66 #ifndef __NRFX_DOXYGEN__
67 enum {
68     /* List all enabled driver instances (in the format NRFX_\<instance_name\>_INST_IDX). */
69     NRFX_INSTANCE_ENUM_LIST(TWIM)
70     NRFX_TWIM_ENABLED_COUNT
71 };
72 #endif
73 
74 /** @brief Structure for the TWIM driver instance configuration. */
75 typedef struct
76 {
77     uint32_t             scl_pin;            ///< SCL pin number.
78     uint32_t             sda_pin;            ///< SDA pin number.
79     nrf_twim_frequency_t frequency;          ///< TWIM frequency.
80     uint8_t              interrupt_priority; ///< Interrupt priority.
81     bool                 hold_bus_uninit;    ///< Hold pull up state on GPIO pins after uninit.
82     bool                 skip_gpio_cfg;      ///< Skip GPIO configuration of pins.
83                                              /**< When set to true, the driver does not modify
84                                               *   any GPIO parameters of the used pins. Those
85                                               *   parameters are supposed to be configured
86                                               *   externally before the driver is initialized. */
87     bool                 skip_psel_cfg;      ///< Skip pin selection configuration.
88                                              /**< When set to true, the driver does not modify
89                                               *   pin select registers in the peripheral.
90                                               *   Those registers are supposed to be set up
91                                               *   externally before the driver is initialized.
92                                               *   @note When both GPIO configuration and pin
93                                               *   selection are to be skipped, the structure
94                                               *   fields that specify pins can be omitted,
95                                               *   as they are ignored anyway. */
96 } nrfx_twim_config_t;
97 
98 /**
99  * @brief TWIM driver default configuration.
100  *
101  * This configuration sets up TWIM with the following options:
102  * - clock frequency: 100 kHz
103  * - disable bus holding after uninit
104  *
105  * @param[in] _pin_scl SCL pin.
106  * @param[in] _pin_sda SDA pin.
107  */
108 #define NRFX_TWIM_DEFAULT_CONFIG(_pin_scl, _pin_sda)             \
109 {                                                                \
110     .scl_pin            = _pin_scl,                              \
111     .sda_pin            = _pin_sda,                              \
112     .frequency          = NRF_TWIM_FREQ_100K,                    \
113     .interrupt_priority = NRFX_TWIM_DEFAULT_CONFIG_IRQ_PRIORITY, \
114     .hold_bus_uninit    = false,                                 \
115 }
116 
117 /** @brief Flag indicating that TX buffer address will be incremented after the transfer. */
118 #define NRFX_TWIM_FLAG_TX_POSTINC             (1UL << 0)
119 /** @brief Flag indicating that RX buffer address will be incremented after the transfer. */
120 #define NRFX_TWIM_FLAG_RX_POSTINC             (1UL << 1)
121 /** @brief Flag indicating that the interrupt after each transfer will be suppressed, and the event handler will not be called. */
122 #define NRFX_TWIM_FLAG_NO_XFER_EVT_HANDLER    (1UL << 2)
123 /** @brief Flag indicating that the transfer will be set up, but not started. */
124 #define NRFX_TWIM_FLAG_HOLD_XFER              (1UL << 3)
125 /** @brief Flag indicating that the transfer will be executed multiple times. */
126 #define NRFX_TWIM_FLAG_REPEATED_XFER          (1UL << 4)
127 /** @brief Flag indicating that the TX transfer will not end with a stop condition. */
128 #define NRFX_TWIM_FLAG_TX_NO_STOP             (1UL << 5)
129 /** @brief Flag indicating that checks for spurious STOP condition will not be performed. */
130 #define NRFX_TWIM_FLAG_NO_SPURIOUS_STOP_CHECK (1UL << 6)
131 
132 /** @brief TWIM driver event types. */
133 typedef enum
134 {
135     NRFX_TWIM_EVT_DONE,         ///< Transfer completed event.
136     NRFX_TWIM_EVT_ADDRESS_NACK, ///< Error event: NACK received after sending the address.
137     NRFX_TWIM_EVT_DATA_NACK,    ///< Error event: NACK received after sending a data byte.
138     NRFX_TWIM_EVT_OVERRUN,      ///< Error event: The unread data is replaced by new data.
139     NRFX_TWIM_EVT_BUS_ERROR     ///< Error event: An unexpected transition occurred on the bus.
140 } nrfx_twim_evt_type_t;
141 
142 /** @brief TWIM driver transfer types. */
143 typedef enum
144 {
145     NRFX_TWIM_XFER_TX,   ///< TX transfer.
146     NRFX_TWIM_XFER_RX,   ///< RX transfer.
147     NRFX_TWIM_XFER_TXRX, ///< TX transfer followed by RX transfer with repeated start.
148     NRFX_TWIM_XFER_TXTX  ///< TX transfer followed by TX transfer with repeated start.
149 } nrfx_twim_xfer_type_t;
150 
151 /** @brief Structure for a TWIM transfer descriptor. */
152 typedef struct
153 {
154     nrfx_twim_xfer_type_t type;             ///< Type of transfer.
155     uint8_t               address;          ///< Slave address.
156     size_t                primary_length;   ///< Number of bytes transferred.
157     size_t                secondary_length; ///< Number of bytes transferred.
158     uint8_t *             p_primary_buf;    ///< Pointer to transferred data.
159     uint8_t *             p_secondary_buf;  ///< Pointer to transferred data.
160 } nrfx_twim_xfer_desc_t;
161 
162 /** @brief Macro for setting the transfer descriptor. */
163 #define NRFX_TWIM_XFER_DESC(transfer, addr, p_buf1, buf_len1, p_buf2, buf_len2) \
164 {                                                                               \
165     .type             = (transfer),                                             \
166     .address          = (addr),                                                 \
167     .primary_length   = (buf_len1),                                             \
168     .secondary_length = (buf_len2),                                             \
169     .p_primary_buf    = (p_buf1),                                               \
170     .p_secondary_buf  = (p_buf2)                                                \
171 }
172 
173 /** @brief Macro for setting the TX transfer descriptor. */
174 #define NRFX_TWIM_XFER_DESC_TX(addr, p_data, length) \
175         NRFX_TWIM_XFER_DESC(NRFX_TWIM_XFER_TX, addr, p_data, length, NULL, 0)
176 
177 /** @brief Macro for setting the RX transfer descriptor. */
178 #define NRFX_TWIM_XFER_DESC_RX(addr, p_data, length) \
179         NRFX_TWIM_XFER_DESC(NRFX_TWIM_XFER_RX, addr, p_data, length, NULL, 0)
180 
181 /** @brief Macro for setting the TX-RX transfer descriptor. */
182 #define NRFX_TWIM_XFER_DESC_TXRX(addr, p_tx, tx_len, p_rx, rx_len) \
183         NRFX_TWIM_XFER_DESC(NRFX_TWIM_XFER_TXRX, addr, p_tx, tx_len, p_rx, rx_len)
184 
185 /** @brief Macro for setting the TX-TX transfer descriptor. */
186 #define NRFX_TWIM_XFER_DESC_TXTX(addr, p_tx, tx_len, p_tx2, tx_len2) \
187         NRFX_TWIM_XFER_DESC(NRFX_TWIM_XFER_TXTX, addr, p_tx, tx_len, p_tx2, tx_len2)
188 
189 /** @brief Structure for a TWIM event. */
190 typedef struct
191 {
192     nrfx_twim_evt_type_t  type;      ///< Event type.
193     nrfx_twim_xfer_desc_t xfer_desc; ///< Transfer details.
194 } nrfx_twim_evt_t;
195 
196 /** @brief TWIM event handler prototype. */
197 typedef void (* nrfx_twim_evt_handler_t)(nrfx_twim_evt_t const * p_event,
198                                          void *                  p_context);
199 
200 /**
201  * @brief Function for initializing the TWIM driver instance.
202  *
203  * @param[in] p_instance    Pointer to the driver instance structure.
204  * @param[in] p_config      Pointer to the structure with the initial configuration.
205  * @param[in] event_handler Event handler provided by the user. If NULL, blocking mode is enabled.
206  * @param[in] p_context     Context passed to event handler.
207  *
208  * @warning On nRF5340, 1 MHz setting is supported only on the dedicated pins. See the chapter
209  *          <a href=@nRF5340pinAssignmentsURL>Pin assignments</a> in the Product Specification.
210  *
211  * @retval NRFX_SUCCESS             Initialization was successful.
212  * @retval NRFX_ERROR_ALREADY       The driver is already initialized.
213  * @retval NRFX_ERROR_INVALID_STATE The driver is already initialized.
214  *                                  Deprecated - use @ref NRFX_ERROR_ALREADY instead.
215  * @retval NRFX_ERROR_INVALID_PARAM Requested frequency is not available on the specified pins.
216  * @retval NRFX_ERROR_BUSY          Some other peripheral with the same
217  *                                  instance ID is already in use. This is
218  *                                  possible only if @ref nrfx_prs module
219  *                                  is enabled.
220  */
221 nrfx_err_t nrfx_twim_init(nrfx_twim_t const *        p_instance,
222                           nrfx_twim_config_t const * p_config,
223                           nrfx_twim_evt_handler_t    event_handler,
224                           void *                     p_context);
225 
226 /**
227  * @brief Function for reconfiguring the TWIM instance.
228  *
229  * @param[in] p_instance Pointer to the driver instance structure.
230  * @param[in] p_config   Pointer to the structure with the configuration.
231  *
232  * @retval NRFX_SUCCESS             Reconfiguration was successful.
233  * @retval NRFX_ERROR_BUSY          The driver is during transaction.
234  * @retval NRFX_ERROR_INVALID_STATE The driver is uninitialized.
235  * @retval NRFX_ERROR_INVALID_PARAM Requested frequency is not available on the specified pins.
236  */
237 nrfx_err_t nrfx_twim_reconfigure(nrfx_twim_t const *        p_instance,
238                                  nrfx_twim_config_t const * p_config);
239 
240 /**
241  * @brief Function for uninitializing the TWIM instance.
242  *
243  * @param[in] p_instance Pointer to the driver instance structure.
244  */
245 void nrfx_twim_uninit(nrfx_twim_t const * p_instance);
246 
247 /**
248  * @brief Function for checking if the TWIM driver instance is initialized.
249  *
250  * @param[in] p_instance Pointer to the driver instance structure.
251  *
252  * @retval true  Instance is already initialized.
253  * @retval false Instance is not initialized.
254  */
255 bool nrfx_twim_init_check(nrfx_twim_t const * p_instance);
256 
257 /**
258  * @brief Function for enabling the TWIM instance.
259  *
260  * @param[in] p_instance Pointer to the driver instance structure.
261  */
262 void nrfx_twim_enable(nrfx_twim_t const * p_instance);
263 
264 /**
265  * @brief Function for disabling the TWIM instance.
266  *
267  * @param[in] p_instance Pointer to the driver instance structure.
268  */
269 void nrfx_twim_disable(nrfx_twim_t const * p_instance);
270 
271 /**
272  * @brief Function for performing a TWIM transfer.
273  *
274  * The following transfer types can be configured (@ref nrfx_twim_xfer_desc_t.type):
275  * - @ref NRFX_TWIM_XFER_TXRX - Write operation followed by a read operation (without STOP condition in between).
276  * - @ref NRFX_TWIM_XFER_TXTX - Write operation followed by a write operation (without STOP condition in between).
277  * - @ref NRFX_TWIM_XFER_TX - Write operation (with or without STOP condition).
278  * - @ref NRFX_TWIM_XFER_RX - Read operation  (with STOP condition).
279  *
280  * @note TX-RX and TX-TX transfers are supported only in non-blocking mode.
281  *
282  * Additional options are provided using the flags parameter:
283  * - @ref NRFX_TWIM_FLAG_TX_POSTINC and @ref NRFX_TWIM_FLAG_RX_POSTINC - Post-incrementation of buffer addresses.
284  * - @ref NRFX_TWIM_FLAG_NO_XFER_EVT_HANDLER - No user event handler after the transfer completion. In most cases, this also means no interrupt at the end of the transfer.
285  * - @ref NRFX_TWIM_FLAG_HOLD_XFER - Driver is not starting the transfer. Use this flag if the transfer is triggered externally by PPI.
286  *   Use @ref nrfx_twim_start_task_address_get to get the address of the start task.
287  * - @ref NRFX_TWIM_FLAG_REPEATED_XFER - Prepare for repeated transfers. You can set up a number of transfers that will be triggered externally (for example by PPI).
288  *   An example is a TXRX transfer with the options @ref NRFX_TWIM_FLAG_RX_POSTINC, @ref NRFX_TWIM_FLAG_NO_XFER_EVT_HANDLER, and @ref NRFX_TWIM_FLAG_REPEATED_XFER.
289  *   After the transfer is set up, a set of transfers can be triggered by PPI that will read, for example, the same register of an
290  *   external component and put it into a RAM buffer without any interrupts. @ref nrfx_twim_stopped_event_address_get can be used to get the
291  *   address of the STOPPED event, which can be used to count the number of transfers. If @ref NRFX_TWIM_FLAG_REPEATED_XFER is used,
292  *   the driver does not set the driver instance into busy state, so you must ensure that the next transfers are set up
293  *   when TWIM is not active.
294  * - @ref NRFX_TWIM_FLAG_TX_NO_STOP - No stop condition after the TX transfer.
295  * - @ref NRFX_TWIM_FLAG_NO_SPURIOUS_STOP_CHECK - Checks for spurious STOP conditions are disabled.
296  *        Used together with @ref NRFX_TWIM_FLAG_NO_XFER_EVT_HANDLER can result in lower power consumption
297  *        when transfers are triggered externally and CPU is sleeping.
298  *        Use only with I2C standard-compliant slave devices.
299  *
300  * @note
301  * Some flag combinations are invalid:
302  * - @ref NRFX_TWIM_FLAG_TX_NO_STOP with @ref nrfx_twim_xfer_desc_t.type different than @ref NRFX_TWIM_XFER_TX
303  * - @ref NRFX_TWIM_FLAG_REPEATED_XFER with @ref nrfx_twim_xfer_desc_t.type set to @ref NRFX_TWIM_XFER_TXTX
304  *
305  * If @ref nrfx_twim_xfer_desc_t.type is set to @ref NRFX_TWIM_XFER_TX and the @ref NRFX_TWIM_FLAG_TX_NO_STOP and @ref NRFX_TWIM_FLAG_REPEATED_XFER
306  * flags are set, two tasks must be used to trigger a transfer: TASKS_RESUME followed by TASKS_STARTTX. If no stop condition is generated,
307  * TWIM is in SUSPENDED state. Therefore, it must be resumed before the transfer can be started.
308  *
309  * @note Peripherals using EasyDMA (including TWIM) require the transfer buffers
310  *       to be placed in the Data RAM region. If this condition is not met,
311  *       this function will fail with the error code NRFX_ERROR_INVALID_ADDR.
312  *
313  * @param[in] p_instance  Pointer to the driver instance structure.
314  * @param[in] p_xfer_desc Pointer to the transfer descriptor.
315  * @param[in] flags       Transfer options (0 for default settings).
316  *
317  * @retval NRFX_SUCCESS                   The procedure is successful.
318  * @retval NRFX_ERROR_BUSY                The driver is not ready for a new transfer.
319  * @retval NRFX_ERROR_NOT_SUPPORTED       The provided parameters are not supported.
320  * @retval NRFX_ERROR_INTERNAL            An unexpected transition occurred on the bus.
321  * @retval NRFX_ERROR_INVALID_ADDR        The provided buffers are not placed in the Data RAM region.
322  * @retval NRFX_ERROR_DRV_TWI_ERR_OVERRUN The unread data is replaced by new data.
323  * @retval NRFX_ERROR_DRV_TWI_ERR_ANACK   NACK is received after sending the address.
324  * @retval NRFX_ERROR_DRV_TWI_ERR_DNACK   NACK is received after sending a data byte.
325  */
326 nrfx_err_t nrfx_twim_xfer(nrfx_twim_t           const * p_instance,
327                           nrfx_twim_xfer_desc_t const * p_xfer_desc,
328                           uint32_t                      flags);
329 
330 /**
331  * @brief Function for checking the TWIM driver state.
332  *
333  * @param[in] p_instance TWIM instance.
334  *
335  * @retval true  The TWIM driver is currently busy performing a transfer.
336  * @retval false The TWIM driver is ready for a new transfer.
337  */
338 bool nrfx_twim_is_busy(nrfx_twim_t const * p_instance);
339 
340 
341 /**
342  * @brief Function for returning the address of a TWIM start task.
343  *
344  * This function is to be used if @ref nrfx_twim_xfer was called with the flag @ref NRFX_TWIM_FLAG_HOLD_XFER.
345  * In that case, the transfer is not started by the driver, but it must be started externally by PPI.
346  *
347  * @param[in] p_instance Pointer to the driver instance structure.
348  * @param[in] xfer_type  Transfer type used in the last call of the @ref nrfx_twim_xfer function.
349  *
350  * @return Start task address (TX or RX) depending on the value of xfer_type.
351  */
352 uint32_t nrfx_twim_start_task_address_get(nrfx_twim_t const *   p_instance,
353                                           nrfx_twim_xfer_type_t xfer_type);
354 
355 /**
356  * @brief Function for returning the address of a STOPPED TWIM event.
357  *
358  * A STOPPED event can be used to detect the end of a transfer if the @ref NRFX_TWIM_FLAG_NO_XFER_EVT_HANDLER
359  * option is used.
360  *
361  * @param[in] p_instance Pointer to the driver instance structure.
362  *
363  * @return STOPPED event address.
364  */
365 uint32_t nrfx_twim_stopped_event_address_get(nrfx_twim_t const * p_instance);
366 
367 /**
368  * @brief Function for recovering the bus.
369  *
370  * This function checks if the bus is not stuck because of a slave holding the SDA line in the low state,
371  * and if needed it performs required number of pulses on the SCL line to make the slave release the SDA line.
372  * Finally, the function generates a STOP condition on the bus to put it into a known state.
373  *
374  * @note This function can be used only if the TWIM driver is uninitialized.
375  *
376  * @param[in] scl_pin SCL pin number.
377  * @param[in] sda_pin SDA pin number.
378  *
379  * @retval NRFX_SUCCESS        Bus recovery was successful.
380  * @retval NRFX_ERROR_INTERNAL Bus recovery failed.
381  */
382 NRFX_STATIC_INLINE nrfx_err_t nrfx_twim_bus_recover(uint32_t scl_pin, uint32_t sda_pin);
383 
384 #ifndef NRFX_DECLARE_ONLY
nrfx_twim_bus_recover(uint32_t scl_pin,uint32_t sda_pin)385 NRFX_STATIC_INLINE nrfx_err_t nrfx_twim_bus_recover(uint32_t scl_pin, uint32_t sda_pin)
386 {
387     return nrfx_twi_twim_bus_recover(scl_pin, sda_pin);
388 }
389 #endif
390 
391 /**
392  * @brief Macro returning TWIM interrupt handler.
393  *
394  * param[in] idx TWIM index.
395  *
396  * @return Interrupt handler.
397  */
398 #define NRFX_TWIM_INST_HANDLER_GET(idx) NRFX_CONCAT_3(nrfx_twim_, idx, _irq_handler)
399 
400 /** @} */
401 
402 /*
403  * Declare interrupt handlers for all enabled driver instances in the following format:
404  * nrfx_\<periph_name\>_\<idx\>_irq_handler (for example, nrfx_twim_0_irq_handler).
405  *
406  * A specific interrupt handler for the driver instance can be retrieved by using
407  * the NRFX_TWIM_INST_HANDLER_GET macro.
408  *
409  * Here is a sample of using the NRFX_TWIM_INST_HANDLER_GET macro to map an interrupt handler
410  * in a Zephyr application:
411  *
412  * IRQ_CONNECT(NRFX_IRQ_NUMBER_GET(NRF_TWIM_INST_GET(\<instance_index\>)), \<priority\>,
413  *             NRFX_TWIM_INST_HANDLER_GET(\<instance_index\>), 0, 0);
414  */
415 NRFX_INSTANCE_IRQ_HANDLERS_DECLARE(TWIM, twim)
416 
417 
418 #ifdef __cplusplus
419 }
420 #endif
421 
422 #endif // NRFX_TWIM_H__
423