1 /*
2  * Copyright 2022 NXP
3  * All rights reserved.
4  *
5  * SPDX-License-Identifier: BSD-3-Clause
6  */
7 #ifndef FSL_LPI2C_H_
8 #define FSL_LPI2C_H_
9 
10 #include <stddef.h>
11 #include "fsl_device_registers.h"
12 #include "fsl_common.h"
13 #include "fsl_lpflexcomm.h"
14 
15 /*******************************************************************************
16  * Definitions
17  ******************************************************************************/
18 
19 /*!
20  * @addtogroup lpi2c
21  * @{
22  */
23 
24 /*! @name Driver version */
25 /*@{*/
26 /*! @brief LPI2C driver version. */
27 #define FSL_LPI2C_DRIVER_VERSION (MAKE_VERSION(2, 2, 2))
28 /*@}*/
29 
30 /*! @brief Retry times for waiting flag. */
31 #ifndef I2C_RETRY_TIMES
32 #define I2C_RETRY_TIMES 0U /* Define to zero means keep waiting until the flag is assert/deassert. */
33 #endif
34 
35 /*! @brief LPI2C status return codes. */
36 enum
37 {
38     kStatus_LPI2C_Busy = MAKE_STATUS(kStatusGroup_LPI2C, 0), /*!< The master is already performing a transfer. */
39     kStatus_LPI2C_Idle = MAKE_STATUS(kStatusGroup_LPI2C, 1), /*!< The slave driver is idle. */
40     kStatus_LPI2C_Nak  = MAKE_STATUS(kStatusGroup_LPI2C, 2), /*!< The slave device sent a NAK in response to a byte. */
41     kStatus_LPI2C_FifoError       = MAKE_STATUS(kStatusGroup_LPI2C, 3), /*!< FIFO under run or overrun. */
42     kStatus_LPI2C_BitError        = MAKE_STATUS(kStatusGroup_LPI2C, 4), /*!< Transferred bit was not seen on the bus. */
43     kStatus_LPI2C_ArbitrationLost = MAKE_STATUS(kStatusGroup_LPI2C, 5), /*!< Arbitration lost error. */
44     kStatus_LPI2C_PinLowTimeout =
45         MAKE_STATUS(kStatusGroup_LPI2C, 6), /*!< SCL or SDA were held low longer than the timeout. */
46     kStatus_LPI2C_NoTransferInProgress =
47         MAKE_STATUS(kStatusGroup_LPI2C, 7), /*!< Attempt to abort a transfer when one is not in progress. */
48     kStatus_LPI2C_DmaRequestFail = MAKE_STATUS(kStatusGroup_LPI2C, 8), /*!< DMA request failed. */
49     kStatus_LPI2C_Timeout        = MAKE_STATUS(kStatusGroup_LPI2C, 9), /*!< Timeout polling status flags. */
50 };
51 
52 /*! @} */
53 
54 /*!
55  * @addtogroup lpi2c_master_driver
56  * @{
57  */
58 
59 /*!
60  * @brief LPI2C master peripheral flags.
61  *
62  * The following status register flags can be cleared:
63  * - #kLPI2C_MasterEndOfPacketFlag
64  * - #kLPI2C_MasterStopDetectFlag
65  * - #kLPI2C_MasterNackDetectFlag
66  * - #kLPI2C_MasterArbitrationLostFlag
67  * - #kLPI2C_MasterFifoErrFlag
68  * - #kLPI2C_MasterPinLowTimeoutFlag
69  * - #kLPI2C_MasterDataMatchFlag
70  *
71  * All flags except #kLPI2C_MasterBusyFlag and #kLPI2C_MasterBusBusyFlag can be enabled as
72  * interrupts.
73  *
74  * @note These enums are meant to be OR'd together to form a bit mask.
75  */
76 enum _lpi2c_master_flags
77 {
78     kLPI2C_MasterTxReadyFlag         = LPI2C_MSR_TDF_MASK,  /*!< Transmit data flag */
79     kLPI2C_MasterRxReadyFlag         = LPI2C_MSR_RDF_MASK,  /*!< Receive data flag */
80     kLPI2C_MasterEndOfPacketFlag     = LPI2C_MSR_EPF_MASK,  /*!< End Packet flag */
81     kLPI2C_MasterStopDetectFlag      = LPI2C_MSR_SDF_MASK,  /*!< Stop detect flag */
82     kLPI2C_MasterNackDetectFlag      = LPI2C_MSR_NDF_MASK,  /*!< NACK detect flag */
83     kLPI2C_MasterArbitrationLostFlag = LPI2C_MSR_ALF_MASK,  /*!< Arbitration lost flag */
84     kLPI2C_MasterFifoErrFlag         = LPI2C_MSR_FEF_MASK,  /*!< FIFO error flag */
85     kLPI2C_MasterPinLowTimeoutFlag   = LPI2C_MSR_PLTF_MASK, /*!< Pin low timeout flag */
86     kLPI2C_MasterDataMatchFlag       = LPI2C_MSR_DMF_MASK,  /*!< Data match flag */
87     kLPI2C_MasterBusyFlag            = LPI2C_MSR_MBF_MASK,  /*!< Master busy flag */
88     kLPI2C_MasterBusBusyFlag         = LPI2C_MSR_BBF_MASK,  /*!< Bus busy flag */
89 
90     /*! All flags which are cleared by the driver upon starting a transfer. */
91     kLPI2C_MasterClearFlags = kLPI2C_MasterEndOfPacketFlag | kLPI2C_MasterStopDetectFlag | kLPI2C_MasterNackDetectFlag |
92                               kLPI2C_MasterArbitrationLostFlag | kLPI2C_MasterFifoErrFlag |
93                               kLPI2C_MasterPinLowTimeoutFlag | kLPI2C_MasterDataMatchFlag,
94     /*! IRQ sources enabled by the non-blocking transactional API. */
95     kLPI2C_MasterIrqFlags = kLPI2C_MasterArbitrationLostFlag | kLPI2C_MasterTxReadyFlag | kLPI2C_MasterRxReadyFlag |
96                             kLPI2C_MasterStopDetectFlag | kLPI2C_MasterNackDetectFlag | kLPI2C_MasterPinLowTimeoutFlag |
97                             kLPI2C_MasterFifoErrFlag,
98     /*! Errors to check for. */
99     kLPI2C_MasterErrorFlags = kLPI2C_MasterNackDetectFlag | kLPI2C_MasterArbitrationLostFlag |
100                               kLPI2C_MasterFifoErrFlag | kLPI2C_MasterPinLowTimeoutFlag
101 };
102 
103 /*! @brief Direction of master and slave transfers. */
104 typedef enum _lpi2c_direction
105 {
106     kLPI2C_Write = 0U, /*!< Master transmit. */
107     kLPI2C_Read  = 1U  /*!< Master receive. */
108 } lpi2c_direction_t;
109 
110 /*! @brief LPI2C pin configuration. */
111 typedef enum _lpi2c_master_pin_config
112 {
113     kLPI2C_2PinOpenDrain  = 0x0U, /*!< LPI2C Configured for 2-pin open drain mode */
114     kLPI2C_2PinOutputOnly = 0x1U, /*!< LPI2C Configured for 2-pin output only mode (ultra-fast mode) */
115     kLPI2C_2PinPushPull   = 0x2U, /*!< LPI2C Configured for 2-pin push-pull mode */
116     kLPI2C_4PinPushPull   = 0x3U, /*!< LPI2C Configured for 4-pin push-pull mode */
117     kLPI2C_2PinOpenDrainWithSeparateSlave =
118         0x4U, /*!< LPI2C Configured for 2-pin open drain mode with separate LPI2C slave */
119     kLPI2C_2PinOutputOnlyWithSeparateSlave =
120         0x5U, /*!< LPI2C Configured for 2-pin output only mode(ultra-fast mode) with separate LPI2C slave */
121     kLPI2C_2PinPushPullWithSeparateSlave =
122         0x6U, /*!< LPI2C Configured for 2-pin push-pull mode with separate LPI2C slave */
123     kLPI2C_4PinPushPullWithInvertedOutput = 0x7U /*!< LPI2C Configured for 4-pin push-pull mode(inverted outputs) */
124 } lpi2c_master_pin_config_t;
125 
126 /*! @brief LPI2C master host request selection. */
127 typedef enum _lpi2c_host_request_source
128 {
129     kLPI2C_HostRequestExternalPin  = 0x0U, /*!< Select the LPI2C_HREQ pin as the host request input */
130     kLPI2C_HostRequestInputTrigger = 0x1U, /*!< Select the input trigger as the host request input */
131 } lpi2c_host_request_source_t;
132 
133 /*! @brief LPI2C master host request pin polarity configuration. */
134 typedef enum _lpi2c_host_request_polarity
135 {
136     kLPI2C_HostRequestPinActiveLow  = 0x0U, /*!< Configure the LPI2C_HREQ pin active low */
137     kLPI2C_HostRequestPinActiveHigh = 0x1U  /*!< Configure the LPI2C_HREQ pin active high */
138 } lpi2c_host_request_polarity_t;
139 
140 /*!
141  * @brief Structure with settings to initialize the LPI2C master module.
142  *
143  * This structure holds configuration settings for the LPI2C peripheral. To initialize this
144  * structure to reasonable defaults, call the LPI2C_MasterGetDefaultConfig() function and
145  * pass a pointer to your configuration structure instance.
146  *
147  * The configuration structure can be made constant so it resides in flash.
148  */
149 typedef struct _lpi2c_master_config
150 {
151     bool enableMaster;                   /*!< Whether to enable master mode. */
152     bool enableDoze;                     /*!< Whether master is enabled in doze mode. */
153     bool debugEnable;                    /*!< Enable transfers to continue when halted in debug mode. */
154     bool ignoreAck;                      /*!< Whether to ignore ACK/NACK. */
155     lpi2c_master_pin_config_t pinConfig; /*!< The pin configuration option. */
156     uint32_t baudRate_Hz;                /*!< Desired baud rate in Hertz. */
157     uint32_t busIdleTimeout_ns;          /*!< Bus idle timeout in nanoseconds. Set to 0 to disable. */
158     uint32_t pinLowTimeout_ns;           /*!< Pin low timeout in nanoseconds. Set to 0 to disable. */
159     uint8_t sdaGlitchFilterWidth_ns;     /*!< Width in nanoseconds of glitch filter on SDA pin. Set to 0 to disable. */
160     uint8_t sclGlitchFilterWidth_ns;     /*!< Width in nanoseconds of glitch filter on SCL pin. Set to 0 to disable. */
161     struct
162     {
163         bool enable;                            /*!< Enable host request. */
164         lpi2c_host_request_source_t source;     /*!< Host request source. */
165         lpi2c_host_request_polarity_t polarity; /*!< Host request pin polarity. */
166     } hostRequest;                              /*!< Host request options. */
167 } lpi2c_master_config_t;
168 
169 /*! @brief LPI2C master data match configuration modes. */
170 typedef enum _lpi2c_data_match_config_mode
171 {
172     kLPI2C_MatchDisabled       = 0x0U, /*!< LPI2C Match Disabled */
173     kLPI2C_1stWordEqualsM0OrM1 = 0x2U, /*!< LPI2C Match Enabled and 1st data word equals MATCH0 OR MATCH1 */
174     kLPI2C_AnyWordEqualsM0OrM1 = 0x3U, /*!< LPI2C Match Enabled and any data word equals MATCH0 OR MATCH1 */
175     kLPI2C_1stWordEqualsM0And2ndWordEqualsM1 =
176         0x4U, /*!< LPI2C Match Enabled and 1st data word equals MATCH0, 2nd data equals MATCH1 */
177     kLPI2C_AnyWordEqualsM0AndNextWordEqualsM1 =
178         0x5U, /*!< LPI2C Match Enabled and any data word equals MATCH0, next data equals MATCH1 */
179     kLPI2C_1stWordAndM1EqualsM0AndM1 =
180         0x6U, /*!< LPI2C Match Enabled and 1st data word and MATCH0 equals MATCH0 and MATCH1 */
181     kLPI2C_AnyWordAndM1EqualsM0AndM1 =
182         0x7U /*!< LPI2C Match Enabled and any data word and MATCH0 equals MATCH0 and MATCH1 */
183 } lpi2c_data_match_config_mode_t;
184 
185 /*! @brief LPI2C master data match configuration structure. */
186 typedef struct _lpi2c_match_config
187 {
188     lpi2c_data_match_config_mode_t matchMode; /*!< Data match configuration setting. */
189     bool rxDataMatchOnly; /*!< When set to true, received data is ignored until a successful match. */
190     uint32_t match0;      /*!< Match value 0. */
191     uint32_t match1;      /*!< Match value 1. */
192 } lpi2c_data_match_config_t;
193 
194 /* Forward declaration of the transfer descriptor and handle typedefs. */
195 typedef struct _lpi2c_master_transfer lpi2c_master_transfer_t;
196 typedef struct _lpi2c_master_handle lpi2c_master_handle_t;
197 
198 /*!
199  * @brief Master completion callback function pointer type.
200  *
201  * This callback is used only for the non-blocking master transfer API. Specify the callback you wish to use
202  * in the call to LPI2C_MasterTransferCreateHandle().
203  *
204  * @param base The LPI2C peripheral base address.
205  * @param completionStatus Either kStatus_Success or an error code describing how the transfer completed.
206  * @param userData Arbitrary pointer-sized value passed from the application.
207  */
208 typedef void (*lpi2c_master_transfer_callback_t)(LPI2C_Type *base,
209                                                  lpi2c_master_handle_t *handle,
210                                                  status_t completionStatus,
211                                                  void *userData);
212 
213 /*!
214  * @brief Transfer option flags.
215  *
216  * @note These enumerations are intended to be OR'd together to form a bit mask of options for
217  * the #_lpi2c_master_transfer::flags field.
218  */
219 enum _lpi2c_master_transfer_flags
220 {
221     kLPI2C_TransferDefaultFlag       = 0x00U, /*!< Transfer starts with a start signal, stops with a stop signal. */
222     kLPI2C_TransferNoStartFlag       = 0x01U, /*!< Don't send a start condition, address, and sub address */
223     kLPI2C_TransferRepeatedStartFlag = 0x02U, /*!< Send a repeated start condition */
224     kLPI2C_TransferNoStopFlag        = 0x04U, /*!< Don't send a stop condition. */
225 };
226 
227 /*!
228  * @brief Non-blocking transfer descriptor structure.
229  *
230  * This structure is used to pass transaction parameters to the LPI2C_MasterTransferNonBlocking() API.
231  */
232 struct _lpi2c_master_transfer
233 {
234     uint32_t flags;        /*!< Bit mask of options for the transfer. See enumeration #_lpi2c_master_transfer_flags for
235                               available options. Set to 0 or #kLPI2C_TransferDefaultFlag for normal transfers. */
236     uint16_t slaveAddress; /*!< The 7-bit slave address. */
237     lpi2c_direction_t direction; /*!< Either #kLPI2C_Read or #kLPI2C_Write. */
238     uint32_t subaddress;         /*!< Sub address. Transferred MSB first. */
239     size_t subaddressSize;       /*!< Length of sub address to send in bytes. Maximum size is 4 bytes. */
240     void *data;                  /*!< Pointer to data to transfer. */
241     size_t dataSize;             /*!< Number of bytes to transfer. */
242 };
243 
244 /*!
245  * @brief Driver handle for master non-blocking APIs.
246  * @note The contents of this structure are private and subject to change.
247  */
248 struct _lpi2c_master_handle
249 {
250     uint8_t state;                                       /*!< Transfer state machine current state. */
251     uint16_t remainingBytes;                             /*!< Remaining byte count in current state. */
252     uint8_t *buf;                                        /*!< Buffer pointer for current state. */
253     uint16_t commandBuffer[6];                           /*!< LPI2C command sequence. When all 6 command words are used:
254          Start&addr&write[1 word] + subaddr[4 words] + restart&addr&read[1 word] */
255     lpi2c_master_transfer_t transfer;                    /*!< Copy of the current transfer info. */
256     lpi2c_master_transfer_callback_t completionCallback; /*!< Callback function pointer. */
257     void *userData;                                      /*!< Application data passed to callback. */
258 };
259 
260 /*! @brief Typedef for master interrupt handler, used internally for LPI2C master interrupt and EDMA transactional APIs.
261  */
262 typedef void (*lpi2c_master_isr_t)(uint32_t instance, void *handle);
263 
264 /*! @} */
265 
266 /*!
267  * @addtogroup lpi2c_slave_driver
268  * @{
269  */
270 
271 /*!
272  * @brief LPI2C slave peripheral flags.
273  *
274  * The following status register flags can be cleared:
275  * - #kLPI2C_SlaveRepeatedStartDetectFlag
276  * - #kLPI2C_SlaveStopDetectFlag
277  * - #kLPI2C_SlaveBitErrFlag
278  * - #kLPI2C_SlaveFifoErrFlag
279  *
280  * All flags except #kLPI2C_SlaveBusyFlag and #kLPI2C_SlaveBusBusyFlag can be enabled as
281  * interrupts.
282  *
283  * @note These enumerations are meant to be OR'd together to form a bit mask.
284  */
285 enum _lpi2c_slave_flags
286 {
287     kLPI2C_SlaveTxReadyFlag             = LPI2C_SSR_TDF_MASK,  /*!< Transmit data flag */
288     kLPI2C_SlaveRxReadyFlag             = LPI2C_SSR_RDF_MASK,  /*!< Receive data flag */
289     kLPI2C_SlaveAddressValidFlag        = LPI2C_SSR_AVF_MASK,  /*!< Address valid flag */
290     kLPI2C_SlaveTransmitAckFlag         = LPI2C_SSR_TAF_MASK,  /*!< Transmit ACK flag */
291     kLPI2C_SlaveRepeatedStartDetectFlag = LPI2C_SSR_RSF_MASK,  /*!< Repeated start detect flag */
292     kLPI2C_SlaveStopDetectFlag          = LPI2C_SSR_SDF_MASK,  /*!< Stop detect flag */
293     kLPI2C_SlaveBitErrFlag              = LPI2C_SSR_BEF_MASK,  /*!< Bit error flag */
294     kLPI2C_SlaveFifoErrFlag             = LPI2C_SSR_FEF_MASK,  /*!< FIFO error flag */
295     kLPI2C_SlaveAddressMatch0Flag       = LPI2C_SSR_AM0F_MASK, /*!< Address match 0 flag */
296     kLPI2C_SlaveAddressMatch1Flag       = LPI2C_SSR_AM1F_MASK, /*!< Address match 1 flag */
297     kLPI2C_SlaveGeneralCallFlag         = LPI2C_SSR_GCF_MASK,  /*!< General call flag */
298     kLPI2C_SlaveBusyFlag                = LPI2C_SSR_SBF_MASK,  /*!< Master busy flag */
299     kLPI2C_SlaveBusBusyFlag             = LPI2C_SSR_BBF_MASK,  /*!< Bus busy flag */
300     /*! All flags which are cleared by the driver upon starting a transfer. */
301     kLPI2C_SlaveClearFlags = kLPI2C_SlaveRepeatedStartDetectFlag | kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveBitErrFlag |
302                              kLPI2C_SlaveFifoErrFlag,
303     /*! IRQ sources enabled by the non-blocking transactional API. */
304     kLPI2C_SlaveIrqFlags = kLPI2C_SlaveTxReadyFlag | kLPI2C_SlaveRxReadyFlag | kLPI2C_SlaveStopDetectFlag |
305                            kLPI2C_SlaveRepeatedStartDetectFlag | kLPI2C_SlaveFifoErrFlag | kLPI2C_SlaveBitErrFlag |
306                            kLPI2C_SlaveTransmitAckFlag | kLPI2C_SlaveAddressValidFlag,
307     /*! Errors to check for. */
308     kLPI2C_SlaveErrorFlags = kLPI2C_SlaveFifoErrFlag | kLPI2C_SlaveBitErrFlag
309 };
310 
311 /*! @brief LPI2C slave address match options. */
312 typedef enum _lpi2c_slave_address_match
313 {
314     kLPI2C_MatchAddress0                = 0U, /*!< Match only address 0. */
315     kLPI2C_MatchAddress0OrAddress1      = 2U, /*!< Match either address 0 or address 1. */
316     kLPI2C_MatchAddress0ThroughAddress1 = 6U, /*!< Match a range of slave addresses from address 0 through address 1. */
317 } lpi2c_slave_address_match_t;
318 
319 /*!
320  * @brief Structure with settings to initialize the LPI2C slave module.
321  *
322  * This structure holds configuration settings for the LPI2C slave peripheral. To initialize this
323  * structure to reasonable defaults, call the LPI2C_SlaveGetDefaultConfig() function and
324  * pass a pointer to your configuration structure instance.
325  *
326  * The configuration structure can be made constant so it resides in flash.
327  */
328 typedef struct _lpi2c_slave_config
329 {
330     bool enableSlave;                             /*!< Enable slave mode. */
331     uint8_t address0;                             /*!< Slave's 7-bit address. */
332     uint8_t address1;                             /*!< Alternate slave 7-bit address. */
333     lpi2c_slave_address_match_t addressMatchMode; /*!< Address matching options. */
334     bool filterDozeEnable;                        /*!< Enable digital glitch filter in doze mode. */
335     bool filterEnable;                            /*!< Enable digital glitch filter. */
336     bool enableGeneralCall;                       /*!< Enable general call address matching. */
337     struct
338     {
339         bool enableAck;     /*!< Enables SCL clock stretching during slave-transmit address byte(s)
340                                         and slave-receiver address and data byte(s) to allow software to
341                                         write the Transmit ACK Register before the ACK or NACK is transmitted.
342                                         Clock stretching occurs when transmitting the 9th bit. When
343                                         enableAckSCLStall is enabled, there is no need to set either
344                                         enableRxDataSCLStall or enableAddressSCLStall. */
345         bool enableTx;      /*!< Enables SCL clock stretching when the transmit data flag is set
346                                          during a slave-transmit transfer. */
347         bool enableRx;      /*!< Enables SCL clock stretching when receive data flag is set during
348                                          a slave-receive transfer. */
349         bool enableAddress; /*!< Enables SCL clock stretching when the address valid flag is asserted. */
350     } sclStall;
351     bool ignoreAck;                   /*!< Continue transfers after a NACK is detected. */
352     bool enableReceivedAddressRead;   /*!< Enable reading the address received address as the first byte of data. */
353     uint32_t sdaGlitchFilterWidth_ns; /*!< Width in nanoseconds of the digital filter on the SDA signal. Set to 0 to
354                                          disable. */
355     uint32_t sclGlitchFilterWidth_ns; /*!< Width in nanoseconds of the digital filter on the SCL signal. Set to 0 to
356                                          disable. */
357     uint32_t dataValidDelay_ns;       /*!< Width in nanoseconds of the data valid delay. */
358     uint32_t clockHoldTime_ns;        /*!< Width in nanoseconds of the clock hold time. */
359 } lpi2c_slave_config_t;
360 
361 /*!
362  * @brief Set of events sent to the callback for non blocking slave transfers.
363  *
364  * These event enumerations are used for two related purposes. First, a bit mask created by OR'ing together
365  * events is passed to LPI2C_SlaveTransferNonBlocking() in order to specify which events to enable.
366  * Then, when the slave callback is invoked, it is passed the current event through its @a transfer
367  * parameter.
368  *
369  * @note These enumerations are meant to be OR'd together to form a bit mask of events.
370  */
371 typedef enum _lpi2c_slave_transfer_event
372 {
373     kLPI2C_SlaveAddressMatchEvent = 0x01U,  /*!< Received the slave address after a start or repeated start. */
374     kLPI2C_SlaveTransmitEvent     = 0x02U,  /*!< Callback is requested to provide data to transmit
375                                                  (slave-transmitter role). */
376     kLPI2C_SlaveReceiveEvent = 0x04U,       /*!< Callback is requested to provide a buffer in which to place received
377                                                   data (slave-receiver role). */
378     kLPI2C_SlaveTransmitAckEvent   = 0x08U, /*!< Callback needs to either transmit an ACK or NACK.
379               When this event is set, the driver will no longer decide to reply to ack/nack. */
380     kLPI2C_SlaveRepeatedStartEvent = 0x10U, /*!< A repeated start was detected. */
381     kLPI2C_SlaveCompletionEvent    = 0x20U, /*!< A stop was detected, completing the transfer. */
382 
383     /*! Bit mask of all available events. */
384     kLPI2C_SlaveAllEvents = kLPI2C_SlaveAddressMatchEvent | kLPI2C_SlaveTransmitEvent | kLPI2C_SlaveReceiveEvent |
385                             kLPI2C_SlaveTransmitAckEvent | kLPI2C_SlaveRepeatedStartEvent | kLPI2C_SlaveCompletionEvent,
386 } lpi2c_slave_transfer_event_t;
387 
388 /*! @brief LPI2C slave transfer structure */
389 typedef struct _lpi2c_slave_transfer
390 {
391     lpi2c_slave_transfer_event_t event; /*!< Reason the callback is being invoked. */
392     uint8_t receivedAddress;            /*!< Matching address send by master. */
393     uint8_t *data;                      /*!< Transfer buffer */
394     size_t dataSize;                    /*!< Transfer size */
395     status_t completionStatus; /*!< Success or error code describing how the transfer completed. Only applies for
396                                   #kLPI2C_SlaveCompletionEvent. */
397     size_t transferredCount;   /*!< Number of bytes actually transferred since start or last repeated start. */
398 } lpi2c_slave_transfer_t;
399 
400 /* Forward declaration. */
401 typedef struct _lpi2c_slave_handle lpi2c_slave_handle_t;
402 
403 /*!
404  * @brief Slave event callback function pointer type.
405  *
406  * This callback is used only for the slave non-blocking transfer API. To install a callback,
407  * use the LPI2C_SlaveSetCallback() function after you have created a handle.
408  *
409  * @param base Base address for the LPI2C instance on which the event occurred.
410  * @param transfer Pointer to transfer descriptor containing values passed to and/or from the callback.
411  * @param userData Arbitrary pointer-sized value passed from the application.
412  */
413 typedef void (*lpi2c_slave_transfer_callback_t)(LPI2C_Type *base, lpi2c_slave_transfer_t *transfer, void *userData);
414 
415 /*!
416  * @brief LPI2C slave handle structure.
417  * @note The contents of this structure are private and subject to change.
418  */
419 struct _lpi2c_slave_handle
420 {
421     lpi2c_slave_transfer_t transfer;          /*!< LPI2C slave transfer copy. */
422     bool isBusy;                              /*!< Whether transfer is busy. */
423     bool wasTransmit;                         /*!< Whether the last transfer was a transmit. */
424     uint32_t eventMask;                       /*!< Mask of enabled events. */
425     uint32_t transferredCount;                /*!< Count of bytes transferred. */
426     lpi2c_slave_transfer_callback_t callback; /*!< Callback function called at transfer event. */
427     void *userData;                           /*!< Callback parameter passed to callback. */
428 };
429 
430 /*! @} */
431 
432 /*******************************************************************************
433  * Variables
434  ******************************************************************************/
435 /*! Array to map LPI2C instance number to IRQ number, used internally for LPI2C master interrupt and EDMA transactional
436 APIs. */
437 extern IRQn_Type const kLpi2cIrqs[];
438 
439 /*! Pointer to master IRQ handler for each instance, used internally for LPI2C master interrupt and EDMA transactional
440 APIs. */
441 extern lpi2c_master_isr_t s_lpi2cMasterIsr;
442 
443 /*! Pointers to master handles for each instance, used internally for LPI2C master interrupt and EDMA transactional
444 APIs. */
445 extern void *s_lpi2cMasterHandle[];
446 
447 /*******************************************************************************
448  * API
449  ******************************************************************************/
450 
451 #if defined(__cplusplus)
452 extern "C" {
453 #endif
454 
455 /*!
456  * @brief Returns an instance number given a base address.
457  *
458  * If an invalid base address is passed, debug builds will assert. Release builds will just return
459  * instance number 0.
460  *
461  * @param base The LPI2C peripheral base address.
462  * @return LPI2C instance number starting from 0.
463  */
464 uint32_t LPI2C_GetInstance(LPI2C_Type *base);
465 
466 /*!
467  * @addtogroup lpi2c_master_driver
468  * @{
469  */
470 
471 /*! @name Initialization and deinitialization */
472 /*@{*/
473 
474 /*!
475  * @brief Provides a default configuration for the LPI2C master peripheral.
476  *
477  * This function provides the following default configuration for the LPI2C master peripheral:
478  * @code
479  *  masterConfig->enableMaster            = true;
480  *  masterConfig->debugEnable             = false;
481  *  masterConfig->ignoreAck               = false;
482  *  masterConfig->pinConfig               = kLPI2C_2PinOpenDrain;
483  *  masterConfig->baudRate_Hz             = 100000U;
484  *  masterConfig->busIdleTimeout_ns       = 0;
485  *  masterConfig->pinLowTimeout_ns        = 0;
486  *  masterConfig->sdaGlitchFilterWidth_ns = 0;
487  *  masterConfig->sclGlitchFilterWidth_ns = 0;
488  *  masterConfig->hostRequest.enable      = false;
489  *  masterConfig->hostRequest.source      = kLPI2C_HostRequestExternalPin;
490  *  masterConfig->hostRequest.polarity    = kLPI2C_HostRequestPinActiveHigh;
491  * @endcode
492  *
493  * After calling this function, you can override any settings in order to customize the configuration,
494  * prior to initializing the master driver with LPI2C_MasterInit().
495  *
496  * @param[out] masterConfig User provided configuration structure for default values. Refer to #lpi2c_master_config_t.
497  */
498 void LPI2C_MasterGetDefaultConfig(lpi2c_master_config_t *masterConfig);
499 
500 /*!
501  * @brief Initializes the LPI2C master peripheral.
502  *
503  * This function enables the peripheral clock and initializes the LPI2C master peripheral as described by the user
504  * provided configuration. A software reset is performed prior to configuration.
505  *
506  * @param base The LPI2C peripheral base address.
507  * @param masterConfig User provided peripheral configuration. Use LPI2C_MasterGetDefaultConfig() to get a set of
508  * defaults
509  *      that you can override.
510  * @param sourceClock_Hz Frequency in Hertz of the LPI2C functional clock. Used to calculate the baud rate divisors,
511  *      filter widths, and timeout periods.
512  */
513 void LPI2C_MasterInit(LPI2C_Type *base, const lpi2c_master_config_t *masterConfig, uint32_t sourceClock_Hz);
514 
515 /*!
516  * @brief Deinitializes the LPI2C master peripheral.
517  *
518  * This function disables the LPI2C master peripheral and gates the clock. It also performs a software
519  * reset to restore the peripheral to reset conditions.
520  *
521  * @param base The LPI2C peripheral base address.
522  */
523 void LPI2C_MasterDeinit(LPI2C_Type *base);
524 
525 /*!
526  * @brief Configures LPI2C master data match feature.
527  *
528  * @param base The LPI2C peripheral base address.
529  * @param matchConfig Settings for the data match feature.
530  */
531 void LPI2C_MasterConfigureDataMatch(LPI2C_Type *base, const lpi2c_data_match_config_t *matchConfig);
532 
533 /* Not static so it can be used from fsl_lpi2c_edma.c. */
534 status_t LPI2C_MasterCheckAndClearError(LPI2C_Type *base, uint32_t status);
535 
536 /* Not static so it can be used from fsl_lpi2c_edma.c. */
537 status_t LPI2C_CheckForBusyBus(LPI2C_Type *base);
538 
539 /*!
540  * @brief Performs a software reset.
541  *
542  * Restores the LPI2C master peripheral to reset conditions.
543  *
544  * @param base The LPI2C peripheral base address.
545  */
LPI2C_MasterReset(LPI2C_Type * base)546 static inline void LPI2C_MasterReset(LPI2C_Type *base)
547 {
548     base->MCR = LPI2C_MCR_RST_MASK;
549     base->MCR = 0;
550 }
551 
552 /*!
553  * @brief Enables or disables the LPI2C module as master.
554  *
555  * @param base The LPI2C peripheral base address.
556  * @param enable Pass true to enable or false to disable the specified LPI2C as master.
557  */
LPI2C_MasterEnable(LPI2C_Type * base,bool enable)558 static inline void LPI2C_MasterEnable(LPI2C_Type *base, bool enable)
559 {
560     base->MCR = (base->MCR & ~LPI2C_MCR_MEN_MASK) | LPI2C_MCR_MEN(enable);
561 }
562 
563 /*@}*/
564 
565 /*! @name Status */
566 /*@{*/
567 
568 /*!
569  * @brief Gets the LPI2C master status flags.
570  *
571  * A bit mask with the state of all LPI2C master status flags is returned. For each flag, the corresponding bit
572  * in the return value is set if the flag is asserted.
573  *
574  * @param base The LPI2C peripheral base address.
575  * @return State of the status flags:
576  *         - 1: related status flag is set.
577  *         - 0: related status flag is not set.
578  * @see _lpi2c_master_flags
579  */
LPI2C_MasterGetStatusFlags(LPI2C_Type * base)580 static inline uint32_t LPI2C_MasterGetStatusFlags(LPI2C_Type *base)
581 {
582     return base->MSR;
583 }
584 
585 /*!
586  * @brief Clears the LPI2C master status flag state.
587  *
588  * The following status register flags can be cleared:
589  * - #kLPI2C_MasterEndOfPacketFlag
590  * - #kLPI2C_MasterStopDetectFlag
591  * - #kLPI2C_MasterNackDetectFlag
592  * - #kLPI2C_MasterArbitrationLostFlag
593  * - #kLPI2C_MasterFifoErrFlag
594  * - #kLPI2C_MasterPinLowTimeoutFlag
595  * - #kLPI2C_MasterDataMatchFlag
596  *
597  * Attempts to clear other flags has no effect.
598  *
599  * @param base The LPI2C peripheral base address.
600  * @param statusMask A bitmask of status flags that are to be cleared. The mask is composed of
601  *  _lpi2c_master_flags enumerators OR'd together. You may pass the result of a previous call to
602  *  LPI2C_MasterGetStatusFlags().
603  * @see _lpi2c_master_flags.
604  */
LPI2C_MasterClearStatusFlags(LPI2C_Type * base,uint32_t statusMask)605 static inline void LPI2C_MasterClearStatusFlags(LPI2C_Type *base, uint32_t statusMask)
606 {
607     base->MSR = statusMask;
608 }
609 
610 /*@}*/
611 
612 /*! @name Interrupts */
613 /*@{*/
614 
615 /*!
616  * @brief Enables the LPI2C master interrupt requests.
617  *
618  * All flags except #kLPI2C_MasterBusyFlag and #kLPI2C_MasterBusBusyFlag can be enabled as
619  * interrupts.
620  *
621  * @param base The LPI2C peripheral base address.
622  * @param interruptMask Bit mask of interrupts to enable. See _lpi2c_master_flags for the set
623  *      of constants that should be OR'd together to form the bit mask.
624  */
LPI2C_MasterEnableInterrupts(LPI2C_Type * base,uint32_t interruptMask)625 static inline void LPI2C_MasterEnableInterrupts(LPI2C_Type *base, uint32_t interruptMask)
626 {
627     base->MIER |= interruptMask;
628 }
629 
630 /*!
631  * @brief Disables the LPI2C master interrupt requests.
632  *
633  * All flags except #kLPI2C_MasterBusyFlag and #kLPI2C_MasterBusBusyFlag can be enabled as
634  * interrupts.
635  *
636  * @param base The LPI2C peripheral base address.
637  * @param interruptMask Bit mask of interrupts to disable. See _lpi2c_master_flags for the set
638  *      of constants that should be OR'd together to form the bit mask.
639  */
LPI2C_MasterDisableInterrupts(LPI2C_Type * base,uint32_t interruptMask)640 static inline void LPI2C_MasterDisableInterrupts(LPI2C_Type *base, uint32_t interruptMask)
641 {
642     base->MIER &= ~interruptMask;
643 }
644 
645 /*!
646  * @brief Returns the set of currently enabled LPI2C master interrupt requests.
647  *
648  * @param base The LPI2C peripheral base address.
649  * @return A bitmask composed of _lpi2c_master_flags enumerators OR'd together to indicate the
650  *      set of enabled interrupts.
651  */
LPI2C_MasterGetEnabledInterrupts(LPI2C_Type * base)652 static inline uint32_t LPI2C_MasterGetEnabledInterrupts(LPI2C_Type *base)
653 {
654     return base->MIER;
655 }
656 
657 /*@}*/
658 
659 /*! @name DMA control */
660 /*@{*/
661 
662 /*!
663  * @brief Enables or disables LPI2C master DMA requests.
664  *
665  * @param base The LPI2C peripheral base address.
666  * @param enableTx Enable flag for transmit DMA request. Pass true for enable, false for disable.
667  * @param enableRx Enable flag for receive DMA request. Pass true for enable, false for disable.
668  */
LPI2C_MasterEnableDMA(LPI2C_Type * base,bool enableTx,bool enableRx)669 static inline void LPI2C_MasterEnableDMA(LPI2C_Type *base, bool enableTx, bool enableRx)
670 {
671     base->MDER = LPI2C_MDER_TDDE(enableTx) | LPI2C_MDER_RDDE(enableRx);
672 }
673 
674 /*!
675  * @brief Gets LPI2C master transmit data register address for DMA transfer.
676  *
677  * @param base The LPI2C peripheral base address.
678  * @return The LPI2C Master Transmit Data Register address.
679  */
LPI2C_MasterGetTxFifoAddress(LPI2C_Type * base)680 static inline uint32_t LPI2C_MasterGetTxFifoAddress(LPI2C_Type *base)
681 {
682     return (uint32_t)&base->MTDR;
683 }
684 
685 /*!
686  * @brief Gets LPI2C master receive data register address for DMA transfer.
687  *
688  * @param base The LPI2C peripheral base address.
689  * @return The LPI2C Master Receive Data Register address.
690  */
LPI2C_MasterGetRxFifoAddress(LPI2C_Type * base)691 static inline uint32_t LPI2C_MasterGetRxFifoAddress(LPI2C_Type *base)
692 {
693     return (uint32_t)&base->MRDR;
694 }
695 
696 /*@}*/
697 
698 /*! @name FIFO control */
699 /*@{*/
700 
701 /*!
702  * @brief Sets the watermarks for LPI2C master FIFOs.
703  *
704  * @param base The LPI2C peripheral base address.
705  * @param txWords Transmit FIFO watermark value in words. The #kLPI2C_MasterTxReadyFlag flag is set whenever
706  *      the number of words in the transmit FIFO is equal or less than @a txWords. Writing a value equal or
707  *      greater than the FIFO size is truncated.
708  * @param rxWords Receive FIFO watermark value in words. The #kLPI2C_MasterRxReadyFlag flag is set whenever
709  *      the number of words in the receive FIFO is greater than @a rxWords. Writing a value equal or greater
710  *      than the FIFO size is truncated.
711  */
LPI2C_MasterSetWatermarks(LPI2C_Type * base,size_t txWords,size_t rxWords)712 static inline void LPI2C_MasterSetWatermarks(LPI2C_Type *base, size_t txWords, size_t rxWords)
713 {
714     base->MFCR = LPI2C_MFCR_TXWATER(txWords) | LPI2C_MFCR_RXWATER(rxWords);
715 }
716 
717 /*!
718  * @brief Gets the current number of words in the LPI2C master FIFOs.
719  *
720  * @param base The LPI2C peripheral base address.
721  * @param[out] txCount Pointer through which the current number of words in the transmit FIFO is returned.
722  *      Pass NULL if this value is not required.
723  * @param[out] rxCount Pointer through which the current number of words in the receive FIFO is returned.
724  *      Pass NULL if this value is not required.
725  */
LPI2C_MasterGetFifoCounts(LPI2C_Type * base,size_t * rxCount,size_t * txCount)726 static inline void LPI2C_MasterGetFifoCounts(LPI2C_Type *base, size_t *rxCount, size_t *txCount)
727 {
728     if (NULL != txCount)
729     {
730         *txCount = (base->MFSR & LPI2C_MFSR_TXCOUNT_MASK) >> LPI2C_MFSR_TXCOUNT_SHIFT;
731     }
732     if (NULL != rxCount)
733     {
734         *rxCount = (base->MFSR & LPI2C_MFSR_RXCOUNT_MASK) >> LPI2C_MFSR_RXCOUNT_SHIFT;
735     }
736 }
737 
738 /*@}*/
739 
740 /*! @name Bus operations */
741 /*@{*/
742 
743 /*!
744  * @brief Sets the I2C bus frequency for master transactions.
745  *
746  * The LPI2C master is automatically disabled and re-enabled as necessary to configure the baud
747  * rate. Do not call this function during a transfer, or the transfer is aborted.
748  *
749  * @note Please note that the second parameter is the clock frequency of LPI2C module, the third
750  * parameter means user configured bus baudrate, this implementation is different from other I2C drivers
751  * which use baudrate configuration as second parameter and source clock frequency as third parameter.
752  *
753  * @param base The LPI2C peripheral base address.
754  * @param sourceClock_Hz LPI2C functional clock frequency in Hertz.
755  * @param baudRate_Hz Requested bus frequency in Hertz.
756  */
757 void LPI2C_MasterSetBaudRate(LPI2C_Type *base, uint32_t sourceClock_Hz, uint32_t baudRate_Hz);
758 
759 /*!
760  * @brief Returns whether the bus is idle.
761  *
762  * Requires the master mode to be enabled.
763  *
764  * @param base The LPI2C peripheral base address.
765  * @retval true Bus is busy.
766  * @retval false Bus is idle.
767  */
LPI2C_MasterGetBusIdleState(LPI2C_Type * base)768 static inline bool LPI2C_MasterGetBusIdleState(LPI2C_Type *base)
769 {
770     return ((base->MSR & LPI2C_MSR_BBF_MASK) >> LPI2C_MSR_BBF_SHIFT) == 1U ? true : false;
771 }
772 
773 /*!
774  * @brief Sends a START signal and slave address on the I2C bus.
775  *
776  * This function is used to initiate a new master mode transfer. First, the bus state is checked to ensure
777  * that another master is not occupying the bus. Then a START signal is transmitted, followed by the
778  * 7-bit address specified in the @a address parameter. Note that this function does not actually wait
779  * until the START and address are successfully sent on the bus before returning.
780  *
781  * @param base The LPI2C peripheral base address.
782  * @param address 7-bit slave device address, in bits [6:0].
783  * @param dir Master transfer direction, either #kLPI2C_Read or #kLPI2C_Write. This parameter is used to set
784  *      the R/w bit (bit 0) in the transmitted slave address.
785  * @retval kStatus_Success START signal and address were successfully enqueued in the transmit FIFO.
786  * @retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
787  */
788 status_t LPI2C_MasterStart(LPI2C_Type *base, uint8_t address, lpi2c_direction_t dir);
789 
790 /*!
791  * @brief Sends a repeated START signal and slave address on the I2C bus.
792  *
793  * This function is used to send a Repeated START signal when a transfer is already in progress. Like
794  * LPI2C_MasterStart(), it also sends the specified 7-bit address.
795  *
796  * @note This function exists primarily to maintain compatible APIs between LPI2C and I2C drivers,
797  *      as well as to better document the intent of code that uses these APIs.
798  *
799  * @param base The LPI2C peripheral base address.
800  * @param address 7-bit slave device address, in bits [6:0].
801  * @param dir Master transfer direction, either #kLPI2C_Read or #kLPI2C_Write. This parameter is used to set
802  *      the R/w bit (bit 0) in the transmitted slave address.
803  * @retval kStatus_Success Repeated START signal and address were successfully enqueued in the transmit FIFO.
804  * @retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
805  */
LPI2C_MasterRepeatedStart(LPI2C_Type * base,uint8_t address,lpi2c_direction_t dir)806 static inline status_t LPI2C_MasterRepeatedStart(LPI2C_Type *base, uint8_t address, lpi2c_direction_t dir)
807 {
808     return LPI2C_MasterStart(base, address, dir);
809 }
810 
811 /*!
812  * @brief Performs a polling send transfer on the I2C bus.
813  *
814  * Sends up to @a txSize number of bytes to the previously addressed slave device. The slave may
815  * reply with a NAK to any byte in order to terminate the transfer early. If this happens, this
816  * function returns #kStatus_LPI2C_Nak.
817  *
818  * @param base  The LPI2C peripheral base address.
819  * @param txBuff The pointer to the data to be transferred.
820  * @param txSize The length in bytes of the data to be transferred.
821  * @retval kStatus_Success Data was sent successfully.
822  * @retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
823  * @retval #kStatus_LPI2C_Nak The slave device sent a NAK in response to a byte.
824  * @retval #kStatus_LPI2C_FifoError FIFO under run or over run.
825  * @retval #kStatus_LPI2C_ArbitrationLost Arbitration lost error.
826  * @retval #kStatus_LPI2C_PinLowTimeout SCL or SDA were held low longer than the timeout.
827  */
828 status_t LPI2C_MasterSend(LPI2C_Type *base, void *txBuff, size_t txSize);
829 
830 /*!
831  * @brief Performs a polling receive transfer on the I2C bus.
832  *
833  * @param base  The LPI2C peripheral base address.
834  * @param rxBuff The pointer to the data to be transferred.
835  * @param rxSize The length in bytes of the data to be transferred.
836  * @retval kStatus_Success Data was received successfully.
837  * @retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
838  * @retval #kStatus_LPI2C_Nak The slave device sent a NAK in response to a byte.
839  * @retval #kStatus_LPI2C_FifoError FIFO under run or overrun.
840  * @retval #kStatus_LPI2C_ArbitrationLost Arbitration lost error.
841  * @retval #kStatus_LPI2C_PinLowTimeout SCL or SDA were held low longer than the timeout.
842  */
843 status_t LPI2C_MasterReceive(LPI2C_Type *base, void *rxBuff, size_t rxSize);
844 
845 /*!
846  * @brief Sends a STOP signal on the I2C bus.
847  *
848  * This function does not return until the STOP signal is seen on the bus, or an error occurs.
849  *
850  * @param base The LPI2C peripheral base address.
851  * @retval kStatus_Success The STOP signal was successfully sent on the bus and the transaction terminated.
852  * @retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
853  * @retval #kStatus_LPI2C_Nak The slave device sent a NAK in response to a byte.
854  * @retval #kStatus_LPI2C_FifoError FIFO under run or overrun.
855  * @retval #kStatus_LPI2C_ArbitrationLost Arbitration lost error.
856  * @retval #kStatus_LPI2C_PinLowTimeout SCL or SDA were held low longer than the timeout.
857  */
858 status_t LPI2C_MasterStop(LPI2C_Type *base);
859 
860 /*!
861  * @brief Performs a master polling transfer on the I2C bus.
862  *
863  * @note The API does not return until the transfer succeeds or fails due
864  * to error happens during transfer.
865  *
866  * @param base The LPI2C peripheral base address.
867  * @param transfer Pointer to the transfer structure.
868  * @retval kStatus_Success Data was received successfully.
869  * @retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
870  * @retval #kStatus_LPI2C_Nak The slave device sent a NAK in response to a byte.
871  * @retval #kStatus_LPI2C_FifoError FIFO under run or overrun.
872  * @retval #kStatus_LPI2C_ArbitrationLost Arbitration lost error.
873  * @retval #kStatus_LPI2C_PinLowTimeout SCL or SDA were held low longer than the timeout.
874  */
875 status_t LPI2C_MasterTransferBlocking(LPI2C_Type *base, lpi2c_master_transfer_t *transfer);
876 
877 /*@}*/
878 
879 /*! @name Non-blocking */
880 /*@{*/
881 
882 /*!
883  * @brief Creates a new handle for the LPI2C master non-blocking APIs.
884  *
885  * The creation of a handle is for use with the non-blocking APIs. Once a handle
886  * is created, there is not a corresponding destroy handle. If the user wants to
887  * terminate a transfer, the LPI2C_MasterTransferAbort() API shall be called.
888  *
889  *
890  * @note The function also enables the NVIC IRQ for the input LPI2C. Need to notice
891  * that on some SoCs the LPI2C IRQ is connected to INTMUX, in this case user needs to
892  * enable the associated INTMUX IRQ in application.
893  *
894  * @param base The LPI2C peripheral base address.
895  * @param[out] handle Pointer to the LPI2C master driver handle.
896  * @param callback User provided pointer to the asynchronous callback function.
897  * @param userData User provided pointer to the application callback data.
898  */
899 void LPI2C_MasterTransferCreateHandle(LPI2C_Type *base,
900                                       lpi2c_master_handle_t *handle,
901                                       lpi2c_master_transfer_callback_t callback,
902                                       void *userData);
903 
904 /*!
905  * @brief Performs a non-blocking transaction on the I2C bus.
906  *
907  * @param base The LPI2C peripheral base address.
908  * @param handle Pointer to the LPI2C master driver handle.
909  * @param transfer The pointer to the transfer descriptor.
910  * @retval kStatus_Success The transaction was started successfully.
911  * @retval #kStatus_LPI2C_Busy Either another master is currently utilizing the bus, or a non-blocking
912  *      transaction is already in progress.
913  */
914 status_t LPI2C_MasterTransferNonBlocking(LPI2C_Type *base,
915                                          lpi2c_master_handle_t *handle,
916                                          lpi2c_master_transfer_t *transfer);
917 
918 /*!
919  * @brief Returns number of bytes transferred so far.
920  * @param base The LPI2C peripheral base address.
921  * @param handle Pointer to the LPI2C master driver handle.
922  * @param[out] count Number of bytes transferred so far by the non-blocking transaction.
923  * @retval kStatus_Success
924  * @retval kStatus_NoTransferInProgress There is not a non-blocking transaction currently in progress.
925  */
926 status_t LPI2C_MasterTransferGetCount(LPI2C_Type *base, lpi2c_master_handle_t *handle, size_t *count);
927 
928 /*!
929  * @brief Terminates a non-blocking LPI2C master transmission early.
930  *
931  * @note It is not safe to call this function from an IRQ handler that has a higher priority than the
932  *      LPI2C peripheral's IRQ priority.
933  *
934  * @param base The LPI2C peripheral base address.
935  * @param handle Pointer to the LPI2C master driver handle.
936  * @retval kStatus_Success A transaction was successfully aborted.
937  * @retval #kStatus_LPI2C_Idle There is not a non-blocking transaction currently in progress.
938  */
939 void LPI2C_MasterTransferAbort(LPI2C_Type *base, lpi2c_master_handle_t *handle);
940 
941 /*@}*/
942 
943 /*! @name IRQ handler */
944 /*@{*/
945 
946 /*!
947  * @brief Reusable routine to handle master interrupts.
948  * @note This function does not need to be called unless you are reimplementing the
949  *  nonblocking API's interrupt handler routines to add special functionality.
950  * @param instance The LPI2C instance.
951  * @param lpi2cMasterHandle Pointer to the LPI2C master driver handle.
952  */
953 void LPI2C_MasterTransferHandleIRQ(uint32_t instance, void *lpi2cMasterHandle);
954 
955 /*@}*/
956 
957 /*! @} */
958 
959 /*!
960  * @addtogroup lpi2c_slave_driver
961  * @{
962  */
963 
964 /*! @name Slave initialization and deinitialization */
965 /*@{*/
966 
967 /*!
968  * @brief Provides a default configuration for the LPI2C slave peripheral.
969  *
970  * This function provides the following default configuration for the LPI2C slave peripheral:
971  * @code
972  *  slaveConfig->enableSlave               = true;
973  *  slaveConfig->address0                  = 0U;
974  *  slaveConfig->address1                  = 0U;
975  *  slaveConfig->addressMatchMode          = kLPI2C_MatchAddress0;
976  *  slaveConfig->filterDozeEnable          = true;
977  *  slaveConfig->filterEnable              = true;
978  *  slaveConfig->enableGeneralCall         = false;
979  *  slaveConfig->sclStall.enableAck        = false;
980  *  slaveConfig->sclStall.enableTx         = true;
981  *  slaveConfig->sclStall.enableRx         = true;
982  *  slaveConfig->sclStall.enableAddress    = true;
983  *  slaveConfig->ignoreAck                 = false;
984  *  slaveConfig->enableReceivedAddressRead = false;
985  *  slaveConfig->sdaGlitchFilterWidth_ns   = 0;
986  *  slaveConfig->sclGlitchFilterWidth_ns   = 0;
987  *  slaveConfig->dataValidDelay_ns         = 0;
988  *  slaveConfig->clockHoldTime_ns          = 0;
989  * @endcode
990  *
991  * After calling this function, override any settings  to customize the configuration,
992  * prior to initializing the master driver with LPI2C_SlaveInit(). Be sure to override at least the @a
993  * address0 member of the configuration structure with the desired slave address.
994  *
995  * @param[out] slaveConfig User provided configuration structure that is set to default values. Refer to
996  *      #lpi2c_slave_config_t.
997  */
998 void LPI2C_SlaveGetDefaultConfig(lpi2c_slave_config_t *slaveConfig);
999 
1000 /*!
1001  * @brief Initializes the LPI2C slave peripheral.
1002  *
1003  * This function enables the peripheral clock and initializes the LPI2C slave peripheral as described by the user
1004  * provided configuration.
1005  *
1006  * @param base The LPI2C peripheral base address.
1007  * @param slaveConfig User provided peripheral configuration. Use LPI2C_SlaveGetDefaultConfig() to get a set of defaults
1008  *      that you can override.
1009  * @param sourceClock_Hz Frequency in Hertz of the LPI2C functional clock. Used to calculate the filter widths,
1010  *      data valid delay, and clock hold time.
1011  */
1012 void LPI2C_SlaveInit(LPI2C_Type *base, const lpi2c_slave_config_t *slaveConfig, uint32_t sourceClock_Hz);
1013 
1014 /*!
1015  * @brief Deinitializes the LPI2C slave peripheral.
1016  *
1017  * This function disables the LPI2C slave peripheral and gates the clock. It also performs a software
1018  * reset to restore the peripheral to reset conditions.
1019  *
1020  * @param base The LPI2C peripheral base address.
1021  */
1022 void LPI2C_SlaveDeinit(LPI2C_Type *base);
1023 
1024 /*!
1025  * @brief Performs a software reset of the LPI2C slave peripheral.
1026  *
1027  * @param base The LPI2C peripheral base address.
1028  */
LPI2C_SlaveReset(LPI2C_Type * base)1029 static inline void LPI2C_SlaveReset(LPI2C_Type *base)
1030 {
1031     base->SCR = LPI2C_SCR_RST_MASK;
1032     base->SCR = 0;
1033 }
1034 
1035 /*!
1036  * @brief Enables or disables the LPI2C module as slave.
1037  *
1038  * @param base The LPI2C peripheral base address.
1039  * @param enable Pass true to enable or false to disable the specified LPI2C as slave.
1040  */
LPI2C_SlaveEnable(LPI2C_Type * base,bool enable)1041 static inline void LPI2C_SlaveEnable(LPI2C_Type *base, bool enable)
1042 {
1043     base->SCR = (base->SCR & ~LPI2C_SCR_SEN_MASK) | LPI2C_SCR_SEN(enable);
1044 }
1045 
1046 /*@}*/
1047 
1048 /*! @name Slave status */
1049 /*@{*/
1050 
1051 /*!
1052  * @brief Gets the LPI2C slave status flags.
1053  *
1054  * A bit mask with the state of all LPI2C slave status flags is returned. For each flag, the corresponding bit
1055  * in the return value is set if the flag is asserted.
1056  *
1057  * @param base The LPI2C peripheral base address.
1058  * @return State of the status flags:
1059  *         - 1: related status flag is set.
1060  *         - 0: related status flag is not set.
1061  * @see _lpi2c_slave_flags
1062  */
LPI2C_SlaveGetStatusFlags(LPI2C_Type * base)1063 static inline uint32_t LPI2C_SlaveGetStatusFlags(LPI2C_Type *base)
1064 {
1065     return base->SSR;
1066 }
1067 
1068 /*!
1069  * @brief Clears the LPI2C status flag state.
1070  *
1071  * The following status register flags can be cleared:
1072  * - #kLPI2C_SlaveRepeatedStartDetectFlag
1073  * - #kLPI2C_SlaveStopDetectFlag
1074  * - #kLPI2C_SlaveBitErrFlag
1075  * - #kLPI2C_SlaveFifoErrFlag
1076  *
1077  * Attempts to clear other flags has no effect.
1078  *
1079  * @param base The LPI2C peripheral base address.
1080  * @param statusMask A bitmask of status flags that are to be cleared. The mask is composed of
1081  *  #_lpi2c_slave_flags enumerators OR'd together. You may pass the result of a previous call to
1082  *  LPI2C_SlaveGetStatusFlags().
1083  * @see _lpi2c_slave_flags.
1084  */
LPI2C_SlaveClearStatusFlags(LPI2C_Type * base,uint32_t statusMask)1085 static inline void LPI2C_SlaveClearStatusFlags(LPI2C_Type *base, uint32_t statusMask)
1086 {
1087     base->SSR = statusMask;
1088 }
1089 
1090 /*@}*/
1091 
1092 /*! @name Slave interrupts */
1093 /*@{*/
1094 
1095 /*!
1096  * @brief Enables the LPI2C slave interrupt requests.
1097  *
1098  * All flags except #kLPI2C_SlaveBusyFlag and #kLPI2C_SlaveBusBusyFlag can be enabled as
1099  * interrupts.
1100  *
1101  * @param base The LPI2C peripheral base address.
1102  * @param interruptMask Bit mask of interrupts to enable. See #_lpi2c_slave_flags for the set
1103  *      of constants that should be OR'd together to form the bit mask.
1104  */
LPI2C_SlaveEnableInterrupts(LPI2C_Type * base,uint32_t interruptMask)1105 static inline void LPI2C_SlaveEnableInterrupts(LPI2C_Type *base, uint32_t interruptMask)
1106 {
1107     base->SIER |= interruptMask;
1108 }
1109 
1110 /*!
1111  * @brief Disables the LPI2C slave interrupt requests.
1112  *
1113  * All flags except #kLPI2C_SlaveBusyFlag and #kLPI2C_SlaveBusBusyFlag can be enabled as
1114  * interrupts.
1115  *
1116  * @param base The LPI2C peripheral base address.
1117  * @param interruptMask Bit mask of interrupts to disable. See #_lpi2c_slave_flags for the set
1118  *      of constants that should be OR'd together to form the bit mask.
1119  */
LPI2C_SlaveDisableInterrupts(LPI2C_Type * base,uint32_t interruptMask)1120 static inline void LPI2C_SlaveDisableInterrupts(LPI2C_Type *base, uint32_t interruptMask)
1121 {
1122     base->SIER &= ~interruptMask;
1123 }
1124 
1125 /*!
1126  * @brief Returns the set of currently enabled LPI2C slave interrupt requests.
1127  * @param base The LPI2C peripheral base address.
1128  * @return A bitmask composed of #_lpi2c_slave_flags enumerators OR'd together to indicate the
1129  *      set of enabled interrupts.
1130  */
LPI2C_SlaveGetEnabledInterrupts(LPI2C_Type * base)1131 static inline uint32_t LPI2C_SlaveGetEnabledInterrupts(LPI2C_Type *base)
1132 {
1133     return base->SIER;
1134 }
1135 
1136 /*@}*/
1137 
1138 /*! @name Slave DMA control */
1139 /*@{*/
1140 
1141 /*!
1142  * @brief Enables or disables the LPI2C slave peripheral DMA requests.
1143  *
1144  * @param base The LPI2C peripheral base address.
1145  * @param enableAddressValid Enable flag for the address valid DMA request. Pass true for enable, false for disable.
1146  *      The address valid DMA request is shared with the receive data DMA request.
1147  * @param enableRx Enable flag for the receive data DMA request. Pass true for enable, false for disable.
1148  * @param enableTx Enable flag for the transmit data DMA request. Pass true for enable, false for disable.
1149  */
LPI2C_SlaveEnableDMA(LPI2C_Type * base,bool enableAddressValid,bool enableRx,bool enableTx)1150 static inline void LPI2C_SlaveEnableDMA(LPI2C_Type *base, bool enableAddressValid, bool enableRx, bool enableTx)
1151 {
1152     base->SDER = (base->SDER & ~(LPI2C_SDER_AVDE_MASK | LPI2C_SDER_RDDE_MASK | LPI2C_SDER_TDDE_MASK)) |
1153                  LPI2C_SDER_AVDE(enableAddressValid) | LPI2C_SDER_RDDE(enableRx) | LPI2C_SDER_TDDE(enableTx);
1154 }
1155 
1156 /*@}*/
1157 
1158 /*! @name Slave bus operations */
1159 /*@{*/
1160 
1161 /*!
1162  * @brief Returns whether the bus is idle.
1163  *
1164  * Requires the slave mode to be enabled.
1165  *
1166  * @param base The LPI2C peripheral base address.
1167  * @retval true Bus is busy.
1168  * @retval false Bus is idle.
1169  */
LPI2C_SlaveGetBusIdleState(LPI2C_Type * base)1170 static inline bool LPI2C_SlaveGetBusIdleState(LPI2C_Type *base)
1171 {
1172     return ((base->SSR & LPI2C_SSR_BBF_MASK) >> LPI2C_SSR_BBF_SHIFT) == 1U ? true : false;
1173 }
1174 
1175 /*!
1176  * @brief Transmits either an ACK or NAK on the I2C bus in response to a byte from the master.
1177  *
1178  * Use this function to send an ACK or NAK when the #kLPI2C_SlaveTransmitAckFlag is asserted. This
1179  * only happens if you enable the sclStall.enableAck field of the ::lpi2c_slave_config_t configuration
1180  * structure used to initialize the slave peripheral.
1181  *
1182  * @param base The LPI2C peripheral base address.
1183  * @param ackOrNack Pass true for an ACK or false for a NAK.
1184  */
LPI2C_SlaveTransmitAck(LPI2C_Type * base,bool ackOrNack)1185 static inline void LPI2C_SlaveTransmitAck(LPI2C_Type *base, bool ackOrNack)
1186 {
1187     base->STAR = LPI2C_STAR_TXNACK(!ackOrNack);
1188 }
1189 
1190 /*!
1191  * @brief Enables or disables ACKSTALL.
1192  *
1193  * When enables ACKSTALL, software can transmit either an ACK or NAK on the I2C bus in response to
1194  * a byte from the master.
1195  *
1196  * @param base The LPI2C peripheral base address.
1197  * @param enable True will enable ACKSTALL,false will disable ACKSTALL.
1198  */
LPI2C_SlaveEnableAckStall(LPI2C_Type * base,bool enable)1199 static inline void LPI2C_SlaveEnableAckStall(LPI2C_Type *base, bool enable)
1200 {
1201     if (enable)
1202     {
1203         base->SCFGR1 |= LPI2C_SCFGR1_ACKSTALL_MASK;
1204     }
1205     else
1206     {
1207         base->SCFGR1 &= ~LPI2C_SCFGR1_ACKSTALL_MASK;
1208     }
1209 }
1210 
1211 /*!
1212  * @brief Returns the slave address sent by the I2C master.
1213  *
1214  * This function should only be called if the #kLPI2C_SlaveAddressValidFlag is asserted.
1215  *
1216  * @param base The LPI2C peripheral base address.
1217  * @return The 8-bit address matched by the LPI2C slave. Bit 0 contains the R/w direction bit, and
1218  *      the 7-bit slave address is in the upper 7 bits.
1219  */
LPI2C_SlaveGetReceivedAddress(LPI2C_Type * base)1220 static inline uint32_t LPI2C_SlaveGetReceivedAddress(LPI2C_Type *base)
1221 {
1222     return base->SASR & LPI2C_SASR_RADDR_MASK;
1223 }
1224 
1225 /*!
1226  * @brief Performs a polling send transfer on the I2C bus.
1227  *
1228  * @param base  The LPI2C peripheral base address.
1229  * @param txBuff The pointer to the data to be transferred.
1230  * @param txSize The length in bytes of the data to be transferred.
1231  * @param[out] actualTxSize
1232  * @return Error or success status returned by API.
1233  */
1234 status_t LPI2C_SlaveSend(LPI2C_Type *base, void *txBuff, size_t txSize, size_t *actualTxSize);
1235 
1236 /*!
1237  * @brief Performs a polling receive transfer on the I2C bus.
1238  *
1239  * @param base  The LPI2C peripheral base address.
1240  * @param rxBuff The pointer to the data to be transferred.
1241  * @param rxSize The length in bytes of the data to be transferred.
1242  * @param[out] actualRxSize
1243  * @return Error or success status returned by API.
1244  */
1245 status_t LPI2C_SlaveReceive(LPI2C_Type *base, void *rxBuff, size_t rxSize, size_t *actualRxSize);
1246 
1247 /*@}*/
1248 
1249 /*! @name Slave non-blocking */
1250 /*@{*/
1251 
1252 /*!
1253  * @brief Creates a new handle for the LPI2C slave non-blocking APIs.
1254  *
1255  * The creation of a handle is for use with the non-blocking APIs. Once a handle
1256  * is created, there is not a corresponding destroy handle. If the user wants to
1257  * terminate a transfer, the LPI2C_SlaveTransferAbort() API shall be called.
1258  *
1259  * @note The function also enables the NVIC IRQ for the input LPI2C. Need to notice
1260  * that on some SoCs the LPI2C IRQ is connected to INTMUX, in this case user needs to
1261  * enable the associated INTMUX IRQ in application.
1262 
1263  * @param base The LPI2C peripheral base address.
1264  * @param[out] handle Pointer to the LPI2C slave driver handle.
1265  * @param callback User provided pointer to the asynchronous callback function.
1266  * @param userData User provided pointer to the application callback data.
1267  */
1268 void LPI2C_SlaveTransferCreateHandle(LPI2C_Type *base,
1269                                      lpi2c_slave_handle_t *handle,
1270                                      lpi2c_slave_transfer_callback_t callback,
1271                                      void *userData);
1272 
1273 /*!
1274  * @brief Starts accepting slave transfers.
1275  *
1276  * Call this API after calling I2C_SlaveInit() and LPI2C_SlaveTransferCreateHandle() to start processing
1277  * transactions driven by an I2C master. The slave monitors the I2C bus and pass events to the
1278  * callback that was passed into the call to LPI2C_SlaveTransferCreateHandle(). The callback is always invoked
1279  * from the interrupt context.
1280  *
1281  * The set of events received by the callback is customizable. To do so, set the @a eventMask parameter to
1282  * the OR'd combination of #lpi2c_slave_transfer_event_t enumerators for the events you wish to receive.
1283  * The #kLPI2C_SlaveTransmitEvent and #kLPI2C_SlaveReceiveEvent events are always enabled and do not need
1284  * to be included in the mask. Alternatively, you can pass 0 to get a default set of only the transmit and
1285  * receive events that are always enabled. In addition, the #kLPI2C_SlaveAllEvents constant is provided as
1286  * a convenient way to enable all events.
1287  *
1288  * @param base The LPI2C peripheral base address.
1289  * @param handle Pointer to lpi2c_slave_handle_t structure which stores the transfer state.
1290  * @param eventMask Bit mask formed by OR'ing together #lpi2c_slave_transfer_event_t enumerators to specify
1291  *      which events to send to the callback. Other accepted values are 0 to get a default set of
1292  *      only the transmit and receive events, and #kLPI2C_SlaveAllEvents to enable all events.
1293  *
1294  * @retval kStatus_Success Slave transfers were successfully started.
1295  * @retval #kStatus_LPI2C_Busy Slave transfers have already been started on this handle.
1296  */
1297 status_t LPI2C_SlaveTransferNonBlocking(LPI2C_Type *base, lpi2c_slave_handle_t *handle, uint32_t eventMask);
1298 
1299 /*!
1300  * @brief Gets the slave transfer status during a non-blocking transfer.
1301  * @param base The LPI2C peripheral base address.
1302  * @param handle Pointer to i2c_slave_handle_t structure.
1303  * @param[out] count Pointer to a value to hold the number of bytes transferred. May be NULL if the count is not
1304  *      required.
1305  * @retval kStatus_Success
1306  * @retval kStatus_NoTransferInProgress
1307  */
1308 status_t LPI2C_SlaveTransferGetCount(LPI2C_Type *base, lpi2c_slave_handle_t *handle, size_t *count);
1309 
1310 /*!
1311  * @brief Aborts the slave non-blocking transfers.
1312  * @note This API could be called at any time to stop slave for handling the bus events.
1313  * @param base The LPI2C peripheral base address.
1314  * @param handle Pointer to lpi2c_slave_handle_t structure which stores the transfer state.
1315  * @retval kStatus_Success
1316  * @retval #kStatus_LPI2C_Idle
1317  */
1318 void LPI2C_SlaveTransferAbort(LPI2C_Type *base, lpi2c_slave_handle_t *handle);
1319 
1320 /*@}*/
1321 
1322 /*! @name Slave IRQ handler */
1323 /*@{*/
1324 
1325 /*!
1326  * @brief Reusable routine to handle slave interrupts.
1327  * @note This function does not need to be called unless you are reimplementing the
1328  *  non blocking API's interrupt handler routines to add special functionality.
1329  * @param instance The LPI2C instance.
1330  * @param lpi2cSlaveHandle Pointer to lpi2c_slave_handle_t structure which stores the transfer state.
1331  */
1332 void LPI2C_SlaveTransferHandleIRQ(uint32_t instance, void *lpi2cSlaveHandle);
1333 
1334 /*@}*/
1335 
1336 /*! @} */
1337 
1338 #if defined(__cplusplus)
1339 }
1340 #endif
1341 
1342 #endif /* FSL_LPI2C_H_ */