MCUXpresso SDK API Reference Manual - MKL26Z4
MCUXpresso SDK API Reference Manual - MKL26Z4
NXP Semiconductors
Chapter Trademarks
5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
9.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
14.4 Digital pin filter for external wakeup pin configurations . . . . . . . . . . . . . . 169
PUBWEAK SPI0_IRQHandler
PUBWEAK SPI0_DriverIRQHandler
SPI0_IRQHandler
The first level of the weak implementation are the functions defined in the vector table. In the devices/<-
DEVICE_NAME>/<TOOLCHAIN>/startup_<DEVICE_NAME>.s/.S file, the implementation of the
first layer weak function calls the second layer of weak function. The implementation of the second
layer weak function (ex. SPI0_DriverIRQHandler) jumps to itself (B .). The MCUXpresso SDK drivers
with transactional APIs provide the reimplementation of the second layer function inside of the peripheral
driver. If the MCUXpresso SDK drivers with transactional APIs are linked into the image, the SPI0_-
DriverIRQHandler is replaced with the function implemented in the MCUXpresso SDK SPI driver.
The reason for implementing the double weak functions is to provide a better user experience when using
the transactional APIs. For drivers with a transactional function, call the transactional APIs and the drivers
complete the interrupt-driven flow. Users are not required to redefine the vector entries out of the box. At
the same time, if users are not satisfied by the second layer weak function implemented in the MCU-
Xpresso SDK drivers, users can redefine the first layer weak function and implement their own interrupt
handler functions to suit their implementation.
The limitation of the double weak mechanism is that it cannot be used for peripherals that share the same
vector entry. For this use case, redefine the first layer weak function to enable the desired peripheral
interrupt functionality. For example, if the MCU’s UART0 and UART1 share the same vector entry,
redefine the UART0_UART1_IRQHandler according to the use case requirements.
Feature Header Files
The peripheral drivers are designed to be reusable regardless of the peripheral functional differences from
one MCU device to another. An overall Peripheral Feature Header File is provided for the MCUXpresso
SDK-supported MCU device to define the features or configuration differences for each sub-family device.
Application
See the Getting Started with MCUXpresso SDK document (MCUXSDKGSUG).
adc16_config_t adc16ConfigStruct;
adc16_channel_config_t adc16ChannelConfigStruct;
ADC16_Init(DEMO_ADC16_INSTANCE);
ADC16_GetDefaultConfig(&adc16ConfigStruct);
ADC16_Configure(DEMO_ADC16_INSTANCE, &adc16ConfigStruct);
ADC16_EnableHardwareTrigger(DEMO_ADC16_INSTANCE, false);
#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION
if (kStatus_Success == ADC16_DoAutoCalibration(DEMO_ADC16_INSTANCE))
{
PRINTF("ADC16_DoAutoCalibration() Done.\r\n");
}
else
{
PRINTF("ADC16_DoAutoCalibration() Failed.\r\n");
}
#endif // FSL_FEATURE_ADC16_HAS_CALIBRATION
adc16ChannelConfigStruct.channelNumber = DEMO_ADC16_USER_CHANNEL;
adc16ChannelConfigStruct.enableInterruptOnConversionCompleted =
false;
#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE
adc16ChannelConfigStruct.enableDifferentialConversion = false;
#endif // FSL_FEATURE_ADC16_HAS_DIFF_MODE
while(1)
{
GETCHAR(); // Input any key in terminal console.
ADC16_ChannelConfigure(DEMO_ADC16_INSTANCE, DEMO_ADC16_CHANNEL_GROUP, &adc16ChannelConfigStruct);
while (kADC16_ChannelConversionDoneFlag !=
ADC16_ChannelGetStatusFlags(DEMO_ADC16_INSTANCE, DEMO_ADC16_CHANNEL_GROUP))
{
}
PRINTF("ADC Value: %d\r\n", ADC16_ChannelGetConversionValue(DEMO_ADC16_INSTANCE,
DEMO_ADC16_CHANNEL_GROUP));
}
// ...
adc16_config_t adc16ConfigStruct;
adc16_channel_config_t adc16ChannelConfigStruct;
ADC16_Init(DEMO_ADC16_INSTANCE);
ADC16_GetDefaultConfig(&adc16ConfigStruct);
ADC16_Configure(DEMO_ADC16_INSTANCE, &adc16ConfigStruct);
ADC16_EnableHardwareTrigger(DEMO_ADC16_INSTANCE, false);
#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION
if (ADC16_DoAutoCalibration(DEMO_ADC16_INSTANCE))
{
PRINTF("ADC16_DoAutoCalibration() Done.\r\n");
}
else
{
PRINTF("ADC16_DoAutoCalibration() Failed.\r\n");
}
#endif // FSL_FEATURE_ADC16_HAS_CALIBRATION
adc16ChannelConfigStruct.channelNumber = DEMO_ADC16_USER_CHANNEL;
adc16ChannelConfigStruct.enableInterruptOnConversionCompleted =
true; // Enable the interrupt.
#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE
adc16ChannelConfigStruct.enableDifferentialConversion = false;
#endif // FSL_FEATURE_ADC16_HAS_DIFF_MODE
while(1)
{
GETCHAR(); // Input a key in the terminal console.
g_Adc16ConversionDoneFlag = false;
ADC16_ChannelConfigure(DEMO_ADC16_INSTANCE, DEMO_ADC16_CHANNEL_GROUP, &adc16ChannelConfigStruct);
while (!g_Adc16ConversionDoneFlag)
{
}
PRINTF("ADC Value: %d\r\n", g_Adc16ConversionValue);
PRINTF("ADC Interrupt Count: %d\r\n", g_Adc16InterruptCount);
}
// ...
void DEMO_ADC16_IRQHandler(void)
{
g_Adc16ConversionDoneFlag = true;
// Read the conversion result to clear the conversion completed flag.
g_Adc16ConversionValue = ADC16_ChannelConversionValue(DEMO_ADC16_INSTANCE, DEMO_ADC16_CHANNEL_GROUP
);
g_Adc16InterruptCount++;
}
Data Structures
• struct adc16_config_t
ADC16 converter configuration. More...
• struct adc16_hardware_compare_config_t
ADC16 Hardware comparison configuration. More...
• struct adc16_channel_config_t
ADC16 channel conversion configuration. More...
Enumerations
• enum _adc16_channel_status_flags { kADC16_ChannelConversionDoneFlag = ADC_SC1_COC-
O_MASK }
Driver version
• #define FSL_ADC16_DRIVER_VERSION (MAKE_VERSION(2, 0, 0))
ADC16 driver version 2.0.0.
Initialization
• void ADC16_Init (ADC_Type ∗base, const adc16_config_t ∗config)
Initializes the ADC16 module.
• void ADC16_Deinit (ADC_Type ∗base)
De-initializes the ADC16 module.
• void ADC16_GetDefaultConfig (adc16_config_t ∗config)
Gets an available pre-defined settings for the converter’s configuration.
• status_t ADC16_DoAutoCalibration (ADC_Type ∗base)
Automates the hardware calibration.
• static void ADC16_SetOffsetValue (ADC_Type ∗base, int16_t value)
Sets the offset value for the conversion result.
Advanced Features
• static void ADC16_EnableDMA (ADC_Type ∗base, bool enable)
Enables generating the DMA trigger when the conversion is complete.
• static void ADC16_EnableHardwareTrigger (ADC_Type ∗base, bool enable)
Enables the hardware trigger mode.
• void ADC16_SetChannelMuxMode (ADC_Type ∗base, adc16_channel_mux_mode_t mode)
Sets the channel mux mode.
• void ADC16_SetHardwareCompareConfig (ADC_Type ∗base, const adc16_hardware_compare_-
config_t ∗config)
Configures the hardware compare mode.
• void ADC16_SetHardwareAverage (ADC_Type ∗base, adc16_hardware_average_mode_t mode)
Sets the hardware average mode.
• uint32_t ADC16_GetStatusFlags (ADC_Type ∗base)
Gets the status flags of the converter.
• void ADC16_ClearStatusFlags (ADC_Type ∗base, uint32_t mask)
Clears the status flags of the converter.
Conversion Channel
• void ADC16_SetChannelConfig (ADC_Type ∗base, uint32_t channelGroup, const adc16_channel-
_config_t ∗config)
Configures the conversion channel.
• static uint32_t ADC16_GetChannelConversionValue (ADC_Type ∗base, uint32_t channelGroup)
Gets the conversion value.
• uint32_t ADC16_GetChannelStatusFlags (ADC_Type ∗base, uint32_t channelGroup)
Gets the status flags of channel.
Data Fields
• adc16_reference_voltage_source_t referenceVoltageSource
Select the reference voltage source.
• adc16_clock_source_t clockSource
Select the input clock source to converter.
• bool enableAsynchronousClock
Enable the asynchronous clock output.
• adc16_clock_divider_t clockDivider
Select the divider of input clock source.
• adc16_resolution_t resolution
Select the sample resolution mode.
• adc16_long_sample_mode_t longSampleMode
Select the long sample mode.
• bool enableHighSpeed
Enable the high-speed mode.
• bool enableLowPower
Enable low power.
• bool enableContinuousConversion
Enable continuous conversion mode.
Data Fields
• adc16_hardware_compare_mode_t hardwareCompareMode
Select the hardware compare mode.
• int16_t value1
Setting value1 for hardware compare mode.
• int16_t value2
Setting value2 for hardware compare mode.
See "adc16_hardware_compare_mode_t".
Data Fields
• uint32_t channelNumber
Setting the conversion channel number.
• bool enableInterruptOnConversionCompleted
The available range is 0-31. See channel connection information for each chip in Reference Manual
document.
Enumerator
kADC16_ChannelConversionDoneFlag Conversion done.
Enumerator
kADC16_ActiveFlag Converter is active.
kADC16_CalibrationFailedFlag Calibration is failed.
For some ADC16 channels, there are two pin selections in channel multiplexer. For example, ADC0_SE4a
and ADC0_SE4b are the different channels that share the same channel number.
Enumerator
kADC16_ChannelMuxA For channel with channel mux a.
kADC16_ChannelMuxB For channel with channel mux b.
Enumerator
kADC16_ClockDivider1 For divider 1 from the input clock to the module.
kADC16_ClockDivider2 For divider 2 from the input clock to the module.
kADC16_ClockDivider4 For divider 4 from the input clock to the module.
kADC16_ClockDivider8 For divider 8 from the input clock to the module.
Enumerator
kADC16_Resolution8or9Bit Single End 8-bit or Differential Sample 9-bit.
kADC16_Resolution12or13Bit Single End 12-bit or Differential Sample 13-bit.
kADC16_Resolution10or11Bit Single End 10-bit or Differential Sample 11-bit.
kADC16_ResolutionSE8Bit Single End 8-bit.
kADC16_ResolutionSE12Bit Single End 12-bit.
kADC16_ResolutionSE10Bit Single End 10-bit.
kADC16_ResolutionDF9Bit Differential Sample 9-bit.
kADC16_ResolutionDF13Bit Differential Sample 13-bit.
kADC16_ResolutionDF11Bit Differential Sample 11-bit.
kADC16_Resolution16Bit Single End 16-bit or Differential Sample 16-bit.
kADC16_ResolutionSE16Bit Single End 16-bit.
kADC16_ResolutionDF16Bit Differential Sample 16-bit.
Enumerator
kADC16_ClockSourceAlt0 Selection 0 of the clock source.
kADC16_ClockSourceAlt1 Selection 1 of the clock source.
kADC16_ClockSourceAlt2 Selection 2 of the clock source.
kADC16_ClockSourceAlt3 Selection 3 of the clock source.
kADC16_ClockSourceAsynchronousClock Using internal asynchronous clock.
Enumerator
kADC16_LongSampleCycle24 20 extra ADCK cycles, 24 ADCK cycles total.
kADC16_LongSampleCycle16 12 extra ADCK cycles, 16 ADCK cycles total.
Enumerator
kADC16_ReferenceVoltageSourceVref For external pins pair of VrefH and VrefL.
kADC16_ReferenceVoltageSourceValt For alternate reference pair of ValtH and ValtL.
Enumerator
kADC16_HardwareAverageCount4 For hardware average with 4 samples.
kADC16_HardwareAverageCount8 For hardware average with 8 samples.
kADC16_HardwareAverageCount16 For hardware average with 16 samples.
kADC16_HardwareAverageCount32 For hardware average with 32 samples.
kADC16_HardwareAverageDisabled Disable the hardware average feature.
Enumerator
kADC16_HardwareCompareMode0 x < value1.
kADC16_HardwareCompareMode1 x > value1.
kADC16_HardwareCompareMode2 if value1 <= value2, then x < value1 || x > value2; else,
value1 > x > value2.
kADC16_HardwareCompareMode3 if value1 <= value2, then value1 <= x <= value2; else x >=
value1 || x <= value2.
Parameters
Parameters
This function initializes the converter configuration structure with available settings. The default values
are as follows.
* config->referenceVoltageSource = kADC16_ReferenceVoltageSourceVref
;
* config->clockSource = kADC16_ClockSourceAsynchronousClock
;
* config->enableAsynchronousClock = true;
* config->clockDivider = kADC16_ClockDivider8;
* config->resolution = kADC16_ResolutionSE12Bit;
* config->longSampleMode = kADC16_LongSampleDisabled;
* config->enableHighSpeed = false;
* config->enableLowPower = false;
* config->enableContinuousConversion = false;
*
Parameters
This auto calibration helps to adjust the plus/minus side gain automatically. Execute the calibration before
using the converter. Note that the hardware trigger should be used during the calibration.
Parameters
Returns
Execution status.
Return values
This offset value takes effect on the conversion result. If the offset value is not zero, the reading result is
subtracted by it. Note, the hardware calibration fills the offset value automatically.
Parameters
Parameters
Parameters
Some sample pins share the same channel index. The channel mux mode decides which pin is used for an
indicated channel.
Parameters
The hardware compare mode provides a way to process the conversion result automatically by using
hardware. Only the result in the compare range is available. To compare the range, see "adc16_hardware-
_compare_mode_t" or the appopriate reference manual for more information.
Parameters
The hardware average mode provides a way to process the conversion result automatically by using hard-
ware. The multiple conversion results are accumulated and averaged internally making them easier to
read.
Parameters
Parameters
Returns
Flags’ mask if indicated flags are asserted. See "_adc16_status_flags".
Parameters
This operation triggers the conversion when in software trigger mode. When in hardware trigger mode,
this API configures the channel while the external trigger source helps to trigger the conversion.
Note that the "Channel Group" has a detailed description. To allow sequential conversions of the ADC
to be triggered by internal peripherals, the ADC has more than one group of status and control registers,
one for each conversion. The channel group parameter indicates which group of registers are used, for
example, channel group 0 is for Group A registers and channel group 1 is for Group B registers. The
channel groups are used in a "ping-pong" approach to control the ADC operation. At any point, only
one of the channel groups is actively controlling ADC conversions. The channel group 0 is used for
both software and hardware trigger modes. Channel group 1 and greater indicates multiple channel group
registers for use only in hardware trigger mode. See the chip configuration information in the appropriate
MCU reference manual for the number of SC1n registers (channel groups) specific to this device. Channel
group 1 or greater are not used for software trigger operation. Therefore, writing to these channel groups
does not initiate a new conversion. Updating the channel group 0 while a different channel group is
actively controlling a conversion is allowed and vice versa. Writing any of the channel group registers
while that specific channel group is actively controlling a conversion aborts the current conversion.
Parameters
Parameters
Returns
Conversion value.
Parameters
Returns
Flags’ mask if indicated flags are asserted. See "_adc16_channel_status_flags".
int main(void)
{
cmp_config_t mCmpConfigStruct;
cmp_dac_config_t mCmpDacConfigStruct;
// ...
while (1)
{
if (0U != (kCMP_OutputAssertEventFlag &
CMP_GetStatusFlags(DEMO_CMP_INSTANCE)))
{
// Do something.
}
else
{
// Do something.
}
}
}
// ...
void DEMO_CMP_IRQ_HANDLER_FUNC(void)
{
g_CmpFlags = CMP_GetStatusFlags(DEMO_CMP_INSTANCE);
CMP_ClearStatusFlags(DEMO_CMP_INSTANCE, kCMP_OutputRisingEventFlag |
kCMP_OutputFallingEventFlag);
if (0U != (g_CmpFlags & kCMP_OutputRisingEventFlag))
{
// Do something.
}
else if (0U != (g_CmpFlags & kCMP_OutputFallingEventFlag))
{
// Do something.
}
}
int main(void)
{
cmp_config_t mCmpConfigStruct;
cmp_dac_config_t mCmpDacConfigStruct;
// ...
EnableIRQ(DEMO_CMP_IRQ_ID);
// ...
while (1)
{
}
}
Data Structures
• struct cmp_config_t
Configures the comparator. More...
• struct cmp_filter_config_t
Configures the filter. More...
• struct cmp_dac_config_t
Configures the internal DAC. More...
Enumerations
• enum _cmp_interrupt_enable {
kCMP_OutputRisingInterruptEnable = CMP_SCR_IER_MASK,
kCMP_OutputFallingInterruptEnable = CMP_SCR_IEF_MASK }
Interrupt enable/disable mask.
• enum _cmp_status_flags {
kCMP_OutputRisingEventFlag = CMP_SCR_CFR_MASK,
kCMP_OutputFallingEventFlag = CMP_SCR_CFF_MASK,
kCMP_OutputAssertEventFlag = CMP_SCR_COUT_MASK }
Status flags’ mask.
• enum cmp_hysteresis_mode_t {
kCMP_HysteresisLevel0 = 0U,
kCMP_HysteresisLevel1 = 1U,
kCMP_HysteresisLevel2 = 2U,
kCMP_HysteresisLevel3 = 3U }
CMP Hysteresis mode.
• enum cmp_reference_voltage_source_t {
kCMP_VrefSourceVin1 = 0U,
kCMP_VrefSourceVin2 = 1U }
CMP Voltage Reference source.
Driver version
• #define FSL_CMP_DRIVER_VERSION (MAKE_VERSION(2, 0, 0))
CMP driver version 2.0.0.
Initialization
• void CMP_Init (CMP_Type ∗base, const cmp_config_t ∗config)
Initializes the CMP.
• void CMP_Deinit (CMP_Type ∗base)
De-initializes the CMP module.
• static void CMP_Enable (CMP_Type ∗base, bool enable)
Enables/disables the CMP module.
• void CMP_GetDefaultConfig (cmp_config_t ∗config)
Initializes the CMP user configuration structure.
• void CMP_SetInputChannels (CMP_Type ∗base, uint8_t positiveChannel, uint8_t negativeChannel)
Sets the input channels for the comparator.
Advanced Features
• void CMP_EnableDMA (CMP_Type ∗base, bool enable)
Enables/disables the DMA request for rising/falling events.
• static void CMP_EnableWindowMode (CMP_Type ∗base, bool enable)
Enables/disables the window mode.
• static void CMP_EnablePassThroughMode (CMP_Type ∗base, bool enable)
Enables/disables the pass through mode.
• void CMP_SetFilterConfig (CMP_Type ∗base, const cmp_filter_config_t ∗config)
Configures the filter.
Results
• uint32_t CMP_GetStatusFlags (CMP_Type ∗base)
Gets the status flags.
• void CMP_ClearStatusFlags (CMP_Type ∗base, uint32_t mask)
Clears the status flags.
Data Fields
• bool enableCmp
Enable the CMP module.
• cmp_hysteresis_mode_t hysteresisMode
CMP Hysteresis mode.
• bool enableHighSpeed
Enable High-speed (HS) comparison mode.
• bool enableInvertOutput
Enable the inverted comparator output.
• bool useUnfilteredOutput
Set the compare output(COUT) to equal COUTA(true) or COUT(false).
• bool enablePinOut
The comparator output is available on the associated pin.
• bool enableTriggerMode
Enable the trigger mode.
Data Fields
• bool enableSample
Using the external SAMPLE as a sampling clock input or using a divided bus clock.
• uint8_t filterCount
Filter Sample Count.
• uint8_t filterPeriod
Filter Sample Period.
Data Fields
• cmp_reference_voltage_source_t referenceVoltageSource
Supply voltage reference source.
• uint8_t DACValue
Value for the DAC Output Voltage.
Enumerator
kCMP_OutputRisingInterruptEnable Comparator interrupt enable rising.
kCMP_OutputFallingInterruptEnable Comparator interrupt enable falling.
Enumerator
kCMP_OutputRisingEventFlag Rising-edge on the comparison output has occurred.
kCMP_OutputFallingEventFlag Falling-edge on the comparison output has occurred.
kCMP_OutputAssertEventFlag Return the current value of the analog comparator output.
Enumerator
kCMP_HysteresisLevel0 Hysteresis level 0.
kCMP_HysteresisLevel1 Hysteresis level 1.
kCMP_HysteresisLevel2 Hysteresis level 2.
kCMP_HysteresisLevel3 Hysteresis level 3.
Enumerator
kCMP_VrefSourceVin1 Vin1 is selected as a resistor ladder network supply reference Vin.
kCMP_VrefSourceVin2 Vin2 is selected as a resistor ladder network supply reference Vin.
This function initializes the CMP module. The operations included are as follows.
• Enabling the clock for CMP module.
• Configuring the comparator.
• Enabling the CMP module. Note that for some devices, multiple CMP instances share the same
clock gate. In this case, to enable the clock for any instance enables all CMPs. See the appropriate
MCU reference manual for the clock assignment of the CMP.
Parameters
This function de-initializes the CMP module. The operations included are as follows.
• Disabling the CMP module.
• Disabling the clock for CMP module.
This function disables the clock for the CMP. Note that for some devices, multiple CMP instances share
the same clock gate. In this case, before disabling the clock for the CMP, ensure that all the CMP instances
are not used.
Parameters
Parameters
This function initializes the user configuration structure to these default values.
* config->enableCmp = true;
* config->hysteresisMode = kCMP_HysteresisLevel0;
* config->enableHighSpeed = false;
* config->enableInvertOutput = false;
* config->useUnfilteredOutput = false;
* config->enablePinOut = false;
* config->enableTriggerMode = false;
*
Parameters
This function sets the input channels for the comparator. Note that two input channels cannot be set the
same way in the application. When the user selects the same input from the analog mux to the positive
and negative port, the comparator is disabled automatically.
Parameters
This function enables/disables the DMA request for rising/falling events. Either event triggers the genera-
tion of the DMA request from CMP if the DMA feature is enabled. Both events are ignored for generating
the DMA request from the CMP if the DMA is disabled.
Parameters
Parameters
Parameters
Parameters
Parameters
Parameters
Parameters
Parameters
Returns
Mask value for the asserted flags. See "_cmp_status_flags".
Parameters
Data Structures
• struct cop_config_t
Describes COP configuration structure. More...
Enumerations
• enum cop_clock_source_t {
kCOP_LpoClock = 0U,
kCOP_BusClock = 3U }
COP clock source selection.
• enum cop_timeout_cycles_t {
kCOP_2Power5CyclesOr2Power13Cycles = 1U,
kCOP_2Power8CyclesOr2Power16Cycles = 2U,
kCOP_2Power10CyclesOr2Power18Cycles = 3U }
Define the COP timeout cycles.
Driver version
• #define FSL_COP_DRIVER_VERSION (MAKE_VERSION(2, 0, 0))
COP driver version 2.0.0.
Data Fields
• bool enableWindowMode
COP run mode: window mode or normal mode.
• cop_clock_source_t clockSource
Set COP clock source.
• cop_timeout_cycles_t timeoutCycles
Set COP timeout value.
Enumerator
kCOP_LpoClock COP clock sourced from LPO.
kCOP_BusClock COP clock sourced from Bus clock.
Enumerator
kCOP_2Power5CyclesOr2Power13Cycles 2∧ 5 or 2∧ 13 clock cycles
kCOP_2Power8CyclesOr2Power16Cycles 2∧ 8 or 2∧ 16 clock cycles
kCOP_2Power10CyclesOr2Power18Cycles 2∧ 10 or 2∧ 18 clock cycles
This function initializes the COP configuration structure to default values. The default values are:
* copConfig->enableWindowMode = false;
* copConfig->timeoutMode = kCOP_LongTimeoutMode;
* copConfig->enableStop = false;
* copConfig->enableDebug = false;
* copConfig->clockSource = kCOP_LpoClock;
* copConfig->timeoutCycles = kCOP_2Power10CyclesOr2Power18Cycles;
*
Parameters
See Also
cop_config_t
This function configures the COP. After it is called, the COP starts running according to the configura-
tion. Because all COP control registers are write-once only, the COP_Init function and the COP_Disable
function can be called only once. A second call has no effect.
Example:
* cop_config_t config;
* COP_GetDefaultConfig(&config);
* config.timeoutCycles = kCOP_2Power8CyclesOr2Power16Cycles
;
* COP_Init(sim_base,&config);
*
Parameters
This dedicated function is not provided. Instead, the COP_Disable function can be used to disable the
COP.
Parameters
// ...
// ...
// ...
EnableIRQ(DEMO_DAC_IRQ_ID);
// ...
// Enables interrupts.
mask = 0U;
#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION
mask |= kDAC_BufferWatermarkInterruptEnable;
#endif // FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION
mask |= kDAC_BufferReadPointerTopInterruptEnable |
kDAC_BufferReadPointerBottomInterruptEnable;
DAC_EnableBuffer(DEMO_DAC_INSTANCE, true);
DAC_EnableBufferInterrupts(DEMO_DAC_INSTANCE, mask);
Data Structures
• struct dac_config_t
DAC module configuration. More...
• struct dac_buffer_config_t
DAC buffer configuration. More...
Enumerations
• enum _dac_buffer_status_flags {
kDAC_BufferReadPointerTopPositionFlag = DAC_SR_DACBFRPTF_MASK,
kDAC_BufferReadPointerBottomPositionFlag = DAC_SR_DACBFRPBF_MASK }
Driver version
• #define FSL_DAC_DRIVER_VERSION (MAKE_VERSION(2, 0, 1))
DAC driver version 2.0.1.
Initialization
• void DAC_Init (DAC_Type ∗base, const dac_config_t ∗config)
Initializes the DAC module.
• void DAC_Deinit (DAC_Type ∗base)
De-initializes the DAC module.
• void DAC_GetDefaultConfig (dac_config_t ∗config)
Initializes the DAC user configuration structure.
• static void DAC_Enable (DAC_Type ∗base, bool enable)
Enables the DAC module.
Buffer
• static void DAC_EnableBuffer (DAC_Type ∗base, bool enable)
Enables the DAC buffer.
• void DAC_SetBufferConfig (DAC_Type ∗base, const dac_buffer_config_t ∗config)
Configures the CMP buffer.
• void DAC_GetDefaultBufferConfig (dac_buffer_config_t ∗config)
Initializes the DAC buffer configuration structure.
• static void DAC_EnableBufferDMA (DAC_Type ∗base, bool enable)
Enables the DMA for DAC buffer.
• void DAC_SetBufferValue (DAC_Type ∗base, uint8_t index, uint16_t value)
Sets the value for items in the buffer.
• static void DAC_DoSoftwareTriggerBuffer (DAC_Type ∗base)
Triggers the buffer using software and updates the read pointer of the DAC buffer.
• static uint8_t DAC_GetBufferReadPointer (DAC_Type ∗base)
Gets the current read pointer of the DAC buffer.
Data Fields
• dac_reference_voltage_source_t referenceVoltageSource
Select the DAC reference voltage source.
• bool enableLowPowerMode
Enable the low-power mode.
Data Fields
• dac_buffer_trigger_mode_t triggerMode
Select the buffer’s trigger mode.
• dac_buffer_work_mode_t workMode
Select the buffer’s work mode.
• uint8_t upperLimit
Set the upper limit for the buffer index.
Enumerator
kDAC_BufferReadPointerTopPositionFlag DAC Buffer Read Pointer Top Position Flag.
kDAC_BufferReadPointerBottomPositionFlag DAC Buffer Read Pointer Bottom Position Flag.
Enumerator
kDAC_BufferReadPointerTopInterruptEnable DAC Buffer Read Pointer Top Flag Interrupt En-
able.
kDAC_BufferReadPointerBottomInterruptEnable DAC Buffer Read Pointer Bottom Flag Inter-
rupt Enable.
Enumerator
kDAC_ReferenceVoltageSourceVref1 The DAC selects DACREF_1 as the reference voltage.
kDAC_ReferenceVoltageSourceVref2 The DAC selects DACREF_2 as the reference voltage.
Enumerator
kDAC_BufferTriggerByHardwareMode The DAC hardware trigger is selected.
kDAC_BufferTriggerBySoftwareMode The DAC software trigger is selected.
Enumerator
kDAC_BufferWorkAsNormalMode Normal mode.
kDAC_BufferWorkAsOneTimeScanMode One-Time Scan mode.
This function initializes the DAC module including the following operations.
• Enabling the clock for DAC module.
• Configuring the DAC converter with a user configuration.
• Enabling the DAC module.
Parameters
This function de-initializes the DAC module including the following operations.
• Disabling the DAC module.
• Disabling the clock for the DAC module.
Parameters
This function initializes the user configuration structure to a default value. The default values are as
follows.
* config->referenceVoltageSource = kDAC_ReferenceVoltageSourceVref2;
* config->enableLowPowerMode = false;
*
Parameters
Parameters
Parameters
Parameters
This function initializes the DAC buffer configuration structure to default values. The default values are
as follows.
* config->triggerMode = kDAC_BufferTriggerBySoftwareMode;
* config->watermark = kDAC_BufferWatermark1Word;
* config->workMode = kDAC_BufferWorkAsNormalMode;
* config->upperLimit = DAC_DATL_COUNT - 1U;
*
Parameters
Parameters
Parameters
This function triggers the function using software. The read pointer of the DAC buffer is updated with one
step after this function is called. Changing the read pointer depends on the buffer’s work mode.
Parameters
This function gets the current read pointer of the DAC buffer. The current output value depends on the
item indexed by the read pointer. It is updated either by a software trigger or a hardware trigger.
Parameters
Returns
The current read pointer of the DAC buffer.
This function sets the current read pointer of the DAC buffer. The current output value depends on the
item indexed by the read pointer. It is updated either by a software trigger or a hardware trigger. After the
read pointer changes, the DAC output value also changes.
Parameters
Parameters
Parameters
Parameters
Returns
Mask value for the asserted flags. See "_dac_buffer_status_flags".
Parameters
dma_transfer_config_t transferConfig;
uint32_t transferDone = false;
DMA_Init(DMA0);
DMA_CreateHandle(&g_DMA_Handle, DMA0, channel);
DMA_InstallCallback(&g_DMA_Handle, DMA_Callback, &transferDone);
DMA_PrepareTransfer(&transferConfig, srcAddr, srcWidth, destAddr, destWidth,
transferBytes,
kDMA_MemoryToMemory);
DMA_SubmitTransfer(&g_DMA_Handle, &transferConfig, true);
DMA_StartTransfer(&g_DMA_Handle);
/* Wait for DMA transfer finish */
while (transferDone != true);
Data Structures
• struct dma_transfer_config_t
DMA transfer configuration structure. More...
• struct dma_channel_link_config_t
DMA transfer configuration structure. More...
• struct dma_handle_t
DMA DMA handle structure. More...
Typedefs
• typedef void(∗ dma_callback )(struct _dma_handle ∗handle, void ∗userData)
Callback function prototype for the DMA driver.
Enumerations
• enum _dma_channel_status_flags {
kDMA_TransactionsBCRFlag = DMA_DSR_BCR_BCR_MASK,
kDMA_TransactionsDoneFlag = DMA_DSR_BCR_DONE_MASK,
kDMA_TransactionsBusyFlag = DMA_DSR_BCR_BSY_MASK,
kDMA_TransactionsRequestFlag = DMA_DSR_BCR_REQ_MASK,
kDMA_BusErrorOnDestinationFlag = DMA_DSR_BCR_BED_MASK,
kDMA_BusErrorOnSourceFlag = DMA_DSR_BCR_BES_MASK,
kDMA_ConfigurationErrorFlag = DMA_DSR_BCR_CE_MASK }
status flag for the DMA driver.
• enum dma_transfer_size_t {
kDMA_Transfersize32bits = 0x0U,
kDMA_Transfersize8bits,
kDMA_Transfersize16bits }
DMA transfer size type.
• enum dma_modulo_t {
kDMA_ModuloDisable = 0x0U,
kDMA_Modulo16Bytes,
kDMA_Modulo32Bytes,
kDMA_Modulo64Bytes,
kDMA_Modulo128Bytes,
kDMA_Modulo256Bytes,
kDMA_Modulo512Bytes,
kDMA_Modulo1KBytes,
kDMA_Modulo2KBytes,
kDMA_Modulo4KBytes,
kDMA_Modulo8KBytes,
kDMA_Modulo16KBytes,
kDMA_Modulo32KBytes,
kDMA_Modulo64KBytes,
kDMA_Modulo128KBytes,
kDMA_Modulo256KBytes }
Configuration type for the DMA modulo.
• enum dma_channel_link_type_t {
kDMA_ChannelLinkDisable = 0x0U,
kDMA_ChannelLinkChannel1AndChannel2,
kDMA_ChannelLinkChannel1,
kDMA_ChannelLinkChannel1AfterBCR0 }
DMA channel link type.
• enum dma_transfer_type_t {
kDMA_MemoryToMemory = 0x0U,
kDMA_PeripheralToMemory,
kDMA_MemoryToPeripheral }
DMA transfer type.
• enum dma_transfer_options_t {
kDMA_NoOptions = 0x0U,
kDMA_EnableInterrupt }
DMA transfer options.
• enum _dma_transfer_status
DMA transfer status.
Driver version
• #define FSL_DMA_DRIVER_VERSION (MAKE_VERSION(2, 0, 1))
DMA driver version 2.0.1.
Data Fields
• uint32_t srcAddr
DMA transfer source address.
• uint32_t destAddr
DMA destination address.
• bool enableSrcIncrement
Source address increase after each transfer.
• dma_transfer_size_t srcSize
Source transfer size unit.
• bool enableDestIncrement
Destination address increase after each transfer.
• dma_transfer_size_t destSize
Destination transfer unit.
• uint32_t transferSize
The number of bytes to be transferred.
Data Fields
• dma_channel_link_type_t linkType
Channel link type.
• uint32_t channel1
The index of channel 1.
• uint32_t channel2
The index of channel 2.
Data Fields
• DMA_Type ∗ base
DMA peripheral address.
• uint8_t channel
DMA channel used.
• dma_callback callback
DMA callback function.
• void ∗ userData
Callback parameter.
Enumerator
kDMA_TransactionsBCRFlag Contains the number of bytes yet to be transferred for a given block.
Enumerator
kDMA_Transfersize32bits 32 bits are transferred for every read/write
kDMA_Transfersize8bits 8 bits are transferred for every read/write
kDMA_Transfersize16bits 16b its are transferred for every read/write
Enumerator
kDMA_ModuloDisable Buffer disabled.
Enumerator
kDMA_ChannelLinkDisable No channel link.
kDMA_ChannelLinkChannel1AndChannel2 Perform a link to channel LCH1 after each cycle-
steal transfer. followed by a link to LCH2 after the BCR decrements to 0.
kDMA_ChannelLinkChannel1 Perform a link to LCH1 after each cycle-steal transfer.
kDMA_ChannelLinkChannel1AfterBCR0 Perform a link to LCH1 after the BCR decrements.
Enumerator
kDMA_MemoryToMemory Memory to Memory transfer.
kDMA_PeripheralToMemory Peripheral to Memory transfer.
kDMA_MemoryToPeripheral Memory to Peripheral transfer.
Enumerator
kDMA_NoOptions Transfer without options.
kDMA_EnableInterrupt Enable interrupt while transfer complete.
Parameters
Sets all register values to reset values and enables the cycle steal and auto stop channel request features.
Parameters
This function configures the transfer attribute including the source address, destination address, transfer
size, and so on. This example shows how to set up the the dma_transfer_config_t parameters and how to
call the DMA_ConfigBasicTransfer function.
* dma_transfer_config_t transferConfig;
* memset(&transferConfig, 0, sizeof(transferConfig));
* transferConfig.srcAddr = (uint32_t)srcAddr;
* transferConfig.destAddr = (uint32_t)destAddr;
* transferConfig.enbaleSrcIncrement = true;
* transferConfig.enableDestIncrement = true;
* transferConfig.srcSize = kDMA_Transfersize32bits;
* transferConfig.destSize = kDMA_Transfersize32bits;
* transferConfig.transferSize = sizeof(uint32_t) * BUFF_LENGTH;
* DMA_SetTransferConfig(DMA0, 0, &transferConfig);
*
Parameters
This function allows DMA channels to have their transfers linked. The current DMA channel triggers a
DMA request to the linked channels (LCH1 or LCH2) depending on the channel link type. Perform a link
to channel LCH1 after each cycle-steal transfer followed by a link to LCH2 after the BCR decrements to 0
if the type is kDMA_ChannelLinkChannel1AndChannel2. Perform a link to LCH1 after each cycle-steal
transfer if the type is kDMA_ChannelLinkChannel1. Perform a link to LCH1 after the BCR decrements
to 0 if the type is kDMA_ChannelLinkChannel1AfterBCR0.
Parameters
Parameters
Parameters
Parameters
This function defines a specific address range specified to be the value after (SAR + SSIZE)/(DAR + DS-
IZE) calculation is performed or the original register value. It provides the ability to implement a circular
data queue easily.
Parameters
If the cycle steal feature is enabled (true), the DMA controller forces a single read/write transfer per
request, or it continuously makes read/write transfers until the BCR decrements to 0.
Parameters
If the auto align feature is enabled (true), the appropriate address register increments regardless of DINC
or SINC.
Parameters
If the async request feature is enabled (true), the DMA supports asynchronous DREQs while the MCU is
in stop mode.
Parameters
Parameters
Parameters
Parameters
Parameters
Parameters
Parameters
Returns
The number of bytes which have not been transferred yet.
Parameters
Returns
The mask of the channel status. Use the _dma_channel_status_flags type to decode the return 32 bit
variables.
Parameters
This function is called first if using the transactional API for the DMA. This function initializes the internal
state of the DMA handle.
Parameters
handle DMA handle pointer. The DMA handle stores callback function and parameters.
base DMA peripheral base address.
channel DMA channel number.
This callback is called in the DMA IRQ handler. Use the callback to do something after the current transfer
complete.
Parameters
This function prepares the transfer configuration structure according to the user input.
Parameters
This function submits the DMA transfer request according to the transfer configuration structure.
Parameters
Return values
Note
This function can’t process multi transfer request.
This function enables the channel request. Call this function after submitting a transfer request.
Parameters
Return values
This function disables the channel request to stop a DMA transfer. The transfer can be resumed by calling
the DMA_StartTransfer.
Parameters
This function disables the channel request and clears all status bits. Submit another transfer after calling
this API.
Parameters
This function clears the channel interrupt flag and calls the callback function if it is not NULL.
Parameters
DMAMUX_Init(DMAMUX0);
DMAMUX_SetSource(DMAMUX0, channel, source);
DMAMUX_EnableChannel(DMAMUX0, channel);
...
DMAMUX_DisableChannel(DMAMUX, channel);
DMAMUX_Deinit(DMAMUX0);
Driver version
• #define FSL_DMAMUX_DRIVER_VERSION (MAKE_VERSION(2, 0, 2))
DMAMUX driver version 2.0.2.
Parameters
Note
The user must disable the DMAMUX channel before configuring it.
Parameters
Parameters
Data Structures
• struct flash_execute_in_ram_function_config_t
Flash execute-in-RAM function information. More...
• struct flash_swap_state_config_t
Flash Swap information. More...
• struct flash_swap_ifr_field_config_t
Flash Swap IFR fields. More...
• union flash_swap_ifr_field_data_t
Flash Swap IFR field data. More...
• union pflash_protection_status_low_t
PFlash protection status - low 32bit. More...
• struct pflash_protection_status_t
PFlash protection status - full. More...
• struct flash_prefetch_speculation_status_t
Flash prefetch speculation status. More...
• struct flash_protection_config_t
Active flash protection information for the current operation. More...
• struct flash_access_config_t
Active flash Execute-Only access information for the current operation. More...
• struct flash_operation_config_t
Active flash information for the current operation. More...
• struct flash_config_t
Flash driver state information. More...
Typedefs
• typedef void(∗ flash_callback_t )(void)
A callback type used for the Pflash block.
Enumerations
• enum flash_margin_value_t {
kFLASH_MarginValueNormal,
kFLASH_MarginValueUser,
kFLASH_MarginValueFactory,
kFLASH_MarginValueInvalid }
Enumeration for supported flash margin levels.
• enum flash_security_state_t {
kFLASH_SecurityStateNotSecure,
kFLASH_SecurityStateBackdoorEnabled,
kFLASH_SecurityStateBackdoorDisabled }
Enumeration for the three possible flash security states.
• enum flash_protection_state_t {
kFLASH_ProtectionStateUnprotected,
kFLASH_ProtectionStateProtected,
kFLASH_ProtectionStateMixed }
Enumeration for the three possible flash protection levels.
• enum flash_execute_only_access_state_t {
kFLASH_AccessStateUnLimited,
kFLASH_AccessStateExecuteOnly,
kFLASH_AccessStateMixed }
Enumeration for the three possible flash execute access levels.
• enum flash_property_tag_t {
kFLASH_PropertyPflashSectorSize = 0x00U,
kFLASH_PropertyPflashTotalSize = 0x01U,
kFLASH_PropertyPflashBlockSize = 0x02U,
kFLASH_PropertyPflashBlockCount = 0x03U,
kFLASH_PropertyPflashBlockBaseAddr = 0x04U,
kFLASH_PropertyPflashFacSupport = 0x05U,
kFLASH_PropertyPflashAccessSegmentSize = 0x06U,
kFLASH_PropertyPflashAccessSegmentCount = 0x07U,
kFLASH_PropertyFlexRamBlockBaseAddr = 0x08U,
kFLASH_PropertyFlexRamTotalSize = 0x09U,
kFLASH_PropertyDflashSectorSize = 0x10U,
kFLASH_PropertyDflashTotalSize = 0x11U,
kFLASH_PropertyDflashBlockSize = 0x12U,
kFLASH_PropertyDflashBlockCount = 0x13U,
kFLASH_PropertyDflashBlockBaseAddr = 0x14U,
kFLASH_PropertyEepromTotalSize = 0x15U,
kFLASH_PropertyFlashMemoryIndex = 0x20U,
kFLASH_PropertyFlashCacheControllerIndex = 0x21U }
Enumeration for various flash properties.
• enum _flash_execute_in_ram_function_constants {
kFLASH_ExecuteInRamFunctionMaxSizeInWords = 16U,
kFLASH_ExecuteInRamFunctionTotalNum = 2U }
Constants for execute-in-RAM flash function.
• enum flash_read_resource_option_t {
kFLASH_ResourceOptionFlashIfr,
kFLASH_ResourceOptionVersionId = 0x01U }
Enumeration for the two possible options of flash read resource command.
• enum _flash_read_resource_range {
kFLASH_ResourceRangePflashIfrSizeInBytes = 256U,
kFLASH_ResourceRangeVersionIdSizeInBytes = 8U,
kFLASH_ResourceRangeVersionIdStart = 0x00U,
kFLASH_ResourceRangeVersionIdEnd = 0x07U ,
kFLASH_ResourceRangePflashSwapIfrEnd,
kFLASH_ResourceRangeDflashIfrStart = 0x800000U,
kFLASH_ResourceRangeDflashIfrEnd = 0x8003FFU }
Enumeration for the range of special-purpose flash resource.
• enum _k3_flash_read_once_index {
kFLASH_RecordIndexSwapAddr = 0xA1U,
kFLASH_RecordIndexSwapEnable = 0xA2U,
kFLASH_RecordIndexSwapDisable = 0xA3U }
Enumeration for the index of read/program once record.
• enum flash_flexram_function_option_t {
kFLASH_FlexramFunctionOptionAvailableAsRam = 0xFFU,
kFLASH_FlexramFunctionOptionAvailableForEeprom = 0x00U }
Enumeration for the two possilbe options of set FlexRAM function command.
• enum _flash_acceleration_ram_property
Enumeration for acceleration RAM property.
• enum flash_swap_function_option_t {
kFLASH_SwapFunctionOptionEnable = 0x00U,
kFLASH_SwapFunctionOptionDisable = 0x01U }
Enumeration for the possible options of Swap function.
• enum flash_swap_control_option_t {
kFLASH_SwapControlOptionIntializeSystem = 0x01U,
kFLASH_SwapControlOptionSetInUpdateState = 0x02U,
kFLASH_SwapControlOptionSetInCompleteState = 0x04U,
kFLASH_SwapControlOptionReportStatus = 0x08U,
kFLASH_SwapControlOptionDisableSystem = 0x10U }
Enumeration for the possible options of Swap control commands.
• enum flash_swap_state_t {
kFLASH_SwapStateUninitialized = 0x00U,
kFLASH_SwapStateReady = 0x01U,
kFLASH_SwapStateUpdate = 0x02U,
kFLASH_SwapStateUpdateErased = 0x03U,
kFLASH_SwapStateComplete = 0x04U,
kFLASH_SwapStateDisabled = 0x05U }
Enumeration for the possible flash Swap status.
• enum flash_swap_block_status_t {
kFLASH_SwapBlockStatusLowerHalfProgramBlocksAtZero,
kFLASH_SwapBlockStatusUpperHalfProgramBlocksAtZero }
Enumeration for the possible flash Swap block status
• enum flash_partition_flexram_load_option_t {
kFLASH_PartitionFlexramLoadOptionLoadedWithValidEepromData,
kFLASH_PartitionFlexramLoadOptionNotLoaded = 0x01U }
Enumeration for the FlexRAM load during reset option.
• enum flash_memory_index_t {
kFLASH_MemoryIndexPrimaryFlash = 0x00U,
kFLASH_MemoryIndexSecondaryFlash = 0x01U }
Enumeration for the flash memory index.
• enum flash_cache_controller_index_t {
kFLASH_CacheControllerIndexForCore0 = 0x00U,
kFLASH_CacheControllerIndexForCore1 = 0x01U }
Enumeration for the flash cache controller index.
• enum flash_prefetch_speculation_option_t
Enumeration for the two possible options of flash prefetch speculation.
• enum flash_cache_clear_process_t {
kFLASH_CacheClearProcessPre = 0x00U,
kFLASH_CacheClearProcessPost = 0x01U }
Flash cache clear process code.
Flash version
• enum _flash_driver_version_constants {
kFLASH_DriverVersionName = ’F’,
kFLASH_DriverVersionMajor = 2,
kFLASH_DriverVersionMinor = 3,
kFLASH_DriverVersionBugfix = 1 }
Flash driver version for ROM.
• #define MAKE_VERSION(major, minor, bugfix) (((major) << 16) | ((minor) << 8) | (bugfix))
Constructs the version number for drivers.
• #define FSL_FLASH_DRIVER_VERSION (MAKE_VERSION(2, 3, 1))
Flash driver version for SDK.
Flash configuration
• #define FLASH_SSD_CONFIG_ENABLE_FLEXNVM_SUPPORT 1
Indicates whether to support FlexNVM in the Flash driver.
• #define FLASH_SSD_IS_FLEXNVM_ENABLED (FLASH_SSD_CONFIG_ENABLE_FLEXN-
VM_SUPPORT && FSL_FEATURE_FLASH_HAS_FLEX_NVM)
Indicates whether the FlexNVM is enabled in the Flash driver.
• #define FLASH_SSD_CONFIG_ENABLE_SECONDARY_FLASH_SUPPORT 1
Indicates whether to support Secondary flash in the Flash driver.
• #define FLASH_SSD_IS_SECONDARY_FLASH_ENABLED (0)
Indicates whether the secondary flash is supported in the Flash driver.
• #define FLASH_DRIVER_IS_FLASH_RESIDENT 1
Flash driver location.
• #define FLASH_DRIVER_IS_EXPORTED 0
Flash Driver Export option.
Flash status
• enum _flash_status {
kStatus_FLASH_Success = MAKE_STATUS(kStatusGroupGeneric, 0),
kStatus_FLASH_InvalidArgument = MAKE_STATUS(kStatusGroupGeneric, 4),
kStatus_FLASH_SizeError = MAKE_STATUS(kStatusGroupFlashDriver, 0),
kStatus_FLASH_AlignmentError,
kStatus_FLASH_AddressError = MAKE_STATUS(kStatusGroupFlashDriver, 2),
kStatus_FLASH_AccessError,
kStatus_FLASH_ProtectionViolation,
kStatus_FLASH_CommandFailure,
kStatus_FLASH_UnknownProperty = MAKE_STATUS(kStatusGroupFlashDriver, 6),
kStatus_FLASH_EraseKeyError = MAKE_STATUS(kStatusGroupFlashDriver, 7),
kStatus_FLASH_RegionExecuteOnly,
kStatus_FLASH_ExecuteInRamFunctionNotReady,
kStatus_FLASH_PartitionStatusUpdateFailure,
kStatus_FLASH_SetFlexramAsEepromError,
kStatus_FLASH_RecoverFlexramAsRamError,
kStatus_FLASH_SetFlexramAsRamError = MAKE_STATUS(kStatusGroupFlashDriver, 13),
kStatus_FLASH_RecoverFlexramAsEepromError,
kStatus_FLASH_CommandNotSupported = MAKE_STATUS(kStatusGroupFlashDriver, 15),
kStatus_FLASH_SwapSystemNotInUninitialized,
kStatus_FLASH_SwapIndicatorAddressError,
kStatus_FLASH_ReadOnlyProperty = MAKE_STATUS(kStatusGroupFlashDriver, 18),
kStatus_FLASH_InvalidPropertyValue,
kStatus_FLASH_InvalidSpeculationOption }
Flash driver status codes.
• #define kStatusGroupGeneric 0
Flash driver status group.
• #define kStatusGroupFlashDriver 1
• #define MAKE_STATUS(group, code) ((((group)∗100) + (code)))
Constructs a status code value from a group and a code number.
Initialization
• status_t FLASH_Init (flash_config_t ∗config)
Initializes the global flash properties structure members.
• status_t FLASH_SetCallback (flash_config_t ∗config, flash_callback_t callback)
Sets the desired flash callback function.
• status_t FLASH_PrepareExecuteInRamFunctions (flash_config_t ∗config)
Prepares flash execute-in-RAM functions.
Erasing
• status_t FLASH_EraseAll (flash_config_t ∗config, uint32_t key)
Erases entire flash.
• status_t FLASH_Erase (flash_config_t ∗config, uint32_t start, uint32_t lengthInBytes, uint32_t key)
Erases the flash sectors encompassed by parameters passed into function.
• status_t FLASH_EraseAllExecuteOnlySegments (flash_config_t ∗config, uint32_t key)
Erases the entire flash, including protected sectors.
Programming
• status_t FLASH_Program (flash_config_t ∗config, uint32_t start, uint32_t ∗src, uint32_t lengthIn-
Bytes)
Programs flash with data at locations passed in through parameters.
• status_t FLASH_ProgramOnce (flash_config_t ∗config, uint32_t index, uint32_t ∗src, uint32_-
t lengthInBytes)
Programs Program Once Field through parameters.
Reading
Programs flash with data at locations passed in through parameters via the Program Section command.
This function programs the flash memory with the desired data for a given flash area as determined by the
start address and length.
Parameters
Return values
Return values
Security
• status_t FLASH_GetSecurityState (flash_config_t ∗config, flash_security_state_t ∗state)
Returns the security state via the pointer passed into the function.
• status_t FLASH_SecurityBypass (flash_config_t ∗config, const uint8_t ∗backdoorKey)
Allows users to bypass security with a backdoor key.
Verification
• status_t FLASH_VerifyEraseAll (flash_config_t ∗config, flash_margin_value_t margin)
Verifies erasure of the entire flash at a specified margin level.
• status_t FLASH_VerifyErase (flash_config_t ∗config, uint32_t start, uint32_t lengthInBytes, flash-
_margin_value_t margin)
Verifies an erasure of the desired flash area at a specified margin level.
• status_t FLASH_VerifyProgram (flash_config_t ∗config, uint32_t start, uint32_t lengthInBytes,
const uint32_t ∗expectedData, flash_margin_value_t margin, uint32_t ∗failedAddress, uint32_-
t ∗failedData)
Verifies programming of the desired flash area at a specified margin level.
• status_t FLASH_VerifyEraseAllExecuteOnlySegments (flash_config_t ∗config, flash_margin_-
value_t margin)
Verifies whether the program flash execute-only segments have been erased to the specified read margin
level.
Protection
• status_t FLASH_IsProtected (flash_config_t ∗config, uint32_t start, uint32_t lengthInBytes, flash_-
protection_state_t ∗protection_state)
Returns the protection state of the desired flash area via the pointer passed into the function.
• status_t FLASH_IsExecuteOnly (flash_config_t ∗config, uint32_t start, uint32_t lengthInBytes,
flash_execute_only_access_state_t ∗access_state)
Returns the access state of the desired flash area via the pointer passed into the function.
Properties
• status_t FLASH_GetProperty (flash_config_t ∗config, flash_property_tag_t whichProperty, uint32-
_t ∗value)
Returns the desired flash property.
• status_t FLASH_SetProperty (flash_config_t ∗config, flash_property_tag_t whichProperty, uint32_t
value)
Sets the desired flash property.
Return values
Data Fields
• uint32_t activeFunctionCount
Number of available execute-in-RAM functions.
• uint32_t ∗ flashRunCommand
Execute-in-RAM function: flash_run_command.
• uint32_t ∗ flashCommonBitOperation
Execute-in-RAM function: flash_common_bit_operation.
Data Fields
• flash_swap_state_t flashSwapState
The current Swap system status.
• flash_swap_block_status_t currentSwapBlockStatus
The current Swap block status.
• flash_swap_block_status_t nextSwapBlockStatus
The next Swap block status.
Data Fields
• uint16_t swapIndicatorAddress
A Swap indicator address field.
• uint16_t swapEnableWord
A Swap enable word field.
• uint8_t reserved0 [4]
A reserved field.
Data Fields
Data Fields
• uint32_t protl32b
PROT[31:0] .
• uint8_t protsl
PROTS[7:0] .
• uint8_t protsh
PROTS[15:8] .
Data Fields
• pflash_protection_status_low_t valueLow32b
PROT[31:0] or PROTS[15:0].
Data Fields
• flash_prefetch_speculation_option_t instructionOption
Instruction speculation.
• flash_prefetch_speculation_option_t dataOption
Data speculation.
Data Fields
• uint32_t regionBase
Base address of flash protection region.
• uint32_t regionSize
size of flash protection region.
• uint32_t regionCount
flash protection region count.
Data Fields
• uint32_t SegmentBase
Base address of flash Execute-Only segment.
• uint32_t SegmentSize
size of flash Execute-Only segment.
• uint32_t SegmentCount
flash Execute-Only segment count.
Data Fields
• uint32_t convertedAddress
A converted address for the current flash type.
• uint32_t activeSectorSize
A sector size of the current flash type.
• uint32_t activeBlockSize
A block size of the current flash type.
• uint32_t blockWriteUnitSize
The write unit size.
• uint32_t sectorCmdAddressAligment
An erase sector command address alignment.
• uint32_t partCmdAddressAligment
A program/verify part command address alignment.
• 32_t resourceCmdAddressAligment
A read resource command address alignment.
• uint32_t checkCmdAddressAligment
A program check command address alignment.
An instance of this structure is allocated by the user of the flash driver and passed into each of the driver
APIs.
Data Fields
• uint32_t PFlashBlockBase
A base address of the first PFlash block.
• uint32_t PFlashTotalSize
The size of the combined PFlash block.
• uint8_t PFlashBlockCount
A number of PFlash blocks.
• uint8_t FlashMemoryIndex
0 - primary flash; 1 - secondary flash
• uint8_t FlashCacheControllerIndex
0 - Controller for core 0; 1 - Controller for core 1
• uint8_t Reserved0
Reserved field 0.
• uint32_t PFlashSectorSize
The size in bytes of a sector of PFlash.
• flash_callback_t PFlashCallback
The callback function for the flash API.
• uint32_t PFlashAccessSegmentSize
A size in bytes of an access segment of PFlash.
• uint32_t PFlashAccessSegmentCount
A number of PFlash access segments.
• uint32_t ∗ flashExecuteInRamFunctionInfo
An information structure of the flash execute-in-RAM function.
• uint32_t FlexRAMBlockBase
For the FlexNVM device, this is the base address of the FlexRAM.
• uint32_t FlexRAMTotalSize
For the FlexNVM device, this is the size of the FlexRAM.
• uint32_t DFlashBlockBase
For the FlexNVM device, this is the base address of the D-Flash memory (FlexNVM memory)
• uint32_t DFlashTotalSize
For the FlexNVM device, this is the total size of the FlexNVM memory;.
• uint32_t EEpromTotalSize
For the FlexNVM device, this is the size in bytes of the EEPROM area which was partitioned from FlexR-
AM.
For the non-FlexNVM device, this is the base address of the acceleration RAM memory
For the non-FlexNVM device, this is the size of the acceleration RAM memory
Version 2.3.1.
11.3.9 #define FOUR_CHAR_CODE( a, b, c, d ) (((d) << 24) | ((c) << 16) | ((b)
<< 8) | ((a)))
Enumerator
kFLASH_DriverVersionName Flash driver version name.
Enumerator
kStatus_FLASH_Success API is executed successfully.
kStatus_FLASH_InvalidArgument Invalid argument.
kStatus_FLASH_SizeError Error size.
kStatus_FLASH_AlignmentError Parameter is not aligned with the specified baseline.
kStatus_FLASH_AddressError Address is out of range.
kStatus_FLASH_AccessError Invalid instruction codes and out-of bound addresses.
kStatus_FLASH_ProtectionViolation The program/erase operation is requested to execute on pro-
tected areas.
kStatus_FLASH_CommandFailure Run-time error during command execution.
kStatus_FLASH_UnknownProperty Unknown property.
kStatus_FLASH_EraseKeyError API erase key is invalid.
kStatus_FLASH_RegionExecuteOnly The current region is execute-only.
kStatus_FLASH_ExecuteInRamFunctionNotReady Execute-in-RAM function is not available.
kStatus_FLASH_PartitionStatusUpdateFailure Failed to update partition status.
kStatus_FLASH_SetFlexramAsEepromError Failed to set FlexRAM as EEPROM.
kStatus_FLASH_RecoverFlexramAsRamError Failed to recover FlexRAM as RAM.
kStatus_FLASH_SetFlexramAsRamError Failed to set FlexRAM as RAM.
kStatus_FLASH_RecoverFlexramAsEepromError Failed to recover FlexRAM as EEPROM.
kStatus_FLASH_CommandNotSupported Flash API is not supported.
kStatus_FLASH_SwapSystemNotInUninitialized Swap system is not in an uninitialzed state.
kStatus_FLASH_SwapIndicatorAddressError The swap indicator address is invalid.
kStatus_FLASH_ReadOnlyProperty The flash property is read-only.
kStatus_FLASH_InvalidPropertyValue The flash property value is out of range.
kStatus_FLASH_InvalidSpeculationOption The option of flash prefetch speculation is invalid.
Note
The resulting value is built with a byte order such that the string being readable in expected order
when viewed in a hex editor, if the value is treated as a 32-bit little endian value.
Enumerator
kFLASH_ApiEraseKey Key value used to validate all flash erase APIs.
Enumerator
kFLASH_MarginValueNormal Use the ’normal’ read level for 1s.
kFLASH_MarginValueUser Apply the ’User’ margin to the normal read-1 level.
kFLASH_MarginValueFactory Apply the ’Factory’ margin to the normal read-1 level.
kFLASH_MarginValueInvalid Not real margin level, Used to determine the range of valid margin
level.
Enumerator
kFLASH_SecurityStateNotSecure Flash is not secure.
kFLASH_SecurityStateBackdoorEnabled Flash backdoor is enabled.
kFLASH_SecurityStateBackdoorDisabled Flash backdoor is disabled.
Enumerator
kFLASH_ProtectionStateUnprotected Flash region is not protected.
kFLASH_ProtectionStateProtected Flash region is protected.
kFLASH_ProtectionStateMixed Flash is mixed with protected and unprotected region.
Enumerator
kFLASH_AccessStateUnLimited Flash region is unlimited.
kFLASH_AccessStateExecuteOnly Flash region is execute only.
kFLASH_AccessStateMixed Flash is mixed with unlimited and execute only region.
Enumerator
kFLASH_PropertyPflashSectorSize Pflash sector size property.
kFLASH_PropertyPflashTotalSize Pflash total size property.
Enumerator
kFLASH_ExecuteInRamFunctionMaxSizeInWords The maximum size of execute-in-RAM func-
tion.
kFLASH_ExecuteInRamFunctionTotalNum Total number of execute-in-RAM functions.
Enumerator
kFLASH_ResourceOptionFlashIfr Select code for Program flash 0 IFR, Program flash swap 0 IFR,
Data flash 0 IFR.
kFLASH_ResourceOptionVersionId Select code for the version ID.
Enumerator
kFLASH_ResourceRangePflashIfrSizeInBytes Pflash IFR size in byte.
kFLASH_ResourceRangeVersionIdSizeInBytes Version ID IFR size in byte.
kFLASH_ResourceRangeVersionIdStart Version ID IFR start address.
kFLASH_ResourceRangeVersionIdEnd Version ID IFR end address.
Enumerator
kFLASH_RecordIndexSwapAddr Index of Swap indicator address.
kFLASH_RecordIndexSwapEnable Index of Swap system enable.
kFLASH_RecordIndexSwapDisable Index of Swap system disable.
Enumerator
kFLASH_FlexramFunctionOptionAvailableAsRam An option used to make FlexRAM available
as RAM.
kFLASH_FlexramFunctionOptionAvailableForEeprom An option used to make FlexRAM avail-
able for EEPROM.
Enumerator
kFLASH_SwapFunctionOptionEnable An option used to enable the Swap function.
kFLASH_SwapFunctionOptionDisable An option used to disable the Swap function.
Enumerator
kFLASH_SwapControlOptionIntializeSystem An option used to initialize the Swap system.
kFLASH_SwapControlOptionSetInUpdateState An option used to set the Swap in an update state.
Enumerator
kFLASH_SwapStateUninitialized Flash Swap system is in an uninitialized state.
kFLASH_SwapStateReady Flash Swap system is in a ready state.
kFLASH_SwapStateUpdate Flash Swap system is in an update state.
kFLASH_SwapStateUpdateErased Flash Swap system is in an updateErased state.
kFLASH_SwapStateComplete Flash Swap system is in a complete state.
kFLASH_SwapStateDisabled Flash Swap system is in a disabled state.
Enumerator
kFLASH_SwapBlockStatusLowerHalfProgramBlocksAtZero Swap block status is that lower half
program block at zero.
kFLASH_SwapBlockStatusUpperHalfProgramBlocksAtZero Swap block status is that upper half
program block at zero.
Enumerator
kFLASH_PartitionFlexramLoadOptionLoadedWithValidEepromData FlexRAM is loaded with
valid EEPROM data during reset sequence.
kFLASH_PartitionFlexramLoadOptionNotLoaded FlexRAM is not loaded during reset sequence.
Enumerator
kFLASH_MemoryIndexPrimaryFlash Current flash memory is primary flash.
kFLASH_MemoryIndexSecondaryFlash Current flash memory is secondary flash.
Enumerator
kFLASH_CacheControllerIndexForCore0 Current flash cache controller is for core 0.
kFLASH_CacheControllerIndexForCore1 Current flash cache controller is for core 1.
Enumerator
kFLASH_CacheClearProcessPre Pre flash cache clear process.
kFLASH_CacheClearProcessPost Post flash cache clear process.
This function checks and initializes the Flash module for the other Flash APIs.
Parameters
Return values
Parameters
Return values
Parameters
Return values
Parameters
Return values
This function erases the appropriate number of flash sectors based on the desired start address and length.
Parameters
config The pointer to the storage for the driver runtime state.
start The start address of the desired flash memory to be erased. The start address does not
need to be sector-aligned but must be word-aligned.
lengthInBytes The length, given in bytes (not words or long-words) to be erased. Must be word-
aligned.
key The value used to validate all flash erase APIs.
Return values
Parameters
Return values
Return values
This function programs the flash memory with the desired data for a given flash area as determined by the
start address and the length.
Parameters
Return values
This function programs the Program Once Field with the desired data for a given flash area as determined
by the index and length.
Parameters
index The index indicating which area of the Program Once Field to be programmed.
src A pointer to the source buffer of data that is to be programmed into the Program Once
Field.
lengthInBytes The length, given in bytes (not words or long-words), to be programmed. Must be
word-aligned.
Return values
This function reads the flash memory with the desired location for a given flash area as determined by the
start address and length.
Parameters
option The resource option which indicates which area should be read back.
Return values
This function reads the read once feild with given index and length.
Parameters
Return values
This function retrieves the current flash security status, including the security enabling state and the back-
door key enabling state.
Parameters
Return values
If the MCU is in secured state, this function unsecures the MCU by comparing the provided backdoor key
with ones in the flash configuration field.
Parameters
Return values
This function checks whether the flash is erased to the specified read margin level.
Parameters
Return values
This function checks the appropriate number of flash sectors based on the desired start address and length
to check whether the flash is erased to the specified read margin level.
Parameters
Return values
This function verifies the data programed in the flash memory using the Flash Program Check Command
and compares it to the expected data for a given flash area as determined by the start address and length.
Parameters
Return values
Parameters
Return values
This function retrieves the current flash protect status for a given flash area as determined by the start
address and length.
Parameters
Return values
This function retrieves the current flash access status for a given flash area as determined by the start
address and length.
Parameters
Return values
Parameters
Return values
Parameters
whichProperty The desired property from the list of properties in enum flash_property_tag_t
value A to set for the desired flash property.
Return values
Parameters
Return values
Parameters
Return values
Data Structures
• struct gpio_pin_config_t
The GPIO pin configuration structure. More...
Enumerations
• enum gpio_pin_direction_t {
kGPIO_DigitalInput = 0U,
kGPIO_DigitalOutput = 1U }
GPIO direction definition.
Driver version
• #define FSL_GPIO_DRIVER_VERSION (MAKE_VERSION(2, 1, 1))
GPIO driver version 2.1.1.
Each pin can only be configured as either an output pin or an input pin at a time. If configured as an input
pin, leave the outputConfig unused. Note that in some use cases, the corresponding port property should
be configured in advance with the PORT_SetPinConfig().
Data Fields
• gpio_pin_direction_t pinDirection
GPIO direction, input or output.
• uint8_t outputLogic
Set a default output logic, which has no use in input.
Enumerator
kGPIO_DigitalInput Set current pin as digital input.
kGPIO_DigitalOutput Set current pin as digital output.
The MCUXpresso SDK provides a peripheral driver for the General-Purpose Input/Output (GPIO) module
of MCUXpresso SDK devices.
GPIO Configuration
GPIO Interrupt
To initialize the GPIO, define a pin configuration, as either input or output, in the user file. Then, call the
GPIO_PinInit() function.
This is an example to define an input pin or an output pin configuration.
Parameters
base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.)
pin GPIO port pin number
config GPIO pin configuration pointer
Parameters
base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.)
pin GPIO pin number
output GPIO pin output logic level.
• 0: corresponding pin output low-logic level.
• 1: corresponding pin output high-logic level.
Parameters
base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.)
mask GPIO pin number macro
Parameters
base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.)
mask GPIO pin number macro
Parameters
base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.)
mask GPIO pin number macro
Parameters
base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.)
pin GPIO pin number
Return values
If a pin is configured to generate the DMA request, the corresponding flag is cleared automatically at the
completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to
that flag. If configured for a level sensitive interrupt that remains asserted, the flag is set again immediately.
Parameters
base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.)
Return values
The current GPIO port interrupt status flag, for example, 0x00010001 means
the pin 0 and 17 have the interrupt.
Parameters
base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.)
mask GPIO pin number macro
This chapter describes the programming interface of the FGPIO driver. The FGPIO driver configures the
FGPIO module and provides a functional interface to build the GPIO application.
Note
FGPIO (Fast GPIO) is only available in a few MCUs. FGPIO and GPIO share the same peripheral
but use different registers. FGPIO is closer to the core than the regular GPIO and it’s faster to read
and write.
FGPIO Configuration
FGPIO Interrupt
To initialize the FGPIO driver, define a pin configuration, as either input or output, in the user file. Then,
call the FGPIO_PinInit() function.
This is an example to define an input pin or an output pin configuration:
Parameters
base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.)
pin FGPIO port pin number
config FGPIO pin configuration pointer
Parameters
base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.)
pin FGPIO pin number
output FGPIOpin output logic level.
• 0: corresponding pin output low-logic level.
• 1: corresponding pin output high-logic level.
Parameters
base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.)
mask FGPIO pin number macro
Parameters
base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.)
mask FGPIO pin number macro
Parameters
base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.)
mask FGPIO pin number macro
Parameters
base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.)
pin FGPIO pin number
Return values
If a pin is configured to generate the DMA request, the corresponding flag is cleared automatically at the
completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to
that flag. If configured for a level-sensitive interrupt that remains asserted, the flag is set again immediately.
Parameters
base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.)
Return values
The current FGPIO port interrupt status flags, for example, 0x00010001 means
the pin 0 and 17 have the interrupt.
Parameters
base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.)
mask FGPIO pin number macro
The MCUXpresso SDK provides a peripheral driver for the Inter-Integrated Circuit (I2C) module of MC-
UXpresso SDK devices.
The I2C driver includes functional APIs and transactional APIs.
Functional APIs target the low-level APIs. Functional APIs can be used for the I2C master/slave initializa-
tion/configuration/operation for optimization/customization purpose. Using the functional APIs requires
knowing the I2C master peripheral and how to organize functional APIs to meet the application require-
ments. The I2C functional operation groups provide the functional APIs set.
Transactional APIs target the high-level APIs. The transactional APIs can be used to enable the periph-
eral quickly and also in the application if the code size and performance of transactional APIs satisfy
the requirements. If the code size and performance are critical requirements, see the transactional API
implementation and write custom code using the functional APIs or accessing the hardware registers.
Transactional APIs support asynchronous transfer. This means that the functions I2C_MasterTransfer-
NonBlocking() set up the interrupt non-blocking transfer. When the transfer completes, the upper layer is
notified through a callback function with the status.
if(result)
{
return result;
}
masterXfer.slaveAddress = I2C_MASTER_SLAVE_ADDR_7BIT;
masterXfer.direction = kI2C_Write;
masterXfer.subaddress = NULL;
masterXfer.subaddressSize = 0;
masterXfer.data = txBuff;
masterXfer.dataSize = BUFFER_SIZE;
masterXfer.flags = kI2C_TransferDefaultFlag;
I2C_MasterTransferCreateHandle(EXAMPLE_I2C_MASTER_BASEADDR, &g_m_handle,
i2c_master_callback, NULL);
I2C_MasterTransferNonBlocking(EXAMPLE_I2C_MASTER_BASEADDR, &g_m_handle, &
masterXfer);
{
g_MasterCompletionFlag = true;
}
}
masterXfer.slaveAddress = I2C_MASTER_SLAVE_ADDR_7BIT;
masterXfer.direction = kI2C_Write;
masterXfer.subaddress = NULL;
masterXfer.subaddressSize = 0;
masterXfer.data = txBuff;
masterXfer.dataSize = BUFFER_SIZE;
masterXfer.flags = kI2C_TransferDefaultFlag;
DMAMGR_RequestChannel((dma_request_source_t)DMA_REQUEST_SRC, 0, &dmaHandle);
I2C_MasterTransferCreateHandleDMA(EXAMPLE_I2C_MASTER_BASEADDR, &
g_m_dma_handle, i2c_master_callback, NULL, &dmaHandle);
I2C_MasterTransferDMA(EXAMPLE_I2C_MASTER_BASEADDR, &g_m_dma_handle, &masterXfer);
return result;
/* Receives request */
case kI2C_SlaveReceiveEvent:
/* Update information for received process */
xfer->data = g_slave_buff;
xfer->dataSize = I2C_DATA_LENGTH;
break;
/* Transfer is done */
case kI2C_SlaveCompletionEvent:
g_SlaveCompletionFlag = true;
break;
default:
g_SlaveCompletionFlag = true;
break;
}
}
I2C_SlaveTransferCreateHandle(EXAMPLE_I2C_SLAVE_BASEADDR, &g_s_handle,
i2c_slave_callback, NULL);
I2C_SlaveTransferNonBlocking(EXAMPLE_I2C_SLAVE_BASEADDR, &g_s_handle,
kI2C_SlaveCompletionEvent);
Data Structures
• struct i2c_master_config_t
I2C master user configuration. More...
• struct i2c_slave_config_t
I2C slave user configuration. More...
• struct i2c_master_transfer_t
Typedefs
Enumerations
• enum _i2c_status {
kStatus_I2C_Busy = MAKE_STATUS(kStatusGroup_I2C, 0),
kStatus_I2C_Idle = MAKE_STATUS(kStatusGroup_I2C, 1),
kStatus_I2C_Nak = MAKE_STATUS(kStatusGroup_I2C, 2),
kStatus_I2C_ArbitrationLost = MAKE_STATUS(kStatusGroup_I2C, 3),
kStatus_I2C_Timeout = MAKE_STATUS(kStatusGroup_I2C, 4),
kStatus_I2C_Addr_Nak = MAKE_STATUS(kStatusGroup_I2C, 5) }
I2C status return codes.
• enum _i2c_flags {
kI2C_ReceiveNakFlag = I2C_S_RXAK_MASK,
kI2C_IntPendingFlag = I2C_S_IICIF_MASK,
kI2C_TransferDirectionFlag = I2C_S_SRW_MASK,
kI2C_RangeAddressMatchFlag = I2C_S_RAM_MASK,
kI2C_ArbitrationLostFlag = I2C_S_ARBL_MASK,
kI2C_BusBusyFlag = I2C_S_BUSY_MASK,
kI2C_AddressMatchFlag = I2C_S_IAAS_MASK,
kI2C_TransferCompleteFlag = I2C_S_TCF_MASK,
kI2C_StopDetectFlag = I2C_FLT_STOPF_MASK << 8,
kI2C_StartDetectFlag = I2C_FLT_STARTF_MASK << 8 }
I2C peripheral flags.
• enum _i2c_interrupt_enable {
kI2C_GlobalInterruptEnable = I2C_C1_IICIE_MASK,
kI2C_StartStopDetectInterruptEnable = I2C_FLT_SSIE_MASK }
I2C feature interrupt source.
• enum i2c_direction_t {
kI2C_Write = 0x0U,
kI2C_Read = 0x1U }
The direction of master and slave transfers.
• enum i2c_slave_address_mode_t {
kI2C_Address7bit = 0x0U,
kI2C_RangeMatch = 0X2U }
Addressing mode.
• enum _i2c_master_transfer_flags {
kI2C_TransferDefaultFlag = 0x0U,
kI2C_TransferNoStartFlag = 0x1U,
kI2C_TransferRepeatedStartFlag = 0x2U,
kI2C_TransferNoStopFlag = 0x4U }
I2C transfer control flag.
• enum i2c_slave_transfer_event_t {
kI2C_SlaveAddressMatchEvent = 0x01U,
kI2C_SlaveTransmitEvent = 0x02U,
kI2C_SlaveReceiveEvent = 0x04U,
kI2C_SlaveTransmitAckEvent = 0x08U,
kI2C_SlaveStartEvent = 0x10U,
kI2C_SlaveCompletionEvent = 0x20U,
kI2C_SlaveGenaralcallEvent = 0x40U,
kI2C_SlaveAllEvents }
Set of events sent to the callback for nonblocking slave transfers.
Driver version
Status
Interrupts
DMA Control
Bus Operations
Transactional
Data Fields
• bool enableMaster
Enables the I2C peripheral at initialization time.
• bool enableStopHold
Controls the stop hold enable.
• uint32_t baudRate_Bps
Baud rate configuration of I2C peripheral.
• uint8_t glitchFilterWidth
Controls the width of the glitch.
Data Fields
• bool enableSlave
Enables the I2C peripheral at initialization time.
• bool enableGeneralCall
Enables the general call addressing mode.
• bool enableWakeUp
Enables/disables waking up MCU from low-power mode.
• bool enableBaudRateCtl
Enables/disables independent slave baud rate on SCL in very fast I2C modes.
• uint16_t slaveAddress
A slave address configuration.
• uint16_t upperAddress
A maximum boundary slave address used in a range matching mode.
• i2c_slave_address_mode_t addressingMode
An addressing mode configuration of i2c_slave_address_mode_config_t.
• uint32_t sclStopHoldTime_ns
the delay from the rising edge of SCL (I2C clock) to the rising edge of SDA (I2C data) while SCL is high
(stop condition), SDA hold time and SCL start hold time are also configured according to the SCL stop
hold time.
Data Fields
• uint32_t flags
A transfer flag which controls the transfer.
• uint8_t slaveAddress
7-bit slave address.
• i2c_direction_t direction
A transfer direction, read or write.
• uint32_t subaddress
A sub address.
• uint8_t subaddressSize
A size of the command buffer.
• uint8_t ∗volatile data
A transfer buffer.
• volatile size_t dataSize
A transfer size.
Data Fields
• i2c_master_transfer_t transfer
I2C master transfer copy.
• size_t transferSize
Total bytes to be transferred.
• uint8_t state
A transfer state maintained during transfer.
• i2c_master_transfer_callback_t completionCallback
A callback function called when the transfer is finished.
• void ∗ userData
A callback parameter passed to the callback function.
Data Fields
• i2c_slave_transfer_event_t event
A reason that the callback is invoked.
• uint8_t ∗volatile data
A transfer buffer.
• volatile size_t dataSize
A transfer size.
• status_t completionStatus
Success or error code describing how the transfer completed.
• size_t transferredCount
A number of bytes actually transferred since the start or since the last repeated start.
Data Fields
• volatile bool isBusy
Indicates whether a transfer is busy.
• i2c_slave_transfer_t transfer
I2C slave transfer copy.
• uint32_t eventMask
A mask of enabled events.
• i2c_slave_transfer_callback_t callback
A callback function called at the transfer event.
• void ∗ userData
A callback parameter passed to the callback.
Enumerator
kStatus_I2C_Busy I2C is busy with current transfer.
kStatus_I2C_Idle Bus is Idle.
kStatus_I2C_Nak NAK received during transfer.
kStatus_I2C_ArbitrationLost Arbitration lost during transfer.
kStatus_I2C_Timeout Wait event timeout.
kStatus_I2C_Addr_Nak NAK received during the address probe.
Note
These enumerations are meant to be OR’d together to form a bit mask.
Enumerator
kI2C_ReceiveNakFlag I2C receive NAK flag.
kI2C_IntPendingFlag I2C interrupt pending flag.
kI2C_TransferDirectionFlag I2C transfer direction flag.
kI2C_RangeAddressMatchFlag I2C range address match flag.
kI2C_ArbitrationLostFlag I2C arbitration lost flag.
kI2C_BusBusyFlag I2C bus busy flag.
kI2C_AddressMatchFlag I2C address match flag.
kI2C_TransferCompleteFlag I2C transfer complete flag.
kI2C_StopDetectFlag I2C stop detect flag.
kI2C_StartDetectFlag I2C start detect flag.
Enumerator
kI2C_GlobalInterruptEnable I2C global interrupt.
kI2C_StartStopDetectInterruptEnable I2C start&stop detect interrupt.
Enumerator
kI2C_Write Master transmits to the slave.
kI2C_Read Master receives from the slave.
Enumerator
kI2C_Address7bit 7-bit addressing mode.
kI2C_RangeMatch Range address match addressing mode.
Enumerator
kI2C_TransferDefaultFlag A transfer starts with a start signal, stops with a stop signal.
These event enumerations are used for two related purposes. First, a bit mask created by OR’ing together
events is passed to I2C_SlaveTransferNonBlocking() to specify which events to enable. Then, when the
slave callback is invoked, it is passed the current event through its transfer parameter.
Note
These enumerations are meant to be OR’d together to form a bit mask of events.
Enumerator
kI2C_SlaveAddressMatchEvent Received the slave address after a start or repeated start.
kI2C_SlaveTransmitEvent A callback is requested to provide data to transmit (slave-transmitter
role).
kI2C_SlaveReceiveEvent A callback is requested to provide a buffer in which to place received data
(slave-receiver role).
kI2C_SlaveTransmitAckEvent A callback needs to either transmit an ACK or NACK.
kI2C_SlaveStartEvent A start/repeated start was detected.
kI2C_SlaveCompletionEvent A stop was detected or finished transfer, completing the transfer.
kI2C_SlaveGenaralcallEvent Received the general call address after a start or repeated start.
kI2C_SlaveAllEvents A bit mask of all available events.
Call this API to ungate the I2C clock and configure the I2C with master configuration.
Note
This API should be called at the beginning of the application. Otherwise, any operation to the I2C
module can cause a hard fault because the clock is not enabled. The configuration structure can be
custom filled or it can be set with default values by using the I2C_MasterGetDefaultConfig(). After
calling this API, the master is ready to transfer. This is an example.
* i2c_master_config_t config = {
* .enableMaster = true,
* .enableStopHold = false,
* .highDrive = false,
* .baudRate_Bps = 100000,
* .glitchFilterWidth = 0
* };
* I2C_MasterInit(I2C0, &config, 12000000U);
*
Parameters
Call this API to ungate the I2C clock and initialize the I2C with the slave configuration.
Note
This API should be called at the beginning of the application. Otherwise, any operation to the I2C
module can cause a hard fault because the clock is not enabled. The configuration structure can
partly be set with default values by I2C_SlaveGetDefaultConfig() or it can be custom filled by the
user. This is an example.
* i2c_slave_config_t config = {
* .enableSlave = true,
* .enableGeneralCall = false,
* .addressingMode = kI2C_Address7bit,
* .slaveAddress = 0x1DU,
* .enableWakeUp = false,
* .enablehighDrive = false,
* .enableBaudRateCtl = false,
* .sclStopHoldTime_ns = 4000
* };
* I2C_SlaveInit(I2C0, &config, 12000000U);
*
Parameters
Call this API to gate the I2C clock. The I2C master module can’t work unless the I2C_MasterInit is called.
Parameters
Calling this API gates the I2C clock. The I2C slave module can’t work unless the I2C_SlaveInit is called
to enable the clock.
Parameters
The purpose of this API is to get the configuration structure initialized for use in the I2C_Master-
Configure(). Use the initialized structure unchanged in the I2C_MasterConfigure() or modify the structure
before calling the I2C_MasterConfigure(). This is an example.
* i2c_master_config_t config;
* I2C_MasterGetDefaultConfig(&config);
*
Parameters
The purpose of this API is to get the configuration structure initialized for use in the I2C_SlaveConfigure().
Modify fields of the structure before calling the I2C_SlaveConfigure(). This is an example.
* i2c_slave_config_t config;
* I2C_SlaveGetDefaultConfig(&config);
*
Parameters
13.2.7.7 static void I2C_Enable ( I2C_Type ∗ base, bool enable ) [inline], [static]
Parameters
Parameters
Returns
status flag, use status flag to AND _i2c_flags to get the related status.
Parameters
Returns
status flag, use status flag to AND _i2c_flags to get the related status.
The following status register flags can be cleared kI2C_ArbitrationLostFlag and kI2C_IntPendingFlag.
Parameters
The following status register flags can be cleared kI2C_ArbitrationLostFlag and kI2C_IntPendingFlag
Parameters
Parameters
Parameters
Parameters
This API is used to provide a transfer address for I2C DMA transfer configuration.
Parameters
Returns
data register address
Parameters
This function is used to initiate a new master mode transfer by sending the START signal. The slave
address is sent following the I2C START signal.
Parameters
Return values
Return values
Parameters
Return values
Parameters
Return values
Note
The I2C_MasterReadBlocking function stops the bus before reading the final byte. Without stopping
the bus prior for the final read, the bus issues another read, resulting in garbage data being read into
the data register.
Parameters
Return values
Parameters
Return values
Parameters
Parameters
Return values
Parameters
Note
Calling the API returns immediately after transfer initiates. The user needs to call I2C_MasterGet-
TransferCount to poll the transfer status to check whether the transfer is finished. If the return status
is not kStatus_I2C_Busy, the transfer is finished.
Parameters
Return values
Parameters
Return values
Note
This API can be called at any time when an interrupt non-blocking transfer initiates to abort the
transfer early.
Parameters
Parameters
Parameters
Call this API after calling the I2C_SlaveInit() and I2C_SlaveTransferCreateHandle() to start processing
transactions driven by an I2C master. The slave monitors the I2C bus and passes events to the callback
that was passed into the call to I2C_SlaveTransferCreateHandle(). The callback is always invoked from
the interrupt context.
The set of events received by the callback is customizable. To do so, set the eventMask parameter to the
OR’d combination of i2c_slave_transfer_event_t enumerators for the events you wish to receive. The k-
I2C_SlaveTransmitEvent and #kLPI2C_SlaveReceiveEvent events are always enabled and do not need to
be included in the mask. Alternatively, pass 0 to get a default set of only the transmit and receive events
that are always enabled. In addition, the kI2C_SlaveAllEvents constant is provided as a convenient way
to enable all events.
Parameters
Return values
Note
This API can be called at any time to stop slave for handling the bus events.
Parameters
Parameters
Return values
Parameters
Data Structures
• struct i2c_master_edma_handle_t
I2C master eDMA transfer structure. More...
Typedefs
Data Fields
• i2c_master_transfer_t transfer
I2C master transfer structure.
• size_t transferSize
Total bytes to be transferred.
• uint8_t nbytes
eDMA minor byte transfer count initially configured.
• uint8_t state
Parameters
Parameters
Return values
Parameters
Parameters
Data Structures
• struct i2c_master_dma_handle_t
I2C master DMA transfer structure. More...
Typedefs
Data Fields
• i2c_master_transfer_t transfer
I2C master transfer struct.
• size_t transferSize
Total bytes to be transferred.
• uint8_t state
I2C master transfer status.
• dma_handle_t ∗ dmaHandle
Parameters
Parameters
Return values
Parameters
Parameters
This function initializes the I2C module and the related RTOS context.
Parameters
handle The RTOS I2C handle, the pointer to an allocated space for RTOS context.
base The pointer base address of the I2C instance to initialize.
masterConfig The configuration structure to set-up I2C in master mode.
srcClock_Hz The frequency of an input clock of the I2C module.
Returns
status of the operation.
This function deinitializes the I2C module and the related RTOS context.
Parameters
This function performs the I2C transfer according to the data given in the transfer structure.
Parameters
Returns
status of the operation.
Data Structures
• struct llwu_external_pin_filter_mode_t
An external input pin filter control structure. More...
Enumerations
• enum llwu_external_pin_mode_t {
kLLWU_ExternalPinDisable = 0U,
kLLWU_ExternalPinRisingEdge = 1U,
kLLWU_ExternalPinFallingEdge = 2U,
kLLWU_ExternalPinAnyEdge = 3U }
External input pin control modes.
• enum llwu_pin_filter_mode_t {
kLLWU_PinFilterDisable = 0U,
kLLWU_PinFilterRisingEdge = 1U,
kLLWU_PinFilterFallingEdge = 2U,
kLLWU_PinFilterAnyEdge = 3U }
Digital filter control modes.
Driver version
• #define FSL_LLWU_DRIVER_VERSION (MAKE_VERSION(2, 0, 1))
LLWU driver version 2.0.1.
Data Fields
• uint32_t pinIndex
A pin number.
• llwu_pin_filter_mode_t filterMode
Filter mode.
Enumerator
kLLWU_ExternalPinDisable Pin disabled as a wakeup input.
Enumerator
kLLWU_PinFilterDisable Filter disabled.
kLLWU_PinFilterRisingEdge Filter positive edge detection.
kLLWU_PinFilterFallingEdge Filter negative edge detection.
kLLWU_PinFilterAnyEdge Filter any edge detection.
This function sets the external input pin source mode that is used as a wake up source.
Parameters
This function checks the external pin flag to detect whether the MCU is woken up by the specific pin.
Parameters
Returns
True if the specific pin is a wakeup source.
This function clears the external wakeup source flag for a specific pin.
Parameters
This function enables/disables the internal module source mode that is used as a wake up source.
Parameters
This function checks the external pin flag to detect whether the system is woken up by the specific pin.
Parameters
Returns
True if the specific pin is a wake up source.
Parameters
Returns
True if the flag is a source of the existing low-leakage power mode.
The MCUXpresso SDK provides a peripheral driver for the Universal Asynchronous Receiver/Transmitter
(LPSCI) module of MCUXpresso SDK devices.
The LPSCI driver can be split into 2 parts: functional APIs and transactional APIs.
Functional APIs are feature/property target low level APIs. Functional APIs can be used for the LPSCI
initialization/configuration/operation for optimization/customization purpose. Using the functional API
requires knowledge of the LPSCI peripheral and how to organize functional APIs to meet the application
requirements. All functional APIs use the peripheral base address as the first parameter. The LPSCI
functional operation groups provide the functional APIs set.
The transactional APIs are transaction target high level APIs. Transactional APIs can be used to enable the
peripheral quickly and also in the user’s application if the code size and performance of transactional APIs
can satisfy the user’s requirements. If there are special requirements for the code size and performance,
see the transactional API implementation and write custom code. All transactional APIs use the lpsci-
_handle_t as the second parameter. Initialize the handle by calling the LPSCI_TransferCreateHandle()
API.
Transactional APIs support queue feature for both transmit/receive. Whenever the user calls the LPSCI-
_TransferSendNonBlocking() or LPSCI_TransferReceiveNonBlocking(), the transfer structure is queued
into the internally maintained software queue. The driver automatically continues the transmit/receive if
the queue is not empty. When a transfer is finished, the callback is called to inform the user about the
completion.
The LPSCI transactional APIs support the background receive. Provide the ringbuffer address and size
while calling the LPSCI_TransferCreateHandle() API. The driver automatically starts receiving the data
from the receive buffer into the ringbuffer. When the user makes subsequent calls to the LPSCI_Receive-
DataIRQ(), the driver provides the received data in the ringbuffer for user buffer directly and queues the
left buffer into the receive queue.
This function group implements the LPSCI functional API. Functional APIs are feature-oriented.
LPSCI_Init(UART0,&user_config,120000000U);
LPSCI_EnableTx(UART0, true);
LPSCI_EnableRx(UART0, true);
while(1)
{
LPSCI_ReadBlocking(UART0,&ch, 1);
LPSCI_WriteBlocking(UART0, &ch, 1);
}
Data Structures
• struct lpsci_config_t
LPSCI configure structure. More...
• struct lpsci_transfer_t
LPSCI transfer structure. More...
Driver version
• enum _lpsci_status {
kStatus_LPSCI_TxBusy = MAKE_STATUS(kStatusGroup_LPSCI, 0),
kStatus_LPSCI_RxBusy = MAKE_STATUS(kStatusGroup_LPSCI, 1),
kStatus_LPSCI_TxIdle = MAKE_STATUS(kStatusGroup_LPSCI, 2),
kStatus_LPSCI_RxIdle = MAKE_STATUS(kStatusGroup_LPSCI, 3),
kStatus_LPSCI_FlagCannotClearManually,
kStatus_LPSCI_BaudrateNotSupport,
kStatus_LPSCI_Error = MAKE_STATUS(kStatusGroup_LPSCI, 6),
kStatus_LPSCI_RxRingBufferOverrun,
kStatus_LPSCI_RxHardwareOverrun = MAKE_STATUS(kStatusGroup_LPSCI, 8),
kStatus_LPSCI_NoiseError = MAKE_STATUS(kStatusGroup_LPSCI, 9),
kStatus_LPSCI_FramingError = MAKE_STATUS(kStatusGroup_LPSCI, 10),
kStatus_LPSCI_ParityError = MAKE_STATUS(kStatusGroup_LPSCI, 11) }
Error codes for the LPSCI driver.
• enum lpsci_parity_mode_t {
kLPSCI_ParityDisabled = 0x0U,
kLPSCI_ParityEven = 0x2U,
kLPSCI_ParityOdd = 0x3U }
LPSCI parity mode.
• enum lpsci_stop_bit_count_t {
kLPSCI_OneStopBit = 0U,
kLPSCI_TwoStopBit = 1U }
LPSCI stop bit count.
• enum _lpsci_interrupt_enable_t {
kLPSCI_LinBreakInterruptEnable = (UART0_BDH_LBKDIE_MASK),
kLPSCI_RxActiveEdgeInterruptEnable = (UART0_BDH_RXEDGIE_MASK),
kLPSCI_TxDataRegEmptyInterruptEnable = (UART0_C2_TIE_MASK << 8),
kLPSCI_TransmissionCompleteInterruptEnable = (UART0_C2_TCIE_MASK << 8),
kLPSCI_RxDataRegFullInterruptEnable = (UART0_C2_RIE_MASK << 8),
kLPSCI_IdleLineInterruptEnable = (UART0_C2_ILIE_MASK << 8),
kLPSCI_RxOverrunInterruptEnable = (UART0_C3_ORIE_MASK << 16),
kLPSCI_NoiseErrorInterruptEnable = (UART0_C3_NEIE_MASK << 16),
kLPSCI_FramingErrorInterruptEnable = (UART0_C3_FEIE_MASK << 16),
kLPSCI_ParityErrorInterruptEnable = (UART0_C3_PEIE_MASK << 16) }
LPSCI interrupt configuration structure, default settings all disabled.
• enum _lpsci_status_flag_t {
kLPSCI_TxDataRegEmptyFlag = (UART0_S1_TDRE_MASK),
kLPSCI_TransmissionCompleteFlag,
kLPSCI_RxDataRegFullFlag,
kLPSCI_IdleLineFlag = (UART0_S1_IDLE_MASK),
kLPSCI_RxOverrunFlag,
kLPSCI_NoiseErrorFlag = (UART0_S1_NF_MASK),
kLPSCI_FramingErrorFlag,
kLPSCI_ParityErrorFlag = (UART0_S1_PF_MASK),
kLPSCI_LinBreakFlag,
kLPSCI_RxActiveEdgeFlag,
kLPSCI_RxActiveFlag }
LPSCI status flags.
• typedef void(∗ lpsci_transfer_callback_t )(UART0_Type ∗base, lpsci_handle_t ∗handle, status_t
status, void ∗userData)
LPSCI transfer callback function.
• #define FSL_LPSCI_DRIVER_VERSION (MAKE_VERSION(2, 0, 3))
LPSCI driver version 2.0.3.
Status
Interrupts
DMA Control
Bus Operations
Transactional
Data Fields
• uint32_t baudRate_Bps
LPSCI baud rate.
• lpsci_parity_mode_t parityMode
Parity mode, disabled (default), even, odd.
• lpsci_stop_bit_count_t stopBitCount
Number of stop bits, 1 stop bit (default) or 2 stop bits.
• bool enableTx
Enable TX.
• bool enableRx
Enable RX.
Data Fields
• uint8_t ∗ data
The buffer of data to be transfer.
• size_t dataSize
The byte count to be transfer.
Enumerator
kStatus_LPSCI_TxBusy Transmitter is busy.
kStatus_LPSCI_RxBusy Receiver is busy.
kStatus_LPSCI_TxIdle Transmitter is idle.
kStatus_LPSCI_RxIdle Receiver is idle.
kStatus_LPSCI_FlagCannotClearManually Status flag can’t be manually cleared.
kStatus_LPSCI_BaudrateNotSupport Baudrate is not support in current clock source.
kStatus_LPSCI_Error Error happens on LPSCI.
kStatus_LPSCI_RxRingBufferOverrun LPSCI RX software ring buffer overrun.
kStatus_LPSCI_RxHardwareOverrun LPSCI RX receiver overrun.
kStatus_LPSCI_NoiseError LPSCI noise error.
kStatus_LPSCI_FramingError LPSCI framing error.
kStatus_LPSCI_ParityError LPSCI parity error.
Enumerator
kLPSCI_ParityDisabled Parity disabled.
kLPSCI_ParityEven Parity enabled, type even, bit setting: PE|PT = 10.
kLPSCI_ParityOdd Parity enabled, type odd, bit setting: PE|PT = 11.
Enumerator
kLPSCI_OneStopBit One stop bit.
kLPSCI_TwoStopBit Two stop bits.
This structure contains the settings for all LPSCI interrupt configurations.
Enumerator
kLPSCI_LinBreakInterruptEnable LIN break detect interrupt.
kLPSCI_RxActiveEdgeInterruptEnable RX Active Edge interrupt.
kLPSCI_TxDataRegEmptyInterruptEnable Transmit data register empty interrupt.
kLPSCI_TransmissionCompleteInterruptEnable Transmission complete interrupt.
kLPSCI_RxDataRegFullInterruptEnable Receiver data register full interrupt.
kLPSCI_IdleLineInterruptEnable Idle line interrupt.
kLPSCI_RxOverrunInterruptEnable Receiver Overrun interrupt.
kLPSCI_NoiseErrorInterruptEnable Noise error flag interrupt.
kLPSCI_FramingErrorInterruptEnable Framing error flag interrupt.
kLPSCI_ParityErrorInterruptEnable Parity error flag interrupt.
This provides constants for the LPSCI status flags for use in the LPSCI functions.
Enumerator
kLPSCI_TxDataRegEmptyFlag Tx data register empty flag, sets when Tx buffer is empty.
kLPSCI_TransmissionCompleteFlag Transmission complete flag, sets when transmission activity
complete.
kLPSCI_RxDataRegFullFlag Rx data register full flag, sets when the receive data buffer is full.
kLPSCI_IdleLineFlag Idle line detect flag, sets when idle line detected.
kLPSCI_RxOverrunFlag Rx Overrun, sets when new data is received before data is read from re-
ceive register.
kLPSCI_NoiseErrorFlag Rx takes 3 samples of each received bit. If any of these samples differ,
noise flag sets
kLPSCI_FramingErrorFlag Frame error flag, sets if logic 0 was detected where stop bit expected.
kLPSCI_ParityErrorFlag If parity enabled, sets upon parity error detection.
kLPSCI_LinBreakFlag LIN break detect interrupt flag, sets when LIN break char detected and LIN
circuit enabled.
kLPSCI_RxActiveEdgeFlag Rx pin active edge interrupt flag, sets when active edge detected.
kLPSCI_RxActiveFlag Receiver Active Flag (RAF), sets at beginning of valid start bit.
This function configures the LPSCI module with user-defined settings. The user can configure the con-
figuration structure and can also get the default configuration by calling the LPSCI_GetDefaultConfig()
function. Example below shows how to use this API to configure the LPSCI.
* lpsci_config_t lpsciConfig;
* lpsciConfig.baudRate_Bps = 115200U;
* lpsciConfig.parityMode = kLPSCI_ParityDisabled;
* lpsciConfig.stopBitCount = kLPSCI_OneStopBit;
* LPSCI_Init(UART0, &lpsciConfig, 20000000U);
*
Parameters
Return values
This function waits for TX complete, disables TX and RX, and disables the LPSCI clock.
Parameters
This function initializes the LPSCI configure structure to default value. the default value are: lpsciConfig-
>baudRate_Bps = 115200U; lpsciConfig->parityMode = kLPSCI_ParityDisabled; lpsciConfig->stop-
BitCount = kLPSCI_OneStopBit; lpsciConfig->enableTx = false; lpsciConfig->enableRx = false;
Parameters
This function configures the LPSCI module baudrate. This function is used to update the LPSCI module
baudrate after the LPSCI module is initialized with the LPSCI_Init.
Parameters
Return values
This function gets all LPSCI status flags. The flags are returned as the logical OR value of the enumerators
_lpsci_flags. To check a specific status, compare the return value to the enumerators in _LPSCI_flags. For
example, to check whether the TX is empty:
* if (kLPSCI_TxDataRegEmptyFlag |
LPSCI_GetStatusFlags(UART0))
* {
* ...
* }
*
Parameters
Returns
LPSCI status flags which are ORed by the enumerators in the _lpsci_flags.
This function enables the LPSCI interrupts according to a provided mask. The mask is a logical OR of
enumeration members. See _lpsci_interrupt_enable. For example, to enable the TX empty interrupt and
RX full interrupt:
* LPSCI_EnableInterrupts(UART0,
kLPSCI_TxDataRegEmptyInterruptEnable |
kLPSCI_RxDataRegFullInterruptEnable);
*
Parameters
This function disables the LPSCI interrupts according to a provided mask. The mask is a logical OR of
enumeration members. See _lpsci_interrupt_enable. For example, to disable TX empty interrupt and RX
full interrupt:
* LPSCI_DisableInterrupts(UART0,
kLPSCI_TxDataRegEmptyInterruptEnable |
kLPSCI_RxDataRegFullInterruptEnable);
*
Parameters
This function gets the enabled LPSCI interrupts, which are returned as the logical OR value of the enumer-
ators _lpsci_interrupt_enable. To check a specific interrupts enable status, compare the return value to the
enumerators in _LPSCI_interrupt_enable. For example, to check whether TX empty interrupt is enabled:
Parameters
Returns
LPSCI interrupt flags which are logical OR of the enumerators in _LPSCI_interrupt_enable.
This function returns the LPSCI data register address, which is mainly used by DMA/eDMA case.
Parameters
Returns
LPSCI data register address which are used both by transmitter and receiver.
This function enables or disables the transmit data register empty flag, S1[TDRE], to generate DMA
requests.
Parameters
This function enables or disables the receiver data register full flag, S1[RDRF], to generate DMA requests.
Parameters
This function writes data to the TX register directly. The upper layer must ensure that the TX register is
empty before calling this function.
Parameters
This function reads data from the RX register directly. The upper layer must ensure that the RX register is
full before calling this function.
Parameters
Returns
Data read from RX data register.
This function polls the TX register, waits for the TX register empty, and writes data to the TX buffer.
Note
This function does not check whether all the data has been sent out to bus, so before disable TX,
check kLPSCI_TransmissionCompleteFlag to ensure the TX is finished.
Parameters
This function polls the RX register, waits for the RX register to be full, and reads data from the RX register.
Parameters
Return values
This function initializes the LPSCI handle, which can be used for other LPSCI transactional APIs. Usually,
for a specified LPSCI instance, call this API once to get the initialized handle.
LPSCI driver supports the "background" receiving, which means that the user can set up an RX ring buffer
optionally. Data received are stored into the ring buffer even when the user doesn’t call the LPSCI_-
TransferReceiveNonBlocking() API. If there is already data received in the ring buffer, get the received
data from the ring buffer directly. The ring buffer is disabled if pass NULL as ringBuffer.
Parameters
Note
When using the RX ring buffer, one byte is reserved for internal use. In other words, if ring-
BufferSize is 32, only 31 bytes are used for saving data.
Parameters
This function aborts the background transfer and uninstalls the ringbuffer.
Parameters
This function sends data using the interrupt method. This is a non-blocking function, which returns directly
without waiting for all data to be written to the TX register. When all data is written to the TX register in
ISR, LPSCI driver calls the callback function and passes the kStatus_LPSCI_TxIdle as status parameter.
Note
The kStatus_LPSCI_TxIdle is passed to the upper layer when all data is written to the TX register.
However, it does not ensure that all data is sent out. Before disabling the TX, check the kLPSCI_-
TransmissionCompleteFlag to ensure that the TX is complete.
Parameters
Return values
This function gets the number of bytes that have been written to LPSCI TX register by interrupt method.
Parameters
Return values
This function receives data using the interrupt method. This is a non-blocking function which returns
without waiting for all data to be received. If the RX ring buffer is used and not empty, the data in ring
buffer is copied and the parameter receivedBytes shows how many bytes are copied from the ring
buffer. After copying, if the data in ring buffer is not enough to read, the receive request is saved by the
LPSCI driver. When new data arrives, the receive request is serviced first. When all data is received, the
LPSCI driver notifies the upper layer through a callback function and passes the status parameter kStatus-
_LPSCI_RxIdle. For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring buffer.
The 5 bytes are copied to the xfer->data and the function returns with the parameter receivedBytes
set to 5. For the remaining 5 bytes, newly arrived data is saved from the xfer->data[5]. When 5 bytes
are received, the LPSCI driver notifies the upper layer. If the RX ring buffer is not enabled, this function
enables the RX and RX interrupt to receive data to the xfer->data. When all data is received, the upper
layer is notified.
Parameters
Return values
Parameters
This function gets the number of bytes that have been received.
Parameters
Return values
This function handles the LPSCI transmit and receive IRQ request.
Parameters
Parameters
Data Structures
• struct lpsci_dma_handle_t
LPSCI DMA handle. More...
Typedefs
eDMA transactional
Data Fields
• UART0_Type ∗ base
Parameters
This function sends data using DMA. This is a non-blocking function, which returns immediately. When
all data is sent, the send callback function is called.
Parameters
Return values
This function receives data using DMA. This is a non-blocking function, which returns immediately. When
all data is received, the receive callback function is called.
Parameters
Return values
This function gets the number of bytes that have been written to the LPSCI TX register by DMA.
Parameters
Return values
This function gets the number of bytes that have been received.
Parameters
Return values
Data Structures
• struct lpsci_rtos_config_t
LPSCI RTOS configuration structure. More...
Data Fields
• UART0_Type ∗ base
LPSCI base address.
• uint32_t srcclk
LPSCI source clock in Hz.
• uint32_t baudrate
Desired communication speed.
• lpsci_parity_mode_t parity
Parity setting.
• lpsci_stop_bit_count_t stopbits
Number of stop bits to use.
• uint8_t ∗ buffer
Buffer for background reception.
• uint32_t buffer_size
Size of buffer for background reception.
Parameters
handle The RTOS LPSCI handle, the pointer to allocated space for RTOS context.
t_handle The pointer to allocated space where to store transactional layer internal state.
cfg The pointer to the parameters required to configure the LPSCI after initialization.
Returns
0 succeed, others failed
This function deinitializes the LPSCI modulem, set all register value to reset value and releases the re-
sources.
Parameters
This function sends data. It is synchronous API. If the HW buffer is full, the task is in the blocked state.
Parameters
It is synchronous API.
This function receives data from LPSCI. If any data is immediately available it is returned immediately
and the number of bytes received.
Parameters
The function LPTMR_Init() initializes the LPTMR with specified configurations. The function LPTMR_-
GetDefaultConfig() gets the default configurations. The initialization function configures the LPTMR for
a timer or a pulse counter mode mode. It also sets up the LPTMR’s free running mode operation and a
clock source.
The function LPTMR_DeInit() disables the LPTMR module and gates the module clock.
The function LPTMR_SetTimerPeriod() sets the timer period in units of count. Timers counts from 0 to
the count value set here.
The function LPTMR_GetCurrentTimerCount() reads the current timer counting value. This function
returns the real-time timer counting value ranging from 0 to a timer period.
The timer period operation function takes the count value in ticks. Call the utility macros provided in the
fsl_common.h file to convert to microseconds or milliseconds.
The function LPTMR_StartTimer() starts the timer counting. After calling this function, the timer counts
up to the counter value set earlier by using the LPTMR_SetPeriod() function. Each time the timer reaches
the count value and increments, it generates a trigger pulse and sets the timeout interrupt flag. An interrupt
is also triggered if the timer interrupt is enabled.
The function LPTMR_StopTimer() stops the timer counting and resets the timer’s counter register.
16.2.4 Status
16.2.5 Interrupt
Provides functions to enable/disable LPTMR interrupts and get the currently enabled interrupts.
LED_INIT();
/* Starts counting */
LPTMR_StartTimer(LPTMR0);
while (1)
{
if (currentCounter != lptmrCounter)
{
currentCounter = lptmrCounter;
PRINTF("LPTMR interrupt No.%d \r\n", currentCounter);
}
}
}
Data Structures
• struct lptmr_config_t
LPTMR config structure. More...
Enumerations
• enum lptmr_pin_select_t {
kLPTMR_PinSelectInput_0 = 0x0U,
kLPTMR_PinSelectInput_1 = 0x1U,
kLPTMR_PinSelectInput_2 = 0x2U,
kLPTMR_PinSelectInput_3 = 0x3U }
LPTMR pin selection used in pulse counter mode.
• enum lptmr_pin_polarity_t {
kLPTMR_PinPolarityActiveHigh = 0x0U,
kLPTMR_PinPolarityActiveLow = 0x1U }
LPTMR pin polarity used in pulse counter mode.
• enum lptmr_timer_mode_t {
kLPTMR_TimerModeTimeCounter = 0x0U,
kLPTMR_TimerModePulseCounter = 0x1U }
LPTMR timer mode selection.
• enum lptmr_prescaler_glitch_value_t {
kLPTMR_Prescale_Glitch_0 = 0x0U,
kLPTMR_Prescale_Glitch_1 = 0x1U,
kLPTMR_Prescale_Glitch_2 = 0x2U,
kLPTMR_Prescale_Glitch_3 = 0x3U,
kLPTMR_Prescale_Glitch_4 = 0x4U,
kLPTMR_Prescale_Glitch_5 = 0x5U,
kLPTMR_Prescale_Glitch_6 = 0x6U,
kLPTMR_Prescale_Glitch_7 = 0x7U,
kLPTMR_Prescale_Glitch_8 = 0x8U,
kLPTMR_Prescale_Glitch_9 = 0x9U,
kLPTMR_Prescale_Glitch_10 = 0xAU,
kLPTMR_Prescale_Glitch_11 = 0xBU,
kLPTMR_Prescale_Glitch_12 = 0xCU,
kLPTMR_Prescale_Glitch_13 = 0xDU,
kLPTMR_Prescale_Glitch_14 = 0xEU,
kLPTMR_Prescale_Glitch_15 = 0xFU }
LPTMR prescaler/glitch filter values.
• enum lptmr_prescaler_clock_select_t {
kLPTMR_PrescalerClock_0 = 0x0U,
kLPTMR_PrescalerClock_1 = 0x1U,
kLPTMR_PrescalerClock_2 = 0x2U,
kLPTMR_PrescalerClock_3 = 0x3U }
LPTMR prescaler/glitch filter clock select.
• enum lptmr_interrupt_enable_t { kLPTMR_TimerInterruptEnable = LPTMR_CSR_TIE_MASK }
List of the LPTMR interrupts.
• enum lptmr_status_flags_t { kLPTMR_TimerCompareFlag = LPTMR_CSR_TCF_MASK }
List of the LPTMR status flags.
Driver version
• #define FSL_LPTMR_DRIVER_VERSION (MAKE_VERSION(2, 0, 1))
Version 2.0.1.
Interrupt Interface
• static void LPTMR_EnableInterrupts (LPTMR_Type ∗base, uint32_t mask)
Enables the selected LPTMR interrupts.
• static void LPTMR_DisableInterrupts (LPTMR_Type ∗base, uint32_t mask)
Disables the selected LPTMR interrupts.
• static uint32_t LPTMR_GetEnabledInterrupts (LPTMR_Type ∗base)
Gets the enabled LPTMR interrupts.
Status Interface
• static uint32_t LPTMR_GetStatusFlags (LPTMR_Type ∗base)
Gets the LPTMR status flags.
• static void LPTMR_ClearStatusFlags (LPTMR_Type ∗base, uint32_t mask)
Clears the LPTMR status flags.
This structure holds the configuration settings for the LPTMR peripheral. To initialize this structure to
reasonable defaults, call the LPTMR_GetDefaultConfig() function and pass a pointer to your configuration
structure instance.
The configuration struct can be made constant so it resides in flash.
Data Fields
• lptmr_timer_mode_t timerMode
Time counter mode or pulse counter mode.
• lptmr_pin_select_t pinSelect
LPTMR pulse input pin select; used only in pulse counter mode.
• lptmr_pin_polarity_t pinPolarity
LPTMR pulse input pin polarity; used only in pulse counter mode.
• bool enableFreeRunning
True: enable free running, counter is reset on overflow False: counter is reset when the compare flag is
set.
• bool bypassPrescaler
True: bypass prescaler; false: use clock from prescaler.
• lptmr_prescaler_clock_select_t prescalerClockSource
LPTMR clock source.
• lptmr_prescaler_glitch_value_t value
Prescaler or glitch filter value.
Enumerator
kLPTMR_PinSelectInput_0 Pulse counter input 0 is selected.
kLPTMR_PinSelectInput_1 Pulse counter input 1 is selected.
kLPTMR_PinSelectInput_2 Pulse counter input 2 is selected.
kLPTMR_PinSelectInput_3 Pulse counter input 3 is selected.
Enumerator
kLPTMR_PinPolarityActiveHigh Pulse Counter input source is active-high.
kLPTMR_PinPolarityActiveLow Pulse Counter input source is active-low.
Enumerator
kLPTMR_TimerModeTimeCounter Time Counter mode.
kLPTMR_TimerModePulseCounter Pulse Counter mode.
Enumerator
kLPTMR_Prescale_Glitch_0 Prescaler divide 2, glitch filter does not support this setting.
kLPTMR_Prescale_Glitch_1 Prescaler divide 4, glitch filter 2.
kLPTMR_Prescale_Glitch_2 Prescaler divide 8, glitch filter 4.
kLPTMR_Prescale_Glitch_3 Prescaler divide 16, glitch filter 8.
kLPTMR_Prescale_Glitch_4 Prescaler divide 32, glitch filter 16.
kLPTMR_Prescale_Glitch_5 Prescaler divide 64, glitch filter 32.
kLPTMR_Prescale_Glitch_6 Prescaler divide 128, glitch filter 64.
kLPTMR_Prescale_Glitch_7 Prescaler divide 256, glitch filter 128.
kLPTMR_Prescale_Glitch_8 Prescaler divide 512, glitch filter 256.
kLPTMR_Prescale_Glitch_9 Prescaler divide 1024, glitch filter 512.
kLPTMR_Prescale_Glitch_10 Prescaler divide 2048 glitch filter 1024.
kLPTMR_Prescale_Glitch_11 Prescaler divide 4096, glitch filter 2048.
kLPTMR_Prescale_Glitch_12 Prescaler divide 8192, glitch filter 4096.
kLPTMR_Prescale_Glitch_13 Prescaler divide 16384, glitch filter 8192.
kLPTMR_Prescale_Glitch_14 Prescaler divide 32768, glitch filter 16384.
kLPTMR_Prescale_Glitch_15 Prescaler divide 65536, glitch filter 32768.
Note
Clock connections are SoC-specific
Enumerator
kLPTMR_PrescalerClock_0 Prescaler/glitch filter clock 0 selected.
kLPTMR_PrescalerClock_1 Prescaler/glitch filter clock 1 selected.
kLPTMR_PrescalerClock_2 Prescaler/glitch filter clock 2 selected.
kLPTMR_PrescalerClock_3 Prescaler/glitch filter clock 3 selected.
Enumerator
kLPTMR_TimerInterruptEnable Timer interrupt enable.
Enumerator
kLPTMR_TimerCompareFlag Timer compare flag.
Note
This API should be called at the beginning of the application using the LPTMR driver.
Parameters
Parameters
* config->timerMode = kLPTMR_TimerModeTimeCounter;
* config->pinSelect = kLPTMR_PinSelectInput_0;
* config->pinPolarity = kLPTMR_PinPolarityActiveHigh;
* config->enableFreeRunning = false;
* config->bypassPrescaler = true;
* config->prescalerClockSource = kLPTMR_PrescalerClock_1;
* config->value = kLPTMR_Prescale_Glitch_0;
*
Parameters
Parameters
Parameters
Parameters
Returns
The enabled interrupts. This is the logical OR of members of the enumeration lptmr_interrupt_-
enable_t
Parameters
Returns
The status flags. This is the logical OR of members of the enumeration lptmr_status_flags_t
Parameters
Timers counts from 0 until it equals the count value set here. The count value is written to the CMR
register.
Note
1. The TCF flag is set with the CNR equals the count provided here and then increments.
2. Call the utility macros provided in the fsl_common.h to convert to ticks.
Parameters
This function returns the real-time timer counting value in a range from 0 to a timer period.
Note
Call the utility macros provided in the fsl_common.h to convert ticks to usec or msec.
Parameters
Returns
The current counter value in ticks
After calling this function, the timer counts up to the CMR register value. Each time the timer reaches
the CMR value and then increments, it generates a trigger pulse and sets the timeout interrupt flag. An
interrupt is also triggered if the timer interrupt is enabled.
Parameters
This function stops the timer and resets the timer’s counter register.
Parameters
The function PIT_Init() initializes the PIT with specified configurations. The function PIT_GetDefault-
Config() gets the default configurations. The initialization function configures the PIT operation in debug
mode.
The function PIT_SetTimerChainMode() configures the chain mode operation of each PIT channel.
The function PIT_Deinit() disables the PIT timers and disables the module clock.
The function PITR_SetTimerPeriod() sets the timer period in units of count. Timers begin counting down
from the value set by this function until it reaches 0.
The function PIT_GetCurrentTimerCount() reads the current timer counting value. This function returns
the real-time timer counting value, in a range from 0 to a timer period.
The timer period operation functions takes the count value in ticks. Users can call the utility macros
provided in fsl_common.h to convert to microseconds or milliseconds.
The function PIT_StartTimer() starts the timer counting. After calling this function, the timer loads the
period value set earlier via the PIT_SetPeriod() function and starts counting down to 0. When the timer
reaches 0, it generates a trigger pulse and sets the timeout interrupt flag.
The function PIT_StopTimer() stops the timer counting.
17.2.4 Status
17.2.5 Interrupt
Provides functions to enable/disable PIT interrupts and get current enabled interrupts.
int main(void)
{
/* Structure of initialize PIT */
pit_config_t pitConfig;
PIT_GetDefaultConfig(&pitConfig);
/* Start channel 0 */
PRINTF("\r\nStarting channel No.0 ...");
PIT_StartTimer(PIT, kPIT_Chnl_0);
while (true)
{
/* Check whether occur interupt and toggle LED */
if (true == pitIsrFlag)
{
PRINTF("\r\n Channel No.0 interrupt is occured !");
LED_TOGGLE();
pitIsrFlag = false;
}
}
}
Data Structures
• struct pit_config_t
PIT configuration structure. More...
Enumerations
• enum pit_chnl_t {
kPIT_Chnl_0 = 0U,
kPIT_Chnl_1,
kPIT_Chnl_2,
kPIT_Chnl_3 }
List of PIT channels.
• enum pit_interrupt_enable_t { kPIT_TimerInterruptEnable = PIT_TCTRL_TIE_MASK }
List of PIT interrupts.
• enum pit_status_flags_t { kPIT_TimerFlag = PIT_TFLG_TIF_MASK }
List of PIT status flags.
Functions
• uint64_t PIT_GetLifetimeTimerCount (PIT_Type ∗base)
Reads the current lifetime counter value.
Driver version
• #define FSL_PIT_DRIVER_VERSION (MAKE_VERSION(2, 0, 0))
Version 2.0.0.
Interrupt Interface
• static void PIT_EnableInterrupts (PIT_Type ∗base, pit_chnl_t channel, uint32_t mask)
Enables the selected PIT interrupts.
• static void PIT_DisableInterrupts (PIT_Type ∗base, pit_chnl_t channel, uint32_t mask)
Disables the selected PIT interrupts.
• static uint32_t PIT_GetEnabledInterrupts (PIT_Type ∗base, pit_chnl_t channel)
Gets the enabled PIT interrupts.
Status Interface
• static uint32_t PIT_GetStatusFlags (PIT_Type ∗base, pit_chnl_t channel)
Gets the PIT status flags.
• static void PIT_ClearStatusFlags (PIT_Type ∗base, pit_chnl_t channel, uint32_t mask)
Clears the PIT status flags.
This structure holds the configuration settings for the PIT peripheral. To initialize this structure to rea-
sonable defaults, call the PIT_GetDefaultConfig() function and pass a pointer to your config structure
instance.
The configuration structure can be made constant so it resides in flash.
Data Fields
• bool enableRunInDebug
true: Timers run in debug mode; false: Timers stop in debug mode
Note
Actual number of available channels is SoC dependent
Enumerator
kPIT_Chnl_0 PIT channel number 0.
kPIT_Chnl_1 PIT channel number 1.
Enumerator
kPIT_TimerInterruptEnable Timer interrupt enable.
Enumerator
kPIT_TimerFlag Timer flag.
Note
This API should be called at the beginning of the application using the PIT driver.
Parameters
Parameters
Parameters
When a timer has a chain mode enabled, it only counts after the previous timer has expired. If the timer
n-1 has counted down to 0, counter n decrements the value by one. Each timer is 32-bits, which allows the
developers to chain timers together and form a longer timer (64-bits and larger). The first timer (timer 0)
can’t be chained to any other timer.
Parameters
Parameters
Parameters
Parameters
Returns
The enabled interrupts. This is the logical OR of members of the enumeration pit_interrupt_enable_t
Parameters
Returns
The status flags. This is the logical OR of members of the enumeration pit_status_flags_t
Parameters
Timers begin counting from the value set by this function until it reaches 0, then it generates an interrupt
and load this register value again. Writing a new value to this register does not restart the timer. Instead,
the value is loaded after the timer expires.
Note
Users can call the utility macros provided in fsl_common.h to convert to ticks.
Parameters
This function returns the real-time timer counting value, in a range from 0 to a timer period.
Note
Users can call the utility macros provided in fsl_common.h to convert ticks to usec or msec.
Parameters
Returns
Current timer counting value in ticks
After calling this function, timers load period value, count down to 0 and then load the respective start
value again. Each time a timer reaches 0, it generates a trigger pulse and sets the timeout interrupt flag.
Parameters
This function stops every timer counting. Timers reload their periods respectively after the next time they
call the PIT_DRV_StartTimer.
Parameters
The lifetime timer is a 64-bit timer which chains timer 0 and timer 1 together. Timer 0 and 1 are chained
by calling the PIT_SetTimerChainMode before using this timer. The period of lifetime timer is equal to
the "period of timer 0 ∗ period of timer 1". For the 64-bit value, the higher 32-bit has the value of timer 1,
and the lower 32-bit has the value of timer 0.
Parameters
Returns
Current lifetime timer value
Data Structures
• struct pmc_low_volt_detect_config_t
Low-voltage Detect Configuration Structure. More...
• struct pmc_low_volt_warning_config_t
Low-voltage Warning Configuration Structure. More...
• struct pmc_bandgap_buffer_config_t
Bandgap Buffer configuration. More...
Enumerations
• enum pmc_low_volt_detect_volt_select_t {
kPMC_LowVoltDetectLowTrip = 0U,
kPMC_LowVoltDetectHighTrip = 1U }
Low-voltage Detect Voltage Select.
• enum pmc_low_volt_warning_volt_select_t {
kPMC_LowVoltWarningLowTrip = 0U,
kPMC_LowVoltWarningMid1Trip = 1U,
kPMC_LowVoltWarningMid2Trip = 2U,
kPMC_LowVoltWarningHighTrip = 3U }
Low-voltage Warning Voltage Select.
Driver version
• #define FSL_PMC_DRIVER_VERSION (MAKE_VERSION(2, 0, 0))
PMC driver version.
Data Fields
• bool enableInt
Enable interrupt when Low-voltage detect.
• bool enableReset
Enable system reset when Low-voltage detect.
• pmc_low_volt_detect_volt_select_t voltSelect
Low-voltage detect trip point voltage selection.
Data Fields
• bool enableInt
Enable interrupt when low-voltage warning.
• pmc_low_volt_warning_volt_select_t voltSelect
Low-voltage warning trip point voltage selection.
Data Fields
• bool enable
Enable bandgap buffer.
• bool enableInLowPowerMode
Version 2.0.0.
Enumerator
kPMC_LowVoltDetectLowTrip Low-trip point selected (VLVD = VLVDL )
kPMC_LowVoltDetectHighTrip High-trip point selected (VLVD = VLVDH )
Enumerator
kPMC_LowVoltWarningLowTrip Low-trip point selected (VLVW = VLVW1)
kPMC_LowVoltWarningMid1Trip Mid 1 trip point selected (VLVW = VLVW2)
kPMC_LowVoltWarningMid2Trip Mid 2 trip point selected (VLVW = VLVW3)
kPMC_LowVoltWarningHighTrip High-trip point selected (VLVW = VLVW4)
This function configures the low-voltage detect setting, including the trip point voltage setting, enables or
disables the interrupt, enables or disables the system reset.
Parameters
This function reads the current LVDF status. If it returns 1, a low-voltage event is detected.
Parameters
Returns
Current low-voltage detect flag
• true: Low-voltage detected
• false: Low-voltage not detected
This function acknowledges the low-voltage detection errors (write 1 to clear LVDF).
Parameters
This function configures the low-voltage warning setting, including the trip point voltage setting and en-
abling or disabling the interrupt.
Parameters
This function polls the current LVWF status. When 1 is returned, it indicates a low-voltage warning event.
LVWF is set when V Supply transitions below the trip point or after reset and V Supply is already below
the V LVW.
Parameters
Returns
Current LVWF status
• true: Low-voltage Warning Flag is set.
• false: the Low-voltage Warning does not happen.
This function acknowledges the low voltage warning errors (write 1 to clear LVWF).
Parameters
This function configures the PMC bandgap, including the drive select and behavior in low-power mode.
Parameters
This function reads the Acknowledge Isolation setting that indicates whether certain peripherals and the
I/O pads are in a latched state as a result of having been in the VLLS mode.
Parameters
Returns
ACK isolation 0 - Peripherals and I/O pads are in a normal run state. 1 - Certain peripherals and I/O
pads are in an isolated and latched state.
This function clears the ACK Isolation flag. Writing one to this setting when it is set releases the I/O pads
and certain peripherals to their normal run mode state.
Parameters
This function returns the regulator to run a regulation status. It provides the current status of the internal
voltage regulator.
Parameters
Returns
Regulation status 0 - Regulator is in a stop regulation or in transition to/from the regulation. 1 -
Regulator is in a run regulation.
Data Structures
• struct port_pin_config_t
PORT pin configuration structure. More...
Enumerations
• enum _port_pull {
kPORT_PullDisable = 0U,
kPORT_PullDown = 2U,
kPORT_PullUp = 3U }
Driver version
• #define FSL_PORT_DRIVER_VERSION (MAKE_VERSION(2, 0, 2))
Version 2.0.2.
Configuration
• static void PORT_SetPinConfig (PORT_Type ∗base, uint32_t pin, const port_pin_config_t ∗config)
Sets the port PCR register.
• static void PORT_SetMultiplePinsConfig (PORT_Type ∗base, uint32_t mask, const port_pin_-
config_t ∗config)
Sets the port PCR register for multiple pins.
• static void PORT_SetPinMux (PORT_Type ∗base, uint32_t pin, port_mux_t mux)
Configures the pin muxing.
Interrupt
• static void PORT_SetPinInterruptConfig (PORT_Type ∗base, uint32_t pin, port_interrupt_t config)
Configures the port pin interrupt/DMA request.
• static uint32_t PORT_GetPinsInterruptFlags (PORT_Type ∗base)
Reads the whole port status flag.
• static void PORT_ClearPinsInterruptFlags (PORT_Type ∗base, uint32_t mask)
Clears the multiple pin interrupt status flag.
Data Fields
• uint16_t pullSelect: 2
No-pull/pull-down/pull-up select.
• uint16_t slewRate: 1
Fast/slow slew rate Configure.
• uint16_t passiveFilterEnable: 1
Passive filter enable/disable.
• uint16_t driveStrength: 1
Fast/slow drive strength configure.
• uint16_t mux: 3
Pin mux Configure.
Enumerator
kPORT_PullDisable Internal pull-up/down resistor is disabled.
kPORT_PullDown Internal pull-down resistor is enabled.
kPORT_PullUp Internal pull-up resistor is enabled.
Enumerator
kPORT_FastSlewRate Fast slew rate is configured.
kPORT_SlowSlewRate Slow slew rate is configured.
Enumerator
kPORT_PassiveFilterDisable Passive input filter is disabled.
kPORT_PassiveFilterEnable Passive input filter is enabled.
Enumerator
kPORT_LowDriveStrength Low-drive strength is configured.
kPORT_HighDriveStrength High-drive strength is configured.
Enumerator
kPORT_PinDisabledOrAnalog Corresponding pin is disabled, but is used as an analog pin.
kPORT_MuxAsGpio Corresponding pin is configured as GPIO.
kPORT_MuxAlt2 Chip-specific.
kPORT_MuxAlt3 Chip-specific.
kPORT_MuxAlt4 Chip-specific.
kPORT_MuxAlt5 Chip-specific.
kPORT_MuxAlt6 Chip-specific.
kPORT_MuxAlt7 Chip-specific.
kPORT_MuxAlt8 Chip-specific.
kPORT_MuxAlt9 Chip-specific.
kPORT_MuxAlt10 Chip-specific.
kPORT_MuxAlt11 Chip-specific.
kPORT_MuxAlt12 Chip-specific.
kPORT_MuxAlt13 Chip-specific.
kPORT_MuxAlt14 Chip-specific.
kPORT_MuxAlt15 Chip-specific.
Enumerator
kPORT_InterruptOrDMADisabled Interrupt/DMA request is disabled.
kPORT_DMARisingEdge DMA request on rising edge.
kPORT_DMAFallingEdge DMA request on falling edge.
kPORT_DMAEitherEdge DMA request on either edge.
kPORT_InterruptLogicZero Interrupt when logic zero.
kPORT_InterruptRisingEdge Interrupt on rising edge.
kPORT_InterruptFallingEdge Interrupt on falling edge.
kPORT_InterruptEitherEdge Interrupt on either edge.
kPORT_InterruptLogicOne Interrupt when logic one.
Parameters
* kPORT_PullEnable,
* kPORT_FastSlewRate,
* kPORT_PassiveFilterDisable,
* kPORT_OpenDrainDisable,
* kPORT_LowDriveStrength,
* kPORT_MuxAsGpio,
* kPORT_UnlockRegister,
* };
*
Parameters
Parameters
Parameters
If a pin is configured to generate the DMA request, the corresponding flag is cleared automatically at the
completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to
that flag. If configured for a level sensitive interrupt that remains asserted, the flag is set again immediately.
Parameters
Returns
Current port interrupt status flags, for example, 0x00010001 means the pin 0 and 16 have the inter-
rupt.
Parameters
Data Structures
• struct rcm_reset_pin_filter_config_t
Reset pin filter configuration. More...
Enumerations
• enum rcm_reset_source_t {
kRCM_SourceWakeup = RCM_SRS0_WAKEUP_MASK,
kRCM_SourceLvd = RCM_SRS0_LVD_MASK,
kRCM_SourceLoc = RCM_SRS0_LOC_MASK,
kRCM_SourceLol = RCM_SRS0_LOL_MASK,
kRCM_SourceWdog = RCM_SRS0_WDOG_MASK,
kRCM_SourcePin = RCM_SRS0_PIN_MASK,
kRCM_SourcePor = RCM_SRS0_POR_MASK,
kRCM_SourceLockup = RCM_SRS1_LOCKUP_MASK << 8U,
kRCM_SourceSw = RCM_SRS1_SW_MASK << 8U,
kRCM_SourceMdmap = RCM_SRS1_MDM_AP_MASK << 8U,
kRCM_SourceSackerr = RCM_SRS1_SACKERR_MASK << 8U }
System Reset Source Name definitions.
• enum rcm_run_wait_filter_mode_t {
kRCM_FilterDisable = 0U,
kRCM_FilterBusClock = 1U,
kRCM_FilterLpoClock = 2U }
Reset pin filter select in Run and Wait modes.
Driver version
• #define FSL_RCM_DRIVER_VERSION (MAKE_VERSION(2, 0, 1))
RCM driver version 2.0.1.
Data Fields
• bool enableFilterInStop
Reset pin filter select in stop mode.
• rcm_run_wait_filter_mode_t filterInRunWait
Reset pin filter in run/wait mode.
• uint8_t busClockFilterCount
Reset pin bus clock filter width.
Enumerator
kRCM_SourceWakeup Low-leakage wakeup reset.
kRCM_SourceLvd Low-voltage detect reset.
kRCM_SourceLoc Loss of clock reset.
kRCM_SourceLol Loss of lock reset.
kRCM_SourceWdog Watchdog reset.
kRCM_SourcePin External pin reset.
kRCM_SourcePor Power on reset.
kRCM_SourceLockup Core lock up reset.
kRCM_SourceSw Software reset.
kRCM_SourceMdmap MDM-AP system reset.
kRCM_SourceSackerr Parameter could get all reset flags.
Enumerator
kRCM_FilterDisable All filtering disabled.
kRCM_FilterBusClock Bus clock filter enabled.
kRCM_FilterLpoClock LPO clock filter enabled.
This function gets the current reset source status. Use source masks defined in the rcm_reset_source_t to
get the desired source status.
This is an example.
uint32_t resetStatus;
Parameters
Returns
All reset source status bit map.
This function sets the reset pin filter including the filter source, filter width, and so on.
Parameters
The function RTC_Init() initializes the RTC with specified configurations. The function RTC_GetDefault-
Config() gets the default configurations.
The function RTC_Deinit() disables the RTC timer and disables the module clock.
The function RTC_SetDatetime() sets the timer period in seconds. Users pass in the details in date & time
format by using the below data structure.
The function RTC_GetDatetime() reads the current timer value in seconds, converts it to date & time
format and stores it into a datetime structure passed in by the user.
The function RTC_SetAlarm() sets the alarm time period in seconds. Users pass in the details in date &
time format by using the datetime data structure.
The function RTC_GetAlarm() reads the alarm time in seconds, converts it to date & time format and
stores it into a datetime structure passed in by the user.
21.2.5 Status
21.2.6 Interrupt
Provides functions to enable/disable RTC interrupts and get current enabled interrupts.
Some SoC’s allow control of the RTC oscillator through the RTC module.
The function RTC_SetOscCapLoad() allows the user to modify the capacitor load configuration of the
RTC oscillator.
Some SoC’s have a 64-bit Monotonic counter available in the RTC module.
The function RTC_SetMonotonicCounter() writes a 64-bit to the counter.
The function RTC_GetMonotonicCounter() reads the monotonic counter and returns the 64-bit counter
value to the user.
The function RTC_IncrementMonotonicCounter() increments the Monotonic Counter by one.
int main(void)
{
uint32_t sec;
uint32_t currSeconds;
rtc_datetime_t date;
rtc_config_t rtcConfig;
BOARD_InitHardware();
/* Init RTC */
RTC_GetDefaultConfig(&rtcConfig);
RTC_Init(RTC, &rtcConfig);
/* Select RTC clock source */
BOARD_SetRtcClockSource();
/* RTC time counter has to be stopped before setting the date & time in the TSR register */
RTC_StopTimer(RTC);
Data Structures
• struct rtc_datetime_t
Structure is used to hold the date and time. More...
• struct rtc_config_t
RTC config structure. More...
Enumerations
• enum rtc_interrupt_enable_t {
kRTC_TimeInvalidInterruptEnable = RTC_IER_TIIE_MASK,
kRTC_TimeOverflowInterruptEnable = RTC_IER_TOIE_MASK,
kRTC_AlarmInterruptEnable = RTC_IER_TAIE_MASK,
kRTC_SecondsInterruptEnable = RTC_IER_TSIE_MASK }
List of RTC interrupts.
• enum rtc_status_flags_t {
kRTC_TimeInvalidFlag = RTC_SR_TIF_MASK,
kRTC_TimeOverflowFlag = RTC_SR_TOF_MASK,
kRTC_AlarmFlag = RTC_SR_TAF_MASK }
List of RTC flags.
• enum rtc_osc_cap_load_t {
kRTC_Capacitor_2p = RTC_CR_SC2P_MASK,
kRTC_Capacitor_4p = RTC_CR_SC4P_MASK,
kRTC_Capacitor_8p = RTC_CR_SC8P_MASK,
kRTC_Capacitor_16p = RTC_CR_SC16P_MASK }
List of RTC Oscillator capacitor load settings.
Functions
• static void RTC_SetOscCapLoad (RTC_Type ∗base, uint32_t capLoad)
This function sets the specified capacitor configuration for the RTC oscillator.
• static void RTC_Reset (RTC_Type ∗base)
Performs a software reset on the RTC module.
Driver version
• #define FSL_RTC_DRIVER_VERSION (MAKE_VERSION(2, 0, 0))
Version 2.0.0.
Interrupt Interface
• static void RTC_EnableInterrupts (RTC_Type ∗base, uint32_t mask)
Enables the selected RTC interrupts.
• static void RTC_DisableInterrupts (RTC_Type ∗base, uint32_t mask)
Disables the selected RTC interrupts.
• static uint32_t RTC_GetEnabledInterrupts (RTC_Type ∗base)
Gets the enabled RTC interrupts.
Status Interface
• static uint32_t RTC_GetStatusFlags (RTC_Type ∗base)
Gets the RTC status flags.
• void RTC_ClearStatusFlags (RTC_Type ∗base, uint32_t mask)
Clears the RTC status flags.
Data Fields
• uint16_t year
This structure holds the configuration settings for the RTC peripheral. To initialize this structure to rea-
sonable defaults, call the RTC_GetDefaultConfig() function and pass a pointer to your config structure
instance.
The config struct can be made const so it resides in flash
Data Fields
• bool wakeupSelect
true: Wakeup pin outputs the 32 KHz clock; false:Wakeup pin used to wakeup the chip
• bool updateMode
true: Registers can be written even when locked under certain conditions, false: No writes allowed when
registers are locked
• bool supervisorAccess
true: Non-supervisor accesses are allowed; false: Non-supervisor accesses are not supported
• uint32_t compensationInterval
Compensation interval that is written to the CIR field in RTC TCR Register.
• uint32_t compensationTime
Compensation time that is written to the TCR field in RTC TCR Register.
Enumerator
kRTC_TimeInvalidInterruptEnable Time invalid interrupt.
kRTC_TimeOverflowInterruptEnable Time overflow interrupt.
kRTC_AlarmInterruptEnable Alarm interrupt.
kRTC_SecondsInterruptEnable Seconds interrupt.
Enumerator
kRTC_TimeInvalidFlag Time invalid flag.
kRTC_TimeOverflowFlag Time overflow flag.
kRTC_AlarmFlag Alarm flag.
Enumerator
kRTC_Capacitor_2p 2 pF capacitor load
kRTC_Capacitor_4p 4 pF capacitor load
kRTC_Capacitor_8p 8 pF capacitor load
kRTC_Capacitor_16p 16 pF capacitor load
This function issues a software reset if the timer invalid flag is set.
Note
This API should be called at the beginning of the application using the RTC driver.
Parameters
Parameters
* config->wakeupSelect = false;
* config->updateMode = false;
* config->supervisorAccess = false;
* config->compensationInterval = 0;
* config->compensationTime = 0;
*
Parameters
The RTC counter must be stopped prior to calling this function because writes to the RTC seconds register
fail if the RTC counter is running.
Parameters
datetime Pointer to the structure where the date and time details are stored.
Returns
kStatus_Success: Success in setting the time and starting the RTC kStatus_InvalidArgument: Error
because the datetime format is incorrect
Parameters
The function checks whether the specified alarm time is greater than the present time. If not, the function
does not set the alarm and returns an error.
Parameters
Returns
kStatus_Success: success in setting the RTC alarm kStatus_InvalidArgument: Error because the
alarm datetime format is incorrect kStatus_Fail: Error because the alarm time has already passed
Parameters
Parameters
Parameters
Parameters
Returns
The enabled interrupts. This is the logical OR of members of the enumeration rtc_interrupt_enable_t
Parameters
Returns
The status flags. This is the logical OR of members of the enumeration rtc_status_flags_t
Parameters
After calling this function, the timer counter increments once a second provided SR[TOF] or SR[TIF] are
not set.
Parameters
RTC’s seconds register can be written to only when the timer is stopped.
Parameters
Parameters
This resets all RTC registers except for the SWR bit and the RTC_WAR and RTC_RAR registers. The
SWR bit is cleared by software explicitly clearing it.
Parameters
sai_handle_t g_saiTxHandle;
sai_config_t user_config;
sai_transfer_t sendXfer;
volatile bool txFinished;
volatile bool rxFinished;
const uint8_t sendData[] = [......];
if (kStatus_SAI_TxIdle == status)
{
txFinished = true;
}
}
void main(void)
{
//...
SAI_TxGetDefaultConfig(&user_config);
SAI_TxInit(SAI0, &user_config);
SAI_TransferTxCreateHandle(SAI0, &g_saiHandle, SAI_UserCallback, NULL);
// Prepare to send.
sendXfer.data = sendData
sendXfer.dataSize = sizeof(sendData)/sizeof(sendData[0]);
txFinished = false;
// Send out.
SAI_TransferSendNonBlocking(SAI0, &g_saiHandle, &sendXfer);
// ...
}
sai_handle_t g_saiHandle;
dma_handle_t g_saiTxDmaHandle;
dma_handle_t g_saiRxDmaHandle;
sai_config_t user_config;
sai_transfer_t sendXfer;
volatile bool txFinished;
uint8_t sendData[] = ...;
if (kStatus_SAI_TxIdle == status)
{
txFinished = true;
}
}
void main(void)
{
//...
SAI_TxGetDefaultConfig(&user_config);
SAI_TxInit(SAI0, &user_config);
DMA_Init(DMA0);
// Prepares to send.
sendXfer.data = sendData
sendXfer.dataSize = sizeof(sendData)/sizeof(sendData[0]);
txFinished = false;
// Sends out.
SAI_TransferSendDMA(&g_saiHandle, &sendXfer);
// ...
}
Modules
• SAI DMA Driver
• SAI eDMA Driver
Data Structures
• struct sai_config_t
SAI user configuration structure. More...
• struct sai_transfer_format_t
sai transfer format More...
• struct sai_transfer_t
SAI transfer structure. More...
• struct sai_handle_t
SAI handle structure. More...
Macros
• #define SAI_XFER_QUEUE_SIZE (4)
SAI transfer queue size, user can refine it according to use case.
Typedefs
• typedef void(∗ sai_transfer_callback_t )(I2S_Type ∗base, sai_handle_t ∗handle, status_t status, void
∗userData)
SAI transfer callback prototype.
Enumerations
• enum _sai_status_t {
kStatus_SAI_TxBusy = MAKE_STATUS(kStatusGroup_SAI, 0),
kStatus_SAI_RxBusy = MAKE_STATUS(kStatusGroup_SAI, 1),
kStatus_SAI_TxError = MAKE_STATUS(kStatusGroup_SAI, 2),
kStatus_SAI_RxError = MAKE_STATUS(kStatusGroup_SAI, 3),
kStatus_SAI_QueueFull = MAKE_STATUS(kStatusGroup_SAI, 4),
kStatus_SAI_TxIdle = MAKE_STATUS(kStatusGroup_SAI, 5),
kStatus_SAI_RxIdle = MAKE_STATUS(kStatusGroup_SAI, 6) }
kSAI_FIFOWarningFlag = I2S_TCSR_FWF_MASK }
The SAI status flag.
• enum sai_reset_type_t {
kSAI_ResetTypeSoftware = I2S_TCSR_SR_MASK,
kSAI_ResetTypeFIFO = I2S_TCSR_FR_MASK,
kSAI_ResetAll = I2S_TCSR_SR_MASK | I2S_TCSR_FR_MASK }
The reset type.
• enum sai_sample_rate_t {
kSAI_SampleRate8KHz = 8000U,
kSAI_SampleRate11025Hz = 11025U,
kSAI_SampleRate12KHz = 12000U,
kSAI_SampleRate16KHz = 16000U,
kSAI_SampleRate22050Hz = 22050U,
kSAI_SampleRate24KHz = 24000U,
kSAI_SampleRate32KHz = 32000U,
kSAI_SampleRate44100Hz = 44100U,
kSAI_SampleRate48KHz = 48000U,
kSAI_SampleRate96KHz = 96000U }
Audio sample rate.
• enum sai_word_width_t {
kSAI_WordWidth8bits = 8U,
kSAI_WordWidth16bits = 16U,
kSAI_WordWidth24bits = 24U,
kSAI_WordWidth32bits = 32U }
Audio word width.
Driver version
• #define FSL_SAI_DRIVER_VERSION (MAKE_VERSION(2, 1, 2))
Version 2.1.2.
Status
• static uint32_t SAI_TxGetStatusFlag (I2S_Type ∗base)
Gets the SAI Tx status flag state.
• static void SAI_TxClearStatusFlags (I2S_Type ∗base, uint32_t mask)
Clears the SAI Tx status flag state.
• static uint32_t SAI_RxGetStatusFlag (I2S_Type ∗base)
Gets the SAI Tx status flag state.
• static void SAI_RxClearStatusFlags (I2S_Type ∗base, uint32_t mask)
Clears the SAI Rx status flag state.
Interrupts
• static void SAI_TxEnableInterrupts (I2S_Type ∗base, uint32_t mask)
Enables the SAI Tx interrupt requests.
• static void SAI_RxEnableInterrupts (I2S_Type ∗base, uint32_t mask)
Enables the SAI Rx interrupt requests.
• static void SAI_TxDisableInterrupts (I2S_Type ∗base, uint32_t mask)
Disables the SAI Tx interrupt requests.
• static void SAI_RxDisableInterrupts (I2S_Type ∗base, uint32_t mask)
Disables the SAI Rx interrupt requests.
DMA Control
• static void SAI_TxEnableDMA (I2S_Type ∗base, uint32_t mask, bool enable)
Enables/disables the SAI Tx DMA requests.
• static void SAI_RxEnableDMA (I2S_Type ∗base, uint32_t mask, bool enable)
Enables/disables the SAI Rx DMA requests.
• static uint32_t SAI_TxGetDataRegisterAddress (I2S_Type ∗base, uint32_t channel)
Gets the SAI Tx data register address.
• static uint32_t SAI_RxGetDataRegisterAddress (I2S_Type ∗base, uint32_t channel)
Gets the SAI Rx data register address.
Bus Operations
• void SAI_TxSetFormat (I2S_Type ∗base, sai_transfer_format_t ∗format, uint32_t mclkSource-
ClockHz, uint32_t bclkSourceClockHz)
Configures the SAI Tx audio format.
• void SAI_RxSetFormat (I2S_Type ∗base, sai_transfer_format_t ∗format, uint32_t mclkSource-
ClockHz, uint32_t bclkSourceClockHz)
Configures the SAI Rx audio format.
• void SAI_WriteBlocking (I2S_Type ∗base, uint32_t channel, uint32_t bitWidth, uint8_t ∗buffer,
uint32_t size)
Sends data using a blocking method.
• static void SAI_WriteData (I2S_Type ∗base, uint32_t channel, uint32_t data)
Writes data into SAI FIFO.
• void SAI_ReadBlocking (I2S_Type ∗base, uint32_t channel, uint32_t bitWidth, uint8_t ∗buffer,
uint32_t size)
Receives data using a blocking method.
• static uint32_t SAI_ReadData (I2S_Type ∗base, uint32_t channel)
Reads data from the SAI FIFO.
Transactional
• void SAI_TransferTxCreateHandle (I2S_Type ∗base, sai_handle_t ∗handle, sai_transfer_callback_t
callback, void ∗userData)
Initializes the SAI Tx handle.
• void SAI_TransferRxCreateHandle (I2S_Type ∗base, sai_handle_t ∗handle, sai_transfer_callback_t
callback, void ∗userData)
Initializes the SAI Rx handle.
• status_t SAI_TransferTxSetFormat (I2S_Type ∗base, sai_handle_t ∗handle, sai_transfer_format_t
∗format, uint32_t mclkSourceClockHz, uint32_t bclkSourceClockHz)
Configures the SAI Tx audio format.
• status_t SAI_TransferRxSetFormat (I2S_Type ∗base, sai_handle_t ∗handle, sai_transfer_format_t
∗format, uint32_t mclkSourceClockHz, uint32_t bclkSourceClockHz)
Configures the SAI Rx audio format.
• status_t SAI_TransferSendNonBlocking (I2S_Type ∗base, sai_handle_t ∗handle, sai_transfer_-
t ∗xfer)
Performs an interrupt non-blocking send transfer on SAI.
• status_t SAI_TransferReceiveNonBlocking (I2S_Type ∗base, sai_handle_t ∗handle, sai_transfer_t
∗xfer)
Performs an interrupt non-blocking receive transfer on SAI.
• status_t SAI_TransferGetSendCount (I2S_Type ∗base, sai_handle_t ∗handle, size_t ∗count)
Gets a set byte count.
• status_t SAI_TransferGetReceiveCount (I2S_Type ∗base, sai_handle_t ∗handle, size_t ∗count)
Gets a received byte count.
• void SAI_TransferAbortSend (I2S_Type ∗base, sai_handle_t ∗handle)
Aborts the current send.
• void SAI_TransferAbortReceive (I2S_Type ∗base, sai_handle_t ∗handle)
Aborts the the current IRQ receive.
• void SAI_TransferTxHandleIRQ (I2S_Type ∗base, sai_handle_t ∗handle)
Tx interrupt handler.
• void SAI_TransferRxHandleIRQ (I2S_Type ∗base, sai_handle_t ∗handle)
Tx interrupt handler.
Data Fields
• sai_protocol_t protocol
Audio bus protocol in SAI.
• sai_sync_mode_t syncMode
SAI sync mode, control Tx/Rx clock sync.
• bool mclkOutputEnable
Master clock output enable, true means master clock divider enabled.
• sai_mclk_source_t mclkSource
Master Clock source.
• sai_bclk_source_t bclkSource
Bit Clock source.
• sai_master_slave_t masterSlave
Master or slave.
Data Fields
• uint32_t sampleRate_Hz
Sample rate of audio data.
• uint32_t bitWidth
Data length of audio data, usually 8/16/24/32 bits.
• sai_mono_stereo_t stereo
Mono or stereo.
• uint32_t masterClockHz
Master clock frequency in Hz.
• uint8_t channel
Data channel used in transfer.
• sai_protocol_t protocol
Which audio protocol used.
Data Fields
• uint8_t ∗ data
Data start address to transfer.
• size_t dataSize
Transfer size.
Data Fields
• uint32_t state
Transfer status.
• sai_transfer_callback_t callback
Callback function called at transfer event.
• void ∗ userData
Callback parameter passed to callback function.
• uint8_t bitWidth
Bit width for transfer, 8/16/24/32 bits.
• uint8_t channel
Transfer channel.
• sai_transfer_t saiQueue [SAI_XFER_QUEUE_SIZE]
Transfer queue storing queued transfer.
• size_t transferSize [SAI_XFER_QUEUE_SIZE]
Data bytes need to transfer.
• volatile uint8_t queueUser
Index for user to queue transfer.
• volatile uint8_t queueDriver
Index for driver to get the transfer data and size.
Enumerator
kStatus_SAI_TxBusy SAI Tx is busy.
kStatus_SAI_RxBusy SAI Rx is busy.
kStatus_SAI_TxError SAI Tx FIFO error.
kStatus_SAI_RxError SAI Rx FIFO error.
kStatus_SAI_QueueFull SAI transfer queue is full.
kStatus_SAI_TxIdle SAI Tx is idle.
kStatus_SAI_RxIdle SAI Rx is idle.
Enumerator
kSAI_BusLeftJustified Uses left justified format.
kSAI_BusRightJustified Uses right justified format.
kSAI_BusI2S Uses I2S format.
kSAI_BusPCMA Uses I2S PCM A format.
kSAI_BusPCMB Uses I2S PCM B format.
Enumerator
kSAI_Master Master mode.
kSAI_Slave Slave mode.
Enumerator
kSAI_Stereo Stereo sound.
kSAI_MonoLeft Only left channel have sound.
kSAI_MonoRight Only Right channel have sound.
Enumerator
kSAI_ModeAsync Asynchronous mode.
kSAI_ModeSync Synchronous mode (with receiver or transmit)
kSAI_ModeSyncWithOtherTx Synchronous with another SAI transmit.
kSAI_ModeSyncWithOtherRx Synchronous with another SAI receiver.
Enumerator
kSAI_MclkSourceSysclk Master clock from the system clock.
kSAI_MclkSourceSelect1 Master clock from source 1.
kSAI_MclkSourceSelect2 Master clock from source 2.
kSAI_MclkSourceSelect3 Master clock from source 3.
Enumerator
kSAI_BclkSourceBusclk Bit clock using bus clock.
kSAI_BclkSourceMclkDiv Bit clock using master clock divider.
kSAI_BclkSourceOtherSai0 Bit clock from other SAI device.
kSAI_BclkSourceOtherSai1 Bit clock from other SAI device.
Enumerator
kSAI_WordStartInterruptEnable Word start flag, means the first word in a frame detected.
kSAI_SyncErrorInterruptEnable Sync error flag, means the sync error is detected.
kSAI_FIFOWarningInterruptEnable FIFO warning flag, means the FIFO is empty.
kSAI_FIFOErrorInterruptEnable FIFO error flag.
Enumerator
kSAI_FIFOWarningDMAEnable FIFO warning caused by the DMA request.
Enumerator
kSAI_WordStartFlag Word start flag, means the first word in a frame detected.
kSAI_SyncErrorFlag Sync error flag, means the sync error is detected.
kSAI_FIFOErrorFlag FIFO error flag.
kSAI_FIFOWarningFlag FIFO warning flag.
Enumerator
kSAI_ResetTypeSoftware Software reset, reset the logic state.
kSAI_ResetTypeFIFO FIFO reset, reset the FIFO read and write pointer.
kSAI_ResetAll All reset.
Enumerator
kSAI_SampleRate8KHz Sample rate 8000 Hz.
kSAI_SampleRate11025Hz Sample rate 11025 Hz.
kSAI_SampleRate12KHz Sample rate 12000 Hz.
kSAI_SampleRate16KHz Sample rate 16000 Hz.
kSAI_SampleRate22050Hz Sample rate 22050 Hz.
kSAI_SampleRate24KHz Sample rate 24000 Hz.
kSAI_SampleRate32KHz Sample rate 32000 Hz.
kSAI_SampleRate44100Hz Sample rate 44100 Hz.
kSAI_SampleRate48KHz Sample rate 48000 Hz.
kSAI_SampleRate96KHz Sample rate 96000 Hz.
Enumerator
kSAI_WordWidth8bits Audio data width 8 bits.
kSAI_WordWidth16bits Audio data width 16 bits.
kSAI_WordWidth24bits Audio data width 24 bits.
kSAI_WordWidth32bits Audio data width 32 bits.
Ungates the SAI clock, resets the module, and configures SAI Tx with a configuration structure. The
configuration structure can be custom filled or set with default values by SAI_TxGetDefaultConfig().
Note
This API should be called at the beginning of the application to use the SAI driver. Otherwise,
accessing the SAIM module can cause a hard fault because the clock is not enabled.
Parameters
Ungates the SAI clock, resets the module, and configures the SAI Rx with a configuration structure. The
configuration structure can be custom filled or set with default values by SAI_RxGetDefaultConfig().
Note
This API should be called at the beginning of the application to use the SAI driver. Otherwise,
accessing the SAI module can cause a hard fault because the clock is not enabled.
Parameters
This API initializes the configuration structure for use in SAI_TxConfig(). The initialized structure can
remain unchanged in SAI_TxConfig(), or it can be modified before calling SAI_TxConfig(). This is an
example.
sai_config_t config;
SAI_TxGetDefaultConfig(&config);
Parameters
This API initializes the configuration structure for use in SAI_RxConfig(). The initialized structure can
remain unchanged in SAI_RxConfig() or it can be modified before calling SAI_RxConfig(). This is an
example.
sai_config_t config;
SAI_RxGetDefaultConfig(&config);
Parameters
This API gates the SAI clock. The SAI module can’t operate unless SAI_TxInit or SAI_RxInit is called
to enable the clock.
Parameters
This function enables the software reset and FIFO reset of SAI Tx. After reset, clear the reset bit.
Parameters
This function enables the software reset and FIFO reset of SAI Rx. After reset, clear the reset bit.
Parameters
Parameters
Parameters
Parameters
Returns
SAI Tx status flag value. Use the Status Mask to get the status value needed.
Parameters
Parameters
Returns
SAI Rx status flag value. Use the Status Mask to get the status value needed.
Parameters
Parameters
Parameters
Parameters
Parameters
Parameters
Parameters
This API is used to provide a transfer address for the SAI DMA transfer configuration.
Parameters
Returns
data register address.
This API is used to provide a transfer address for the SAI DMA transfer configuration.
Parameters
Returns
data register address.
The audio format can be changed at run-time. This function configures the sample rate and audio data
format to be transferred.
Parameters
bclkSource- SAI bit clock source frequency in Hz. If the bit clock source is a master clock, this
ClockHz value should equal the masterClockHz.
The audio format can be changed at run-time. This function configures the sample rate and audio data
format to be transferred.
Parameters
Note
This function blocks by polling until data is ready to be sent.
Parameters
Parameters
Note
This function blocks by polling until data is ready to be sent.
Parameters
Parameters
Returns
Data in SAI FIFO.
This function initializes the Tx handle for the SAI Tx transactional APIs. Call this function once to get
the handle initialized.
Parameters
This function initializes the Rx handle for the SAI Rx transactional APIs. Call this function once to get
the handle initialized.
Parameters
The audio format can be changed at run-time. This function configures the sample rate and audio data
format to be transferred.
Parameters
bclkSource- SAI bit clock source frequency in Hz. If a bit clock source is a master clock, this
ClockHz value should equal the masterClockHz in format.
Returns
Status of this function. Return value is the status_t.
The audio format can be changed at run-time. This function configures the sample rate and audio data
format to be transferred.
Parameters
Returns
Status of this function. Return value is one of status_t.
Note
This API returns immediately after the transfer initiates. Call the SAI_TxGetTransferStatusIRQ to
poll the transfer status and check whether the transfer is finished. If the return status is not kStatus_-
SAI_Busy, the transfer is finished.
Parameters
Return values
Note
This API returns immediately after the transfer initiates. Call the SAI_RxGetTransferStatusIRQ to
poll the transfer status and check whether the transfer is finished. If the return status is not kStatus_-
SAI_Busy, the transfer is finished.
Parameters
Return values
Parameters
Return values
Parameters
Return values
Note
This API can be called any time when an interrupt non-blocking transfer initiates to abort the transfer
early.
Parameters
Note
This API can be called when an interrupt non-blocking transfer initiates to abort the transfer early.
Parameters
Parameters
Parameters
Data Structures
• struct sai_dma_handle_t
SAI DMA transfer handle, users should not touch the content of the handle. More...
Typedefs
DMA Transactional
Data Fields
• dma_handle_t ∗ dmaHandle
DMA handler for SAI send.
• uint8_t bytesPerFrame
Bytes in a frame.
• uint8_t channel
Which Data channel SAI use.
• uint32_t state
SAI DMA transfer internal state.
• sai_dma_callback_t callback
Callback for users while transfer finish or error occured.
• void ∗ userData
User callback parameter.
• sai_transfer_t saiQueue [SAI_XFER_QUEUE_SIZE]
Transfer queue storing queued transfer.
• size_t transferSize [SAI_XFER_QUEUE_SIZE]
Data bytes need to transfer.
• volatile uint8_t queueUser
Index for user to queue transfer.
• volatile uint8_t queueDriver
Index for driver to get the transfer data and size.
This function initializes the SAI master DMA handle, which can be used for other SAI master transactional
APIs. Usually, for a specified SAI instance, call this API once to get the initialized handle.
Parameters
This function initializes the SAI slave DMA handle, which can be used for other SAI master transactional
APIs. Usually, for a specified SAI instance, call this API once to get the initialized handle.
Parameters
The audio format can be changed at run-time. This function configures the sample rate and audio data
format to be transferred. This function also sets the eDMA parameter according to the format.
Parameters
Return values
The audio format can be changed at run-time. This function configures the sample rate and audio data
format to be transferred. This function also sets eDMA parameter according to format.
Parameters
Return values
Parameters
Return values
Note
This interface returns immediately after transfer initiates. Call SAI_GetTransferStatus to poll the
transfer status to check whether the SAI transfer is finished.
Parameters
Return values
Parameters
Parameters
Parameters
Return values
Parameters
Return values
Data Structures
• struct sai_edma_handle_t
SAI DMA transfer handle, users should not touch the content of the handle. More...
Typedefs
eDMA Transactional
Data Fields
• edma_handle_t ∗ dmaHandle
DMA handler for SAI send.
• uint8_t nbytes
eDMA minor byte transfer count initially configured.
• uint8_t bytesPerFrame
Bytes in a frame.
• uint8_t channel
Which data channel.
• uint8_t count
The transfer data count in a DMA request.
• uint32_t state
Internal state for SAI eDMA transfer.
• sai_edma_callback_t callback
Callback for users while transfer finish or error occurs.
• void ∗ userData
User callback parameter.
• edma_tcd_t tcd [SAI_XFER_QUEUE_SIZE+1U]
TCD pool for eDMA transfer.
• sai_transfer_t saiQueue [SAI_XFER_QUEUE_SIZE]
Transfer queue storing queued transfer.
• size_t transferSize [SAI_XFER_QUEUE_SIZE]
Data bytes need to transfer.
• volatile uint8_t queueUser
Index for user to queue transfer.
• volatile uint8_t queueDriver
Index for driver to get the transfer data and size.
This function initializes the SAI master DMA handle, which can be used for other SAI master transactional
APIs. Usually, for a specified SAI instance, call this API once to get the initialized handle.
Parameters
This function initializes the SAI slave DMA handle, which can be used for other SAI master transactional
APIs. Usually, for a specified SAI instance, call this API once to get the initialized handle.
Parameters
The audio format can be changed at run-time. This function configures the sample rate and audio data for-
mat to be transferred. This function also sets the eDMA parameter according to formatting requirements.
Parameters
Return values
The audio format can be changed at run-time. This function configures the sample rate and audio data for-
mat to be transferred. This function also sets the eDMA parameter according to formatting requirements.
Parameters
Return values
Note
This interface returns immediately after the transfer initiates. Call SAI_GetTransferStatus to poll the
transfer status and check whether the SAI transfer is finished.
Parameters
Return values
Note
This interface returns immediately after the transfer initiates. Call the SAI_GetReceiveRemaining-
Bytes to poll the transfer status and check whether the SAI transfer is finished.
Parameters
Return values
Parameters
Parameters
Parameters
Return values
Parameters
Return values
Data Structures
• struct sim_uid_t
Unique ID. More...
Enumerations
• enum _sim_usb_volt_reg_enable_mode {
kSIM_UsbVoltRegEnable = SIM_SOPT1_USBREGEN_MASK,
kSIM_UsbVoltRegEnableInLowPower = SIM_SOPT1_USBVSTBY_MASK,
kSIM_UsbVoltRegEnableInStop = SIM_SOPT1_USBSSTBY_MASK,
kSIM_UsbVoltRegEnableInAllModes }
USB voltage regulator enable setting.
• enum _sim_flash_mode {
kSIM_FlashDisableInWait = SIM_FCFG1_FLASHDOZE_MASK,
kSIM_FlashDisable = SIM_FCFG1_FLASHDIS_MASK }
Flash enable mode.
Functions
• void SIM_SetUsbVoltRegulatorEnableMode (uint32_t mask)
Sets the USB voltage regulator setting.
• void SIM_GetUniqueId (sim_uid_t ∗uid)
Gets the unique identification register value.
• static void SIM_SetFlashMode (uint8_t mode)
Sets the flash enable mode.
Driver version
• #define FSL_SIM_DRIVER_VERSION (MAKE_VERSION(2, 0, 0))
Driver version 2.0.0.
Data Fields
• uint32_t MH
UIDMH.
• uint32_t ML
UIDML.
• uint32_t L
UIDL.
Enumerator
kSIM_UsbVoltRegEnable Enable voltage regulator.
kSIM_UsbVoltRegEnableInLowPower Enable voltage regulator in VLPR/VLPW modes.
kSIM_UsbVoltRegEnableInStop Enable voltage regulator in STOP/VLPS/LLS/VLLS modes.
kSIM_UsbVoltRegEnableInAllModes Enable voltage regulator in all power modes.
Enumerator
kSIM_FlashDisableInWait Disable flash in wait mode.
kSIM_FlashDisable Disable flash in normal mode.
This function configures whether the USB voltage regulator is enabled in normal RUN mode, STOP/-
VLPS/LLS/VLLS modes, and VLPR/VLPW modes. The configurations are passed in as mask value of
_sim_usb_volt_reg_enable_mode. For example, to enable USB voltage regulator in RUN/VLPR/VLPW
modes and disable in STOP/VLPS/LLS/VLLS mode, use:
SIM_SetUsbVoltRegulatorEnableMode(kSIM_UsbVoltRegEnable | kSIM_UsbVoltRegEnableInLow-
Power);
Parameters
Parameters
Parameters
SMC driver provides APIs to set MCU to different wait modes and stop modes. Pre and post functions are
used for setting the modes. The pre functions and post functions are used as follows.
1. Disable/enable the interrupt through PRIMASK. This is an example use case. The application sets
the wakeup interrupt and calls SMC function SMC_SetPowerModeStop to set the MCU to STOP
mode, but the wakeup interrupt happens so quickly that the ISR completes before the function S-
MC_SetPowerModeStop. As a result, the MCU enters the STOP mode and never is woken up by
the interrupt. In this use case, the application first disables the interrupt through PRIMASK, sets the
wakeup interrupt, and enters the STOP mode. After wakeup, enable the interrupt through PRIMAS-
K. The MCU can still be woken up by disabling the interrupt through PRIMASK. The pre and post
functions handle the PRIMASK.
2. Disable/enable the flash speculation. When entering stop modes, the flash speculation might be
interrupted. As a result, pre functions disable the flash speculation and post functions enable it.
SMC_PreEnterStopModes();
SMC_SetPowerModeStop(SMC, kSMC_PartialStop);
SMC_PostExitStopModes();
Data Structures
• struct smc_power_mode_vlls_config_t
SMC Very Low-Leakage Stop power mode configuration. More...
Enumerations
• enum smc_power_mode_protection_t {
kSMC_AllowPowerModeVlls = SMC_PMPROT_AVLLS_MASK,
kSMC_AllowPowerModeLls = SMC_PMPROT_ALLS_MASK,
kSMC_AllowPowerModeVlp = SMC_PMPROT_AVLP_MASK,
kSMC_AllowPowerModeAll }
Power Modes Protection.
• enum smc_power_state_t {
kSMC_PowerStateRun = 0x01U << 0U,
kSMC_PowerStateStop = 0x01U << 1U,
kSMC_PowerStateVlpr = 0x01U << 2U,
kSMC_PowerStateVlpw = 0x01U << 3U,
kSMC_PowerStateVlps = 0x01U << 4U,
kSMC_PowerStateLls = 0x01U << 5U,
kSMC_PowerStateVlls = 0x01U << 6U }
Power Modes in PMSTAT.
• enum smc_run_mode_t {
kSMC_RunNormal = 0U,
kSMC_RunVlpr = 2U }
Run mode definition.
• enum smc_stop_mode_t {
kSMC_StopNormal = 0U,
kSMC_StopVlps = 2U,
kSMC_StopLls = 3U,
kSMC_StopVlls = 4U }
Stop mode definition.
• enum smc_stop_submode_t {
kSMC_StopSub0 = 0U,
kSMC_StopSub1 = 1U,
kSMC_StopSub2 = 2U,
kSMC_StopSub3 = 3U }
VLLS/LLS stop sub mode definition.
• enum smc_partial_stop_option_t {
kSMC_PartialStop = 0U,
kSMC_PartialStop1 = 1U,
kSMC_PartialStop2 = 2U }
Partial STOP option.
• enum _smc_status { kStatus_SMC_StopAbort = MAKE_STATUS(kStatusGroup_POWER, 0) }
SMC configuration status.
Driver version
• #define FSL_SMC_DRIVER_VERSION (MAKE_VERSION(2, 0, 3))
SMC driver version 2.0.3.
Data Fields
• smc_stop_submode_t subMode
Very Low-leakage Stop sub-mode.
• bool enablePorDetectInVlls0
Enable Power on reset detect in VLLS mode.
Enumerator
kSMC_AllowPowerModeVlls Allow Very-low-leakage Stop Mode.
kSMC_AllowPowerModeLls Allow Low-leakage Stop Mode.
kSMC_AllowPowerModeVlp Allow Very-Low-power Mode.
kSMC_AllowPowerModeAll Allow all power mode.
Enumerator
kSMC_PowerStateRun 0000_0001 - Current power mode is RUN
kSMC_PowerStateStop 0000_0010 - Current power mode is STOP
kSMC_PowerStateVlpr 0000_0100 - Current power mode is VLPR
kSMC_PowerStateVlpw 0000_1000 - Current power mode is VLPW
kSMC_PowerStateVlps 0001_0000 - Current power mode is VLPS
kSMC_PowerStateLls 0010_0000 - Current power mode is LLS
kSMC_PowerStateVlls 0100_0000 - Current power mode is VLLS
Enumerator
kSMC_RunNormal Normal RUN mode.
kSMC_RunVlpr Very-low-power RUN mode.
Enumerator
kSMC_StopNormal Normal STOP mode.
kSMC_StopVlps Very-low-power STOP mode.
kSMC_StopLls Low-leakage Stop mode.
kSMC_StopVlls Very-low-leakage Stop mode.
Enumerator
kSMC_StopSub0 Stop submode 0, for VLLS0/LLS0.
kSMC_StopSub1 Stop submode 1, for VLLS1/LLS1.
kSMC_StopSub2 Stop submode 2, for VLLS2/LLS2.
kSMC_StopSub3 Stop submode 3, for VLLS3/LLS3.
Enumerator
kSMC_PartialStop STOP - Normal Stop mode.
kSMC_PartialStop1 Partial Stop with both system and bus clocks disabled.
kSMC_PartialStop2 Partial Stop with system clock disabled and bus clock enabled.
Enumerator
kStatus_SMC_StopAbort Entering Stop mode is abort.
This function configures the power mode protection settings for supported power modes in the specified
chip family. The available power modes are defined in the smc_power_mode_protection_t. This should
be done at an early system level initialization stage. See the reference manual for details. This register can
only write once after the power reset.
The allowed modes are passed as bit map. For example, to allow LLS and VLLS, use SMC_SetPower-
ModeProtection(kSMC_AllowPowerModeVlls | kSMC_AllowPowerModeVlps). To allow all modes, use
SMC_SetPowerModeProtection(kSMC_AllowPowerModeAll).
Parameters
This function returns the current power mode status. After the application switches the power mode, it
should always check the status to check whether it runs into the specified mode or not. The application
should check this mode before switching to a different mode. The system requires that only certain modes
can switch to other specific modes. See the reference manual for details and the smc_power_state_t for
information about the power status.
Parameters
Returns
Current power mode status.
This function should be called after wake up from STOP/VLPS/LLS/VLLS modes. It is used with SMC-
_PreEnterStopModes.
This function should be called after wake up from WAIT/VLPW modes. It is used with SMC_PreEnter-
WaitModes.
Parameters
Returns
SMC configuration error code.
Parameters
Returns
SMC configuration error code.
Parameters
Returns
SMC configuration error code.
Parameters
Returns
SMC configuration error code.
Parameters
Returns
SMC configuration error code.
Parameters
Returns
SMC configuration error code.
Parameters
Returns
SMC configuration error code.
Parameters
Returns
SMC configuration error code.
void main(void)
{
//...
SPI_MasterGetDefaultConfig(&masterConfig);
SPI_MasterInit(SPI0, &masterConfig);
SPI_MasterTransferCreateHandle(SPI0, &spiHandle, SPI_UserCallback, NULL);
// Prepare to send.
xfer.txData = sendData;
xfer.rxData = receiveBuff;
xfer.dataSize = BUFFER_LEN;
// Send out.
SPI_MasterTransferNonBlocking(SPI0, &spiHandle, &xfer);
// ...
}
void main(void)
{
//...
SPI_MasterGetDefaultConfig(&masterConfig);
SPI_MasterInit(SPI0, &masterConfig);
DMA_Init(DMA0);
// Prepares to send.
xfer.txData = sendData;
xfer.rxData = receiveBuff;
xfer.dataSize = BUFFER_LEN;
// Sends out.
SPI_MasterTransferDMA(SPI0, &spiHandle, &xfer);
// ...
}
Data Structures
• struct spi_master_config_t
SPI master user configure structure. More...
• struct spi_slave_config_t
SPI slave user configure structure. More...
• struct spi_transfer_t
SPI transfer structure. More...
• struct spi_master_handle_t
SPI transfer handle structure. More...
Macros
Typedefs
Enumerations
• enum _spi_status {
kStatus_SPI_Busy = MAKE_STATUS(kStatusGroup_SPI, 0),
kStatus_SPI_Idle = MAKE_STATUS(kStatusGroup_SPI, 1),
kStatus_SPI_Error = MAKE_STATUS(kStatusGroup_SPI, 2) }
Return status for the SPI driver.
• enum spi_clock_polarity_t {
kSPI_ClockPolarityActiveHigh = 0x0U,
kSPI_ClockPolarityActiveLow }
SPI clock polarity configuration.
• enum spi_clock_phase_t {
kSPI_ClockPhaseFirstEdge = 0x0U,
kSPI_ClockPhaseSecondEdge }
SPI clock phase configuration.
• enum spi_shift_direction_t {
kSPI_MsbFirst = 0x0U,
kSPI_LsbFirst }
kSPI_RxFifoThreeFourthsFull = 0,
kSPI_RxFifoOneHalfFull = 1 }
SPI RX FIFO watermark settings.
• enum _spi_dma_enable_t {
kSPI_TxDmaEnable = SPI_C2_TXDMAE_MASK,
kSPI_RxDmaEnable = SPI_C2_RXDMAE_MASK,
kSPI_DmaAllEnable = (SPI_C2_TXDMAE_MASK | SPI_C2_RXDMAE_MASK) }
SPI DMA source.
Driver version
Status
Interrupts
DMA Control
Bus Operations
Transactional
Data Fields
• bool enableMaster
Enable SPI at initialization time.
• bool enableStopInWaitMode
SPI stop in wait mode.
• spi_clock_polarity_t polarity
Clock polarity.
• spi_clock_phase_t phase
Clock phase.
• spi_shift_direction_t direction
MSB or LSB.
• spi_data_bitcount_mode_t dataMode
8bit or 16bit mode
• spi_txfifo_watermark_t txWatermark
Tx watermark settings.
• spi_rxfifo_watermark_t rxWatermark
Rx watermark settings.
• spi_ss_output_mode_t outputMode
SS pin setting.
• spi_pin_mode_t pinMode
SPI pin mode select.
• uint32_t baudRate_Bps
Baud Rate for SPI in Hz.
Data Fields
• bool enableSlave
Enable SPI at initialization time.
• bool enableStopInWaitMode
SPI stop in wait mode.
• spi_clock_polarity_t polarity
Clock polarity.
• spi_clock_phase_t phase
Clock phase.
• spi_shift_direction_t direction
MSB or LSB.
• spi_data_bitcount_mode_t dataMode
8bit or 16bit mode
• spi_txfifo_watermark_t txWatermark
Tx watermark settings.
• spi_rxfifo_watermark_t rxWatermark
Rx watermark settings.
Data Fields
• uint8_t ∗ txData
Send buffer.
• uint8_t ∗ rxData
Receive buffer.
• size_t dataSize
Transfer bytes.
• uint32_t flags
SPI control flag, useless to SPI.
Data Fields
• uint8_t ∗volatile txData
Transfer buffer.
• uint8_t ∗volatile rxData
Receive buffer.
• volatile size_t txRemainingBytes
Send data remaining in bytes.
• volatile size_t rxRemainingBytes
Receive data remaining in bytes.
• volatile uint32_t state
SPI internal state.
• size_t transferSize
Bytes to be transferred.
• uint8_t bytePerFrame
SPI mode, 2bytes or 1byte in a frame.
• uint8_t watermark
Watermark value for SPI transfer.
• spi_master_callback_t callback
SPI callback.
• void ∗ userData
Callback parameter.
Enumerator
kStatus_SPI_Busy SPI bus is busy.
kStatus_SPI_Idle SPI is idle.
kStatus_SPI_Error SPI error.
Enumerator
kSPI_ClockPolarityActiveHigh Active-high SPI clock (idles low).
kSPI_ClockPolarityActiveLow Active-low SPI clock (idles high).
Enumerator
kSPI_ClockPhaseFirstEdge First edge on SPSCK occurs at the middle of the first cycle of a data
transfer.
kSPI_ClockPhaseSecondEdge First edge on SPSCK occurs at the start of the first cycle of a data
transfer.
Enumerator
kSPI_MsbFirst Data transfers start with most significant bit.
kSPI_LsbFirst Data transfers start with least significant bit.
Enumerator
kSPI_SlaveSelectAsGpio Slave select pin configured as GPIO.
kSPI_SlaveSelectFaultInput Slave select pin configured for fault detection.
kSPI_SlaveSelectAutomaticOutput Slave select pin configured for automatic SPI output.
Enumerator
kSPI_PinModeNormal Pins operate in normal, single-direction mode.
kSPI_PinModeInput Bidirectional mode. Master: MOSI pin is input; Slave: MISO pin is input.
kSPI_PinModeOutput Bidirectional mode. Master: MOSI pin is output; Slave: MISO pin is output.
Enumerator
kSPI_8BitMode 8-bit data transmission mode
kSPI_16BitMode 16-bit data transmission mode
Enumerator
kSPI_RxFullAndModfInterruptEnable Receive buffer full (SPRF) and mode fault (MODF) inter-
rupt.
kSPI_TxEmptyInterruptEnable Transmit buffer empty interrupt.
kSPI_MatchInterruptEnable Match interrupt.
kSPI_RxFifoNearFullInterruptEnable Receive FIFO nearly full interrupt.
kSPI_TxFifoNearEmptyInterruptEnable Transmit FIFO nearly empty interrupt.
Enumerator
kSPI_RxBufferFullFlag Read buffer full flag.
kSPI_MatchFlag Match flag.
kSPI_TxBufferEmptyFlag Transmit buffer empty flag.
kSPI_ModeFaultFlag Mode fault flag.
kSPI_RxFifoNearFullFlag Rx FIFO near full.
Enumerator
kSPI_RxFifoFullClearInterrupt Receive FIFO full interrupt.
kSPI_TxFifoEmptyClearInterrupt Transmit FIFO empty interrupt.
kSPI_RxNearFullClearInterrupt Receive FIFO nearly full interrupt.
kSPI_TxNearEmptyClearInterrupt Transmit FIFO nearly empty interrupt.
Enumerator
kSPI_TxFifoOneFourthEmpty SPI tx watermark at 1/4 FIFO size.
kSPI_TxFifoOneHalfEmpty SPI tx watermark at 1/2 FIFO size.
Enumerator
kSPI_RxFifoThreeFourthsFull SPI rx watermark at 3/4 FIFO size.
kSPI_RxFifoOneHalfFull SPI rx watermark at 1/2 FIFO size.
Enumerator
kSPI_TxDmaEnable Tx DMA request source.
kSPI_RxDmaEnable Rx DMA request source.
kSPI_DmaAllEnable All DMA request source.
The purpose of this API is to get the configuration structure initialized for use in SPI_MasterInit(). User
may use the initialized structure unchanged in SPI_MasterInit(), or modify some fields of the structure
before calling SPI_MasterInit(). After calling this API, the master is ready to transfer. Example:
spi_master_config_t config;
SPI_MasterGetDefaultConfig(&config);
Parameters
The configuration structure can be filled by user from scratch, or be set with default values by SPI_Master-
GetDefaultConfig(). After calling this API, the slave is ready to transfer. Example
spi_master_config_t config = {
.baudRate_Bps = 400000,
...
};
SPI_MasterInit(SPI0, &config);
Parameters
The purpose of this API is to get the configuration structure initialized for use in SPI_SlaveInit(). Modify
some fields of the structure before calling SPI_SlaveInit(). Example:
spi_slave_config_t config;
SPI_SlaveGetDefaultConfig(&config);
Parameters
The configuration structure can be filled by user from scratch or be set with default values by SPI_Slave-
GetDefaultConfig(). After calling this API, the slave is ready to transfer. Example
spi_slave_config_t config = {
.polarity = kSPIClockPolarity_ActiveHigh;
.phase = kSPIClockPhase_FirstEdge;
.direction = kSPIMsbFirst;
...
};
SPI_MasterInit(SPI0, &config);
Parameters
Calling this API resets the SPI module, gates the SPI clock. The SPI module can’t work unless calling the
SPI_MasterInit/SPI_SlaveInit to initialize module.
Parameters
25.2.6.6 static void SPI_Enable ( SPI_Type ∗ base, bool enable ) [inline], [static]
Parameters
Parameters
Returns
SPI Status, use status flag to AND _spi_flags could get the related status.
Parameters
Parameters
Parameters
25.2.6.11 static void SPI_EnableDMA ( SPI_Type ∗ base, uint32_t mask, bool enable )
[inline], [static]
Parameters
This API is used to provide a transfer address for the SPI DMA transfer configuration.
Parameters
Returns
data register address
Parameters
The match data is a hardware comparison value. When the value received in the SPI receive data buffer
equals the hardware comparison value, the SPI Match Flag in the S register (S[SPMF]) sets. This can also
generate an interrupt if the enable bit sets.
Parameters
Parameters
Note
This function blocks via polling until all bytes have been sent.
Parameters
Parameters
Parameters
Returns
Data in the register.
This function initializes the SPI master handle which can be used for other SPI master transactional APIs.
Usually, for a specified SPI instance, call this API once to get the initialized handle.
Parameters
Parameters
Return values
Note
The API immediately returns after transfer initialization is finished. Call SPI_GetStatusIRQ() to get
the transfer status.
If SPI transfer data frame size is 16 bits, the transfer size cannot be an odd number.
Parameters
Return values
Parameters
Return values
Parameters
Parameters
This function initializes the SPI slave handle which can be used for other SPI slave transactional APIs.
Usually, for a specified SPI instance, call this API once to get the initialized handle.
Parameters
Parameters
Return values
Parameters
Return values
Parameters
Parameters
This section describes the programming interface of the SPI DMA driver.
Data Structures
• struct spi_dma_handle_t
SPI DMA transfer handle, users should not touch the content of the handle. More...
Typedefs
DMA Transactional
Data Fields
• bool txInProgress
Send transfer finished.
• bool rxInProgress
Receive transfer finished.
• dma_handle_t ∗ txHandle
DMA handler for SPI send.
• dma_handle_t ∗ rxHandle
DMA handler for SPI receive.
• uint8_t bytesPerFrame
Bytes in a frame for SPI tranfer.
• spi_dma_callback_t callback
Callback for SPI DMA transfer.
• void ∗ userData
User Data for SPI DMA callback.
• uint32_t state
Internal state of SPI DMA transfer.
• size_t transferSize
Bytes need to be transfer.
This function initializes the SPI master DMA handle which can be used for other SPI master transactional
APIs. Usually, for a specified SPI instance, user need only call this API once to get the initialized handle.
Parameters
Note
This interface returned immediately after transfer initiates, users should call SPI_GetTransferStatus
to poll the transfer status to check whether SPI transfer finished.
Parameters
Return values
Parameters
Parameters
Return values
This function initializes the SPI slave DMA handle which can be used for other SPI master transactional
APIs. Usually, for a specified SPI instance, user need only call this API once to get the initialized handle.
Parameters
Note
This interface returned immediately after transfer initiates, users should call SPI_GetTransferStatus
to poll the transfer status to check whether SPI transfer finished.
Parameters
Return values
Parameters
Parameters
Return values
This section describes the programming interface of the SPI FreeRTOS driver.
This function initializes the SPI module and related RTOS context.
Parameters
handle The RTOS SPI handle, the pointer to an allocated space for RTOS context.
base The pointer base address of the SPI instance to initialize.
masterConfig Configuration structure to set-up SPI in master mode.
srcClock_Hz Frequency of input clock of the SPI module.
Returns
status of the operation.
This function deinitializes the SPI module and related RTOS context.
Parameters
This function performs an SPI transfer according to data given in the transfer structure.
Parameters
Returns
status of the operation.
input signal.
The function TPM_SetupFault() sets up the properties for each fault, which is available only for certain
SoCs. The user can specify the fault polarity and whether to use a filter on a fault input. The overall fault
filter value and fault control mode are set up during initialization.
Provides functions to get and clear the TPM status.
Provides functions to enable/disable TPM interrupts and get current enabled interrupts.
Output the PWM signal on 2 TPM channels with different duty cycles. Periodically update the PWM
signal duty cycle.
int main(void)
{
bool brightnessUp = true; /* Indicates whether the LED is brighter or dimmer. */
tpm_config_t tpmInfo;
uint8_t updatedDutycycle = 0U;
tpm_chnl_pwm_signal_param_t tpmParam[2];
tpmParam[1].chnlNumber = (tpm_chnl_t)BOARD_SECOND_TPM_CHANNEL;
tpmParam[1].level = kTPM_LowTrue;
tpmParam[1].dutyCyclePercent = 0U;
TPM_GetDefaultConfig(&tpmInfo);
/* Initializes the TPM module. */
TPM_Init(BOARD_TPM_BASEADDR, &tpmInfo);
if (brightnessUp)
{
/* Increases a duty cycle until it reaches a limited value. */
if (++updatedDutycycle == 100U)
{
brightnessUp = false;
}
}
else
{
/* Decreases a duty cycle until it reaches a limited value. */
if (--updatedDutycycle == 0U)
{
brightnessUp = true;
}
}
/* Starts PWM mode with an updated duty cycle. */
TPM_UpdatePwmDutycycle(BOARD_TPM_BASEADDR, (
tpm_chnl_t)BOARD_FIRST_TPM_CHANNEL, kTPM_EdgeAlignedPwm,
updatedDutycycle);
TPM_UpdatePwmDutycycle(BOARD_TPM_BASEADDR, (
tpm_chnl_t)BOARD_SECOND_TPM_CHANNEL, kTPM_EdgeAlignedPwm,
updatedDutycycle);
}
}
Data Structures
• struct tpm_chnl_pwm_signal_param_t
Options to configure a TPM channel’s PWM signal. More...
• struct tpm_config_t
TPM config structure. More...
Enumerations
• enum tpm_chnl_t {
kTPM_Chnl_0 = 0U,
kTPM_Chnl_1,
kTPM_Chnl_2,
kTPM_Chnl_3,
kTPM_Chnl_4,
kTPM_Chnl_5,
kTPM_Chnl_6,
kTPM_Chnl_7 }
List of TPM channels.
• enum tpm_pwm_mode_t {
kTPM_EdgeAlignedPwm = 0U,
kTPM_CenterAlignedPwm }
TPM PWM operation modes.
• enum tpm_pwm_level_select_t {
kTPM_NoPwmSignal = 0U,
kTPM_LowTrue,
kTPM_HighTrue }
TPM PWM output pulse mode: high-true, low-true or no output.
• enum tpm_trigger_select_t
Trigger options available.
• enum tpm_output_compare_mode_t {
kTPM_NoOutputSignal = (1U << TPM_CnSC_MSA_SHIFT),
kTPM_ToggleOnMatch = ((1U << TPM_CnSC_MSA_SHIFT) | (1U << TPM_CnSC_ELSA_S-
HIFT)),
kTPM_ClearOnMatch = ((1U << TPM_CnSC_MSA_SHIFT) | (2U << TPM_CnSC_ELSA_SH-
IFT)),
kTPM_SetOnMatch = ((1U << TPM_CnSC_MSA_SHIFT) | (3U << TPM_CnSC_ELSA_SHIF-
T)),
kTPM_HighPulseOutput = ((3U << TPM_CnSC_MSA_SHIFT) | (1U << TPM_CnSC_ELSA_-
SHIFT)),
kTPM_LowPulseOutput = ((3U << TPM_CnSC_MSA_SHIFT) | (2U << TPM_CnSC_ELSA_S-
HIFT)) }
TPM output compare modes.
• enum tpm_input_capture_edge_t {
kTPM_RisingEdge = (1U << TPM_CnSC_ELSA_SHIFT),
kTPM_FallingEdge = (2U << TPM_CnSC_ELSA_SHIFT),
kTPM_RiseAndFallEdge = (3U << TPM_CnSC_ELSA_SHIFT) }
TPM input capture edge.
• enum tpm_clock_source_t {
kTPM_SystemClock = 1U,
kTPM_ExternalClock }
TPM clock source selection.
• enum tpm_clock_prescale_t {
kTPM_Prescale_Divide_1 = 0U,
kTPM_Prescale_Divide_2,
kTPM_Prescale_Divide_4,
kTPM_Prescale_Divide_8,
kTPM_Prescale_Divide_16,
kTPM_Prescale_Divide_32,
kTPM_Prescale_Divide_64,
kTPM_Prescale_Divide_128 }
TPM prescale value selection for the clock source.
• enum tpm_interrupt_enable_t {
kTPM_Chnl0InterruptEnable = (1U << 0),
kTPM_Chnl1InterruptEnable = (1U << 1),
kTPM_Chnl2InterruptEnable = (1U << 2),
kTPM_Chnl3InterruptEnable = (1U << 3),
kTPM_Chnl4InterruptEnable = (1U << 4),
kTPM_Chnl5InterruptEnable = (1U << 5),
kTPM_Chnl6InterruptEnable = (1U << 6),
kTPM_Chnl7InterruptEnable = (1U << 7),
kTPM_TimeOverflowInterruptEnable = (1U << 8) }
List of TPM interrupts.
• enum tpm_status_flags_t {
kTPM_Chnl0Flag = (1U << 0),
kTPM_Chnl1Flag = (1U << 1),
kTPM_Chnl2Flag = (1U << 2),
kTPM_Chnl3Flag = (1U << 3),
kTPM_Chnl4Flag = (1U << 4),
kTPM_Chnl5Flag = (1U << 5),
kTPM_Chnl6Flag = (1U << 6),
kTPM_Chnl7Flag = (1U << 7),
kTPM_TimeOverflowFlag = (1U << 8) }
List of TPM flags.
Driver version
• #define FSL_TPM_DRIVER_VERSION (MAKE_VERSION(2, 0, 2))
Version 2.0.2.
Interrupt Interface
• void TPM_EnableInterrupts (TPM_Type ∗base, uint32_t mask)
Enables the selected TPM interrupts.
• void TPM_DisableInterrupts (TPM_Type ∗base, uint32_t mask)
Disables the selected TPM interrupts.
• uint32_t TPM_GetEnabledInterrupts (TPM_Type ∗base)
Gets the enabled TPM interrupts.
Status Interface
• static uint32_t TPM_GetStatusFlags (TPM_Type ∗base)
Gets the TPM status flags.
• static void TPM_ClearStatusFlags (TPM_Type ∗base, uint32_t mask)
Clears the TPM status flags.
Data Fields
• tpm_chnl_t chnlNumber
TPM channel to configure.
• tpm_pwm_level_select_t level
PWM output active level select.
• uint8_t dutyCyclePercent
PWM pulse width, value should be between 0 to 100 0=inactive signal(0% duty cycle)...
In combined mode (available in some SoC’s, this represents the channel pair number
This structure holds the configuration settings for the TPM peripheral. To initialize this structure to rea-
sonable defaults, call the TPM_GetDefaultConfig() function and pass a pointer to your config structure
instance.
The config struct can be made const so it resides in flash
Data Fields
• tpm_clock_prescale_t prescale
Select TPM clock prescale value.
• bool useGlobalTimeBase
Note
Actual number of available channels is SoC dependent
Enumerator
kTPM_Chnl_0 TPM channel number 0.
kTPM_Chnl_1 TPM channel number 1.
kTPM_Chnl_2 TPM channel number 2.
kTPM_Chnl_3 TPM channel number 3.
kTPM_Chnl_4 TPM channel number 4.
kTPM_Chnl_5 TPM channel number 5.
kTPM_Chnl_6 TPM channel number 6.
kTPM_Chnl_7 TPM channel number 7.
Enumerator
kTPM_EdgeAlignedPwm Edge aligned PWM.
kTPM_CenterAlignedPwm Center aligned PWM.
Enumerator
kTPM_NoPwmSignal No PWM output on pin.
This is used for both internal & external trigger sources (external option available in certain SoC’s)
Note
The actual trigger options available is SoC-specific.
Enumerator
kTPM_NoOutputSignal No channel output when counter reaches CnV.
kTPM_ToggleOnMatch Toggle output.
kTPM_ClearOnMatch Clear output.
kTPM_SetOnMatch Set output.
kTPM_HighPulseOutput Pulse output high.
kTPM_LowPulseOutput Pulse output low.
Enumerator
kTPM_RisingEdge Capture on rising edge only.
kTPM_FallingEdge Capture on falling edge only.
kTPM_RiseAndFallEdge Capture on rising or falling edge.
Enumerator
kTPM_SystemClock System clock.
kTPM_ExternalClock External clock.
Enumerator
kTPM_Prescale_Divide_1 Divide by 1.
kTPM_Prescale_Divide_2 Divide by 2.
kTPM_Prescale_Divide_4 Divide by 4.
kTPM_Prescale_Divide_8 Divide by 8.
kTPM_Prescale_Divide_16 Divide by 16.
kTPM_Prescale_Divide_32 Divide by 32.
kTPM_Prescale_Divide_64 Divide by 64.
kTPM_Prescale_Divide_128 Divide by 128.
Enumerator
kTPM_Chnl0InterruptEnable Channel 0 interrupt.
kTPM_Chnl1InterruptEnable Channel 1 interrupt.
kTPM_Chnl2InterruptEnable Channel 2 interrupt.
kTPM_Chnl3InterruptEnable Channel 3 interrupt.
kTPM_Chnl4InterruptEnable Channel 4 interrupt.
kTPM_Chnl5InterruptEnable Channel 5 interrupt.
kTPM_Chnl6InterruptEnable Channel 6 interrupt.
kTPM_Chnl7InterruptEnable Channel 7 interrupt.
kTPM_TimeOverflowInterruptEnable Time overflow interrupt.
Enumerator
kTPM_Chnl0Flag Channel 0 flag.
kTPM_Chnl1Flag Channel 1 flag.
kTPM_Chnl2Flag Channel 2 flag.
kTPM_Chnl3Flag Channel 3 flag.
kTPM_Chnl4Flag Channel 4 flag.
kTPM_Chnl5Flag Channel 5 flag.
kTPM_Chnl6Flag Channel 6 flag.
kTPM_Chnl7Flag Channel 7 flag.
kTPM_TimeOverflowFlag Time overflow flag.
Note
This API should be called at the beginning of the application using the TPM driver.
Parameters
Parameters
* config->prescale = kTPM_Prescale_Divide_1;
* config->useGlobalTimeBase = false;
* config->dozeEnable = false;
* config->dbgMode = false;
* config->enableReloadOnTrigger = false;
* config->enableStopOnOverflow = false;
* config->enableStartOnTrigger = false;
*#if FSL_FEATURE_TPM_HAS_PAUSE_COUNTER_ON_TRIGGER
* config->enablePauseOnTrigger = false;
*#endif
* config->triggerSelect = kTPM_Trigger_Select_0;
*#if FSL_FEATURE_TPM_HAS_EXTERNAL_TRIGGER_SELECTION
* config->triggerSource = kTPM_TriggerSource_External;
*#endif
*
Parameters
User calls this function to configure the PWM signals period, mode, dutycycle and edge. Use this function
to configure all the TPM channels that will be used to output a PWM signal
Parameters
Returns
kStatus_Success if the PWM setup was successful, kStatus_Error on failure
Parameters
Parameters
When the edge specified in the captureMode argument occurs on the channel, the TPM counter is captured
into the CnV register. The user has to read the CnV register separately to get this value.
Parameters
When the TPM counter matches the value of compareVal argument (this is written into CnV reg), the
channel output is changed based on what is specified in the compareMode argument.
Parameters
Parameters
Parameters
Parameters
Returns
The enabled interrupts. This is the logical OR of members of the enumeration tpm_interrupt_enable-
_t
Parameters
Returns
The status flags. This is the logical OR of members of the enumeration tpm_status_flags_t
Parameters
Timers counts from 0 until it equals the count value set here. The count value is written to the MOD
register.
Note
1. This API allows the user to use the TPM module as a timer. Do not mix usage of this API with
TPM’s PWM setup API’s.
2. Call the utility macros provided in the fsl_common.h to convert usec or msec to ticks.
Parameters
This function returns the real-time timer counting value in a range from 0 to a timer period.
Note
Call the utility macros provided in the fsl_common.h to convert ticks to usec or msec.
Parameters
Returns
The current counter value in ticks
Parameters
Parameters
The MCUXpresso SDK provides driver for the Touch Sensing Input (TSI) module of MCUXpresso SDK
devices.
TSI_EnableSoftwareTriggerScan(TSI0);
TSI_EnableModule(TSI0);
while(1)
{
TSI_StartSoftwareTrigger(TSI0);
TSI_GetCounter(TSI0);
}
Data Structures
• struct tsi_calibration_data_t
TSI calibration data storage. More...
• struct tsi_config_t
TSI configuration structure. More...
Macros
Enumerations
• enum tsi_n_consecutive_scans_t {
kTSI_ConsecutiveScansNumber_1time = 0U,
kTSI_ConsecutiveScansNumber_2time = 1U,
kTSI_ConsecutiveScansNumber_3time = 2U,
kTSI_ConsecutiveScansNumber_4time = 3U,
kTSI_ConsecutiveScansNumber_5time = 4U,
kTSI_ConsecutiveScansNumber_6time = 5U,
kTSI_ConsecutiveScansNumber_7time = 6U,
kTSI_ConsecutiveScansNumber_8time = 7U,
kTSI_ConsecutiveScansNumber_9time = 8U,
kTSI_ConsecutiveScansNumber_10time = 9U,
kTSI_ConsecutiveScansNumber_11time = 10U,
kTSI_ConsecutiveScansNumber_12time = 11U,
kTSI_ConsecutiveScansNumber_13time = 12U,
kTSI_ConsecutiveScansNumber_14time = 13U,
kTSI_ConsecutiveScansNumber_15time = 14U,
kTSI_ConsecutiveScansNumber_16time = 15U,
kTSI_ConsecutiveScansNumber_17time = 16U,
kTSI_ConsecutiveScansNumber_18time = 17U,
kTSI_ConsecutiveScansNumber_19time = 18U,
kTSI_ConsecutiveScansNumber_20time = 19U,
kTSI_ConsecutiveScansNumber_21time = 20U,
kTSI_ConsecutiveScansNumber_22time = 21U,
kTSI_ConsecutiveScansNumber_23time = 22U,
kTSI_ConsecutiveScansNumber_24time = 23U,
kTSI_ConsecutiveScansNumber_25time = 24U,
kTSI_ConsecutiveScansNumber_26time = 25U,
kTSI_ConsecutiveScansNumber_27time = 26U,
kTSI_ConsecutiveScansNumber_28time = 27U,
kTSI_ConsecutiveScansNumber_29time = 28U,
kTSI_ConsecutiveScansNumber_30time = 29U,
kTSI_ConsecutiveScansNumber_31time = 30U,
kTSI_ConsecutiveScansNumber_32time = 31U }
TSI number of scan intervals for each electrode.
• enum tsi_electrode_osc_prescaler_t {
kTSI_ElecOscPrescaler_1div = 0U,
kTSI_ElecOscPrescaler_2div = 1U,
kTSI_ElecOscPrescaler_4div = 2U,
kTSI_ElecOscPrescaler_8div = 3U,
kTSI_ElecOscPrescaler_16div = 4U,
kTSI_ElecOscPrescaler_32div = 5U,
kTSI_ElecOscPrescaler_64div = 6U,
kTSI_ElecOscPrescaler_128div = 7U }
Functions
Driver version
Data Fields
• uint16_t calibratedData [FSL_FEATURE_TSI_CHANNEL_COUNT]
TSI calibration data storage buffer.
This structure contains the settings for the most common TSI configurations including the TSI module
charge currents, number of scans, thresholds, and so on.
Data Fields
• uint16_t thresh
High threshold.
• uint16_t thresl
Low threshold.
• tsi_electrode_osc_prescaler_t prescaler
Prescaler.
• tsi_external_osc_charge_current_t extchrg
Electrode charge current.
• tsi_reference_osc_charge_current_t refchrg
Reference charge current.
• tsi_n_consecutive_scans_t nscn
Number of scans.
• tsi_analog_mode_t mode
TSI mode of operation.
• tsi_osc_voltage_rails_t dvolt
Oscillator’s voltage rails.
• tsi_series_resistor_t resistor
Series resistance value.
• tsi_filter_bits_t filter
Noise mode filter bits.
These constants define the tsi number of consecutive scans in a TSI instance for each electrode.
Enumerator
kTSI_ConsecutiveScansNumber_1time Once per electrode.
kTSI_ConsecutiveScansNumber_2time Twice per electrode.
kTSI_ConsecutiveScansNumber_3time 3 times consecutive scan
kTSI_ConsecutiveScansNumber_4time 4 times consecutive scan
kTSI_ConsecutiveScansNumber_5time 5 times consecutive scan
kTSI_ConsecutiveScansNumber_6time 6 times consecutive scan
kTSI_ConsecutiveScansNumber_7time 7 times consecutive scan
kTSI_ConsecutiveScansNumber_8time 8 times consecutive scan
kTSI_ConsecutiveScansNumber_9time 9 times consecutive scan
kTSI_ConsecutiveScansNumber_10time 10 times consecutive scan
These constants define the TSI electrode oscillator prescaler in a TSI instance.
Enumerator
kTSI_ElecOscPrescaler_1div Electrode oscillator frequency divided by 1.
kTSI_ElecOscPrescaler_2div Electrode oscillator frequency divided by 2.
kTSI_ElecOscPrescaler_4div Electrode oscillator frequency divided by 4.
kTSI_ElecOscPrescaler_8div Electrode oscillator frequency divided by 8.
kTSI_ElecOscPrescaler_16div Electrode oscillator frequency divided by 16.
kTSI_ElecOscPrescaler_32div Electrode oscillator frequency divided by 32.
kTSI_ElecOscPrescaler_64div Electrode oscillator frequency divided by 64.
kTSI_ElecOscPrescaler_128div Electrode oscillator frequency divided by 128.
These constants define the TSI Reference oscillator charge current select in a TSI (REFCHRG) instance.
Enumerator
kTSI_RefOscChargeCurrent_500nA Reference oscillator charge current is 500 µA.
kTSI_RefOscChargeCurrent_1uA Reference oscillator charge current is 1 µA.
kTSI_RefOscChargeCurrent_2uA Reference oscillator charge current is 2 µA.
kTSI_RefOscChargeCurrent_4uA Reference oscillator charge current is 4 µA.
kTSI_RefOscChargeCurrent_8uA Reference oscillator charge current is 8 µA.
kTSI_RefOscChargeCurrent_16uA Reference oscillator charge current is 16 µA.
kTSI_RefOscChargeCurrent_32uA Reference oscillator charge current is 32 µA.
kTSI_RefOscChargeCurrent_64uA Reference oscillator charge current is 64 µA.
Enumerator
kTSI_OscVolRailsOption_0 DVOLT value option 0, the value may differ on different platforms.
kTSI_OscVolRailsOption_1 DVOLT value option 1, the value may differ on different platforms.
kTSI_OscVolRailsOption_2 DVOLT value option 2, the value may differ on different platforms.
kTSI_OscVolRailsOption_3 DVOLT value option 3, the value may differ on different platforms.
These bits indicate the electrode oscillator charge and discharge current value in TSI (EXTCHRG) in-
stance.
Enumerator
kTSI_ExtOscChargeCurrent_500nA External oscillator charge current is 500 µA.
kTSI_ExtOscChargeCurrent_1uA External oscillator charge current is 1 µA.
kTSI_ExtOscChargeCurrent_2uA External oscillator charge current is 2 µA.
kTSI_ExtOscChargeCurrent_4uA External oscillator charge current is 4 µA.
These bits indicate the electrode RS series resistance for the noise mode in TSI (EXTCHRG) instance.
Enumerator
kTSI_SeriesResistance_32k Series Resistance is 32 kilo ohms.
kTSI_SeriesResistance_187k Series Resistance is 18 7 kilo ohms.
These bits indicate the count of the filter bits in TSI noise mode EXTCHRG[2:1] bits
Enumerator
kTSI_FilterBits_3 3 filter bits, 8 peaks increments the cnt+1
kTSI_FilterBits_2 2 filter bits, 4 peaks increments the cnt+1
kTSI_FilterBits_1 1 filter bits, 2 peaks increments the cnt+1
kTSI_FilterBits_0 no filter bits,1 peak increments the cnt+1
Enumerator
kTSI_EndOfScanFlag End-Of-Scan flag.
kTSI_OutOfRangeFlag Out-Of-Range flag.
Enumerator
kTSI_GlobalInterruptEnable TSI module global interrupt.
kTSI_OutOfRangeInterruptEnable Out-Of-Range interrupt.
kTSI_EndOfScanInterruptEnable End-Of-Scan interrupt.
Initializes the peripheral to the targeted state specified by parameter configuration, such as sets prescalers,
number of scans, clocks, delta voltage series resistor, filter bits, reference, and electrode charge current
and threshold.
Parameters
Returns
none
Returns
none
This interface sets userConfig structure to a default value. The configuration structure only includes the
settings for the whole TSI. The user configure is set to these values:
userConfig->prescaler = kTSI_ElecOscPrescaler_2div;
userConfig->extchrg = kTSI_ExtOscChargeCurrent_500nA;
userConfig->refchrg = kTSI_RefOscChargeCurrent_4uA;
userConfig->nscn = kTSI_ConsecutiveScansNumber_10time;
userConfig->mode = kTSI_AnalogModeSel_Capacitive;
userConfig->dvolt = kTSI_OscVolRailsOption_0;
userConfig->thresh = 0U;
userConfig->thresl = 0U;
Parameters
This interface sets userConfig structure to a default value. The configuration structure only includes the
settings for the whole TSI. The user configure is set to these values:
userConfig->prescaler = kTSI_ElecOscPrescaler_2div;
userConfig->extchrg = kTSI_ExtOscChargeCurrent_500nA;
userConfig->refchrg = kTSI_RefOscChargeCurrent_4uA;
userConfig->nscn = kTSI_ConsecutiveScansNumber_10time;
userConfig->mode = kTSI_AnalogModeSel_Capacitive;
userConfig->dvolt = kTSI_OscVolRailsOption_0;
userConfig->thresh = 400U;
userConfig->thresl = 0U;
Parameters
Calibrates the peripheral to fetch the initial counter value of the enabled electrodes. This API is mostly
used at initial application setup. Call this function after the TSI_Init API and use the calibrated counter
values to set up applications (such as to determine under which counter value we can confirm a touch event
occurs).
Parameters
Returns
none
Parameters
Parameters
Returns
The mask of these status flags combination.
This function clears the TSI interrupt flag, automatically cleared flags can’t be cleared by this function.
Parameters
Parameters
Returns
Scan trigger mode.
Parameters
Returns
True - scan is in progress. False - scan is not in progress.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
uint8_t Channel number 0 ... 15.
Parameters
Returns
none.
Parameters
Returns
Accumulated scan counter value ticked by the reference clock.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
Value of the GENCS[MODE] bit-fields.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
Parameters
Returns
none.
The MCUXpresso SDK provides a peripheral driver for the Universal Asynchronous Receiver/Transmitter
(UART) module of MCUXpresso SDK devices.
The UART driver includes functional APIs and transactional APIs.
Functional APIs are used for UART initialization/configuration/operation for optimization/customization
purpose. Using the functional API requires the knowledge of the UART peripheral and how to organize
functional APIs to meet the application requirements. All functional APIs use the peripheral base address
as the first parameter. UART functional operation groups provide the functional API set.
Transactional APIs can be used to enable the peripheral quickly and in the application if the code size
and performance of transactional APIs can satisfy the requirements. If the code size and performance are
critical requirements, see the transactional API implementation and write custom code. All transactional
APIs use the uart_handle_t as the second parameter. Initialize the handle by calling the UART_Transfer-
CreateHandle() API.
Transactional APIs support asynchronous transfer, which means that the functions UART_TransferSend-
NonBlocking() and UART_TransferReceiveNonBlocking() set up an interrupt for data transfer. When the
transfer completes, the upper layer is notified through a callback function with the kStatus_UART_TxIdle
and kStatus_UART_RxIdle.
Transactional receive APIs support the ring buffer. Prepare the memory for the ring buffer and pass in the
start address and size while calling the UART_TransferCreateHandle(). If passing NULL, the ring buffer
feature is disabled. When the ring buffer is enabled, the received data is saved to the ring buffer in the
background. The UART_TransferReceiveNonBlocking() function first gets data from the ring buffer. If
the ring buffer does not have enough data, the function first returns the data in the ring buffer and then
saves the received data to user memory. When all data is received, the upper layer is informed through a
callback with the kStatus_UART_RxIdle.
If the receive ring buffer is full, the upper layer is informed through a callback with the kStatus_UART-
_RxRingBufferOverrun. In the callback function, the upper layer reads data out from the ring buffer. If
not, existing data is overwritten by the new data.
The ring buffer size is specified when creating the handle. Note that one byte is reserved for the ring buffer
maintenance. When creating handle using the following code.
In this example, the buffer size is 32, but only 31 bytes are used for saving data.
UART_GetDefaultConfig(&user_config);
user_config.baudRate_Bps = 115200U;
user_config.enableTx = true;
user_config.enableRx = true;
UART_Init(UART1,&user_config,120000000U);
while(1)
{
UART_ReadBlocking(UART1, &ch, 1);
UART_WriteBlocking(UART1, &ch, 1);
}
if (kStatus_UART_TxIdle == status)
{
txFinished = true;
}
if (kStatus_UART_RxIdle == status)
{
rxFinished = true;
}
}
void main(void)
{
//...
UART_GetDefaultConfig(&user_config);
user_config.baudRate_Bps = 115200U;
user_config.enableTx = true;
user_config.enableRx = true;
// Prepare to send.
sendXfer.data = sendData
sendXfer.dataSize = sizeof(sendData)/sizeof(sendData[0]);
txFinished = false;
// Send out.
UART_TransferSendNonBlocking(&g_uartHandle, &g_uartHandle, &sendXfer);
// Prepare to receive.
receiveXfer.data = receiveData;
receiveXfer.dataSize = sizeof(receiveData)/sizeof(receiveData[0]);
rxFinished = false;
// Receive.
UART_TransferReceiveNonBlocking(&g_uartHandle, &g_uartHandle, &
receiveXfer);
// ...
}
uart_handle_t g_uartHandle;
uart_config_t user_config;
uart_transfer_t sendXfer;
uart_transfer_t receiveXfer;
volatile bool txFinished;
volatile bool rxFinished;
uint8_t receiveData[RX_DATA_SIZE];
uint8_t ringBuffer[RING_BUFFER_SIZE];
if (kStatus_UART_RxIdle == status)
{
rxFinished = true;
}
}
void main(void)
{
size_t bytesRead;
//...
UART_GetDefaultConfig(&user_config);
user_config.baudRate_Bps = 115200U;
user_config.enableTx = true;
user_config.enableRx = true;
// Prepare to receive.
receiveXfer.data = receiveData;
receiveXfer.dataSize = RX_DATA_SIZE;
rxFinished = false;
// Receive.
UART_TransferReceiveNonBlocking(UART1, &g_uartHandle, &receiveXfer);
;
}
else
{
if (bytesRead) /* Received some data, process first. */
{
;
}
// ...
}
if (kStatus_UART_TxIdle == status)
{
txFinished = true;
}
if (kStatus_UART_RxIdle == status)
{
rxFinished = true;
}
}
void main(void)
{
//...
UART_GetDefaultConfig(&user_config);
user_config.baudRate_Bps = 115200U;
user_config.enableTx = true;
user_config.enableRx = true;
DMA_Init(DMA0);
// Prepare to send.
sendXfer.data = sendData
sendXfer.dataSize = sizeof(sendData)/sizeof(sendData[0]);
txFinished = false;
// Send out.
UART_TransferSendDMA(UART1, &g_uartHandle, &sendXfer);
// Prepare to receive.
receiveXfer.data = receiveData;
receiveXfer.dataSize = sizeof(receiveData)/sizeof(receiveData[0]);
rxFinished = false;
// Receive.
UART_TransferReceiveDMA(UART1, &g_uartHandle, &receiveXfer);
// ...
}
Data Structures
• struct uart_config_t
UART configuration structure. More...
• struct uart_transfer_t
UART transfer structure. More...
• struct uart_handle_t
UART handle structure. More...
Typedefs
Enumerations
• enum _uart_status {
kStatus_UART_TxBusy = MAKE_STATUS(kStatusGroup_UART, 0),
kStatus_UART_RxBusy = MAKE_STATUS(kStatusGroup_UART, 1),
kStatus_UART_TxIdle = MAKE_STATUS(kStatusGroup_UART, 2),
kStatus_UART_RxIdle = MAKE_STATUS(kStatusGroup_UART, 3),
kStatus_UART_TxWatermarkTooLarge = MAKE_STATUS(kStatusGroup_UART, 4),
kStatus_UART_RxWatermarkTooLarge = MAKE_STATUS(kStatusGroup_UART, 5),
kStatus_UART_FlagCannotClearManually,
kStatus_UART_Error = MAKE_STATUS(kStatusGroup_UART, 7),
kStatus_UART_RxRingBufferOverrun = MAKE_STATUS(kStatusGroup_UART, 8),
kStatus_UART_RxHardwareOverrun = MAKE_STATUS(kStatusGroup_UART, 9),
kStatus_UART_NoiseError = MAKE_STATUS(kStatusGroup_UART, 10),
kStatus_UART_FramingError = MAKE_STATUS(kStatusGroup_UART, 11),
kStatus_UART_ParityError = MAKE_STATUS(kStatusGroup_UART, 12),
kStatus_UART_BaudrateNotSupport }
Error codes for the UART driver.
• enum uart_parity_mode_t {
kUART_ParityDisabled = 0x0U,
kUART_ParityEven = 0x2U,
kUART_ParityOdd = 0x3U }
UART parity mode.
• enum uart_stop_bit_count_t {
kUART_OneStopBit = 0U,
kUART_TwoStopBit = 1U }
UART stop bit count.
• enum _uart_interrupt_enable {
kUART_LinBreakInterruptEnable = (UART_BDH_LBKDIE_MASK),
kUART_RxActiveEdgeInterruptEnable = (UART_BDH_RXEDGIE_MASK),
kUART_TxDataRegEmptyInterruptEnable = (UART_C2_TIE_MASK << 8),
kUART_TransmissionCompleteInterruptEnable = (UART_C2_TCIE_MASK << 8),
kUART_RxDataRegFullInterruptEnable = (UART_C2_RIE_MASK << 8),
kUART_IdleLineInterruptEnable = (UART_C2_ILIE_MASK << 8),
kUART_RxOverrunInterruptEnable = (UART_C3_ORIE_MASK << 16),
kUART_NoiseErrorInterruptEnable = (UART_C3_NEIE_MASK << 16),
kUART_FramingErrorInterruptEnable = (UART_C3_FEIE_MASK << 16),
kUART_ParityErrorInterruptEnable = (UART_C3_PEIE_MASK << 16) }
UART interrupt configuration structure, default settings all disabled.
• enum _uart_flags {
kUART_TxDataRegEmptyFlag = (UART_S1_TDRE_MASK),
kUART_TransmissionCompleteFlag = (UART_S1_TC_MASK),
kUART_RxDataRegFullFlag = (UART_S1_RDRF_MASK),
kUART_IdleLineFlag = (UART_S1_IDLE_MASK),
kUART_RxOverrunFlag = (UART_S1_OR_MASK),
kUART_NoiseErrorFlag = (UART_S1_NF_MASK),
kUART_FramingErrorFlag = (UART_S1_FE_MASK),
kUART_ParityErrorFlag = (UART_S1_PF_MASK),
kUART_LinBreakFlag,
kUART_RxActiveEdgeFlag,
kUART_RxActiveFlag }
UART status flags.
Driver version
Status
Interrupts
DMA Control
Bus Operations
Transactional
Data Fields
• uint32_t baudRate_Bps
UART baud rate.
• uart_parity_mode_t parityMode
Parity mode, disabled (default), even, odd.
• uart_stop_bit_count_t stopBitCount
Number of stop bits, 1 stop bit (default) or 2 stop bits.
• bool enableTx
Enable TX.
• bool enableRx
Enable RX.
Data Fields
• uint8_t ∗ data
The buffer of data to be transfer.
• size_t dataSize
The byte count to be transfer.
Data Fields
• uint8_t ∗volatile txData
Address of remaining data to send.
• volatile size_t txDataSize
Size of the remaining data to send.
• size_t txDataSizeAll
Size of the data to send out.
• uint8_t ∗volatile rxData
Address of remaining data to receive.
• volatile size_t rxDataSize
Size of the remaining data to receive.
• size_t rxDataSizeAll
Size of the data to receive.
• uint8_t ∗ rxRingBuffer
Start address of the receiver ring buffer.
• size_t rxRingBufferSize
Size of the ring buffer.
• volatile uint16_t rxRingBufferHead
Index for the driver to store received data into ring buffer.
• volatile uint16_t rxRingBufferTail
Index for the user to get data from the ring buffer.
• uart_transfer_callback_t callback
Callback function.
• void ∗ userData
UART callback function parameter.
• volatile uint8_t txState
TX transfer state.
• volatile uint8_t rxState
RX transfer state.
Enumerator
kStatus_UART_TxBusy Transmitter is busy.
kStatus_UART_RxBusy Receiver is busy.
kStatus_UART_TxIdle UART transmitter is idle.
kStatus_UART_RxIdle UART receiver is idle.
kStatus_UART_TxWatermarkTooLarge TX FIFO watermark too large.
Enumerator
kUART_ParityDisabled Parity disabled.
kUART_ParityEven Parity enabled, type even, bit setting: PE|PT = 10.
kUART_ParityOdd Parity enabled, type odd, bit setting: PE|PT = 11.
Enumerator
kUART_OneStopBit One stop bit.
kUART_TwoStopBit Two stop bits.
This structure contains the settings for all of the UART interrupt configurations.
Enumerator
kUART_LinBreakInterruptEnable LIN break detect interrupt.
kUART_RxActiveEdgeInterruptEnable RX active edge interrupt.
kUART_TxDataRegEmptyInterruptEnable Transmit data register empty interrupt.
kUART_TransmissionCompleteInterruptEnable Transmission complete interrupt.
kUART_RxDataRegFullInterruptEnable Receiver data register full interrupt.
kUART_IdleLineInterruptEnable Idle line interrupt.
kUART_RxOverrunInterruptEnable Receiver overrun interrupt.
kUART_NoiseErrorInterruptEnable Noise error flag interrupt.
kUART_FramingErrorInterruptEnable Framing error flag interrupt.
kUART_ParityErrorInterruptEnable Parity error flag interrupt.
This provides constants for the UART status flags for use in the UART functions.
Enumerator
kUART_TxDataRegEmptyFlag TX data register empty flag.
kUART_TransmissionCompleteFlag Transmission complete flag.
kUART_RxDataRegFullFlag RX data register full flag.
kUART_IdleLineFlag Idle line detect flag.
kUART_RxOverrunFlag RX overrun flag.
kUART_NoiseErrorFlag RX takes 3 samples of each received bit. If any of these samples differ,
noise flag sets
kUART_FramingErrorFlag Frame error flag, sets if logic 0 was detected where stop bit expected.
kUART_ParityErrorFlag If parity enabled, sets upon parity error detection.
kUART_LinBreakFlag LIN break detect interrupt flag, sets when LIN break char detected and LIN
circuit enabled.
kUART_RxActiveEdgeFlag RX pin active edge interrupt flag, sets when active edge detected.
kUART_RxActiveFlag Receiver Active Flag (RAF), sets at beginning of valid start bit.
This function configures the UART module with the user-defined settings. The user can configure the
configuration structure and also get the default configuration by using the UART_GetDefaultConfig()
function. The example below shows how to use this API to configure UART.
* uart_config_t uartConfig;
* uartConfig.baudRate_Bps = 115200U;
* uartConfig.parityMode = kUART_ParityDisabled;
* uartConfig.stopBitCount = kUART_OneStopBit;
* uartConfig.txFifoWatermark = 0;
* uartConfig.rxFifoWatermark = 1;
* UART_Init(UART1, &uartConfig, 20000000U);
*
Parameters
Return values
This function waits for TX complete, disables TX and RX, and disables the UART clock.
Parameters
This function initializes the UART configuration structure to a default value. The default values are
as follows. uartConfig->baudRate_Bps = 115200U; uartConfig->bitCountPerChar = kUART_8BitsPer-
Char; uartConfig->parityMode = kUART_ParityDisabled; uartConfig->stopBitCount = kUART_One-
StopBit; uartConfig->txFifoWatermark = 0; uartConfig->rxFifoWatermark = 1; uartConfig->enableTx =
false; uartConfig->enableRx = false;
Parameters
This function configures the UART module baud rate. This function is used to update the UART module
baud rate after the UART module is initialized by the UART_Init.
Parameters
Return values
This function gets all UART status flags. The flags are returned as the logical OR value of the enumerators
_uart_flags. To check a specific status, compare the return value with enumerators in _uart_flags. For
example, to check whether the TX is empty, do the following.
Parameters
Returns
UART status flags which are ORed by the enumerators in the _uart_flags.
This function clears UART status flags with a provided mask. An automatically cleared flag can’t be
cleared by this function. These flags can only be cleared or set by hardware. kUART_TxDataRegEmpty-
Flag, kUART_TransmissionCompleteFlag, kUART_RxDataRegFullFlag, kUART_RxActiveFlag, kUA-
RT_NoiseErrorInRxDataRegFlag, kUART_ParityErrorInRxDataRegFlag, kUART_TxFifoEmptyFlag,k-
UART_RxFifoEmptyFlag Note that this API should be called when the Tx/Rx is idle. Otherwise it has no
effect.
Parameters
Return values
kStatus_UART_Flag- The flag can’t be cleared by this function but it is cleared automatically by
CannotClearManually hardware.
kStatus_Success Status in the mask is cleared.
This function enables the UART interrupts according to the provided mask. The mask is a logical OR of
enumeration members. See _uart_interrupt_enable. For example, to enable TX empty interrupt and RX
full interrupt, do the following.
* UART_EnableInterrupts(UART1,
kUART_TxDataRegEmptyInterruptEnable |
kUART_RxDataRegFullInterruptEnable);
*
Parameters
This function disables the UART interrupts according to the provided mask. The mask is a logical OR of
enumeration members. See _uart_interrupt_enable. For example, to disable TX empty interrupt and RX
full interrupt do the following.
* UART_DisableInterrupts(UART1,
kUART_TxDataRegEmptyInterruptEnable |
kUART_RxDataRegFullInterruptEnable);
*
Parameters
This function gets the enabled UART interrupts. The enabled interrupts are returned as the logical OR
value of the enumerators _uart_interrupt_enable. To check a specific interrupts enable status, compare
the return value with enumerators in _uart_interrupt_enable. For example, to check whether TX empty
interrupt is enabled, do the following.
* uint32_t enabledInterrupts = UART_GetEnabledInterrupts(UART1);
*
* if (kUART_TxDataRegEmptyInterruptEnable & enabledInterrupts)
* {
* ...
* }
*
Parameters
Returns
UART interrupt flags which are logical OR of the enumerators in _uart_interrupt_enable.
This function returns the UART data register address, which is mainly used by DMA/eDMA.
Parameters
Returns
UART data register addresses which are used both by the transmitter and the receiver.
This function enables or disables the transmit data register empty flag, S1[TDRE], to generate the DMA
requests.
Parameters
This function enables or disables the receiver data register full flag, S1[RDRF], to generate DMA requests.
Parameters
This function writes data to the TX register directly. The upper layer must ensure that the TX register is
empty or TX FIFO has empty room before calling this function.
Parameters
This function reads data from the RX register directly. The upper layer must ensure that the RX register is
full or that the TX FIFO has data before calling this function.
Parameters
Returns
The byte read from UART data register.
This function polls the TX register, waits for the TX register to be empty or for the TX FIFO to have room
and writes data to the TX buffer.
Note
This function does not check whether all data is sent out to the bus. Before disabling the TX, check
kUART_TransmissionCompleteFlag to ensure that the TX is finished.
Parameters
This function polls the RX register, waits for the RX register to be full or for RX FIFO to have data, and
reads data from the TX register.
Parameters
Return values
This function initializes the UART handle which can be used for other UART transactional APIs. Usually,
for a specified UART instance, call this API once to get the initialized handle.
Parameters
Note
When using the RX ring buffer, one byte is reserved for internal use. In other words, if ring-
BufferSize is 32, only 31 bytes are used for saving data.
Parameters
This function aborts the background transfer and uninstalls the ring buffer.
Parameters
This function sends data using an interrupt method. This is a non-blocking function, which returns directly
without waiting for all data to be written to the TX register. When all data is written to the TX register
in the ISR, the UART driver calls the callback function and passes the kStatus_UART_TxIdle as status
parameter.
Note
The kStatus_UART_TxIdle is passed to the upper layer when all data is written to the TX register.
However, it does not ensure that all data is sent out. Before disabling the TX, check the kUART_-
TransmissionCompleteFlag to ensure that the TX is finished.
Parameters
Return values
This function aborts the interrupt-driven data sending. The user can get the remainBytes to find out how
many bytes are not sent out.
Parameters
This function gets the number of bytes written to the UART TX register by using the interrupt method.
Parameters
Return values
This function receives data using an interrupt method. This is a non-blocking function, which returns
without waiting for all data to be received. If the RX ring buffer is used and not empty, the data in the ring
buffer is copied and the parameter receivedBytes shows how many bytes are copied from the ring
buffer. After copying, if the data in the ring buffer is not enough to read, the receive request is saved by the
UART driver. When the new data arrives, the receive request is serviced first. When all data is received,
the UART driver notifies the upper layer through a callback function and passes the status parameter k-
Status_UART_RxIdle. For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring
buffer. The 5 bytes are copied to the xfer->data and this function returns with the parameter received-
Bytes set to 5. For the left 5 bytes, newly arrived data is saved from the xfer->data[5]. When 5 bytes
are received, the UART driver notifies the upper layer. If the RX ring buffer is not enabled, this function
enables the RX and RX interrupt to receive data to the xfer->data. When all data is received, the upper
layer is notified.
Parameters
Return values
This function aborts the interrupt-driven data receiving. The user can get the remainBytes to know how
many bytes are not received yet.
Parameters
This function gets the number of bytes that have been received.
Parameters
Return values
This function handles the UART transmit and receive IRQ request.
Parameters
Parameters
Data Structures
• struct uart_dma_handle_t
UART DMA handle. More...
Typedefs
eDMA transactional
Data Fields
• UART_Type ∗ base
Parameters
This function sends data using DMA. This is non-blocking function, which returns right away. When all
data is sent, the send callback function is called.
Parameters
Return values
This function receives data using DMA. This is non-blocking function, which returns right away. When
all data is received, the receive callback function is called.
Parameters
Return values
This function gets the number of bytes written to UART TX register by DMA.
Parameters
Return values
This function gets the number of bytes that have been received.
Parameters
Return values
Data Structures
• struct uart_edma_handle_t
UART eDMA handle. More...
Typedefs
eDMA transactional
Data Fields
• uart_edma_transfer_callback_t callback
Callback function.
• void ∗ userData
UART callback function parameter.
• size_t rxDataSizeAll
Size of the data to receive.
• size_t txDataSizeAll
Size of the data to send out.
• edma_handle_t ∗ txEdmaHandle
The eDMA TX channel used.
• edma_handle_t ∗ rxEdmaHandle
The eDMA RX channel used.
• uint8_t nbytes
eDMA minor byte transfer count initially configured.
• volatile uint8_t txState
TX transfer state.
• volatile uint8_t rxState
RX transfer state.
Parameters
This function sends data using eDMA. This is a non-blocking function, which returns right away. When
all data is sent, the send callback function is called.
Parameters
Return values
This function receives data using eDMA. This is a non-blocking function, which returns right away. When
all data is received, the receive callback function is called.
Parameters
Return values
This function gets the number of bytes that have been written to UART TX register by DMA.
Parameters
Return values
Return values
Data Structures
• struct uart_rtos_config_t
UART configuration structure. More...
Data Fields
• UART_Type ∗ base
UART base address.
• uint32_t srcclk
UART source clock in Hz.
• uint32_t baudrate
Desired communication speed.
• uart_parity_mode_t parity
Parity setting.
• uart_stop_bit_count_t stopbits
Number of stop bits to use.
• uint8_t ∗ buffer
Buffer for background reception.
• uint32_t buffer_size
Size of buffer for background reception.
Parameters
handle The RTOS UART handle, the pointer to an allocated space for RTOS context.
t_handle The pointer to the allocated space to store the transactional layer internal state.
cfg The pointer to the parameters required to configure the UART after initialization.
Returns
0 succeed; otherwise fail.
This function deinitializes the UART module, sets all register values to reset value, and frees the resources.
Parameters
This function sends data. It is a synchronous API. If the hardware buffer is full, the task is in the blocked
state.
Parameters
This function receives data from UART. It is a synchronous API. If data is immediately available, it is
returned immediately and the number of bytes received.
Parameters
Modules
• Multipurpose Clock Generator (MCG)
Files
• file fsl_clock.h
Data Structures
• struct sim_clock_config_t
SIM configuration structure for clock setting. More...
• struct oscer_config_t
OSC configuration for OSCERCLK. More...
• struct osc_config_t
OSC Initialization Configuration Structure. More...
• struct mcg_pll_config_t
Macros
• #define MCG_CONFIG_CHECK_PARAM 0U
Configures whether to check a parameter in a function.
• #define FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL 0
Configure whether driver controls clock.
• #define DMAMUX_CLOCKS
Clock ip name array for DMAMUX.
• #define RTC_CLOCKS
Clock ip name array for RTC.
• #define SAI_CLOCKS
Clock ip name array for SAI.
• #define SPI_CLOCKS
Clock ip name array for SPI.
• #define PIT_CLOCKS
Clock ip name array for PIT.
• #define PORT_CLOCKS
Clock ip name array for PORT.
• #define TSI_CLOCKS
Clock ip name array for TSI.
• #define DAC_CLOCKS
Clock ip name array for DAC.
• #define LPTMR_CLOCKS
Clock ip name array for LPTMR.
• #define ADC16_CLOCKS
Clock ip name array for ADC16.
• #define DMA_CLOCKS
Clock ip name array for DMA.
• #define UART0_CLOCKS
Clock ip name array for LPSCI/UART0.
• #define UART_CLOCKS
Clock ip name array for UART.
• #define TPM_CLOCKS
Clock ip name array for TPM.
• #define I2C_CLOCKS
Clock ip name array for I2C.
• #define FTF_CLOCKS
Clock ip name array for FTF.
• #define CMP_CLOCKS
Clock ip name array for CMP.
• #define LPO_CLK_FREQ 1000U
LPO clock frequency.
• #define SYS_CLK kCLOCK_CoreSysClk
Peripherals clock source definition.
Enumerations
• enum clock_name_t {
kCLOCK_CoreSysClk,
kCLOCK_PlatClk,
kCLOCK_BusClk,
kCLOCK_FlexBusClk,
kCLOCK_FlashClk,
kCLOCK_PllFllSelClk,
kCLOCK_Er32kClk,
kCLOCK_Osc0ErClk,
kCLOCK_McgFixedFreqClk,
kCLOCK_McgInternalRefClk,
kCLOCK_McgFllClk,
kCLOCK_McgPll0Clk,
kCLOCK_McgExtPllClk,
kCLOCK_LpoClk }
Clock name used to get clock frequency.
• enum clock_usb_src_t {
kCLOCK_UsbSrcPll0 = SIM_SOPT2_USBSRC(1U) | SIM_SOPT2_PLLFLLSEL(1U),
kCLOCK_UsbSrcExt = SIM_SOPT2_USBSRC(0U) }
USB clock source definition.
• enum clock_ip_name_t
Clock gate name used for CLOCK_EnableClock/CLOCK_DisableClock.
• enum osc_mode_t {
kOSC_ModeExt = 0U,
kOSC_ModeOscLowPower = MCG_C2_EREFS0_MASK,
kOSC_ModeOscHighGain }
OSC work mode.
• enum _osc_cap_load {
kOSC_Cap2P = OSC_CR_SC2P_MASK,
kOSC_Cap4P = OSC_CR_SC4P_MASK,
kOSC_Cap8P = OSC_CR_SC8P_MASK,
kOSC_Cap16P = OSC_CR_SC16P_MASK }
Oscillator capacitor load setting.
• enum _oscer_enable_mode {
kOSC_ErClkEnable = OSC_CR_ERCLKEN_MASK,
kOSC_ErClkEnableInStop = OSC_CR_EREFSTEN_MASK }
OSCERCLK enable mode.
• enum mcg_fll_src_t {
kMCG_FllSrcExternal,
kMCG_FllSrcInternal }
MCG FLL reference clock source select.
• enum mcg_irc_mode_t {
kMCG_IrcSlow,
kMCG_IrcFast }
MCG internal reference clock select.
• enum mcg_dmx32_t {
kMCG_Dmx32Default,
kMCG_Dmx32Fine }
MCG DCO Maximum Frequency with 32.768 kHz Reference.
• enum mcg_drs_t {
kMCG_DrsLow,
kMCG_DrsMid,
kMCG_DrsMidHigh,
kMCG_DrsHigh }
MCG DCO range select.
• enum mcg_pll_ref_src_t {
kMCG_PllRefOsc0,
kMCG_PllRefOsc1 }
MCG PLL reference clock select.
• enum mcg_clkout_src_t {
kMCG_ClkOutSrcOut,
kMCG_ClkOutSrcInternal,
kMCG_ClkOutSrcExternal }
MCGOUT clock source.
• enum mcg_atm_select_t {
kMCG_AtmSel32k,
kMCG_AtmSel4m }
MCG Automatic Trim Machine Select.
• enum mcg_oscsel_t {
kMCG_OscselOsc,
kMCG_OscselRtc }
MCG OSC Clock Select.
• enum mcg_pll_clk_select_t { kMCG_PllClkSelPll0 }
MCG PLLCS select.
• enum mcg_monitor_mode_t {
kMCG_MonitorNone,
kMCG_MonitorInt,
kMCG_MonitorReset }
MCG clock monitor mode.
• enum _mcg_status {
kStatus_MCG_ModeUnreachable = MAKE_STATUS(kStatusGroup_MCG, 0),
kStatus_MCG_ModeInvalid = MAKE_STATUS(kStatusGroup_MCG, 1),
kStatus_MCG_AtmBusClockInvalid = MAKE_STATUS(kStatusGroup_MCG, 2),
kStatus_MCG_AtmDesiredFreqInvalid = MAKE_STATUS(kStatusGroup_MCG, 3),
kStatus_MCG_AtmIrcUsed = MAKE_STATUS(kStatusGroup_MCG, 4),
kStatus_MCG_AtmHardwareFail = MAKE_STATUS(kStatusGroup_MCG, 5),
kStatus_MCG_SourceUsed = MAKE_STATUS(kStatusGroup_MCG, 6) }
MCG status.
• enum _mcg_status_flags_t {
kMCG_Osc0LostFlag = (1U << 0U),
kMCG_Osc0InitFlag = (1U << 1U),
kMCG_Pll0LostFlag = (1U << 5U),
Functions
• static void CLOCK_EnableClock (clock_ip_name_t name)
Enable the clock for specific IP.
• static void CLOCK_DisableClock (clock_ip_name_t name)
Disable the clock for specific IP.
• static void CLOCK_SetEr32kClock (uint32_t src)
Set ERCLK32K source.
• static void CLOCK_SetPllFllSelClock (uint32_t src)
Set PLLFLLSEL clock source.
• static void CLOCK_SetTpmClock (uint32_t src)
Set TPM clock source.
• static void CLOCK_SetLpsci0Clock (uint32_t src)
Set LPSCI0 (UART0) clock source.
• bool CLOCK_EnableUsbfs0Clock (clock_usb_src_t src, uint32_t freq)
Enable USB FS clock.
• static void CLOCK_DisableUsbfs0Clock (void)
Disable USB FS clock.
• static void CLOCK_SetClkOutClock (uint32_t src)
Set CLKOUT source.
• static void CLOCK_SetRtcClkOutClock (uint32_t src)
Set RTC_CLKOUT source.
• static void CLOCK_SetOutDiv (uint32_t outdiv1, uint32_t outdiv4)
Set the SIM_CLKDIV1[OUTDIV1], SIM_CLKDIV1[OUTDIV4].
• uint32_t CLOCK_GetFreq (clock_name_t clockName)
Gets the clock frequency for a specific clock name.
• uint32_t CLOCK_GetCoreSysClkFreq (void)
Variables
• uint32_t g_xtal0Freq
External XTAL0 (OSC0) clock frequency.
• uint32_t g_xtal32Freq
External XTAL32/EXTAL32/RTC_CLKIN clock frequency.
Driver version
• #define FSL_CLOCK_DRIVER_VERSION (MAKE_VERSION(2, 2, 1))
CLOCK driver version 2.2.1.
OSC configuration
• static void OSC_SetExtRefClkConfig (OSC_Type ∗base, oscer_config_t const ∗config)
Configures the OSC external reference clock (OSCERCLK).
• static void OSC_SetCapLoad (OSC_Type ∗base, uint8_t capLoad)
Sets the capacitor load configuration for the oscillator.
• void CLOCK_InitOsc0 (osc_config_t const ∗config)
Initializes the OSC0.
• void CLOCK_DeinitOsc0 (void)
Deinitializes the OSC0.
Data Fields
• uint8_t er32kSrc
ERCLK32K source selection.
• uint32_t clkdiv1
SIM_CLKDIV1.
Data Fields
• uint8_t enableMode
OSCERCLK enable mode.
Defines the configuration data structure to initialize the OSC. When porting to a new board, set the fol-
lowing members according to the board setting:
1. freq: The external frequency.
2. workMode: The OSC module mode.
Data Fields
• uint32_t freq
External clock frequency.
• uint8_t capLoad
Capacitor load setting.
• osc_mode_t workMode
OSC work mode setting.
• oscer_config_t oscerConfig
Configuration for OSCERCLK.
Data Fields
• uint8_t enableMode
Enable mode.
• uint8_t prdiv
Reference divider PRDIV.
• uint8_t vdiv
VCO divider VDIV.
When porting to a new board, set the following members according to the board setting:
1. frdiv: If the FLL uses the external reference clock, set this value to ensure that the external reference
clock divided by frdiv is in the 31.25 kHz to 39.0625 kHz range.
2. The PLL reference clock divider PRDIV: PLL reference clock frequency after PRDIV should be in
the FSL_FEATURE_MCG_PLL_REF_MIN to FSL_FEATURE_MCG_PLL_REF_MAX range.
Data Fields
• mcg_mode_t mcgMode
MCG mode.
• uint8_t irclkEnableMode
MCGIRCLK enable mode.
• mcg_irc_mode_t ircs
Source, MCG_C2[IRCS].
• uint8_t fcrdiv
Divider, MCG_SC[FCRDIV].
• uint8_t frdiv
Divider MCG_C1[FRDIV].
• mcg_drs_t drs
DCO range MCG_C4[DRST_DRS].
• mcg_dmx32_t dmx32
MCG_C4[DMX32].
• mcg_pll_config_t pll0Config
MCGPLL0CLK configuration.
When set to 0, peripheral drivers will enable clock in initialize function and disable clock in de-initialize
function. When set to 1, peripheral driver will not control the clock, application could contol the clock out
of the driver.
Note
All drivers share this feature switcher. If it is set to 1, application should handle clock enable and
disable for all drivers.
Value:
{ \
kCLOCK_Dmamux0 \
}
Value:
{ \
kCLOCK_Rtc0 \
}
Value:
{ \
kCLOCK_Sai0 \
}
Value:
{ \
kCLOCK_Spi0, kCLOCK_Spi1 \
}
Value:
{ \
kCLOCK_Pit0 \
}
Value:
{ \
kCLOCK_PortA, kCLOCK_PortB, kCLOCK_PortC, kCLOCK_PortD, kCLOCK_PortE \
}
Value:
{ \
kCLOCK_Tsi0 \
}
Value:
{ \
kCLOCK_Dac0 \
}
Value:
{ \
kCLOCK_Lptmr0 \
}
Value:
{ \
kCLOCK_Adc0 \
}
Value:
{ \
kCLOCK_Dma0 \
}
Value:
{ \
kCLOCK_Uart0 \
}
Value:
{ \
kCLOCK_IpInvalid, kCLOCK_Uart1, kCLOCK_Uart2 \
}
Value:
{ \
kCLOCK_Tpm0, kCLOCK_Tpm1, kCLOCK_Tpm2 \
}
Value:
{ \
kCLOCK_I2c0, kCLOCK_I2c1 \
}
Value:
{ \
kCLOCK_Ftf0 \
}
Value:
{ \
kCLOCK_Cmp0 \
}
Enumerator
kCLOCK_CoreSysClk Core/system clock.
kCLOCK_PlatClk Platform clock.
kCLOCK_BusClk Bus clock.
kCLOCK_FlexBusClk FlexBus clock.
kCLOCK_FlashClk Flash clock.
kCLOCK_PllFllSelClk The clock after SIM[PLLFLLSEL].
kCLOCK_Er32kClk External reference 32K clock (ERCLK32K)
kCLOCK_Osc0ErClk OSC0 external reference clock (OSC0ERCLK)
kCLOCK_McgFixedFreqClk MCG fixed frequency clock (MCGFFCLK)
kCLOCK_McgInternalRefClk MCG internal reference clock (MCGIRCLK)
kCLOCK_McgFllClk MCGFLLCLK.
kCLOCK_McgPll0Clk MCGPLL0CLK.
kCLOCK_McgExtPllClk EXT_PLLCLK.
kCLOCK_LpoClk LPO clock.
Enumerator
kCLOCK_UsbSrcPll0 Use PLL0.
kCLOCK_UsbSrcExt Use USB_CLKIN.
Enumerator
kOSC_ModeExt Use an external clock.
kOSC_ModeOscLowPower Oscillator low power.
kOSC_ModeOscHighGain Oscillator high gain.
Enumerator
kOSC_Cap2P 2 pF capacitor load
kOSC_Cap4P 4 pF capacitor load
kOSC_Cap8P 8 pF capacitor load
kOSC_Cap16P 16 pF capacitor load
Enumerator
kOSC_ErClkEnable Enable.
kOSC_ErClkEnableInStop Enable in stop mode.
Enumerator
kMCG_FllSrcExternal External reference clock is selected.
kMCG_FllSrcInternal The slow internal reference clock is selected.
Enumerator
kMCG_IrcSlow Slow internal reference clock selected.
kMCG_IrcFast Fast internal reference clock selected.
Enumerator
kMCG_Dmx32Default DCO has a default range of 25%.
kMCG_Dmx32Fine DCO is fine-tuned for maximum frequency with 32.768 kHz reference.
Enumerator
kMCG_DrsLow Low frequency range.
kMCG_DrsMid Mid frequency range.
kMCG_DrsMidHigh Mid-High frequency range.
kMCG_DrsHigh High frequency range.
Enumerator
kMCG_PllRefOsc0 Selects OSC0 as PLL reference clock.
kMCG_PllRefOsc1 Selects OSC1 as PLL reference clock.
Enumerator
kMCG_ClkOutSrcOut Output of the FLL is selected (reset default)
kMCG_ClkOutSrcInternal Internal reference clock is selected.
kMCG_ClkOutSrcExternal External reference clock is selected.
Enumerator
kMCG_AtmSel32k 32 kHz Internal Reference Clock selected
kMCG_AtmSel4m 4 MHz Internal Reference Clock selected
Enumerator
kMCG_OscselOsc Selects System Oscillator (OSCCLK)
kMCG_OscselRtc Selects 32 kHz RTC Oscillator.
Enumerator
kMCG_PllClkSelPll0 PLL0 output clock is selected.
Enumerator
kMCG_MonitorNone Clock monitor is disabled.
kMCG_MonitorInt Trigger interrupt when clock lost.
kMCG_MonitorReset System reset when clock lost.
Enumerator
kStatus_MCG_ModeUnreachable Can’t switch to target mode.
kStatus_MCG_ModeInvalid Current mode invalid for the specific function.
kStatus_MCG_AtmBusClockInvalid Invalid bus clock for ATM.
kStatus_MCG_AtmDesiredFreqInvalid Invalid desired frequency for ATM.
kStatus_MCG_AtmIrcUsed IRC is used when using ATM.
kStatus_MCG_AtmHardwareFail Hardware fail occurs during ATM.
kStatus_MCG_SourceUsed Can’t change the clock source because it is in use.
Enumerator
kMCG_Osc0LostFlag OSC0 lost.
kMCG_Osc0InitFlag OSC0 crystal initialized.
kMCG_Pll0LostFlag PLL0 lost.
kMCG_Pll0LockFlag PLL0 locked.
Enumerator
kMCG_IrclkEnable MCGIRCLK enable.
kMCG_IrclkEnableInStop MCGIRCLK enable in stop mode.
Enumerator
kMCG_PllEnableIndependent MCGPLLCLK enable independent of the MCG clock mode. Gen-
erally, the PLL is disabled in FLL modes (FEI/FBI/FEE/FBE). Setting the PLL clock enable
independent, enables the PLL in the FLL modes.
kMCG_PllEnableInStop MCGPLLCLK enable in STOP mode.
Enumerator
kMCG_ModeFEI FEI - FLL Engaged Internal.
Parameters
Parameters
Parameters
Return values
This function checks the current clock configurations and then calculates the clock frequency for a specific
clock name defined in clock_name_t. The MCG must be properly configured before using this function.
Parameters
Returns
Clock frequency value in Hertz
Returns
Clock frequency in Hz.
Returns
Clock frequency in Hz.
Returns
Clock frequency in Hz.
Returns
Clock frequency in Hz.
Returns
Clock frequency in Hz.
Returns
Clock frequency in Hz.
Returns
Clock frequency in Hz.
Parameters
The system level clocks (core clock, bus clock, flexbus clock and flash clock) must be in allowed ranges.
During MCG clock mode switch, the MCG output clock changes then the system level clocks may be out
of range. This function could be used before MCG mode change, to make sure system level clocks are in
allowed range.
Parameters
This function gets the MCG output clock frequency in Hz based on the current MCG register value.
Returns
The frequency of MCGOUTCLK.
This function gets the MCG FLL clock frequency in Hz based on the current MCG register value. The
FLL is enabled in FEI/FBI/FEE/FBE mode and disabled in low power state in other modes.
Returns
The frequency of MCGFLLCLK.
This function gets the MCG internal reference clock frequency in Hz based on the current MCG register
value.
Returns
The frequency of MCGIRCLK.
This function gets the MCG fixed frequency clock frequency in Hz based on the current MCG register
value.
Returns
The frequency of MCGFFCLK.
This function gets the MCG PLL0 clock frequency in Hz based on the current MCG register value.
Returns
The frequency of MCGPLL0CLK.
Enabling the MCG low power disables the PLL and FLL in bypass modes. In other words, in FBE and
PBE modes, enabling low power sets the MCG to BLPE mode. In FBI and PBI modes, enabling low
power sets the MCG to BLPI mode. When disabling the MCG low power, the PLL or FLL are enabled
based on MCG settings.
Parameters
enable True to enable MCG low power, false to disable MCG low power.
This function sets the MCGIRCLK base on parameters. It also selects the IRC source. If the fast IRC is
used, this function sets the fast IRC divider. This function also sets whether the MCGIRCLK is enabled in
stop mode. Calling this function in FBI/PBI/BLPI modes may change the system clock. As a result, using
the function in these modes it is not allowed.
Parameters
Return values
kStatus_MCG_Source- Because the internall reference clock is used as a clock source, the confu-
Used ration should not be changed. Otherwise, a glitch occurs.
kStatus_Success MCGIRCLK configuration finished successfully.
Selects the MCG external reference clock source, changes the MCG_C7[OSCSEL], and waits for the
clock source to be stable. Because the external reference clock should not be changed in FEE/FBE/BLP-
E/PBE/PEE modes, do not call this function in these modes.
Parameters
Return values
kStatus_MCG_Source- Because the external reference clock is used as a clock source, the confu-
Used ration should not be changed. Otherwise, a glitch occurs.
kStatus_Success External reference clock set successfully.
Sets the FLL external reference clock divider value, the register MCG_C1[FRDIV].
Parameters
This function sets us the PLL0 in FLL mode and reconfigures the PLL0. Ensure that the PLL reference
clock is enabled before calling this function and that the PLL0 is not used as a clock source. The function
CLOCK_CalcPllDiv gets the correct PLL divider values.
Parameters
This function disables the PLL0 in FLL mode. It should be used together with the CLOCK_EnablePll0.
This function calculates the correct reference clock divider (PRDIV) and VCO divider (VDIV) to generate
a desired PLL output frequency. It returns the closest frequency match with the corresponding PRDIV/-
VDIV returned from parameters. If a desired frequency is not valid, this function returns 0.
Parameters
Returns
Closest frequency match that the PLL was able generate.
This function sets the OSC0 clock monitor mode. See mcg_monitor_mode_t for details.
Parameters
This function sets the PLL0 clock monitor mode. See mcg_monitor_mode_t for details.
Parameters
This function gets the MCG clock status flags. All status flags are returned as a logical OR of the enumer-
ation _mcg_status_flags_t. To check a specific flag, compare the return value with the flag.
Example:
// To check the clock lost lock status of OSC0 and PLL0.
uint32_t mcgFlags;
mcgFlags = CLOCK_GetStatusFlags();
Returns
Logical OR value of the _mcg_status_flags_t.
This function clears the MCG clock lock lost status. The parameter is a logical OR value of the flags to
clear. See _mcg_status_flags_t.
Example:
// To clear the clock lost lock status flags of OSC0 and PLL0.
CLOCK_ClearStatusFlags(kMCG_Osc0LostFlag | kMCG_Pll0LostFlag);
Parameters
mask The status flags to clear. This is a logical OR of members of the enumeration _mcg_-
status_flags_t.
This function configures the OSC external reference clock (OSCERCLK). This is an example to enable
the OSCERCLK in normal and stop modes and also set the output divider to 1:
oscer_config_t config =
{
.enableMode = kOSC_ErClkEnable |
kOSC_ErClkEnableInStop,
.erclkDiv = 1U,
};
OSC_SetExtRefClkConfig(OSC, &config);
Parameters
This function sets the specified capacitors configuration for the oscillator. This should be done in the early
system level initialization function call based on the system configuration.
Parameters
Parameters
Parameters
Parameters
This function trims the internal reference clock by using the external clock. If successful, it returns the
kStatus_Success and the frequency after trimming is received in the parameter actualFreq. If an error
occurs, the error code is returned.
Parameters
Return values
This function checks the MCG registers and determines the current MCG mode.
Returns
Current MCG mode or error code; See mcg_mode_t.
This function sets the MCG to FEI mode. If setting to FEI mode fails from the current mode, this function
returns an error.
Parameters
Return values
Note
If dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed to a frequency above
32768 Hz.
This function sets the MCG to FEE mode. If setting to FEE mode fails from the current mode, this function
returns an error.
Parameters
Return values
This function sets the MCG to FBI mode. If setting to FBI mode fails from the current mode, this function
returns an error.
Parameters
Return values
Note
If dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed to frequency above 32768
Hz.
This function sets the MCG to FBE mode. If setting to FBE mode fails from the current mode, this
function returns an error.
Parameters
Return values
This function sets the MCG to BLPI mode. If setting to BLPI mode fails from the current mode, this
function returns an error.
Return values
This function sets the MCG to BLPE mode. If setting to BLPE mode fails from the current mode, this
function returns an error.
Return values
This function sets the MCG to PBE mode. If setting to PBE mode fails from the current mode, this
function returns an error.
Parameters
Return values
Note
1. The parameter pllcs selects the PLL. For platforms with only one PLL, the parameter pllcs
is kept for interface compatibility.
2. The parameter config is the PLL configuration structure. On some platforms, it is possible
to choose the external PLL directly, which renders the configuration structure not necessary. In
this case, pass in NULL. For example: CLOCK_SetPbeMode(kMCG_OscselOsc, kMCG_Pll-
ClkSelExtPll, NULL);
Note
This function only changes the CLKS to use the PLL/FLL output. If the PRDIV/VDIV are different
than in the PBE mode, set them up in PBE mode and wait. When the clock is stable, switch to PEE
mode.
This function switches the MCG from external modes (PEE/PBE/BLPE/FEE) to the FBE mode quickly.
The external clock is used as the system clock souce and PLL is disabled. However, the FLL settings are
not configured. This is a lite function with a small code size, which is useful during the mode switch. For
example, to switch from PEE mode to FEI mode:
* CLOCK_ExternalModeToFbeModeQuick();
* CLOCK_SetFeiMode(...);
*
Return values
This function switches the MCG from internal modes (PEI/PBI/BLPI/FEI) to the FBI mode quickly. The
MCGIRCLK is used as the system clock souce and PLL is disabled. However, FLL settings are not
configured. This is a lite function with a small code size, which is useful during the mode switch. For
example, to switch from PEI mode to FEE mode:
* CLOCK_InternalModeToFbiModeQuick();
* CLOCK_SetFeeMode(...);
*
Return values
This function sets the MCG to FEI mode from the reset mode. It can also be used to set up MCG during
system boot up.
Parameters
Return values
Note
If dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed to frequency above 32768
Hz.
This function sets MCG to FEE mode from the reset mode. It can also be used to set up the MCG during
system boot up.
Parameters
Return values
This function sets the MCG to BLPI mode from the reset mode. It can also be used to set up the MCG
during sytem boot up.
Parameters
Return values
This function sets the MCG to BLPE mode from the reset mode. It can also be used to set up the MCG
during sytem boot up.
Parameters
Return values
This function sets the MCG to PEE mode from reset mode. It can also be used to set up the MCG during
system boot up.
Parameters
Return values
This function sets MCG to a target mode defined by the configuration structure. If switching to the target
mode fails, this function chooses the correct path.
Parameters
Returns
Return kStatus_Success if switched successfully; Otherwise, it returns an error code _mcg_status.
Note
If the external clock is used in the target mode, ensure that it is enabled. For example, if the OSC0
is used, set up OSC0 correctly before calling this function.
The XTAL0/EXTAL0 (OSC0) clock frequency in Hz. When the clock is set up, use the function CLOC-
K_SetXtal0Freq to set the value in the clock driver. For example, if XTAL0 is 8 MHz:
This is important for the multicore platforms where only one core needs to set up the OSC0 using the
CLOCK_InitOsc0. All other cores need to call the CLOCK_SetXtal0Freq to get a valid clock frequency.
The XTAL32/EXTAL32/RTC_CLKIN clock frequency in Hz. When the clock is set up, use the function
CLOCK_SetXtal32Freq to set the value in the clock driver.
This is important for the multicore platforms where only one core needs to set up the clock. All other
cores need to call the CLOCK_SetXtal32Freq to get a valid clock frequency.
MCG module provides clocks, such as MCGOUTCLK, MCGIRCLK, MCGFFCLK, MCGFLLCLK and
MCGPLLCLK. The MCG driver provides functions to get the frequency of these clocks, such as C-
LOCK_GetOutClkFreq(), CLOCK_GetInternalRefClkFreq(), CLOCK_GetFixedFreqClkFreq(), CLOC-
K_GetFllFreq(), CLOCK_GetPll0Freq(), CLOCK_GetPll1Freq(), and CLOCK_GetExtPllFreq(). These
functions get the clock frequency based on the current MCG registers.
The MCG driver provides functions to configure the internal reference clock (MCGIRCLK), the external
reference clock, and MCGPLLCLK.
The function CLOCK_SetInternalRefClkConfig() configures the MCGIRCLK, including the source and
the driver. Do not change MCGIRCLK when the MCG mode is BLPI/FBI/PBI because the MCGIRCLK
is used as a system clock in these modes and changing settings makes the system clock unstable.
The function CLOCK_SetExternalRefClkConfig() configures the external reference clock source (MCG-
_C7[OSCSEL]). Do not call this function when the MCG mode is BLPE/FBE/PBE/FEE/PEE because
the external reference clock is used as a clock source in these modes. Changing the external reference
clock source requires at least a 50 microseconds wait. The function CLOCK_SetExternalRefClkConfig()
implements a for loop delay internally. The for loop delay assumes that the system clock is 96 MHz,
which ensures at least 50 micro seconds delay. However, when the system clock is slow, the delay time
may significantly increase. This for loop count can be optimized for better performance for specific cases.
The MCGPLLCLK is disabled in FBE/FEE/FBI/FEI modes by default. Applications can enable the M-
CGPLLCLK in these modes using the functions CLOCK_EnablePll0() and CLOCK_EnablePll1(). To
enable the MCGPLLCLK, the PLL reference clock divider(PRDIV) and the PLL VCO divider(VDIV)
must be set to a proper value. The function CLOCK_CalcPllDiv() helps to get the PRDIV/VDIV.
The MCG module monitors the OSC and the PLL clock lock status. The MCG driver provides the func-
tions to set the clock monitor mode, check the clock lost status, and clear the clock lost status.
The MCG is needed together with the OSC module to enable the OSC clock. The function CLOCK_Init-
Osc0() CLOCK_InitOsc1 uses the MCG and OSC to initialize the OSC. The OSC should be configured
based on the board design.
The MCG provides an auto-trim machine to trim the MCG internal reference clock based on the external
reference clock (BUS clock). During clock trimming, the MCG must not work in FEI/FBI/BLPI/PBI/PEI
modes. The function CLOCK_TrimInternalRefClk() is used for the auto clock trimming.
The function CLOCK_GetMcgMode returns the current MCG mode. The MCG can only switch between
the neighbouring modes. If the target mode is not current mode’s neighbouring mode, the application must
choose the proper switch path. For example, to switch to PEE mode from FEI mode, use FEI -> FBE ->
PBE -> PEE.
For the MCG modes, the MCG driver provides three kinds of functions:
The first type of functions involve functions CLOCK_SetXxxMode, such as CLOCK_SetFeiMode().
These functions only set the MCG mode from neighbouring modes. If switching to the target mode
directly from current mode is not possible, the functions return an error.
The second type of functions are the functions CLOCK_BootToXxxMode, such as CLOCK_BootToFei-
Mode(). These functions set the MCG to specific modes from reset mode. Because the source mode and
target mode are specific, these functions choose the best switch path. The functions are also useful to set
up the system clock during boot up.
The third type of functions is the CLOCK_SetMcgConfig(). This function chooses the right path to switch
to the target mode. It is easy to use, but introduces a large code size.
Whenever the FLL settings change, there should be a 1 millisecond delay to ensure that the FLL is stable.
The function CLOCK_SetMcgConfig() implements a for loop delay internally to ensure that the FLL is
stable. The for loop delay assumes that the system clock is 96 MHz, which ensures at least 1 millisecond
delay. However, when the system clock is slow, the delay time may increase significantly. The for loop
count can be optimized for better performance according to a specific use case.
The function CLOCK_SetMcgConfig is used to switch between any modes. However, this heavy-light
function introduces a large code size. This section shows how to use the mode function to implement a
quick and light-weight switch between typical specific modes. Note that the step to enable the external
clock is not included in the following steps. Enable the corresponding clock before using it as a clock
source.
This table applies when using the same external clock source (MCG_C7[OSCSEL]) in BLPE mode and
PEE mode.
If using different external clock sources (MCG_C7[OSCSEL]) in BLPE mode and PEE mode, call the
CLOCK_SetExternalRefClkConfig() in FBI or FEI mode to change the external reference clock.
This table applies when using the same external clock source (MCG_C7[OSCSEL]) in BLPE mode and
FEE mode.
If using different external clock sources (MCG_C7[OSCSEL]) in BLPE mode and FEE mode, call the
CLOCK_SetExternalRefClkConfig() in FBI or FEI mode to change the external reference clock.
29.9.3.1 MCG_USER_CONFIG_FLL_STABLE_DELAY_EN
When switching to use FLL with function CLOCK_SetFeiMode() and CLOCK_SetFeeMode(), there is
an internal function CLOCK_FllStableDelay(). It is used to delay a few ms so that to wait the FLL to be
stable enough. By default, it is implemented in driver code like:
#ifndef MCG_USER_CONFIG_FLL_STABLE_DELAY_EN
void CLOCK_FllStableDelay(void)
{
/*
Should wait at least 1ms. Because in these modes, the core clock is 100MHz
at most, so this function could obtain the 1ms delay.
*/
volatile uint32_t i = 30000U;
while (i--)
{
__NOP();
}
}
#endif /* MCG_USER_CONFIG_FLL_STABLE_DELAY_EN */
Once user is willing to create his own delay funcion, just assert the macro MCG_USER_CONFIG_FLL-
_STABLE_DELAY_EN, and then define function CLOCK_FllStableDelay in the application code.
This function group requests/releases the DMAMUX channel and configures the channel request source.
uint8_t channel;
dmamanager_handle_t dmamanager_handle;
/* Initialize DMAMGR */
DMAMGR_Init(&dmamanager_handle, EXAMPLE_DMA_BASEADDR, DMA_CHANNEL_NUMBER, startChannel);
/* Request a DMAMUX channel by static allocate mechanism */
channel = kDMAMGR_STATIC_ALLOCATE;
DMAMGR_RequestChannel(&dmamanager_handle, kDmaRequestMux0AlwaysOn63, channel, &handle)
;
uint8_t channel;
dmamanager_handle_t dmamanager_handle;
/* Initialize DMAMGR */
DMAMGR_Init(&dmamanager_handle, EXAMPLE_DMA_BASEADDR, DMA_CHANNEL_NUMBER, startChannel);
/* Request a DMAMUX channel by Dynamic allocate mechanism */
channel = DMAMGR_DYNAMIC_ALLOCATE;
DMAMGR_RequestChannel(&dmamanager_handle, kDmaRequestMux0AlwaysOn63, channel, &handle)
;
Data Structures
• struct dmamanager_handle_t
dmamanager handle typedef. More...
Macros
• #define DMAMGR_DYNAMIC_ALLOCATE 0xFFU
Dynamic channel allocation mechanism.
Enumerations
• enum _dma_manager_status {
kStatus_DMAMGR_ChannelOccupied = MAKE_STATUS(kStatusGroup_DMAMGR, 0),
kStatus_DMAMGR_ChannelNotUsed = MAKE_STATUS(kStatusGroup_DMAMGR, 1),
kStatus_DMAMGR_NoFreeChannel = MAKE_STATUS(kStatusGroup_DMAMGR, 2) }
DMA manager status.
DMAMGR Operation
• status_t DMAMGR_RequestChannel (dmamanager_handle_t ∗dmamanager_handle, uint32_t
requestSource, uint32_t channel, void ∗handle)
Requests a DMA channel.
• status_t DMAMGR_ReleaseChannel (dmamanager_handle_t ∗dmamanager_handle, void ∗handle)
Releases a DMA channel.
• bool DMAMGR_IsChannelOccupied (dmamanager_handle_t ∗dmamanager_handle, uint32_t
channel)
Get a DMA channel status.
Note
The contents of this structure are private and subject to change.
This dma manager handle structure is used to store the parameters transfered by users.And users shall not
free the memory before calling DMAMGR_Deinit, also shall not modify the contents of the memory.
Data Fields
• void ∗ dma_base
Peripheral DMA instance.
• uint32_t channelNum
Channel numbers for the DMA instance which need to be managed by dma manager.
• uint32_t startChannel
The start channel that can be managed by dma manager,users need to transfer it with a certain number or
NULL.
• bool s_DMAMGR_Channels [64]
The s_DMAMGR_Channels is used to store dma manager state.
• uint32_t DmamuxInstanceStart
The DmamuxInstance is used to calculate the DMAMUX Instance according to the DMA Instance.
• uint32_t multiple
The multiple is used to calculate the multiple between DMAMUX count and DMA count.
Enumerator
kStatus_DMAMGR_ChannelOccupied Channel has been occupied.
kStatus_DMAMGR_ChannelNotUsed Channel has not been used.
kStatus_DMAMGR_NoFreeChannel All channels have been occupied.
This function initializes the DMA manager, ungates the DMAMUX clocks, and initializes the eDMA or
DMA peripherals.
Parameters
dmamanager_- DMA manager handle pointer, this structure is maintained by dma manager inter-
handle nal,users only need to transfer the structure to the function. And users shall not free
the memory before calling DMAMGR_Deinit, also shall not modify the contents of
the memory.
dma_base Peripheral DMA instance base pointer.
dmamux_base Peripheral DMAMUX instance base pointer.
channelNum Channel numbers for the DMA instance which need to be managed by dma manager.
startChannel The start channel that can be managed by dma manager.
This function deinitializes the DMA manager, disables the DMAMUX channels, gates the DMAMUX
clocks, and deinitializes the eDMA or DMA peripherals.
Parameters
dmamanager_- DMA manager handle pointer, this structure is maintained by dma manager inter-
handle nal,users only need to transfer the structure to the function. And users shall not free
the memory before calling DMAMGR_Deinit, also shall not modify the contents of
the memory.
This function requests a DMA channel which is not occupied. The two channels to allocate the mechanism
are dynamic and static channels. For the dynamic allocation mechanism (channe = DMAMGR_DYNAM-
IC_ALLOCATE), DMAMGR allocates a DMA channel according to the given request source and start-
Channel and then configures it. For static allocation mechanism, DMAMGR configures the given channel
according to the given request source and channel number.
Parameters
dmamanager_- DMA manager handle pointer, this structure is maintained by dma manager inter-
handle nal,users only need to transfer the structure to the function. And users shall not free
the memory before calling DMAMGR_Deinit, also shall not modify the contents of
the memory.
requestSource DMA channel request source number. See the soc.h, see the enum dma_request_-
source_t
channel The channel number users want to occupy. If using the dynamic channel allocate
mechanism, set the channel equal to DMAMGR_DYNAMIC_ALLOCATE.
handle DMA or eDMA handle pointer.
Return values
dmamanager_- DMA manager handle pointer, this structure is maintained by dma manager inter-
handle nal,users only need to transfer the structure to the function. And users shall not free
the memory before calling DMAMGR_Deinit, also shall not modify the contents of
the memory.
handle DMA or eDMA handle pointer.
Return values
This function get a DMA channel status. Return 0 indicates the channel has not been used, return 1
indicates the channel has been occupied.
Parameters
dmamanager_- DMA manager handle pointer, this structure is maintained by dma manager inter-
handle nal,users only need to transfer the structure to the function. And users shall not free
the memory before calling DMAMGR_Deinit, also shall not modify the contents of
the memory.
channel The channel number that users want get its status.
Function groups
This function group implements the SD card functional API.
This function group implements the MMC card functional API.
/* Init card. */
if (SD_Init(card))
{
PRINTF("\r\nSD card init failed.\r\n");
}
while (true)
{
if (kStatus_Success != SD_WriteBlocks(card, g_dataWrite, DATA_BLOCK_START,
DATA_BLOCK_COUNT))
{
PRINTF("Write multiple data blocks failed.\r\n");
}
if (kStatus_Success != SD_ReadBlocks(card, g_dataRead, DATA_BLOCK_START, DATA_BLOCK_COUNT)
)
{
PRINTF("Read multiple data blocks failed.\r\n");
}
SD_Deinit(card);
/* Initialize SDHC. */
sdhcConfig->cardDetectDat3 = false;
sdhcConfig->endianMode = kSDHC_EndianModeLittle;
sdhcConfig->dmaMode = kSDHC_DmaModeAdma2;
sdhcConfig->readWatermarkLevel = 0x80U;
sdhcConfig->writeWatermarkLevel = 0x80U;
SDHC_Init(BOARD_SDHC_BASEADDR, sdhcConfig);
/* Init card. */
if (MMC_Init(card))
{
PRINTF("\n MMC card init failed \n");
}
while (true)
{
if (kStatus_Success != MMC_WriteBlocks(card, g_dataWrite, DATA_BLOCK_START,
DATA_BLOCK_COUNT))
{
PRINTF("Write multiple data blocks failed.\r\n");
}
if (kStatus_Success != MMC_ReadBlocks(card, g_dataRead, DATA_BLOCK_START,
DATA_BLOCK_COUNT))
{
PRINTF("Read multiple data blocks failed.\r\n");
}
}
MMC_Deinit(card);
Data Structures
• struct sd_card_t
SD card state. More...
• struct sdio_card_t
SDIO card state. More...
• struct mmc_card_t
SD card state. More...
• struct mmc_boot_config_t
MMC card boot configuration definition. More...
Macros
• #define FSL_SDMMC_DRIVER_VERSION (MAKE_VERSION(2U, 1U, 2U)) /∗2.1.2∗/
Driver version.
• #define FSL_SDMMC_DEFAULT_BLOCK_SIZE (512U)
Default block size.
• #define HOST_NOT_SUPPORT 0U
use this define to indicate the host not support feature
• #define HOST_SUPPORT 1U
use this define to indicate the host support feature
Enumerations
• enum _sdmmc_status {
kStatus_SDMMC_NotSupportYet = MAKE_STATUS(kStatusGroup_SDMMC, 0U),
kStatus_SDMMC_TransferFailed = MAKE_STATUS(kStatusGroup_SDMMC, 1U),
kStatus_SDMMC_SetCardBlockSizeFailed = MAKE_STATUS(kStatusGroup_SDMMC, 2U),
kStatus_SDMMC_HostNotSupport = MAKE_STATUS(kStatusGroup_SDMMC, 3U),
kStatus_SDMMC_CardNotSupport = MAKE_STATUS(kStatusGroup_SDMMC, 4U),
kStatus_SDMMC_AllSendCidFailed = MAKE_STATUS(kStatusGroup_SDMMC, 5U),
kStatus_SDMMC_SendRelativeAddressFailed = MAKE_STATUS(kStatusGroup_SDMMC, 6U),
kStatus_SDMMC_SendCsdFailed = MAKE_STATUS(kStatusGroup_SDMMC, 7U),
kStatus_SDMMC_SelectCardFailed = MAKE_STATUS(kStatusGroup_SDMMC, 8U),
kStatus_SDMMC_SendScrFailed = MAKE_STATUS(kStatusGroup_SDMMC, 9U),
kStatus_SDMMC_SetDataBusWidthFailed = MAKE_STATUS(kStatusGroup_SDMMC, 10U),
kStatus_SDMMC_GoIdleFailed = MAKE_STATUS(kStatusGroup_SDMMC, 11U),
kStatus_SDMMC_HandShakeOperationConditionFailed,
kStatus_SDMMC_SendApplicationCommandFailed,
kStatus_SDMMC_SwitchFailed = MAKE_STATUS(kStatusGroup_SDMMC, 14U),
kStatus_SDMMC_StopTransmissionFailed = MAKE_STATUS(kStatusGroup_SDMMC, 15U),
kStatus_SDMMC_WaitWriteCompleteFailed = MAKE_STATUS(kStatusGroup_SDMMC, 16U),
kStatus_SDMMC_SetBlockCountFailed = MAKE_STATUS(kStatusGroup_SDMMC, 17U),
kStatus_SDMMC_SetRelativeAddressFailed = MAKE_STATUS(kStatusGroup_SDMMC, 18U),
kStatus_SDMMC_SwitchBusTimingFailed = MAKE_STATUS(kStatusGroup_SDMMC, 19U),
kStatus_SDMMC_SendExtendedCsdFailed = MAKE_STATUS(kStatusGroup_SDMMC, 20U),
kStatus_SDMMC_ConfigureBootFailed = MAKE_STATUS(kStatusGroup_SDMMC, 21U),
kStatus_SDMMC_ConfigureExtendedCsdFailed = MAKE_STATUS(kStatusGroup_SDMMC, 22-
U),
kStatus_SDMMC_EnableHighCapacityEraseFailed,
kStatus_SDMMC_SendTestPatternFailed = MAKE_STATUS(kStatusGroup_SDMMC, 24U),
kStatus_SDMMC_ReceiveTestPatternFailed = MAKE_STATUS(kStatusGroup_SDMMC, 25U),
kStatus_SDMMC_SDIO_ResponseError = MAKE_STATUS(kStatusGroup_SDMMC, 26U),
kStatus_SDMMC_SDIO_InvalidArgument,
kStatus_SDMMC_SDIO_SendOperationConditionFail,
kStatus_SDMMC_InvalidVoltage = MAKE_STATUS(kStatusGroup_SDMMC, 29U),
kStatus_SDMMC_SDIO_SwitchHighSpeedFail = MAKE_STATUS(kStatusGroup_SDMMC, 30-
U),
kStatus_SDMMC_SDIO_ReadCISFail = MAKE_STATUS(kStatusGroup_SDMMC, 31U),
kStatus_SDMMC_SDIO_InvalidCard = MAKE_STATUS(kStatusGroup_SDMMC, 32U),
kStatus_SDMMC_TuningFail = MAKE_STATUS(kStatusGroup_SDMMC, 33U),
kStatus_SDMMC_SwitchVoltageFail = MAKE_STATUS(kStatusGroup_SDMMC, 34U),
kStatus_SDMMC_ReTuningRequest = MAKE_STATUS(kStatusGroup_SDMMC, 35U),
kStatus_SDMMC_SetDriverStrengthFail = MAKE_STATUS(kStatusGroup_SDMMC, 36U),
kStatus_SDMMC_SetPowerClassFail = MAKE_STATUS(kStatusGroup_SDMMC, 37U) }
SD/MMC card API’s running status.
• enum _sd_card_flag {
SDCARD Function
• status_t SD_Init (sd_card_t ∗card)
Initializes the card on a specific host controller.
• void SD_Deinit (sd_card_t ∗card)
Deinitializes the card.
• bool SD_CheckReadOnly (sd_card_t ∗card)
Checks whether the card is write-protected.
• status_t SD_ReadBlocks (sd_card_t ∗card, uint8_t ∗buffer, uint32_t startBlock, uint32_t block-
Count)
MMCCARD Function
• status_t MMC_Init (mmc_card_t ∗card)
Initializes the MMC card.
• void MMC_Deinit (mmc_card_t ∗card)
Deinitializes the card.
• bool MMC_CheckReadOnly (mmc_card_t ∗card)
Checks if the card is read-only.
• status_t MMC_ReadBlocks (mmc_card_t ∗card, uint8_t ∗buffer, uint32_t startBlock, uint32_-
t blockCount)
Reads data blocks from the card.
• status_t MMC_WriteBlocks (mmc_card_t ∗card, const uint8_t ∗buffer, uint32_t startBlock, uint32-
_t blockCount)
Writes data blocks to the card.
• status_t MMC_EraseGroups (mmc_card_t ∗card, uint32_t startGroup, uint32_t endGroup)
Erases groups of the card.
• status_t MMC_SelectPartition (mmc_card_t ∗card, mmc_access_partition_t partitionNumber)
Selects the partition to access.
• status_t MMC_SetBootConfig (mmc_card_t ∗card, const mmc_boot_config_t ∗config)
Configures the boot activity of the card.
• status_t SDIO_CardInActive (sdio_card_t ∗card)
set SDIO card to inactive state
• status_t SDIO_IO_Write_Direct (sdio_card_t ∗card, sdio_func_num_t func, uint32_t regAddr,
uint8_t ∗data, bool raw)
IO direct write transfer function.
• status_t SDIO_IO_Read_Direct (sdio_card_t ∗card, sdio_func_num_t func, uint32_t regAddr,
uint8_t ∗data)
IO direct read transfer function.
• status_t SDIO_IO_Write_Extended (sdio_card_t ∗card, sdio_func_num_t func, uint32_t regAddr,
uint8_t ∗buffer, uint32_t count, uint32_t flags)
IO extended write transfer function.
• status_t SDIO_IO_Read_Extended (sdio_card_t ∗card, sdio_func_num_t func, uint32_t regAddr,
uint8_t ∗buffer, uint32_t count, uint32_t flags)
IO extended read transfer function.
• status_t SDIO_GetCardCapability (sdio_card_t ∗card, sdio_func_num_t func)
get SDIO card capability
• status_t SDIO_SetBlockSize (sdio_card_t ∗card, sdio_func_num_t func, uint32_t blockSize)
set SDIO card block size
• status_t SDIO_CardReset (sdio_card_t ∗card)
set SDIO card reset
• status_t SDIO_SetDataBusWidth (sdio_card_t ∗card, sdio_bus_width_t busWidth)
set SDIO card data bus width
• status_t SDIO_SwitchToHighSpeed (sdio_card_t ∗card)
adaptor function
• static status_t HOST_NotSupport (void ∗parameter)
host not support function, this function is used for host not support feature
• status_t CardInsertDetect (HOST_TYPE ∗hostBase)
Detect card insert, only need for SD cases.
• status_t HOST_Init (void ∗host)
Init host controller.
• void HOST_Deinit (void ∗host)
Deinit host controller.
Define the card structure including the necessary fields to identify and describe the card.
Data Fields
• HOST_CONFIG host
Host information.
• bool isHostReady
use this flag to indicate if need host re-init or not
• uint32_t busClock_Hz
SD bus clock frequency united in Hz.
• uint32_t relativeAddress
Relative address of the card.
• uint32_t version
Card version.
• uint32_t flags
Flags in _sd_card_flag.
• uint32_t rawCid [4U]
Define the card structure including the necessary fields to identify and describe the card.
Data Fields
• HOST_CONFIG host
Host information.
• bool isHostReady
use this flag to indicate if need host re-init or not
• bool memPresentFlag
indicate if memory present
• uint32_t busClock_Hz
SD bus clock frequency united in Hz.
• uint32_t relativeAddress
Relative address of the card.
• uint8_t sdVersion
SD version.
• uint8_t sdioVersion
SDIO version.
• uint8_t cccrVersioin
CCCR version.
• uint8_t ioTotalNumber
total number of IO function
• uint32_t cccrflags
Flags in _sd_card_flag.
• uint32_t io0blockSize
record the io0 block size
• uint32_t ocr
Raw OCR content, only 24bit avalible for SDIO card.
• uint32_t commonCISPointer
point to common CIS
• sdio_fbr_t ioFBR [7U]
FBR table.
• sdio_common_cis_t commonCIS
CIS table.
• sdio_func_cis_t funcCIS [7U]
function CIS table
Define the card structure including the necessary fields to identify and describe the card.
Data Fields
• HOST_CONFIG host
Host information.
• bool isHostReady
use this flag to indicate if need host re-init or not
• uint32_t busClock_Hz
MMC bus clock united in Hz.
• uint32_t relativeAddress
Relative address of the card.
• bool enablePreDefinedBlockCount
Enable PRE-DEFINED block count when read/write.
• uint32_t flags
Capability flag in _mmc_card_flag.
• uint32_t rawCid [4U]
Raw CID content.
• uint32_t rawCsd [4U]
Raw CSD content.
• uint32_t rawExtendedCsd [MMC_EXTENDED_CSD_BYTES/4U]
Raw MMC Extended CSD content.
• uint32_t ocr
Raw OCR content.
• mmc_cid_t cid
CID.
• mmc_csd_t csd
CSD.
• mmc_extended_csd_t extendedCsd
Extended CSD.
• uint32_t blockSize
Card block size.
• uint32_t userPartitionBlocks
Card total block number in user partition.
• uint32_t bootPartitionBlocks
Boot partition size united as block size.
• uint32_t eraseGroupBlocks
Erase group size united as block size.
• mmc_access_partition_t currentPartition
Current access partition.
• mmc_voltage_window_t hostVoltageWindow
Host voltage window.
• mmc_high_speed_timing_t currentTiming
indicate the current host timing mode
Data Fields
• bool enableBootAck
Enable boot ACK.
• mmc_boot_partition_enable_t bootPartition
Boot partition.
• bool retainBootBusWidth
If retain boot bus width.
• mmc_data_bus_width_t bootDataBusWidth
Boot data bus width.
Enumerator
kStatus_SDMMC_NotSupportYet Haven’t supported.
kStatus_SDMMC_TransferFailed Send command failed.
kStatus_SDMMC_SetCardBlockSizeFailed Set block size failed.
kStatus_SDMMC_HostNotSupport Host doesn’t support.
kStatus_SDMMC_CardNotSupport Card doesn’t support.
kStatus_SDMMC_AllSendCidFailed Send CID failed.
kStatus_SDMMC_SendRelativeAddressFailed Send relative address failed.
Enumerator
kSD_SupportHighCapacityFlag Support high capacity.
kSD_Support4BitWidthFlag Support 4-bit data width.
kSD_SupportSdhcFlag Card is SDHC.
kSD_SupportSdxcFlag Card is SDXC.
kSD_SupportVoltage180v card support 1.8v voltage
kSD_SupportSetBlockCountCmd card support cmd23 flag
kSD_SupportSpeedClassControlCmd card support speed class control flag
Enumerator
kMMC_SupportHighSpeed26MHZFlag Support high speed 26MHZ.
kMMC_SupportHighSpeed52MHZFlag Support high speed 52MHZ.
kMMC_SupportHighSpeedDDR52MHZ180V300VFlag ddr 52MHZ 1.8V or 3.0V
kMMC_SupportHighSpeedDDR52MHZ120VFlag DDR 52MHZ 1.2V.
kMMC_SupportHS200200MHZ180VFlag HS200 ,200MHZ,1.8V.
kMMC_SupportHS200200MHZ120VFlag HS200, 200MHZ, 1.2V.
kMMC_SupportHS400DDR200MHZ180VFlag HS400, DDR, 200MHZ,1.8V.
kMMC_SupportHS400DDR200MHZ120VFlag HS400, DDR, 200MHZ,1.2V.
kMMC_SupportHighCapacityFlag Support high capacity.
kMMC_SupportAlternateBootFlag Support alternate boot.
kMMC_SupportDDRBootFlag support DDR boot flag
kMMC_SupportHighSpeedBootFlag support high speed boot flag
kMMC_DataBusWidth4BitFlag current data bus is 4 bit mode
kMMC_DataBusWidth8BitFlag current data bus is 8 bit mode
kMMC_DataBusWidth1BitFlag current data bus is 1 bit mode
Enumerator
kCARD_OperationVoltageNone indicate current voltage setting is not setting bu suser
kCARD_OperationVoltage330V card operation voltage around 3.3v
kCARD_OperationVoltage300V card operation voltage around 3.0v
kCARD_OperationVoltage180V card operation voltage around 31.8v
Enumerator
kHOST_EndianModeBig Big endian mode.
kHOST_EndianModeHalfWordBig Half word big endian mode.
kHOST_EndianModeLittle Little endian mode.
Parameters
Return values
Parameters
This function checks if the card is write-protected via the CSD register.
Parameters
Return values
This function reads blocks from the specific card with default block size defined by the SDHC_CARD_-
DEFAULT_BLOCK_SIZE.
Parameters
Return values
This function writes blocks to the specific card with default block size 512 bytes.
Parameters
Return values
This function erases blocks of the specific card with default block size 512 bytes.
Parameters
Return values
Parameters
Return values
Parameters
Parameters
Return values
Parameters
Return values
Parameters
Return values
Erase group is the smallest erase unit in MMC card. The erase range is [startGroup, endGroup].
Parameters
Return values
Parameters
Return values
Parameters
Return values
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_SDMMC_SDIO-
_InvalidArgument
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_SDMMC_SDIO-
_InvalidArgument
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_Set-
CardBlockSizeFailed
kStatus_SDMMC_SDIO-
_InvalidArgument
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_SDMMC_SDIO-
_SwitchHighSpeedFail
kStatus_Success
Parameters
Return values
kStatus_SDMMC_SDIO-
_ReadCISFail
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_Go-
IdleFailed
kStatus_SDMMC_Hand-
ShakeOperation-
ConditionFailed
kStatus_SDMMC_SDIO-
_InvalidCard
kStatus_SDMMC_SDIO-
_InvalidVoltage
kStatus_SDMMC_Send-
RelativeAddressFailed
kStatus_SDMMC_Select-
CardFailed
kStatus_SDMMC_SDIO-
_SwitchHighSpeedFail
kStatus_SDMMC_SDIO-
_ReadCISFail
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Return values
kStatus_SDMMC_-
TransferFailed
kStatus_Success
Parameters
Parameters
Return values
Parameters
Return values
Parameters
Return values
Parameters
Function groups
This function group implements the SD card functional API in the SPI mode.
/* Initializes card. */
if (kStatus_Success != SDSPI_Init(card))
{
SDSPI_Deinit(card)
return;
}
/* Read/Write card */
memset(g_testWriteBuffer, 0x17U, sizeof(g_testWriteBuffer));
while (true)
{
memset(g_testReadBuffer, 0U, sizeof(g_testReadBuffer));
Data Structures
• struct sdspi_command_t
SDSPI command. More...
• struct sdspi_host_t
SDSPI host state. More...
• struct sdspi_card_t
SD Card Structure. More...
Enumerations
• enum _sdspi_status {
kStatus_SDSPI_SetFrequencyFailed = MAKE_STATUS(kStatusGroup_SDSPI, 0U),
kStatus_SDSPI_ExchangeFailed = MAKE_STATUS(kStatusGroup_SDSPI, 1U),
kStatus_SDSPI_WaitReadyFailed = MAKE_STATUS(kStatusGroup_SDSPI, 2U),
kStatus_SDSPI_ResponseError = MAKE_STATUS(kStatusGroup_SDSPI, 3U),
kStatus_SDSPI_WriteProtected = MAKE_STATUS(kStatusGroup_SDSPI, 4U),
kStatus_SDSPI_GoIdleFailed = MAKE_STATUS(kStatusGroup_SDSPI, 5U),
kStatus_SDSPI_SendCommandFailed = MAKE_STATUS(kStatusGroup_SDSPI, 6U),
kStatus_SDSPI_ReadFailed = MAKE_STATUS(kStatusGroup_SDSPI, 7U),
kStatus_SDSPI_WriteFailed = MAKE_STATUS(kStatusGroup_SDSPI, 8U),
kStatus_SDSPI_SendInterfaceConditionFailed,
kStatus_SDSPI_SendOperationConditionFailed,
kStatus_SDSPI_ReadOcrFailed = MAKE_STATUS(kStatusGroup_SDSPI, 11U),
kStatus_SDSPI_SetBlockSizeFailed = MAKE_STATUS(kStatusGroup_SDSPI, 12U),
kStatus_SDSPI_SendCsdFailed = MAKE_STATUS(kStatusGroup_SDSPI, 13U),
kStatus_SDSPI_SendCidFailed = MAKE_STATUS(kStatusGroup_SDSPI, 14U),
kStatus_SDSPI_StopTransmissionFailed = MAKE_STATUS(kStatusGroup_SDSPI, 15U),
kStatus_SDSPI_SendApplicationCommandFailed }
SDSPI API status.
• enum _sdspi_card_flag {
kSDSPI_SupportHighCapacityFlag = (1U << 0U),
kSDSPI_SupportSdhcFlag = (1U << 1U),
kSDSPI_SupportSdxcFlag = (1U << 2U),
kSDSPI_SupportSdscFlag = (1U << 3U) }
SDSPI card flag.
• enum sdspi_response_type_t {
kSDSPI_ResponseTypeR1 = 0U,
kSDSPI_ResponseTypeR1b = 1U,
kSDSPI_ResponseTypeR2 = 2U,
kSDSPI_ResponseTypeR3 = 3U,
kSDSPI_ResponseTypeR7 = 4U }
SDSPI response type.
SDSPI Function
• status_t SDSPI_Init (sdspi_card_t ∗card)
Initializes the card on a specific SPI instance.
• void SDSPI_Deinit (sdspi_card_t ∗card)
Deinitializes the card.
• bool SDSPI_CheckReadOnly (sdspi_card_t ∗card)
Checks whether the card is write-protected.
• status_t SDSPI_ReadBlocks (sdspi_card_t ∗card, uint8_t ∗buffer, uint32_t startBlock, uint32_-
t blockCount)
Reads blocks from the specific card.
• status_t SDSPI_WriteBlocks (sdspi_card_t ∗card, uint8_t ∗buffer, uint32_t startBlock, uint32_t
blockCount)
Data Fields
• uint8_t index
Command index.
• uint32_t argument
Command argument.
• uint8_t responseType
Response type.
• uint8_t response [5U]
Response content.
Data Fields
• uint32_t busBaudRate
Bus baud rate.
• status_t(∗ setFrequency )(uint32_t frequency)
Set frequency of SPI.
• status_t(∗ exchange )(uint8_t ∗in, uint8_t ∗out, uint32_t size)
Exchange data over SPI.
• uint32_t(∗ getCurrentMilliseconds )(void)
Get current time in milliseconds.
Define the card structure including the necessary fields to identify and describe the card.
Data Fields
• sdspi_host_t ∗ host
Host state information.
• uint32_t relativeAddress
Relative address of the card.
• uint32_t flags
Flags defined in _sdspi_card_flag.
• uint8_t rawCid [16U]
Raw CID content.
• uint8_t rawCsd [16U]
Enumerator
kStatus_SDSPI_SetFrequencyFailed Set frequency failed.
kStatus_SDSPI_ExchangeFailed Exchange data on SPI bus failed.
kStatus_SDSPI_WaitReadyFailed Wait card ready failed.
kStatus_SDSPI_ResponseError Response is error.
kStatus_SDSPI_WriteProtected Write protected.
kStatus_SDSPI_GoIdleFailed Go idle failed.
kStatus_SDSPI_SendCommandFailed Send command failed.
kStatus_SDSPI_ReadFailed Read data failed.
kStatus_SDSPI_WriteFailed Write data failed.
kStatus_SDSPI_SendInterfaceConditionFailed Send interface condition failed.
kStatus_SDSPI_SendOperationConditionFailed Send operation condition failed.
kStatus_SDSPI_ReadOcrFailed Read OCR failed.
kStatus_SDSPI_SetBlockSizeFailed Set block size failed.
kStatus_SDSPI_SendCsdFailed Send CSD failed.
kStatus_SDSPI_SendCidFailed Send CID failed.
kStatus_SDSPI_StopTransmissionFailed Stop transmission failed.
kStatus_SDSPI_SendApplicationCommandFailed Send application command failed.
Enumerator
kSDSPI_SupportHighCapacityFlag Card is high capacity.
kSDSPI_SupportSdhcFlag Card is SDHC.
kSDSPI_SupportSdxcFlag Card is SDXC.
kSDSPI_SupportSdscFlag Card is SDSC.
Enumerator
kSDSPI_ResponseTypeR1 Response 1.
kSDSPI_ResponseTypeR1b Response 1 with busy.
kSDSPI_ResponseTypeR2 Response 2.
kSDSPI_ResponseTypeR3 Response 3.
kSDSPI_ResponseTypeR7 Response 7.
Return values
Return values
Return values
Return values
To initialize the debug console, call the DbgConsole_Init() function with these parameters. This function
automatically enables the module and the clock.
/*
* @brief Initializes the the peripheral used to debug messages.
*
* @param baseAddr Indicates which address of the peripheral is used to send debug messages.
* @param baudRate The desired baud rate in bits per second.
* @param device Low level device type for the debug console, can be one of:
* @arg DEBUG_CONSOLE_DEVICE_TYPE_UART,
* @arg DEBUG_CONSOLE_DEVICE_TYPE_LPUART,
* @arg DEBUG_CONSOLE_DEVICE_TYPE_LPSCI,
* @arg DEBUG_CONSOLE_DEVICE_TYPE_USBCDC.
* @param clkSrcFreq Frequency of peripheral source clock.
*
* @return Whether initialization was successful or not.
*/
status_t DbgConsole_Init(uint32_t baseAddr, uint32_t baudRate, uint8_t device, uint32_t clkSrcFreq)
DEBUG_CONSOLE_DEVICE_TYPE_NONE
DEBUG_CONSOLE_DEVICE_TYPE_LPSCI
DEBUG_CONSOLE_DEVICE_TYPE_UART
DEBUG_CONSOLE_DEVICE_TYPE_LPUART
DEBUG_CONSOLE_DEVICE_TYPE_USBCDC
After the initialization is successful, stdout and stdin are connected to the selected peripheral. The debug
console state is stored in the debug_console_state_t structure, such as shown here.
This example shows how to call the DbgConsole_Init() given the user configuration structure.
The debug console provides input and output functions to scan and print formatted data.
• Support a format specifier for PRINTF following this prototype " %[flags][width][.precision][length]specifier",
which is explained below
flags Description
- Left-justified within the given field width. Right-
justified is the default.
+ Forces to precede the result with a plus or minus
sign (+ or -) even for positive numbers. By default,
only negative numbers are preceded with a - sign.
(space) If no sign is written, a blank space is inserted be-
fore the value.
# Used with o, x, or X specifiers the value is pre-
ceded with 0, 0x, or 0X respectively for values
other than zero. Used with e, E and f, it forces
the written output to contain a decimal point even
if no digits would follow. By default, if no digits
follow, no decimal point is written. Used with g or
G the result is the same as with e or E but trailing
zeros are not removed.
0 Left-pads the number with zeroes (0) instead of
spaces, where padding is specified (see width sub-
specifier).
Width Description
(number) A minimum number of characters to be printed. If
the value to be printed is shorter than this number,
the result is padded with blank spaces. The value
is not truncated even if the result is larger.
∗ The width is not specified in the format string, but
as an additional integer value argument preceding
the argument that has to be formatted.
.precision Description
.number For integer specifiers (d, i, o, u, x, X) precision
specifies the minimum number of digits to be writ-
ten. If the value to be written is shorter than this
number, the result is padded with leading zeros.
The value is not truncated even if the result is
longer. A precision of 0 means that no character
is written for the value 0. For e, E, and f speci-
fiers this is the number of digits to be printed after
the decimal point. For g and G specifiers This
is the maximum number of significant digits to be
printed. For s this is the maximum number of
characters to be printed. By default, all characters
are printed until the ending null character is en-
countered. For c type it has no effect. When no
precision is specified, the default is 1. If the period
is specified without an explicit value for precision,
0 is assumed.
.∗ The precision is not specified in the format string,
but as an additional integer value argument pre-
ceding the argument that has to be formatted.
length Description
Do not support
specifier Description
d or i Signed decimal integer
f Decimal floating point
F Decimal floating point capital letters
x Unsigned hexadecimal integer
X Unsigned hexadecimal integer capital letters
o Signed octal
b Binary value
p Pointer address
u Unsigned decimal integer
c Character
s String of characters
n Nothing printed
• Support a format specifier for SCANF following this prototype " %[∗][width][length]specifier",
which is explained below
∗ Description
An optional starting asterisk indicates that the data is to be read from the stream but ignored. In other
words, it is not stored in the corresponding argument.
width Description
This specifies the maximum number of characters to be read in the current reading operation.
length Description
hh The argument is interpreted as a signed charac-
ter or unsigned character (only applies to integer
specifiers: i, d, o, u, x, and X).
h The argument is interpreted as a short integer
or unsigned short integer (only applies to integer
specifiers: i, d, o, u, x, and X).
l The argument is interpreted as a long integer or
unsigned long integer for integer specifiers (i, d,
o, u, x, and X) and as a wide character or wide
character string for specifiers c and s.
ll The argument is interpreted as a long long integer
or unsigned long long integer for integer specifiers
(i, d, o, u, x, and X) and as a wide character or
wide character string for specifiers c and s.
L The argument is interpreted as a long double (only
applies to floating point specifiers: e, E, f, g, and
G).
j or z or t Not supported
The debug console has its own printf/scanf/putchar/getchar functions which are defined in the header file.
This utility supports selecting toolchain’s printf/scanf or the MCUXpresso SDK printf/scanf.
ch = GETCHAR();
PUTCHAR(ch);
PRINTF("Execution timer: %s\n\rTime: %u ticks %2.5f milliseconds\n\rDONE\n\r", "1 day", 86400, 86.4);
void __assert_func(const char *file, int line, const char *func, const char *failedExpr)
{
PRINTF("ASSERT ERROR \" %s \": file \"%s\" Line \"%d\" function name \"%s\" \n", failedExpr, file ,
line, func);
for (;;)
{}
}
Note:
To use ’printf’ and ’scanf’ for GNUC Base, add file ’fsl_sbrk.c’ in path: ..\{package}\devices\{subset}\utilities\fsl-
_sbrk.c to your project.
Modules
• Semihosting
33.4 Semihosting
Semihosting is a mechanism for ARM targets to communicate input/output requests from application code
to a host computer running a debugger. This mechanism can be used, for example, to enable functions in
the C library, such as printf() and scanf(), to use the screen and keyboard of the host rather than having a
screen and keyboard on the target system.
NOTE: After the setting both "printf" and "scanf" are available for debugging.
Remove function fputc and fgetc is used to support KEIL in "fsl_debug_console.c" and add the following
code to project.
#pragma import(__use_no_semihosting_swi)
struct __FILE
{
int handle;
};
FILE __stdout;
FILE __stdin;
defsym=__heap_size__=0x2000")
SET(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}
--defsym=__heap_size__=0x2000")
G} --specs=rdimon.specs ")
Remove
target_link_libraries(semihosting_ARMGCC.elf debug nosys)
2. Run "build_debug.bat" to build project
(b) After the setting, press "enter". The PuTTY window now shows the printf() output.
#include "fsl_notifier.h"
...
...
...
return ret;
}
// Definition of the Power Manager user function.
status_t APP_PowerModeSwitch(notifier_user_config_t *targetConfig, void *userData)
{
...
...
...
}
...
...
...
...
...
// Main function.
int main(void)
{
// Define a notifier handle.
notifier_handle_t powerModeHandle;
// Callback configuration.
user_callback_data_t callbackData0;
stopConfig = vlprConfig;
stopConfig.mode = kAPP_PowerModeStop;
Data Structures
• struct notifier_notification_block_t
notification block passed to the registered callback function. More...
• struct notifier_callback_config_t
Callback configuration structure. More...
• struct notifier_handle_t
Notifier handle structure. More...
Typedefs
• typedef void notifier_user_config_t
Notifier user configuration type.
• typedef status_t(∗ notifier_user_function_t )(notifier_user_config_t ∗targetConfig, void ∗userData)
Notifier user function prototype Use this function to execute specific operations in configuration switch.
Enumerations
• enum _notifier_status {
kStatus_NOTIFIER_ErrorNotificationBefore,
kStatus_NOTIFIER_ErrorNotificationAfter }
Notifier error codes.
• enum notifier_policy_t {
kNOTIFIER_PolicyAgreement,
kNOTIFIER_PolicyForcible }
Notifier policies.
• enum notifier_notification_type_t {
kNOTIFIER_NotifyRecover = 0x00U,
kNOTIFIER_NotifyBefore = 0x01U,
kNOTIFIER_NotifyAfter = 0x02U }
Notification type.
• enum notifier_callback_type_t {
kNOTIFIER_CallbackBefore = 0x01U,
kNOTIFIER_CallbackAfter = 0x02U,
kNOTIFIER_CallbackBeforeAfter = 0x03U }
The callback type, which indicates kinds of notification the callback handles.
Functions
• status_t NOTIFIER_CreateHandle (notifier_handle_t ∗notifierHandle, notifier_user_config_t
∗∗configs, uint8_t configsNumber, notifier_callback_config_t ∗callbacks, uint8_t callbacksNumber,
notifier_user_function_t userFunction, void ∗userData)
Creates a Notifier handle.
• status_t NOTIFIER_SwitchConfig (notifier_handle_t ∗notifierHandle, uint8_t configIndex, notifier-
_policy_t policy)
Switches the configuration according to a pre-defined structure.
• uint8_t NOTIFIER_GetErrorCallbackIndex (notifier_handle_t ∗notifierHandle)
This function returns the last failed notification callback.
Data Fields
• notifier_user_config_t ∗ targetConfig
Pointer to target configuration.
• notifier_policy_t policy
Configure transition policy.
• notifier_notification_type_t notifyType
Configure notification type.
This structure holds the configuration of callbacks. Callbacks of this type are expected to be statically
allocated. This structure contains the following application-defined data. callback - pointer to the callback
function callbackType - specifies when the callback is called callbackData - pointer to the data passed to
the callback.
Data Fields
• notifier_callback_t callback
Pointer to the callback function.
• notifier_callback_type_t callbackType
Callback type.
• void ∗ callbackData
Pointer to the data passed to the callback.
Notifier handle structure. Contains data necessary for the Notifier proper function. Stores references to
registered configurations, callbacks, information about their numbers, user function, user data, and other
internal data. NOTIFIER_CreateHandle() must be called to initialize this handle.
Data Fields
• notifier_user_config_t ∗∗ configsTable
Pointer to configure table.
• uint8_t configsNumber
Number of configurations.
• notifier_callback_config_t ∗ callbacksTable
Pointer to callback table.
• uint8_t callbacksNumber
Maximum number of callback configurations.
• uint8_t errorCallbackIndex
Index of callback returns error.
• uint8_t currentConfigIndex
Index of current configuration.
• notifier_user_function_t userFunction
User function.
• void ∗ userData
User data passed to user function.
Reference of the user defined configuration is stored in an array; the notifier switches between these
configurations based on this array.
Before and after this function execution, different notification is sent to registered callbacks. If this func-
tion returns any error code, NOTIFIER_SwitchConfig() exits.
Parameters
Returns
An error code or kStatus_Success.
Declaration of a callback. It is common for registered callbacks. Reference to function of this type is part
of the notifier_callback_config_t callback configuration structure. Depending on callback type, function
of this prototype is called (see NOTIFIER_SwitchConfig()) before configuration switch, after it or in both
use cases to notify about the switch progress (see notifier_callback_type_t). When called, the type of the
notification is passed as a parameter along with the reference to the target configuration structure (see
notifier_notification_block_t) and any data passed during the callback registration. When notified before
the configuration switch, depending on the configuration switch policy (see notifier_policy_t), the callback
may deny the execution of the user function by returning an error code different than kStatus_Success (see
NOTIFIER_SwitchConfig()).
Parameters
Returns
An error code or kStatus_Success.
Enumerator
kStatus_NOTIFIER_ErrorNotificationBefore An error occurs during send "BEFORE" notifica-
tion.
kStatus_NOTIFIER_ErrorNotificationAfter An error occurs during send "AFTER" notification.
Defines whether the user function execution is forced or not. For kNOTIFIER_PolicyForcible, the user
function is executed regardless of the callback results, while kNOTIFIER_PolicyAgreement policy is used
to exit NOTIFIER_SwitchConfig() when any of the callbacks returns error code. See also NOTIFIER_-
SwitchConfig() description.
Enumerator
kNOTIFIER_PolicyAgreement NOTIFIER_SwitchConfig() method is exited when any of the call-
backs returns error code.
kNOTIFIER_PolicyForcible The user function is executed regardless of the results.
Enumerator
kNOTIFIER_NotifyRecover Notify IP to recover to previous work state.
kNOTIFIER_NotifyBefore Notify IP that configuration setting is going to change.
kNOTIFIER_NotifyAfter Notify IP that configuration setting has been changed.
Used in the callback configuration structure (notifier_callback_config_t) to specify when the registered
callback is called during configuration switch initiated by the NOTIFIER_SwitchConfig(). Callback can
be invoked in following situations.
• Before the configuration switch (Callback return value can affect NOTIFIER_SwitchConfig() exe-
cution. See the NOTIFIER_SwitchConfig() and notifier_policy_t documentation).
• After an unsuccessful attempt to switch configuration
• After a successful configuration switch
Enumerator
kNOTIFIER_CallbackBefore Callback handles BEFORE notification.
kNOTIFIER_CallbackAfter Callback handles AFTER notification.
kNOTIFIER_CallbackBeforeAfter Callback handles BEFORE and AFTER notification.
Parameters
Returns
An error Code or kStatus_Success.
This function sets the system to the target configuration. Before transition, the Notifier sends notifications
to all callbacks registered to the callback table. Callbacks are invoked in the following order: All registered
callbacks are notified ordered by index in the callbacks array. The same order is used for before and after
switch notifications. The notifications before the configuration switch can be used to obtain confirmation
about the change from registered callbacks. If any registered callback denies the configuration change,
further execution of this function depends on the notifier policy: the configuration change is either forced
(kNOTIFIER_PolicyForcible) or exited (kNOTIFIER_PolicyAgreement). When configuration change is
forced, the result of the before switch notifications are ignored. If an agreement is required, if any call-
back returns an error code, further notifications before switch notifications are cancelled and all already
notified callbacks are re-invoked. The index of the callback which returned error code during pre-switch
notifications is stored (any error codes during callbacks re-invocation are ignored) and NOTIFIER_Get-
ErrorCallback() can be used to get it. Regardless of the policies, if any callback returns an error code,
an error code indicating in which phase the error occurred is returned when NOTIFIER_SwitchConfig()
exits.
Parameters
Returns
An error code or kStatus_Success.
This function returns an index of the last callback that failed during the configuration switch while the last
NOTIFIER_SwitchConfig() was called. If the last NOTIFIER_SwitchConfig() call ended successfully
value equal to callbacks number is returned. The returned value represents an index in the array of static
call-backs.
Parameters
Returns
Callback Index of the last failed callback or value equal to callbacks count.
To initialize the Shell middleware, call the SHELL_Init() function with these parameters. This function
automatically enables the middleware.
Then, after the initialization was successful, call a command to control MCUs.
This example shows how to call the SHELL_Init() given the user configuration structure.
Commands Description
Help Lists all commands which are supported by Shell.
Exit Exits the Shell program.
strCompare Compares the two input strings.
Clears a command.
Data Structures
• struct p_shell_context_t
Data structure for Shell environment. More...
• struct shell_command_context_t
User command data structure. More...
• struct shell_command_context_list_t
Structure list command. More...
Macros
• #define SHELL_USE_HISTORY (0U)
Macro to set on/off history feature.
• #define SHELL_SEARCH_IN_HIST (1U)
Macro to set on/off history feature.
• #define SHELL_USE_FILE_STREAM (0U)
Macro to select method stream.
• #define SHELL_AUTO_COMPLETE (1U)
Macro to set on/off auto-complete feature.
• #define SHELL_BUFFER_SIZE (64U)
Macro to set console buffer size.
• #define SHELL_MAX_ARGS (8U)
Macro to set maximum arguments in command.
• #define SHELL_HIST_MAX (3U)
Macro to set maximum count of history commands.
• #define SHELL_MAX_CMD (20U)
Macro to set maximum count of commands.
• #define SHELL_OPTIONAL_PARAMS (0xFF)
Macro to bypass arguments check.
Typedefs
• typedef void(∗ send_data_cb_t )(uint8_t ∗buf, uint32_t len)
Shell user send data callback prototype.
• typedef void(∗ recv_data_cb_t )(uint8_t ∗buf, uint32_t len)
Enumerations
• enum fun_key_status_t {
kSHELL_Normal = 0U,
kSHELL_Special = 1U,
kSHELL_Function = 2U }
A type for the handle special key.
Data Fields
• char ∗ prompt
Prompt string.
• enum _fun_key_status stat
Special key status.
• char line [SHELL_BUFFER_SIZE]
Consult buffer.
• uint8_t cmd_num
Number of user commands.
• uint8_t l_pos
Total line position.
• uint8_t c_pos
Current line position.
• send_data_cb_t send_data_func
Send data interface operation.
• recv_data_cb_t recv_data_func
Receive data interface operation.
• uint16_t hist_current
Current history command in hist buff.
• uint16_t hist_count
Data Fields
It should start with the command itself, and end with "\r\n". For example "help: Returns a list of all the
commands\r\n".
Data Fields
Enumerator
kSHELL_Normal Normal key.
kSHELL_Special Special key.
kSHELL_Function Function key.
This function must be called before calling all other Shell functions. Call operation the Shell commands
with user-defined settings. The example below shows how to set up the middleware Shell and how to call
the SHELL_Init function by passing in these parameters. This is an example.
* shell_context_struct user_context;
* SHELL_Init(&user_context, SendDataFunc, ReceiveDataFunc, "SHELL>> ");
*
Parameters
Parameters
Returns
-1 if error or 0 if success
Main loop for Shell; After this function is called, Shell begins to initialize the basic variables and starts to
work.
Parameters
Returns
This function does not return until Shell command exit was called.
NXP, the NXP logo, Freescale, the Freescale logo, Kinetis, Processor
Expert are trademarks of NXP B.V. Tower is a trademark of NXP. All
other product or service names are the property of their respective
owners. ARM, ARM Powered logo, and Cortex are registered
trademarks of ARM Limited (or its subsidiaries) in the EU and/or
elsewhere. All rights reserved.