From 56e86c626df3dbf74c1021210636a7c5d92a49ce Mon Sep 17 00:00:00 2001 From: Dominik Sliwa Date: Tue, 30 Oct 2018 16:31:29 +0100 Subject: move to cmake Signed-off-by: Dominik Sliwa --- drivers/include/fsl_adc16.h | 525 ++++++++++++ drivers/include/fsl_clock.h | 1540 +++++++++++++++++++++++++++++++++++ drivers/include/fsl_cmp.h | 343 ++++++++ drivers/include/fsl_cmt.h | 401 +++++++++ drivers/include/fsl_common.h | 348 ++++++++ drivers/include/fsl_crc.h | 193 +++++ drivers/include/fsl_dac.h | 378 +++++++++ drivers/include/fsl_dmamux.h | 200 +++++ drivers/include/fsl_dspi.h | 1180 +++++++++++++++++++++++++++ drivers/include/fsl_dspi_edma.h | 281 +++++++ drivers/include/fsl_dspi_freertos.h | 128 +++ drivers/include/fsl_edma.h | 910 +++++++++++++++++++++ drivers/include/fsl_ewm.h | 241 ++++++ drivers/include/fsl_flash.h | 1386 +++++++++++++++++++++++++++++++ drivers/include/fsl_flexbus.h | 265 ++++++ drivers/include/fsl_flexcan.h | 1081 ++++++++++++++++++++++++ drivers/include/fsl_ftm.h | 973 ++++++++++++++++++++++ drivers/include/fsl_gpio.h | 440 ++++++++++ drivers/include/fsl_i2c.h | 794 ++++++++++++++++++ drivers/include/fsl_i2c_edma.h | 132 +++ drivers/include/fsl_i2c_freertos.h | 128 +++ drivers/include/fsl_llwu.h | 320 ++++++++ drivers/include/fsl_lptmr.h | 370 +++++++++ drivers/include/fsl_mpu.h | 422 ++++++++++ drivers/include/fsl_pdb.h | 576 +++++++++++++ drivers/include/fsl_pit.h | 354 ++++++++ drivers/include/fsl_pmc.h | 421 ++++++++++ drivers/include/fsl_port.h | 431 ++++++++++ drivers/include/fsl_rcm.h | 431 ++++++++++ drivers/include/fsl_rtc.h | 414 ++++++++++ drivers/include/fsl_sai.h | 849 +++++++++++++++++++ drivers/include/fsl_sai_edma.h | 231 ++++++ drivers/include/fsl_sdhc.h | 1095 +++++++++++++++++++++++++ drivers/include/fsl_sim.h | 127 +++ drivers/include/fsl_smc.h | 456 +++++++++++ drivers/include/fsl_sysmpu.h | 435 ++++++++++ drivers/include/fsl_tsi_v2.h | 777 ++++++++++++++++++ drivers/include/fsl_uart.h | 777 ++++++++++++++++++ drivers/include/fsl_uart_edma.h | 190 +++++ drivers/include/fsl_uart_freertos.h | 166 ++++ drivers/include/fsl_vref.h | 256 ++++++ drivers/include/fsl_wdog.h | 433 ++++++++++ 42 files changed, 21398 insertions(+) create mode 100644 drivers/include/fsl_adc16.h create mode 100644 drivers/include/fsl_clock.h create mode 100644 drivers/include/fsl_cmp.h create mode 100644 drivers/include/fsl_cmt.h create mode 100644 drivers/include/fsl_common.h create mode 100644 drivers/include/fsl_crc.h create mode 100644 drivers/include/fsl_dac.h create mode 100644 drivers/include/fsl_dmamux.h create mode 100644 drivers/include/fsl_dspi.h create mode 100644 drivers/include/fsl_dspi_edma.h create mode 100644 drivers/include/fsl_dspi_freertos.h create mode 100644 drivers/include/fsl_edma.h create mode 100644 drivers/include/fsl_ewm.h create mode 100644 drivers/include/fsl_flash.h create mode 100644 drivers/include/fsl_flexbus.h create mode 100644 drivers/include/fsl_flexcan.h create mode 100644 drivers/include/fsl_ftm.h create mode 100644 drivers/include/fsl_gpio.h create mode 100644 drivers/include/fsl_i2c.h create mode 100644 drivers/include/fsl_i2c_edma.h create mode 100644 drivers/include/fsl_i2c_freertos.h create mode 100644 drivers/include/fsl_llwu.h create mode 100644 drivers/include/fsl_lptmr.h create mode 100644 drivers/include/fsl_mpu.h create mode 100644 drivers/include/fsl_pdb.h create mode 100644 drivers/include/fsl_pit.h create mode 100644 drivers/include/fsl_pmc.h create mode 100644 drivers/include/fsl_port.h create mode 100644 drivers/include/fsl_rcm.h create mode 100644 drivers/include/fsl_rtc.h create mode 100644 drivers/include/fsl_sai.h create mode 100644 drivers/include/fsl_sai_edma.h create mode 100644 drivers/include/fsl_sdhc.h create mode 100644 drivers/include/fsl_sim.h create mode 100644 drivers/include/fsl_smc.h create mode 100644 drivers/include/fsl_sysmpu.h create mode 100644 drivers/include/fsl_tsi_v2.h create mode 100644 drivers/include/fsl_uart.h create mode 100644 drivers/include/fsl_uart_edma.h create mode 100644 drivers/include/fsl_uart_freertos.h create mode 100644 drivers/include/fsl_vref.h create mode 100644 drivers/include/fsl_wdog.h (limited to 'drivers/include') diff --git a/drivers/include/fsl_adc16.h b/drivers/include/fsl_adc16.h new file mode 100644 index 0000000..ea62c55 --- /dev/null +++ b/drivers/include/fsl_adc16.h @@ -0,0 +1,525 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_ADC16_H_ +#define _FSL_ADC16_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup adc16 + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief ADC16 driver version 2.0.0. */ +#define FSL_ADC16_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/*! + * @brief Channel status flags. + */ +enum _adc16_channel_status_flags +{ + kADC16_ChannelConversionDoneFlag = ADC_SC1_COCO_MASK, /*!< Conversion done. */ +}; + +/*! + * @brief Converter status flags. + */ +enum _adc16_status_flags +{ + kADC16_ActiveFlag = ADC_SC2_ADACT_MASK, /*!< Converter is active. */ +#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION + kADC16_CalibrationFailedFlag = ADC_SC3_CALF_MASK, /*!< Calibration is failed. */ +#endif /* FSL_FEATURE_ADC16_HAS_CALIBRATION */ +}; + +#if defined(FSL_FEATURE_ADC16_HAS_MUX_SELECT) && FSL_FEATURE_ADC16_HAS_MUX_SELECT +/*! + * @brief Channel multiplexer mode for each channel. + * + * 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. + */ +typedef enum _adc_channel_mux_mode +{ + kADC16_ChannelMuxA = 0U, /*!< For channel with channel mux a. */ + kADC16_ChannelMuxB = 1U, /*!< For channel with channel mux b. */ +} adc16_channel_mux_mode_t; +#endif /* FSL_FEATURE_ADC16_HAS_MUX_SELECT */ + +/*! + * @brief Clock divider for the converter. + */ +typedef enum _adc16_clock_divider +{ + kADC16_ClockDivider1 = 0U, /*!< For divider 1 from the input clock to the module. */ + kADC16_ClockDivider2 = 1U, /*!< For divider 2 from the input clock to the module. */ + kADC16_ClockDivider4 = 2U, /*!< For divider 4 from the input clock to the module. */ + kADC16_ClockDivider8 = 3U, /*!< For divider 8 from the input clock to the module. */ +} adc16_clock_divider_t; + +/*! + *@brief Converter's resolution. + */ +typedef enum _adc16_resolution +{ + /* This group of enumeration is for internal use which is related to register setting. */ + kADC16_Resolution8or9Bit = 0U, /*!< Single End 8-bit or Differential Sample 9-bit. */ + kADC16_Resolution12or13Bit = 1U, /*!< Single End 12-bit or Differential Sample 13-bit. */ + kADC16_Resolution10or11Bit = 2U, /*!< Single End 10-bit or Differential Sample 11-bit. */ + + /* This group of enumeration is for a public user. */ + kADC16_ResolutionSE8Bit = kADC16_Resolution8or9Bit, /*!< Single End 8-bit. */ + kADC16_ResolutionSE12Bit = kADC16_Resolution12or13Bit, /*!< Single End 12-bit. */ + kADC16_ResolutionSE10Bit = kADC16_Resolution10or11Bit, /*!< Single End 10-bit. */ +#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE + kADC16_ResolutionDF9Bit = kADC16_Resolution8or9Bit, /*!< Differential Sample 9-bit. */ + kADC16_ResolutionDF13Bit = kADC16_Resolution12or13Bit, /*!< Differential Sample 13-bit. */ + kADC16_ResolutionDF11Bit = kADC16_Resolution10or11Bit, /*!< Differential Sample 11-bit. */ +#endif /* FSL_FEATURE_ADC16_HAS_DIFF_MODE */ + +#if defined(FSL_FEATURE_ADC16_MAX_RESOLUTION) && (FSL_FEATURE_ADC16_MAX_RESOLUTION >= 16U) + /* 16-bit is supported by default. */ + kADC16_Resolution16Bit = 3U, /*!< Single End 16-bit or Differential Sample 16-bit. */ + kADC16_ResolutionSE16Bit = kADC16_Resolution16Bit, /*!< Single End 16-bit. */ +#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE + kADC16_ResolutionDF16Bit = kADC16_Resolution16Bit, /*!< Differential Sample 16-bit. */ +#endif /* FSL_FEATURE_ADC16_HAS_DIFF_MODE */ +#endif /* FSL_FEATURE_ADC16_MAX_RESOLUTION >= 16U */ +} adc16_resolution_t; + +/*! + * @brief Clock source. + */ +typedef enum _adc16_clock_source +{ + kADC16_ClockSourceAlt0 = 0U, /*!< Selection 0 of the clock source. */ + kADC16_ClockSourceAlt1 = 1U, /*!< Selection 1 of the clock source. */ + kADC16_ClockSourceAlt2 = 2U, /*!< Selection 2 of the clock source. */ + kADC16_ClockSourceAlt3 = 3U, /*!< Selection 3 of the clock source. */ + + /* Chip defined clock source */ + kADC16_ClockSourceAsynchronousClock = kADC16_ClockSourceAlt3, /*!< Using internal asynchronous clock. */ +} adc16_clock_source_t; + +/*! + * @brief Long sample mode. + */ +typedef enum _adc16_long_sample_mode +{ + kADC16_LongSampleCycle24 = 0U, /*!< 20 extra ADCK cycles, 24 ADCK cycles total. */ + kADC16_LongSampleCycle16 = 1U, /*!< 12 extra ADCK cycles, 16 ADCK cycles total. */ + kADC16_LongSampleCycle10 = 2U, /*!< 6 extra ADCK cycles, 10 ADCK cycles total. */ + kADC16_LongSampleCycle6 = 3U, /*!< 2 extra ADCK cycles, 6 ADCK cycles total. */ + kADC16_LongSampleDisabled = 4U, /*!< Disable the long sample feature. */ +} adc16_long_sample_mode_t; + +/*! + * @brief Reference voltage source. + */ +typedef enum _adc16_reference_voltage_source +{ + kADC16_ReferenceVoltageSourceVref = 0U, /*!< For external pins pair of VrefH and VrefL. */ + kADC16_ReferenceVoltageSourceValt = 1U, /*!< For alternate reference pair of ValtH and ValtL. */ +} adc16_reference_voltage_source_t; + +#if defined(FSL_FEATURE_ADC16_HAS_HW_AVERAGE) && FSL_FEATURE_ADC16_HAS_HW_AVERAGE +/*! + * @brief Hardware average mode. + */ +typedef enum _adc16_hardware_average_mode +{ + kADC16_HardwareAverageCount4 = 0U, /*!< For hardware average with 4 samples. */ + kADC16_HardwareAverageCount8 = 1U, /*!< For hardware average with 8 samples. */ + kADC16_HardwareAverageCount16 = 2U, /*!< For hardware average with 16 samples. */ + kADC16_HardwareAverageCount32 = 3U, /*!< For hardware average with 32 samples. */ + kADC16_HardwareAverageDisabled = 4U, /*!< Disable the hardware average feature.*/ +} adc16_hardware_average_mode_t; +#endif /* FSL_FEATURE_ADC16_HAS_HW_AVERAGE */ + +/*! + * @brief Hardware compare mode. + */ +typedef enum _adc16_hardware_compare_mode +{ + kADC16_HardwareCompareMode0 = 0U, /*!< x < value1. */ + kADC16_HardwareCompareMode1 = 1U, /*!< x > value1. */ + kADC16_HardwareCompareMode2 = 2U, /*!< if value1 <= value2, then x < value1 || x > value2; + else, value1 > x > value2. */ + kADC16_HardwareCompareMode3 = 3U, /*!< if value1 <= value2, then value1 <= x <= value2; + else x >= value1 || x <= value2. */ +} adc16_hardware_compare_mode_t; + +#if defined(FSL_FEATURE_ADC16_HAS_PGA) && FSL_FEATURE_ADC16_HAS_PGA +/*! + * @brief PGA's Gain mode. + */ +typedef enum _adc16_pga_gain +{ + kADC16_PGAGainValueOf1 = 0U, /*!< For amplifier gain of 1. */ + kADC16_PGAGainValueOf2 = 1U, /*!< For amplifier gain of 2. */ + kADC16_PGAGainValueOf4 = 2U, /*!< For amplifier gain of 4. */ + kADC16_PGAGainValueOf8 = 3U, /*!< For amplifier gain of 8. */ + kADC16_PGAGainValueOf16 = 4U, /*!< For amplifier gain of 16. */ + kADC16_PGAGainValueOf32 = 5U, /*!< For amplifier gain of 32. */ + kADC16_PGAGainValueOf64 = 6U, /*!< For amplifier gain of 64. */ +} adc16_pga_gain_t; +#endif /* FSL_FEATURE_ADC16_HAS_PGA */ + +/*! + * @brief ADC16 converter configuration. + */ +typedef struct _adc16_config +{ + 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. */ +} adc16_config_t; + +/*! + * @brief ADC16 Hardware comparison configuration. + */ +typedef struct _adc16_hardware_compare_config +{ + adc16_hardware_compare_mode_t hardwareCompareMode; /*!< Select the hardware compare mode. + See "adc16_hardware_compare_mode_t". */ + int16_t value1; /*!< Setting value1 for hardware compare mode. */ + int16_t value2; /*!< Setting value2 for hardware compare mode. */ +} adc16_hardware_compare_config_t; + +/*! + * @brief ADC16 channel conversion configuration. + */ +typedef struct _adc16_channel_config +{ + uint32_t channelNumber; /*!< Setting the conversion channel number. The available range is 0-31. + See channel connection information for each chip in Reference + Manual document. */ + bool enableInterruptOnConversionCompleted; /*!< Generate an interrupt request once the conversion is completed. */ +#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE + bool enableDifferentialConversion; /*!< Using Differential sample mode. */ +#endif /* FSL_FEATURE_ADC16_HAS_DIFF_MODE */ +} adc16_channel_config_t; + +#if defined(FSL_FEATURE_ADC16_HAS_PGA) && FSL_FEATURE_ADC16_HAS_PGA +/*! + * @brief ADC16 programmable gain amplifier configuration. + */ +typedef struct _adc16_pga_config +{ + adc16_pga_gain_t pgaGain; /*!< Setting PGA gain. */ + bool enableRunInNormalMode; /*!< Enable PGA working in normal mode, or low power mode by default. */ +#if defined(FSL_FEATURE_ADC16_HAS_PGA_CHOPPING) && FSL_FEATURE_ADC16_HAS_PGA_CHOPPING + bool disablePgaChopping; /*!< Disable the PGA chopping function. + The PGA employs chopping to remove/reduce offset and 1/f noise and offers + an offset measurement configuration that aids the offset calibration. */ +#endif /* FSL_FEATURE_ADC16_HAS_PGA_CHOPPING */ +#if defined(FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT) && FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT + bool enableRunInOffsetMeasurement; /*!< Enable the PGA working in offset measurement mode. + When this feature is enabled, the PGA disconnects itself from the external + inputs and auto-configures into offset measurement mode. With this field + set, run the ADC in the recommended settings and enable the maximum hardware + averaging to get the PGA offset number. The output is the + (PGA offset * (64+1)) for the given PGA setting. */ +#endif /* FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT */ +} adc16_pga_config_t; +#endif /* FSL_FEATURE_ADC16_HAS_PGA */ + +#if defined(__cplusplus) +extern "C" { +#endif + +/******************************************************************************* + * API + ******************************************************************************/ + +/*! + * @name Initialization + * @{ + */ + +/*! + * @brief Initializes the ADC16 module. + * + * @param base ADC16 peripheral base address. + * @param config Pointer to configuration structure. See "adc16_config_t". + */ +void ADC16_Init(ADC_Type *base, const adc16_config_t *config); + +/*! + * @brief De-initializes the ADC16 module. + * + * @param base ADC16 peripheral base address. + */ +void ADC16_Deinit(ADC_Type *base); + +/*! + * @brief Gets an available pre-defined settings for the converter's configuration. + * + * This function initializes the converter configuration structure with available settings. The default values are as follows. + * @code + * 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; + * @endcode + * @param config Pointer to the configuration structure. + */ +void ADC16_GetDefaultConfig(adc16_config_t *config); + +#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION +/*! + * @brief Automates the hardware calibration. + * + * 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. + * + * @param base ADC16 peripheral base address. + * + * @return Execution status. + * @retval kStatus_Success Calibration is done successfully. + * @retval kStatus_Fail Calibration has failed. + */ +status_t ADC16_DoAutoCalibration(ADC_Type *base); +#endif /* FSL_FEATURE_ADC16_HAS_CALIBRATION */ + +#if defined(FSL_FEATURE_ADC16_HAS_OFFSET_CORRECTION) && FSL_FEATURE_ADC16_HAS_OFFSET_CORRECTION +/*! + * @brief Sets the offset value for the conversion result. + * + * 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. + * + * @param base ADC16 peripheral base address. + * @param value Setting offset value. + */ +static inline void ADC16_SetOffsetValue(ADC_Type *base, int16_t value) +{ + base->OFS = (uint32_t)(value); +} +#endif /* FSL_FEATURE_ADC16_HAS_OFFSET_CORRECTION */ + +/* @} */ + +/*! + * @name Advanced Features + * @{ + */ + +#if defined(FSL_FEATURE_ADC16_HAS_DMA) && FSL_FEATURE_ADC16_HAS_DMA +/*! + * @brief Enables generating the DMA trigger when the conversion is complete. + * + * @param base ADC16 peripheral base address. + * @param enable Switcher of the DMA feature. "true" means enabled, "false" means not enabled. + */ +static inline void ADC16_EnableDMA(ADC_Type *base, bool enable) +{ + if (enable) + { + base->SC2 |= ADC_SC2_DMAEN_MASK; + } + else + { + base->SC2 &= ~ADC_SC2_DMAEN_MASK; + } +} +#endif /* FSL_FEATURE_ADC16_HAS_DMA */ + +/*! + * @brief Enables the hardware trigger mode. + * + * @param base ADC16 peripheral base address. + * @param enable Switcher of the hardware trigger feature. "true" means enabled, "false" means not enabled. + */ +static inline void ADC16_EnableHardwareTrigger(ADC_Type *base, bool enable) +{ + if (enable) + { + base->SC2 |= ADC_SC2_ADTRG_MASK; + } + else + { + base->SC2 &= ~ADC_SC2_ADTRG_MASK; + } +} + +#if defined(FSL_FEATURE_ADC16_HAS_MUX_SELECT) && FSL_FEATURE_ADC16_HAS_MUX_SELECT +/*! + * @brief Sets the channel mux mode. + * + * Some sample pins share the same channel index. The channel mux mode decides which pin is used for an + * indicated channel. + * + * @param base ADC16 peripheral base address. + * @param mode Setting channel mux mode. See "adc16_channel_mux_mode_t". + */ +void ADC16_SetChannelMuxMode(ADC_Type *base, adc16_channel_mux_mode_t mode); +#endif /* FSL_FEATURE_ADC16_HAS_MUX_SELECT */ + +/*! + * @brief Configures the hardware compare mode. + * + * 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. + * + * @param base ADC16 peripheral base address. + * @param config Pointer to the "adc16_hardware_compare_config_t" structure. Passing "NULL" disables the feature. + */ +void ADC16_SetHardwareCompareConfig(ADC_Type *base, const adc16_hardware_compare_config_t *config); + +#if defined(FSL_FEATURE_ADC16_HAS_HW_AVERAGE) && FSL_FEATURE_ADC16_HAS_HW_AVERAGE +/*! + * @brief Sets the hardware average mode. + * + * The hardware average mode provides a way to process the conversion result automatically by using hardware. The multiple + * conversion results are accumulated and averaged internally making them easier to read. + * + * @param base ADC16 peripheral base address. + * @param mode Setting the hardware average mode. See "adc16_hardware_average_mode_t". + */ +void ADC16_SetHardwareAverage(ADC_Type *base, adc16_hardware_average_mode_t mode); +#endif /* FSL_FEATURE_ADC16_HAS_HW_AVERAGE */ + +#if defined(FSL_FEATURE_ADC16_HAS_PGA) && FSL_FEATURE_ADC16_HAS_PGA +/*! + * @brief Configures the PGA for the converter's front end. + * + * @param base ADC16 peripheral base address. + * @param config Pointer to the "adc16_pga_config_t" structure. Passing "NULL" disables the feature. + */ +void ADC16_SetPGAConfig(ADC_Type *base, const adc16_pga_config_t *config); +#endif /* FSL_FEATURE_ADC16_HAS_PGA */ + +/*! + * @brief Gets the status flags of the converter. + * + * @param base ADC16 peripheral base address. + * + * @return Flags' mask if indicated flags are asserted. See "_adc16_status_flags". + */ +uint32_t ADC16_GetStatusFlags(ADC_Type *base); + +/*! + * @brief Clears the status flags of the converter. + * + * @param base ADC16 peripheral base address. + * @param mask Mask value for the cleared flags. See "_adc16_status_flags". + */ +void ADC16_ClearStatusFlags(ADC_Type *base, uint32_t mask); + +/* @} */ + +/*! + * @name Conversion Channel + * @{ + */ + +/*! + * @brief Configures the conversion channel. + * + * 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. + * + * @param base ADC16 peripheral base address. + * @param channelGroup Channel group index. + * @param config Pointer to the "adc16_channel_config_t" structure for the conversion channel. + */ +void ADC16_SetChannelConfig(ADC_Type *base, uint32_t channelGroup, const adc16_channel_config_t *config); + +/*! + * @brief Gets the conversion value. + * + * @param base ADC16 peripheral base address. + * @param channelGroup Channel group index. + * + * @return Conversion value. + */ +static inline uint32_t ADC16_GetChannelConversionValue(ADC_Type *base, uint32_t channelGroup) +{ + assert(channelGroup < ADC_R_COUNT); + + return base->R[channelGroup]; +} + +/*! + * @brief Gets the status flags of channel. + * + * @param base ADC16 peripheral base address. + * @param channelGroup Channel group index. + * + * @return Flags' mask if indicated flags are asserted. See "_adc16_channel_status_flags". + */ +uint32_t ADC16_GetChannelStatusFlags(ADC_Type *base, uint32_t channelGroup); + +/* @} */ + +#if defined(__cplusplus) +} +#endif +/*! + * @} + */ +#endif /* _FSL_ADC16_H_ */ diff --git a/drivers/include/fsl_clock.h b/drivers/include/fsl_clock.h new file mode 100644 index 0000000..8f5a577 --- /dev/null +++ b/drivers/include/fsl_clock.h @@ -0,0 +1,1540 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright (c) 2016 - 2017 , NXP + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_CLOCK_H_ +#define _FSL_CLOCK_H_ + +#include "fsl_common.h" + +/*! @addtogroup clock */ +/*! @{ */ + +/*! @file */ + +/******************************************************************************* + * Configurations + ******************************************************************************/ + +/*! @brief Configures whether to check a parameter in a function. + * + * Some MCG settings must be changed with conditions, for example: + * 1. MCGIRCLK settings, such as the source, divider, and the trim value should not change when + * MCGIRCLK is used as a system clock source. + * 2. MCG_C7[OSCSEL] should not be changed when the external reference clock is used + * as a system clock source. For example, in FBE/BLPE/PBE modes. + * 3. The users should only switch between the supported clock modes. + * + * MCG functions check the parameter and MCG status before setting, if not allowed + * to change, the functions return error. The parameter checking increases code size, + * if code size is a critical requirement, change #MCG_CONFIG_CHECK_PARAM to 0 to + * disable parameter checking. + */ +#ifndef MCG_CONFIG_CHECK_PARAM +#define MCG_CONFIG_CHECK_PARAM 0U +#endif + +/*! @brief Configure whether driver controls clock + * + * 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. + */ +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)) +#define FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL 0 +#endif + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief CLOCK driver version 2.2.1. */ +#define FSL_CLOCK_DRIVER_VERSION (MAKE_VERSION(2, 2, 1)) +/*@}*/ + +/*! @brief External XTAL0 (OSC0) clock frequency. + * + * The XTAL0/EXTAL0 (OSC0) clock frequency in Hz. When the clock is set up, use the + * function CLOCK_SetXtal0Freq to set the value in the clock driver. For example, + * if XTAL0 is 8 MHz: + * @code + * CLOCK_InitOsc0(...); // Set up the OSC0 + * CLOCK_SetXtal0Freq(80000000); // Set the XTAL0 value to the clock driver. + * @endcode + * + * 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. + */ +extern uint32_t g_xtal0Freq; + +/*! @brief External XTAL32/EXTAL32/RTC_CLKIN 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. + */ +extern uint32_t g_xtal32Freq; + +#if (defined(OSC) && !(defined(OSC0))) +#define OSC0 OSC +#endif + +/*! @brief Clock ip name array for DMAMUX. */ +#define DMAMUX_CLOCKS \ + { \ + kCLOCK_Dmamux0 \ + } + +/*! @brief Clock ip name array for RTC. */ +#define RTC_CLOCKS \ + { \ + kCLOCK_Rtc0 \ + } + +/*! @brief Clock ip name array for PORT. */ +#define PORT_CLOCKS \ + { \ + kCLOCK_PortA, kCLOCK_PortB, kCLOCK_PortC, kCLOCK_PortD, kCLOCK_PortE \ + } + +/*! @brief Clock ip name array for SAI. */ +#define SAI_CLOCKS \ + { \ + kCLOCK_Sai0 \ + } + +/*! @brief Clock ip name array for FLEXBUS. */ +#define FLEXBUS_CLOCKS \ + { \ + kCLOCK_Flexbus0 \ + } + +/*! @brief Clock ip name array for TSI. */ +#define TSI_CLOCKS \ + { \ + kCLOCK_Tsi0 \ + } + +/*! @brief Clock ip name array for EWM. */ +#define EWM_CLOCKS \ + { \ + kCLOCK_Ewm0 \ + } + +/*! @brief Clock ip name array for PIT. */ +#define PIT_CLOCKS \ + { \ + kCLOCK_Pit0 \ + } + +/*! @brief Clock ip name array for DSPI. */ +#define DSPI_CLOCKS \ + { \ + kCLOCK_Spi0, kCLOCK_Spi1, kCLOCK_Spi2 \ + } + +/*! @brief Clock ip name array for LPTMR. */ +#define LPTMR_CLOCKS \ + { \ + kCLOCK_Lptmr0 \ + } + +/*! @brief Clock ip name array for SDHC. */ +#define SDHC_CLOCKS \ + { \ + kCLOCK_Sdhc0 \ + } + +/*! @brief Clock ip name array for FTM. */ +#define FTM_CLOCKS \ + { \ + kCLOCK_Ftm0, kCLOCK_Ftm1, kCLOCK_Ftm2 \ + } + +/*! @brief Clock ip name array for LLWU. */ +#define LLWU_CLOCKS \ + { \ + kCLOCK_Llwu0 \ + } + +/*! @brief Clock ip name array for EDMA. */ +#define EDMA_CLOCKS \ + { \ + kCLOCK_Dma0 \ + } + +/*! @brief Clock ip name array for FLEXCAN. */ +#define FLEXCAN_CLOCKS \ + { \ + kCLOCK_Flexcan0, kCLOCK_Flexcan1 \ + } + +/*! @brief Clock ip name array for DAC. */ +#define DAC_CLOCKS \ + { \ + kCLOCK_Dac0, kCLOCK_Dac1 \ + } + +/*! @brief Clock ip name array for ADC16. */ +#define ADC16_CLOCKS \ + { \ + kCLOCK_Adc0, kCLOCK_Adc1 \ + } + +/*! @brief Clock ip name array for MPU. */ +#define SYSMPU_CLOCKS \ + { \ + kCLOCK_Sysmpu0 \ + } + +/*! @brief Clock ip name array for VREF. */ +#define VREF_CLOCKS \ + { \ + kCLOCK_Vref0 \ + } + +/*! @brief Clock ip name array for CMT. */ +#define CMT_CLOCKS \ + { \ + kCLOCK_Cmt0 \ + } + +/*! @brief Clock ip name array for UART. */ +#define UART_CLOCKS \ + { \ + kCLOCK_Uart0, kCLOCK_Uart1, kCLOCK_Uart2, kCLOCK_Uart3, kCLOCK_Uart4, kCLOCK_Uart5 \ + } + +/*! @brief Clock ip name array for CRC. */ +#define CRC_CLOCKS \ + { \ + kCLOCK_Crc0 \ + } + +/*! @brief Clock ip name array for I2C. */ +#define I2C_CLOCKS \ + { \ + kCLOCK_I2c0, kCLOCK_I2c1 \ + } + +/*! @brief Clock ip name array for PDB. */ +#define PDB_CLOCKS \ + { \ + kCLOCK_Pdb0 \ + } + +/*! @brief Clock ip name array for FTF. */ +#define FTF_CLOCKS \ + { \ + kCLOCK_Ftf0 \ + } + +/*! @brief Clock ip name array for CMP. */ +#define CMP_CLOCKS \ + { \ + kCLOCK_Cmp0, kCLOCK_Cmp1, kCLOCK_Cmp2 \ + } + +/*! + * @brief LPO clock frequency. + */ +#define LPO_CLK_FREQ 1000U + +/*! @brief Peripherals clock source definition. */ +#define SYS_CLK kCLOCK_CoreSysClk +#define BUS_CLK kCLOCK_BusClk + +#define I2C0_CLK_SRC BUS_CLK +#define I2C1_CLK_SRC BUS_CLK +#define DSPI0_CLK_SRC BUS_CLK +#define DSPI1_CLK_SRC BUS_CLK +#define DSPI2_CLK_SRC BUS_CLK +#define UART0_CLK_SRC SYS_CLK +#define UART1_CLK_SRC SYS_CLK +#define UART2_CLK_SRC BUS_CLK +#define UART3_CLK_SRC BUS_CLK +#define UART4_CLK_SRC BUS_CLK +#define UART5_CLK_SRC BUS_CLK + +/*! @brief Clock name used to get clock frequency. */ +typedef enum _clock_name +{ + + /* ----------------------------- System layer clock -------------------------------*/ + kCLOCK_CoreSysClk, /*!< Core/system clock */ + kCLOCK_PlatClk, /*!< Platform clock */ + kCLOCK_BusClk, /*!< Bus clock */ + kCLOCK_FlexBusClk, /*!< FlexBus clock */ + kCLOCK_FlashClk, /*!< Flash clock */ + kCLOCK_FastPeriphClk, /*!< Fast peripheral clock */ + kCLOCK_PllFllSelClk, /*!< The clock after SIM[PLLFLLSEL]. */ + + /* ---------------------------------- OSC clock -----------------------------------*/ + kCLOCK_Er32kClk, /*!< External reference 32K clock (ERCLK32K) */ + kCLOCK_Osc0ErClk, /*!< OSC0 external reference clock (OSC0ERCLK) */ + kCLOCK_Osc1ErClk, /*!< OSC1 external reference clock (OSC1ERCLK) */ + kCLOCK_Osc0ErClkUndiv, /*!< OSC0 external reference undivided clock(OSC0ERCLK_UNDIV). */ + + /* ----------------------------- MCG and MCG-Lite clock ---------------------------*/ + kCLOCK_McgFixedFreqClk, /*!< MCG fixed frequency clock (MCGFFCLK) */ + kCLOCK_McgInternalRefClk, /*!< MCG internal reference clock (MCGIRCLK) */ + kCLOCK_McgFllClk, /*!< MCGFLLCLK */ + kCLOCK_McgPll0Clk, /*!< MCGPLL0CLK */ + kCLOCK_McgPll1Clk, /*!< MCGPLL1CLK */ + kCLOCK_McgExtPllClk, /*!< EXT_PLLCLK */ + kCLOCK_McgPeriphClk, /*!< MCG peripheral clock (MCGPCLK) */ + kCLOCK_McgIrc48MClk, /*!< MCG IRC48M clock */ + + /* --------------------------------- Other clock ----------------------------------*/ + kCLOCK_LpoClk, /*!< LPO clock */ + +} clock_name_t; + +/*! @brief USB clock source definition. */ +typedef enum _clock_usb_src +{ + kCLOCK_UsbSrcPll0 = SIM_SOPT2_USBSRC(1U) | SIM_SOPT2_PLLFLLSEL(1U), /*!< Use PLL0. */ + kCLOCK_UsbSrcExt = SIM_SOPT2_USBSRC(0U) /*!< Use USB_CLKIN. */ +} clock_usb_src_t; + +/*------------------------------------------------------------------------------ + + clock_gate_t definition: + + 31 16 0 + ----------------------------------------------------------------- + | SIM_SCGC register offset | control bit offset in SCGC | + ----------------------------------------------------------------- + + For example, the SDHC clock gate is controlled by SIM_SCGC3[17], the + SIM_SCGC3 offset in SIM is 0x1030, then kCLOCK_GateSdhc0 is defined as + + kCLOCK_GateSdhc0 = (0x1030 << 16) | 17; + +------------------------------------------------------------------------------*/ + +#define CLK_GATE_REG_OFFSET_SHIFT 16U +#define CLK_GATE_REG_OFFSET_MASK 0xFFFF0000U +#define CLK_GATE_BIT_SHIFT_SHIFT 0U +#define CLK_GATE_BIT_SHIFT_MASK 0x0000FFFFU + +#define CLK_GATE_DEFINE(reg_offset, bit_shift) \ + ((((reg_offset) << CLK_GATE_REG_OFFSET_SHIFT) & CLK_GATE_REG_OFFSET_MASK) | \ + (((bit_shift) << CLK_GATE_BIT_SHIFT_SHIFT) & CLK_GATE_BIT_SHIFT_MASK)) + +#define CLK_GATE_ABSTRACT_REG_OFFSET(x) (((x)&CLK_GATE_REG_OFFSET_MASK) >> CLK_GATE_REG_OFFSET_SHIFT) +#define CLK_GATE_ABSTRACT_BITS_SHIFT(x) (((x)&CLK_GATE_BIT_SHIFT_MASK) >> CLK_GATE_BIT_SHIFT_SHIFT) + +/*! @brief Clock gate name used for CLOCK_EnableClock/CLOCK_DisableClock. */ +typedef enum _clock_ip_name +{ + kCLOCK_IpInvalid = 0U, + kCLOCK_Uart4 = CLK_GATE_DEFINE(0x1028U, 10U), + kCLOCK_Uart5 = CLK_GATE_DEFINE(0x1028U, 11U), + + kCLOCK_Dac0 = CLK_GATE_DEFINE(0x102CU, 12U), + kCLOCK_Dac1 = CLK_GATE_DEFINE(0x102CU, 13U), + + kCLOCK_Flexcan1 = CLK_GATE_DEFINE(0x1030U, 4U), + kCLOCK_Spi2 = CLK_GATE_DEFINE(0x1030U, 12U), + kCLOCK_Sdhc0 = CLK_GATE_DEFINE(0x1030U, 17U), + kCLOCK_Ftm2 = CLK_GATE_DEFINE(0x1030U, 24U), + kCLOCK_Adc1 = CLK_GATE_DEFINE(0x1030U, 27U), + + kCLOCK_Ewm0 = CLK_GATE_DEFINE(0x1034U, 1U), + kCLOCK_Cmt0 = CLK_GATE_DEFINE(0x1034U, 2U), + kCLOCK_I2c0 = CLK_GATE_DEFINE(0x1034U, 6U), + kCLOCK_I2c1 = CLK_GATE_DEFINE(0x1034U, 7U), + kCLOCK_Uart0 = CLK_GATE_DEFINE(0x1034U, 10U), + kCLOCK_Uart1 = CLK_GATE_DEFINE(0x1034U, 11U), + kCLOCK_Uart2 = CLK_GATE_DEFINE(0x1034U, 12U), + kCLOCK_Uart3 = CLK_GATE_DEFINE(0x1034U, 13U), + kCLOCK_Usbfs0 = CLK_GATE_DEFINE(0x1034U, 18U), + kCLOCK_Cmp0 = CLK_GATE_DEFINE(0x1034U, 19U), + kCLOCK_Cmp1 = CLK_GATE_DEFINE(0x1034U, 19U), + kCLOCK_Cmp2 = CLK_GATE_DEFINE(0x1034U, 19U), + kCLOCK_Vref0 = CLK_GATE_DEFINE(0x1034U, 20U), + kCLOCK_Llwu0 = CLK_GATE_DEFINE(0x1034U, 28U), + + kCLOCK_Lptmr0 = CLK_GATE_DEFINE(0x1038U, 0U), + kCLOCK_Tsi0 = CLK_GATE_DEFINE(0x1038U, 5U), + kCLOCK_PortA = CLK_GATE_DEFINE(0x1038U, 9U), + kCLOCK_PortB = CLK_GATE_DEFINE(0x1038U, 10U), + kCLOCK_PortC = CLK_GATE_DEFINE(0x1038U, 11U), + kCLOCK_PortD = CLK_GATE_DEFINE(0x1038U, 12U), + kCLOCK_PortE = CLK_GATE_DEFINE(0x1038U, 13U), + + kCLOCK_Ftf0 = CLK_GATE_DEFINE(0x103CU, 0U), + kCLOCK_Dmamux0 = CLK_GATE_DEFINE(0x103CU, 1U), + kCLOCK_Flexcan0 = CLK_GATE_DEFINE(0x103CU, 4U), + kCLOCK_Spi0 = CLK_GATE_DEFINE(0x103CU, 12U), + kCLOCK_Spi1 = CLK_GATE_DEFINE(0x103CU, 13U), + kCLOCK_Sai0 = CLK_GATE_DEFINE(0x103CU, 15U), + kCLOCK_Crc0 = CLK_GATE_DEFINE(0x103CU, 18U), + kCLOCK_Usbdcd0 = CLK_GATE_DEFINE(0x103CU, 21U), + kCLOCK_Pdb0 = CLK_GATE_DEFINE(0x103CU, 22U), + kCLOCK_Pit0 = CLK_GATE_DEFINE(0x103CU, 23U), + kCLOCK_Ftm0 = CLK_GATE_DEFINE(0x103CU, 24U), + kCLOCK_Ftm1 = CLK_GATE_DEFINE(0x103CU, 25U), + kCLOCK_Adc0 = CLK_GATE_DEFINE(0x103CU, 27U), + kCLOCK_Rtc0 = CLK_GATE_DEFINE(0x103CU, 29U), + + kCLOCK_Flexbus0 = CLK_GATE_DEFINE(0x1040U, 0U), + kCLOCK_Dma0 = CLK_GATE_DEFINE(0x1040U, 1U), + kCLOCK_Sysmpu0 = CLK_GATE_DEFINE(0x1040U, 2U), +} clock_ip_name_t; + +/*!@brief SIM configuration structure for clock setting. */ +typedef struct _sim_clock_config +{ + uint8_t pllFllSel; /*!< PLL/FLL/IRC48M selection. */ + uint8_t er32kSrc; /*!< ERCLK32K source selection. */ + uint32_t clkdiv1; /*!< SIM_CLKDIV1. */ +} sim_clock_config_t; + +/*! @brief OSC work mode. */ +typedef enum _osc_mode +{ + kOSC_ModeExt = 0U, /*!< Use an external clock. */ +#if (defined(MCG_C2_EREFS_MASK) && !(defined(MCG_C2_EREFS0_MASK))) + kOSC_ModeOscLowPower = MCG_C2_EREFS_MASK, /*!< Oscillator low power. */ +#else + kOSC_ModeOscLowPower = MCG_C2_EREFS0_MASK, /*!< Oscillator low power. */ +#endif + kOSC_ModeOscHighGain = 0U +#if (defined(MCG_C2_EREFS_MASK) && !(defined(MCG_C2_EREFS0_MASK))) + | + MCG_C2_EREFS_MASK +#else + | + MCG_C2_EREFS0_MASK +#endif +#if (defined(MCG_C2_HGO_MASK) && !(defined(MCG_C2_HGO0_MASK))) + | + MCG_C2_HGO_MASK, /*!< Oscillator high gain. */ +#else + | + MCG_C2_HGO0_MASK, /*!< Oscillator high gain. */ +#endif +} osc_mode_t; + +/*! @brief Oscillator capacitor load setting.*/ +enum _osc_cap_load +{ + kOSC_Cap2P = OSC_CR_SC2P_MASK, /*!< 2 pF capacitor load */ + kOSC_Cap4P = OSC_CR_SC4P_MASK, /*!< 4 pF capacitor load */ + kOSC_Cap8P = OSC_CR_SC8P_MASK, /*!< 8 pF capacitor load */ + kOSC_Cap16P = OSC_CR_SC16P_MASK /*!< 16 pF capacitor load */ +}; + +/*! @brief OSCERCLK enable mode. */ +enum _oscer_enable_mode +{ + kOSC_ErClkEnable = OSC_CR_ERCLKEN_MASK, /*!< Enable. */ + kOSC_ErClkEnableInStop = OSC_CR_EREFSTEN_MASK /*!< Enable in stop mode. */ +}; + +/*! @brief OSC configuration for OSCERCLK. */ +typedef struct _oscer_config +{ + uint8_t enableMode; /*!< OSCERCLK enable mode. OR'ed value of @ref _oscer_enable_mode. */ + +} oscer_config_t; + +/*! + * @brief OSC Initialization Configuration Structure + * + * Defines the configuration data structure to initialize the OSC. + * When porting to a new board, set the following members + * according to the board setting: + * 1. freq: The external frequency. + * 2. workMode: The OSC module mode. + */ +typedef struct _osc_config +{ + 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. */ +} osc_config_t; + +/*! @brief MCG FLL reference clock source select. */ +typedef enum _mcg_fll_src +{ + kMCG_FllSrcExternal, /*!< External reference clock is selected */ + kMCG_FllSrcInternal /*!< The slow internal reference clock is selected */ +} mcg_fll_src_t; + +/*! @brief MCG internal reference clock select */ +typedef enum _mcg_irc_mode +{ + kMCG_IrcSlow, /*!< Slow internal reference clock selected */ + kMCG_IrcFast /*!< Fast internal reference clock selected */ +} mcg_irc_mode_t; + +/*! @brief MCG DCO Maximum Frequency with 32.768 kHz Reference */ +typedef enum _mcg_dmx32 +{ + kMCG_Dmx32Default, /*!< DCO has a default range of 25% */ + kMCG_Dmx32Fine /*!< DCO is fine-tuned for maximum frequency with 32.768 kHz reference */ +} mcg_dmx32_t; + +/*! @brief MCG DCO range select */ +typedef enum _mcg_drs +{ + kMCG_DrsLow, /*!< Low frequency range */ + kMCG_DrsMid, /*!< Mid frequency range */ + kMCG_DrsMidHigh, /*!< Mid-High frequency range */ + kMCG_DrsHigh /*!< High frequency range */ +} mcg_drs_t; + +/*! @brief MCG PLL reference clock select */ +typedef enum _mcg_pll_ref_src +{ + kMCG_PllRefOsc0, /*!< Selects OSC0 as PLL reference clock */ + kMCG_PllRefOsc1 /*!< Selects OSC1 as PLL reference clock */ +} mcg_pll_ref_src_t; + +/*! @brief MCGOUT clock source. */ +typedef enum _mcg_clkout_src +{ + kMCG_ClkOutSrcOut, /*!< Output of the FLL is selected (reset default) */ + kMCG_ClkOutSrcInternal, /*!< Internal reference clock is selected */ + kMCG_ClkOutSrcExternal, /*!< External reference clock is selected */ +} mcg_clkout_src_t; + +/*! @brief MCG Automatic Trim Machine Select */ +typedef enum _mcg_atm_select +{ + kMCG_AtmSel32k, /*!< 32 kHz Internal Reference Clock selected */ + kMCG_AtmSel4m /*!< 4 MHz Internal Reference Clock selected */ +} mcg_atm_select_t; + +/*! @brief MCG OSC Clock Select */ +typedef enum _mcg_oscsel +{ + kMCG_OscselOsc, /*!< Selects System Oscillator (OSCCLK) */ + kMCG_OscselRtc, /*!< Selects 32 kHz RTC Oscillator */ +} mcg_oscsel_t; + +/*! @brief MCG PLLCS select */ +typedef enum _mcg_pll_clk_select +{ + kMCG_PllClkSelPll0, /*!< PLL0 output clock is selected */ + kMCG_PllClkSelPll1 /* PLL1 output clock is selected */ +} mcg_pll_clk_select_t; + +/*! @brief MCG clock monitor mode. */ +typedef enum _mcg_monitor_mode +{ + kMCG_MonitorNone, /*!< Clock monitor is disabled. */ + kMCG_MonitorInt, /*!< Trigger interrupt when clock lost. */ + kMCG_MonitorReset /*!< System reset when clock lost. */ +} mcg_monitor_mode_t; + +/*! @brief MCG status. */ +enum _mcg_status +{ + kStatus_MCG_ModeUnreachable = MAKE_STATUS(kStatusGroup_MCG, 0), /*!< Can't switch to target mode. */ + kStatus_MCG_ModeInvalid = MAKE_STATUS(kStatusGroup_MCG, 1), /*!< Current mode invalid for the specific + function. */ + kStatus_MCG_AtmBusClockInvalid = MAKE_STATUS(kStatusGroup_MCG, 2), /*!< Invalid bus clock for ATM. */ + kStatus_MCG_AtmDesiredFreqInvalid = MAKE_STATUS(kStatusGroup_MCG, 3), /*!< Invalid desired frequency for ATM. */ + kStatus_MCG_AtmIrcUsed = MAKE_STATUS(kStatusGroup_MCG, 4), /*!< IRC is used when using ATM. */ + kStatus_MCG_AtmHardwareFail = MAKE_STATUS(kStatusGroup_MCG, 5), /*!< Hardware fail occurs during ATM. */ + kStatus_MCG_SourceUsed = MAKE_STATUS(kStatusGroup_MCG, 6) /*!< Can't change the clock source because + it is in use. */ +}; + +/*! @brief MCG status flags. */ +enum _mcg_status_flags_t +{ + kMCG_Osc0LostFlag = (1U << 0U), /*!< OSC0 lost. */ + kMCG_Osc0InitFlag = (1U << 1U), /*!< OSC0 crystal initialized. */ + kMCG_RtcOscLostFlag = (1U << 4U), /*!< RTC OSC lost. */ + kMCG_Pll0LostFlag = (1U << 5U), /*!< PLL0 lost. */ + kMCG_Pll0LockFlag = (1U << 6U), /*!< PLL0 locked. */ +}; + +/*! @brief MCG internal reference clock (MCGIRCLK) enable mode definition. */ +enum _mcg_irclk_enable_mode +{ + kMCG_IrclkEnable = MCG_C1_IRCLKEN_MASK, /*!< MCGIRCLK enable. */ + kMCG_IrclkEnableInStop = MCG_C1_IREFSTEN_MASK /*!< MCGIRCLK enable in stop mode. */ +}; + +/*! @brief MCG PLL clock enable mode definition. */ +enum _mcg_pll_enable_mode +{ + kMCG_PllEnableIndependent = MCG_C5_PLLCLKEN0_MASK, /*!< MCGPLLCLK enable independent of the + MCG clock mode. Generally, 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 = MCG_C5_PLLSTEN0_MASK /*!< MCGPLLCLK enable in STOP mode. */ +}; + +/*! @brief MCG mode definitions */ +typedef enum _mcg_mode +{ + kMCG_ModeFEI = 0U, /*!< FEI - FLL Engaged Internal */ + kMCG_ModeFBI, /*!< FBI - FLL Bypassed Internal */ + kMCG_ModeBLPI, /*!< BLPI - Bypassed Low Power Internal */ + kMCG_ModeFEE, /*!< FEE - FLL Engaged External */ + kMCG_ModeFBE, /*!< FBE - FLL Bypassed External */ + kMCG_ModeBLPE, /*!< BLPE - Bypassed Low Power External */ + kMCG_ModePBE, /*!< PBE - PLL Bypassed External */ + kMCG_ModePEE, /*!< PEE - PLL Engaged External */ + kMCG_ModeError /*!< Unknown mode */ +} mcg_mode_t; + +/*! @brief MCG PLL configuration. */ +typedef struct _mcg_pll_config +{ + uint8_t enableMode; /*!< Enable mode. OR'ed value of @ref _mcg_pll_enable_mode. */ + uint8_t prdiv; /*!< Reference divider PRDIV. */ + uint8_t vdiv; /*!< VCO divider VDIV. */ +} mcg_pll_config_t; + +/*! @brief MCG mode change configuration structure + * + * 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. + */ +typedef struct _mcg_config +{ + mcg_mode_t mcgMode; /*!< MCG mode. */ + + /* ----------------------- MCGIRCCLK settings ------------------------ */ + uint8_t irclkEnableMode; /*!< MCGIRCLK enable mode. */ + mcg_irc_mode_t ircs; /*!< Source, MCG_C2[IRCS]. */ + uint8_t fcrdiv; /*!< Divider, MCG_SC[FCRDIV]. */ + + /* ------------------------ MCG FLL settings ------------------------- */ + 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_oscsel_t oscsel; /*!< OSC select MCG_C7[OSCSEL]. */ + + /* ------------------------ MCG PLL settings ------------------------- */ + mcg_pll_config_t pll0Config; /*!< MCGPLL0CLK configuration. */ + +} mcg_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*! + * @brief Enable the clock for specific IP. + * + * @param name Which clock to enable, see \ref clock_ip_name_t. + */ +static inline void CLOCK_EnableClock(clock_ip_name_t name) +{ + uint32_t regAddr = SIM_BASE + CLK_GATE_ABSTRACT_REG_OFFSET((uint32_t)name); + (*(volatile uint32_t *)regAddr) |= (1U << CLK_GATE_ABSTRACT_BITS_SHIFT((uint32_t)name)); +} + +/*! + * @brief Disable the clock for specific IP. + * + * @param name Which clock to disable, see \ref clock_ip_name_t. + */ +static inline void CLOCK_DisableClock(clock_ip_name_t name) +{ + uint32_t regAddr = SIM_BASE + CLK_GATE_ABSTRACT_REG_OFFSET((uint32_t)name); + (*(volatile uint32_t *)regAddr) &= ~(1U << CLK_GATE_ABSTRACT_BITS_SHIFT((uint32_t)name)); +} + +/*! + * @brief Set ERCLK32K source. + * + * @param src The value to set ERCLK32K clock source. + */ +static inline void CLOCK_SetEr32kClock(uint32_t src) +{ + SIM->SOPT1 = ((SIM->SOPT1 & ~SIM_SOPT1_OSC32KSEL_MASK) | SIM_SOPT1_OSC32KSEL(src)); +} + +/*! + * @brief Set SDHC0 clock source. + * + * @param src The value to set SDHC0 clock source. + */ +static inline void CLOCK_SetSdhc0Clock(uint32_t src) +{ + SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_SDHCSRC_MASK) | SIM_SOPT2_SDHCSRC(src)); +} + +/*! + * @brief Set debug trace clock source. + * + * @param src The value to set debug trace clock source. + */ +static inline void CLOCK_SetTraceClock(uint32_t src) +{ + SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_TRACECLKSEL_MASK) | SIM_SOPT2_TRACECLKSEL(src)); +} + +/*! + * @brief Set PLLFLLSEL clock source. + * + * @param src The value to set PLLFLLSEL clock source. + */ +static inline void CLOCK_SetPllFllSelClock(uint32_t src) +{ + SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_PLLFLLSEL_MASK) | SIM_SOPT2_PLLFLLSEL(src)); +} +/*! + * @brief Set CLKOUT source. + * + * @param src The value to set CLKOUT source. + */ +static inline void CLOCK_SetClkOutClock(uint32_t src) +{ + SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_CLKOUTSEL_MASK) | SIM_SOPT2_CLKOUTSEL(src)); +} + +/*! + * @brief Set RTC_CLKOUT source. + * + * @param src The value to set RTC_CLKOUT source. + */ +static inline void CLOCK_SetRtcClkOutClock(uint32_t src) +{ + SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_RTCCLKOUTSEL_MASK) | SIM_SOPT2_RTCCLKOUTSEL(src)); +} + +/*! @brief Enable USB FS clock. + * + * @param src USB FS clock source. + * @param freq The frequency specified by src. + * @retval true The clock is set successfully. + * @retval false The clock source is invalid to get proper USB FS clock. + */ +bool CLOCK_EnableUsbfs0Clock(clock_usb_src_t src, uint32_t freq); + +/*! @brief Disable USB FS clock. + * + * Disable USB FS clock. + */ +static inline void CLOCK_DisableUsbfs0Clock(void) +{ + CLOCK_DisableClock(kCLOCK_Usbfs0); +} + +/*! + * @brief System clock divider + * + * Set the SIM_CLKDIV1[OUTDIV1], SIM_CLKDIV1[OUTDIV2], SIM_CLKDIV1[OUTDIV3], SIM_CLKDIV1[OUTDIV4]. + * + * @param outdiv1 Clock 1 output divider value. + * + * @param outdiv2 Clock 2 output divider value. + * + * @param outdiv3 Clock 3 output divider value. + * + * @param outdiv4 Clock 4 output divider value. + */ +static inline void CLOCK_SetOutDiv(uint32_t outdiv1, uint32_t outdiv2, uint32_t outdiv3, uint32_t outdiv4) +{ + SIM->CLKDIV1 = SIM_CLKDIV1_OUTDIV1(outdiv1) | SIM_CLKDIV1_OUTDIV2(outdiv2) | SIM_CLKDIV1_OUTDIV3(outdiv3) | + SIM_CLKDIV1_OUTDIV4(outdiv4); +} + +/*! + * @brief Gets the clock frequency for a specific clock name. + * + * 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. + * + * @param clockName Clock names defined in clock_name_t + * @return Clock frequency value in Hertz + */ +uint32_t CLOCK_GetFreq(clock_name_t clockName); + +/*! + * @brief Get the core clock or system clock frequency. + * + * @return Clock frequency in Hz. + */ +uint32_t CLOCK_GetCoreSysClkFreq(void); + +/*! + * @brief Get the platform clock frequency. + * + * @return Clock frequency in Hz. + */ +uint32_t CLOCK_GetPlatClkFreq(void); + +/*! + * @brief Get the bus clock frequency. + * + * @return Clock frequency in Hz. + */ +uint32_t CLOCK_GetBusClkFreq(void); + +/*! + * @brief Get the flexbus clock frequency. + * + * @return Clock frequency in Hz. + */ +uint32_t CLOCK_GetFlexBusClkFreq(void); + +/*! + * @brief Get the flash clock frequency. + * + * @return Clock frequency in Hz. + */ +uint32_t CLOCK_GetFlashClkFreq(void); + +/*! + * @brief Get the output clock frequency selected by SIM[PLLFLLSEL]. + * + * @return Clock frequency in Hz. + */ +uint32_t CLOCK_GetPllFllSelClkFreq(void); + +/*! + * @brief Get the external reference 32K clock frequency (ERCLK32K). + * + * @return Clock frequency in Hz. + */ +uint32_t CLOCK_GetEr32kClkFreq(void); + +/*! + * @brief Get the OSC0 external reference clock frequency (OSC0ERCLK). + * + * @return Clock frequency in Hz. + */ +uint32_t CLOCK_GetOsc0ErClkFreq(void); + +/*! + * @brief Set the clock configure in SIM module. + * + * This function sets system layer clock settings in SIM module. + * + * @param config Pointer to the configure structure. + */ +void CLOCK_SetSimConfig(sim_clock_config_t const *config); + +/*! + * @brief Set the system clock dividers in SIM to safe value. + * + * 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. + * + * @param config Pointer to the configure structure. + */ +static inline void CLOCK_SetSimSafeDivs(void) +{ + SIM->CLKDIV1 = 0x01240000U; +} + +/*! @name MCG frequency functions. */ +/*@{*/ + +/*! + * @brief Gets the MCG output clock (MCGOUTCLK) frequency. + * + * This function gets the MCG output clock frequency in Hz based on the current MCG + * register value. + * + * @return The frequency of MCGOUTCLK. + */ +uint32_t CLOCK_GetOutClkFreq(void); + +/*! + * @brief Gets the MCG FLL clock (MCGFLLCLK) frequency. + * + * 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. + * + * @return The frequency of MCGFLLCLK. + */ +uint32_t CLOCK_GetFllFreq(void); + +/*! + * @brief Gets the MCG internal reference clock (MCGIRCLK) frequency. + * + * This function gets the MCG internal reference clock frequency in Hz based + * on the current MCG register value. + * + * @return The frequency of MCGIRCLK. + */ +uint32_t CLOCK_GetInternalRefClkFreq(void); + +/*! + * @brief Gets the MCG fixed frequency clock (MCGFFCLK) frequency. + * + * This function gets the MCG fixed frequency clock frequency in Hz based + * on the current MCG register value. + * + * @return The frequency of MCGFFCLK. + */ +uint32_t CLOCK_GetFixedFreqClkFreq(void); + +/*! + * @brief Gets the MCG PLL0 clock (MCGPLL0CLK) frequency. + * + * This function gets the MCG PLL0 clock frequency in Hz based on the current MCG + * register value. + * + * @return The frequency of MCGPLL0CLK. + */ +uint32_t CLOCK_GetPll0Freq(void); + +/*@}*/ + +/*! @name MCG clock configuration. */ +/*@{*/ + +/*! + * @brief Enables or disables the MCG low power. + * + * 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. + * + * @param enable True to enable MCG low power, false to disable MCG low power. + */ +static inline void CLOCK_SetLowPowerEnable(bool enable) +{ + if (enable) + { + MCG->C2 |= MCG_C2_LP_MASK; + } + else + { + MCG->C2 &= ~MCG_C2_LP_MASK; + } +} + +/*! + * @brief Configures the Internal Reference clock (MCGIRCLK). + * + * This function sets the \c 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 \c 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. + * + * @param enableMode MCGIRCLK enable mode, OR'ed value of @ref _mcg_irclk_enable_mode. + * @param ircs MCGIRCLK clock source, choose fast or slow. + * @param fcrdiv Fast IRC divider setting (\c FCRDIV). + * @retval kStatus_MCG_SourceUsed Because the internall reference clock is used as a clock source, + * the confuration should not be changed. Otherwise, a glitch occurs. + * @retval kStatus_Success MCGIRCLK configuration finished successfully. + */ +status_t CLOCK_SetInternalRefClkConfig(uint8_t enableMode, mcg_irc_mode_t ircs, uint8_t fcrdiv); + +/*! + * @brief Selects the MCG external reference clock. + * + * 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/BLPE/PBE/PEE modes, do not call this function in these modes. + * + * @param oscsel MCG external reference clock source, MCG_C7[OSCSEL]. + * @retval kStatus_MCG_SourceUsed Because the external reference clock is used as a clock source, + * the confuration should not be changed. Otherwise, a glitch occurs. + * @retval kStatus_Success External reference clock set successfully. + */ +status_t CLOCK_SetExternalRefClkConfig(mcg_oscsel_t oscsel); + +/*! + * @brief Set the FLL external reference clock divider value. + * + * Sets the FLL external reference clock divider value, the register MCG_C1[FRDIV]. + * + * @param frdiv The FLL external reference clock divider value, MCG_C1[FRDIV]. + */ +static inline void CLOCK_SetFllExtRefDiv(uint8_t frdiv) +{ + MCG->C1 = (MCG->C1 & ~MCG_C1_FRDIV_MASK) | MCG_C1_FRDIV(frdiv); +} + +/*! + * @brief Enables the PLL0 in FLL mode. + * + * 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. + * + * @param config Pointer to the configuration structure. + */ +void CLOCK_EnablePll0(mcg_pll_config_t const *config); + +/*! + * @brief Disables the PLL0 in FLL mode. + * + * This function disables the PLL0 in FLL mode. It should be used together with the + * @ref CLOCK_EnablePll0. + */ +static inline void CLOCK_DisablePll0(void) +{ + MCG->C5 &= ~(MCG_C5_PLLCLKEN0_MASK | MCG_C5_PLLSTEN0_MASK); +} + +/*! + * @brief Calculates the PLL divider setting for a desired output frequency. + * + * This function calculates the correct reference clock divider (\c PRDIV) and + * VCO divider (\c VDIV) to generate a desired PLL output frequency. It returns the + * closest frequency match with the corresponding \c PRDIV/VDIV + * returned from parameters. If a desired frequency is not valid, this function + * returns 0. + * + * @param refFreq PLL reference clock frequency. + * @param desireFreq Desired PLL output frequency. + * @param prdiv PRDIV value to generate desired PLL frequency. + * @param vdiv VDIV value to generate desired PLL frequency. + * @return Closest frequency match that the PLL was able generate. + */ +uint32_t CLOCK_CalcPllDiv(uint32_t refFreq, uint32_t desireFreq, uint8_t *prdiv, uint8_t *vdiv); + +/*@}*/ + +/*! @name MCG clock lock monitor functions. */ +/*@{*/ + +/*! + * @brief Sets the OSC0 clock monitor mode. + * + * This function sets the OSC0 clock monitor mode. See @ref mcg_monitor_mode_t for details. + * + * @param mode Monitor mode to set. + */ +void CLOCK_SetOsc0MonitorMode(mcg_monitor_mode_t mode); + +/*! + * @brief Sets the RTC OSC clock monitor mode. + * + * This function sets the RTC OSC clock monitor mode. See @ref mcg_monitor_mode_t for details. + * + * @param mode Monitor mode to set. + */ +void CLOCK_SetRtcOscMonitorMode(mcg_monitor_mode_t mode); + +/*! + * @brief Sets the PLL0 clock monitor mode. + * + * This function sets the PLL0 clock monitor mode. See @ref mcg_monitor_mode_t for details. + * + * @param mode Monitor mode to set. + */ +void CLOCK_SetPll0MonitorMode(mcg_monitor_mode_t mode); + +/*! + * @brief Gets the MCG status flags. + * + * This function gets the MCG clock status flags. All status flags are + * returned as a logical OR of the enumeration @ref _mcg_status_flags_t. To + * check a specific flag, compare the return value with the flag. + * + * Example: + * @code + // To check the clock lost lock status of OSC0 and PLL0. + uint32_t mcgFlags; + + mcgFlags = CLOCK_GetStatusFlags(); + + if (mcgFlags & kMCG_Osc0LostFlag) + { + // OSC0 clock lock lost. Do something. + } + if (mcgFlags & kMCG_Pll0LostFlag) + { + // PLL0 clock lock lost. Do something. + } + @endcode + * + * @return Logical OR value of the @ref _mcg_status_flags_t. + */ +uint32_t CLOCK_GetStatusFlags(void); + +/*! + * @brief Clears the MCG status flags. + * + * This function clears the MCG clock lock lost status. The parameter is a logical + * OR value of the flags to clear. See @ref _mcg_status_flags_t. + * + * Example: + * @code + // To clear the clock lost lock status flags of OSC0 and PLL0. + + CLOCK_ClearStatusFlags(kMCG_Osc0LostFlag | kMCG_Pll0LostFlag); + @endcode + * + * @param mask The status flags to clear. This is a logical OR of members of the + * enumeration @ref _mcg_status_flags_t. + */ +void CLOCK_ClearStatusFlags(uint32_t mask); + +/*@}*/ + +/*! + * @name OSC configuration + * @{ + */ + +/*! + * @brief Configures the OSC external reference clock (OSCERCLK). + * + * 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: + * + @code + oscer_config_t config = + { + .enableMode = kOSC_ErClkEnable | kOSC_ErClkEnableInStop, + .erclkDiv = 1U, + }; + + OSC_SetExtRefClkConfig(OSC, &config); + @endcode + * + * @param base OSC peripheral address. + * @param config Pointer to the configuration structure. + */ +static inline void OSC_SetExtRefClkConfig(OSC_Type *base, oscer_config_t const *config) +{ + uint8_t reg = base->CR; + + reg &= ~(OSC_CR_ERCLKEN_MASK | OSC_CR_EREFSTEN_MASK); + reg |= config->enableMode; + + base->CR = reg; +} + +/*! + * @brief Sets the capacitor load configuration for the oscillator. + * + * 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. + * + * @param base OSC peripheral address. + * @param capLoad OR'ed value for the capacitor load option, see \ref _osc_cap_load. + * + * Example: + @code + // To enable only 2 pF and 8 pF capacitor load, please use like this. + OSC_SetCapLoad(OSC, kOSC_Cap2P | kOSC_Cap8P); + @endcode + */ +static inline void OSC_SetCapLoad(OSC_Type *base, uint8_t capLoad) +{ + uint8_t reg = base->CR; + + reg &= ~(OSC_CR_SC2P_MASK | OSC_CR_SC4P_MASK | OSC_CR_SC8P_MASK | OSC_CR_SC16P_MASK); + reg |= capLoad; + + base->CR = reg; +} + +/*! + * @brief Initializes the OSC0. + * + * This function initializes the OSC0 according to the board configuration. + * + * @param config Pointer to the OSC0 configuration structure. + */ +void CLOCK_InitOsc0(osc_config_t const *config); + +/*! + * @brief Deinitializes the OSC0. + * + * This function deinitializes the OSC0. + */ +void CLOCK_DeinitOsc0(void); + +/* @} */ + +/*! + * @name External clock frequency + * @{ + */ + +/*! + * @brief Sets the XTAL0 frequency based on board settings. + * + * @param freq The XTAL0/EXTAL0 input clock frequency in Hz. + */ +static inline void CLOCK_SetXtal0Freq(uint32_t freq) +{ + g_xtal0Freq = freq; +} + +/*! + * @brief Sets the XTAL32/RTC_CLKIN frequency based on board settings. + * + * @param freq The XTAL32/EXTAL32/RTC_CLKIN input clock frequency in Hz. + */ +static inline void CLOCK_SetXtal32Freq(uint32_t freq) +{ + g_xtal32Freq = freq; +} +/* @} */ + +/*! + * @name MCG auto-trim machine. + * @{ + */ + +/*! + * @brief Auto trims the internal reference clock. + * + * 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 @p actualFreq. If an error occurs, + * the error code is returned. + * + * @param extFreq External clock frequency, which should be a bus clock. + * @param desireFreq Frequency to trim to. + * @param actualFreq Actual frequency after trimming. + * @param atms Trim fast or slow internal reference clock. + * @retval kStatus_Success ATM success. + * @retval kStatus_MCG_AtmBusClockInvalid The bus clock is not in allowed range for the ATM. + * @retval kStatus_MCG_AtmDesiredFreqInvalid MCGIRCLK could not be trimmed to the desired frequency. + * @retval kStatus_MCG_AtmIrcUsed Could not trim because MCGIRCLK is used as a bus clock source. + * @retval kStatus_MCG_AtmHardwareFail Hardware fails while trimming. + */ +status_t CLOCK_TrimInternalRefClk(uint32_t extFreq, uint32_t desireFreq, uint32_t *actualFreq, mcg_atm_select_t atms); +/* @} */ + +/*! @name MCG mode functions. */ +/*@{*/ + +/*! + * @brief Gets the current MCG mode. + * + * This function checks the MCG registers and determines the current MCG mode. + * + * @return Current MCG mode or error code; See @ref mcg_mode_t. + */ +mcg_mode_t CLOCK_GetMode(void); + +/*! + * @brief Sets the MCG to FEI mode. + * + * This function sets the MCG to FEI mode. If setting to FEI mode fails + * from the current mode, this function returns an error. + * + * @param dmx32 DMX32 in FEI mode. + * @param drs The DCO range selection. + * @param fllStableDelay Delay function to ensure that the FLL is stable. Passing + * NULL does not cause a delay. + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + * @note If @p dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed + * to a frequency above 32768 Hz. + */ +status_t CLOCK_SetFeiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); + +/*! + * @brief Sets the MCG to FEE mode. + * + * This function sets the MCG to FEE mode. If setting to FEE mode fails + * from the current mode, this function returns an error. + * + * @param frdiv FLL reference clock divider setting, FRDIV. + * @param dmx32 DMX32 in FEE mode. + * @param drs The DCO range selection. + * @param fllStableDelay Delay function to make sure FLL is stable. Passing + * NULL does not cause a delay. + * + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + */ +status_t CLOCK_SetFeeMode(uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); + +/*! + * @brief Sets the MCG to FBI mode. + * + * This function sets the MCG to FBI mode. If setting to FBI mode fails + * from the current mode, this function returns an error. + * + * @param dmx32 DMX32 in FBI mode. + * @param drs The DCO range selection. + * @param fllStableDelay Delay function to make sure FLL is stable. If the FLL + * is not used in FBI mode, this parameter can be NULL. Passing + * NULL does not cause a delay. + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + * @note If @p dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed + * to frequency above 32768 Hz. + */ +status_t CLOCK_SetFbiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); + +/*! + * @brief Sets the MCG to FBE mode. + * + * This function sets the MCG to FBE mode. If setting to FBE mode fails + * from the current mode, this function returns an error. + * + * @param frdiv FLL reference clock divider setting, FRDIV. + * @param dmx32 DMX32 in FBE mode. + * @param drs The DCO range selection. + * @param fllStableDelay Delay function to make sure FLL is stable. If the FLL + * is not used in FBE mode, this parameter can be NULL. Passing NULL + * does not cause a delay. + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + */ +status_t CLOCK_SetFbeMode(uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); + +/*! + * @brief Sets the MCG to BLPI mode. + * + * This function sets the MCG to BLPI mode. If setting to BLPI mode fails + * from the current mode, this function returns an error. + * + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + */ +status_t CLOCK_SetBlpiMode(void); + +/*! + * @brief Sets the MCG to BLPE mode. + * + * This function sets the MCG to BLPE mode. If setting to BLPE mode fails + * from the current mode, this function returns an error. + * + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + */ +status_t CLOCK_SetBlpeMode(void); + +/*! + * @brief Sets the MCG to PBE mode. + * + * This function sets the MCG to PBE mode. If setting to PBE mode fails + * from the current mode, this function returns an error. + * + * @param pllcs The PLL selection, PLLCS. + * @param config Pointer to the PLL configuration. + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + * + * @note + * 1. The parameter \c pllcs selects the PLL. For platforms with + * only one PLL, the parameter pllcs is kept for interface compatibility. + * 2. The parameter \c 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_PllClkSelExtPll, NULL); + */ +status_t CLOCK_SetPbeMode(mcg_pll_clk_select_t pllcs, mcg_pll_config_t const *config); + +/*! + * @brief Sets the MCG to PEE mode. + * + * This function sets the MCG to PEE mode. + * + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + * + * @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. + */ +status_t CLOCK_SetPeeMode(void); + +/*! + * @brief Switches the MCG to FBE mode from the external 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: + * + * @code + * CLOCK_ExternalModeToFbeModeQuick(); + * CLOCK_SetFeiMode(...); + * @endcode + * + * @retval kStatus_Success Switched successfully. + * @retval kStatus_MCG_ModeInvalid If the current mode is not an external mode, do not call this function. + */ +status_t CLOCK_ExternalModeToFbeModeQuick(void); + +/*! + * @brief Switches the MCG to FBI mode from internal modes. + * + * 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: + * + * @code + * CLOCK_InternalModeToFbiModeQuick(); + * CLOCK_SetFeeMode(...); + * @endcode + * + * @retval kStatus_Success Switched successfully. + * @retval kStatus_MCG_ModeInvalid If the current mode is not an internal mode, do not call this function. + */ +status_t CLOCK_InternalModeToFbiModeQuick(void); + +/*! + * @brief Sets the MCG to FEI mode during system boot up. + * + * 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. + * + * @param dmx32 DMX32 in FEI mode. + * @param drs The DCO range selection. + * @param fllStableDelay Delay function to ensure that the FLL is stable. + * + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + * @note If @p dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed + * to frequency above 32768 Hz. + */ +status_t CLOCK_BootToFeiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); + +/*! + * @brief Sets the MCG to FEE mode during system bootup. + * + * 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. + * + * @param oscsel OSC clock select, OSCSEL. + * @param frdiv FLL reference clock divider setting, FRDIV. + * @param dmx32 DMX32 in FEE mode. + * @param drs The DCO range selection. + * @param fllStableDelay Delay function to ensure that the FLL is stable. + * + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + */ +status_t CLOCK_BootToFeeMode( + mcg_oscsel_t oscsel, uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); + +/*! + * @brief Sets the MCG to BLPI mode during system boot up. + * + * 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. + * + * @param fcrdiv Fast IRC divider, FCRDIV. + * @param ircs The internal reference clock to select, IRCS. + * @param ircEnableMode The MCGIRCLK enable mode, OR'ed value of @ref _mcg_irclk_enable_mode. + * + * @retval kStatus_MCG_SourceUsed Could not change MCGIRCLK setting. + * @retval kStatus_Success Switched to the target mode successfully. + */ +status_t CLOCK_BootToBlpiMode(uint8_t fcrdiv, mcg_irc_mode_t ircs, uint8_t ircEnableMode); + +/*! + * @brief Sets the MCG to BLPE mode during sytem boot up. + * + * 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. + * + * @param oscsel OSC clock select, MCG_C7[OSCSEL]. + * + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + */ +status_t CLOCK_BootToBlpeMode(mcg_oscsel_t oscsel); + +/*! + * @brief Sets the MCG to PEE mode during system boot up. + * + * 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. + * + * @param oscsel OSC clock select, MCG_C7[OSCSEL]. + * @param pllcs The PLL selection, PLLCS. + * @param config Pointer to the PLL configuration. + * + * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. + * @retval kStatus_Success Switched to the target mode successfully. + */ +status_t CLOCK_BootToPeeMode(mcg_oscsel_t oscsel, mcg_pll_clk_select_t pllcs, mcg_pll_config_t const *config); + +/*! + * @brief Sets the MCG to a target mode. + * + * 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. + * + * @param config Pointer to the target MCG mode configuration structure. + * @return 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. + */ +status_t CLOCK_SetMcgConfig(mcg_config_t const *config); + +/*@}*/ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/*! @} */ + +#endif /* _FSL_CLOCK_H_ */ diff --git a/drivers/include/fsl_cmp.h b/drivers/include/fsl_cmp.h new file mode 100644 index 0000000..5d16bf0 --- /dev/null +++ b/drivers/include/fsl_cmp.h @@ -0,0 +1,343 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_CMP_H_ +#define _FSL_CMP_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup cmp + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief CMP driver version 2.0.0. */ +#define FSL_CMP_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/*! +* @brief Interrupt enable/disable mask. +*/ +enum _cmp_interrupt_enable +{ + kCMP_OutputRisingInterruptEnable = CMP_SCR_IER_MASK, /*!< Comparator interrupt enable rising. */ + kCMP_OutputFallingInterruptEnable = CMP_SCR_IEF_MASK, /*!< Comparator interrupt enable falling. */ +}; + +/*! + * @brief Status flags' mask. + */ +enum _cmp_status_flags +{ + kCMP_OutputRisingEventFlag = CMP_SCR_CFR_MASK, /*!< Rising-edge on the comparison output has occurred. */ + kCMP_OutputFallingEventFlag = CMP_SCR_CFF_MASK, /*!< Falling-edge on the comparison output has occurred. */ + kCMP_OutputAssertEventFlag = CMP_SCR_COUT_MASK, /*!< Return the current value of the analog comparator output. */ +}; + +/*! + * @brief CMP Hysteresis mode. + */ +typedef enum _cmp_hysteresis_mode +{ + kCMP_HysteresisLevel0 = 0U, /*!< Hysteresis level 0. */ + kCMP_HysteresisLevel1 = 1U, /*!< Hysteresis level 1. */ + kCMP_HysteresisLevel2 = 2U, /*!< Hysteresis level 2. */ + kCMP_HysteresisLevel3 = 3U, /*!< Hysteresis level 3. */ +} cmp_hysteresis_mode_t; + +/*! + * @brief CMP Voltage Reference source. + */ +typedef enum _cmp_reference_voltage_source +{ + kCMP_VrefSourceVin1 = 0U, /*!< Vin1 is selected as a resistor ladder network supply reference Vin. */ + kCMP_VrefSourceVin2 = 1U, /*!< Vin2 is selected as a resistor ladder network supply reference Vin. */ +} cmp_reference_voltage_source_t; + +/*! + * @brief Configures the comparator. + */ +typedef struct _cmp_config +{ + 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. */ +#if defined(FSL_FEATURE_CMP_HAS_TRIGGER_MODE) && FSL_FEATURE_CMP_HAS_TRIGGER_MODE + bool enableTriggerMode; /*!< Enable the trigger mode. */ +#endif /* FSL_FEATURE_CMP_HAS_TRIGGER_MODE */ +} cmp_config_t; + +/*! + * @brief Configures the filter. + */ +typedef struct _cmp_filter_config +{ +#if defined(FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT) && FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT + bool enableSample; /*!< Using the external SAMPLE as a sampling clock input or using a divided bus clock. */ +#endif /* FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT */ + uint8_t filterCount; /*!< Filter Sample Count. Available range is 1-7; 0 disables the filter.*/ + uint8_t filterPeriod; /*!< Filter Sample Period. The divider to the bus clock. Available range is 0-255. */ +} cmp_filter_config_t; + +/*! + * @brief Configures the internal DAC. + */ +typedef struct _cmp_dac_config +{ + cmp_reference_voltage_source_t referenceVoltageSource; /*!< Supply voltage reference source. */ + uint8_t DACValue; /*!< Value for the DAC Output Voltage. Available range is 0-63.*/ +} cmp_dac_config_t; + +#if defined(__cplusplus) +extern "C" { +#endif + +/******************************************************************************* + * API + ******************************************************************************/ + +/*! + * @name Initialization + * @{ + */ + +/*! + * @brief Initializes the CMP. + * + * 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. + * + * @param base CMP peripheral base address. + * @param config Pointer to the configuration structure. + */ +void CMP_Init(CMP_Type *base, const cmp_config_t *config); + +/*! + * @brief De-initializes the CMP module. + * + * 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. + * + * @param base CMP peripheral base address. + */ +void CMP_Deinit(CMP_Type *base); + +/*! + * @brief Enables/disables the CMP module. + * + * @param base CMP peripheral base address. + * @param enable Enables or disables the module. + */ +static inline void CMP_Enable(CMP_Type *base, bool enable) +{ + if (enable) + { + base->CR1 |= CMP_CR1_EN_MASK; + } + else + { + base->CR1 &= ~CMP_CR1_EN_MASK; + } +} + +/*! +* @brief Initializes the CMP user configuration structure. +* +* This function initializes the user configuration structure to these default values. +* @code +* config->enableCmp = true; +* config->hysteresisMode = kCMP_HysteresisLevel0; +* config->enableHighSpeed = false; +* config->enableInvertOutput = false; +* config->useUnfilteredOutput = false; +* config->enablePinOut = false; +* config->enableTriggerMode = false; +* @endcode +* @param config Pointer to the configuration structure. +*/ +void CMP_GetDefaultConfig(cmp_config_t *config); + +/*! + * @brief Sets the input channels for the comparator. + * + * 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. + * + * @param base CMP peripheral base address. + * @param positiveChannel Positive side input channel number. Available range is 0-7. + * @param negativeChannel Negative side input channel number. Available range is 0-7. + */ +void CMP_SetInputChannels(CMP_Type *base, uint8_t positiveChannel, uint8_t negativeChannel); + +/* @} */ + +/*! + * @name Advanced Features + * @{ + */ + +#if defined(FSL_FEATURE_CMP_HAS_DMA) && FSL_FEATURE_CMP_HAS_DMA +/*! + * @brief Enables/disables the DMA request for rising/falling events. + * + * This function enables/disables the DMA request for rising/falling events. Either event triggers the generation 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. + * + * @param base CMP peripheral base address. + * @param enable Enables or disables the feature. + */ +void CMP_EnableDMA(CMP_Type *base, bool enable); +#endif /* FSL_FEATURE_CMP_HAS_DMA */ + +#if defined(FSL_FEATURE_CMP_HAS_WINDOW_MODE) && FSL_FEATURE_CMP_HAS_WINDOW_MODE +/*! + * @brief Enables/disables the window mode. + * + * @param base CMP peripheral base address. + * @param enable Enables or disables the feature. + */ +static inline void CMP_EnableWindowMode(CMP_Type *base, bool enable) +{ + if (enable) + { + base->CR1 |= CMP_CR1_WE_MASK; + } + else + { + base->CR1 &= ~CMP_CR1_WE_MASK; + } +} +#endif /* FSL_FEATURE_CMP_HAS_WINDOW_MODE */ + +#if defined(FSL_FEATURE_CMP_HAS_PASS_THROUGH_MODE) && FSL_FEATURE_CMP_HAS_PASS_THROUGH_MODE +/*! + * @brief Enables/disables the pass through mode. + * + * @param base CMP peripheral base address. + * @param enable Enables or disables the feature. + */ +static inline void CMP_EnablePassThroughMode(CMP_Type *base, bool enable) +{ + if (enable) + { + base->MUXCR |= CMP_MUXCR_PSTM_MASK; + } + else + { + base->MUXCR &= ~CMP_MUXCR_PSTM_MASK; + } +} +#endif /* FSL_FEATURE_CMP_HAS_PASS_THROUGH_MODE */ + +/*! + * @brief Configures the filter. + * + * @param base CMP peripheral base address. + * @param config Pointer to the configuration structure. + */ +void CMP_SetFilterConfig(CMP_Type *base, const cmp_filter_config_t *config); + +/*! + * @brief Configures the internal DAC. + * + * @param base CMP peripheral base address. + * @param config Pointer to the configuration structure. "NULL" disables the feature. + */ +void CMP_SetDACConfig(CMP_Type *base, const cmp_dac_config_t *config); + +/*! + * @brief Enables the interrupts. + * + * @param base CMP peripheral base address. + * @param mask Mask value for interrupts. See "_cmp_interrupt_enable". + */ +void CMP_EnableInterrupts(CMP_Type *base, uint32_t mask); + +/*! + * @brief Disables the interrupts. + * + * @param base CMP peripheral base address. + * @param mask Mask value for interrupts. See "_cmp_interrupt_enable". + */ +void CMP_DisableInterrupts(CMP_Type *base, uint32_t mask); + +/* @} */ + +/*! + * @name Results + * @{ + */ + +/*! + * @brief Gets the status flags. + * + * @param base CMP peripheral base address. + * + * @return Mask value for the asserted flags. See "_cmp_status_flags". + */ +uint32_t CMP_GetStatusFlags(CMP_Type *base); + +/*! + * @brief Clears the status flags. + * + * @param base CMP peripheral base address. + * @param mask Mask value for the flags. See "_cmp_status_flags". + */ +void CMP_ClearStatusFlags(CMP_Type *base, uint32_t mask); + +/* @} */ +#if defined(__cplusplus) +} +#endif +/*! + * @} + */ +#endif /* _FSL_CMP_H_ */ diff --git a/drivers/include/fsl_cmt.h b/drivers/include/fsl_cmt.h new file mode 100644 index 0000000..3d81f8a --- /dev/null +++ b/drivers/include/fsl_cmt.h @@ -0,0 +1,401 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_CMT_H_ +#define _FSL_CMT_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup cmt + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief CMT driver version 2.0.1. */ +#define FSL_CMT_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) +/*@}*/ + +/*! + * @brief The modes of CMT. + */ +typedef enum _cmt_mode +{ + kCMT_DirectIROCtl = 0x00U, /*!< Carrier modulator is disabled and the IRO signal is directly in software control */ + kCMT_TimeMode = 0x01U, /*!< Carrier modulator is enabled in time mode. */ + kCMT_FSKMode = 0x05U, /*!< Carrier modulator is enabled in FSK mode. */ + kCMT_BasebandMode = 0x09U /*!< Carrier modulator is enabled in baseband mode. */ +} cmt_mode_t; + +/*! + * @brief The CMT clock divide primary prescaler. + * The primary clock divider is used to divider the bus clock to + * get the intermediate frequency to approximately equal to 8 MHZ. + * When the bus clock is 8 MHZ, set primary prescaler to "kCMT_PrimaryClkDiv1". + */ +typedef enum _cmt_primary_clkdiv +{ + kCMT_PrimaryClkDiv1 = 0U, /*!< The intermediate frequency is the bus clock divided by 1. */ + kCMT_PrimaryClkDiv2 = 1U, /*!< The intermediate frequency is the bus clock divided by 2. */ + kCMT_PrimaryClkDiv3 = 2U, /*!< The intermediate frequency is the bus clock divided by 3. */ + kCMT_PrimaryClkDiv4 = 3U, /*!< The intermediate frequency is the bus clock divided by 4. */ + kCMT_PrimaryClkDiv5 = 4U, /*!< The intermediate frequency is the bus clock divided by 5. */ + kCMT_PrimaryClkDiv6 = 5U, /*!< The intermediate frequency is the bus clock divided by 6. */ + kCMT_PrimaryClkDiv7 = 6U, /*!< The intermediate frequency is the bus clock divided by 7. */ + kCMT_PrimaryClkDiv8 = 7U, /*!< The intermediate frequency is the bus clock divided by 8. */ + kCMT_PrimaryClkDiv9 = 8U, /*!< The intermediate frequency is the bus clock divided by 9. */ + kCMT_PrimaryClkDiv10 = 9U, /*!< The intermediate frequency is the bus clock divided by 10. */ + kCMT_PrimaryClkDiv11 = 10U, /*!< The intermediate frequency is the bus clock divided by 11. */ + kCMT_PrimaryClkDiv12 = 11U, /*!< The intermediate frequency is the bus clock divided by 12. */ + kCMT_PrimaryClkDiv13 = 12U, /*!< The intermediate frequency is the bus clock divided by 13. */ + kCMT_PrimaryClkDiv14 = 13U, /*!< The intermediate frequency is the bus clock divided by 14. */ + kCMT_PrimaryClkDiv15 = 14U, /*!< The intermediate frequency is the bus clock divided by 15. */ + kCMT_PrimaryClkDiv16 = 15U /*!< The intermediate frequency is the bus clock divided by 16. */ +} cmt_primary_clkdiv_t; + +/*! + * @brief The CMT clock divide secondary prescaler. + * The second prescaler can be used to divide the 8 MHZ CMT clock + * by 1, 2, 4, or 8 according to the specification. + */ +typedef enum _cmt_second_clkdiv +{ + kCMT_SecondClkDiv1 = 0U, /*!< The CMT clock is the intermediate frequency frequency divided by 1. */ + kCMT_SecondClkDiv2 = 1U, /*!< The CMT clock is the intermediate frequency frequency divided by 2. */ + kCMT_SecondClkDiv4 = 2U, /*!< The CMT clock is the intermediate frequency frequency divided by 4. */ + kCMT_SecondClkDiv8 = 3U /*!< The CMT clock is the intermediate frequency frequency divided by 8. */ +} cmt_second_clkdiv_t; + +/*! + * @brief The CMT infrared output polarity. + */ +typedef enum _cmt_infrared_output_polarity +{ + kCMT_IROActiveLow = 0U, /*!< The CMT infrared output signal polarity is active-low. */ + kCMT_IROActiveHigh = 1U /*!< The CMT infrared output signal polarity is active-high. */ +} cmt_infrared_output_polarity_t; + +/*! + * @brief The CMT infrared output signal state control. + */ +typedef enum _cmt_infrared_output_state +{ + kCMT_IROCtlLow = 0U, /*!< The CMT Infrared output signal state is controlled to low. */ + kCMT_IROCtlHigh = 1U /*!< The CMT Infrared output signal state is controlled to high. */ +} cmt_infrared_output_state_t; + +/*! + * @brief CMT interrupt configuration structure, default settings all disabled. + * + * This structure contains the settings for all of the CMT interrupt configurations. + */ +enum _cmt_interrupt_enable +{ + kCMT_EndOfCycleInterruptEnable = CMT_MSC_EOCIE_MASK, /*!< CMT end of cycle interrupt. */ +}; + +/*! + * @brief CMT carrier generator and modulator configuration structure + * + */ +typedef struct _cmt_modulate_config +{ + uint8_t highCount1; /*!< The high-time for carrier generator first register. */ + uint8_t lowCount1; /*!< The low-time for carrier generator first register. */ + uint8_t highCount2; /*!< The high-time for carrier generator second register for FSK mode. */ + uint8_t lowCount2; /*!< The low-time for carrier generator second register for FSK mode. */ + uint16_t markCount; /*!< The mark time for the modulator gate. */ + uint16_t spaceCount; /*!< The space time for the modulator gate. */ +} cmt_modulate_config_t; + +/*! @brief CMT basic configuration structure. */ +typedef struct _cmt_config +{ + bool isInterruptEnabled; /*!< Timer interrupt 0-disable, 1-enable. */ + bool isIroEnabled; /*!< The IRO output 0-disabled, 1-enabled. */ + cmt_infrared_output_polarity_t iroPolarity; /*!< The IRO polarity. */ + cmt_second_clkdiv_t divider; /*!< The CMT clock divide prescaler. */ +} cmt_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Gets the CMT default configuration structure. This API + * gets the default configuration structure for the CMT_Init(). + * Use the initialized structure unchanged in CMT_Init() or modify + * fields of the structure before calling the CMT_Init(). + * + * @param config The CMT configuration structure pointer. + */ +void CMT_GetDefaultConfig(cmt_config_t *config); + +/*! + * @brief Initializes the CMT module. + * + * This function ungates the module clock and sets the CMT internal clock, + * interrupt, and infrared output signal for the CMT module. + * + * @param base CMT peripheral base address. + * @param config The CMT basic configuration structure. + * @param busClock_Hz The CMT module input clock - bus clock frequency. + */ +void CMT_Init(CMT_Type *base, const cmt_config_t *config, uint32_t busClock_Hz); + +/*! + * @brief Disables the CMT module and gate control. + * + * This function disables CMT modulator, interrupts, and gates the + * CMT clock control. CMT_Init must be called to use the CMT again. + * + * @param base CMT peripheral base address. + */ +void CMT_Deinit(CMT_Type *base); + +/*! @}*/ + +/*! + * @name Basic Control Operations + * @{ + */ + +/*! + * @brief Selects the mode for CMT. + * + * @param base CMT peripheral base address. + * @param mode The CMT feature mode enumeration. See "cmt_mode_t". + * @param modulateConfig The carrier generation and modulator configuration. + */ +void CMT_SetMode(CMT_Type *base, cmt_mode_t mode, cmt_modulate_config_t *modulateConfig); + +/*! + * @brief Gets the mode of the CMT module. + * + * @param base CMT peripheral base address. + * @return The CMT mode. + * kCMT_DirectIROCtl Carrier modulator is disabled; the IRO signal is directly in software control. + * kCMT_TimeMode Carrier modulator is enabled in time mode. + * kCMT_FSKMode Carrier modulator is enabled in FSK mode. + * kCMT_BasebandMode Carrier modulator is enabled in baseband mode. + */ +cmt_mode_t CMT_GetMode(CMT_Type *base); + +/*! + * @brief Gets the actual CMT clock frequency. + * + * @param base CMT peripheral base address. + * @param busClock_Hz CMT module input clock - bus clock frequency. + * @return The CMT clock frequency. + */ +uint32_t CMT_GetCMTFrequency(CMT_Type *base, uint32_t busClock_Hz); + +/*! + * @brief Sets the primary data set for the CMT carrier generator counter. + * + * This function sets the high-time and low-time of the primary data set for the + * CMT carrier generator counter to control the period and the duty cycle of the + * output carrier signal. + * If the CMT clock period is Tcmt, the period of the carrier generator signal equals + * (highCount + lowCount) * Tcmt. The duty cycle equals to highCount / (highCount + lowCount). + * + * @param base CMT peripheral base address. + * @param highCount The number of CMT clocks for carrier generator signal high time, + * integer in the range of 1 ~ 0xFF. + * @param lowCount The number of CMT clocks for carrier generator signal low time, + * integer in the range of 1 ~ 0xFF. + */ +static inline void CMT_SetCarrirGenerateCountOne(CMT_Type *base, uint32_t highCount, uint32_t lowCount) +{ + assert(highCount <= CMT_CGH1_PH_MASK); + assert(highCount); + assert(lowCount <= CMT_CGL1_PL_MASK); + assert(lowCount); + + base->CGH1 = highCount; + base->CGL1 = lowCount; +} + +/*! + * @brief Sets the secondary data set for the CMT carrier generator counter. + * + * This function is used for FSK mode setting the high-time and low-time of the secondary + * data set CMT carrier generator counter to control the period and the duty cycle + * of the output carrier signal. + * If the CMT clock period is Tcmt, the period of the carrier generator signal equals + * (highCount + lowCount) * Tcmt. The duty cycle equals highCount / (highCount + lowCount). + * + * @param base CMT peripheral base address. + * @param highCount The number of CMT clocks for carrier generator signal high time, + * integer in the range of 1 ~ 0xFF. + * @param lowCount The number of CMT clocks for carrier generator signal low time, + * integer in the range of 1 ~ 0xFF. + */ +static inline void CMT_SetCarrirGenerateCountTwo(CMT_Type *base, uint32_t highCount, uint32_t lowCount) +{ + assert(highCount <= CMT_CGH2_SH_MASK); + assert(highCount); + assert(lowCount <= CMT_CGL2_SL_MASK); + assert(lowCount); + + base->CGH2 = highCount; + base->CGL2 = lowCount; +} + +/*! + * @brief Sets the modulation mark and space time period for the CMT modulator. + * + * This function sets the mark time period of the CMT modulator counter + * to control the mark time of the output modulated signal from the carrier generator output signal. + * If the CMT clock frequency is Fcmt and the carrier out signal frequency is fcg: + * - In Time and Baseband mode: The mark period of the generated signal equals (markCount + 1) / (Fcmt/8). + * The space period of the generated signal equals spaceCount / (Fcmt/8). + * - In FSK mode: The mark period of the generated signal equals (markCount + 1)/fcg. + * The space period of the generated signal equals spaceCount / fcg. + * + * @param base Base address for current CMT instance. + * @param markCount The number of clock period for CMT modulator signal mark period, + * in the range of 0 ~ 0xFFFF. + * @param spaceCount The number of clock period for CMT modulator signal space period, + * in the range of the 0 ~ 0xFFFF. + */ +void CMT_SetModulateMarkSpace(CMT_Type *base, uint32_t markCount, uint32_t spaceCount); + +/*! + * @brief Enables or disables the extended space operation. + * + * This function is used to make the space period longer + * for time, baseband, and FSK modes. + * + * @param base CMT peripheral base address. + * @param enable True enable the extended space, false disable the extended space. + */ +static inline void CMT_EnableExtendedSpace(CMT_Type *base, bool enable) +{ + if (enable) + { + base->MSC |= CMT_MSC_EXSPC_MASK; + } + else + { + base->MSC &= ~CMT_MSC_EXSPC_MASK; + } +} + +/*! + * @brief Sets the IRO (infrared output) signal state. + * + * Changes the states of the IRO signal when the kCMT_DirectIROMode mode is set + * and the IRO signal is enabled. + * + * @param base CMT peripheral base address. + * @param state The control of the IRO signal. See "cmt_infrared_output_state_t" + */ +void CMT_SetIroState(CMT_Type *base, cmt_infrared_output_state_t state); + +/*! + * @brief Enables the CMT interrupt. + * + * This function enables the CMT interrupts according to the provided mask if enabled. + * The CMT only has the end of the cycle interrupt - an interrupt occurs at the end + * of the modulator cycle. This interrupt provides a means for the user + * to reload the new mark/space values into the CMT modulator data registers + * and verify the modulator mark and space. + * For example, to enable the end of cycle, do the following. + * @code + * CMT_EnableInterrupts(CMT, kCMT_EndOfCycleInterruptEnable); + * @endcode + * @param base CMT peripheral base address. + * @param mask The interrupts to enable. Logical OR of @ref _cmt_interrupt_enable. + */ +static inline void CMT_EnableInterrupts(CMT_Type *base, uint32_t mask) +{ + base->MSC |= mask; +} + +/*! + * @brief Disables the CMT interrupt. + * + * This function disables the CMT interrupts according to the provided maskIf enabled. + * The CMT only has the end of the cycle interrupt. + * For example, to disable the end of cycle, do the following. + * @code + * CMT_DisableInterrupts(CMT, kCMT_EndOfCycleInterruptEnable); + * @endcode + * + * @param base CMT peripheral base address. + * @param mask The interrupts to enable. Logical OR of @ref _cmt_interrupt_enable. + */ +static inline void CMT_DisableInterrupts(CMT_Type *base, uint32_t mask) +{ + base->MSC &= ~mask; +} + +/*! + * @brief Gets the end of the cycle status flag. + * + * The flag is set: + * - When the modulator is not currently active and carrier and modulator + * are set to start the initial CMT transmission. + * - At the end of each modulation cycle when the counter is reloaded and + * the carrier and modulator are enabled. + * @param base CMT peripheral base address. + * @return Current status of the end of cycle status flag + * @arg non-zero: End-of-cycle has occurred. + * @arg zero: End-of-cycle has not yet occurred since the flag last cleared. + */ +static inline uint32_t CMT_GetStatusFlags(CMT_Type *base) +{ + return base->MSC & CMT_MSC_EOCF_MASK; +} + +/*! @}*/ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_CMT_H_*/ diff --git a/drivers/include/fsl_common.h b/drivers/include/fsl_common.h new file mode 100644 index 0000000..f20c090 --- /dev/null +++ b/drivers/include/fsl_common.h @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_COMMON_H_ +#define _FSL_COMMON_H_ + +#include +#include +#include +#include + +#if defined(__ICCARM__) +#include +#endif + +#include "fsl_device_registers.h" + +/*! + * @addtogroup ksdk_common + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @brief Construct a status code value from a group and code number. */ +#define MAKE_STATUS(group, code) ((((group)*100) + (code))) + +/*! @brief Construct the version number for drivers. */ +#define MAKE_VERSION(major, minor, bugfix) (((major) << 16) | ((minor) << 8) | (bugfix)) + +/* Debug console type definition. */ +#define DEBUG_CONSOLE_DEVICE_TYPE_NONE 0U /*!< No debug console. */ +#define DEBUG_CONSOLE_DEVICE_TYPE_UART 1U /*!< Debug console base on UART. */ +#define DEBUG_CONSOLE_DEVICE_TYPE_LPUART 2U /*!< Debug console base on LPUART. */ +#define DEBUG_CONSOLE_DEVICE_TYPE_LPSCI 3U /*!< Debug console base on LPSCI. */ +#define DEBUG_CONSOLE_DEVICE_TYPE_USBCDC 4U /*!< Debug console base on USBCDC. */ +#define DEBUG_CONSOLE_DEVICE_TYPE_FLEXCOMM 5U /*!< Debug console base on USBCDC. */ +#define DEBUG_CONSOLE_DEVICE_TYPE_IUART 6U /*!< Debug console base on i.MX UART. */ + +/*! @brief Status group numbers. */ +enum _status_groups +{ + kStatusGroup_Generic = 0, /*!< Group number for generic status codes. */ + kStatusGroup_FLASH = 1, /*!< Group number for FLASH status codes. */ + kStatusGroup_LPSPI = 4, /*!< Group number for LPSPI status codes. */ + kStatusGroup_FLEXIO_SPI = 5, /*!< Group number for FLEXIO SPI status codes. */ + kStatusGroup_DSPI = 6, /*!< Group number for DSPI status codes. */ + kStatusGroup_FLEXIO_UART = 7, /*!< Group number for FLEXIO UART status codes. */ + kStatusGroup_FLEXIO_I2C = 8, /*!< Group number for FLEXIO I2C status codes. */ + kStatusGroup_LPI2C = 9, /*!< Group number for LPI2C status codes. */ + kStatusGroup_UART = 10, /*!< Group number for UART status codes. */ + kStatusGroup_I2C = 11, /*!< Group number for UART status codes. */ + kStatusGroup_LPSCI = 12, /*!< Group number for LPSCI status codes. */ + kStatusGroup_LPUART = 13, /*!< Group number for LPUART status codes. */ + kStatusGroup_SPI = 14, /*!< Group number for SPI status code.*/ + kStatusGroup_XRDC = 15, /*!< Group number for XRDC status code.*/ + kStatusGroup_SEMA42 = 16, /*!< Group number for SEMA42 status code.*/ + kStatusGroup_SDHC = 17, /*!< Group number for SDHC status code */ + kStatusGroup_SDMMC = 18, /*!< Group number for SDMMC status code */ + kStatusGroup_SAI = 19, /*!< Group number for SAI status code */ + kStatusGroup_MCG = 20, /*!< Group number for MCG status codes. */ + kStatusGroup_SCG = 21, /*!< Group number for SCG status codes. */ + kStatusGroup_SDSPI = 22, /*!< Group number for SDSPI status codes. */ + kStatusGroup_FLEXIO_I2S = 23, /*!< Group number for FLEXIO I2S status codes */ + kStatusGroup_FLEXIO_MCULCD = 24, /*!< Group number for FLEXIO LCD status codes */ + kStatusGroup_FLASHIAP = 25, /*!< Group number for FLASHIAP status codes */ + kStatusGroup_FLEXCOMM_I2C = 26, /*!< Group number for FLEXCOMM I2C status codes */ + kStatusGroup_I2S = 27, /*!< Group number for I2S status codes */ + kStatusGroup_IUART = 28, /*!< Group number for IUART status codes */ + kStatusGroup_SDRAMC = 35, /*!< Group number for SDRAMC status codes. */ + kStatusGroup_POWER = 39, /*!< Group number for POWER status codes. */ + kStatusGroup_ENET = 40, /*!< Group number for ENET status codes. */ + kStatusGroup_PHY = 41, /*!< Group number for PHY status codes. */ + kStatusGroup_TRGMUX = 42, /*!< Group number for TRGMUX status codes. */ + kStatusGroup_SMARTCARD = 43, /*!< Group number for SMARTCARD status codes. */ + kStatusGroup_LMEM = 44, /*!< Group number for LMEM status codes. */ + kStatusGroup_QSPI = 45, /*!< Group number for QSPI status codes. */ + kStatusGroup_DMA = 50, /*!< Group number for DMA status codes. */ + kStatusGroup_EDMA = 51, /*!< Group number for EDMA status codes. */ + kStatusGroup_DMAMGR = 52, /*!< Group number for DMAMGR status codes. */ + kStatusGroup_FLEXCAN = 53, /*!< Group number for FlexCAN status codes. */ + kStatusGroup_LTC = 54, /*!< Group number for LTC status codes. */ + kStatusGroup_FLEXIO_CAMERA = 55, /*!< Group number for FLEXIO CAMERA status codes. */ + kStatusGroup_LPC_SPI = 56, /*!< Group number for LPC_SPI status codes. */ + kStatusGroup_LPC_USART = 57, /*!< Group number for LPC_USART status codes. */ + kStatusGroup_DMIC = 58, /*!< Group number for DMIC status codes. */ + kStatusGroup_SDIF = 59, /*!< Group number for SDIF status codes.*/ + kStatusGroup_SPIFI = 60, /*!< Group number for SPIFI status codes. */ + kStatusGroup_OTP = 61, /*!< Group number for OTP status codes. */ + kStatusGroup_MCAN = 62, /*!< Group number for MCAN status codes. */ + kStatusGroup_CAAM = 63, /*!< Group number for CAAM status codes. */ + kStatusGroup_ECSPI = 64, /*!< Group number for ECSPI status codes. */ + kStatusGroup_USDHC = 65, /*!< Group number for USDHC status codes.*/ + kStatusGroup_ESAI = 69, /*!< Group number for ESAI status codes. */ + kStatusGroup_FLEXSPI = 70, /*!< Group number for FLEXSPI status codes. */ + kStatusGroup_NOTIFIER = 98, /*!< Group number for NOTIFIER status codes. */ + kStatusGroup_DebugConsole = 99, /*!< Group number for debug console status codes. */ + kStatusGroup_ApplicationRangeStart = 100, /*!< Starting number for application groups. */ +}; + +/*! @brief Generic status return codes. */ +enum _generic_status +{ + kStatus_Success = MAKE_STATUS(kStatusGroup_Generic, 0), + kStatus_Fail = MAKE_STATUS(kStatusGroup_Generic, 1), + kStatus_ReadOnly = MAKE_STATUS(kStatusGroup_Generic, 2), + kStatus_OutOfRange = MAKE_STATUS(kStatusGroup_Generic, 3), + kStatus_InvalidArgument = MAKE_STATUS(kStatusGroup_Generic, 4), + kStatus_Timeout = MAKE_STATUS(kStatusGroup_Generic, 5), + kStatus_NoTransferInProgress = MAKE_STATUS(kStatusGroup_Generic, 6), +}; + +/*! @brief Type used for all status and error return values. */ +typedef int32_t status_t; + +/* + * The fsl_clock.h is included here because it needs MAKE_VERSION/MAKE_STATUS/status_t + * defined in previous of this file. + */ +#include "fsl_clock.h" + +/* + * Chip level peripheral reset API, for MCUs that implement peripheral reset control external to a peripheral + */ +#if ((defined(FSL_FEATURE_SOC_SYSCON_COUNT) && (FSL_FEATURE_SOC_SYSCON_COUNT > 0)) || \ + (defined(FSL_FEATURE_SOC_ASYNC_SYSCON_COUNT) && (FSL_FEATURE_SOC_ASYNC_SYSCON_COUNT > 0))) +#include "fsl_reset.h" +#endif + +/*! @name Min/max macros */ +/* @{ */ +#if !defined(MIN) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#if !defined(MAX) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#endif +/* @} */ + +/*! @brief Computes the number of elements in an array. */ +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) + +/*! @name UINT16_MAX/UINT32_MAX value */ +/* @{ */ +#if !defined(UINT16_MAX) +#define UINT16_MAX ((uint16_t)-1) +#endif + +#if !defined(UINT32_MAX) +#define UINT32_MAX ((uint32_t)-1) +#endif +/* @} */ + +/*! @name Timer utilities */ +/* @{ */ +/*! Macro to convert a microsecond period to raw count value */ +#define USEC_TO_COUNT(us, clockFreqInHz) (uint64_t)((uint64_t)us * clockFreqInHz / 1000000U) +/*! Macro to convert a raw count value to microsecond */ +#define COUNT_TO_USEC(count, clockFreqInHz) (uint64_t)((uint64_t)count * 1000000U / clockFreqInHz) + +/*! Macro to convert a millisecond period to raw count value */ +#define MSEC_TO_COUNT(ms, clockFreqInHz) (uint64_t)((uint64_t)ms * clockFreqInHz / 1000U) +/*! Macro to convert a raw count value to millisecond */ +#define COUNT_TO_MSEC(count, clockFreqInHz) (uint64_t)((uint64_t)count * 1000U / clockFreqInHz) +/* @} */ + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @brief Enable specific interrupt. + * + * Enable the interrupt not routed from intmux. + * + * @param interrupt The IRQ number. + */ +static inline void EnableIRQ(IRQn_Type interrupt) +{ + if (NotAvail_IRQn == interrupt) + { + return; + } + +#if defined(FSL_FEATURE_SOC_INTMUX_COUNT) && (FSL_FEATURE_SOC_INTMUX_COUNT > 0) + if (interrupt < FSL_FEATURE_INTMUX_IRQ_START_INDEX) +#endif + { +#if defined(__GIC_PRIO_BITS) + GIC_EnableIRQ(interrupt); +#else + NVIC_EnableIRQ(interrupt); +#endif + } +} + +/*! + * @brief Disable specific interrupt. + * + * Disable the interrupt not routed from intmux. + * + * @param interrupt The IRQ number. + */ +static inline void DisableIRQ(IRQn_Type interrupt) +{ + if (NotAvail_IRQn == interrupt) + { + return; + } + +#if defined(FSL_FEATURE_SOC_INTMUX_COUNT) && (FSL_FEATURE_SOC_INTMUX_COUNT > 0) + if (interrupt < FSL_FEATURE_INTMUX_IRQ_START_INDEX) +#endif + { +#if defined(__GIC_PRIO_BITS) + GIC_DisableIRQ(interrupt); +#else + NVIC_DisableIRQ(interrupt); +#endif + } +} + +/*! + * @brief Disable the global IRQ + * + * Disable the global interrupt and return the current primask register. User is required to provided the primask + * register for the EnableGlobalIRQ(). + * + * @return Current primask value. + */ +static inline uint32_t DisableGlobalIRQ(void) +{ +#if defined(CPSR_I_Msk) + uint32_t cpsr = __get_CPSR() & CPSR_I_Msk; + + __disable_irq(); + + return cpsr; +#else + uint32_t regPrimask = __get_PRIMASK(); + + __disable_irq(); + + return regPrimask; +#endif +} + +/*! + * @brief Enaable the global IRQ + * + * Set the primask register with the provided primask value but not just enable the primask. The idea is for the + * convinience of integration of RTOS. some RTOS get its own management mechanism of primask. User is required to + * use the EnableGlobalIRQ() and DisableGlobalIRQ() in pair. + * + * @param primask value of primask register to be restored. The primask value is supposed to be provided by the + * DisableGlobalIRQ(). + */ +static inline void EnableGlobalIRQ(uint32_t primask) +{ +#if defined(CPSR_I_Msk) + __set_CPSR((__get_CPSR() & ~CPSR_I_Msk) | primask); +#else + __set_PRIMASK(primask); +#endif +} + +/*! + * @brief install IRQ handler + * + * @param irq IRQ number + * @param irqHandler IRQ handler address + * @return The old IRQ handler address + */ +uint32_t InstallIRQHandler(IRQn_Type irq, uint32_t irqHandler); + +#if (defined(FSL_FEATURE_SOC_SYSCON_COUNT) && (FSL_FEATURE_SOC_SYSCON_COUNT > 0)) +/*! + * @brief Enable specific interrupt for wake-up from deep-sleep mode. + * + * Enable the interrupt for wake-up from deep sleep mode. + * Some interrupts are typically used in sleep mode only and will not occur during + * deep-sleep mode because relevant clocks are stopped. However, it is possible to enable + * those clocks (significantly increasing power consumption in the reduced power mode), + * making these wake-ups possible. + * + * @note This function also enables the interrupt in the NVIC (EnableIRQ() is called internally). + * + * @param interrupt The IRQ number. + */ +void EnableDeepSleepIRQ(IRQn_Type interrupt); + +/*! + * @brief Disable specific interrupt for wake-up from deep-sleep mode. + * + * Disable the interrupt for wake-up from deep sleep mode. + * Some interrupts are typically used in sleep mode only and will not occur during + * deep-sleep mode because relevant clocks are stopped. However, it is possible to enable + * those clocks (significantly increasing power consumption in the reduced power mode), + * making these wake-ups possible. + * + * @note This function also disables the interrupt in the NVIC (DisableIRQ() is called internally). + * + * @param interrupt The IRQ number. + */ +void DisableDeepSleepIRQ(IRQn_Type interrupt); +#endif /* FSL_FEATURE_SOC_SYSCON_COUNT */ + +#if defined(__cplusplus) +} +#endif + +/*! @} */ + +#endif /* _FSL_COMMON_H_ */ diff --git a/drivers/include/fsl_crc.h b/drivers/include/fsl_crc.h new file mode 100644 index 0000000..247a9ba --- /dev/null +++ b/drivers/include/fsl_crc.h @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_CRC_H_ +#define _FSL_CRC_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup crc + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief CRC driver version. Version 2.0.1. + * + * Current version: 2.0.1 + * + * Change log: + * - Version 2.0.1 + * - move DATA and DATALL macro definition from header file to source file + */ +#define FSL_CRC_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) +/*@}*/ + +#ifndef CRC_DRIVER_CUSTOM_DEFAULTS +/*! @brief Default configuration structure filled by CRC_GetDefaultConfig(). Use CRC16-CCIT-FALSE as defeault. */ +#define CRC_DRIVER_USE_CRC16_CCIT_FALSE_AS_DEFAULT 1 +#endif + +/*! @brief CRC bit width */ +typedef enum _crc_bits +{ + kCrcBits16 = 0U, /*!< Generate 16-bit CRC code */ + kCrcBits32 = 1U /*!< Generate 32-bit CRC code */ +} crc_bits_t; + +/*! @brief CRC result type */ +typedef enum _crc_result +{ + kCrcFinalChecksum = 0U, /*!< CRC data register read value is the final checksum. + Reflect out and final xor protocol features are applied. */ + kCrcIntermediateChecksum = 1U /*!< CRC data register read value is intermediate checksum (raw value). + Reflect out and final xor protocol feature are not applied. + Intermediate checksum can be used as a seed for CRC_Init() + to continue adding data to this checksum. */ +} crc_result_t; + +/*! +* @brief CRC protocol configuration. +* +* This structure holds the configuration for the CRC protocol. +* +*/ +typedef struct _crc_config +{ + uint32_t polynomial; /*!< CRC Polynomial, MSBit first. + Example polynomial: 0x1021 = 1_0000_0010_0001 = x^12+x^5+1 */ + uint32_t seed; /*!< Starting checksum value */ + bool reflectIn; /*!< Reflect bits on input. */ + bool reflectOut; /*!< Reflect bits on output. */ + bool complementChecksum; /*!< True if the result shall be complement of the actual checksum. */ + crc_bits_t crcBits; /*!< Selects 16- or 32- bit CRC protocol. */ + crc_result_t crcResult; /*!< Selects final or intermediate checksum return from CRC_Get16bitResult() or + CRC_Get32bitResult() */ +} crc_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @brief Enables and configures the CRC peripheral module. + * + * This function enables the clock gate in the SIM module for the CRC peripheral. + * It also configures the CRC module and starts a checksum computation by writing the seed. + * + * @param base CRC peripheral address. + * @param config CRC module configuration structure. + */ +void CRC_Init(CRC_Type *base, const crc_config_t *config); + +/*! + * @brief Disables the CRC peripheral module. + * + * This function disables the clock gate in the SIM module for the CRC peripheral. + * + * @param base CRC peripheral address. + */ +static inline void CRC_Deinit(CRC_Type *base) +{ +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) + /* gate clock */ + CLOCK_DisableClock(kCLOCK_Crc0); +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ +} + +/*! + * @brief Loads default values to the CRC protocol configuration structure. + * + * Loads default values to the CRC protocol configuration structure. The default values are as follows. + * @code + * config->polynomial = 0x1021; + * config->seed = 0xFFFF; + * config->reflectIn = false; + * config->reflectOut = false; + * config->complementChecksum = false; + * config->crcBits = kCrcBits16; + * config->crcResult = kCrcFinalChecksum; + * @endcode + * + * @param config CRC protocol configuration structure. + */ +void CRC_GetDefaultConfig(crc_config_t *config); + +/*! + * @brief Writes data to the CRC module. + * + * Writes input data buffer bytes to the CRC data register. + * The configured type of transpose is applied. + * + * @param base CRC peripheral address. + * @param data Input data stream, MSByte in data[0]. + * @param dataSize Size in bytes of the input data buffer. + */ +void CRC_WriteData(CRC_Type *base, const uint8_t *data, size_t dataSize); + +/*! + * @brief Reads the 32-bit checksum from the CRC module. + * + * Reads the CRC data register (either an intermediate or the final checksum). + * The configured type of transpose and complement is applied. + * + * @param base CRC peripheral address. + * @return An intermediate or the final 32-bit checksum, after configured transpose and complement operations. + */ +uint32_t CRC_Get32bitResult(CRC_Type *base); + +/*! + * @brief Reads a 16-bit checksum from the CRC module. + * + * Reads the CRC data register (either an intermediate or the final checksum). + * The configured type of transpose and complement is applied. + * + * @param base CRC peripheral address. + * @return An intermediate or the final 16-bit checksum, after configured transpose and complement operations. + */ +uint16_t CRC_Get16bitResult(CRC_Type *base); + +#if defined(__cplusplus) +} +#endif + +/*! + *@} + */ + +#endif /* _FSL_CRC_H_ */ diff --git a/drivers/include/fsl_dac.h b/drivers/include/fsl_dac.h new file mode 100644 index 0000000..b71febf --- /dev/null +++ b/drivers/include/fsl_dac.h @@ -0,0 +1,378 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_DAC_H_ +#define _FSL_DAC_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup dac + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief DAC driver version 2.0.1. */ +#define FSL_DAC_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) +/*@}*/ + +/*! + * @brief DAC buffer flags. + */ +enum _dac_buffer_status_flags +{ +#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION + kDAC_BufferWatermarkFlag = DAC_SR_DACBFWMF_MASK, /*!< DAC Buffer Watermark Flag. */ +#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ + kDAC_BufferReadPointerTopPositionFlag = DAC_SR_DACBFRPTF_MASK, /*!< DAC Buffer Read Pointer Top Position Flag. */ + kDAC_BufferReadPointerBottomPositionFlag = DAC_SR_DACBFRPBF_MASK, /*!< DAC Buffer Read Pointer Bottom Position + Flag. */ +}; + +/*! + * @brief DAC buffer interrupts. + */ +enum _dac_buffer_interrupt_enable +{ +#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION + kDAC_BufferWatermarkInterruptEnable = DAC_C0_DACBWIEN_MASK, /*!< DAC Buffer Watermark Interrupt Enable. */ +#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ + kDAC_BufferReadPointerTopInterruptEnable = DAC_C0_DACBTIEN_MASK, /*!< DAC Buffer Read Pointer Top Flag Interrupt + Enable. */ + kDAC_BufferReadPointerBottomInterruptEnable = DAC_C0_DACBBIEN_MASK, /*!< DAC Buffer Read Pointer Bottom Flag + Interrupt Enable */ +}; + +/*! + * @brief DAC reference voltage source. + */ +typedef enum _dac_reference_voltage_source +{ + kDAC_ReferenceVoltageSourceVref1 = 0U, /*!< The DAC selects DACREF_1 as the reference voltage. */ + kDAC_ReferenceVoltageSourceVref2 = 1U, /*!< The DAC selects DACREF_2 as the reference voltage. */ +} dac_reference_voltage_source_t; + +/*! + * @brief DAC buffer trigger mode. + */ +typedef enum _dac_buffer_trigger_mode +{ + kDAC_BufferTriggerByHardwareMode = 0U, /*!< The DAC hardware trigger is selected. */ + kDAC_BufferTriggerBySoftwareMode = 1U, /*!< The DAC software trigger is selected. */ +} dac_buffer_trigger_mode_t; + +#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION +/*! + * @brief DAC buffer watermark. + */ +typedef enum _dac_buffer_watermark +{ +#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_1_WORD) && FSL_FEATURE_DAC_HAS_WATERMARK_1_WORD + kDAC_BufferWatermark1Word = 0U, /*!< 1 word away from the upper limit. */ +#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_1_WORD */ +#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_2_WORDS) && FSL_FEATURE_DAC_HAS_WATERMARK_2_WORDS + kDAC_BufferWatermark2Word = 1U, /*!< 2 words away from the upper limit. */ +#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_2_WORDS */ +#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_3_WORDS) && FSL_FEATURE_DAC_HAS_WATERMARK_3_WORDS + kDAC_BufferWatermark3Word = 2U, /*!< 3 words away from the upper limit. */ +#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_3_WORDS */ +#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_4_WORDS) && FSL_FEATURE_DAC_HAS_WATERMARK_4_WORDS + kDAC_BufferWatermark4Word = 3U, /*!< 4 words away from the upper limit. */ +#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_4_WORDS */ +} dac_buffer_watermark_t; +#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION */ + +/*! + * @brief DAC buffer work mode. + */ +typedef enum _dac_buffer_work_mode +{ + kDAC_BufferWorkAsNormalMode = 0U, /*!< Normal mode. */ +#if defined(FSL_FEATURE_DAC_HAS_BUFFER_SWING_MODE) && FSL_FEATURE_DAC_HAS_BUFFER_SWING_MODE + kDAC_BufferWorkAsSwingMode, /*!< Swing mode. */ +#endif /* FSL_FEATURE_DAC_HAS_BUFFER_SWING_MODE */ + kDAC_BufferWorkAsOneTimeScanMode, /*!< One-Time Scan mode. */ +#if defined(FSL_FEATURE_DAC_HAS_BUFFER_FIFO_MODE) && FSL_FEATURE_DAC_HAS_BUFFER_FIFO_MODE + kDAC_BufferWorkAsFIFOMode, /*!< FIFO mode. */ +#endif /* FSL_FEATURE_DAC_HAS_BUFFER_FIFO_MODE */ +} dac_buffer_work_mode_t; + +/*! + * @brief DAC module configuration. + */ +typedef struct _dac_config +{ + dac_reference_voltage_source_t referenceVoltageSource; /*!< Select the DAC reference voltage source. */ + bool enableLowPowerMode; /*!< Enable the low-power mode. */ +} dac_config_t; + +/*! + * @brief DAC buffer configuration. + */ +typedef struct _dac_buffer_config +{ + dac_buffer_trigger_mode_t triggerMode; /*!< Select the buffer's trigger mode. */ +#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION + dac_buffer_watermark_t watermark; /*!< Select the buffer's watermark. */ +#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION */ + dac_buffer_work_mode_t workMode; /*!< Select the buffer's work mode. */ + uint8_t upperLimit; /*!< Set the upper limit for the buffer index. + Normally, 0-15 is available for a buffer with 16 items. */ +} dac_buffer_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization + * @{ + */ + +/*! + * @brief Initializes the DAC module. + * + * 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. + * + * @param base DAC peripheral base address. + * @param config Pointer to the configuration structure. See "dac_config_t". + */ +void DAC_Init(DAC_Type *base, const dac_config_t *config); + +/*! + * @brief De-initializes the DAC module. + * + * This function de-initializes the DAC module including the following operations. + * - Disabling the DAC module. + * - Disabling the clock for the DAC module. + * + * @param base DAC peripheral base address. + */ +void DAC_Deinit(DAC_Type *base); + +/*! + * @brief Initializes the DAC user configuration structure. + * + * This function initializes the user configuration structure to a default value. The default values are as follows. + * @code + * config->referenceVoltageSource = kDAC_ReferenceVoltageSourceVref2; + * config->enableLowPowerMode = false; + * @endcode + * @param config Pointer to the configuration structure. See "dac_config_t". + */ +void DAC_GetDefaultConfig(dac_config_t *config); + +/*! + * @brief Enables the DAC module. + * + * @param base DAC peripheral base address. + * @param enable Enables or disables the feature. + */ +static inline void DAC_Enable(DAC_Type *base, bool enable) +{ + if (enable) + { + base->C0 |= DAC_C0_DACEN_MASK; + } + else + { + base->C0 &= ~DAC_C0_DACEN_MASK; + } +} + +/* @} */ + +/*! + * @name Buffer + * @{ + */ + +/*! + * @brief Enables the DAC buffer. + * + * @param base DAC peripheral base address. + * @param enable Enables or disables the feature. + */ +static inline void DAC_EnableBuffer(DAC_Type *base, bool enable) +{ + if (enable) + { + base->C1 |= DAC_C1_DACBFEN_MASK; + } + else + { + base->C1 &= ~DAC_C1_DACBFEN_MASK; + } +} + +/*! + * @brief Configures the CMP buffer. + * + * @param base DAC peripheral base address. + * @param config Pointer to the configuration structure. See "dac_buffer_config_t". + */ +void DAC_SetBufferConfig(DAC_Type *base, const dac_buffer_config_t *config); + +/*! + * @brief Initializes the DAC buffer configuration structure. + * + * This function initializes the DAC buffer configuration structure to default values. The default values are as follows. + * @code + * config->triggerMode = kDAC_BufferTriggerBySoftwareMode; + * config->watermark = kDAC_BufferWatermark1Word; + * config->workMode = kDAC_BufferWorkAsNormalMode; + * config->upperLimit = DAC_DATL_COUNT - 1U; + * @endcode + * @param config Pointer to the configuration structure. See "dac_buffer_config_t". + */ +void DAC_GetDefaultBufferConfig(dac_buffer_config_t *config); + +/*! + * @brief Enables the DMA for DAC buffer. + * + * @param base DAC peripheral base address. + * @param enable Enables or disables the feature. + */ +static inline void DAC_EnableBufferDMA(DAC_Type *base, bool enable) +{ + if (enable) + { + base->C1 |= DAC_C1_DMAEN_MASK; + } + else + { + base->C1 &= ~DAC_C1_DMAEN_MASK; + } +} + +/*! + * @brief Sets the value for items in the buffer. + * + * @param base DAC peripheral base address. + * @param index Setting the index for items in the buffer. The available index should not exceed the size of the DAC buffer. + * @param value Setting the value for items in the buffer. 12-bits are available. + */ +void DAC_SetBufferValue(DAC_Type *base, uint8_t index, uint16_t value); + +/*! + * @brief Triggers the buffer using software and updates the read pointer of the DAC buffer. + * + * 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. + * + * @param base DAC peripheral base address. + */ +static inline void DAC_DoSoftwareTriggerBuffer(DAC_Type *base) +{ + base->C0 |= DAC_C0_DACSWTRG_MASK; +} + +/*! + * @brief Gets the current read pointer of the DAC buffer. + * + * 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. + * + * @param base DAC peripheral base address. + * + * @return The current read pointer of the DAC buffer. + */ +static inline uint8_t DAC_GetBufferReadPointer(DAC_Type *base) +{ + return ((base->C2 & DAC_C2_DACBFRP_MASK) >> DAC_C2_DACBFRP_SHIFT); +} + +/*! + * @brief Sets 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. + * + * @param base DAC peripheral base address. + * @param index Setting an index value for the pointer. + */ +void DAC_SetBufferReadPointer(DAC_Type *base, uint8_t index); + +/*! + * @brief Enables interrupts for the DAC buffer. + * + * @param base DAC peripheral base address. + * @param mask Mask value for interrupts. See "_dac_buffer_interrupt_enable". + */ +void DAC_EnableBufferInterrupts(DAC_Type *base, uint32_t mask); + +/*! + * @brief Disables interrupts for the DAC buffer. + * + * @param base DAC peripheral base address. + * @param mask Mask value for interrupts. See "_dac_buffer_interrupt_enable". + */ +void DAC_DisableBufferInterrupts(DAC_Type *base, uint32_t mask); + +/*! + * @brief Gets the flags of events for the DAC buffer. + * + * @param base DAC peripheral base address. + * + * @return Mask value for the asserted flags. See "_dac_buffer_status_flags". + */ +uint32_t DAC_GetBufferStatusFlags(DAC_Type *base); + +/*! + * @brief Clears the flags of events for the DAC buffer. + * + * @param base DAC peripheral base address. + * @param mask Mask value for flags. See "_dac_buffer_status_flags_t". + */ +void DAC_ClearBufferStatusFlags(DAC_Type *base, uint32_t mask); + +/* @} */ + +#if defined(__cplusplus) +} +#endif +/*! + * @} + */ +#endif /* _FSL_DAC_H_ */ diff --git a/drivers/include/fsl_dmamux.h b/drivers/include/fsl_dmamux.h new file mode 100644 index 0000000..071348b --- /dev/null +++ b/drivers/include/fsl_dmamux.h @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_DMAMUX_H_ +#define _FSL_DMAMUX_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup dmamux + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief DMAMUX driver version 2.0.2. */ +#define FSL_DMAMUX_DRIVER_VERSION (MAKE_VERSION(2, 0, 2)) +/*@}*/ + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*! + * @name DMAMUX Initialization and de-initialization + * @{ + */ + +/*! + * @brief Initializes the DMAMUX peripheral. + * + * This function ungates the DMAMUX clock. + * + * @param base DMAMUX peripheral base address. + * + */ +void DMAMUX_Init(DMAMUX_Type *base); + +/*! + * @brief Deinitializes the DMAMUX peripheral. + * + * This function gates the DMAMUX clock. + * + * @param base DMAMUX peripheral base address. + */ +void DMAMUX_Deinit(DMAMUX_Type *base); + +/* @} */ +/*! + * @name DMAMUX Channel Operation + * @{ + */ + +/*! + * @brief Enables the DMAMUX channel. + * + * This function enables the DMAMUX channel. + * + * @param base DMAMUX peripheral base address. + * @param channel DMAMUX channel number. + */ +static inline void DMAMUX_EnableChannel(DMAMUX_Type *base, uint32_t channel) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->CHCFG[channel] |= DMAMUX_CHCFG_ENBL_MASK; +} + +/*! + * @brief Disables the DMAMUX channel. + * + * This function disables the DMAMUX channel. + * + * @note The user must disable the DMAMUX channel before configuring it. + * @param base DMAMUX peripheral base address. + * @param channel DMAMUX channel number. + */ +static inline void DMAMUX_DisableChannel(DMAMUX_Type *base, uint32_t channel) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->CHCFG[channel] &= ~DMAMUX_CHCFG_ENBL_MASK; +} + +/*! + * @brief Configures the DMAMUX channel source. + * + * @param base DMAMUX peripheral base address. + * @param channel DMAMUX channel number. + * @param source Channel source, which is used to trigger the DMA transfer. + */ +static inline void DMAMUX_SetSource(DMAMUX_Type *base, uint32_t channel, uint32_t source) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->CHCFG[channel] = ((base->CHCFG[channel] & ~DMAMUX_CHCFG_SOURCE_MASK) | DMAMUX_CHCFG_SOURCE(source)); +} + +#if defined(FSL_FEATURE_DMAMUX_HAS_TRIG) && FSL_FEATURE_DMAMUX_HAS_TRIG > 0U +/*! + * @brief Enables the DMAMUX period trigger. + * + * This function enables the DMAMUX period trigger feature. + * + * @param base DMAMUX peripheral base address. + * @param channel DMAMUX channel number. + */ +static inline void DMAMUX_EnablePeriodTrigger(DMAMUX_Type *base, uint32_t channel) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->CHCFG[channel] |= DMAMUX_CHCFG_TRIG_MASK; +} + +/*! + * @brief Disables the DMAMUX period trigger. + * + * This function disables the DMAMUX period trigger. + * + * @param base DMAMUX peripheral base address. + * @param channel DMAMUX channel number. + */ +static inline void DMAMUX_DisablePeriodTrigger(DMAMUX_Type *base, uint32_t channel) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->CHCFG[channel] &= ~DMAMUX_CHCFG_TRIG_MASK; +} +#endif /* FSL_FEATURE_DMAMUX_HAS_TRIG */ + +#if (defined(FSL_FEATURE_DMAMUX_HAS_A_ON) && FSL_FEATURE_DMAMUX_HAS_A_ON) +/*! + * @brief Enables the DMA channel to be always ON. + * + * This function enables the DMAMUX channel always ON feature. + * + * @param base DMAMUX peripheral base address. + * @param channel DMAMUX channel number. + * @param enable Switcher of the always ON feature. "true" means enabled, "false" means disabled. + */ +static inline void DMAMUX_EnableAlwaysOn(DMAMUX_Type *base, uint32_t channel, bool enable) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + if (enable) + { + base->CHCFG[channel] |= DMAMUX_CHCFG_A_ON_MASK; + } + else + { + base->CHCFG[channel] &= ~DMAMUX_CHCFG_A_ON_MASK; + } +} +#endif /* FSL_FEATURE_DMAMUX_HAS_A_ON */ + +/* @} */ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/* @} */ + +#endif /* _FSL_DMAMUX_H_ */ diff --git a/drivers/include/fsl_dspi.h b/drivers/include/fsl_dspi.h new file mode 100644 index 0000000..ae89c6d --- /dev/null +++ b/drivers/include/fsl_dspi.h @@ -0,0 +1,1180 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_DSPI_H_ +#define _FSL_DSPI_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup dspi_driver + * @{ + */ + + +/********************************************************************************************************************** + * Definitions + *********************************************************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief DSPI driver version 2.1.4. */ +#define FSL_DSPI_DRIVER_VERSION (MAKE_VERSION(2, 1, 4)) +/*@}*/ + +#ifndef DSPI_DUMMY_DATA +/*! @brief DSPI dummy data if there is no Tx data.*/ +#define DSPI_DUMMY_DATA (0xBBU) /*!< Dummy data used for Tx if there is no txData. */ +#endif + +/*! @brief Status for the DSPI driver.*/ +enum _dspi_status +{ + kStatus_DSPI_Busy = MAKE_STATUS(kStatusGroup_DSPI, 0), /*!< DSPI transfer is busy.*/ + kStatus_DSPI_Error = MAKE_STATUS(kStatusGroup_DSPI, 1), /*!< DSPI driver error. */ + kStatus_DSPI_Idle = MAKE_STATUS(kStatusGroup_DSPI, 2), /*!< DSPI is idle.*/ + kStatus_DSPI_OutOfRange = MAKE_STATUS(kStatusGroup_DSPI, 3) /*!< DSPI transfer out of range. */ +}; + +/*! @brief DSPI status flags in SPIx_SR register.*/ +enum _dspi_flags +{ + kDSPI_TxCompleteFlag = SPI_SR_TCF_MASK, /*!< Transfer Complete Flag. */ + kDSPI_EndOfQueueFlag = SPI_SR_EOQF_MASK, /*!< End of Queue Flag.*/ + kDSPI_TxFifoUnderflowFlag = SPI_SR_TFUF_MASK, /*!< Transmit FIFO Underflow Flag.*/ + kDSPI_TxFifoFillRequestFlag = SPI_SR_TFFF_MASK, /*!< Transmit FIFO Fill Flag.*/ + kDSPI_RxFifoOverflowFlag = SPI_SR_RFOF_MASK, /*!< Receive FIFO Overflow Flag.*/ + kDSPI_RxFifoDrainRequestFlag = SPI_SR_RFDF_MASK, /*!< Receive FIFO Drain Flag.*/ + kDSPI_TxAndRxStatusFlag = SPI_SR_TXRXS_MASK, /*!< The module is in Stopped/Running state.*/ + kDSPI_AllStatusFlag = SPI_SR_TCF_MASK | SPI_SR_EOQF_MASK | SPI_SR_TFUF_MASK | SPI_SR_TFFF_MASK | SPI_SR_RFOF_MASK | + SPI_SR_RFDF_MASK | SPI_SR_TXRXS_MASK /*!< All statuses above.*/ +}; + +/*! @brief DSPI interrupt source.*/ +enum _dspi_interrupt_enable +{ + kDSPI_TxCompleteInterruptEnable = SPI_RSER_TCF_RE_MASK, /*!< TCF interrupt enable.*/ + kDSPI_EndOfQueueInterruptEnable = SPI_RSER_EOQF_RE_MASK, /*!< EOQF interrupt enable.*/ + kDSPI_TxFifoUnderflowInterruptEnable = SPI_RSER_TFUF_RE_MASK, /*!< TFUF interrupt enable.*/ + kDSPI_TxFifoFillRequestInterruptEnable = SPI_RSER_TFFF_RE_MASK, /*!< TFFF interrupt enable, DMA disable.*/ + kDSPI_RxFifoOverflowInterruptEnable = SPI_RSER_RFOF_RE_MASK, /*!< RFOF interrupt enable.*/ + kDSPI_RxFifoDrainRequestInterruptEnable = SPI_RSER_RFDF_RE_MASK, /*!< RFDF interrupt enable, DMA disable.*/ + kDSPI_AllInterruptEnable = SPI_RSER_TCF_RE_MASK | SPI_RSER_EOQF_RE_MASK | SPI_RSER_TFUF_RE_MASK | + SPI_RSER_TFFF_RE_MASK | SPI_RSER_RFOF_RE_MASK | SPI_RSER_RFDF_RE_MASK + /*!< All above interrupts enable.*/ +}; + +/*! @brief DSPI DMA source.*/ +enum _dspi_dma_enable +{ + kDSPI_TxDmaEnable = (SPI_RSER_TFFF_RE_MASK | SPI_RSER_TFFF_DIRS_MASK), /*!< TFFF flag generates DMA requests. + No Tx interrupt request. */ + kDSPI_RxDmaEnable = (SPI_RSER_RFDF_RE_MASK | SPI_RSER_RFDF_DIRS_MASK) /*!< RFDF flag generates DMA requests. + No Rx interrupt request. */ +}; + +/*! @brief DSPI master or slave mode configuration.*/ +typedef enum _dspi_master_slave_mode +{ + kDSPI_Master = 1U, /*!< DSPI peripheral operates in master mode.*/ + kDSPI_Slave = 0U /*!< DSPI peripheral operates in slave mode.*/ +} dspi_master_slave_mode_t; + +/*! + * @brief DSPI Sample Point: Controls when the DSPI master samples SIN in the Modified Transfer Format. This field is valid + * only when the CPHA bit in the CTAR register is 0. + */ +typedef enum _dspi_master_sample_point +{ + kDSPI_SckToSin0Clock = 0U, /*!< 0 system clocks between SCK edge and SIN sample.*/ + kDSPI_SckToSin1Clock = 1U, /*!< 1 system clock between SCK edge and SIN sample.*/ + kDSPI_SckToSin2Clock = 2U /*!< 2 system clocks between SCK edge and SIN sample.*/ +} dspi_master_sample_point_t; + +/*! @brief DSPI Peripheral Chip Select (Pcs) configuration (which Pcs to configure).*/ +typedef enum _dspi_which_pcs_config +{ + kDSPI_Pcs0 = 1U << 0, /*!< Pcs[0] */ + kDSPI_Pcs1 = 1U << 1, /*!< Pcs[1] */ + kDSPI_Pcs2 = 1U << 2, /*!< Pcs[2] */ + kDSPI_Pcs3 = 1U << 3, /*!< Pcs[3] */ + kDSPI_Pcs4 = 1U << 4, /*!< Pcs[4] */ + kDSPI_Pcs5 = 1U << 5 /*!< Pcs[5] */ +} dspi_which_pcs_t; + +/*! @brief DSPI Peripheral Chip Select (Pcs) Polarity configuration.*/ +typedef enum _dspi_pcs_polarity_config +{ + kDSPI_PcsActiveHigh = 0U, /*!< Pcs Active High (idles low). */ + kDSPI_PcsActiveLow = 1U /*!< Pcs Active Low (idles high). */ +} dspi_pcs_polarity_config_t; + +/*! @brief DSPI Peripheral Chip Select (Pcs) Polarity.*/ +enum _dspi_pcs_polarity +{ + kDSPI_Pcs0ActiveLow = 1U << 0, /*!< Pcs0 Active Low (idles high). */ + kDSPI_Pcs1ActiveLow = 1U << 1, /*!< Pcs1 Active Low (idles high). */ + kDSPI_Pcs2ActiveLow = 1U << 2, /*!< Pcs2 Active Low (idles high). */ + kDSPI_Pcs3ActiveLow = 1U << 3, /*!< Pcs3 Active Low (idles high). */ + kDSPI_Pcs4ActiveLow = 1U << 4, /*!< Pcs4 Active Low (idles high). */ + kDSPI_Pcs5ActiveLow = 1U << 5, /*!< Pcs5 Active Low (idles high). */ + kDSPI_PcsAllActiveLow = 0xFFU /*!< Pcs0 to Pcs5 Active Low (idles high). */ +}; + +/*! @brief DSPI clock polarity configuration for a given CTAR.*/ +typedef enum _dspi_clock_polarity +{ + kDSPI_ClockPolarityActiveHigh = 0U, /*!< CPOL=0. Active-high DSPI clock (idles low).*/ + kDSPI_ClockPolarityActiveLow = 1U /*!< CPOL=1. Active-low DSPI clock (idles high).*/ +} dspi_clock_polarity_t; + +/*! @brief DSPI clock phase configuration for a given CTAR.*/ +typedef enum _dspi_clock_phase +{ + kDSPI_ClockPhaseFirstEdge = 0U, /*!< CPHA=0. Data is captured on the leading edge of the SCK and changed on the + following edge.*/ + kDSPI_ClockPhaseSecondEdge = 1U /*!< CPHA=1. Data is changed on the leading edge of the SCK and captured on the + following edge.*/ +} dspi_clock_phase_t; + +/*! @brief DSPI data shifter direction options for a given CTAR.*/ +typedef enum _dspi_shift_direction +{ + kDSPI_MsbFirst = 0U, /*!< Data transfers start with most significant bit.*/ + kDSPI_LsbFirst = 1U /*!< Data transfers start with least significant bit. + Shifting out of LSB is not supported for slave */ +} dspi_shift_direction_t; + +/*! @brief DSPI delay type selection.*/ +typedef enum _dspi_delay_type +{ + kDSPI_PcsToSck = 1U, /*!< Pcs-to-SCK delay. */ + kDSPI_LastSckToPcs, /*!< The last SCK edge to Pcs delay. */ + kDSPI_BetweenTransfer /*!< Delay between transfers. */ +} dspi_delay_type_t; + +/*! @brief DSPI Clock and Transfer Attributes Register (CTAR) selection.*/ +typedef enum _dspi_ctar_selection +{ + kDSPI_Ctar0 = 0U, /*!< CTAR0 selection option for master or slave mode; note that CTAR0 and CTAR0_SLAVE are the + same register address. */ + kDSPI_Ctar1 = 1U, /*!< CTAR1 selection option for master mode only. */ + kDSPI_Ctar2 = 2U, /*!< CTAR2 selection option for master mode only; note that some devices do not support CTAR2. */ + kDSPI_Ctar3 = 3U, /*!< CTAR3 selection option for master mode only; note that some devices do not support CTAR3. */ + kDSPI_Ctar4 = 4U, /*!< CTAR4 selection option for master mode only; note that some devices do not support CTAR4. */ + kDSPI_Ctar5 = 5U, /*!< CTAR5 selection option for master mode only; note that some devices do not support CTAR5. */ + kDSPI_Ctar6 = 6U, /*!< CTAR6 selection option for master mode only; note that some devices do not support CTAR6. */ + kDSPI_Ctar7 = 7U /*!< CTAR7 selection option for master mode only; note that some devices do not support CTAR7. */ +} dspi_ctar_selection_t; + +#define DSPI_MASTER_CTAR_SHIFT (0U) /*!< DSPI master CTAR shift macro; used internally. */ +#define DSPI_MASTER_CTAR_MASK (0x0FU) /*!< DSPI master CTAR mask macro; used internally. */ +#define DSPI_MASTER_PCS_SHIFT (4U) /*!< DSPI master PCS shift macro; used internally. */ +#define DSPI_MASTER_PCS_MASK (0xF0U) /*!< DSPI master PCS mask macro; used internally. */ +/*! @brief Use this enumeration for the DSPI master transfer configFlags. */ +enum _dspi_transfer_config_flag_for_master +{ + kDSPI_MasterCtar0 = 0U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR0 setting. */ + kDSPI_MasterCtar1 = 1U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR1 setting. */ + kDSPI_MasterCtar2 = 2U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR2 setting. */ + kDSPI_MasterCtar3 = 3U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR3 setting. */ + kDSPI_MasterCtar4 = 4U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR4 setting. */ + kDSPI_MasterCtar5 = 5U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR5 setting. */ + kDSPI_MasterCtar6 = 6U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR6 setting. */ + kDSPI_MasterCtar7 = 7U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR7 setting. */ + + kDSPI_MasterPcs0 = 0U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS0 signal. */ + kDSPI_MasterPcs1 = 1U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS1 signal. */ + kDSPI_MasterPcs2 = 2U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS2 signal.*/ + kDSPI_MasterPcs3 = 3U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS3 signal. */ + kDSPI_MasterPcs4 = 4U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS4 signal. */ + kDSPI_MasterPcs5 = 5U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS5 signal. */ + + kDSPI_MasterPcsContinuous = 1U << 20, /*!< Indicates whether the PCS signal is continuous. */ + kDSPI_MasterActiveAfterTransfer = 1U << 21, /*!< Indicates whether the PCS signal is active after the last frame transfer.*/ +}; + +#define DSPI_SLAVE_CTAR_SHIFT (0U) /*!< DSPI slave CTAR shift macro; used internally. */ +#define DSPI_SLAVE_CTAR_MASK (0x07U) /*!< DSPI slave CTAR mask macro; used internally. */ +/*! @brief Use this enumeration for the DSPI slave transfer configFlags. */ +enum _dspi_transfer_config_flag_for_slave +{ + kDSPI_SlaveCtar0 = 0U << DSPI_SLAVE_CTAR_SHIFT, /*!< DSPI slave transfer use CTAR0 setting. */ + /*!< DSPI slave can only use PCS0. */ +}; + +/*! @brief DSPI transfer state, which is used for DSPI transactional API state machine. */ +enum _dspi_transfer_state +{ + kDSPI_Idle = 0x0U, /*!< Nothing in the transmitter/receiver. */ + kDSPI_Busy, /*!< Transfer queue is not finished. */ + kDSPI_Error /*!< Transfer error. */ +}; + +/*! @brief DSPI master command date configuration used for the SPIx_PUSHR.*/ +typedef struct _dspi_command_data_config +{ + bool isPcsContinuous; /*!< Option to enable the continuous assertion of the chip select between transfers.*/ + dspi_ctar_selection_t whichCtar; /*!< The desired Clock and Transfer Attributes + Register (CTAR) to use for CTAS.*/ + dspi_which_pcs_t whichPcs; /*!< The desired PCS signal to use for the data transfer.*/ + bool isEndOfQueue; /*!< Signals that the current transfer is the last in the queue.*/ + bool clearTransferCount; /*!< Clears the SPI Transfer Counter (SPI_TCNT) before transmission starts.*/ +} dspi_command_data_config_t; + +/*! @brief DSPI master ctar configuration structure.*/ +typedef struct _dspi_master_ctar_config +{ + uint32_t baudRate; /*!< Baud Rate for DSPI. */ + uint32_t bitsPerFrame; /*!< Bits per frame, minimum 4, maximum 16.*/ + dspi_clock_polarity_t cpol; /*!< Clock polarity. */ + dspi_clock_phase_t cpha; /*!< Clock phase. */ + dspi_shift_direction_t direction; /*!< MSB or LSB data shift direction. */ + + uint32_t pcsToSckDelayInNanoSec; /*!< PCS to SCK delay time in nanoseconds; setting to 0 sets the minimum + delay. It also sets the boundary value if out of range.*/ + uint32_t lastSckToPcsDelayInNanoSec; /*!< The last SCK to PCS delay time in nanoseconds; setting to 0 sets the + minimum delay. It also sets the boundary value if out of range.*/ + + uint32_t betweenTransferDelayInNanoSec; /*!< After the SCK delay time in nanoseconds; setting to 0 sets the minimum + delay. It also sets the boundary value if out of range.*/ +} dspi_master_ctar_config_t; + +/*! @brief DSPI master configuration structure.*/ +typedef struct _dspi_master_config +{ + dspi_ctar_selection_t whichCtar; /*!< The desired CTAR to use. */ + dspi_master_ctar_config_t ctarConfig; /*!< Set the ctarConfig to the desired CTAR. */ + + dspi_which_pcs_t whichPcs; /*!< The desired Peripheral Chip Select (pcs). */ + dspi_pcs_polarity_config_t pcsActiveHighOrLow; /*!< The desired PCS active high or low. */ + + bool enableContinuousSCK; /*!< CONT_SCKE, continuous SCK enable. Note that the continuous SCK is only + supported for CPHA = 1.*/ + bool enableRxFifoOverWrite; /*!< ROOE, receive FIFO overflow overwrite enable. If ROOE = 0, the incoming + data is ignored and the data from the transfer that generated the overflow + is also ignored. If ROOE = 1, the incoming data is shifted to the + shift register. */ + + bool enableModifiedTimingFormat; /*!< Enables a modified transfer format to be used if true.*/ + dspi_master_sample_point_t samplePoint; /*!< Controls when the module master samples SIN in the Modified Transfer + Format. It's valid only when CPHA=0. */ +} dspi_master_config_t; + +/*! @brief DSPI slave ctar configuration structure.*/ +typedef struct _dspi_slave_ctar_config +{ + uint32_t bitsPerFrame; /*!< Bits per frame, minimum 4, maximum 16.*/ + dspi_clock_polarity_t cpol; /*!< Clock polarity. */ + dspi_clock_phase_t cpha; /*!< Clock phase. */ + /*!< Slave only supports MSB and does not support LSB.*/ +} dspi_slave_ctar_config_t; + +/*! @brief DSPI slave configuration structure.*/ +typedef struct _dspi_slave_config +{ + dspi_ctar_selection_t whichCtar; /*!< The desired CTAR to use. */ + dspi_slave_ctar_config_t ctarConfig; /*!< Set the ctarConfig to the desired CTAR. */ + + bool enableContinuousSCK; /*!< CONT_SCKE, continuous SCK enable. Note that the continuous SCK is only + supported for CPHA = 1.*/ + bool enableRxFifoOverWrite; /*!< ROOE, receive FIFO overflow overwrite enable. If ROOE = 0, the incoming + data is ignored and the data from the transfer that generated the overflow + is also ignored. If ROOE = 1, the incoming data is shifted to the + shift register. */ + bool enableModifiedTimingFormat; /*!< Enables a modified transfer format to be used if true.*/ + dspi_master_sample_point_t samplePoint; /*!< Controls when the module master samples SIN in the Modified Transfer + Format. It's valid only when CPHA=0. */ +} dspi_slave_config_t; + +/*! +* @brief Forward declaration of the _dspi_master_handle typedefs. +*/ +typedef struct _dspi_master_handle dspi_master_handle_t; + +/*! +* @brief Forward declaration of the _dspi_slave_handle typedefs. +*/ +typedef struct _dspi_slave_handle dspi_slave_handle_t; + +/*! + * @brief Completion callback function pointer type. + * + * @param base DSPI peripheral address. + * @param handle Pointer to the handle for the DSPI master. + * @param status Success or error code describing whether the transfer completed. + * @param userData Arbitrary pointer-dataSized value passed from the application. + */ +typedef void (*dspi_master_transfer_callback_t)(SPI_Type *base, + dspi_master_handle_t *handle, + status_t status, + void *userData); +/*! + * @brief Completion callback function pointer type. + * + * @param base DSPI peripheral address. + * @param handle Pointer to the handle for the DSPI slave. + * @param status Success or error code describing whether the transfer completed. + * @param userData Arbitrary pointer-dataSized value passed from the application. + */ +typedef void (*dspi_slave_transfer_callback_t)(SPI_Type *base, + dspi_slave_handle_t *handle, + status_t status, + void *userData); + +/*! @brief DSPI master/slave transfer structure.*/ +typedef struct _dspi_transfer +{ + uint8_t *txData; /*!< Send buffer. */ + uint8_t *rxData; /*!< Receive buffer. */ + volatile size_t dataSize; /*!< Transfer bytes. */ + + uint32_t + configFlags; /*!< Transfer transfer configuration flags; set from _dspi_transfer_config_flag_for_master if the + transfer is used for master or _dspi_transfer_config_flag_for_slave enumeration if the transfer + is used for slave.*/ +} dspi_transfer_t; + +/*! @brief DSPI master transfer handle structure used for transactional API. */ +struct _dspi_master_handle +{ + uint32_t bitsPerFrame; /*!< The desired number of bits per frame. */ + volatile uint32_t command; /*!< The desired data command. */ + volatile uint32_t lastCommand; /*!< The desired last data command. */ + + uint8_t fifoSize; /*!< FIFO dataSize. */ + + volatile bool isPcsActiveAfterTransfer; /*!< Indicates whether the PCS signal is active after the last frame transfer.*/ + volatile bool isThereExtraByte; /*!< Indicates whether there are extra bytes.*/ + + uint8_t *volatile txData; /*!< Send buffer. */ + uint8_t *volatile rxData; /*!< Receive buffer. */ + volatile size_t remainingSendByteCount; /*!< A number of bytes remaining to send.*/ + volatile size_t remainingReceiveByteCount; /*!< A number of bytes remaining to receive.*/ + size_t totalByteCount; /*!< A number of transfer bytes*/ + + volatile uint8_t state; /*!< DSPI transfer state, see _dspi_transfer_state.*/ + + dspi_master_transfer_callback_t callback; /*!< Completion callback. */ + void *userData; /*!< Callback user data. */ +}; + +/*! @brief DSPI slave transfer handle structure used for the transactional API. */ +struct _dspi_slave_handle +{ + uint32_t bitsPerFrame; /*!< The desired number of bits per frame. */ + volatile bool isThereExtraByte; /*!< Indicates whether there are extra bytes.*/ + + uint8_t *volatile txData; /*!< Send buffer. */ + uint8_t *volatile rxData; /*!< Receive buffer. */ + volatile size_t remainingSendByteCount; /*!< A number of bytes remaining to send.*/ + volatile size_t remainingReceiveByteCount; /*!< A number of bytes remaining to receive.*/ + size_t totalByteCount; /*!< A number of transfer bytes*/ + + volatile uint8_t state; /*!< DSPI transfer state.*/ + + volatile uint32_t errorCount; /*!< Error count for slave transfer.*/ + + dspi_slave_transfer_callback_t callback; /*!< Completion callback. */ + void *userData; /*!< Callback user data. */ +}; + +/********************************************************************************************************************** + * API + *********************************************************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /*_cplusplus*/ + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Initializes the DSPI master. + * + * This function initializes the DSPI master configuration. This is an example use case. + * @code + * dspi_master_config_t masterConfig; + * masterConfig.whichCtar = kDSPI_Ctar0; + * masterConfig.ctarConfig.baudRate = 500000000U; + * masterConfig.ctarConfig.bitsPerFrame = 8; + * masterConfig.ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh; + * masterConfig.ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge; + * masterConfig.ctarConfig.direction = kDSPI_MsbFirst; + * masterConfig.ctarConfig.pcsToSckDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ; + * masterConfig.ctarConfig.lastSckToPcsDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ; + * masterConfig.ctarConfig.betweenTransferDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ; + * masterConfig.whichPcs = kDSPI_Pcs0; + * masterConfig.pcsActiveHighOrLow = kDSPI_PcsActiveLow; + * masterConfig.enableContinuousSCK = false; + * masterConfig.enableRxFifoOverWrite = false; + * masterConfig.enableModifiedTimingFormat = false; + * masterConfig.samplePoint = kDSPI_SckToSin0Clock; + * DSPI_MasterInit(base, &masterConfig, srcClock_Hz); + * @endcode + * + * @param base DSPI peripheral address. + * @param masterConfig Pointer to the structure dspi_master_config_t. + * @param srcClock_Hz Module source input clock in Hertz. + */ +void DSPI_MasterInit(SPI_Type *base, const dspi_master_config_t *masterConfig, uint32_t srcClock_Hz); + +/*! + * @brief Sets the dspi_master_config_t structure to default values. + * + * The purpose of this API is to get the configuration structure initialized for the DSPI_MasterInit(). + * Users may use the initialized structure unchanged in the DSPI_MasterInit() or modify the structure + * before calling the DSPI_MasterInit(). + * Example: + * @code + * dspi_master_config_t masterConfig; + * DSPI_MasterGetDefaultConfig(&masterConfig); + * @endcode + * @param masterConfig pointer to dspi_master_config_t structure + */ +void DSPI_MasterGetDefaultConfig(dspi_master_config_t *masterConfig); + +/*! + * @brief DSPI slave configuration. + * + * This function initializes the DSPI slave configuration. This is an example use case. + * @code + * dspi_slave_config_t slaveConfig; + * slaveConfig->whichCtar = kDSPI_Ctar0; + * slaveConfig->ctarConfig.bitsPerFrame = 8; + * slaveConfig->ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh; + * slaveConfig->ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge; + * slaveConfig->enableContinuousSCK = false; + * slaveConfig->enableRxFifoOverWrite = false; + * slaveConfig->enableModifiedTimingFormat = false; + * slaveConfig->samplePoint = kDSPI_SckToSin0Clock; + * DSPI_SlaveInit(base, &slaveConfig); + * @endcode + * + * @param base DSPI peripheral address. + * @param slaveConfig Pointer to the structure dspi_master_config_t. + */ +void DSPI_SlaveInit(SPI_Type *base, const dspi_slave_config_t *slaveConfig); + +/*! + * @brief Sets the dspi_slave_config_t structure to a default value. + * + * The purpose of this API is to get the configuration structure initialized for the DSPI_SlaveInit(). + * Users may use the initialized structure unchanged in the DSPI_SlaveInit() or modify the structure + * before calling the DSPI_SlaveInit(). + * This is an example. + * @code + * dspi_slave_config_t slaveConfig; + * DSPI_SlaveGetDefaultConfig(&slaveConfig); + * @endcode + * @param slaveConfig Pointer to the dspi_slave_config_t structure. + */ +void DSPI_SlaveGetDefaultConfig(dspi_slave_config_t *slaveConfig); + +/*! + * @brief De-initializes the DSPI peripheral. Call this API to disable the DSPI clock. + * @param base DSPI peripheral address. + */ +void DSPI_Deinit(SPI_Type *base); + +/*! + * @brief Enables the DSPI peripheral and sets the MCR MDIS to 0. + * + * @param base DSPI peripheral address. + * @param enable Pass true to enable module, false to disable module. + */ +static inline void DSPI_Enable(SPI_Type *base, bool enable) +{ + if (enable) + { + base->MCR &= ~SPI_MCR_MDIS_MASK; + } + else + { + base->MCR |= SPI_MCR_MDIS_MASK; + } +} + +/*! + *@} +*/ + +/*! + * @name Status + * @{ + */ + +/*! + * @brief Gets the DSPI status flag state. + * @param base DSPI peripheral address. + * @return DSPI status (in SR register). + */ +static inline uint32_t DSPI_GetStatusFlags(SPI_Type *base) +{ + return (base->SR); +} + +/*! + * @brief Clears the DSPI status flag. + * + * This function clears the desired status bit by using a write-1-to-clear. The user passes in the base and the + * desired status bit to clear. The list of status bits is defined in the dspi_status_and_interrupt_request_t. The + * function uses these bit positions in its algorithm to clear the desired flag state. + * This is an example. + * @code + * DSPI_ClearStatusFlags(base, kDSPI_TxCompleteFlag|kDSPI_EndOfQueueFlag); + * @endcode + * + * @param base DSPI peripheral address. + * @param statusFlags The status flag used from the type dspi_flags. + */ +static inline void DSPI_ClearStatusFlags(SPI_Type *base, uint32_t statusFlags) +{ + base->SR = statusFlags; /*!< The status flags are cleared by writing 1 (w1c).*/ +} + +/*! + *@} +*/ + +/*! + * @name Interrupts + * @{ + */ + +/*! + * @brief Enables the DSPI interrupts. + * + * This function configures the various interrupt masks of the DSPI. The parameters are a base and an interrupt mask. + * Note, for Tx Fill and Rx FIFO drain requests, enable the interrupt request and disable the DMA request. + * + * @code + * DSPI_EnableInterrupts(base, kDSPI_TxCompleteInterruptEnable | kDSPI_EndOfQueueInterruptEnable ); + * @endcode + * + * @param base DSPI peripheral address. + * @param mask The interrupt mask; use the enum _dspi_interrupt_enable. + */ +void DSPI_EnableInterrupts(SPI_Type *base, uint32_t mask); + +/*! + * @brief Disables the DSPI interrupts. + * + * @code + * DSPI_DisableInterrupts(base, kDSPI_TxCompleteInterruptEnable | kDSPI_EndOfQueueInterruptEnable ); + * @endcode + * + * @param base DSPI peripheral address. + * @param mask The interrupt mask; use the enum _dspi_interrupt_enable. + */ +static inline void DSPI_DisableInterrupts(SPI_Type *base, uint32_t mask) +{ + base->RSER &= ~mask; +} + +/*! + *@} +*/ + +/*! + * @name DMA Control + * @{ + */ + +/*! + * @brief Enables the DSPI DMA request. + * + * This function configures the Rx and Tx DMA mask of the DSPI. The parameters are a base and a DMA mask. + * @code + * DSPI_EnableDMA(base, kDSPI_TxDmaEnable | kDSPI_RxDmaEnable); + * @endcode + * + * @param base DSPI peripheral address. + * @param mask The interrupt mask; use the enum dspi_dma_enable. + */ +static inline void DSPI_EnableDMA(SPI_Type *base, uint32_t mask) +{ + base->RSER |= mask; +} + +/*! + * @brief Disables the DSPI DMA request. + * + * This function configures the Rx and Tx DMA mask of the DSPI. The parameters are a base and a DMA mask. + * @code + * SPI_DisableDMA(base, kDSPI_TxDmaEnable | kDSPI_RxDmaEnable); + * @endcode + * + * @param base DSPI peripheral address. + * @param mask The interrupt mask; use the enum dspi_dma_enable. + */ +static inline void DSPI_DisableDMA(SPI_Type *base, uint32_t mask) +{ + base->RSER &= ~mask; +} + +/*! + * @brief Gets the DSPI master PUSHR data register address for the DMA operation. + * + * This function gets the DSPI master PUSHR data register address because this value is needed for the DMA operation. + * + * @param base DSPI peripheral address. + * @return The DSPI master PUSHR data register address. + */ +static inline uint32_t DSPI_MasterGetTxRegisterAddress(SPI_Type *base) +{ + return (uint32_t) & (base->PUSHR); +} + +/*! + * @brief Gets the DSPI slave PUSHR data register address for the DMA operation. + * + * This function gets the DSPI slave PUSHR data register address as this value is needed for the DMA operation. + * + * @param base DSPI peripheral address. + * @return The DSPI slave PUSHR data register address. + */ +static inline uint32_t DSPI_SlaveGetTxRegisterAddress(SPI_Type *base) +{ + return (uint32_t) & (base->PUSHR_SLAVE); +} + +/*! + * @brief Gets the DSPI POPR data register address for the DMA operation. + * + * This function gets the DSPI POPR data register address as this value is needed for the DMA operation. + * + * @param base DSPI peripheral address. + * @return The DSPI POPR data register address. + */ +static inline uint32_t DSPI_GetRxRegisterAddress(SPI_Type *base) +{ + return (uint32_t) & (base->POPR); +} + +/*! + *@} +*/ + +/*! + * @name Bus Operations + * @{ + */ + +/*! + * @brief Configures the DSPI for master or slave. + * + * @param base DSPI peripheral address. + * @param mode Mode setting (master or slave) of type dspi_master_slave_mode_t. + */ +static inline void DSPI_SetMasterSlaveMode(SPI_Type *base, dspi_master_slave_mode_t mode) +{ + base->MCR = (base->MCR & (~SPI_MCR_MSTR_MASK)) | SPI_MCR_MSTR(mode); +} + +/*! + * @brief Returns whether the DSPI module is in master mode. + * + * @param base DSPI peripheral address. + * @return Returns true if the module is in master mode or false if the module is in slave mode. + */ +static inline bool DSPI_IsMaster(SPI_Type *base) +{ + return (bool)((base->MCR) & SPI_MCR_MSTR_MASK); +} +/*! + * @brief Starts the DSPI transfers and clears HALT bit in MCR. + * + * This function sets the module to start data transfer in either master or slave mode. + * + * @param base DSPI peripheral address. + */ +static inline void DSPI_StartTransfer(SPI_Type *base) +{ + base->MCR &= ~SPI_MCR_HALT_MASK; +} +/*! + * @brief Stops DSPI transfers and sets the HALT bit in MCR. + * + * This function stops data transfers in either master or slave modes. + * + * @param base DSPI peripheral address. + */ +static inline void DSPI_StopTransfer(SPI_Type *base) +{ + base->MCR |= SPI_MCR_HALT_MASK; +} + +/*! + * @brief Enables or disables the DSPI FIFOs. + * + * This function allows the caller to disable/enable the Tx and Rx FIFOs independently. + * Note that to disable, pass in a logic 0 (false) for the particular FIFO configuration. To enable, + * pass in a logic 1 (true). + * + * @param base DSPI peripheral address. + * @param enableTxFifo Disables (false) the TX FIFO; Otherwise, enables (true) the TX FIFO + * @param enableRxFifo Disables (false) the RX FIFO; Otherwise, enables (true) the RX FIFO + */ +static inline void DSPI_SetFifoEnable(SPI_Type *base, bool enableTxFifo, bool enableRxFifo) +{ + base->MCR = (base->MCR & (~(SPI_MCR_DIS_RXF_MASK | SPI_MCR_DIS_TXF_MASK))) | SPI_MCR_DIS_TXF(!enableTxFifo) | + SPI_MCR_DIS_RXF(!enableRxFifo); +} + +/*! + * @brief Flushes the DSPI FIFOs. + * + * @param base DSPI peripheral address. + * @param flushTxFifo Flushes (true) the Tx FIFO; Otherwise, does not flush (false) the Tx FIFO + * @param flushRxFifo Flushes (true) the Rx FIFO; Otherwise, does not flush (false) the Rx FIFO + */ +static inline void DSPI_FlushFifo(SPI_Type *base, bool flushTxFifo, bool flushRxFifo) +{ + base->MCR = (base->MCR & (~(SPI_MCR_CLR_TXF_MASK | SPI_MCR_CLR_RXF_MASK))) | SPI_MCR_CLR_TXF(flushTxFifo) | + SPI_MCR_CLR_RXF(flushRxFifo); +} + +/*! + * @brief Configures the DSPI peripheral chip select polarity simultaneously. + * For example, PCS0 and PCS1 are set to active low and other PCS is set to active high. Note that the number of + * PCSs is specific to the device. + * @code + * DSPI_SetAllPcsPolarity(base, kDSPI_Pcs0ActiveLow | kDSPI_Pcs1ActiveLow); + @endcode + * @param base DSPI peripheral address. + * @param mask The PCS polarity mask; use the enum _dspi_pcs_polarity. + */ +static inline void DSPI_SetAllPcsPolarity(SPI_Type *base, uint32_t mask) +{ + base->MCR = (base->MCR & ~SPI_MCR_PCSIS_MASK) | SPI_MCR_PCSIS(mask); +} + +/*! + * @brief Sets the DSPI baud rate in bits per second. + * + * This function takes in the desired baudRate_Bps (baud rate) and calculates the nearest possible baud rate without + * exceeding the desired baud rate, and returns the calculated baud rate in bits-per-second. It requires that the + * caller also provide the frequency of the module source clock (in Hertz). + * + * @param base DSPI peripheral address. + * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of the type dspi_ctar_selection_t + * @param baudRate_Bps The desired baud rate in bits per second + * @param srcClock_Hz Module source input clock in Hertz + * @return The actual calculated baud rate + */ +uint32_t DSPI_MasterSetBaudRate(SPI_Type *base, + dspi_ctar_selection_t whichCtar, + uint32_t baudRate_Bps, + uint32_t srcClock_Hz); + +/*! + * @brief Manually configures the delay prescaler and scaler for a particular CTAR. + * + * This function configures the PCS to SCK delay pre-scalar (PcsSCK) and scalar (CSSCK), after SCK delay pre-scalar + * (PASC) and scalar (ASC), and the delay after transfer pre-scalar (PDT) and scalar (DT). + * + * These delay names are available in the type dspi_delay_type_t. + * + * The user passes the delay to the configuration along with the prescaler and scaler value. + * This allows the user to directly set the prescaler/scaler values if pre-calculated or + * to manually increment either value. + * + * @param base DSPI peripheral address. + * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type dspi_ctar_selection_t. + * @param prescaler The prescaler delay value (can be an integer 0, 1, 2, or 3). + * @param scaler The scaler delay value (can be any integer between 0 to 15). + * @param whichDelay The desired delay to configure; must be of type dspi_delay_type_t + */ +void DSPI_MasterSetDelayScaler( + SPI_Type *base, dspi_ctar_selection_t whichCtar, uint32_t prescaler, uint32_t scaler, dspi_delay_type_t whichDelay); + +/*! + * @brief Calculates the delay prescaler and scaler based on the desired delay input in nanoseconds. + * + * This function calculates the values for the following. + * PCS to SCK delay pre-scalar (PCSSCK) and scalar (CSSCK), or + * After SCK delay pre-scalar (PASC) and scalar (ASC), or + * Delay after transfer pre-scalar (PDT) and scalar (DT). + * + * These delay names are available in the type dspi_delay_type_t. + * + * The user passes which delay to configure along with the desired delay value in nanoseconds. The function + * calculates the values needed for the prescaler and scaler. Note that returning the calculated delay as an exact + * delay match may not be possible. In this case, the closest match is calculated without going below the desired + * delay value input. + * It is possible to input a very large delay value that exceeds the capability of the part, in which case the maximum + * supported delay is returned. The higher-level peripheral driver alerts the user of an out of range delay + * input. + * + * @param base DSPI peripheral address. + * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type dspi_ctar_selection_t. + * @param whichDelay The desired delay to configure, must be of type dspi_delay_type_t + * @param srcClock_Hz Module source input clock in Hertz + * @param delayTimeInNanoSec The desired delay value in nanoseconds. + * @return The actual calculated delay value. + */ +uint32_t DSPI_MasterSetDelayTimes(SPI_Type *base, + dspi_ctar_selection_t whichCtar, + dspi_delay_type_t whichDelay, + uint32_t srcClock_Hz, + uint32_t delayTimeInNanoSec); + +/*! + * @brief Writes data into the data buffer for master mode. + * + * In master mode, the 16-bit data is appended to the 16-bit command info. The command portion + * provides characteristics of the data, such as the optional continuous chip select + * operation between transfers, the desired Clock and Transfer Attributes register to use for the + * associated SPI frame, the desired PCS signal to use for the data transfer, whether the current + * transfer is the last in the queue, and whether to clear the transfer count (normally needed when + * sending the first frame of a data packet). This is an example. + * @code + * dspi_command_data_config_t commandConfig; + * commandConfig.isPcsContinuous = true; + * commandConfig.whichCtar = kDSPICtar0; + * commandConfig.whichPcs = kDSPIPcs0; + * commandConfig.clearTransferCount = false; + * commandConfig.isEndOfQueue = false; + * DSPI_MasterWriteData(base, &commandConfig, dataWord); + @endcode + * + * @param base DSPI peripheral address. + * @param command Pointer to the command structure. + * @param data The data word to be sent. + */ +static inline void DSPI_MasterWriteData(SPI_Type *base, dspi_command_data_config_t *command, uint16_t data) +{ + base->PUSHR = SPI_PUSHR_CONT(command->isPcsContinuous) | SPI_PUSHR_CTAS(command->whichCtar) | + SPI_PUSHR_PCS(command->whichPcs) | SPI_PUSHR_EOQ(command->isEndOfQueue) | + SPI_PUSHR_CTCNT(command->clearTransferCount) | SPI_PUSHR_TXDATA(data); +} + +/*! + * @brief Sets the dspi_command_data_config_t structure to default values. + * + * The purpose of this API is to get the configuration structure initialized for use in the DSPI_MasterWrite_xx(). + * Users may use the initialized structure unchanged in the DSPI_MasterWrite_xx() or modify the structure + * before calling the DSPI_MasterWrite_xx(). + * This is an example. + * @code + * dspi_command_data_config_t command; + * DSPI_GetDefaultDataCommandConfig(&command); + * @endcode + * @param command Pointer to the dspi_command_data_config_t structure. + */ +void DSPI_GetDefaultDataCommandConfig(dspi_command_data_config_t *command); + +/*! + * @brief Writes data into the data buffer master mode and waits till complete to return. + * + * In master mode, the 16-bit data is appended to the 16-bit command info. The command portion + * provides characteristics of the data, such as the optional continuous chip select + * operation between transfers, the desired Clock and Transfer Attributes register to use for the + * associated SPI frame, the desired PCS signal to use for the data transfer, whether the current + * transfer is the last in the queue, and whether to clear the transfer count (normally needed when + * sending the first frame of a data packet). This is an example. + * @code + * dspi_command_config_t commandConfig; + * commandConfig.isPcsContinuous = true; + * commandConfig.whichCtar = kDSPICtar0; + * commandConfig.whichPcs = kDSPIPcs1; + * commandConfig.clearTransferCount = false; + * commandConfig.isEndOfQueue = false; + * DSPI_MasterWriteDataBlocking(base, &commandConfig, dataWord); + * @endcode + * + * Note that this function does not return until after the transmit is complete. Also note that the DSPI must be + * enabled and running to transmit data (MCR[MDIS] & [HALT] = 0). Because the SPI is a synchronous protocol, + * the received data is available when the transmit completes. + * + * @param base DSPI peripheral address. + * @param command Pointer to the command structure. + * @param data The data word to be sent. + */ +void DSPI_MasterWriteDataBlocking(SPI_Type *base, dspi_command_data_config_t *command, uint16_t data); + +/*! + * @brief Returns the DSPI command word formatted to the PUSHR data register bit field. + * + * This function allows the caller to pass in the data command structure and returns the command word formatted + * according to the DSPI PUSHR register bit field placement. The user can then "OR" the returned command word with the + * desired data to send and use the function DSPI_HAL_WriteCommandDataMastermode or + * DSPI_HAL_WriteCommandDataMastermodeBlocking to write the entire 32-bit command data word to the PUSHR. This helps + * improve performance in cases where the command structure is constant. For example, the user calls this function + * before starting a transfer to generate the command word. When they are ready to transmit the data, they OR + * this formatted command word with the desired data to transmit. This process increases transmit performance when + * compared to calling send functions, such as DSPI_HAL_WriteDataMastermode, which format the command word each time a + * data word is to be sent. + * + * @param command Pointer to the command structure. + * @return The command word formatted to the PUSHR data register bit field. + */ +static inline uint32_t DSPI_MasterGetFormattedCommand(dspi_command_data_config_t *command) +{ + /* Format the 16-bit command word according to the PUSHR data register bit field*/ + return (uint32_t)(SPI_PUSHR_CONT(command->isPcsContinuous) | SPI_PUSHR_CTAS(command->whichCtar) | + SPI_PUSHR_PCS(command->whichPcs) | SPI_PUSHR_EOQ(command->isEndOfQueue) | + SPI_PUSHR_CTCNT(command->clearTransferCount)); +} + +/*! + * @brief Writes a 32-bit data word (16-bit command appended with 16-bit data) into the data + * buffer master mode and waits till complete to return. + * + * In this function, the user must append the 16-bit data to the 16-bit command information and then provide the total 32-bit word + * as the data to send. + * The command portion provides characteristics of the data, such as the optional continuous chip select operation + * between transfers, the desired Clock and Transfer Attributes register to use for the associated SPI frame, the desired PCS + * signal to use for the data transfer, whether the current transfer is the last in the queue, and whether to clear the + * transfer count (normally needed when sending the first frame of a data packet). The user is responsible for + * appending this command with the data to send. This is an example: + * @code + * dataWord = <16-bit command> | <16-bit data>; + * DSPI_MasterWriteCommandDataBlocking(base, dataWord); + * @endcode + * + * Note that this function does not return until after the transmit is complete. Also note that the DSPI must be + * enabled and running to transmit data (MCR[MDIS] & [HALT] = 0). + * Because the SPI is a synchronous protocol, the received data is available when the transmit completes. + * + * For a blocking polling transfer, see methods below. + * Option 1: +* uint32_t command_to_send = DSPI_MasterGetFormattedCommand(&command); +* uint32_t data0 = command_to_send | data_need_to_send_0; +* uint32_t data1 = command_to_send | data_need_to_send_1; +* uint32_t data2 = command_to_send | data_need_to_send_2; +* +* DSPI_MasterWriteCommandDataBlocking(base,data0); +* DSPI_MasterWriteCommandDataBlocking(base,data1); +* DSPI_MasterWriteCommandDataBlocking(base,data2); +* +* Option 2: +* DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_0); +* DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_1); +* DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_2); +* + * @param base DSPI peripheral address. + * @param data The data word (command and data combined) to be sent. + */ +void DSPI_MasterWriteCommandDataBlocking(SPI_Type *base, uint32_t data); + +/*! + * @brief Writes data into the data buffer in slave mode. + * + * In slave mode, up to 16-bit words may be written. + * + * @param base DSPI peripheral address. + * @param data The data to send. + */ +static inline void DSPI_SlaveWriteData(SPI_Type *base, uint32_t data) +{ + base->PUSHR_SLAVE = data; +} + +/*! + * @brief Writes data into the data buffer in slave mode, waits till data was transmitted, and returns. + * + * In slave mode, up to 16-bit words may be written. The function first clears the transmit complete flag, writes data + * into data register, and finally waits until the data is transmitted. + * + * @param base DSPI peripheral address. + * @param data The data to send. + */ +void DSPI_SlaveWriteDataBlocking(SPI_Type *base, uint32_t data); + +/*! + * @brief Reads data from the data buffer. + * + * @param base DSPI peripheral address. + * @return The data from the read data buffer. + */ +static inline uint32_t DSPI_ReadData(SPI_Type *base) +{ + return (base->POPR); +} + +/*! + *@} +*/ + +/*! + * @name Transactional + * @{ + */ +/*Transactional APIs*/ + +/*! + * @brief Initializes the DSPI master handle. + * + * This function initializes the DSPI handle, which can be used for other DSPI transactional APIs. Usually, for a + * specified DSPI instance, call this API once to get the initialized handle. + * + * @param base DSPI peripheral base address. + * @param handle DSPI handle pointer to dspi_master_handle_t. + * @param callback DSPI callback. + * @param userData Callback function parameter. + */ +void DSPI_MasterTransferCreateHandle(SPI_Type *base, + dspi_master_handle_t *handle, + dspi_master_transfer_callback_t callback, + void *userData); + +/*! + * @brief DSPI master transfer data using polling. + * + * This function transfers data using polling. This is a blocking function, which does not return until all transfers + * have been completed. + * + * @param base DSPI peripheral base address. + * @param transfer Pointer to the dspi_transfer_t structure. + * @return status of status_t. + */ +status_t DSPI_MasterTransferBlocking(SPI_Type *base, dspi_transfer_t *transfer); + +/*! + * @brief DSPI master transfer data using interrupts. + * + * This function transfers data using interrupts. This is a non-blocking function, which returns right away. When all + * data is transferred, the callback function is called. + + * @param base DSPI peripheral base address. + * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. + * @param transfer Pointer to the dspi_transfer_t structure. + * @return status of status_t. + */ +status_t DSPI_MasterTransferNonBlocking(SPI_Type *base, dspi_master_handle_t *handle, dspi_transfer_t *transfer); + +/*! + * @brief Gets the master transfer count. + * + * This function gets the master transfer count. + * + * @param base DSPI peripheral base address. + * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. + * @param count The number of bytes transferred by using the non-blocking transaction. + * @return status of status_t. + */ +status_t DSPI_MasterTransferGetCount(SPI_Type *base, dspi_master_handle_t *handle, size_t *count); + +/*! + * @brief DSPI master aborts a transfer using an interrupt. + * + * This function aborts a transfer using an interrupt. + * + * @param base DSPI peripheral base address. + * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. + */ +void DSPI_MasterTransferAbort(SPI_Type *base, dspi_master_handle_t *handle); + +/*! + * @brief DSPI Master IRQ handler function. + * + * This function processes the DSPI transmit and receive IRQ. + + * @param base DSPI peripheral base address. + * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. + */ +void DSPI_MasterTransferHandleIRQ(SPI_Type *base, dspi_master_handle_t *handle); + +/*! + * @brief Initializes the DSPI slave handle. + * + * This function initializes the DSPI handle, which can be used for other DSPI transactional APIs. Usually, for a + * specified DSPI instance, call this API once to get the initialized handle. + * + * @param handle DSPI handle pointer to the dspi_slave_handle_t. + * @param base DSPI peripheral base address. + * @param callback DSPI callback. + * @param userData Callback function parameter. + */ +void DSPI_SlaveTransferCreateHandle(SPI_Type *base, + dspi_slave_handle_t *handle, + dspi_slave_transfer_callback_t callback, + void *userData); + +/*! + * @brief DSPI slave transfers data using an interrupt. + * + * This function transfers data using an interrupt. This is a non-blocking function, which returns right away. When all + * data is transferred, the callback function is called. + * + * @param base DSPI peripheral base address. + * @param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state. + * @param transfer Pointer to the dspi_transfer_t structure. + * @return status of status_t. + */ +status_t DSPI_SlaveTransferNonBlocking(SPI_Type *base, dspi_slave_handle_t *handle, dspi_transfer_t *transfer); + +/*! + * @brief Gets the slave transfer count. + * + * This function gets the slave transfer count. + * + * @param base DSPI peripheral base address. + * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. + * @param count The number of bytes transferred by using the non-blocking transaction. + * @return status of status_t. + */ +status_t DSPI_SlaveTransferGetCount(SPI_Type *base, dspi_slave_handle_t *handle, size_t *count); + +/*! + * @brief DSPI slave aborts a transfer using an interrupt. + * + * This function aborts a transfer using an interrupt. + * + * @param base DSPI peripheral base address. + * @param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state. + */ +void DSPI_SlaveTransferAbort(SPI_Type *base, dspi_slave_handle_t *handle); + +/*! + * @brief DSPI Master IRQ handler function. + * + * This function processes the DSPI transmit and receive IRQ. + * + * @param base DSPI peripheral base address. + * @param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state. + */ +void DSPI_SlaveTransferHandleIRQ(SPI_Type *base, dspi_slave_handle_t *handle); + +/*! + *@} +*/ + +#if defined(__cplusplus) +} +#endif /*_cplusplus*/ + /*! + *@} + */ + +#endif /*_FSL_DSPI_H_*/ diff --git a/drivers/include/fsl_dspi_edma.h b/drivers/include/fsl_dspi_edma.h new file mode 100644 index 0000000..23e29ce --- /dev/null +++ b/drivers/include/fsl_dspi_edma.h @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_DSPI_EDMA_H_ +#define _FSL_DSPI_EDMA_H_ + +#include "fsl_dspi.h" +#include "fsl_edma.h" +/*! + * @addtogroup dspi_edma_driver + * @{ + */ + +/*********************************************************************************************************************** + * Definitions + **********************************************************************************************************************/ + +/*! +* @brief Forward declaration of the DSPI eDMA master handle typedefs. +*/ +typedef struct _dspi_master_edma_handle dspi_master_edma_handle_t; + +/*! +* @brief Forward declaration of the DSPI eDMA slave handle typedefs. +*/ +typedef struct _dspi_slave_edma_handle dspi_slave_edma_handle_t; + +/*! + * @brief Completion callback function pointer type. + * + * @param base DSPI peripheral base address. + * @param handle A pointer to the handle for the DSPI master. + * @param status Success or error code describing whether the transfer completed. + * @param userData An arbitrary pointer-dataSized value passed from the application. + */ +typedef void (*dspi_master_edma_transfer_callback_t)(SPI_Type *base, + dspi_master_edma_handle_t *handle, + status_t status, + void *userData); +/*! + * @brief Completion callback function pointer type. + * + * @param base DSPI peripheral base address. + * @param handle A pointer to the handle for the DSPI slave. + * @param status Success or error code describing whether the transfer completed. + * @param userData An arbitrary pointer-dataSized value passed from the application. + */ +typedef void (*dspi_slave_edma_transfer_callback_t)(SPI_Type *base, + dspi_slave_edma_handle_t *handle, + status_t status, + void *userData); + +/*! @brief DSPI master eDMA transfer handle structure used for the transactional API. */ +struct _dspi_master_edma_handle +{ + uint32_t bitsPerFrame; /*!< The desired number of bits per frame. */ + volatile uint32_t command; /*!< The desired data command. */ + volatile uint32_t lastCommand; /*!< The desired last data command. */ + + uint8_t fifoSize; /*!< FIFO dataSize. */ + + volatile bool + isPcsActiveAfterTransfer; /*!< Indicates whether the PCS signal keeps active after the last frame transfer.*/ + + uint8_t nbytes; /*!< eDMA minor byte transfer count initially configured. */ + volatile uint8_t state; /*!< DSPI transfer state , _dspi_transfer_state.*/ + + uint8_t *volatile txData; /*!< Send buffer. */ + uint8_t *volatile rxData; /*!< Receive buffer. */ + volatile size_t remainingSendByteCount; /*!< A number of bytes remaining to send.*/ + volatile size_t remainingReceiveByteCount; /*!< A number of bytes remaining to receive.*/ + size_t totalByteCount; /*!< A number of transfer bytes*/ + + uint32_t rxBuffIfNull; /*!< Used if there is not rxData for DMA purpose.*/ + uint32_t txBuffIfNull; /*!< Used if there is not txData for DMA purpose.*/ + + dspi_master_edma_transfer_callback_t callback; /*!< Completion callback. */ + void *userData; /*!< Callback user data. */ + + edma_handle_t *edmaRxRegToRxDataHandle; /*!DCHPRI3))[DMA_DCHPRI_INDEX(channel)] + +/*! @brief eDMA transfer configuration */ +typedef enum _edma_transfer_size +{ + kEDMA_TransferSize1Bytes = 0x0U, /*!< Source/Destination data transfer size is 1 byte every time */ + kEDMA_TransferSize2Bytes = 0x1U, /*!< Source/Destination data transfer size is 2 bytes every time */ + kEDMA_TransferSize4Bytes = 0x2U, /*!< Source/Destination data transfer size is 4 bytes every time */ + kEDMA_TransferSize16Bytes = 0x4U, /*!< Source/Destination data transfer size is 16 bytes every time */ + kEDMA_TransferSize32Bytes = 0x5U, /*!< Source/Destination data transfer size is 32 bytes every time */ +} edma_transfer_size_t; + +/*! @brief eDMA modulo configuration */ +typedef enum _edma_modulo +{ + kEDMA_ModuloDisable = 0x0U, /*!< Disable modulo */ + kEDMA_Modulo2bytes, /*!< Circular buffer size is 2 bytes. */ + kEDMA_Modulo4bytes, /*!< Circular buffer size is 4 bytes. */ + kEDMA_Modulo8bytes, /*!< Circular buffer size is 8 bytes. */ + kEDMA_Modulo16bytes, /*!< Circular buffer size is 16 bytes. */ + kEDMA_Modulo32bytes, /*!< Circular buffer size is 32 bytes. */ + kEDMA_Modulo64bytes, /*!< Circular buffer size is 64 bytes. */ + kEDMA_Modulo128bytes, /*!< Circular buffer size is 128 bytes. */ + kEDMA_Modulo256bytes, /*!< Circular buffer size is 256 bytes. */ + kEDMA_Modulo512bytes, /*!< Circular buffer size is 512 bytes. */ + kEDMA_Modulo1Kbytes, /*!< Circular buffer size is 1 K bytes. */ + kEDMA_Modulo2Kbytes, /*!< Circular buffer size is 2 K bytes. */ + kEDMA_Modulo4Kbytes, /*!< Circular buffer size is 4 K bytes. */ + kEDMA_Modulo8Kbytes, /*!< Circular buffer size is 8 K bytes. */ + kEDMA_Modulo16Kbytes, /*!< Circular buffer size is 16 K bytes. */ + kEDMA_Modulo32Kbytes, /*!< Circular buffer size is 32 K bytes. */ + kEDMA_Modulo64Kbytes, /*!< Circular buffer size is 64 K bytes. */ + kEDMA_Modulo128Kbytes, /*!< Circular buffer size is 128 K bytes. */ + kEDMA_Modulo256Kbytes, /*!< Circular buffer size is 256 K bytes. */ + kEDMA_Modulo512Kbytes, /*!< Circular buffer size is 512 K bytes. */ + kEDMA_Modulo1Mbytes, /*!< Circular buffer size is 1 M bytes. */ + kEDMA_Modulo2Mbytes, /*!< Circular buffer size is 2 M bytes. */ + kEDMA_Modulo4Mbytes, /*!< Circular buffer size is 4 M bytes. */ + kEDMA_Modulo8Mbytes, /*!< Circular buffer size is 8 M bytes. */ + kEDMA_Modulo16Mbytes, /*!< Circular buffer size is 16 M bytes. */ + kEDMA_Modulo32Mbytes, /*!< Circular buffer size is 32 M bytes. */ + kEDMA_Modulo64Mbytes, /*!< Circular buffer size is 64 M bytes. */ + kEDMA_Modulo128Mbytes, /*!< Circular buffer size is 128 M bytes. */ + kEDMA_Modulo256Mbytes, /*!< Circular buffer size is 256 M bytes. */ + kEDMA_Modulo512Mbytes, /*!< Circular buffer size is 512 M bytes. */ + kEDMA_Modulo1Gbytes, /*!< Circular buffer size is 1 G bytes. */ + kEDMA_Modulo2Gbytes, /*!< Circular buffer size is 2 G bytes. */ +} edma_modulo_t; + +/*! @brief Bandwidth control */ +typedef enum _edma_bandwidth +{ + kEDMA_BandwidthStallNone = 0x0U, /*!< No eDMA engine stalls. */ + kEDMA_BandwidthStall4Cycle = 0x2U, /*!< eDMA engine stalls for 4 cycles after each read/write. */ + kEDMA_BandwidthStall8Cycle = 0x3U, /*!< eDMA engine stalls for 8 cycles after each read/write. */ +} edma_bandwidth_t; + +/*! @brief Channel link type */ +typedef enum _edma_channel_link_type +{ + kEDMA_LinkNone = 0x0U, /*!< No channel link */ + kEDMA_MinorLink, /*!< Channel link after each minor loop */ + kEDMA_MajorLink, /*!< Channel link while major loop count exhausted */ +} edma_channel_link_type_t; + +/*!@brief eDMA channel status flags. */ +enum _edma_channel_status_flags +{ + kEDMA_DoneFlag = 0x1U, /*!< DONE flag, set while transfer finished, CITER value exhausted*/ + kEDMA_ErrorFlag = 0x2U, /*!< eDMA error flag, an error occurred in a transfer */ + kEDMA_InterruptFlag = 0x4U, /*!< eDMA interrupt flag, set while an interrupt occurred of this channel */ +}; + +/*! @brief eDMA channel error status flags. */ +enum _edma_error_status_flags +{ + kEDMA_DestinationBusErrorFlag = DMA_ES_DBE_MASK, /*!< Bus error on destination address */ + kEDMA_SourceBusErrorFlag = DMA_ES_SBE_MASK, /*!< Bus error on the source address */ + kEDMA_ScatterGatherErrorFlag = DMA_ES_SGE_MASK, /*!< Error on the Scatter/Gather address, not 32byte aligned. */ + kEDMA_NbytesErrorFlag = DMA_ES_NCE_MASK, /*!< NBYTES/CITER configuration error */ + kEDMA_DestinationOffsetErrorFlag = DMA_ES_DOE_MASK, /*!< Destination offset not aligned with destination size */ + kEDMA_DestinationAddressErrorFlag = DMA_ES_DAE_MASK, /*!< Destination address not aligned with destination size */ + kEDMA_SourceOffsetErrorFlag = DMA_ES_SOE_MASK, /*!< Source offset not aligned with source size */ + kEDMA_SourceAddressErrorFlag = DMA_ES_SAE_MASK, /*!< Source address not aligned with source size*/ + kEDMA_ErrorChannelFlag = DMA_ES_ERRCHN_MASK, /*!< Error channel number of the cancelled channel number */ + kEDMA_ChannelPriorityErrorFlag = DMA_ES_CPE_MASK, /*!< Channel priority is not unique. */ + kEDMA_TransferCanceledFlag = DMA_ES_ECX_MASK, /*!< Transfer cancelled */ +#if defined(FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT) && FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT > 1 + kEDMA_GroupPriorityErrorFlag = DMA_ES_GPE_MASK, /*!< Group priority is not unique. */ +#endif + kEDMA_ValidFlag = DMA_ES_VLD_MASK, /*!< No error occurred, this bit is 0. Otherwise, it is 1. */ +}; + +/*! @brief eDMA interrupt source */ +typedef enum _edma_interrupt_enable +{ + kEDMA_ErrorInterruptEnable = 0x1U, /*!< Enable interrupt while channel error occurs. */ + kEDMA_MajorInterruptEnable = DMA_CSR_INTMAJOR_MASK, /*!< Enable interrupt while major count exhausted. */ + kEDMA_HalfInterruptEnable = DMA_CSR_INTHALF_MASK, /*!< Enable interrupt while major count to half value. */ +} edma_interrupt_enable_t; + +/*! @brief eDMA transfer type */ +typedef enum _edma_transfer_type +{ + kEDMA_MemoryToMemory = 0x0U, /*!< Transfer from memory to memory */ + kEDMA_PeripheralToMemory, /*!< Transfer from peripheral to memory */ + kEDMA_MemoryToPeripheral, /*!< Transfer from memory to peripheral */ +} edma_transfer_type_t; + +/*! @brief eDMA transfer status */ +enum _edma_transfer_status +{ + kStatus_EDMA_QueueFull = MAKE_STATUS(kStatusGroup_EDMA, 0), /*!< TCD queue is full. */ + kStatus_EDMA_Busy = MAKE_STATUS(kStatusGroup_EDMA, 1), /*!< Channel is busy and can't handle the + transfer request. */ +}; + +/*! @brief eDMA global configuration structure.*/ +typedef struct _edma_config +{ + bool enableContinuousLinkMode; /*!< Enable (true) continuous link mode. Upon minor loop completion, the channel + activates again if that channel has a minor loop channel link enabled and + the link channel is itself. */ + bool enableHaltOnError; /*!< Enable (true) transfer halt on error. Any error causes the HALT bit to set. + Subsequently, all service requests are ignored until the HALT bit is cleared.*/ + bool enableRoundRobinArbitration; /*!< Enable (true) round robin channel arbitration method or fixed priority + arbitration is used for channel selection */ + bool enableDebugMode; /*!< Enable(true) eDMA debug mode. When in debug mode, the eDMA stalls the start of + a new channel. Executing channels are allowed to complete. */ +} edma_config_t; + +/*! + * @brief eDMA transfer configuration + * + * This structure configures the source/destination transfer attribute. + * This figure shows the eDMA's transfer model: + * _________________________________________________ + * | Transfer Size | | + * Minor Loop |_______________| Major loop Count 1 | + * Bytes | Transfer Size | | + * ____________|_______________|____________________|--> Minor loop complete + * ____________________________________ + * | | | + * |_______________| Major Loop Count 2 | + * | | | + * |_______________|____________________|--> Minor loop Complete + * + * ---------------------------------------------------------> Transfer complete + */ +typedef struct _edma_transfer_config +{ + uint32_t srcAddr; /*!< Source data address. */ + uint32_t destAddr; /*!< Destination data address. */ + edma_transfer_size_t srcTransferSize; /*!< Source data transfer size. */ + edma_transfer_size_t destTransferSize; /*!< Destination data transfer size. */ + int16_t srcOffset; /*!< Sign-extended offset applied to the current source address to + form the next-state value as each source read is completed. */ + int16_t destOffset; /*!< Sign-extended offset applied to the current destination address to + form the next-state value as each destination write is completed. */ + uint32_t minorLoopBytes; /*!< Bytes to transfer in a minor loop*/ + uint32_t majorLoopCounts; /*!< Major loop iteration count. */ +} edma_transfer_config_t; + +/*! @brief eDMA channel priority configuration */ +typedef struct _edma_channel_Preemption_config +{ + bool enableChannelPreemption; /*!< If true: a channel can be suspended by other channel with higher priority */ + bool enablePreemptAbility; /*!< If true: a channel can suspend other channel with low priority */ + uint8_t channelPriority; /*!< Channel priority */ +} edma_channel_Preemption_config_t; + +/*! @brief eDMA minor offset configuration */ +typedef struct _edma_minor_offset_config +{ + bool enableSrcMinorOffset; /*!< Enable(true) or Disable(false) source minor loop offset. */ + bool enableDestMinorOffset; /*!< Enable(true) or Disable(false) destination minor loop offset. */ + uint32_t minorOffset; /*!< Offset for a minor loop mapping. */ +} edma_minor_offset_config_t; + +/*! + * @brief eDMA TCD. + * + * This structure is same as TCD register which is described in reference manual, + * and is used to configure the scatter/gather feature as a next hardware TCD. + */ +typedef struct _edma_tcd +{ + __IO uint32_t SADDR; /*!< SADDR register, used to save source address */ + __IO uint16_t SOFF; /*!< SOFF register, save offset bytes every transfer */ + __IO uint16_t ATTR; /*!< ATTR register, source/destination transfer size and modulo */ + __IO uint32_t NBYTES; /*!< Nbytes register, minor loop length in bytes */ + __IO uint32_t SLAST; /*!< SLAST register */ + __IO uint32_t DADDR; /*!< DADDR register, used for destination address */ + __IO uint16_t DOFF; /*!< DOFF register, used for destination offset */ + __IO uint16_t CITER; /*!< CITER register, current minor loop numbers, for unfinished minor loop.*/ + __IO uint32_t DLAST_SGA; /*!< DLASTSGA register, next stcd address used in scatter-gather mode */ + __IO uint16_t CSR; /*!< CSR register, for TCD control status */ + __IO uint16_t BITER; /*!< BITER register, begin minor loop count. */ +} edma_tcd_t; + +/*! @brief Callback for eDMA */ +struct _edma_handle; + +/*! @brief Define callback function for eDMA. */ +typedef void (*edma_callback)(struct _edma_handle *handle, void *userData, bool transferDone, uint32_t tcds); + +/*! @brief eDMA transfer handle structure */ +typedef struct _edma_handle +{ + edma_callback callback; /*!< Callback function for major count exhausted. */ + void *userData; /*!< Callback function parameter. */ + DMA_Type *base; /*!< eDMA peripheral base address. */ + edma_tcd_t *tcdPool; /*!< Pointer to memory stored TCDs. */ + uint8_t channel; /*!< eDMA channel number. */ + volatile int8_t header; /*!< The first TCD index. Should point to the next TCD to be loaded into the eDMA engine. */ + volatile int8_t tail; /*!< The last TCD index. Should point to the next TCD to be stored into the memory pool. */ + volatile int8_t tcdUsed; /*!< The number of used TCD slots. Should reflect the number of TCDs can be used/loaded in + the memory. */ + volatile int8_t tcdSize; /*!< The total number of TCD slots in the queue. */ + uint8_t flags; /*!< The status of the current channel. */ +} edma_handle_t; + +/******************************************************************************* + * APIs + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*! + * @name eDMA initialization and de-initialization + * @{ + */ + +/*! + * @brief Initializes the eDMA peripheral. + * + * This function ungates the eDMA clock and configures the eDMA peripheral according + * to the configuration structure. + * + * @param base eDMA peripheral base address. + * @param config A pointer to the configuration structure, see "edma_config_t". + * @note This function enables the minor loop map feature. + */ +void EDMA_Init(DMA_Type *base, const edma_config_t *config); + +/*! + * @brief Deinitializes the eDMA peripheral. + * + * This function gates the eDMA clock. + * + * @param base eDMA peripheral base address. + */ +void EDMA_Deinit(DMA_Type *base); + +/*! + * @brief Gets the eDMA default configuration structure. + * + * This function sets the configuration structure to default values. + * The default configuration is set to the following values. + * @code + * config.enableContinuousLinkMode = false; + * config.enableHaltOnError = true; + * config.enableRoundRobinArbitration = false; + * config.enableDebugMode = false; + * @endcode + * + * @param config A pointer to the eDMA configuration structure. + */ +void EDMA_GetDefaultConfig(edma_config_t *config); + +/* @} */ +/*! + * @name eDMA Channel Operation + * @{ + */ + +/*! + * @brief Sets all TCD registers to default values. + * + * This function sets TCD registers for this channel to default values. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @note This function must not be called while the channel transfer is ongoing + * or it causes unpredictable results. + * @note This function enables the auto stop request feature. + */ +void EDMA_ResetChannel(DMA_Type *base, uint32_t channel); + +/*! + * @brief Configures the eDMA transfer attribute. + * + * This function configures the transfer attribute, including source address, destination address, + * transfer size, address offset, and so on. It also configures the scatter gather feature if the + * user supplies the TCD address. + * Example: + * @code + * edma_transfer_t config; + * edma_tcd_t tcd; + * config.srcAddr = ..; + * config.destAddr = ..; + * ... + * EDMA_SetTransferConfig(DMA0, channel, &config, &stcd); + * @endcode + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param config Pointer to eDMA transfer configuration structure. + * @param nextTcd Point to TCD structure. It can be NULL if users + * do not want to enable scatter/gather feature. + * @note If nextTcd is not NULL, it means scatter gather feature is enabled + * and DREQ bit is cleared in the previous transfer configuration, which + * is set in the eDMA_ResetChannel. + */ +void EDMA_SetTransferConfig(DMA_Type *base, + uint32_t channel, + const edma_transfer_config_t *config, + edma_tcd_t *nextTcd); + +/*! + * @brief Configures the eDMA minor offset feature. + * + * The minor offset means that the signed-extended value is added to the source address or destination + * address after each minor loop. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param config A pointer to the minor offset configuration structure. + */ +void EDMA_SetMinorOffsetConfig(DMA_Type *base, uint32_t channel, const edma_minor_offset_config_t *config); + +/*! + * @brief Configures the eDMA channel preemption feature. + * + * This function configures the channel preemption attribute and the priority of the channel. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number + * @param config A pointer to the channel preemption configuration structure. + */ +static inline void EDMA_SetChannelPreemptionConfig(DMA_Type *base, + uint32_t channel, + const edma_channel_Preemption_config_t *config) +{ + assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); + assert(config != NULL); + + DMA_DCHPRIn(base, channel) = + (DMA_DCHPRI0_DPA(!config->enablePreemptAbility) | DMA_DCHPRI0_ECP(config->enableChannelPreemption) | + DMA_DCHPRI0_CHPRI(config->channelPriority)); +} + +/*! + * @brief Sets the channel link for the eDMA transfer. + * + * This function configures either the minor link or the major link mode. The minor link means that the channel link is + * triggered every time CITER decreases by 1. The major link means that the channel link is triggered when the CITER is + * exhausted. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param type A channel link type, which can be one of the following: + * @arg kEDMA_LinkNone + * @arg kEDMA_MinorLink + * @arg kEDMA_MajorLink + * @param linkedChannel The linked channel number. + * @note Users should ensure that DONE flag is cleared before calling this interface, or the configuration is invalid. + */ +void EDMA_SetChannelLink(DMA_Type *base, uint32_t channel, edma_channel_link_type_t type, uint32_t linkedChannel); + +/*! + * @brief Sets the bandwidth for the eDMA transfer. + * + * Because the eDMA processes the minor loop, it continuously generates read/write sequences + * until the minor count is exhausted. The bandwidth forces the eDMA to stall after the completion of + * each read/write access to control the bus request bandwidth seen by the crossbar switch. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param bandWidth A bandwidth setting, which can be one of the following: + * @arg kEDMABandwidthStallNone + * @arg kEDMABandwidthStall4Cycle + * @arg kEDMABandwidthStall8Cycle + */ +void EDMA_SetBandWidth(DMA_Type *base, uint32_t channel, edma_bandwidth_t bandWidth); + +/*! + * @brief Sets the source modulo and the destination modulo for the eDMA transfer. + * + * This function defines a specific address range specified to be the value after (SADDR + SOFF)/(DADDR + DOFF) + * calculation is performed or the original register value. It provides the ability to implement a circular data + * queue easily. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param srcModulo A source modulo value. + * @param destModulo A destination modulo value. + */ +void EDMA_SetModulo(DMA_Type *base, uint32_t channel, edma_modulo_t srcModulo, edma_modulo_t destModulo); + +#if defined(FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT) && FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT +/*! + * @brief Enables an async request for the eDMA transfer. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param enable The command to enable (true) or disable (false). + */ +static inline void EDMA_EnableAsyncRequest(DMA_Type *base, uint32_t channel, bool enable) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->EARS = (base->EARS & (~(1U << channel))) | ((uint32_t)enable << channel); +} +#endif /* FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT */ + +/*! + * @brief Enables an auto stop request for the eDMA transfer. + * + * If enabling the auto stop request, the eDMA hardware automatically disables the hardware channel request. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param enable The command to enable (true) or disable (false). + */ +static inline void EDMA_EnableAutoStopRequest(DMA_Type *base, uint32_t channel, bool enable) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->TCD[channel].CSR = (base->TCD[channel].CSR & (~DMA_CSR_DREQ_MASK)) | DMA_CSR_DREQ(enable); +} + +/*! + * @brief Enables the interrupt source for the eDMA transfer. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param mask The mask of interrupt source to be set. Users need to use + * the defined edma_interrupt_enable_t type. + */ +void EDMA_EnableChannelInterrupts(DMA_Type *base, uint32_t channel, uint32_t mask); + +/*! + * @brief Disables the interrupt source for the eDMA transfer. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param mask The mask of the interrupt source to be set. Use + * the defined edma_interrupt_enable_t type. + */ +void EDMA_DisableChannelInterrupts(DMA_Type *base, uint32_t channel, uint32_t mask); + +/* @} */ +/*! + * @name eDMA TCD Operation + * @{ + */ + +/*! + * @brief Sets all fields to default values for the TCD structure. + * + * This function sets all fields for this TCD structure to default value. + * + * @param tcd Pointer to the TCD structure. + * @note This function enables the auto stop request feature. + */ +void EDMA_TcdReset(edma_tcd_t *tcd); + +/*! + * @brief Configures the eDMA TCD transfer attribute. + * + * The TCD is a transfer control descriptor. The content of the TCD is the same as the hardware TCD registers. + * The STCD is used in the scatter-gather mode. + * This function configures the TCD transfer attribute, including source address, destination address, + * transfer size, address offset, and so on. It also configures the scatter gather feature if the + * user supplies the next TCD address. + * Example: + * @code + * edma_transfer_t config = { + * ... + * } + * edma_tcd_t tcd __aligned(32); + * edma_tcd_t nextTcd __aligned(32); + * EDMA_TcdSetTransferConfig(&tcd, &config, &nextTcd); + * @endcode + * + * @param tcd Pointer to the TCD structure. + * @param config Pointer to eDMA transfer configuration structure. + * @param nextTcd Pointer to the next TCD structure. It can be NULL if users + * do not want to enable scatter/gather feature. + * @note TCD address should be 32 bytes aligned or it causes an eDMA error. + * @note If the nextTcd is not NULL, the scatter gather feature is enabled + * and DREQ bit is cleared in the previous transfer configuration, which + * is set in the EDMA_TcdReset. + */ +void EDMA_TcdSetTransferConfig(edma_tcd_t *tcd, const edma_transfer_config_t *config, edma_tcd_t *nextTcd); + +/*! + * @brief Configures the eDMA TCD minor offset feature. + * + * A minor offset is a signed-extended value added to the source address or a destination + * address after each minor loop. + * + * @param tcd A point to the TCD structure. + * @param config A pointer to the minor offset configuration structure. + */ +void EDMA_TcdSetMinorOffsetConfig(edma_tcd_t *tcd, const edma_minor_offset_config_t *config); + +/*! + * @brief Sets the channel link for the eDMA TCD. + * + * This function configures either a minor link or a major link. The minor link means the channel link is + * triggered every time CITER decreases by 1. The major link means that the channel link is triggered when the CITER is + * exhausted. + * + * @note Users should ensure that DONE flag is cleared before calling this interface, or the configuration is invalid. + * @param tcd Point to the TCD structure. + * @param type Channel link type, it can be one of: + * @arg kEDMA_LinkNone + * @arg kEDMA_MinorLink + * @arg kEDMA_MajorLink + * @param linkedChannel The linked channel number. + */ +void EDMA_TcdSetChannelLink(edma_tcd_t *tcd, edma_channel_link_type_t type, uint32_t linkedChannel); + +/*! + * @brief Sets the bandwidth for the eDMA TCD. + * + * Because the eDMA processes the minor loop, it continuously generates read/write sequences + * until the minor count is exhausted. The bandwidth forces the eDMA to stall after the completion of + * each read/write access to control the bus request bandwidth seen by the crossbar switch. + * @param tcd A pointer to the TCD structure. + * @param bandWidth A bandwidth setting, which can be one of the following: + * @arg kEDMABandwidthStallNone + * @arg kEDMABandwidthStall4Cycle + * @arg kEDMABandwidthStall8Cycle + */ +static inline void EDMA_TcdSetBandWidth(edma_tcd_t *tcd, edma_bandwidth_t bandWidth) +{ + assert(tcd != NULL); + assert(((uint32_t)tcd & 0x1FU) == 0); + + tcd->CSR = (tcd->CSR & (~DMA_CSR_BWC_MASK)) | DMA_CSR_BWC(bandWidth); +} + +/*! + * @brief Sets the source modulo and the destination modulo for the eDMA TCD. + * + * This function defines a specific address range specified to be the value after (SADDR + SOFF)/(DADDR + DOFF) + * calculation is performed or the original register value. It provides the ability to implement a circular data + * queue easily. + * + * @param tcd A pointer to the TCD structure. + * @param srcModulo A source modulo value. + * @param destModulo A destination modulo value. + */ +void EDMA_TcdSetModulo(edma_tcd_t *tcd, edma_modulo_t srcModulo, edma_modulo_t destModulo); + +/*! + * @brief Sets the auto stop request for the eDMA TCD. + * + * If enabling the auto stop request, the eDMA hardware automatically disables the hardware channel request. + * + * @param tcd A pointer to the TCD structure. + * @param enable The command to enable (true) or disable (false). + */ +static inline void EDMA_TcdEnableAutoStopRequest(edma_tcd_t *tcd, bool enable) +{ + assert(tcd != NULL); + assert(((uint32_t)tcd & 0x1FU) == 0); + + tcd->CSR = (tcd->CSR & (~DMA_CSR_DREQ_MASK)) | DMA_CSR_DREQ(enable); +} + +/*! + * @brief Enables the interrupt source for the eDMA TCD. + * + * @param tcd Point to the TCD structure. + * @param mask The mask of interrupt source to be set. Users need to use + * the defined edma_interrupt_enable_t type. + */ +void EDMA_TcdEnableInterrupts(edma_tcd_t *tcd, uint32_t mask); + +/*! + * @brief Disables the interrupt source for the eDMA TCD. + * + * @param tcd Point to the TCD structure. + * @param mask The mask of interrupt source to be set. Users need to use + * the defined edma_interrupt_enable_t type. + */ +void EDMA_TcdDisableInterrupts(edma_tcd_t *tcd, uint32_t mask); + +/*! @} */ +/*! + * @name eDMA Channel Transfer Operation + * @{ + */ + +/*! + * @brief Enables the eDMA hardware channel request. + * + * This function enables the hardware channel request. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + */ +static inline void EDMA_EnableChannelRequest(DMA_Type *base, uint32_t channel) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->SERQ = DMA_SERQ_SERQ(channel); +} + +/*! + * @brief Disables the eDMA hardware channel request. + * + * This function disables the hardware channel request. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + */ +static inline void EDMA_DisableChannelRequest(DMA_Type *base, uint32_t channel) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->CERQ = DMA_CERQ_CERQ(channel); +} + +/*! + * @brief Starts the eDMA transfer by using the software trigger. + * + * This function starts a minor loop transfer. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + */ +static inline void EDMA_TriggerChannelStart(DMA_Type *base, uint32_t channel) +{ + assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); + + base->SSRT = DMA_SSRT_SSRT(channel); +} + +/*! @} */ +/*! + * @name eDMA Channel Status Operation + * @{ + */ + +/*! + * @brief Gets the remaining major loop count from the eDMA current channel TCD. + * + * This function checks the TCD (Task Control Descriptor) status for a specified + * eDMA channel and returns the the number of major loop count that has not finished. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @return Major loop count which has not been transferred yet for the current TCD. + * @note 1. This function can only be used to get unfinished major loop count of transfer without + * the next TCD, or it might be inaccuracy. + * 2. The unfinished/remaining transfer bytes cannot be obtained directly from registers while + * the channel is running. + * Because to calculate the remaining bytes, the initial NBYTES configured in DMA_TCDn_NBYTES_MLNO + * register is needed while the eDMA IP does not support getting it while a channel is active. + * In another word, the NBYTES value reading is always the actual (decrementing) NBYTES value the dma_engine + * is working with while a channel is running. + * Consequently, to get the remaining transfer bytes, a software-saved initial value of NBYTES (for example + * copied before enabling the channel) is needed. The formula to calculate it is shown below: + * RemainingBytes = RemainingMajorLoopCount * NBYTES(initially configured) + */ +uint32_t EDMA_GetRemainingMajorLoopCount(DMA_Type *base, uint32_t channel); + +/*! + * @brief Gets the eDMA channel error status flags. + * + * @param base eDMA peripheral base address. + * @return The mask of error status flags. Users need to use the +* _edma_error_status_flags type to decode the return variables. + */ +static inline uint32_t EDMA_GetErrorStatusFlags(DMA_Type *base) +{ + return base->ES; +} + +/*! + * @brief Gets the eDMA channel status flags. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @return The mask of channel status flags. Users need to use the + * _edma_channel_status_flags type to decode the return variables. + */ +uint32_t EDMA_GetChannelStatusFlags(DMA_Type *base, uint32_t channel); + +/*! + * @brief Clears the eDMA channel status flags. + * + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + * @param mask The mask of channel status to be cleared. Users need to use + * the defined _edma_channel_status_flags type. + */ +void EDMA_ClearChannelStatusFlags(DMA_Type *base, uint32_t channel, uint32_t mask); + +/*! @} */ +/*! + * @name eDMA Transactional Operation + */ + +/*! + * @brief Creates the eDMA handle. + * + * This function is called if using the transactional API for eDMA. This function + * initializes the internal state of the eDMA handle. + * + * @param handle eDMA handle pointer. The eDMA handle stores callback function and + * parameters. + * @param base eDMA peripheral base address. + * @param channel eDMA channel number. + */ +void EDMA_CreateHandle(edma_handle_t *handle, DMA_Type *base, uint32_t channel); + +/*! + * @brief Installs the TCDs memory pool into the eDMA handle. + * + * This function is called after the EDMA_CreateHandle to use scatter/gather feature. + * + * @param handle eDMA handle pointer. + * @param tcdPool A memory pool to store TCDs. It must be 32 bytes aligned. + * @param tcdSize The number of TCD slots. + */ +void EDMA_InstallTCDMemory(edma_handle_t *handle, edma_tcd_t *tcdPool, uint32_t tcdSize); + +/*! + * @brief Installs a callback function for the eDMA transfer. + * + * This callback is called in the eDMA IRQ handler. Use the callback to do something after + * the current major loop transfer completes. + * + * @param handle eDMA handle pointer. + * @param callback eDMA callback function pointer. + * @param userData A parameter for the callback function. + */ +void EDMA_SetCallback(edma_handle_t *handle, edma_callback callback, void *userData); + +/*! + * @brief Prepares the eDMA transfer structure. + * + * This function prepares the transfer configuration structure according to the user input. + * + * @param config The user configuration structure of type edma_transfer_t. + * @param srcAddr eDMA transfer source address. + * @param srcWidth eDMA transfer source address width(bytes). + * @param destAddr eDMA transfer destination address. + * @param destWidth eDMA transfer destination address width(bytes). + * @param bytesEachRequest eDMA transfer bytes per channel request. + * @param transferBytes eDMA transfer bytes to be transferred. + * @param type eDMA transfer type. + * @note The data address and the data width must be consistent. For example, if the SRC + * is 4 bytes, the source address must be 4 bytes aligned, or it results in + * source address error (SAE). + */ +void EDMA_PrepareTransfer(edma_transfer_config_t *config, + void *srcAddr, + uint32_t srcWidth, + void *destAddr, + uint32_t destWidth, + uint32_t bytesEachRequest, + uint32_t transferBytes, + edma_transfer_type_t type); + +/*! + * @brief Submits the eDMA transfer request. + * + * This function submits the eDMA transfer request according to the transfer configuration structure. + * If submitting the transfer request repeatedly, this function packs an unprocessed request as + * a TCD and enables scatter/gather feature to process it in the next time. + * + * @param handle eDMA handle pointer. + * @param config Pointer to eDMA transfer configuration structure. + * @retval kStatus_EDMA_Success It means submit transfer request succeed. + * @retval kStatus_EDMA_QueueFull It means TCD queue is full. Submit transfer request is not allowed. + * @retval kStatus_EDMA_Busy It means the given channel is busy, need to submit request later. + */ +status_t EDMA_SubmitTransfer(edma_handle_t *handle, const edma_transfer_config_t *config); + +/*! + * @brief eDMA starts transfer. + * + * This function enables the channel request. Users can call this function after submitting the transfer request + * or before submitting the transfer request. + * + * @param handle eDMA handle pointer. + */ +void EDMA_StartTransfer(edma_handle_t *handle); + +/*! + * @brief eDMA stops transfer. + * + * This function disables the channel request to pause the transfer. Users can call EDMA_StartTransfer() + * again to resume the transfer. + * + * @param handle eDMA handle pointer. + */ +void EDMA_StopTransfer(edma_handle_t *handle); + +/*! + * @brief eDMA aborts transfer. + * + * This function disables the channel request and clear transfer status bits. + * Users can submit another transfer after calling this API. + * + * @param handle DMA handle pointer. + */ +void EDMA_AbortTransfer(edma_handle_t *handle); + +/*! + * @brief eDMA IRQ handler for the current major loop transfer completion. + * + * This function clears the channel major interrupt flag and calls + * the callback function if it is not NULL. + * + * Note: + * For the case using TCD queue, when the major iteration count is exhausted, additional operations are performed. + * These include the final address adjustments and reloading of the BITER field into the CITER. + * Assertion of an optional interrupt request also occurs at this time, as does a possible fetch of a new TCD from + * memory using the scatter/gather address pointer included in the descriptor (if scatter/gather is enabled). + * + * For instance, when the time interrupt of TCD[0] happens, the TCD[1] has already been loaded into the eDMA engine. + * As sga and sga_index are calculated based on the DLAST_SGA bitfield lies in the TCD_CSR register, the sga_index + * in this case should be 2 (DLAST_SGA of TCD[1] stores the address of TCD[2]). Thus, the "tcdUsed" updated should be + * (tcdUsed - 2U) which indicates the number of TCDs can be loaded in the memory pool (because TCD[0] and TCD[1] have + * been loaded into the eDMA engine at this point already.). + * + * For the last two continuous ISRs in a scatter/gather process, they both load the last TCD (The last ISR does not + * load a new TCD) from the memory pool to the eDMA engine when major loop completes. + * Therefore, ensure that the header and tcdUsed updated are identical for them. + * tcdUsed are both 0 in this case as no TCD to be loaded. + * + * See the "eDMA basic data flow" in the eDMA Functional description section of the Reference Manual for + * further details. + * + * @param handle eDMA handle pointer. + */ +void EDMA_HandleIRQ(edma_handle_t *handle); + +/* @} */ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/* @} */ + +#endif /*_FSL_EDMA_H_*/ diff --git a/drivers/include/fsl_ewm.h b/drivers/include/fsl_ewm.h new file mode 100644 index 0000000..aa32ed3 --- /dev/null +++ b/drivers/include/fsl_ewm.h @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_EWM_H_ +#define _FSL_EWM_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup ewm + * @{ + */ + + +/******************************************************************************* + * Definitions + *******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief EWM driver version 2.0.1. */ +#define FSL_EWM_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) +/*@}*/ + +/*! @brief Describes EWM clock source. */ +#if defined(FSL_FEATURE_EWM_HAS_CLOCK_SELECT) && FSL_FEATURE_EWM_HAS_CLOCK_SELECT +typedef enum _ewm_lpo_clock_source +{ + kEWM_LpoClockSource0 = 0U, /*!< EWM clock sourced from lpo_clk[0]*/ + kEWM_LpoClockSource1 = 1U, /*!< EWM clock sourced from lpo_clk[1]*/ + kEWM_LpoClockSource2 = 2U, /*!< EWM clock sourced from lpo_clk[2]*/ + kEWM_LpoClockSource3 = 3U, /*!< EWM clock sourced from lpo_clk[3]*/ +} ewm_lpo_clock_source_t; +#endif /* FSL_FEATURE_EWM_HAS_CLOCK_SELECT */ + +/*! +* @brief Data structure for EWM configuration. +* +* This structure is used to configure the EWM. +*/ +typedef struct _ewm_config +{ + bool enableEwm; /*!< Enable EWM module */ + bool enableEwmInput; /*!< Enable EWM_in input */ + bool setInputAssertLogic; /*!< EWM_in signal assertion state */ + bool enableInterrupt; /*!< Enable EWM interrupt */ +#if defined(FSL_FEATURE_EWM_HAS_CLOCK_SELECT) && FSL_FEATURE_EWM_HAS_CLOCK_SELECT + ewm_lpo_clock_source_t clockSource; /*!< Clock source select */ +#endif /* FSL_FEATURE_EWM_HAS_CLOCK_SELECT */ +#if defined(FSL_FEATURE_EWM_HAS_PRESCALER) && FSL_FEATURE_EWM_HAS_PRESCALER + uint8_t prescaler; /*!< Clock prescaler value */ +#endif /* FSL_FEATURE_EWM_HAS_PRESCALER */ + uint8_t compareLowValue; /*!< Compare low-register value */ + uint8_t compareHighValue; /*!< Compare high-register value */ +} ewm_config_t; + +/*! + * @brief EWM interrupt configuration structure with default settings all disabled. + * + * This structure contains the settings for all of EWM interrupt configurations. + */ +enum _ewm_interrupt_enable_t +{ + kEWM_InterruptEnable = EWM_CTRL_INTEN_MASK, /*!< Enable the EWM to generate an interrupt*/ +}; + +/*! + * @brief EWM status flags. + * + * This structure contains the constants for the EWM status flags for use in the EWM functions. + */ +enum _ewm_status_flags_t +{ + kEWM_RunningFlag = EWM_CTRL_EWMEN_MASK, /*!< Running flag, set when EWM is enabled*/ +}; + +/******************************************************************************* + * API + *******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*! + * @name EWM initialization and de-initialization + * @{ + */ + +/*! + * @brief Initializes the EWM peripheral. + * + * This function is used to initialize the EWM. After calling, the EWM + * runs immediately according to the configuration. + * Note that, except for the interrupt enable control bit, other control bits and registers are write once after a + * CPU reset. Modifying them more than once generates a bus transfer error. + * + * This is an example. + * @code + * ewm_config_t config; + * EWM_GetDefaultConfig(&config); + * config.compareHighValue = 0xAAU; + * EWM_Init(ewm_base,&config); + * @endcode + * + * @param base EWM peripheral base address + * @param config The configuration of the EWM +*/ +void EWM_Init(EWM_Type *base, const ewm_config_t *config); + +/*! + * @brief Deinitializes the EWM peripheral. + * + * This function is used to shut down the EWM. + * + * @param base EWM peripheral base address +*/ +void EWM_Deinit(EWM_Type *base); + +/*! + * @brief Initializes the EWM configuration structure. + * + * This function initializes the EWM configuration structure to default values. The default + * values are as follows. + * @code + * ewmConfig->enableEwm = true; + * ewmConfig->enableEwmInput = false; + * ewmConfig->setInputAssertLogic = false; + * ewmConfig->enableInterrupt = false; + * ewmConfig->ewm_lpo_clock_source_t = kEWM_LpoClockSource0; + * ewmConfig->prescaler = 0; + * ewmConfig->compareLowValue = 0; + * ewmConfig->compareHighValue = 0xFEU; + * @endcode + * + * @param config Pointer to the EWM configuration structure. + * @see ewm_config_t + */ +void EWM_GetDefaultConfig(ewm_config_t *config); + +/* @} */ + +/*! + * @name EWM functional Operation + * @{ + */ + +/*! + * @brief Enables the EWM interrupt. + * + * This function enables the EWM interrupt. + * + * @param base EWM peripheral base address + * @param mask The interrupts to enable + * The parameter can be combination of the following source if defined + * @arg kEWM_InterruptEnable + */ +static inline void EWM_EnableInterrupts(EWM_Type *base, uint32_t mask) +{ + base->CTRL |= mask; +} + +/*! + * @brief Disables the EWM interrupt. + * + * This function enables the EWM interrupt. + * + * @param base EWM peripheral base address + * @param mask The interrupts to disable + * The parameter can be combination of the following source if defined + * @arg kEWM_InterruptEnable + */ +static inline void EWM_DisableInterrupts(EWM_Type *base, uint32_t mask) +{ + base->CTRL &= ~mask; +} + +/*! + * @brief Gets all status flags. + * + * This function gets all status flags. + * + * This is an example for getting the running flag. + * @code + * uint32_t status; + * status = EWM_GetStatusFlags(ewm_base) & kEWM_RunningFlag; + * @endcode + * @param base EWM peripheral base address + * @return State of the status flag: asserted (true) or not-asserted (false).@see _ewm_status_flags_t + * - True: a related status flag has been set. + * - False: a related status flag is not set. + */ +static inline uint32_t EWM_GetStatusFlags(EWM_Type *base) +{ + return (base->CTRL & EWM_CTRL_EWMEN_MASK); +} + +/*! + * @brief Services the EWM. + * + * This function resets the EWM counter to zero. + * + * @param base EWM peripheral base address +*/ +void EWM_Refresh(EWM_Type *base); + +/*@}*/ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/*! @}*/ + +#endif /* _FSL_EWM_H_ */ diff --git a/drivers/include/fsl_flash.h b/drivers/include/fsl_flash.h new file mode 100644 index 0000000..e143cb3 --- /dev/null +++ b/drivers/include/fsl_flash.h @@ -0,0 +1,1386 @@ +/* + * Copyright (c) 2013-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_FLASH_H_ +#define _FSL_FLASH_H_ + +#if (defined(BL_TARGET_FLASH) || defined(BL_TARGET_ROM) || defined(BL_TARGET_RAM)) +#include +#include +#include "fsl_device_registers.h" +#include "bootloader_common.h" +#else +#include "fsl_common.h" +#endif + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! + * @addtogroup flash_driver + * @{ + */ + +/*! + * @name Flash version + * @{ + */ +/*! @brief Constructs the version number for drivers. */ +#if !defined(MAKE_VERSION) +#define MAKE_VERSION(major, minor, bugfix) (((major) << 16) | ((minor) << 8) | (bugfix)) +#endif + +/*! @brief Flash driver version for SDK*/ +#define FSL_FLASH_DRIVER_VERSION (MAKE_VERSION(2, 3, 1)) /*!< Version 2.3.1. */ + +/*! @brief Flash driver version for ROM*/ +enum _flash_driver_version_constants +{ + kFLASH_DriverVersionName = 'F', /*!< Flash driver version name.*/ + kFLASH_DriverVersionMajor = 2, /*!< Major flash driver version.*/ + kFLASH_DriverVersionMinor = 3, /*!< Minor flash driver version.*/ + kFLASH_DriverVersionBugfix = 1 /*!< Bugfix for flash driver version.*/ +}; +/*@}*/ + +/*! + * @name Flash configuration + * @{ + */ +/*! @brief Indicates whether to support FlexNVM in the Flash driver */ +#if !defined(FLASH_SSD_CONFIG_ENABLE_FLEXNVM_SUPPORT) +#define FLASH_SSD_CONFIG_ENABLE_FLEXNVM_SUPPORT 1 /*!< Enables the FlexNVM support by default. */ +#endif + +/*! @brief Indicates whether the FlexNVM is enabled in the Flash driver */ +#define FLASH_SSD_IS_FLEXNVM_ENABLED (FLASH_SSD_CONFIG_ENABLE_FLEXNVM_SUPPORT && FSL_FEATURE_FLASH_HAS_FLEX_NVM) + +/*! @brief Indicates whether to support Secondary flash in the Flash driver */ +#if !defined(FLASH_SSD_CONFIG_ENABLE_SECONDARY_FLASH_SUPPORT) +#define FLASH_SSD_CONFIG_ENABLE_SECONDARY_FLASH_SUPPORT 1 /*!< Enables the secondary flash support by default. */ +#endif + +/*! @brief Indicates whether the secondary flash is supported in the Flash driver */ +#if defined(FSL_FEATURE_FLASH_HAS_MULTIPLE_FLASH) || defined(FSL_FEATURE_FLASH_PFLASH_1_START_ADDRESS) +#define FLASH_SSD_IS_SECONDARY_FLASH_ENABLED (FLASH_SSD_CONFIG_ENABLE_SECONDARY_FLASH_SUPPORT) +#else +#define FLASH_SSD_IS_SECONDARY_FLASH_ENABLED (0) +#endif + +/*! @brief Flash driver location. */ +#if !defined(FLASH_DRIVER_IS_FLASH_RESIDENT) +#if (!defined(BL_TARGET_ROM) && !defined(BL_TARGET_RAM)) +#define FLASH_DRIVER_IS_FLASH_RESIDENT 1 /*!< Used for the flash resident application. */ +#else +#define FLASH_DRIVER_IS_FLASH_RESIDENT 0 /*!< Used for the non-flash resident application. */ +#endif +#endif + +/*! @brief Flash Driver Export option */ +#if !defined(FLASH_DRIVER_IS_EXPORTED) +#if (defined(BL_TARGET_ROM) || defined(BL_TARGET_FLASH)) +#define FLASH_DRIVER_IS_EXPORTED 1 /*!< Used for the ROM bootloader. */ +#else +#define FLASH_DRIVER_IS_EXPORTED 0 /*!< Used for the MCUXpresso SDK application. */ +#endif +#endif +/*@}*/ + +/*! + * @name Flash status + * @{ + */ +/*! @brief Flash driver status group. */ +#if defined(kStatusGroup_FlashDriver) +#define kStatusGroupGeneric kStatusGroup_Generic +#define kStatusGroupFlashDriver kStatusGroup_FlashDriver +#elif defined(kStatusGroup_FLASH) +#define kStatusGroupGeneric kStatusGroup_Generic +#define kStatusGroupFlashDriver kStatusGroup_FLASH +#else +#define kStatusGroupGeneric 0 +#define kStatusGroupFlashDriver 1 +#endif + +/*! @brief Constructs a status code value from a group and a code number. */ +#if !defined(MAKE_STATUS) +#define MAKE_STATUS(group, code) ((((group)*100) + (code))) +#endif + +/*! + * @brief Flash driver status codes. + */ +enum _flash_status +{ + kStatus_FLASH_Success = MAKE_STATUS(kStatusGroupGeneric, 0), /*!< API is executed successfully*/ + kStatus_FLASH_InvalidArgument = MAKE_STATUS(kStatusGroupGeneric, 4), /*!< Invalid argument*/ + kStatus_FLASH_SizeError = MAKE_STATUS(kStatusGroupFlashDriver, 0), /*!< Error size*/ + kStatus_FLASH_AlignmentError = + MAKE_STATUS(kStatusGroupFlashDriver, 1), /*!< Parameter is not aligned with the specified baseline*/ + kStatus_FLASH_AddressError = MAKE_STATUS(kStatusGroupFlashDriver, 2), /*!< Address is out of range */ + kStatus_FLASH_AccessError = + MAKE_STATUS(kStatusGroupFlashDriver, 3), /*!< Invalid instruction codes and out-of bound addresses */ + kStatus_FLASH_ProtectionViolation = MAKE_STATUS( + kStatusGroupFlashDriver, 4), /*!< The program/erase operation is requested to execute on protected areas */ + kStatus_FLASH_CommandFailure = + MAKE_STATUS(kStatusGroupFlashDriver, 5), /*!< Run-time error during command execution. */ + kStatus_FLASH_UnknownProperty = MAKE_STATUS(kStatusGroupFlashDriver, 6), /*!< Unknown property.*/ + kStatus_FLASH_EraseKeyError = MAKE_STATUS(kStatusGroupFlashDriver, 7), /*!< API erase key is invalid.*/ + kStatus_FLASH_RegionExecuteOnly = + MAKE_STATUS(kStatusGroupFlashDriver, 8), /*!< The current region is execute-only.*/ + kStatus_FLASH_ExecuteInRamFunctionNotReady = + MAKE_STATUS(kStatusGroupFlashDriver, 9), /*!< Execute-in-RAM function is not available.*/ + kStatus_FLASH_PartitionStatusUpdateFailure = + MAKE_STATUS(kStatusGroupFlashDriver, 10), /*!< Failed to update partition status.*/ + kStatus_FLASH_SetFlexramAsEepromError = + MAKE_STATUS(kStatusGroupFlashDriver, 11), /*!< Failed to set FlexRAM as EEPROM.*/ + kStatus_FLASH_RecoverFlexramAsRamError = + MAKE_STATUS(kStatusGroupFlashDriver, 12), /*!< Failed to recover FlexRAM as RAM.*/ + kStatus_FLASH_SetFlexramAsRamError = MAKE_STATUS(kStatusGroupFlashDriver, 13), /*!< Failed to set FlexRAM as RAM.*/ + kStatus_FLASH_RecoverFlexramAsEepromError = + MAKE_STATUS(kStatusGroupFlashDriver, 14), /*!< Failed to recover FlexRAM as EEPROM.*/ + kStatus_FLASH_CommandNotSupported = MAKE_STATUS(kStatusGroupFlashDriver, 15), /*!< Flash API is not supported.*/ + kStatus_FLASH_SwapSystemNotInUninitialized = + MAKE_STATUS(kStatusGroupFlashDriver, 16), /*!< Swap system is not in an uninitialzed state.*/ + kStatus_FLASH_SwapIndicatorAddressError = + MAKE_STATUS(kStatusGroupFlashDriver, 17), /*!< The swap indicator address is invalid.*/ + kStatus_FLASH_ReadOnlyProperty = MAKE_STATUS(kStatusGroupFlashDriver, 18), /*!< The flash property is read-only.*/ + kStatus_FLASH_InvalidPropertyValue = + MAKE_STATUS(kStatusGroupFlashDriver, 19), /*!< The flash property value is out of range.*/ + kStatus_FLASH_InvalidSpeculationOption = + MAKE_STATUS(kStatusGroupFlashDriver, 20), /*!< The option of flash prefetch speculation is invalid.*/ +}; +/*@}*/ + +/*! + * @name Flash API key + * @{ + */ +/*! @brief Constructs the four character code for the Flash driver API key. */ +#if !defined(FOUR_CHAR_CODE) +#define FOUR_CHAR_CODE(a, b, c, d) (((d) << 24) | ((c) << 16) | ((b) << 8) | ((a))) +#endif + +/*! + * @brief Enumeration for Flash driver API keys. + * + * @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. + */ +enum _flash_driver_api_keys +{ + kFLASH_ApiEraseKey = FOUR_CHAR_CODE('k', 'f', 'e', 'k') /*!< Key value used to validate all flash erase APIs.*/ +}; +/*@}*/ + +/*! + * @brief Enumeration for supported flash margin levels. + */ +typedef enum _flash_margin_value +{ + 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. */ +} flash_margin_value_t; + +/*! + * @brief Enumeration for the three possible flash security states. + */ +typedef enum _flash_security_state +{ + kFLASH_SecurityStateNotSecure, /*!< Flash is not secure.*/ + kFLASH_SecurityStateBackdoorEnabled, /*!< Flash backdoor is enabled.*/ + kFLASH_SecurityStateBackdoorDisabled /*!< Flash backdoor is disabled.*/ +} flash_security_state_t; + +/*! + * @brief Enumeration for the three possible flash protection levels. + */ +typedef enum _flash_protection_state +{ + kFLASH_ProtectionStateUnprotected, /*!< Flash region is not protected.*/ + kFLASH_ProtectionStateProtected, /*!< Flash region is protected.*/ + kFLASH_ProtectionStateMixed /*!< Flash is mixed with protected and unprotected region.*/ +} flash_protection_state_t; + +/*! + * @brief Enumeration for the three possible flash execute access levels. + */ +typedef enum _flash_execute_only_access_state +{ + kFLASH_AccessStateUnLimited, /*!< Flash region is unlimited.*/ + kFLASH_AccessStateExecuteOnly, /*!< Flash region is execute only.*/ + kFLASH_AccessStateMixed /*!< Flash is mixed with unlimited and execute only region.*/ +} flash_execute_only_access_state_t; + +/*! + * @brief Enumeration for various flash properties. + */ +typedef enum _flash_property_tag +{ + kFLASH_PropertyPflashSectorSize = 0x00U, /*!< Pflash sector size property.*/ + kFLASH_PropertyPflashTotalSize = 0x01U, /*!< Pflash total size property.*/ + kFLASH_PropertyPflashBlockSize = 0x02U, /*!< Pflash block size property.*/ + kFLASH_PropertyPflashBlockCount = 0x03U, /*!< Pflash block count property.*/ + kFLASH_PropertyPflashBlockBaseAddr = 0x04U, /*!< Pflash block base address property.*/ + kFLASH_PropertyPflashFacSupport = 0x05U, /*!< Pflash fac support property.*/ + kFLASH_PropertyPflashAccessSegmentSize = 0x06U, /*!< Pflash access segment size property.*/ + kFLASH_PropertyPflashAccessSegmentCount = 0x07U, /*!< Pflash access segment count property.*/ + kFLASH_PropertyFlexRamBlockBaseAddr = 0x08U, /*!< FlexRam block base address property.*/ + kFLASH_PropertyFlexRamTotalSize = 0x09U, /*!< FlexRam total size property.*/ + kFLASH_PropertyDflashSectorSize = 0x10U, /*!< Dflash sector size property.*/ + kFLASH_PropertyDflashTotalSize = 0x11U, /*!< Dflash total size property.*/ + kFLASH_PropertyDflashBlockSize = 0x12U, /*!< Dflash block size property.*/ + kFLASH_PropertyDflashBlockCount = 0x13U, /*!< Dflash block count property.*/ + kFLASH_PropertyDflashBlockBaseAddr = 0x14U, /*!< Dflash block base address property.*/ + kFLASH_PropertyEepromTotalSize = 0x15U, /*!< EEPROM total size property.*/ + kFLASH_PropertyFlashMemoryIndex = 0x20U, /*!< Flash memory index property.*/ + kFLASH_PropertyFlashCacheControllerIndex = 0x21U /*!< Flash cache controller index property.*/ +} flash_property_tag_t; + +/*! + * @brief Constants for execute-in-RAM flash function. + */ +enum _flash_execute_in_ram_function_constants +{ + kFLASH_ExecuteInRamFunctionMaxSizeInWords = 16U, /*!< The maximum size of execute-in-RAM function.*/ + kFLASH_ExecuteInRamFunctionTotalNum = 2U /*!< Total number of execute-in-RAM functions.*/ +}; + +/*! + * @brief Flash execute-in-RAM function information. + */ +typedef struct _flash_execute_in_ram_function_config +{ + 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.*/ +} flash_execute_in_ram_function_config_t; + +/*! + * @brief Enumeration for the two possible options of flash read resource command. + */ +typedef enum _flash_read_resource_option +{ + kFLASH_ResourceOptionFlashIfr = + 0x00U, /*!< Select code for Program flash 0 IFR, Program flash swap 0 IFR, Data flash 0 IFR */ + kFLASH_ResourceOptionVersionId = 0x01U /*!< Select code for the version ID*/ +} flash_read_resource_option_t; + +/*! + * @brief Enumeration for the range of special-purpose flash resource + */ +enum _flash_read_resource_range +{ +#if (FSL_FEATURE_FLASH_IS_FTFE == 1) + kFLASH_ResourceRangePflashIfrSizeInBytes = 1024U, /*!< Pflash IFR size in byte.*/ + kFLASH_ResourceRangeVersionIdSizeInBytes = 8U, /*!< Version ID IFR size in byte.*/ + kFLASH_ResourceRangeVersionIdStart = 0x08U, /*!< Version ID IFR start address.*/ + kFLASH_ResourceRangeVersionIdEnd = 0x0FU, /*!< Version ID IFR end address.*/ + kFLASH_ResourceRangePflashSwapIfrStart = 0x40000U, /*!< Pflash swap IFR start address.*/ + kFLASH_ResourceRangePflashSwapIfrEnd = + (kFLASH_ResourceRangePflashSwapIfrStart + 0x3FFU), /*!< Pflash swap IFR end address.*/ +#else /* FSL_FEATURE_FLASH_IS_FTFL == 1 or FSL_FEATURE_FLASH_IS_FTFA = =1 */ + kFLASH_ResourceRangePflashIfrSizeInBytes = 256U, /*!< Pflash IFR size in byte.*/ + kFLASH_ResourceRangeVersionIdSizeInBytes = 8U, /*!< Version ID IFR size in byte.*/ + kFLASH_ResourceRangeVersionIdStart = 0x00U, /*!< Version ID IFR start address.*/ + kFLASH_ResourceRangeVersionIdEnd = 0x07U, /*!< Version ID IFR end address.*/ +#if 0x20000U == (FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE) + kFLASH_ResourceRangePflashSwapIfrStart = 0x8000U, /*!< Pflash swap IFR start address.*/ +#elif 0x40000U == (FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE) + kFLASH_ResourceRangePflashSwapIfrStart = 0x10000U, /*!< Pflash swap IFR start address.*/ +#elif 0x80000U == (FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE) + kFLASH_ResourceRangePflashSwapIfrStart = 0x20000U, /*!< Pflash swap IFR start address.*/ +#else + kFLASH_ResourceRangePflashSwapIfrStart = 0, +#endif + kFLASH_ResourceRangePflashSwapIfrEnd = + (kFLASH_ResourceRangePflashSwapIfrStart + 0xFFU), /*!< Pflash swap IFR end address.*/ +#endif + kFLASH_ResourceRangeDflashIfrStart = 0x800000U, /*!< Dflash IFR start address.*/ + kFLASH_ResourceRangeDflashIfrEnd = 0x8003FFU, /*!< Dflash IFR end address.*/ +}; + +/*! + * @brief Enumeration for the index of read/program once record + */ +enum _k3_flash_read_once_index +{ + kFLASH_RecordIndexSwapAddr = 0xA1U, /*!< Index of Swap indicator address.*/ + kFLASH_RecordIndexSwapEnable = 0xA2U, /*!< Index of Swap system enable.*/ + kFLASH_RecordIndexSwapDisable = 0xA3U, /*!< Index of Swap system disable.*/ +}; + +/*! + * @brief Enumeration for the two possilbe options of set FlexRAM function command. + */ +typedef enum _flash_flexram_function_option +{ + kFLASH_FlexramFunctionOptionAvailableAsRam = 0xFFU, /*!< An option used to make FlexRAM available as RAM */ + kFLASH_FlexramFunctionOptionAvailableForEeprom = 0x00U /*!< An option used to make FlexRAM available for EEPROM */ +} flash_flexram_function_option_t; + +/*! + * @brief Enumeration for acceleration RAM property. + */ +enum _flash_acceleration_ram_property +{ + kFLASH_AccelerationRamSize = 0x400U +}; + +/*! + * @brief Enumeration for the possible options of Swap function + */ +typedef enum _flash_swap_function_option +{ + kFLASH_SwapFunctionOptionEnable = 0x00U, /*!< An option used to enable the Swap function */ + kFLASH_SwapFunctionOptionDisable = 0x01U /*!< An option used to disable the Swap function */ +} flash_swap_function_option_t; + +/*! + * @brief Enumeration for the possible options of Swap control commands + */ +typedef enum _flash_swap_control_option +{ + kFLASH_SwapControlOptionIntializeSystem = 0x01U, /*!< An option used to initialize the Swap system */ + kFLASH_SwapControlOptionSetInUpdateState = 0x02U, /*!< An option used to set the Swap in an update state */ + kFLASH_SwapControlOptionSetInCompleteState = 0x04U, /*!< An option used to set the Swap in a complete state */ + kFLASH_SwapControlOptionReportStatus = 0x08U, /*!< An option used to report the Swap status */ + kFLASH_SwapControlOptionDisableSystem = 0x10U /*!< An option used to disable the Swap status */ +} flash_swap_control_option_t; + +/*! + * @brief Enumeration for the possible flash Swap status. + */ +typedef enum _flash_swap_state +{ + kFLASH_SwapStateUninitialized = 0x00U, /*!< Flash Swap system is in an uninitialized state.*/ + kFLASH_SwapStateReady = 0x01U, /*!< Flash Swap system is in a ready state.*/ + kFLASH_SwapStateUpdate = 0x02U, /*!< Flash Swap system is in an update state.*/ + kFLASH_SwapStateUpdateErased = 0x03U, /*!< Flash Swap system is in an updateErased state.*/ + kFLASH_SwapStateComplete = 0x04U, /*!< Flash Swap system is in a complete state.*/ + kFLASH_SwapStateDisabled = 0x05U /*!< Flash Swap system is in a disabled state.*/ +} flash_swap_state_t; + +/*! + * @breif Enumeration for the possible flash Swap block status + */ +typedef enum _flash_swap_block_status +{ + kFLASH_SwapBlockStatusLowerHalfProgramBlocksAtZero = + 0x00U, /*!< Swap block status is that lower half program block at zero.*/ + kFLASH_SwapBlockStatusUpperHalfProgramBlocksAtZero = + 0x01U, /*!< Swap block status is that upper half program block at zero.*/ +} flash_swap_block_status_t; + +/*! + * @brief Flash Swap information + */ +typedef struct _flash_swap_state_config +{ + flash_swap_state_t flashSwapState; /*!chip = 0; + fbConfig->writeProtect = 0; + fbConfig->burstWrite = 0; + fbConfig->burstRead = 0; + fbConfig->byteEnableMode = 0; + fbConfig->autoAcknowledge = true; + fbConfig->extendTransferAddress = 0; + fbConfig->secondaryWaitStates = 0; + fbConfig->byteLaneShift = kFLEXBUS_NotShifted; + fbConfig->writeAddressHold = kFLEXBUS_Hold1Cycle; + fbConfig->readAddressHold = kFLEXBUS_Hold1Or0Cycles; + fbConfig->addressSetup = kFLEXBUS_FirstRisingEdge; + fbConfig->portSize = kFLEXBUS_1Byte; + fbConfig->group1MultiplexControl = kFLEXBUS_MultiplexGroup1_FB_ALE; + fbConfig->group2MultiplexControl = kFLEXBUS_MultiplexGroup2_FB_CS4 ; + fbConfig->group3MultiplexControl = kFLEXBUS_MultiplexGroup3_FB_CS5; + fbConfig->group4MultiplexControl = kFLEXBUS_MultiplexGroup4_FB_TBST; + fbConfig->group5MultiplexControl = kFLEXBUS_MultiplexGroup5_FB_TA; + @endcode + * @param config Pointer to the initialization structure. + * @see FLEXBUS_Init + */ +void FLEXBUS_GetDefaultConfig(flexbus_config_t *config); + +/*! @}*/ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/*! @}*/ + +#endif /* _FSL_FLEXBUS_H_ */ diff --git a/drivers/include/fsl_flexcan.h b/drivers/include/fsl_flexcan.h new file mode 100644 index 0000000..40246fe --- /dev/null +++ b/drivers/include/fsl_flexcan.h @@ -0,0 +1,1081 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_FLEXCAN_H_ +#define _FSL_FLEXCAN_H_ + +#include "fsl_common.h" +#include "FreeRTOS.h" +#include "task.h" + +/*! + * @addtogroup flexcan_driver + * @{ + */ + +/****************************************************************************** + * Definitions + *****************************************************************************/ + +#define CAN_CTRLMODE_NORMAL 0x00 /* normal mode */ +#define CAN_CTRLMODE_LOOPBACK 0x01 /* Loopback mode */ +#define CAN_CTRLMODE_LISTENONLY 0x02 /* Listen-only mode */ +#define CAN_CTRLMODE_3_SAMPLES 0x03 /* Triple sampling mode */ + +/*! @name Driver version */ +/*@{*/ +/*! @brief FlexCAN driver version 2.2.0. */ +#define FLEXCAN_DRIVER_VERSION (MAKE_VERSION(2, 2, 0)) +/*@}*/ + +/*! @brief FlexCAN Frame ID helper macro. */ +#define FLEXCAN_ID_STD(id) \ + (((uint32_t)(((uint32_t)(id)) << CAN_ID_STD_SHIFT)) & CAN_ID_STD_MASK) /*!< Standard Frame ID helper macro. */ +#define FLEXCAN_ID_EXT(id) \ + (((uint32_t)(((uint32_t)(id)) << CAN_ID_EXT_SHIFT)) & \ + (CAN_ID_EXT_MASK | CAN_ID_STD_MASK)) /*!< Extend Frame ID helper macro. */ + +/*! @brief FlexCAN Rx Message Buffer Mask helper macro. */ +#define FLEXCAN_RX_MB_STD_MASK(id, rtr, ide) \ + (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ + FLEXCAN_ID_STD(id)) /*!< Standard Rx Message Buffer Mask helper macro. */ +#define FLEXCAN_RX_MB_EXT_MASK(id, rtr, ide) \ + (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ + FLEXCAN_ID_EXT(id)) /*!< Extend Rx Message Buffer Mask helper macro. */ + +/*! @brief FlexCAN Rx FIFO Mask helper macro. */ +#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_A(id, rtr, ide) \ + (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ + (FLEXCAN_ID_STD(id) << 1)) /*!< Standard Rx FIFO Mask helper macro Type A helper macro. */ +#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_HIGH(id, rtr, ide) \ + (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ + (((uint32_t)(id) & 0x7FF) << 19)) /*!< Standard Rx FIFO Mask helper macro Type B upper part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_LOW(id, rtr, ide) \ + (((uint32_t)((uint32_t)(rtr) << 15) | (uint32_t)((uint32_t)(ide) << 14)) | \ + (((uint32_t)(id) & 0x7FF) << 3)) /*!< Standard Rx FIFO Mask helper macro Type B lower part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_HIGH(id) \ + (((uint32_t)(id) & 0x7F8) << 21) /*!< Standard Rx FIFO Mask helper macro Type C upper part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_HIGH(id) \ + (((uint32_t)(id) & 0x7F8) << 13) /*!< Standard Rx FIFO Mask helper macro Type C mid-upper part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_LOW(id) \ + (((uint32_t)(id) & 0x7F8) << 5) /*!< Standard Rx FIFO Mask helper macro Type C mid-lower part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_LOW(id) \ + (((uint32_t)(id) & 0x7F8) >> 3) /*!< Standard Rx FIFO Mask helper macro Type C lower part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_A(id, rtr, ide) \ + (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ + (FLEXCAN_ID_EXT(id) << 1)) /*!< Extend Rx FIFO Mask helper macro Type A helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_HIGH(id, rtr, ide) \ + (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ + ((FLEXCAN_ID_EXT(id) & 0x1FFF8000) << 1)) /*!< Extend Rx FIFO Mask helper macro Type B upper part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_LOW(id, rtr, ide) \ + (((uint32_t)((uint32_t)(rtr) << 15) | (uint32_t)((uint32_t)(ide) << 14)) | \ + ((FLEXCAN_ID_EXT(id) & 0x1FFF8000) >> \ + 15)) /*!< Extend Rx FIFO Mask helper macro Type B lower part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_HIGH(id) \ + ((FLEXCAN_ID_EXT(id) & 0x1FE00000) << 3) /*!< Extend Rx FIFO Mask helper macro Type C upper part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_HIGH(id) \ + ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >> \ + 5) /*!< Extend Rx FIFO Mask helper macro Type C mid-upper part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_LOW(id) \ + ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >> \ + 13) /*!< Extend Rx FIFO Mask helper macro Type C mid-lower part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_LOW(id) \ + ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >> 21) /*!< Extend Rx FIFO Mask helper macro Type C lower part helper macro. */ + +/*! @brief FlexCAN Rx FIFO Filter helper macro. */ +#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_A(id, rtr, ide) \ + FLEXCAN_RX_FIFO_STD_MASK_TYPE_A(id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type A helper macro. */ +#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_B_HIGH(id, rtr, ide) \ + FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_HIGH( \ + id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type B upper part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_B_LOW(id, rtr, ide) \ + FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_LOW( \ + id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type B lower part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_HIGH(id) \ + FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_HIGH( \ + id) /*!< Standard Rx FIFO Filter helper macro Type C upper part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_MID_HIGH(id) \ + FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_HIGH( \ + id) /*!< Standard Rx FIFO Filter helper macro Type C mid-upper part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_MID_LOW(id) \ + FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_LOW( \ + id) /*!< Standard Rx FIFO Filter helper macro Type C mid-lower part helper macro. */ +#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_LOW(id) \ + FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_LOW(id) /*!< Standard Rx FIFO Filter helper macro Type C lower part helper macro. \ + */ +#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_A(id, rtr, ide) \ + FLEXCAN_RX_FIFO_EXT_MASK_TYPE_A(id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type A helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_B_HIGH(id, rtr, ide) \ + FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_HIGH( \ + id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type B upper part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_B_LOW(id, rtr, ide) \ + FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_LOW( \ + id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type B lower part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_HIGH(id) \ + FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_HIGH(id) /*!< Extend Rx FIFO Filter helper macro Type C upper part helper macro. \ + */ +#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_MID_HIGH(id) \ + FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_HIGH( \ + id) /*!< Extend Rx FIFO Filter helper macro Type C mid-upper part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_MID_LOW(id) \ + FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_LOW( \ + id) /*!< Extend Rx FIFO Filter helper macro Type C mid-lower part helper macro. */ +#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_LOW(id) \ + FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_LOW(id) /*!< Extend Rx FIFO Filter helper macro Type C lower part helper macro. */ + +/*! @brief FlexCAN transfer status. */ +enum _flexcan_status +{ + kStatus_FLEXCAN_TxBusy = MAKE_STATUS(kStatusGroup_FLEXCAN, 0), /*!< Tx Message Buffer is Busy. */ + kStatus_FLEXCAN_TxIdle = MAKE_STATUS(kStatusGroup_FLEXCAN, 1), /*!< Tx Message Buffer is Idle. */ + kStatus_FLEXCAN_TxSwitchToRx = MAKE_STATUS( + kStatusGroup_FLEXCAN, 2), /*!< Remote Message is send out and Message buffer changed to Receive one. */ + kStatus_FLEXCAN_RxBusy = MAKE_STATUS(kStatusGroup_FLEXCAN, 3), /*!< Rx Message Buffer is Busy. */ + kStatus_FLEXCAN_RxIdle = MAKE_STATUS(kStatusGroup_FLEXCAN, 4), /*!< Rx Message Buffer is Idle. */ + kStatus_FLEXCAN_RxOverflow = MAKE_STATUS(kStatusGroup_FLEXCAN, 5), /*!< Rx Message Buffer is Overflowed. */ + kStatus_FLEXCAN_RxFifoBusy = MAKE_STATUS(kStatusGroup_FLEXCAN, 6), /*!< Rx Message FIFO is Busy. */ + kStatus_FLEXCAN_RxFifoIdle = MAKE_STATUS(kStatusGroup_FLEXCAN, 7), /*!< Rx Message FIFO is Idle. */ + kStatus_FLEXCAN_RxFifoOverflow = MAKE_STATUS(kStatusGroup_FLEXCAN, 8), /*!< Rx Message FIFO is overflowed. */ + kStatus_FLEXCAN_RxFifoWarning = MAKE_STATUS(kStatusGroup_FLEXCAN, 9), /*!< Rx Message FIFO is almost overflowed. */ + kStatus_FLEXCAN_ErrorStatus = MAKE_STATUS(kStatusGroup_FLEXCAN, 10), /*!< FlexCAN Module Error and Status. */ + kStatus_FLEXCAN_UnHandled = MAKE_STATUS(kStatusGroup_FLEXCAN, 11), /*!< UnHadled Interrupt asserted. */ +}; + +/*! @brief FlexCAN frame format. */ +typedef enum _flexcan_frame_format +{ + kFLEXCAN_FrameFormatStandard = 0x0U, /*!< Standard frame format attribute. */ + kFLEXCAN_FrameFormatExtend = 0x1U, /*!< Extend frame format attribute. */ +} flexcan_frame_format_t; + +/*! @brief FlexCAN frame type. */ +typedef enum _flexcan_frame_type +{ + kFLEXCAN_FrameTypeData = 0x0U, /*!< Data frame type attribute. */ + kFLEXCAN_FrameTypeRemote = 0x1U, /*!< Remote frame type attribute. */ +} flexcan_frame_type_t; + +#if (!defined(FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE)) || !FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE +/*! @brief FlexCAN clock source. */ +typedef enum _flexcan_clock_source +{ + kFLEXCAN_ClkSrcOsc = 0x0U, /*!< FlexCAN Protocol Engine clock from Oscillator. */ + kFLEXCAN_ClkSrcPeri = 0x1U, /*!< FlexCAN Protocol Engine clock from Peripheral Clock. */ +} flexcan_clock_source_t; +#endif /* FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE */ + +/*! @brief FlexCAN Rx Fifo Filter type. */ +typedef enum _flexcan_rx_fifo_filter_type +{ + kFLEXCAN_RxFifoFilterTypeA = 0x0U, /*!< One full ID (standard and extended) per ID Filter element. */ + kFLEXCAN_RxFifoFilterTypeB = + 0x1U, /*!< Two full standard IDs or two partial 14-bit ID slices per ID Filter Table element. */ + kFLEXCAN_RxFifoFilterTypeC = + 0x2U, /*!< Four partial 8-bit Standard or extended ID slices per ID Filter Table element. */ + kFLEXCAN_RxFifoFilterTypeD = 0x3U, /*!< All frames rejected. */ +} flexcan_rx_fifo_filter_type_t; + +/*! + * @brief FlexCAN Rx FIFO priority. + * + * The matching process starts from the Rx MB(or Rx FIFO) with higher priority. + * If no MB(or Rx FIFO filter) is satisfied, the matching process goes on with + * the Rx FIFO(or Rx MB) with lower priority. + */ +typedef enum _flexcan_rx_fifo_priority +{ + kFLEXCAN_RxFifoPrioLow = 0x0U, /*!< Matching process start from Rx Message Buffer first*/ + kFLEXCAN_RxFifoPrioHigh = 0x1U, /*!< Matching process start from Rx FIFO first*/ +} flexcan_rx_fifo_priority_t; + +/*! + * @brief FlexCAN interrupt configuration structure, default settings all disabled. + * + * This structure contains the settings for all of the FlexCAN Module interrupt configurations. + * Note: FlexCAN Message Buffers and Rx FIFO have their own interrupts. + */ +enum _flexcan_interrupt_enable +{ + kFLEXCAN_BusOffInterruptEnable = CAN_CTRL1_BOFFMSK_MASK, /*!< Bus Off interrupt. */ + kFLEXCAN_ErrorInterruptEnable = CAN_CTRL1_ERRMSK_MASK, /*!< Error interrupt. */ + kFLEXCAN_RxWarningInterruptEnable = CAN_CTRL1_RWRNMSK_MASK, /*!< Rx Warning interrupt. */ + kFLEXCAN_TxWarningInterruptEnable = CAN_CTRL1_TWRNMSK_MASK, /*!< Tx Warning interrupt. */ + kFLEXCAN_WakeUpInterruptEnable = CAN_MCR_WAKMSK_MASK, /*!< Wake Up interrupt. */ +}; + +/*! + * @brief FlexCAN status flags. + * + * This provides constants for the FlexCAN status flags for use in the FlexCAN functions. + * Note: The CPU read action clears FlEXCAN_ErrorFlag, therefore user need to + * read FlEXCAN_ErrorFlag and distinguish which error is occur using + * @ref _flexcan_error_flags enumerations. + */ +enum _flexcan_flags +{ + kFLEXCAN_SynchFlag = CAN_ESR1_SYNCH_MASK, /*!< CAN Synchronization Status. */ + kFLEXCAN_TxWarningIntFlag = CAN_ESR1_TWRNINT_MASK, /*!< Tx Warning Interrupt Flag. */ + kFLEXCAN_RxWarningIntFlag = CAN_ESR1_RWRNINT_MASK, /*!< Rx Warning Interrupt Flag. */ + kFLEXCAN_TxErrorWarningFlag = CAN_ESR1_TXWRN_MASK, /*!< Tx Error Warning Status. */ + kFLEXCAN_RxErrorWarningFlag = CAN_ESR1_RXWRN_MASK, /*!< Rx Error Warning Status. */ + kFLEXCAN_IdleFlag = CAN_ESR1_IDLE_MASK, /*!< CAN IDLE Status Flag. */ + kFLEXCAN_FaultConfinementFlag = CAN_ESR1_FLTCONF_MASK, /*!< Fault Confinement State Flag. */ + kFLEXCAN_TransmittingFlag = CAN_ESR1_TX_MASK, /*!< FlexCAN In Transmission Status. */ + kFLEXCAN_ReceivingFlag = CAN_ESR1_RX_MASK, /*!< FlexCAN In Reception Status. */ + kFLEXCAN_BusOffIntFlag = CAN_ESR1_BOFFINT_MASK, /*!< Bus Off Interrupt Flag. */ + kFLEXCAN_ErrorIntFlag = CAN_ESR1_ERRINT_MASK, /*!< Error Interrupt Flag. */ + kFLEXCAN_WakeUpIntFlag = CAN_ESR1_WAKINT_MASK, /*!< Wake-Up Interrupt Flag. */ + kFLEXCAN_ErrorFlag = CAN_ESR1_BIT1ERR_MASK | /*!< All FlexCAN Error Status. */ + CAN_ESR1_BIT0ERR_MASK | + CAN_ESR1_ACKERR_MASK | CAN_ESR1_CRCERR_MASK | CAN_ESR1_FRMERR_MASK | CAN_ESR1_STFERR_MASK, +}; + +/*! + * @brief FlexCAN error status flags. + * + * The FlexCAN Error Status enumerations is used to report current error of the FlexCAN bus. + * This enumerations should be used with KFLEXCAN_ErrorFlag in @ref _flexcan_flags enumerations + * to ditermine which error is generated. + */ +enum _flexcan_error_flags +{ + kFLEXCAN_StuffingError = CAN_ESR1_STFERR_MASK, /*!< Stuffing Error. */ + kFLEXCAN_FormError = CAN_ESR1_FRMERR_MASK, /*!< Form Error. */ + kFLEXCAN_CrcError = CAN_ESR1_CRCERR_MASK, /*!< Cyclic Redundancy Check Error. */ + kFLEXCAN_AckError = CAN_ESR1_ACKERR_MASK, /*!< Received no ACK on transmission. */ + kFLEXCAN_Bit0Error = CAN_ESR1_BIT0ERR_MASK, /*!< Unable to send dominant bit. */ + kFLEXCAN_Bit1Error = CAN_ESR1_BIT1ERR_MASK, /*!< Unable to send recessive bit. */ +}; + +/*! + * @brief FlexCAN Rx FIFO status flags. + * + * The FlexCAN Rx FIFO Status enumerations are used to determine the status of the + * Rx FIFO. Because Rx FIFO occupy the MB0 ~ MB7 (Rx Fifo filter also occupies + * more Message Buffer space), Rx FIFO status flags are mapped to the corresponding + * Message Buffer status flags. + */ +enum _flexcan_rx_fifo_flags +{ + kFLEXCAN_RxFifoOverflowFlag = CAN_IFLAG1_BUF7I_MASK, /*!< Rx FIFO overflow flag. */ + kFLEXCAN_RxFifoWarningFlag = CAN_IFLAG1_BUF6I_MASK, /*!< Rx FIFO almost full flag. */ + kFLEXCAN_RxFifoFrameAvlFlag = CAN_IFLAG1_BUF5I_MASK, /*!< Frames available in Rx FIFO flag. */ +}; + +#if defined(__CC_ARM) +#pragma anon_unions +#endif +/*! @brief FlexCAN message frame structure. */ +typedef struct _flexcan_frame +{ + struct + { + uint32_t timestamp : 16; /*!< FlexCAN internal Free-Running Counter Time Stamp. */ + uint32_t length : 4; /*!< CAN frame payload length in bytes(Range: 0~8). */ + uint32_t type : 1; /*!< CAN Frame Type(DATA or REMOTE). */ + uint32_t format : 1; /*!< CAN Frame Identifier(STD or EXT format). */ + uint32_t : 1; /*!< Reserved. */ + uint32_t idhit : 9; /*!< CAN Rx FIFO filter hit id(This value is only used in Rx FIFO receive mode). */ + }; + struct + { + uint32_t id : 29; /*!< CAN Frame Identifier, should be set using FLEXCAN_ID_EXT() or FLEXCAN_ID_STD() macro. */ + uint32_t : 3; /*!< Reserved. */ + }; + union + { + struct + { + uint32_t dataWord0; /*!< CAN Frame payload word0. */ + uint32_t dataWord1; /*!< CAN Frame payload word1. */ + }; + struct + { + uint8_t dataByte3; /*!< CAN Frame payload byte3. */ + uint8_t dataByte2; /*!< CAN Frame payload byte2. */ + uint8_t dataByte1; /*!< CAN Frame payload byte1. */ + uint8_t dataByte0; /*!< CAN Frame payload byte0. */ + uint8_t dataByte7; /*!< CAN Frame payload byte7. */ + uint8_t dataByte6; /*!< CAN Frame payload byte6. */ + uint8_t dataByte5; /*!< CAN Frame payload byte5. */ + uint8_t dataByte4; /*!< CAN Frame payload byte4. */ + }; + }; +} flexcan_frame_t; + +/*! @brief FlexCAN module configuration structure. */ +typedef struct _flexcan_config +{ + uint32_t baudRate; /*!< FlexCAN baud rate in bps. */ +#if (!defined(FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE)) || !FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE + flexcan_clock_source_t clkSrc; /*!< Clock source for FlexCAN Protocol Engine. */ +#endif /* FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE */ + uint8_t maxMbNum; /*!< The maximum number of Message Buffers used by user. */ + bool enableLoopBack; /*!< Enable or Disable Loop Back Self Test Mode. */ + bool enableSelfWakeup; /*!< Enable or Disable Self Wakeup Mode. */ + bool enableIndividMask; /*!< Enable or Disable Rx Individual Mask. */ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) + bool enableDoze; /*!< Enable or Disable Doze Mode. */ +#endif +} flexcan_config_t; + +/*! @brief FlexCAN protocol timing characteristic configuration structure. */ +typedef struct _flexcan_timing_config +{ + uint8_t preDivider; /*!< Clock Pre-scaler Division Factor. */ + uint8_t rJumpwidth; /*!< Re-sync Jump Width. */ + uint8_t phaseSeg1; /*!< Phase Segment 1. */ + uint8_t phaseSeg2; /*!< Phase Segment 2. */ + uint8_t propSeg; /*!< Propagation Segment. */ +} flexcan_timing_config_t; + +/*! + * @brief FlexCAN Receive Message Buffer configuration structure + * + * This structure is used as the parameter of FLEXCAN_SetRxMbConfig() function. + * The FLEXCAN_SetRxMbConfig() function is used to configure FlexCAN Receive + * Message Buffer. The function abort previous receiving process, clean the + * Message Buffer and activate the Rx Message Buffer using given Message Buffer + * setting. + */ +typedef struct _flexcan_rx_mb_config +{ + uint32_t id; /*!< CAN Message Buffer Frame Identifier, should be set using + FLEXCAN_ID_EXT() or FLEXCAN_ID_STD() macro. */ + flexcan_frame_format_t format; /*!< CAN Frame Identifier format(Standard of Extend). */ + flexcan_frame_type_t type; /*!< CAN Frame Type(Data or Remote). */ +} flexcan_rx_mb_config_t; + +/*! @brief FlexCAN Rx FIFO configuration structure. */ +typedef struct _flexcan_rx_fifo_config +{ + uint32_t *idFilterTable; /*!< Pointer to the FlexCAN Rx FIFO identifier filter table. */ + uint8_t idFilterNum; /*!< The quantity of filter elements. */ + flexcan_rx_fifo_filter_type_t idFilterType; /*!< The FlexCAN Rx FIFO Filter type. */ + flexcan_rx_fifo_priority_t priority; /*!< The FlexCAN Rx FIFO receive priority. */ +} flexcan_rx_fifo_config_t; + +/*! @brief FlexCAN Message Buffer transfer. */ +typedef struct _flexcan_mb_transfer +{ + flexcan_frame_t *frame; /*!< The buffer of CAN Message to be transfer. */ + uint8_t mbIdx; /*!< The index of Message buffer used to transfer Message. */ +} flexcan_mb_transfer_t; + +/*! @brief FlexCAN Rx FIFO transfer. */ +typedef struct _flexcan_fifo_transfer +{ + flexcan_frame_t *frame; /*!< The buffer of CAN Message to be received from Rx FIFO. */ +} flexcan_fifo_transfer_t; + +/*! @brief FlexCAN handle structure definition. */ +typedef struct _flexcan_handle flexcan_handle_t; + +/*! @brief FlexCAN transfer callback function. + * + * The FlexCAN transfer callback returns a value from the underlying layer. + * If the status equals to kStatus_FLEXCAN_ErrorStatus, the result parameter is the Content of + * FlexCAN status register which can be used to get the working status(or error status) of FlexCAN module. + * If the status equals to other FlexCAN Message Buffer transfer status, the result is the index of + * Message Buffer that generate transfer event. + * If the status equals to other FlexCAN Message Buffer transfer status, the result is meaningless and should be + * Ignored. + */ +typedef BaseType_t (*flexcan_transfer_callback_t)( + CAN_Type *base, flexcan_handle_t *handle, status_t status, uint32_t result, void *userData); + +/*! @brief FlexCAN handle structure. */ +struct _flexcan_handle +{ + flexcan_transfer_callback_t callback; /*!< Callback function. */ + void *userData; /*!< FlexCAN callback function parameter.*/ + flexcan_frame_t *volatile mbFrameBuf[CAN_WORD1_COUNT]; + /*!< The buffer for received data from Message Buffers. */ + flexcan_frame_t *volatile rxFifoFrameBuf; /*!< The buffer for received data from Rx FIFO. */ + volatile uint8_t mbState[CAN_WORD1_COUNT]; /*!< Message Buffer transfer state. */ + volatile uint8_t rxFifoState; /*!< Rx FIFO transfer state. */ +}; + +/****************************************************************************** + * API + *****************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Initializes a FlexCAN instance. + * + * This function initializes the FlexCAN module with user-defined settings. + * This example shows how to set up the flexcan_config_t parameters and how + * to call the FLEXCAN_Init function by passing in these parameters. + * @code + * flexcan_config_t flexcanConfig; + * flexcanConfig.clkSrc = kFLEXCAN_ClkSrcOsc; + * flexcanConfig.baudRate = 125000U; + * flexcanConfig.maxMbNum = 16; + * flexcanConfig.enableLoopBack = false; + * flexcanConfig.enableSelfWakeup = false; + * flexcanConfig.enableIndividMask = false; + * flexcanConfig.enableDoze = false; + * FLEXCAN_Init(CAN0, &flexcanConfig, 8000000UL); + * @endcode + * + * @param base FlexCAN peripheral base address. + * @param config Pointer to the user-defined configuration structure. + * @param sourceClock_Hz FlexCAN Protocol Engine clock source frequency in Hz. + */ +void FLEXCAN_Init(CAN_Type *base, const flexcan_config_t *config, uint32_t sourceClock_Hz); + +/*! + * @brief De-initializes a FlexCAN instance. + * + * This function disables the FlexCAN module clock and sets all register values + * to the reset value. + * + * @param base FlexCAN peripheral base address. + */ +void FLEXCAN_Deinit(CAN_Type *base); + +/*! + * @brief Gets the default configuration structure. + * + * This function initializes the FlexCAN configuration structure to default values. The default + * values are as follows. + * flexcanConfig->clkSrc = KFLEXCAN_ClkSrcOsc; + * flexcanConfig->baudRate = 125000U; + * flexcanConfig->maxMbNum = 16; + * flexcanConfig->enableLoopBack = false; + * flexcanConfig->enableSelfWakeup = false; + * flexcanConfig->enableIndividMask = false; + * flexcanConfig->enableDoze = false; + * + * @param config Pointer to the FlexCAN configuration structure. + */ +void FLEXCAN_GetDefaultConfig(flexcan_config_t *config); + +/* @} */ + +/*! + * @name Configuration. + * @{ + */ + +/*! + * @brief Enter FlexCAN Freeze Mode. + * + * This function makes the FlexCAN work under Freeze Mode. + * + * @param base FlexCAN peripheral base address. + */ +void FLEXCAN_EnterFreezeMode(CAN_Type *base); + +/*! + * @brief Exit FlexCAN Freeze Mode. + * + * This function makes the FlexCAN leave Freeze Mode. + * + * @param base FlexCAN peripheral base address. + */ +void FLEXCAN_ExitFreezeMode(CAN_Type *base); + +/*! + * @brief Sets the FlexCAN protocol timing characteristic. + * + * This function gives user settings to CAN bus timing characteristic. + * The function is for an experienced user. For less experienced users, call + * the FLEXCAN_Init() and fill the baud rate field with a desired value. + * This provides the default timing characteristics to the module. + * + * Note that calling FLEXCAN_SetTimingConfig() overrides the baud rate set + * in FLEXCAN_Init(). + * + * @param base FlexCAN peripheral base address. + * @param config Pointer to the timing configuration structure. + */ +void FLEXCAN_SetTimingConfig(CAN_Type *base, const flexcan_timing_config_t *config); + +void FLEXCAN_SetBitRate(CAN_Type *base, uint32_t sourceClock_Hz, uint32_t baudRate_Bps); + +void FLEXCAN_SetMode(CAN_Type *base, uint32_t mode); + +/*! + * @brief Sets the FlexCAN receive message buffer global mask. + * + * This function sets the global mask for the FlexCAN message buffer in a matching process. + * The configuration is only effective when the Rx individual mask is disabled in the FLEXCAN_Init(). + * + * @param base FlexCAN peripheral base address. + * @param mask Rx Message Buffer Global Mask value. + */ +void FLEXCAN_SetRxMbGlobalMask(CAN_Type *base, uint32_t mask); + +/*! + * @brief Sets the FlexCAN receive FIFO global mask. + * + * This function sets the global mask for FlexCAN FIFO in a matching process. + * + * @param base FlexCAN peripheral base address. + * @param mask Rx Fifo Global Mask value. + */ +void FLEXCAN_SetRxFifoGlobalMask(CAN_Type *base, uint32_t mask); + +/*! + * @brief Sets the FlexCAN receive individual mask. + * + * This function sets the individual mask for the FlexCAN matching process. + * The configuration is only effective when the Rx individual mask is enabled in the FLEXCAN_Init(). + * If the Rx FIFO is disabled, the individual mask is applied to the corresponding Message Buffer. + * If the Rx FIFO is enabled, the individual mask for Rx FIFO occupied Message Buffer is applied to + * the Rx Filter with the same index. Note that only the first 32 + * individual masks can be used as the Rx FIFO filter mask. + * + * @param base FlexCAN peripheral base address. + * @param maskIdx The Index of individual Mask. + * @param mask Rx Individual Mask value. + */ +void FLEXCAN_SetRxIndividualMask(CAN_Type *base, uint8_t maskIdx, uint32_t mask); + +/*! + * @brief Configures a FlexCAN transmit message buffer. + * + * This function aborts the previous transmission, cleans the Message Buffer, and + * configures it as a Transmit Message Buffer. + * + * @param base FlexCAN peripheral base address. + * @param mbIdx The Message Buffer index. + * @param enable Enable/disable Tx Message Buffer. + * - true: Enable Tx Message Buffer. + * - false: Disable Tx Message Buffer. + */ +void FLEXCAN_SetTxMbConfig(CAN_Type *base, uint8_t mbIdx, bool enable); + +/*! + * @brief Configures a FlexCAN Receive Message Buffer. + * + * This function cleans a FlexCAN build-in Message Buffer and configures it + * as a Receive Message Buffer. + * + * @param base FlexCAN peripheral base address. + * @param mbIdx The Message Buffer index. + * @param config Pointer to the FlexCAN Message Buffer configuration structure. + * @param enable Enable/disable Rx Message Buffer. + * - true: Enable Rx Message Buffer. + * - false: Disable Rx Message Buffer. + */ +void FLEXCAN_SetRxMbConfig(CAN_Type *base, uint8_t mbIdx, const flexcan_rx_mb_config_t *config, bool enable); + +/*! + * @brief Configures the FlexCAN Rx FIFO. + * + * This function configures the Rx FIFO with given Rx FIFO configuration. + * + * @param base FlexCAN peripheral base address. + * @param config Pointer to the FlexCAN Rx FIFO configuration structure. + * @param enable Enable/disable Rx FIFO. + * - true: Enable Rx FIFO. + * - false: Disable Rx FIFO. + */ +void FLEXCAN_SetRxFifoConfig(CAN_Type *base, const flexcan_rx_fifo_config_t *config, bool enable); + +/* @} */ + +/*! + * @name Status + * @{ + */ + +/*! + * @brief Gets the FlexCAN module interrupt flags. + * + * This function gets all FlexCAN status flags. The flags are returned as the logical + * OR value of the enumerators @ref _flexcan_flags. To check the specific status, + * compare the return value with enumerators in @ref _flexcan_flags. + * + * @param base FlexCAN peripheral base address. + * @return FlexCAN status flags which are ORed by the enumerators in the _flexcan_flags. + */ +static inline uint32_t FLEXCAN_GetStatusFlags(CAN_Type *base) +{ + return base->ESR1; +} + +/*! + * @brief Clears status flags with the provided mask. + * + * This function clears the FlexCAN status flags with a provided mask. An automatically cleared flag + * can't be cleared by this function. + * + * @param base FlexCAN peripheral base address. + * @param mask The status flags to be cleared, it is logical OR value of @ref _flexcan_flags. + */ +static inline void FLEXCAN_ClearStatusFlags(CAN_Type *base, uint32_t mask) +{ + /* Write 1 to clear status flag. */ + base->ESR1 = mask; +} + +/*! + * @brief Gets the FlexCAN Bus Error Counter value. + * + * This function gets the FlexCAN Bus Error Counter value for both Tx and + * Rx direction. These values may be needed in the upper layer error handling. + * + * @param base FlexCAN peripheral base address. + * @param txErrBuf Buffer to store Tx Error Counter value. + * @param rxErrBuf Buffer to store Rx Error Counter value. + */ +static inline void FLEXCAN_GetBusErrCount(CAN_Type *base, uint8_t *txErrBuf, uint8_t *rxErrBuf) +{ + if (txErrBuf) + { + *txErrBuf = (uint8_t)((base->ECR & CAN_ECR_TXERRCNT_MASK) >> CAN_ECR_TXERRCNT_SHIFT); + } + + if (rxErrBuf) + { + *rxErrBuf = (uint8_t)((base->ECR & CAN_ECR_RXERRCNT_MASK) >> CAN_ECR_RXERRCNT_SHIFT); + } +} + +/*! + * @brief Gets the FlexCAN Message Buffer interrupt flags. + * + * This function gets the interrupt flags of a given Message Buffers. + * + * @param base FlexCAN peripheral base address. + * @param mask The ORed FlexCAN Message Buffer mask. + * @return The status of given Message Buffers. + */ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) +static inline uint64_t FLEXCAN_GetMbStatusFlags(CAN_Type *base, uint64_t mask) +#else +static inline uint32_t FLEXCAN_GetMbStatusFlags(CAN_Type *base, uint32_t mask) +#endif +{ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) + return ((((uint64_t)base->IFLAG1) & mask) | ((((uint64_t)base->IFLAG2) << 32) & mask)); +#else + return (base->IFLAG1 & mask); +#endif +} + +/*! + * @brief Clears the FlexCAN Message Buffer interrupt flags. + * + * This function clears the interrupt flags of a given Message Buffers. + * + * @param base FlexCAN peripheral base address. + * @param mask The ORed FlexCAN Message Buffer mask. + */ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) +static inline void FLEXCAN_ClearMbStatusFlags(CAN_Type *base, uint64_t mask) +#else +static inline void FLEXCAN_ClearMbStatusFlags(CAN_Type *base, uint32_t mask) +#endif +{ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) + base->IFLAG1 = (uint32_t)(mask & 0xFFFFFFFFU); + base->IFLAG2 = (uint32_t)(mask >> 32); +#else + base->IFLAG1 = mask; +#endif +} + +/* @} */ + +/*! + * @name Interrupts + * @{ + */ + +/*! + * @brief Enables FlexCAN interrupts according to the provided mask. + * + * This function enables the FlexCAN interrupts according to the provided mask. The mask + * is a logical OR of enumeration members, see @ref _flexcan_interrupt_enable. + * + * @param base FlexCAN peripheral base address. + * @param mask The interrupts to enable. Logical OR of @ref _flexcan_interrupt_enable. + */ +static inline void FLEXCAN_EnableInterrupts(CAN_Type *base, uint32_t mask) +{ + /* Solve Wake Up Interrupt. */ + if (mask & kFLEXCAN_WakeUpInterruptEnable) + { + base->MCR |= CAN_MCR_WAKMSK_MASK; + } + + /* Solve others. */ + base->CTRL1 |= (mask & (~((uint32_t)kFLEXCAN_WakeUpInterruptEnable))); +} + +/*! + * @brief Disables FlexCAN interrupts according to the provided mask. + * + * This function disables the FlexCAN interrupts according to the provided mask. The mask + * is a logical OR of enumeration members, see @ref _flexcan_interrupt_enable. + * + * @param base FlexCAN peripheral base address. + * @param mask The interrupts to disable. Logical OR of @ref _flexcan_interrupt_enable. + */ +static inline void FLEXCAN_DisableInterrupts(CAN_Type *base, uint32_t mask) +{ + /* Solve Wake Up Interrupt. */ + if (mask & kFLEXCAN_WakeUpInterruptEnable) + { + base->MCR &= ~CAN_MCR_WAKMSK_MASK; + } + + /* Solve others. */ + base->CTRL1 &= ~(mask & (~((uint32_t)kFLEXCAN_WakeUpInterruptEnable))); +} + +/*! + * @brief Enables FlexCAN Message Buffer interrupts. + * + * This function enables the interrupts of given Message Buffers. + * + * @param base FlexCAN peripheral base address. + * @param mask The ORed FlexCAN Message Buffer mask. + */ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) +static inline void FLEXCAN_EnableMbInterrupts(CAN_Type *base, uint64_t mask) +#else +static inline void FLEXCAN_EnableMbInterrupts(CAN_Type *base, uint32_t mask) +#endif +{ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) + base->IMASK1 |= (uint32_t)(mask & 0xFFFFFFFFU); + base->IMASK2 |= (uint32_t)(mask >> 32); +#else + base->IMASK1 |= mask; +#endif +} + +/*! + * @brief Disables FlexCAN Message Buffer interrupts. + * + * This function disables the interrupts of given Message Buffers. + * + * @param base FlexCAN peripheral base address. + * @param mask The ORed FlexCAN Message Buffer mask. + */ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) +static inline void FLEXCAN_DisableMbInterrupts(CAN_Type *base, uint64_t mask) +#else +static inline void FLEXCAN_DisableMbInterrupts(CAN_Type *base, uint32_t mask) +#endif +{ +#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) + base->IMASK1 &= ~((uint32_t)(mask & 0xFFFFFFFFU)); + base->IMASK2 &= ~((uint32_t)(mask >> 32)); +#else + base->IMASK1 &= ~mask; +#endif +} + +/* @} */ + +#if (defined(FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA) && FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA) +/*! + * @name DMA Control + * @{ + */ + +/*! + * @brief Enables or disables the FlexCAN Rx FIFO DMA request. + * + * This function enables or disables the DMA feature of FlexCAN build-in Rx FIFO. + * + * @param base FlexCAN peripheral base address. + * @param enable true to enable, false to disable. + */ +void FLEXCAN_EnableRxFifoDMA(CAN_Type *base, bool enable); + +/*! + * @brief Gets the Rx FIFO Head address. + * + * This function returns the FlexCAN Rx FIFO Head address, which is mainly used for the DMA/eDMA use case. + * + * @param base FlexCAN peripheral base address. + * @return FlexCAN Rx FIFO Head address. + */ +static inline uint32_t FLEXCAN_GetRxFifoHeadAddr(CAN_Type *base) +{ + return (uint32_t) & (base->MB[0].CS); +} + +/* @} */ +#endif /* FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA */ + +/*! + * @name Bus Operations + * @{ + */ + +/*! + * @brief Enables or disables the FlexCAN module operation. + * + * This function enables or disables the FlexCAN module. + * + * @param base FlexCAN base pointer. + * @param enable true to enable, false to disable. + */ +static inline void FLEXCAN_Enable(CAN_Type *base, bool enable) +{ + if (enable) + { + base->MCR &= ~CAN_MCR_MDIS_MASK; + + /* Wait FlexCAN exit from low-power mode. */ + while (base->MCR & CAN_MCR_LPMACK_MASK) + { + } + } + else + { + base->MCR |= CAN_MCR_MDIS_MASK; + + /* Wait FlexCAN enter low-power mode. */ + while (!(base->MCR & CAN_MCR_LPMACK_MASK)) + { + } + } +} + +/*! + * @brief Writes a FlexCAN Message to the Transmit Message Buffer. + * + * This function writes a CAN Message to the specified Transmit Message Buffer + * and changes the Message Buffer state to start CAN Message transmit. After + * that the function returns immediately. + * + * @param base FlexCAN peripheral base address. + * @param mbIdx The FlexCAN Message Buffer index. + * @param txFrame Pointer to CAN message frame to be sent. + * @retval kStatus_Success - Write Tx Message Buffer Successfully. + * @retval kStatus_Fail - Tx Message Buffer is currently in use. + */ +status_t FLEXCAN_WriteTxMb(CAN_Type *base, uint8_t mbIdx, const flexcan_frame_t *txFrame); + +/*! + * @brief Reads a FlexCAN Message from Receive Message Buffer. + * + * This function reads a CAN message from a specified Receive Message Buffer. + * The function fills a receive CAN message frame structure with + * just received data and activates the Message Buffer again. + * The function returns immediately. + * + * @param base FlexCAN peripheral base address. + * @param mbIdx The FlexCAN Message Buffer index. + * @param rxFrame Pointer to CAN message frame structure for reception. + * @retval kStatus_Success - Rx Message Buffer is full and has been read successfully. + * @retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully. + * @retval kStatus_Fail - Rx Message Buffer is empty. + */ +status_t FLEXCAN_ReadRxMb(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *rxFrame); + +/*! + * @brief Reads a FlexCAN Message from Rx FIFO. + * + * This function reads a CAN message from the FlexCAN build-in Rx FIFO. + * + * @param base FlexCAN peripheral base address. + * @param rxFrame Pointer to CAN message frame structure for reception. + * @retval kStatus_Success - Read Message from Rx FIFO successfully. + * @retval kStatus_Fail - Rx FIFO is not enabled. + */ +status_t FLEXCAN_ReadRxFifo(CAN_Type *base, flexcan_frame_t *rxFrame); + +/* @} */ + +/*! + * @name Transactional + * @{ + */ + +/*! + * @brief Performs a polling send transaction on the CAN bus. + * + * Note that a transfer handle does not need to be created before calling this API. + * + * @param base FlexCAN peripheral base pointer. + * @param mbIdx The FlexCAN Message Buffer index. + * @param txFrame Pointer to CAN message frame to be sent. + * @retval kStatus_Success - Write Tx Message Buffer Successfully. + * @retval kStatus_Fail - Tx Message Buffer is currently in use. + */ +status_t FLEXCAN_TransferSendBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *txFrame); + +/*! + * @brief Performs a polling receive transaction on the CAN bus. + * + * Note that a transfer handle does not need to be created before calling this API. + * + * @param base FlexCAN peripheral base pointer. + * @param mbIdx The FlexCAN Message Buffer index. + * @param rxFrame Pointer to CAN message frame structure for reception. + * @retval kStatus_Success - Rx Message Buffer is full and has been read successfully. + * @retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully. + * @retval kStatus_Fail - Rx Message Buffer is empty. + */ +status_t FLEXCAN_TransferReceiveBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *rxFrame); + +/*! + * @brief Performs a polling receive transaction from Rx FIFO on the CAN bus. + * + * Note that a transfer handle does not need to be created before calling this API. + * + * @param base FlexCAN peripheral base pointer. + * @param rxFrame Pointer to CAN message frame structure for reception. + * @retval kStatus_Success - Read Message from Rx FIFO successfully. + * @retval kStatus_Fail - Rx FIFO is not enabled. + */ +status_t FLEXCAN_TransferReceiveFifoBlocking(CAN_Type *base, flexcan_frame_t *rxFrame); + +/*! + * @brief Initializes the FlexCAN handle. + * + * This function initializes the FlexCAN handle, which can be used for other FlexCAN + * transactional APIs. Usually, for a specified FlexCAN instance, + * call this API once to get the initialized handle. + * + * @param base FlexCAN peripheral base address. + * @param handle FlexCAN handle pointer. + * @param callback The callback function. + * @param userData The parameter of the callback function. + */ +void FLEXCAN_TransferCreateHandle(CAN_Type *base, + flexcan_handle_t *handle, + flexcan_transfer_callback_t callback, + void *userData); + +/*! + * @brief Sends a message using IRQ. + * + * This function sends a message using IRQ. This is a non-blocking function, which returns + * right away. When messages have been sent out, the send callback function is called. + * + * @param base FlexCAN peripheral base address. + * @param handle FlexCAN handle pointer. + * @param xfer FlexCAN Message Buffer transfer structure. See the #flexcan_mb_transfer_t. + * @retval kStatus_Success Start Tx Message Buffer sending process successfully. + * @retval kStatus_Fail Write Tx Message Buffer failed. + * @retval kStatus_FLEXCAN_TxBusy Tx Message Buffer is in use. + */ +status_t FLEXCAN_TransferSendNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *xfer); + +/*! + * @brief Receives a message using IRQ. + * + * This function receives a message using IRQ. This is non-blocking function, which returns + * right away. When the message has been received, the receive callback function is called. + * + * @param base FlexCAN peripheral base address. + * @param handle FlexCAN handle pointer. + * @param xfer FlexCAN Message Buffer transfer structure. See the #flexcan_mb_transfer_t. + * @retval kStatus_Success - Start Rx Message Buffer receiving process successfully. + * @retval kStatus_FLEXCAN_RxBusy - Rx Message Buffer is in use. + */ +status_t FLEXCAN_TransferReceiveNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *xfer); + +/*! + * @brief Receives a message from Rx FIFO using IRQ. + * + * This function receives a message using IRQ. This is a non-blocking function, which returns + * right away. When all messages have been received, the receive callback function is called. + * + * @param base FlexCAN peripheral base address. + * @param handle FlexCAN handle pointer. + * @param xfer FlexCAN Rx FIFO transfer structure. See the @ref flexcan_fifo_transfer_t. + * @retval kStatus_Success - Start Rx FIFO receiving process successfully. + * @retval kStatus_FLEXCAN_RxFifoBusy - Rx FIFO is currently in use. + */ +status_t FLEXCAN_TransferReceiveFifoNonBlocking(CAN_Type *base, + flexcan_handle_t *handle, + flexcan_fifo_transfer_t *xfer); + +/*! + * @brief Aborts the interrupt driven message send process. + * + * This function aborts the interrupt driven message send process. + * + * @param base FlexCAN peripheral base address. + * @param handle FlexCAN handle pointer. + * @param mbIdx The FlexCAN Message Buffer index. + */ +void FLEXCAN_TransferAbortSend(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx); + +/*! + * @brief Aborts the interrupt driven message receive process. + * + * This function aborts the interrupt driven message receive process. + * + * @param base FlexCAN peripheral base address. + * @param handle FlexCAN handle pointer. + * @param mbIdx The FlexCAN Message Buffer index. + */ +void FLEXCAN_TransferAbortReceive(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx); + +/*! + * @brief Aborts the interrupt driven message receive from Rx FIFO process. + * + * This function aborts the interrupt driven message receive from Rx FIFO process. + * + * @param base FlexCAN peripheral base address. + * @param handle FlexCAN handle pointer. + */ +void FLEXCAN_TransferAbortReceiveFifo(CAN_Type *base, flexcan_handle_t *handle); + +/*! + * @brief FlexCAN IRQ handle function. + * + * This function handles the FlexCAN Error, the Message Buffer, and the Rx FIFO IRQ request. + * + * @param base FlexCAN peripheral base address. + * @param handle FlexCAN handle pointer. + */ +void FLEXCAN_TransferHandleIRQ(CAN_Type *base, flexcan_handle_t *handle); + +/* @} */ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_FLEXCAN_H_ */ diff --git a/drivers/include/fsl_ftm.h b/drivers/include/fsl_ftm.h new file mode 100644 index 0000000..8db81a6 --- /dev/null +++ b/drivers/include/fsl_ftm.h @@ -0,0 +1,973 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_FTM_H_ +#define _FSL_FTM_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup ftm + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +#define FSL_FTM_DRIVER_VERSION (MAKE_VERSION(2, 0, 2)) /*!< Version 2.0.2 */ + /*@}*/ + +/*! + * @brief List of FTM channels + * @note Actual number of available channels is SoC dependent + */ +typedef enum _ftm_chnl +{ + kFTM_Chnl_0 = 0U, /*!< FTM channel number 0*/ + kFTM_Chnl_1, /*!< FTM channel number 1 */ + kFTM_Chnl_2, /*!< FTM channel number 2 */ + kFTM_Chnl_3, /*!< FTM channel number 3 */ + kFTM_Chnl_4, /*!< FTM channel number 4 */ + kFTM_Chnl_5, /*!< FTM channel number 5 */ + kFTM_Chnl_6, /*!< FTM channel number 6 */ + kFTM_Chnl_7 /*!< FTM channel number 7 */ +} ftm_chnl_t; + +/*! @brief List of FTM faults */ +typedef enum _ftm_fault_input +{ + kFTM_Fault_0 = 0U, /*!< FTM fault 0 input pin */ + kFTM_Fault_1, /*!< FTM fault 1 input pin */ + kFTM_Fault_2, /*!< FTM fault 2 input pin */ + kFTM_Fault_3 /*!< FTM fault 3 input pin */ +} ftm_fault_input_t; + +/*! @brief FTM PWM operation modes */ +typedef enum _ftm_pwm_mode +{ + kFTM_EdgeAlignedPwm = 0U, /*!< Edge-aligned PWM */ + kFTM_CenterAlignedPwm, /*!< Center-aligned PWM */ + kFTM_CombinedPwm /*!< Combined PWM */ +} ftm_pwm_mode_t; + +/*! @brief FTM PWM output pulse mode: high-true, low-true or no output */ +typedef enum _ftm_pwm_level_select +{ + kFTM_NoPwmSignal = 0U, /*!< No PWM output on pin */ + kFTM_LowTrue, /*!< Low true pulses */ + kFTM_HighTrue /*!< High true pulses */ +} ftm_pwm_level_select_t; + +/*! @brief Options to configure a FTM channel's PWM signal */ +typedef struct _ftm_chnl_pwm_signal_param +{ + ftm_chnl_t chnlNumber; /*!< The channel/channel pair number. + In combined mode, this represents the channel pair number. */ + ftm_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)... + 100 = always active signal (100% duty cycle).*/ + uint8_t firstEdgeDelayPercent; /*!< Used only in combined PWM mode to generate an asymmetrical PWM. + Specifies the delay to the first edge in a PWM period. + If unsure leave as 0; Should be specified as a + percentage of the PWM period */ +} ftm_chnl_pwm_signal_param_t; + +/*! @brief FlexTimer output compare mode */ +typedef enum _ftm_output_compare_mode +{ + kFTM_NoOutputSignal = (1U << FTM_CnSC_MSA_SHIFT), /*!< No channel output when counter reaches CnV */ + kFTM_ToggleOnMatch = ((1U << FTM_CnSC_MSA_SHIFT) | (1U << FTM_CnSC_ELSA_SHIFT)), /*!< Toggle output */ + kFTM_ClearOnMatch = ((1U << FTM_CnSC_MSA_SHIFT) | (2U << FTM_CnSC_ELSA_SHIFT)), /*!< Clear output */ + kFTM_SetOnMatch = ((1U << FTM_CnSC_MSA_SHIFT) | (3U << FTM_CnSC_ELSA_SHIFT)) /*!< Set output */ +} ftm_output_compare_mode_t; + +/*! @brief FlexTimer input capture edge */ +typedef enum _ftm_input_capture_edge +{ + kFTM_RisingEdge = (1U << FTM_CnSC_ELSA_SHIFT), /*!< Capture on rising edge only*/ + kFTM_FallingEdge = (2U << FTM_CnSC_ELSA_SHIFT), /*!< Capture on falling edge only*/ + kFTM_RiseAndFallEdge = (3U << FTM_CnSC_ELSA_SHIFT) /*!< Capture on rising or falling edge */ +} ftm_input_capture_edge_t; + +/*! @brief FlexTimer dual edge capture modes */ +typedef enum _ftm_dual_edge_capture_mode +{ + kFTM_OneShot = 0U, /*!< One-shot capture mode */ + kFTM_Continuous = (1U << FTM_CnSC_MSA_SHIFT) /*!< Continuous capture mode */ +} ftm_dual_edge_capture_mode_t; + +/*! @brief FlexTimer dual edge capture parameters */ +typedef struct _ftm_dual_edge_capture_param +{ + ftm_dual_edge_capture_mode_t mode; /*!< Dual Edge Capture mode */ + ftm_input_capture_edge_t currChanEdgeMode; /*!< Input capture edge select for channel n */ + ftm_input_capture_edge_t nextChanEdgeMode; /*!< Input capture edge select for channel n+1 */ +} ftm_dual_edge_capture_param_t; + +/*! @brief FlexTimer quadrature decode modes */ +typedef enum _ftm_quad_decode_mode +{ + kFTM_QuadPhaseEncode = 0U, /*!< Phase A and Phase B encoding mode */ + kFTM_QuadCountAndDir /*!< Count and direction encoding mode */ +} ftm_quad_decode_mode_t; + +/*! @brief FlexTimer quadrature phase polarities */ +typedef enum _ftm_phase_polarity +{ + kFTM_QuadPhaseNormal = 0U, /*!< Phase input signal is not inverted */ + kFTM_QuadPhaseInvert /*!< Phase input signal is inverted */ +} ftm_phase_polarity_t; + +/*! @brief FlexTimer quadrature decode phase parameters */ +typedef struct _ftm_phase_param +{ + bool enablePhaseFilter; /*!< True: enable phase filter; false: disable filter */ + uint32_t phaseFilterVal; /*!< Filter value, used only if phase filter is enabled */ + ftm_phase_polarity_t phasePolarity; /*!< Phase polarity */ +} ftm_phase_params_t; + +/*! @brief Structure is used to hold the parameters to configure a FTM fault */ +typedef struct _ftm_fault_param +{ + bool enableFaultInput; /*!< True: Fault input is enabled; false: Fault input is disabled */ + bool faultLevel; /*!< True: Fault polarity is active low; in other words, '0' indicates a fault; + False: Fault polarity is active high */ + bool useFaultFilter; /*!< True: Use the filtered fault signal; + False: Use the direct path from fault input */ +} ftm_fault_param_t; + +/*! @brief FlexTimer pre-scaler factor for the dead time insertion*/ +typedef enum _ftm_deadtime_prescale +{ + kFTM_Deadtime_Prescale_1 = 1U, /*!< Divide by 1 */ + kFTM_Deadtime_Prescale_4, /*!< Divide by 4 */ + kFTM_Deadtime_Prescale_16 /*!< Divide by 16 */ +} ftm_deadtime_prescale_t; + +/*! @brief FlexTimer clock source selection*/ +typedef enum _ftm_clock_source +{ + kFTM_SystemClock = 1U, /*!< System clock selected */ + kFTM_FixedClock, /*!< Fixed frequency clock */ + kFTM_ExternalClock /*!< External clock */ +} ftm_clock_source_t; + +/*! @brief FlexTimer pre-scaler factor selection for the clock source*/ +typedef enum _ftm_clock_prescale +{ + kFTM_Prescale_Divide_1 = 0U, /*!< Divide by 1 */ + kFTM_Prescale_Divide_2, /*!< Divide by 2 */ + kFTM_Prescale_Divide_4, /*!< Divide by 4 */ + kFTM_Prescale_Divide_8, /*!< Divide by 8 */ + kFTM_Prescale_Divide_16, /*!< Divide by 16 */ + kFTM_Prescale_Divide_32, /*!< Divide by 32 */ + kFTM_Prescale_Divide_64, /*!< Divide by 64 */ + kFTM_Prescale_Divide_128 /*!< Divide by 128 */ +} ftm_clock_prescale_t; + +/*! @brief Options for the FlexTimer behaviour in BDM Mode */ +typedef enum _ftm_bdm_mode +{ + kFTM_BdmMode_0 = 0U, + /*!< FTM counter stopped, CH(n)F bit can be set, FTM channels in functional mode, writes to MOD,CNTIN and C(n)V + registers bypass the register buffers */ + kFTM_BdmMode_1, + /*!< FTM counter stopped, CH(n)F bit is not set, FTM channels outputs are forced to their safe value , writes to + MOD,CNTIN and C(n)V registers bypass the register buffers */ + kFTM_BdmMode_2, + /*!< FTM counter stopped, CH(n)F bit is not set, FTM channels outputs are frozen when chip enters in BDM mode, + writes to MOD,CNTIN and C(n)V registers bypass the register buffers */ + kFTM_BdmMode_3 + /*!< FTM counter in functional mode, CH(n)F bit can be set, FTM channels in functional mode, writes to MOD,CNTIN and + C(n)V registers is in fully functional mode */ +} ftm_bdm_mode_t; + +/*! @brief Options for the FTM fault control mode */ +typedef enum _ftm_fault_mode +{ + kFTM_Fault_Disable = 0U, /*!< Fault control is disabled for all channels */ + kFTM_Fault_EvenChnls, /*!< Enabled for even channels only(0,2,4,6) with manual fault clearing */ + kFTM_Fault_AllChnlsMan, /*!< Enabled for all channels with manual fault clearing */ + kFTM_Fault_AllChnlsAuto /*!< Enabled for all channels with automatic fault clearing */ +} ftm_fault_mode_t; + +/*! + * @brief FTM external trigger options + * @note Actual available external trigger sources are SoC-specific + */ +typedef enum _ftm_external_trigger +{ + kFTM_Chnl0Trigger = (1U << 4), /*!< Generate trigger when counter equals chnl 0 CnV reg */ + kFTM_Chnl1Trigger = (1U << 5), /*!< Generate trigger when counter equals chnl 1 CnV reg */ + kFTM_Chnl2Trigger = (1U << 0), /*!< Generate trigger when counter equals chnl 2 CnV reg */ + kFTM_Chnl3Trigger = (1U << 1), /*!< Generate trigger when counter equals chnl 3 CnV reg */ + kFTM_Chnl4Trigger = (1U << 2), /*!< Generate trigger when counter equals chnl 4 CnV reg */ + kFTM_Chnl5Trigger = (1U << 3), /*!< Generate trigger when counter equals chnl 5 CnV reg */ + kFTM_Chnl6Trigger = + (1U << 8), /*!< Available on certain SoC's, generate trigger when counter equals chnl 6 CnV reg */ + kFTM_Chnl7Trigger = + (1U << 9), /*!< Available on certain SoC's, generate trigger when counter equals chnl 7 CnV reg */ + kFTM_InitTrigger = (1U << 6), /*!< Generate Trigger when counter is updated with CNTIN */ + kFTM_ReloadInitTrigger = (1U << 7) /*!< Available on certain SoC's, trigger on reload point */ +} ftm_external_trigger_t; + +/*! @brief FlexTimer PWM sync options to update registers with buffer */ +typedef enum _ftm_pwm_sync_method +{ + kFTM_SoftwareTrigger = FTM_SYNC_SWSYNC_MASK, /*!< Software triggers PWM sync */ + kFTM_HardwareTrigger_0 = FTM_SYNC_TRIG0_MASK, /*!< Hardware trigger 0 causes PWM sync */ + kFTM_HardwareTrigger_1 = FTM_SYNC_TRIG1_MASK, /*!< Hardware trigger 1 causes PWM sync */ + kFTM_HardwareTrigger_2 = FTM_SYNC_TRIG2_MASK /*!< Hardware trigger 2 causes PWM sync */ +} ftm_pwm_sync_method_t; + +/*! + * @brief FTM options available as loading point for register reload + * @note Actual available reload points are SoC-specific + */ +typedef enum _ftm_reload_point +{ + kFTM_Chnl0Match = (1U << 0), /*!< Channel 0 match included as a reload point */ + kFTM_Chnl1Match = (1U << 1), /*!< Channel 1 match included as a reload point */ + kFTM_Chnl2Match = (1U << 2), /*!< Channel 2 match included as a reload point */ + kFTM_Chnl3Match = (1U << 3), /*!< Channel 3 match included as a reload point */ + kFTM_Chnl4Match = (1U << 4), /*!< Channel 4 match included as a reload point */ + kFTM_Chnl5Match = (1U << 5), /*!< Channel 5 match included as a reload point */ + kFTM_Chnl6Match = (1U << 6), /*!< Channel 6 match included as a reload point */ + kFTM_Chnl7Match = (1U << 7), /*!< Channel 7 match included as a reload point */ + kFTM_CntMax = (1U << 8), /*!< Use in up-down count mode only, reload when counter reaches the maximum value */ + kFTM_CntMin = (1U << 9), /*!< Use in up-down count mode only, reload when counter reaches the minimum value */ + kFTM_HalfCycMatch = (1U << 10) /*!< Available on certain SoC's, half cycle match reload point */ +} ftm_reload_point_t; + +/*! + * @brief List of FTM interrupts + * @note Actual available interrupts are SoC-specific + */ +typedef enum _ftm_interrupt_enable +{ + kFTM_Chnl0InterruptEnable = (1U << 0), /*!< Channel 0 interrupt */ + kFTM_Chnl1InterruptEnable = (1U << 1), /*!< Channel 1 interrupt */ + kFTM_Chnl2InterruptEnable = (1U << 2), /*!< Channel 2 interrupt */ + kFTM_Chnl3InterruptEnable = (1U << 3), /*!< Channel 3 interrupt */ + kFTM_Chnl4InterruptEnable = (1U << 4), /*!< Channel 4 interrupt */ + kFTM_Chnl5InterruptEnable = (1U << 5), /*!< Channel 5 interrupt */ + kFTM_Chnl6InterruptEnable = (1U << 6), /*!< Channel 6 interrupt */ + kFTM_Chnl7InterruptEnable = (1U << 7), /*!< Channel 7 interrupt */ + kFTM_FaultInterruptEnable = (1U << 8), /*!< Fault interrupt */ + kFTM_TimeOverflowInterruptEnable = (1U << 9), /*!< Time overflow interrupt */ + kFTM_ReloadInterruptEnable = (1U << 10) /*!< Reload interrupt; Available only on certain SoC's */ +} ftm_interrupt_enable_t; + +/*! + * @brief List of FTM flags + * @note Actual available flags are SoC-specific + */ +typedef enum _ftm_status_flags +{ + kFTM_Chnl0Flag = (1U << 0), /*!< Channel 0 Flag */ + kFTM_Chnl1Flag = (1U << 1), /*!< Channel 1 Flag */ + kFTM_Chnl2Flag = (1U << 2), /*!< Channel 2 Flag */ + kFTM_Chnl3Flag = (1U << 3), /*!< Channel 3 Flag */ + kFTM_Chnl4Flag = (1U << 4), /*!< Channel 4 Flag */ + kFTM_Chnl5Flag = (1U << 5), /*!< Channel 5 Flag */ + kFTM_Chnl6Flag = (1U << 6), /*!< Channel 6 Flag */ + kFTM_Chnl7Flag = (1U << 7), /*!< Channel 7 Flag */ + kFTM_FaultFlag = (1U << 8), /*!< Fault Flag */ + kFTM_TimeOverflowFlag = (1U << 9), /*!< Time overflow Flag */ + kFTM_ChnlTriggerFlag = (1U << 10), /*!< Channel trigger Flag */ + kFTM_ReloadFlag = (1U << 11) /*!< Reload Flag; Available only on certain SoC's */ +} ftm_status_flags_t; + +/*! + * @brief List of FTM Quad Decoder flags. + */ +enum _ftm_quad_decoder_flags +{ + kFTM_QuadDecoderCountingIncreaseFlag = FTM_QDCTRL_QUADIR_MASK, /*!< Counting direction is increasing (FTM counter + increment), or the direction is decreasing. */ + kFTM_QuadDecoderCountingOverflowOnTopFlag = FTM_QDCTRL_TOFDIR_MASK, /*!< Indicates if the TOF bit was set on the top + or the bottom of counting. */ +}; + +/*! + * @brief FTM configuration structure + * + * This structure holds the configuration settings for the FTM peripheral. To initialize this + * structure to reasonable defaults, call the FTM_GetDefaultConfig() function and pass a + * pointer to the configuration structure instance. + * + * The configuration structure can be made constant so as to reside in flash. + */ +typedef struct _ftm_config +{ + ftm_clock_prescale_t prescale; /*!< FTM clock prescale value */ + ftm_bdm_mode_t bdmMode; /*!< FTM behavior in BDM mode */ + uint32_t pwmSyncMode; /*!< Synchronization methods to use to update buffered registers; Multiple + update modes can be used by providing an OR'ed list of options + available in enumeration ::ftm_pwm_sync_method_t. */ + uint32_t reloadPoints; /*!< FTM reload points; When using this, the PWM + synchronization is not required. Multiple reload points can be used by providing + an OR'ed list of options available in + enumeration ::ftm_reload_point_t. */ + ftm_fault_mode_t faultMode; /*!< FTM fault control mode */ + uint8_t faultFilterValue; /*!< Fault input filter value */ + ftm_deadtime_prescale_t deadTimePrescale; /*!< The dead time prescalar value */ + uint32_t deadTimeValue; /*!< The dead time value + deadTimeValue's available range is 0-1023 when register has DTVALEX, + otherwise its available range is 0-63. */ + uint32_t extTriggers; /*!< External triggers to enable. Multiple trigger sources can be + enabled by providing an OR'ed list of options available in + enumeration ::ftm_external_trigger_t. */ + uint8_t chnlInitState; /*!< Defines the initialization value of the channels in OUTINT register */ + uint8_t chnlPolarity; /*!< Defines the output polarity of the channels in POL register */ + bool useGlobalTimeBase; /*!< True: Use of an external global time base is enabled; + False: disabled */ +} ftm_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Ungates the FTM clock and configures the peripheral for basic operation. + * + * @note This API should be called at the beginning of the application which is using the FTM driver. + * + * @param base FTM peripheral base address + * @param config Pointer to the user configuration structure. + * + * @return kStatus_Success indicates success; Else indicates failure. + */ +status_t FTM_Init(FTM_Type *base, const ftm_config_t *config); + +/*! + * @brief Gates the FTM clock. + * + * @param base FTM peripheral base address + */ +void FTM_Deinit(FTM_Type *base); + +/*! + * @brief Fills in the FTM configuration structure with the default settings. + * + * The default values are: + * @code + * config->prescale = kFTM_Prescale_Divide_1; + * config->bdmMode = kFTM_BdmMode_0; + * config->pwmSyncMode = kFTM_SoftwareTrigger; + * config->reloadPoints = 0; + * config->faultMode = kFTM_Fault_Disable; + * config->faultFilterValue = 0; + * config->deadTimePrescale = kFTM_Deadtime_Prescale_1; + * config->deadTimeValue = 0; + * config->extTriggers = 0; + * config->chnlInitState = 0; + * config->chnlPolarity = 0; + * config->useGlobalTimeBase = false; + * @endcode + * @param config Pointer to the user configuration structure. + */ +void FTM_GetDefaultConfig(ftm_config_t *config); + +/*! @}*/ + +/*! + * @name Channel mode operations + * @{ + */ + +/*! + * @brief Configures the PWM signal parameters. + * + * Call this function to configure the PWM signal period, mode, duty cycle, and edge. Use this + * function to configure all FTM channels that are used to output a PWM signal. + * + * @param base FTM peripheral base address + * @param chnlParams Array of PWM channel parameters to configure the channel(s) + * @param numOfChnls Number of channels to configure; This should be the size of the array passed in + * @param mode PWM operation mode, options available in enumeration ::ftm_pwm_mode_t + * @param pwmFreq_Hz PWM signal frequency in Hz + * @param srcClock_Hz FTM counter clock in Hz + * + * @return kStatus_Success if the PWM setup was successful + * kStatus_Error on failure + */ +status_t FTM_SetupPwm(FTM_Type *base, + const ftm_chnl_pwm_signal_param_t *chnlParams, + uint8_t numOfChnls, + ftm_pwm_mode_t mode, + uint32_t pwmFreq_Hz, + uint32_t srcClock_Hz); + +/*! + * @brief Updates the duty cycle of an active PWM signal. + * + * @param base FTM peripheral base address + * @param chnlNumber The channel/channel pair number. In combined mode, this represents + * the channel pair number + * @param currentPwmMode The current PWM mode set during PWM setup + * @param dutyCyclePercent New PWM pulse width; The value should be between 0 to 100 + * 0=inactive signal(0% duty cycle)... + * 100=active signal (100% duty cycle) + */ +void FTM_UpdatePwmDutycycle(FTM_Type *base, + ftm_chnl_t chnlNumber, + ftm_pwm_mode_t currentPwmMode, + uint8_t dutyCyclePercent); + +/*! + * @brief Updates the edge level selection for a channel. + * + * @param base FTM peripheral base address + * @param chnlNumber The channel number + * @param level The level to be set to the ELSnB:ELSnA field; Valid values are 00, 01, 10, 11. + * See the Kinetis SoC reference manual for details about this field. + */ +void FTM_UpdateChnlEdgeLevelSelect(FTM_Type *base, ftm_chnl_t chnlNumber, uint8_t level); + +/*! + * @brief Enables capturing an input signal on the channel using the function parameters. + * + * When the edge specified in the captureMode argument occurs on the channel, the FTM counter is + * captured into the CnV register. The user has to read the CnV register separately to get this + * value. The filter function is disabled if the filterVal argument passed in is 0. The filter + * function is available only for channels 0, 1, 2, 3. + * + * @param base FTM peripheral base address + * @param chnlNumber The channel number + * @param captureMode Specifies which edge to capture + * @param filterValue Filter value, specify 0 to disable filter. Available only for channels 0-3. + */ +void FTM_SetupInputCapture(FTM_Type *base, + ftm_chnl_t chnlNumber, + ftm_input_capture_edge_t captureMode, + uint32_t filterValue); + +/*! + * @brief Configures the FTM to generate timed pulses. + * + * When the FTM 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. + * + * @param base FTM peripheral base address + * @param chnlNumber The channel number + * @param compareMode Action to take on the channel output when the compare condition is met + * @param compareValue Value to be programmed in the CnV register. + */ +void FTM_SetupOutputCompare(FTM_Type *base, + ftm_chnl_t chnlNumber, + ftm_output_compare_mode_t compareMode, + uint32_t compareValue); + +/*! + * @brief Configures the dual edge capture mode of the FTM. + * + * This function sets up the dual edge capture mode on a channel pair. The capture edge for the + * channel pair and the capture mode (one-shot or continuous) is specified in the parameter + * argument. The filter function is disabled if the filterVal argument passed is zero. The filter + * function is available only on channels 0 and 2. The user has to read the channel CnV registers + * separately to get the capture values. + * + * @param base FTM peripheral base address + * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 + * @param edgeParam Sets up the dual edge capture function + * @param filterValue Filter value, specify 0 to disable filter. Available only for channel pair 0 and 1. + */ +void FTM_SetupDualEdgeCapture(FTM_Type *base, + ftm_chnl_t chnlPairNumber, + const ftm_dual_edge_capture_param_t *edgeParam, + uint32_t filterValue); + +/*! @}*/ + +/*! + * @brief Sets up the working of the FTM fault protection. + * + * FTM can have up to 4 fault inputs. This function sets up fault parameters, fault level, and a filter. + * + * @param base FTM peripheral base address + * @param faultNumber FTM fault to configure. + * @param faultParams Parameters passed in to set up the fault + */ +void FTM_SetupFault(FTM_Type *base, ftm_fault_input_t faultNumber, const ftm_fault_param_t *faultParams); + +/*! + * @name Interrupt Interface + * @{ + */ + +/*! + * @brief Enables the selected FTM interrupts. + * + * @param base FTM peripheral base address + * @param mask The interrupts to enable. This is a logical OR of members of the + * enumeration ::ftm_interrupt_enable_t + */ +void FTM_EnableInterrupts(FTM_Type *base, uint32_t mask); + +/*! + * @brief Disables the selected FTM interrupts. + * + * @param base FTM peripheral base address + * @param mask The interrupts to enable. This is a logical OR of members of the + * enumeration ::ftm_interrupt_enable_t + */ +void FTM_DisableInterrupts(FTM_Type *base, uint32_t mask); + +/*! + * @brief Gets the enabled FTM interrupts. + * + * @param base FTM peripheral base address + * + * @return The enabled interrupts. This is the logical OR of members of the + * enumeration ::ftm_interrupt_enable_t + */ +uint32_t FTM_GetEnabledInterrupts(FTM_Type *base); + +/*! @}*/ + +/*! + * @name Status Interface + * @{ + */ + +/*! + * @brief Gets the FTM status flags. + * + * @param base FTM peripheral base address + * + * @return The status flags. This is the logical OR of members of the + * enumeration ::ftm_status_flags_t + */ +uint32_t FTM_GetStatusFlags(FTM_Type *base); + +/*! + * @brief Clears the FTM status flags. + * + * @param base FTM peripheral base address + * @param mask The status flags to clear. This is a logical OR of members of the + * enumeration ::ftm_status_flags_t + */ +void FTM_ClearStatusFlags(FTM_Type *base, uint32_t mask); + +/*! @}*/ + +/*! + * @name Read and write the timer period + * @{ + */ + +/*! + * @brief Sets the timer period in units of ticks. + * + * 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 FTM module as a timer. Do not mix usage + * of this API with FTM's PWM setup API's. + * 2. Call the utility macros provided in the fsl_common.h to convert usec or msec to ticks. + * + * @param base FTM peripheral base address + * @param ticks A timer period in units of ticks, which should be equal or greater than 1. + */ +static inline void FTM_SetTimerPeriod(FTM_Type *base, uint32_t ticks) +{ + base->MOD = ticks; +} + +/*! + * @brief Reads the current timer counting value. + * + * 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. + * + * @param base FTM peripheral base address + * + * @return The current counter value in ticks + */ +static inline uint32_t FTM_GetCurrentTimerCount(FTM_Type *base) +{ + return (uint32_t)((base->CNT & FTM_CNT_COUNT_MASK) >> FTM_CNT_COUNT_SHIFT); +} + +/*! @}*/ +/*! + * @name Timer Start and Stop + * @{ + */ + +/*! + * @brief Starts the FTM counter. + * + * @param base FTM peripheral base address + * @param clockSource FTM clock source; After the clock source is set, the counter starts running. + */ +static inline void FTM_StartTimer(FTM_Type *base, ftm_clock_source_t clockSource) +{ + uint32_t reg = base->SC; + + reg &= ~(FTM_SC_CLKS_MASK); + reg |= FTM_SC_CLKS(clockSource); + base->SC = reg; +} + +/*! + * @brief Stops the FTM counter. + * + * @param base FTM peripheral base address + */ +static inline void FTM_StopTimer(FTM_Type *base) +{ + /* Set clock source to none to disable counter */ + base->SC &= ~(FTM_SC_CLKS_MASK); +} + +/*! @}*/ + +/*! + * @name Software output control + * @{ + */ + +/*! + * @brief Enables or disables the channel software output control. + * + * @param base FTM peripheral base address + * @param chnlNumber Channel to be enabled or disabled + * @param value true: channel output is affected by software output control + false: channel output is unaffected by software output control + */ +static inline void FTM_SetSoftwareCtrlEnable(FTM_Type *base, ftm_chnl_t chnlNumber, bool value) +{ + if (value) + { + base->SWOCTRL |= (1U << chnlNumber); + } + else + { + base->SWOCTRL &= ~(1U << chnlNumber); + } +} + +/*! + * @brief Sets the channel software output control value. + * + * @param base FTM peripheral base address. + * @param chnlNumber Channel to be configured + * @param value true to set 1, false to set 0 + */ +static inline void FTM_SetSoftwareCtrlVal(FTM_Type *base, ftm_chnl_t chnlNumber, bool value) +{ + if (value) + { + base->SWOCTRL |= (1U << (chnlNumber + FTM_SWOCTRL_CH0OCV_SHIFT)); + } + else + { + base->SWOCTRL &= ~(1U << (chnlNumber + FTM_SWOCTRL_CH0OCV_SHIFT)); + } +} + +/*! @}*/ + +/*! + * @brief Enables or disables the FTM global time base signal generation to other FTMs. + * + * @param base FTM peripheral base address + * @param enable true to enable, false to disable + */ +static inline void FTM_SetGlobalTimeBaseOutputEnable(FTM_Type *base, bool enable) +{ + if (enable) + { + base->CONF |= FTM_CONF_GTBEOUT_MASK; + } + else + { + base->CONF &= ~FTM_CONF_GTBEOUT_MASK; + } +} + +/*! + * @brief Sets the FTM peripheral timer channel output mask. + * + * @param base FTM peripheral base address + * @param chnlNumber Channel to be configured + * @param mask true: masked, channel is forced to its inactive state; false: unmasked + */ +static inline void FTM_SetOutputMask(FTM_Type *base, ftm_chnl_t chnlNumber, bool mask) +{ + if (mask) + { + base->OUTMASK |= (1U << chnlNumber); + } + else + { + base->OUTMASK &= ~(1U << chnlNumber); + } +} + +#if defined(FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) && (FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) +/*! + * @brief Allows users to enable an output on an FTM channel. + * + * To enable the PWM channel output call this function with val=true. For input mode, + * call this function with val=false. + * + * @param base FTM peripheral base address + * @param chnlNumber Channel to be configured + * @param value true: enable output; false: output is disabled, used in input mode + */ +static inline void FTM_SetPwmOutputEnable(FTM_Type *base, ftm_chnl_t chnlNumber, bool value) +{ + if (value) + { + base->SC |= (1U << (chnlNumber + FTM_SC_PWMEN0_SHIFT)); + } + else + { + base->SC &= ~(1U << (chnlNumber + FTM_SC_PWMEN0_SHIFT)); + } +} +#endif + +/*! + * @name Channel pair operations + * @{ + */ + +/*! + * @brief This function enables/disables the fault control in a channel pair. + * + * @param base FTM peripheral base address + * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 + * @param value true: Enable fault control for this channel pair; false: No fault control + */ +static inline void FTM_SetFaultControlEnable(FTM_Type *base, ftm_chnl_t chnlPairNumber, bool value) +{ + if (value) + { + base->COMBINE |= (1U << (FTM_COMBINE_FAULTEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); + } + else + { + base->COMBINE &= ~(1U << (FTM_COMBINE_FAULTEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); + } +} + +/*! + * @brief This function enables/disables the dead time insertion in a channel pair. + * + * @param base FTM peripheral base address + * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 + * @param value true: Insert dead time in this channel pair; false: No dead time inserted + */ +static inline void FTM_SetDeadTimeEnable(FTM_Type *base, ftm_chnl_t chnlPairNumber, bool value) +{ + if (value) + { + base->COMBINE |= (1U << (FTM_COMBINE_DTEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); + } + else + { + base->COMBINE &= ~(1U << (FTM_COMBINE_DTEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); + } +} + +/*! + * @brief This function enables/disables complementary mode in a channel pair. + * + * @param base FTM peripheral base address + * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 + * @param value true: enable complementary mode; false: disable complementary mode + */ +static inline void FTM_SetComplementaryEnable(FTM_Type *base, ftm_chnl_t chnlPairNumber, bool value) +{ + if (value) + { + base->COMBINE |= (1U << (FTM_COMBINE_COMP0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); + } + else + { + base->COMBINE &= ~(1U << (FTM_COMBINE_COMP0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); + } +} + +/*! + * @brief This function enables/disables inverting control in a channel pair. + * + * @param base FTM peripheral base address + * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 + * @param value true: enable inverting; false: disable inverting + */ +static inline void FTM_SetInvertEnable(FTM_Type *base, ftm_chnl_t chnlPairNumber, bool value) +{ + if (value) + { + base->INVCTRL |= (1U << chnlPairNumber); + } + else + { + base->INVCTRL &= ~(1U << chnlPairNumber); + } +} + +/*! @}*/ + +/*! + * @name Quad Decoder + * @{ + */ + +/*! + * @brief Configures the parameters and activates the quadrature decoder mode. + * + * @param base FTM peripheral base address + * @param phaseAParams Phase A configuration parameters + * @param phaseBParams Phase B configuration parameters + * @param quadMode Selects encoding mode used in quadrature decoder mode + */ +void FTM_SetupQuadDecode(FTM_Type *base, + const ftm_phase_params_t *phaseAParams, + const ftm_phase_params_t *phaseBParams, + ftm_quad_decode_mode_t quadMode); + +/*! + * @brief Gets the FTM Quad Decoder flags. + * + * @param base FTM peripheral base address. + * @return Flag mask of FTM Quad Decoder, see #_ftm_quad_decoder_flags. + */ +static inline uint32_t FTM_GetQuadDecoderFlags(FTM_Type *base) +{ + return base->QDCTRL & (FTM_QDCTRL_QUADIR_MASK | FTM_QDCTRL_TOFDIR_MASK); +} + +/*! + * @brief Sets the modulo values for Quad Decoder. + * + * The modulo values configure the minimum and maximum values that the Quad decoder counter can reach. After the counter goes + * over, the counter value goes to the other side and decrease/increase again. + * + * @param base FTM peripheral base address. + * @param startValue The low limit value for Quad Decoder counter. + * @param overValue The high limit value for Quad Decoder counter. + */ +static inline void FTM_SetQuadDecoderModuloValue(FTM_Type *base, uint32_t startValue, uint32_t overValue) +{ + base->CNTIN = startValue; + base->MOD = overValue; +} + +/*! + * @brief Gets the current Quad Decoder counter value. + * + * @param base FTM peripheral base address. + * @return Current quad Decoder counter value. + */ +static inline uint32_t FTM_GetQuadDecoderCounterValue(FTM_Type *base) +{ + return base->CNT; +} + +/*! + * @brief Clears the current Quad Decoder counter value. + * + * The counter is set as the initial value. + * + * @param base FTM peripheral base address. + */ +static inline void FTM_ClearQuadDecoderCounterValue(FTM_Type *base) +{ + base->CNT = base->CNTIN; +} + +/*! @}*/ + +/*! + * @brief Enables or disables the FTM software trigger for PWM synchronization. + * + * @param base FTM peripheral base address + * @param enable true: software trigger is selected, false: software trigger is not selected + */ +static inline void FTM_SetSoftwareTrigger(FTM_Type *base, bool enable) +{ + if (enable) + { + base->SYNC |= FTM_SYNC_SWSYNC_MASK; + } + else + { + base->SYNC &= ~FTM_SYNC_SWSYNC_MASK; + } +} + +/*! + * @brief Enables or disables the FTM write protection. + * + * @param base FTM peripheral base address + * @param enable true: Write-protection is enabled, false: Write-protection is disabled + */ +static inline void FTM_SetWriteProtection(FTM_Type *base, bool enable) +{ + /* Configure write protection */ + if (enable) + { + base->FMS |= FTM_FMS_WPEN_MASK; + } + else + { + base->MODE |= FTM_MODE_WPDIS_MASK; + } +} + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_FTM_H_*/ diff --git a/drivers/include/fsl_gpio.h b/drivers/include/fsl_gpio.h new file mode 100644 index 0000000..410e2b8 --- /dev/null +++ b/drivers/include/fsl_gpio.h @@ -0,0 +1,440 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_GPIO_H_ +#define _FSL_GPIO_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup gpio + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief GPIO driver version 2.1.1. */ +#define FSL_GPIO_DRIVER_VERSION (MAKE_VERSION(2, 1, 1)) +/*@}*/ + +/*! @brief GPIO direction definition */ +typedef enum _gpio_pin_direction +{ + kGPIO_DigitalInput = 0U, /*!< Set current pin as digital input*/ + kGPIO_DigitalOutput = 1U, /*!< Set current pin as digital output*/ +} gpio_pin_direction_t; + +#if defined(FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER) && FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER +/*! @brief GPIO checker attribute */ +typedef enum _gpio_checker_attribute +{ + kGPIO_UsernonsecureRWUsersecureRWPrivilegedsecureRW = + 0x00U, /*!< User nonsecure:Read+Write; User Secure:Read+Write; Privileged Secure:Read+Write */ + kGPIO_UsernonsecureRUsersecureRWPrivilegedsecureRW = + 0x01U, /*!< User nonsecure:Read; User Secure:Read+Write; Privileged Secure:Read+Write */ + kGPIO_UsernonsecureNUsersecureRWPrivilegedsecureRW = + 0x02U, /*!< User nonsecure:None; User Secure:Read+Write; Privileged Secure:Read+Write */ + kGPIO_UsernonsecureRUsersecureRPrivilegedsecureRW = + 0x03U, /*!< User nonsecure:Read; User Secure:Read; Privileged Secure:Read+Write */ + kGPIO_UsernonsecureNUsersecureRPrivilegedsecureRW = + 0x04U, /*!< User nonsecure:None; User Secure:Read; Privileged Secure:Read+Write */ + kGPIO_UsernonsecureNUsersecureNPrivilegedsecureRW = + 0x05U, /*!< User nonsecure:None; User Secure:None; Privileged Secure:Read+Write */ + kGPIO_UsernonsecureNUsersecureNPrivilegedsecureR = + 0x06U, /*!< User nonsecure:None; User Secure:None; Privileged Secure:Read */ + kGPIO_UsernonsecureNUsersecureNPrivilegedsecureN = + 0x07U, /*!< User nonsecure:None; User Secure:None; Privileged Secure:None */ + kGPIO_IgnoreAttributeCheck = 0x10U, /*!< Ignores the attribute check */ +} gpio_checker_attribute_t; +#endif + +/*! + * @brief The GPIO pin configuration structure. + * + * 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(). + */ +typedef struct _gpio_pin_config +{ + gpio_pin_direction_t pinDirection; /*!< GPIO direction, input or output */ + /* Output configurations; ignore if configured as an input pin */ + uint8_t outputLogic; /*!< Set a default output logic, which has no use in input */ +} gpio_pin_config_t; + +/*! @} */ + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @addtogroup gpio_driver + * @{ + */ + +/*! @name GPIO Configuration */ +/*@{*/ + +/*! + * @brief Initializes a GPIO pin used by the board. + * + * 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. + * @code + * // Define a digital input pin configuration, + * gpio_pin_config_t config = + * { + * kGPIO_DigitalInput, + * 0, + * } + * //Define a digital output pin configuration, + * gpio_pin_config_t config = + * { + * kGPIO_DigitalOutput, + * 0, + * } + * @endcode + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @param pin GPIO port pin number + * @param config GPIO pin configuration pointer + */ +void GPIO_PinInit(GPIO_Type *base, uint32_t pin, const gpio_pin_config_t *config); + +/*@}*/ + +/*! @name GPIO Output Operations */ +/*@{*/ + +/*! + * @brief Sets the output level of the multiple GPIO pins to the logic 1 or 0. + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @param pin GPIO pin number + * @param output GPIO pin output logic level. + * - 0: corresponding pin output low-logic level. + * - 1: corresponding pin output high-logic level. + */ +static inline void GPIO_WritePinOutput(GPIO_Type *base, uint32_t pin, uint8_t output) +{ + if (output == 0U) + { + base->PCOR = 1U << pin; + } + else + { + base->PSOR = 1U << pin; + } +} + +/*! + * @brief Sets the output level of the multiple GPIO pins to the logic 1. + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @param mask GPIO pin number macro + */ +static inline void GPIO_SetPinsOutput(GPIO_Type *base, uint32_t mask) +{ + base->PSOR = mask; +} + +/*! + * @brief Sets the output level of the multiple GPIO pins to the logic 0. + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @param mask GPIO pin number macro + */ +static inline void GPIO_ClearPinsOutput(GPIO_Type *base, uint32_t mask) +{ + base->PCOR = mask; +} + +/*! + * @brief Reverses the current output logic of the multiple GPIO pins. + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @param mask GPIO pin number macro + */ +static inline void GPIO_TogglePinsOutput(GPIO_Type *base, uint32_t mask) +{ + base->PTOR = mask; +} +/*@}*/ + +/*! @name GPIO Input Operations */ +/*@{*/ + +/*! + * @brief Reads the current input value of the GPIO port. + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @param pin GPIO pin number + * @retval GPIO port input value + * - 0: corresponding pin input low-logic level. + * - 1: corresponding pin input high-logic level. + */ +static inline uint32_t GPIO_ReadPinInput(GPIO_Type *base, uint32_t pin) +{ + return (((base->PDIR) >> pin) & 0x01U); +} +/*@}*/ + +/*! @name GPIO Interrupt */ +/*@{*/ + +/*! + * @brief Reads the GPIO port interrupt status flag. + * + * 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. + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @retval The current GPIO port interrupt status flag, for example, 0x00010001 means the + * pin 0 and 17 have the interrupt. + */ +uint32_t GPIO_GetPinsInterruptFlags(GPIO_Type *base); + +/*! + * @brief Clears multiple GPIO pin interrupt status flags. + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @param mask GPIO pin number macro + */ +void GPIO_ClearPinsInterruptFlags(GPIO_Type *base, uint32_t mask); + +#if defined(FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER) && FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER +/*! + * @brief The GPIO module supports a device-specific number of data ports, organized as 32-bit + * words. Each 32-bit data port includes a GACR register, which defines the byte-level + * attributes required for a successful access to the GPIO programming model. The attribute controls for the 4 data + * bytes in the GACR follow a standard little endian + * data convention. + * + * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) + * @param mask GPIO pin number macro + */ +void GPIO_CheckAttributeBytes(GPIO_Type *base, gpio_checker_attribute_t attribute); +#endif + +/*@}*/ +/*! @} */ + +/*! + * @addtogroup fgpio_driver + * @{ + */ + +/* + * Introduces the FGPIO feature. + * + * The FGPIO features are only support on some Kinetis MCUs. The FGPIO registers are aliased to the IOPORT + * interface. Accesses via the IOPORT interface occur in parallel with any instruction fetches and + * complete in a single cycle. This aliased Fast GPIO memory map is called FGPIO. + */ + +#if defined(FSL_FEATURE_SOC_FGPIO_COUNT) && FSL_FEATURE_SOC_FGPIO_COUNT + +/*! @name FGPIO Configuration */ +/*@{*/ + +/*! + * @brief Initializes a FGPIO pin used by the board. + * + * 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: + * @code + * // Define a digital input pin configuration, + * gpio_pin_config_t config = + * { + * kGPIO_DigitalInput, + * 0, + * } + * //Define a digital output pin configuration, + * gpio_pin_config_t config = + * { + * kGPIO_DigitalOutput, + * 0, + * } + * @endcode + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @param pin FGPIO port pin number + * @param config FGPIO pin configuration pointer + */ +void FGPIO_PinInit(FGPIO_Type *base, uint32_t pin, const gpio_pin_config_t *config); + +/*@}*/ + +/*! @name FGPIO Output Operations */ +/*@{*/ + +/*! + * @brief Sets the output level of the multiple FGPIO pins to the logic 1 or 0. + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @param pin FGPIO pin number + * @param output FGPIOpin output logic level. + * - 0: corresponding pin output low-logic level. + * - 1: corresponding pin output high-logic level. + */ +static inline void FGPIO_WritePinOutput(FGPIO_Type *base, uint32_t pin, uint8_t output) +{ + if (output == 0U) + { + base->PCOR = 1 << pin; + } + else + { + base->PSOR = 1 << pin; + } +} + +/*! + * @brief Sets the output level of the multiple FGPIO pins to the logic 1. + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @param mask FGPIO pin number macro + */ +static inline void FGPIO_SetPinsOutput(FGPIO_Type *base, uint32_t mask) +{ + base->PSOR = mask; +} + +/*! + * @brief Sets the output level of the multiple FGPIO pins to the logic 0. + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @param mask FGPIO pin number macro + */ +static inline void FGPIO_ClearPinsOutput(FGPIO_Type *base, uint32_t mask) +{ + base->PCOR = mask; +} + +/*! + * @brief Reverses the current output logic of the multiple FGPIO pins. + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @param mask FGPIO pin number macro + */ +static inline void FGPIO_TogglePinsOutput(FGPIO_Type *base, uint32_t mask) +{ + base->PTOR = mask; +} +/*@}*/ + +/*! @name FGPIO Input Operations */ +/*@{*/ + +/*! + * @brief Reads the current input value of the FGPIO port. + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @param pin FGPIO pin number + * @retval FGPIO port input value + * - 0: corresponding pin input low-logic level. + * - 1: corresponding pin input high-logic level. + */ +static inline uint32_t FGPIO_ReadPinInput(FGPIO_Type *base, uint32_t pin) +{ + return (((base->PDIR) >> pin) & 0x01U); +} +/*@}*/ + +/*! @name FGPIO Interrupt */ +/*@{*/ + +/*! + * @brief Reads the FGPIO port interrupt status flag. + * + * 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. + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @retval The current FGPIO port interrupt status flags, for example, 0x00010001 means the + * pin 0 and 17 have the interrupt. + */ +uint32_t FGPIO_GetPinsInterruptFlags(FGPIO_Type *base); + +/*! + * @brief Clears the multiple FGPIO pin interrupt status flag. + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @param mask FGPIO pin number macro + */ +void FGPIO_ClearPinsInterruptFlags(FGPIO_Type *base, uint32_t mask); + +#if defined(FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER) && FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER +/*! + * @brief The FGPIO module supports a device-specific number of data ports, organized as 32-bit + * words. Each 32-bit data port includes a GACR register, which defines the byte-level + * attributes required for a successful access to the GPIO programming model. The attribute controls for the 4 data + * bytes in the GACR follow a standard little endian + * data convention. + * + * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) + * @param mask FGPIO pin number macro + */ +void FGPIO_CheckAttributeBytes(FGPIO_Type *base, gpio_checker_attribute_t attribute); +#endif + +/*@}*/ + +#endif /* FSL_FEATURE_SOC_FGPIO_COUNT */ + +#if defined(__cplusplus) +} +#endif + +/*! + * @} + */ + +#endif /* _FSL_GPIO_H_*/ diff --git a/drivers/include/fsl_i2c.h b/drivers/include/fsl_i2c.h new file mode 100644 index 0000000..d55fd1d --- /dev/null +++ b/drivers/include/fsl_i2c.h @@ -0,0 +1,794 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_I2C_H_ +#define _FSL_I2C_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup i2c_driver + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief I2C driver version 2.0.3. */ +#define FSL_I2C_DRIVER_VERSION (MAKE_VERSION(2, 0, 3)) +/*@}*/ + +#if (defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT || \ + defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT) +#define I2C_HAS_STOP_DETECT +#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT / FSL_FEATURE_I2C_HAS_STOP_DETECT */ + +/*! @brief I2C status return codes. */ +enum _i2c_status +{ + kStatus_I2C_Busy = MAKE_STATUS(kStatusGroup_I2C, 0), /*!< I2C is busy with current transfer. */ + kStatus_I2C_Idle = MAKE_STATUS(kStatusGroup_I2C, 1), /*!< Bus is Idle. */ + kStatus_I2C_Nak = MAKE_STATUS(kStatusGroup_I2C, 2), /*!< NAK received during transfer. */ + kStatus_I2C_ArbitrationLost = MAKE_STATUS(kStatusGroup_I2C, 3), /*!< Arbitration lost during transfer. */ + kStatus_I2C_Timeout = MAKE_STATUS(kStatusGroup_I2C, 4), /*!< Wait event timeout. */ + kStatus_I2C_Addr_Nak = MAKE_STATUS(kStatusGroup_I2C, 5), /*!< NAK received during the address probe. */ +}; + +/*! + * @brief I2C peripheral flags + * + * The following status register flags can be cleared: + * - #kI2C_ArbitrationLostFlag + * - #kI2C_IntPendingFlag + * - #kI2C_StartDetectFlag + * - #kI2C_StopDetectFlag + * + * @note These enumerations are meant to be OR'd together to form a bit mask. + * + */ +enum _i2c_flags +{ + kI2C_ReceiveNakFlag = I2C_S_RXAK_MASK, /*!< I2C receive NAK flag. */ + kI2C_IntPendingFlag = I2C_S_IICIF_MASK, /*!< I2C interrupt pending flag. */ + kI2C_TransferDirectionFlag = I2C_S_SRW_MASK, /*!< I2C transfer direction flag. */ + kI2C_RangeAddressMatchFlag = I2C_S_RAM_MASK, /*!< I2C range address match flag. */ + kI2C_ArbitrationLostFlag = I2C_S_ARBL_MASK, /*!< I2C arbitration lost flag. */ + kI2C_BusBusyFlag = I2C_S_BUSY_MASK, /*!< I2C bus busy flag. */ + kI2C_AddressMatchFlag = I2C_S_IAAS_MASK, /*!< I2C address match flag. */ + kI2C_TransferCompleteFlag = I2C_S_TCF_MASK, /*!< I2C transfer complete flag. */ +#ifdef I2C_HAS_STOP_DETECT + kI2C_StopDetectFlag = I2C_FLT_STOPF_MASK << 8, /*!< I2C stop detect flag. */ +#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT / FSL_FEATURE_I2C_HAS_STOP_DETECT */ + +#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT + kI2C_StartDetectFlag = I2C_FLT_STARTF_MASK << 8, /*!< I2C start detect flag. */ +#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ +}; + +/*! @brief I2C feature interrupt source. */ +enum _i2c_interrupt_enable +{ + kI2C_GlobalInterruptEnable = I2C_C1_IICIE_MASK, /*!< I2C global interrupt. */ + +#if defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT + kI2C_StopDetectInterruptEnable = I2C_FLT_STOPIE_MASK, /*!< I2C stop detect interrupt. */ +#endif /* FSL_FEATURE_I2C_HAS_STOP_DETECT */ + +#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT + kI2C_StartStopDetectInterruptEnable = I2C_FLT_SSIE_MASK, /*!< I2C start&stop detect interrupt. */ +#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ +}; + +/*! @brief The direction of master and slave transfers. */ +typedef enum _i2c_direction +{ + kI2C_Write = 0x0U, /*!< Master transmits to the slave. */ + kI2C_Read = 0x1U, /*!< Master receives from the slave. */ +} i2c_direction_t; + +/*! @brief Addressing mode. */ +typedef enum _i2c_slave_address_mode +{ + kI2C_Address7bit = 0x0U, /*!< 7-bit addressing mode. */ + kI2C_RangeMatch = 0X2U, /*!< Range address match addressing mode. */ +} i2c_slave_address_mode_t; + +/*! @brief I2C transfer control flag. */ +enum _i2c_master_transfer_flags +{ + kI2C_TransferDefaultFlag = 0x0U, /*!< A transfer starts with a start signal, stops with a stop signal. */ + kI2C_TransferNoStartFlag = 0x1U, /*!< A transfer starts without a start signal. */ + kI2C_TransferRepeatedStartFlag = 0x2U, /*!< A transfer starts with a repeated start signal. */ + kI2C_TransferNoStopFlag = 0x4U, /*!< A transfer ends without a stop signal. */ +}; + +/*! + * @brief Set of events sent to the callback for nonblocking slave transfers. + * + * 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 @a transfer + * parameter. + * + * @note These enumerations are meant to be OR'd together to form a bit mask of events. + */ +typedef enum _i2c_slave_transfer_event +{ + kI2C_SlaveAddressMatchEvent = 0x01U, /*!< Received the slave address after a start or repeated start. */ + kI2C_SlaveTransmitEvent = 0x02U, /*!< A callback is requested to provide data to transmit + (slave-transmitter role). */ + kI2C_SlaveReceiveEvent = 0x04U, /*!< A callback is requested to provide a buffer in which to place received + data (slave-receiver role). */ + kI2C_SlaveTransmitAckEvent = 0x08U, /*!< A callback needs to either transmit an ACK or NACK. */ +#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT + kI2C_SlaveStartEvent = 0x10U, /*!< A start/repeated start was detected. */ +#endif + kI2C_SlaveCompletionEvent = 0x20U, /*!< A stop was detected or finished transfer, completing the transfer. */ + kI2C_SlaveGenaralcallEvent = 0x40U, /*!< Received the general call address after a start or repeated start. */ + + /*! A bit mask of all available events. */ + kI2C_SlaveAllEvents = kI2C_SlaveAddressMatchEvent | kI2C_SlaveTransmitEvent | kI2C_SlaveReceiveEvent | +#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT + kI2C_SlaveStartEvent | +#endif + kI2C_SlaveCompletionEvent | kI2C_SlaveGenaralcallEvent, +} i2c_slave_transfer_event_t; + +/*! @brief I2C master user configuration. */ +typedef struct _i2c_master_config +{ + bool enableMaster; /*!< Enables the I2C peripheral at initialization time. */ +#if defined(FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF) && FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF + bool enableStopHold; /*!< Controls the stop hold enable. */ +#endif +#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE + bool enableDoubleBuffering; /*!< Controls double buffer enable; notice that + enabling the double buffer disables the clock stretch. */ +#endif + uint32_t baudRate_Bps; /*!< Baud rate configuration of I2C peripheral. */ + uint8_t glitchFilterWidth; /*!< Controls the width of the glitch. */ +} i2c_master_config_t; + +/*! @brief I2C slave user configuration. */ +typedef struct _i2c_slave_config +{ + 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. */ +#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE + bool enableDoubleBuffering; /*!< Controls a double buffer enable; notice that + enabling the double buffer disables the clock stretch. */ +#endif + 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. */ +} i2c_slave_config_t; + +/*! @brief I2C master handle typedef. */ +typedef struct _i2c_master_handle i2c_master_handle_t; + +/*! @brief I2C master transfer callback typedef. */ +typedef void (*i2c_master_transfer_callback_t)(I2C_Type *base, + i2c_master_handle_t *handle, + status_t status, + void *userData); + +/*! @brief I2C slave handle typedef. */ +typedef struct _i2c_slave_handle i2c_slave_handle_t; + +/*! @brief I2C master transfer structure. */ +typedef struct _i2c_master_transfer +{ + 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. Transferred MSB first. */ + uint8_t subaddressSize; /*!< A size of the command buffer. */ + uint8_t *volatile data; /*!< A transfer buffer. */ + volatile size_t dataSize; /*!< A transfer size. */ +} i2c_master_transfer_t; + +/*! @brief I2C master handle structure. */ +struct _i2c_master_handle +{ + 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. */ +}; + +/*! @brief I2C slave transfer structure. */ +typedef struct _i2c_slave_transfer +{ + 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. Only applies for + #kI2C_SlaveCompletionEvent. */ + size_t transferredCount; /*!< A number of bytes actually transferred since the start or since the last repeated + start. */ +} i2c_slave_transfer_t; + +/*! @brief I2C slave transfer callback typedef. */ +typedef void (*i2c_slave_transfer_callback_t)(I2C_Type *base, i2c_slave_transfer_t *xfer, void *userData); + +/*! @brief I2C slave handle structure. */ +struct _i2c_slave_handle +{ + 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. */ +}; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /*_cplusplus. */ + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Initializes the I2C peripheral. 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. + * @code + * i2c_master_config_t config = { + * .enableMaster = true, + * .enableStopHold = false, + * .highDrive = false, + * .baudRate_Bps = 100000, + * .glitchFilterWidth = 0 + * }; + * I2C_MasterInit(I2C0, &config, 12000000U); + * @endcode + * + * @param base I2C base pointer + * @param masterConfig A pointer to the master configuration structure + * @param srcClock_Hz I2C peripheral clock frequency in Hz + */ +void I2C_MasterInit(I2C_Type *base, const i2c_master_config_t *masterConfig, uint32_t srcClock_Hz); + +/*! + * @brief Initializes the I2C peripheral. 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. + * @code + * 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); + * @endcode + * + * @param base I2C base pointer + * @param slaveConfig A pointer to the slave configuration structure + * @param srcClock_Hz I2C peripheral clock frequency in Hz + */ +void I2C_SlaveInit(I2C_Type *base, const i2c_slave_config_t *slaveConfig, uint32_t srcClock_Hz); + +/*! + * @brief De-initializes the I2C master peripheral. Call this API to gate the I2C clock. + * The I2C master module can't work unless the I2C_MasterInit is called. + * @param base I2C base pointer + */ +void I2C_MasterDeinit(I2C_Type *base); + +/*! + * @brief De-initializes the I2C slave peripheral. Calling this API gates the I2C clock. + * The I2C slave module can't work unless the I2C_SlaveInit is called to enable the clock. + * @param base I2C base pointer + */ +void I2C_SlaveDeinit(I2C_Type *base); + +/*! + * @brief Sets the I2C master configuration structure to default values. + * + * The purpose of this API is to get the configuration structure initialized for use in the I2C_MasterConfigure(). + * Use the initialized structure unchanged in the I2C_MasterConfigure() or modify + * the structure before calling the I2C_MasterConfigure(). + * This is an example. + * @code + * i2c_master_config_t config; + * I2C_MasterGetDefaultConfig(&config); + * @endcode + * @param masterConfig A pointer to the master configuration structure. +*/ +void I2C_MasterGetDefaultConfig(i2c_master_config_t *masterConfig); + +/*! + * @brief Sets the I2C slave configuration structure to default values. + * + * 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. + * @code + * i2c_slave_config_t config; + * I2C_SlaveGetDefaultConfig(&config); + * @endcode + * @param slaveConfig A pointer to the slave configuration structure. + */ +void I2C_SlaveGetDefaultConfig(i2c_slave_config_t *slaveConfig); + +/*! + * @brief Enables or disabless the I2C peripheral operation. + * + * @param base I2C base pointer + * @param enable Pass true to enable and false to disable the module. + */ +static inline void I2C_Enable(I2C_Type *base, bool enable) +{ + if (enable) + { + base->C1 |= I2C_C1_IICEN_MASK; + } + else + { + base->C1 &= ~I2C_C1_IICEN_MASK; + } +} + +/* @} */ + +/*! + * @name Status + * @{ + */ + +/*! + * @brief Gets the I2C status flags. + * + * @param base I2C base pointer + * @return status flag, use status flag to AND #_i2c_flags to get the related status. + */ +uint32_t I2C_MasterGetStatusFlags(I2C_Type *base); + +/*! + * @brief Gets the I2C status flags. + * + * @param base I2C base pointer + * @return status flag, use status flag to AND #_i2c_flags to get the related status. + */ +static inline uint32_t I2C_SlaveGetStatusFlags(I2C_Type *base) +{ + return I2C_MasterGetStatusFlags(base); +} + +/*! + * @brief Clears the I2C status flag state. + * + * The following status register flags can be cleared kI2C_ArbitrationLostFlag and kI2C_IntPendingFlag. + * + * @param base I2C base pointer + * @param statusMask The status flag mask, defined in type i2c_status_flag_t. + * The parameter can be any combination of the following values: + * @arg kI2C_StartDetectFlag (if available) + * @arg kI2C_StopDetectFlag (if available) + * @arg kI2C_ArbitrationLostFlag + * @arg kI2C_IntPendingFlagFlag + */ +static inline void I2C_MasterClearStatusFlags(I2C_Type *base, uint32_t statusMask) +{ +/* Must clear the STARTF / STOPF bits prior to clearing IICIF */ +#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT + if (statusMask & kI2C_StartDetectFlag) + { + /* Shift the odd-ball flags back into place. */ + base->FLT |= (uint8_t)(statusMask >> 8U); + } +#endif + +#ifdef I2C_HAS_STOP_DETECT + if (statusMask & kI2C_StopDetectFlag) + { + /* Shift the odd-ball flags back into place. */ + base->FLT |= (uint8_t)(statusMask >> 8U); + } +#endif + + base->S = (uint8_t)statusMask; +} + +/*! + * @brief Clears the I2C status flag state. + * + * The following status register flags can be cleared kI2C_ArbitrationLostFlag and kI2C_IntPendingFlag + * + * @param base I2C base pointer + * @param statusMask The status flag mask, defined in type i2c_status_flag_t. + * The parameter can be any combination of the following values: + * @arg kI2C_StartDetectFlag (if available) + * @arg kI2C_StopDetectFlag (if available) + * @arg kI2C_ArbitrationLostFlag + * @arg kI2C_IntPendingFlagFlag + */ +static inline void I2C_SlaveClearStatusFlags(I2C_Type *base, uint32_t statusMask) +{ + I2C_MasterClearStatusFlags(base, statusMask); +} + +/* @} */ + +/*! + * @name Interrupts + * @{ + */ + +/*! + * @brief Enables I2C interrupt requests. + * + * @param base I2C base pointer + * @param mask interrupt source + * The parameter can be combination of the following source if defined: + * @arg kI2C_GlobalInterruptEnable + * @arg kI2C_StopDetectInterruptEnable/kI2C_StartDetectInterruptEnable + * @arg kI2C_SdaTimeoutInterruptEnable + */ +void I2C_EnableInterrupts(I2C_Type *base, uint32_t mask); + +/*! + * @brief Disables I2C interrupt requests. + * + * @param base I2C base pointer + * @param mask interrupt source + * The parameter can be combination of the following source if defined: + * @arg kI2C_GlobalInterruptEnable + * @arg kI2C_StopDetectInterruptEnable/kI2C_StartDetectInterruptEnable + * @arg kI2C_SdaTimeoutInterruptEnable + */ +void I2C_DisableInterrupts(I2C_Type *base, uint32_t mask); + +/*! + * @name DMA Control + * @{ + */ +#if defined(FSL_FEATURE_I2C_HAS_DMA_SUPPORT) && FSL_FEATURE_I2C_HAS_DMA_SUPPORT +/*! + * @brief Enables/disables the I2C DMA interrupt. + * + * @param base I2C base pointer + * @param enable true to enable, false to disable +*/ +static inline void I2C_EnableDMA(I2C_Type *base, bool enable) +{ + if (enable) + { + base->C1 |= I2C_C1_DMAEN_MASK; + } + else + { + base->C1 &= ~I2C_C1_DMAEN_MASK; + } +} + +#endif /* FSL_FEATURE_I2C_HAS_DMA_SUPPORT */ + +/*! + * @brief Gets the I2C tx/rx data register address. This API is used to provide a transfer address + * for I2C DMA transfer configuration. + * + * @param base I2C base pointer + * @return data register address + */ +static inline uint32_t I2C_GetDataRegAddr(I2C_Type *base) +{ + return (uint32_t)(&(base->D)); +} + +/* @} */ +/*! + * @name Bus Operations + * @{ + */ + +/*! + * @brief Sets the I2C master transfer baud rate. + * + * @param base I2C base pointer + * @param baudRate_Bps the baud rate value in bps + * @param srcClock_Hz Source clock + */ +void I2C_MasterSetBaudRate(I2C_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz); + +/*! + * @brief Sends a START on the I2C bus. + * + * 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. + * + * @param base I2C peripheral base pointer + * @param address 7-bit slave device address. + * @param direction Master transfer directions(transmit/receive). + * @retval kStatus_Success Successfully send the start signal. + * @retval kStatus_I2C_Busy Current bus is busy. + */ +status_t I2C_MasterStart(I2C_Type *base, uint8_t address, i2c_direction_t direction); + +/*! + * @brief Sends a STOP signal on the I2C bus. + * + * @retval kStatus_Success Successfully send the stop signal. + * @retval kStatus_I2C_Timeout Send stop signal failed, timeout. + */ +status_t I2C_MasterStop(I2C_Type *base); + +/*! + * @brief Sends a REPEATED START on the I2C bus. + * + * @param base I2C peripheral base pointer + * @param address 7-bit slave device address. + * @param direction Master transfer directions(transmit/receive). + * @retval kStatus_Success Successfully send the start signal. + * @retval kStatus_I2C_Busy Current bus is busy but not occupied by current I2C master. + */ +status_t I2C_MasterRepeatedStart(I2C_Type *base, uint8_t address, i2c_direction_t direction); + +/*! + * @brief Performs a polling send transaction on the I2C bus. + * + * @param base The I2C peripheral base pointer. + * @param txBuff The pointer to the data to be transferred. + * @param txSize The length in bytes of the data to be transferred. + * @param flags Transfer control flag to decide whether need to send a stop, use kI2C_TransferDefaultFlag +* to issue a stop and kI2C_TransferNoStop to not send a stop. + * @retval kStatus_Success Successfully complete the data transmission. + * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. + * @retval kStataus_I2C_Nak Transfer error, receive NAK during transfer. + */ +status_t I2C_MasterWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize, uint32_t flags); + +/*! + * @brief Performs a polling receive transaction on the I2C bus. + * + * @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. + * + * @param base I2C peripheral base pointer. + * @param rxBuff The pointer to the data to store the received data. + * @param rxSize The length in bytes of the data to be received. + * @param flags Transfer control flag to decide whether need to send a stop, use kI2C_TransferDefaultFlag +* to issue a stop and kI2C_TransferNoStop to not send a stop. + * @retval kStatus_Success Successfully complete the data transmission. + * @retval kStatus_I2C_Timeout Send stop signal failed, timeout. + */ +status_t I2C_MasterReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize, uint32_t flags); + +/*! + * @brief Performs a polling send transaction on the I2C bus. + * + * @param base The I2C peripheral base pointer. + * @param txBuff The pointer to the data to be transferred. + * @param txSize The length in bytes of the data to be transferred. + * @retval kStatus_Success Successfully complete the data transmission. + * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. + * @retval kStataus_I2C_Nak Transfer error, receive NAK during transfer. + */ +status_t I2C_SlaveWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize); + +/*! + * @brief Performs a polling receive transaction on the I2C bus. + * + * @param base I2C peripheral base pointer. + * @param rxBuff The pointer to the data to store the received data. + * @param rxSize The length in bytes of the data to be received. + */ +void I2C_SlaveReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize); + +/*! + * @brief Performs a master polling transfer on the I2C bus. + * + * @note The API does not return until the transfer succeeds or fails due + * to arbitration lost or receiving a NAK. + * + * @param base I2C peripheral base address. + * @param xfer Pointer to the transfer structure. + * @retval kStatus_Success Successfully complete the data transmission. + * @retval kStatus_I2C_Busy Previous transmission still not finished. + * @retval kStatus_I2C_Timeout Transfer error, wait signal timeout. + * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. + * @retval kStataus_I2C_Nak Transfer error, receive NAK during transfer. + */ +status_t I2C_MasterTransferBlocking(I2C_Type *base, i2c_master_transfer_t *xfer); + +/* @} */ + +/*! + * @name Transactional + * @{ + */ + +/*! + * @brief Initializes the I2C handle which is used in transactional functions. + * + * @param base I2C base pointer. + * @param handle pointer to i2c_master_handle_t structure to store the transfer state. + * @param callback pointer to user callback function. + * @param userData user parameter passed to the callback function. + */ +void I2C_MasterTransferCreateHandle(I2C_Type *base, + i2c_master_handle_t *handle, + i2c_master_transfer_callback_t callback, + void *userData); + +/*! + * @brief Performs a master interrupt non-blocking transfer on the I2C bus. + * + * @note Calling the API returns immediately after transfer initiates. The user needs + * to call I2C_MasterGetTransferCount 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. + * + * @param base I2C base pointer. + * @param handle pointer to i2c_master_handle_t structure which stores the transfer state. + * @param xfer pointer to i2c_master_transfer_t structure. + * @retval kStatus_Success Successfully start the data transmission. + * @retval kStatus_I2C_Busy Previous transmission still not finished. + * @retval kStatus_I2C_Timeout Transfer error, wait signal timeout. + */ +status_t I2C_MasterTransferNonBlocking(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer); + +/*! + * @brief Gets the master transfer status during a interrupt non-blocking transfer. + * + * @param base I2C base pointer. + * @param handle pointer to i2c_master_handle_t structure which stores the transfer state. + * @param count Number of bytes transferred so far by the non-blocking transaction. + * @retval kStatus_InvalidArgument count is Invalid. + * @retval kStatus_Success Successfully return the count. + */ +status_t I2C_MasterTransferGetCount(I2C_Type *base, i2c_master_handle_t *handle, size_t *count); + +/*! + * @brief Aborts an interrupt non-blocking transfer early. + * + * @note This API can be called at any time when an interrupt non-blocking transfer initiates + * to abort the transfer early. + * + * @param base I2C base pointer. + * @param handle pointer to i2c_master_handle_t structure which stores the transfer state + */ +void I2C_MasterTransferAbort(I2C_Type *base, i2c_master_handle_t *handle); + +/*! + * @brief Master interrupt handler. + * + * @param base I2C base pointer. + * @param i2cHandle pointer to i2c_master_handle_t structure. + */ +void I2C_MasterTransferHandleIRQ(I2C_Type *base, void *i2cHandle); + +/*! + * @brief Initializes the I2C handle which is used in transactional functions. + * + * @param base I2C base pointer. + * @param handle pointer to i2c_slave_handle_t structure to store the transfer state. + * @param callback pointer to user callback function. + * @param userData user parameter passed to the callback function. + */ +void I2C_SlaveTransferCreateHandle(I2C_Type *base, + i2c_slave_handle_t *handle, + i2c_slave_transfer_callback_t callback, + void *userData); + +/*! + * @brief Starts accepting slave transfers. + * + * 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 @a eventMask parameter to + * the OR'd combination of #i2c_slave_transfer_event_t enumerators for the events you wish to receive. + * The #kI2C_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. + * + * @param base The I2C peripheral base address. + * @param handle Pointer to #i2c_slave_handle_t structure which stores the transfer state. + * @param eventMask Bit mask formed by OR'ing together #i2c_slave_transfer_event_t enumerators to specify + * which events to send to the callback. Other accepted values are 0 to get a default set of + * only the transmit and receive events, and #kI2C_SlaveAllEvents to enable all events. + * + * @retval #kStatus_Success Slave transfers were successfully started. + * @retval #kStatus_I2C_Busy Slave transfers have already been started on this handle. + */ +status_t I2C_SlaveTransferNonBlocking(I2C_Type *base, i2c_slave_handle_t *handle, uint32_t eventMask); + +/*! + * @brief Aborts the slave transfer. + * + * @note This API can be called at any time to stop slave for handling the bus events. + * + * @param base I2C base pointer. + * @param handle pointer to i2c_slave_handle_t structure which stores the transfer state. + */ +void I2C_SlaveTransferAbort(I2C_Type *base, i2c_slave_handle_t *handle); + +/*! + * @brief Gets the slave transfer remaining bytes during a interrupt non-blocking transfer. + * + * @param base I2C base pointer. + * @param handle pointer to i2c_slave_handle_t structure. + * @param count Number of bytes transferred so far by the non-blocking transaction. + * @retval kStatus_InvalidArgument count is Invalid. + * @retval kStatus_Success Successfully return the count. + */ +status_t I2C_SlaveTransferGetCount(I2C_Type *base, i2c_slave_handle_t *handle, size_t *count); + +/*! + * @brief Slave interrupt handler. + * + * @param base I2C base pointer. + * @param i2cHandle pointer to i2c_slave_handle_t structure which stores the transfer state + */ +void I2C_SlaveTransferHandleIRQ(I2C_Type *base, void *i2cHandle); + +/* @} */ +#if defined(__cplusplus) +} +#endif /*_cplusplus. */ +/*@}*/ + +#endif /* _FSL_I2C_H_*/ diff --git a/drivers/include/fsl_i2c_edma.h b/drivers/include/fsl_i2c_edma.h new file mode 100644 index 0000000..40cb648 --- /dev/null +++ b/drivers/include/fsl_i2c_edma.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_I2C_DMA_H_ +#define _FSL_I2C_DMA_H_ + +#include "fsl_i2c.h" +#include "fsl_dmamux.h" +#include "fsl_edma.h" + +/*! + * @addtogroup i2c_edma_driver + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @brief I2C master eDMA handle typedef. */ +typedef struct _i2c_master_edma_handle i2c_master_edma_handle_t; + +/*! @brief I2C master eDMA transfer callback typedef. */ +typedef void (*i2c_master_edma_transfer_callback_t)(I2C_Type *base, + i2c_master_edma_handle_t *handle, + status_t status, + void *userData); + +/*! @brief I2C master eDMA transfer structure. */ +struct _i2c_master_edma_handle +{ + 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; /*!< I2C master transfer status. */ + edma_handle_t *dmaHandle; /*!< The eDMA handler used. */ + i2c_master_edma_transfer_callback_t + completionCallback; /*!< A callback function called after the eDMA transfer is finished. */ + void *userData; /*!< A callback parameter passed to the callback function. */ +}; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /*_cplusplus. */ + +/*! + * @name I2C Block eDMA Transfer Operation + * @{ + */ + +/*! + * @brief Initializes the I2C handle which is used in transcational functions. + * + * @param base I2C peripheral base address. + * @param handle A pointer to the i2c_master_edma_handle_t structure. + * @param callback A pointer to the user callback function. + * @param userData A user parameter passed to the callback function. + * @param edmaHandle eDMA handle pointer. + */ +void I2C_MasterCreateEDMAHandle(I2C_Type *base, + i2c_master_edma_handle_t *handle, + i2c_master_edma_transfer_callback_t callback, + void *userData, + edma_handle_t *edmaHandle); + +/*! + * @brief Performs a master eDMA non-blocking transfer on the I2C bus. + * + * @param base I2C peripheral base address. + * @param handle A pointer to the i2c_master_edma_handle_t structure. + * @param xfer A pointer to the transfer structure of i2c_master_transfer_t. + * @retval kStatus_Success Sucessfully completed the data transmission. + * @retval kStatus_I2C_Busy A previous transmission is still not finished. + * @retval kStatus_I2C_Timeout Transfer error, waits for a signal timeout. + * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. + * @retval kStataus_I2C_Nak Transfer error, receive NAK during transfer. + */ +status_t I2C_MasterTransferEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle, i2c_master_transfer_t *xfer); + +/*! + * @brief Gets a master transfer status during the eDMA non-blocking transfer. + * + * @param base I2C peripheral base address. + * @param handle A pointer to the i2c_master_edma_handle_t structure. + * @param count A number of bytes transferred by the non-blocking transaction. + */ +status_t I2C_MasterTransferGetCountEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle, size_t *count); + +/*! + * @brief Aborts a master eDMA non-blocking transfer early. + * + * @param base I2C peripheral base address. + * @param handle A pointer to the i2c_master_edma_handle_t structure. + */ +void I2C_MasterTransferAbortEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle); + +/* @} */ +#if defined(__cplusplus) +} +#endif /*_cplusplus. */ +/*@}*/ +#endif /*_FSL_I2C_DMA_H_*/ diff --git a/drivers/include/fsl_i2c_freertos.h b/drivers/include/fsl_i2c_freertos.h new file mode 100644 index 0000000..52ed2d0 --- /dev/null +++ b/drivers/include/fsl_i2c_freertos.h @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef __FSL_I2C_FREERTOS_H__ +#define __FSL_I2C_FREERTOS_H__ + +#include "FreeRTOSConfig.h" +#include "FreeRTOS.h" +#include "portable.h" +#include "semphr.h" + +#include "fsl_i2c.h" + +/*! + * @addtogroup i2c_freertos_driver I2C FreeRTOS driver + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! + * @cond RTOS_PRIVATE + * @brief I2C FreeRTOS handle + */ +typedef struct _i2c_rtos_handle +{ + I2C_Type *base; /*!< I2C base address */ + i2c_master_handle_t drv_handle; /*!< A handle of the underlying driver, treated as opaque by the RTOS layer */ + status_t async_status; /*!< Transactional state of the underlying driver */ + SemaphoreHandle_t mutex; /*!< A mutex to lock the handle during a transfer */ + SemaphoreHandle_t semaphore; /*!< A semaphore to notify and unblock task when the transfer ends */ +#if (configSUPPORT_STATIC_ALLOCATION == 1) + StaticSemaphore_t mutexBuffer; /*!< Statically allocated memory for mutex */ + StaticSemaphore_t semaphoreBuffer; /*!< Statically allocated memory for semaphore */ +#endif +} i2c_rtos_handle_t; +/*! \endcond */ + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name I2C RTOS Operation + * @{ + */ + +/*! + * @brief Initializes I2C. + * + * This function initializes the I2C module and the related RTOS context. + * + * @param handle The RTOS I2C handle, the pointer to an allocated space for RTOS context. + * @param base The pointer base address of the I2C instance to initialize. + * @param masterConfig The configuration structure to set-up I2C in master mode. + * @param srcClock_Hz The frequency of an input clock of the I2C module. + * @return status of the operation. + */ +status_t I2C_RTOS_Init(i2c_rtos_handle_t *handle, + I2C_Type *base, + const i2c_master_config_t *masterConfig, + uint32_t srcClock_Hz); + +/*! + * @brief Deinitializes the I2C. + * + * This function deinitializes the I2C module and the related RTOS context. + * + * @param handle The RTOS I2C handle. + */ +status_t I2C_RTOS_Deinit(i2c_rtos_handle_t *handle); + +/*! + * @brief Performs the I2C transfer. + * + * This function performs the I2C transfer according to the data given in the transfer structure. + * + * @param handle The RTOS I2C handle. + * @param transfer A structure specifying the transfer parameters. + * @return status of the operation. + */ +status_t I2C_RTOS_Transfer(i2c_rtos_handle_t *handle, i2c_master_transfer_t *transfer); + +/*! + * @} + */ + +#if defined(__cplusplus) +} +#endif + +/*! + * @} + */ + +#endif /* __FSL_I2C_FREERTOS_H__ */ diff --git a/drivers/include/fsl_llwu.h b/drivers/include/fsl_llwu.h new file mode 100644 index 0000000..d5a0037 --- /dev/null +++ b/drivers/include/fsl_llwu.h @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_LLWU_H_ +#define _FSL_LLWU_H_ + +#include "fsl_common.h" + +/*! @addtogroup llwu */ +/*! @{ */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief LLWU driver version 2.0.1. */ +#define FSL_LLWU_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) +/*@}*/ + +/*! + * @brief External input pin control modes + */ +typedef enum _llwu_external_pin_mode +{ + kLLWU_ExternalPinDisable = 0U, /*!< Pin disabled as a wakeup input. */ + kLLWU_ExternalPinRisingEdge = 1U, /*!< Pin enabled with the rising edge detection. */ + kLLWU_ExternalPinFallingEdge = 2U, /*!< Pin enabled with the falling edge detection.*/ + kLLWU_ExternalPinAnyEdge = 3U /*!< Pin enabled with any change detection. */ +} llwu_external_pin_mode_t; + +/*! + * @brief Digital filter control modes + */ +typedef enum _llwu_pin_filter_mode +{ + kLLWU_PinFilterDisable = 0U, /*!< Filter disabled. */ + kLLWU_PinFilterRisingEdge = 1U, /*!< Filter positive edge detection.*/ + kLLWU_PinFilterFallingEdge = 2U, /*!< Filter negative edge detection.*/ + kLLWU_PinFilterAnyEdge = 3U /*!< Filter any edge detection. */ +} llwu_pin_filter_mode_t; + +#if (defined(FSL_FEATURE_LLWU_HAS_VERID) && FSL_FEATURE_LLWU_HAS_VERID) +/*! + * @brief IP version ID definition. + */ +typedef struct _llwu_version_id +{ + uint16_t feature; /*!< A feature specification number. */ + uint8_t minor; /*!< The minor version number. */ + uint8_t major; /*!< The major version number. */ +} llwu_version_id_t; +#endif /* FSL_FEATURE_LLWU_HAS_VERID */ + +#if (defined(FSL_FEATURE_LLWU_HAS_PARAM) && FSL_FEATURE_LLWU_HAS_PARAM) +/*! + * @brief IP parameter definition. + */ +typedef struct _llwu_param +{ + uint8_t filters; /*!< A number of the pin filter. */ + uint8_t dmas; /*!< A number of the wakeup DMA. */ + uint8_t modules; /*!< A number of the wakeup module. */ + uint8_t pins; /*!< A number of the wake up pin. */ +} llwu_param_t; +#endif /* FSL_FEATURE_LLWU_HAS_PARAM */ + +#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && FSL_FEATURE_LLWU_HAS_PIN_FILTER) +/*! + * @brief An external input pin filter control structure + */ +typedef struct _llwu_external_pin_filter_mode +{ + uint32_t pinIndex; /*!< A pin number */ + llwu_pin_filter_mode_t filterMode; /*!< Filter mode */ +} llwu_external_pin_filter_mode_t; +#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Low-Leakage Wakeup Unit Control APIs + * @{ + */ + +#if (defined(FSL_FEATURE_LLWU_HAS_VERID) && FSL_FEATURE_LLWU_HAS_VERID) +/*! + * @brief Gets the LLWU version ID. + * + * This function gets the LLWU version ID, including the major version number, + * the minor version number, and the feature specification number. + * + * @param base LLWU peripheral base address. + * @param versionId A pointer to the version ID structure. + */ +static inline void LLWU_GetVersionId(LLWU_Type *base, llwu_version_id_t *versionId) +{ + *((uint32_t *)versionId) = base->VERID; +} +#endif /* FSL_FEATURE_LLWU_HAS_VERID */ + +#if (defined(FSL_FEATURE_LLWU_HAS_PARAM) && FSL_FEATURE_LLWU_HAS_PARAM) +/*! + * @brief Gets the LLWU parameter. + * + * This function gets the LLWU parameter, including a wakeup pin number, a module + * number, a DMA number, and a pin filter number. + * + * @param base LLWU peripheral base address. + * @param param A pointer to the LLWU parameter structure. + */ +static inline void LLWU_GetParam(LLWU_Type *base, llwu_param_t *param) +{ + *((uint32_t *)param) = base->PARAM; +} +#endif /* FSL_FEATURE_LLWU_HAS_PARAM */ + +#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) +/*! + * @brief Sets the external input pin source mode. + * + * This function sets the external input pin source mode that is used + * as a wake up source. + * + * @param base LLWU peripheral base address. + * @param pinIndex A pin index to be enabled as an external wakeup source starting from 1. + * @param pinMode A pin configuration mode defined in the llwu_external_pin_modes_t. + */ +void LLWU_SetExternalWakeupPinMode(LLWU_Type *base, uint32_t pinIndex, llwu_external_pin_mode_t pinMode); + +/*! + * @brief Gets the external wakeup source flag. + * + * This function checks the external pin flag to detect whether the MCU is + * woken up by the specific pin. + * + * @param base LLWU peripheral base address. + * @param pinIndex A pin index, which starts from 1. + * @return True if the specific pin is a wakeup source. + */ +bool LLWU_GetExternalWakeupPinFlag(LLWU_Type *base, uint32_t pinIndex); + +/*! + * @brief Clears the external wakeup source flag. + * + * This function clears the external wakeup source flag for a specific pin. + * + * @param base LLWU peripheral base address. + * @param pinIndex A pin index, which starts from 1. + */ +void LLWU_ClearExternalWakeupPinFlag(LLWU_Type *base, uint32_t pinIndex); +#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ + +#if (defined(FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE) && FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE) +/*! + * @brief Enables/disables the internal module source. + * + * This function enables/disables the internal module source mode that is used + * as a wake up source. + * + * @param base LLWU peripheral base address. + * @param moduleIndex A module index to be enabled as an internal wakeup source starting from 1. + * @param enable An enable or a disable setting + */ +static inline void LLWU_EnableInternalModuleInterruptWakup(LLWU_Type *base, uint32_t moduleIndex, bool enable) +{ + if (enable) + { + base->ME |= 1U << moduleIndex; + } + else + { + base->ME &= ~(1U << moduleIndex); + } +} + +/*! + * @brief Gets the external wakeup source flag. + * + * This function checks the external pin flag to detect whether the system is + * woken up by the specific pin. + * + * @param base LLWU peripheral base address. + * @param moduleIndex A module index, which starts from 1. + * @return True if the specific pin is a wake up source. + */ +static inline bool LLWU_GetInternalWakeupModuleFlag(LLWU_Type *base, uint32_t moduleIndex) +{ +#if (defined(FSL_FEATURE_LLWU_HAS_MF) && FSL_FEATURE_LLWU_HAS_MF) +#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) + return (bool)(base->MF & (1U << moduleIndex)); +#else + return (bool)(base->MF5 & (1U << moduleIndex)); +#endif /* FSL_FEATURE_LLWU_REG_BITWIDTH */ +#else +#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 16)) + return (bool)(base->F5 & (1U << moduleIndex)); +#else +#if (defined(FSL_FEATURE_LLWU_HAS_PF) && FSL_FEATURE_LLWU_HAS_PF) + return (bool)(base->PF3 & (1U << moduleIndex)); +#else + return (bool)(base->F3 & (1U << moduleIndex)); +#endif /* FSL_FEATURE_LLWU_HAS_PF */ +#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ +#endif /* FSL_FEATURE_LLWU_HAS_MF */ +} +#endif /* FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE */ + +#if (defined(FSL_FEATURE_LLWU_HAS_DMA_ENABLE_REG) && FSL_FEATURE_LLWU_HAS_DMA_ENABLE_REG) +/*! + * @brief Enables/disables the internal module DMA wakeup source. + * + * This function enables/disables the internal DMA that is used as a wake up source. + * + * @param base LLWU peripheral base address. + * @param moduleIndex An internal module index which is used as a DMA request source, starting from 1. + * @param enable Enable or disable the DMA request source + */ +static inline void LLWU_EnableInternalModuleDmaRequestWakup(LLWU_Type *base, uint32_t moduleIndex, bool enable) +{ + if (enable) + { + base->DE |= 1U << moduleIndex; + } + else + { + base->DE &= ~(1U << moduleIndex); + } +} +#endif /* FSL_FEATURE_LLWU_HAS_DMA_ENABLE_REG */ + +#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && FSL_FEATURE_LLWU_HAS_PIN_FILTER) +/*! + * @brief Sets the pin filter configuration. + * + * This function sets the pin filter configuration. + * + * @param base LLWU peripheral base address. + * @param filterIndex A pin filter index used to enable/disable the digital filter, starting from 1. + * @param filterMode A filter mode configuration + */ +void LLWU_SetPinFilterMode(LLWU_Type *base, uint32_t filterIndex, llwu_external_pin_filter_mode_t filterMode); + +/*! + * @brief Gets the pin filter configuration. + * + * This function gets the pin filter flag. + * + * @param base LLWU peripheral base address. + * @param filterIndex A pin filter index, which starts from 1. + * @return True if the flag is a source of the existing low-leakage power mode. + */ +bool LLWU_GetPinFilterFlag(LLWU_Type *base, uint32_t filterIndex); + +/*! + * @brief Clears the pin filter configuration. + * + * This function clears the pin filter flag. + * + * @param base LLWU peripheral base address. + * @param filterIndex A pin filter index to clear the flag, starting from 1. + */ +void LLWU_ClearPinFilterFlag(LLWU_Type *base, uint32_t filterIndex); + +#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ + +#if (defined(FSL_FEATURE_LLWU_HAS_RESET_ENABLE) && FSL_FEATURE_LLWU_HAS_RESET_ENABLE) +/*! + * @brief Sets the reset pin mode. + * + * This function determines how the reset pin is used as a low leakage mode exit source. + * + * @param pinEnable Enable reset the pin filter + * @param pinFilterEnable Specify whether the pin filter is enabled in Low-Leakage power mode. + */ +void LLWU_SetResetPinMode(LLWU_Type *base, bool pinEnable, bool enableInLowLeakageMode); +#endif /* FSL_FEATURE_LLWU_HAS_RESET_ENABLE */ + +/*@}*/ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ +#endif /* _FSL_LLWU_H_*/ diff --git a/drivers/include/fsl_lptmr.h b/drivers/include/fsl_lptmr.h new file mode 100644 index 0000000..6cc909b --- /dev/null +++ b/drivers/include/fsl_lptmr.h @@ -0,0 +1,370 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_LPTMR_H_ +#define _FSL_LPTMR_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup lptmr + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +#define FSL_LPTMR_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) /*!< Version 2.0.1 */ +/*@}*/ + +/*! @brief LPTMR pin selection used in pulse counter mode.*/ +typedef enum _lptmr_pin_select +{ + kLPTMR_PinSelectInput_0 = 0x0U, /*!< Pulse counter input 0 is selected */ + kLPTMR_PinSelectInput_1 = 0x1U, /*!< Pulse counter input 1 is selected */ + kLPTMR_PinSelectInput_2 = 0x2U, /*!< Pulse counter input 2 is selected */ + kLPTMR_PinSelectInput_3 = 0x3U /*!< Pulse counter input 3 is selected */ +} lptmr_pin_select_t; + +/*! @brief LPTMR pin polarity used in pulse counter mode.*/ +typedef enum _lptmr_pin_polarity +{ + kLPTMR_PinPolarityActiveHigh = 0x0U, /*!< Pulse Counter input source is active-high */ + kLPTMR_PinPolarityActiveLow = 0x1U /*!< Pulse Counter input source is active-low */ +} lptmr_pin_polarity_t; + +/*! @brief LPTMR timer mode selection.*/ +typedef enum _lptmr_timer_mode +{ + kLPTMR_TimerModeTimeCounter = 0x0U, /*!< Time Counter mode */ + kLPTMR_TimerModePulseCounter = 0x1U /*!< Pulse Counter mode */ +} lptmr_timer_mode_t; + +/*! @brief LPTMR prescaler/glitch filter values*/ +typedef enum _lptmr_prescaler_glitch_value +{ + kLPTMR_Prescale_Glitch_0 = 0x0U, /*!< Prescaler divide 2, glitch filter does not support this setting */ + kLPTMR_Prescale_Glitch_1 = 0x1U, /*!< Prescaler divide 4, glitch filter 2 */ + kLPTMR_Prescale_Glitch_2 = 0x2U, /*!< Prescaler divide 8, glitch filter 4 */ + kLPTMR_Prescale_Glitch_3 = 0x3U, /*!< Prescaler divide 16, glitch filter 8 */ + kLPTMR_Prescale_Glitch_4 = 0x4U, /*!< Prescaler divide 32, glitch filter 16 */ + kLPTMR_Prescale_Glitch_5 = 0x5U, /*!< Prescaler divide 64, glitch filter 32 */ + kLPTMR_Prescale_Glitch_6 = 0x6U, /*!< Prescaler divide 128, glitch filter 64 */ + kLPTMR_Prescale_Glitch_7 = 0x7U, /*!< Prescaler divide 256, glitch filter 128 */ + kLPTMR_Prescale_Glitch_8 = 0x8U, /*!< Prescaler divide 512, glitch filter 256 */ + kLPTMR_Prescale_Glitch_9 = 0x9U, /*!< Prescaler divide 1024, glitch filter 512*/ + kLPTMR_Prescale_Glitch_10 = 0xAU, /*!< Prescaler divide 2048 glitch filter 1024 */ + kLPTMR_Prescale_Glitch_11 = 0xBU, /*!< Prescaler divide 4096, glitch filter 2048 */ + kLPTMR_Prescale_Glitch_12 = 0xCU, /*!< Prescaler divide 8192, glitch filter 4096 */ + kLPTMR_Prescale_Glitch_13 = 0xDU, /*!< Prescaler divide 16384, glitch filter 8192 */ + kLPTMR_Prescale_Glitch_14 = 0xEU, /*!< Prescaler divide 32768, glitch filter 16384 */ + kLPTMR_Prescale_Glitch_15 = 0xFU /*!< Prescaler divide 65536, glitch filter 32768 */ +} lptmr_prescaler_glitch_value_t; + +/*! + * @brief LPTMR prescaler/glitch filter clock select. + * @note Clock connections are SoC-specific + */ +typedef enum _lptmr_prescaler_clock_select +{ + kLPTMR_PrescalerClock_0 = 0x0U, /*!< Prescaler/glitch filter clock 0 selected. */ + kLPTMR_PrescalerClock_1 = 0x1U, /*!< Prescaler/glitch filter clock 1 selected. */ + kLPTMR_PrescalerClock_2 = 0x2U, /*!< Prescaler/glitch filter clock 2 selected. */ + kLPTMR_PrescalerClock_3 = 0x3U, /*!< Prescaler/glitch filter clock 3 selected. */ +} lptmr_prescaler_clock_select_t; + +/*! @brief List of the LPTMR interrupts */ +typedef enum _lptmr_interrupt_enable +{ + kLPTMR_TimerInterruptEnable = LPTMR_CSR_TIE_MASK, /*!< Timer interrupt enable */ +} lptmr_interrupt_enable_t; + +/*! @brief List of the LPTMR status flags */ +typedef enum _lptmr_status_flags +{ + kLPTMR_TimerCompareFlag = LPTMR_CSR_TCF_MASK, /*!< Timer compare flag */ +} lptmr_status_flags_t; + +/*! + * @brief LPTMR config structure + * + * 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. + */ +typedef struct _lptmr_config +{ + 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 */ +} lptmr_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Ungates the LPTMR clock and configures the peripheral for a basic operation. + * + * @note This API should be called at the beginning of the application using the LPTMR driver. + * + * @param base LPTMR peripheral base address + * @param config A pointer to the LPTMR configuration structure. + */ +void LPTMR_Init(LPTMR_Type *base, const lptmr_config_t *config); + +/*! + * @brief Gates the LPTMR clock. + * + * @param base LPTMR peripheral base address + */ +void LPTMR_Deinit(LPTMR_Type *base); + +/*! + * @brief Fills in the LPTMR configuration structure with default settings. + * + * The default values are as follows. + * @code + * 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; + * @endcode + * @param config A pointer to the LPTMR configuration structure. + */ +void LPTMR_GetDefaultConfig(lptmr_config_t *config); + +/*! @}*/ + +/*! + * @name Interrupt Interface + * @{ + */ + +/*! + * @brief Enables the selected LPTMR interrupts. + * + * @param base LPTMR peripheral base address + * @param mask The interrupts to enable. This is a logical OR of members of the + * enumeration ::lptmr_interrupt_enable_t + */ +static inline void LPTMR_EnableInterrupts(LPTMR_Type *base, uint32_t mask) +{ + uint32_t reg = base->CSR; + + /* Clear the TCF bit so that we don't clear this w1c bit when writing back */ + reg &= ~(LPTMR_CSR_TCF_MASK); + reg |= mask; + base->CSR = reg; +} + +/*! + * @brief Disables the selected LPTMR interrupts. + * + * @param base LPTMR peripheral base address + * @param mask The interrupts to disable. This is a logical OR of members of the + * enumeration ::lptmr_interrupt_enable_t. + */ +static inline void LPTMR_DisableInterrupts(LPTMR_Type *base, uint32_t mask) +{ + uint32_t reg = base->CSR; + + /* Clear the TCF bit so that we don't clear this w1c bit when writing back */ + reg &= ~(LPTMR_CSR_TCF_MASK); + reg &= ~mask; + base->CSR = reg; +} + +/*! + * @brief Gets the enabled LPTMR interrupts. + * + * @param base LPTMR peripheral base address + * + * @return The enabled interrupts. This is the logical OR of members of the + * enumeration ::lptmr_interrupt_enable_t + */ +static inline uint32_t LPTMR_GetEnabledInterrupts(LPTMR_Type *base) +{ + return (base->CSR & LPTMR_CSR_TIE_MASK); +} + +/*! @}*/ + +/*! + * @name Status Interface + * @{ + */ + +/*! + * @brief Gets the LPTMR status flags. + * + * @param base LPTMR peripheral base address + * + * @return The status flags. This is the logical OR of members of the + * enumeration ::lptmr_status_flags_t + */ +static inline uint32_t LPTMR_GetStatusFlags(LPTMR_Type *base) +{ + return (base->CSR & LPTMR_CSR_TCF_MASK); +} + +/*! + * @brief Clears the LPTMR status flags. + * + * @param base LPTMR peripheral base address + * @param mask The status flags to clear. This is a logical OR of members of the + * enumeration ::lptmr_status_flags_t. + */ +static inline void LPTMR_ClearStatusFlags(LPTMR_Type *base, uint32_t mask) +{ + base->CSR |= mask; +} + +/*! @}*/ + +/*! + * @name Read and write the timer period + * @{ + */ + +/*! + * @brief Sets the timer period in units of count. + * + * 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. + * + * @param base LPTMR peripheral base address + * @param ticks A timer period in units of ticks, which should be equal or greater than 1. + */ +static inline void LPTMR_SetTimerPeriod(LPTMR_Type *base, uint32_t ticks) +{ + assert(ticks > 0); + base->CMR = ticks - 1; +} + +/*! + * @brief Reads the current timer counting value. + * + * 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. + * + * @param base LPTMR peripheral base address + * + * @return The current counter value in ticks + */ +static inline uint32_t LPTMR_GetCurrentTimerCount(LPTMR_Type *base) +{ + /* Must first write any value to the CNR. This synchronizes and registers the current value + * of the CNR into a temporary register which can then be read + */ + base->CNR = 0U; + return (uint32_t)((base->CNR & LPTMR_CNR_COUNTER_MASK) >> LPTMR_CNR_COUNTER_SHIFT); +} + +/*! @}*/ + +/*! + * @name Timer Start and Stop + * @{ + */ + +/*! + * @brief Starts the timer. + * + * 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. + * + * @param base LPTMR peripheral base address + */ +static inline void LPTMR_StartTimer(LPTMR_Type *base) +{ + uint32_t reg = base->CSR; + + /* Clear the TCF bit to avoid clearing the w1c bit when writing back. */ + reg &= ~(LPTMR_CSR_TCF_MASK); + reg |= LPTMR_CSR_TEN_MASK; + base->CSR = reg; +} + +/*! + * @brief Stops the timer. + * + * This function stops the timer and resets the timer's counter register. + * + * @param base LPTMR peripheral base address + */ +static inline void LPTMR_StopTimer(LPTMR_Type *base) +{ + uint32_t reg = base->CSR; + + /* Clear the TCF bit to avoid clearing the w1c bit when writing back. */ + reg &= ~(LPTMR_CSR_TCF_MASK); + reg &= ~LPTMR_CSR_TEN_MASK; + base->CSR = reg; +} + +/*! @}*/ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_LPTMR_H_ */ diff --git a/drivers/include/fsl_mpu.h b/drivers/include/fsl_mpu.h new file mode 100644 index 0000000..d39d78a --- /dev/null +++ b/drivers/include/fsl_mpu.h @@ -0,0 +1,422 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of Freescale Semiconductor, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_MPU_H_ +#define _FSL_MPU_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup mpu + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief MPU driver version 2.1.0. */ +#define FSL_MPU_DRIVER_VERSION (MAKE_VERSION(2, 1, 0)) +/*@}*/ + +/*! @brief MPU the bit shift for masters with privilege rights: read write and execute. */ +#define MPU_REGION_RWXRIGHTS_MASTER_SHIFT(n) (n * 6) + +/*! @brief MPU masters with read, write and execute rights bit mask. */ +#define MPU_REGION_RWXRIGHTS_MASTER_MASK(n) (0x1Fu << MPU_REGION_RWXRIGHTS_MASTER_SHIFT(n)) + +/*! @brief MPU masters with read, write and execute rights bit width. */ +#define MPU_REGION_RWXRIGHTS_MASTER_WIDTH 5 + +/*! @brief MPU masters with read, write and execute rights priority setting. */ +#define MPU_REGION_RWXRIGHTS_MASTER(n, x) \ + (((uint32_t)(((uint32_t)(x)) << MPU_REGION_RWXRIGHTS_MASTER_SHIFT(n))) & MPU_REGION_RWXRIGHTS_MASTER_MASK(n)) + +/*! @brief MPU masters with read, write and execute rights process enable bit shift. */ +#define MPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n) (n * 6 + MPU_REGION_RWXRIGHTS_MASTER_WIDTH) + +/*! @brief MPU masters with read, write and execute rights process enable bit mask. */ +#define MPU_REGION_RWXRIGHTS_MASTER_PE_MASK(n) (0x1u << MPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n)) + +/*! @brief MPU masters with read, write and execute rights process enable setting. */ +#define MPU_REGION_RWXRIGHTS_MASTER_PE(n, x) \ + (((uint32_t)(((uint32_t)(x)) << MPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n))) & MPU_REGION_RWXRIGHTS_MASTER_PE_MASK(n)) + +/*! @brief MPU masters with normal read write permission bit shift. */ +#define MPU_REGION_RWRIGHTS_MASTER_SHIFT(n) ((n - FSL_FEATURE_MPU_PRIVILEGED_RIGHTS_MASTER_COUNT) * 2 + 24) + +/*! @brief MPU masters with normal read write rights bit mask. */ +#define MPU_REGION_RWRIGHTS_MASTER_MASK(n) (0x3u << MPU_REGION_RWRIGHTS_MASTER_SHIFT(n)) + +/*! @brief MPU masters with normal read write rights priority setting. */ +#define MPU_REGION_RWRIGHTS_MASTER(n, x) \ + (((uint32_t)(((uint32_t)(x)) << MPU_REGION_RWRIGHTS_MASTER_SHIFT(n))) & MPU_REGION_RWRIGHTS_MASTER_MASK(n)) + +/*! @brief Describes the number of MPU regions. */ +typedef enum _mpu_region_total_num +{ + kMPU_8Regions = 0x0U, /*!< MPU supports 8 regions. */ + kMPU_12Regions = 0x1U, /*!< MPU supports 12 regions. */ + kMPU_16Regions = 0x2U /*!< MPU supports 16 regions. */ +} mpu_region_total_num_t; + +/*! @brief MPU slave port number. */ +typedef enum _mpu_slave +{ + kMPU_Slave0 = 4U, /*!< MPU slave port 0. */ + kMPU_Slave1 = 3U, /*!< MPU slave port 1. */ + kMPU_Slave2 = 2U, /*!< MPU slave port 2. */ + kMPU_Slave3 = 1U, /*!< MPU slave port 3. */ + kMPU_Slave4 = 0U /*!< MPU slave port 4. */ +} mpu_slave_t; + +/*! @brief MPU error access control detail. */ +typedef enum _mpu_err_access_control +{ + kMPU_NoRegionHit = 0U, /*!< No region hit error. */ + kMPU_NoneOverlappRegion = 1U, /*!< Access single region error. */ + kMPU_OverlappRegion = 2U /*!< Access overlapping region error. */ +} mpu_err_access_control_t; + +/*! @brief MPU error access type. */ +typedef enum _mpu_err_access_type +{ + kMPU_ErrTypeRead = 0U, /*!< MPU error access type --- read. */ + kMPU_ErrTypeWrite = 1U /*!< MPU error access type --- write. */ +} mpu_err_access_type_t; + +/*! @brief MPU access error attributes.*/ +typedef enum _mpu_err_attributes +{ + kMPU_InstructionAccessInUserMode = 0U, /*!< Access instruction error in user mode. */ + kMPU_DataAccessInUserMode = 1U, /*!< Access data error in user mode. */ + kMPU_InstructionAccessInSupervisorMode = 2U, /*!< Access instruction error in supervisor mode. */ + kMPU_DataAccessInSupervisorMode = 3U /*!< Access data error in supervisor mode. */ +} mpu_err_attributes_t; + +/*! @brief MPU access rights in supervisor mode for bus master 0 ~ 3. */ +typedef enum _mpu_supervisor_access_rights +{ + kMPU_SupervisorReadWriteExecute = 0U, /*!< Read write and execute operations are allowed in supervisor mode. */ + kMPU_SupervisorReadExecute = 1U, /*!< Read and execute operations are allowed in supervisor mode. */ + kMPU_SupervisorReadWrite = 2U, /*!< Read write operations are allowed in supervisor mode. */ + kMPU_SupervisorEqualToUsermode = 3U /*!< Access permission equal to user mode. */ +} mpu_supervisor_access_rights_t; + +/*! @brief MPU access rights in user mode for bus master 0 ~ 3. */ +typedef enum _mpu_user_access_rights +{ + kMPU_UserNoAccessRights = 0U, /*!< No access allowed in user mode. */ + kMPU_UserExecute = 1U, /*!< Execute operation is allowed in user mode. */ + kMPU_UserWrite = 2U, /*!< Write operation is allowed in user mode. */ + kMPU_UserWriteExecute = 3U, /*!< Write and execute operations are allowed in user mode. */ + kMPU_UserRead = 4U, /*!< Read is allowed in user mode. */ + kMPU_UserReadExecute = 5U, /*!< Read and execute operations are allowed in user mode. */ + kMPU_UserReadWrite = 6U, /*!< Read and write operations are allowed in user mode. */ + kMPU_UserReadWriteExecute = 7U /*!< Read write and execute operations are allowed in user mode. */ +} mpu_user_access_rights_t; + +/*! @brief MPU hardware basic information. */ +typedef struct _mpu_hardware_info +{ + uint8_t hardwareRevisionLevel; /*!< Specifies the MPU's hardware and definition reversion level. */ + uint8_t slavePortsNumbers; /*!< Specifies the number of slave ports connected to MPU. */ + mpu_region_total_num_t regionsNumbers; /*!< Indicates the number of region descriptors implemented. */ +} mpu_hardware_info_t; + +/*! @brief MPU detail error access information. */ +typedef struct _mpu_access_err_info +{ + uint32_t master; /*!< Access error master. */ + mpu_err_attributes_t attributes; /*!< Access error attributes. */ + mpu_err_access_type_t accessType; /*!< Access error type. */ + mpu_err_access_control_t accessControl; /*!< Access error control. */ + uint32_t address; /*!< Access error address. */ +#if FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER + uint8_t processorIdentification; /*!< Access error processor identification. */ +#endif /* FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER */ +} mpu_access_err_info_t; + +/*! @brief MPU read/write/execute rights control for bus master 0 ~ 3. */ +typedef struct _mpu_rwxrights_master_access_control +{ + mpu_supervisor_access_rights_t superAccessRights; /*!< Master access rights in supervisor mode. */ + mpu_user_access_rights_t userAccessRights; /*!< Master access rights in user mode. */ +#if FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER + bool processIdentifierEnable; /*!< Enables or disables process identifier. */ +#endif /* FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER */ +} mpu_rwxrights_master_access_control_t; + +/*! @brief MPU read/write access control for bus master 4 ~ 7. */ +typedef struct _mpu_rwrights_master_access_control +{ + bool writeEnable; /*!< Enables or disables write permission. */ + bool readEnable; /*!< Enables or disables read permission. */ +} mpu_rwrights_master_access_control_t; + +/*! + * @brief MPU region configuration structure. + * + * This structure is used to configure the regionNum region. + * The accessRights1[0] ~ accessRights1[3] are used to configure the bus master + * 0 ~ 3 with the privilege rights setting. The accessRights2[0] ~ accessRights2[3] + * are used to configure the high master 4 ~ 7 with the normal read write permission. + * The master port assignment is the chip configuration. Normally, the core is the + * master 0, debugger is the master 1. + * Note: MPU assigns a priority scheme where the debugger is treated as the highest + * priority master followed by the core and then all the remaining masters. + * MPU protection does not allow writes from the core to affect the "regionNum 0" start + * and end address nor the permissions associated with the debugger. It can only write + * the permission fields associated with the other masters. This protection guarantee + * the debugger always has access to the entire address space and those rights can't + * be changed by the core or any other bus master. Prepare + * the region configuration when regionNum is 0. + */ +typedef struct _mpu_region_config +{ + uint32_t regionNum; /*!< MPU region number, range form 0 ~ FSL_FEATURE_MPU_DESCRIPTOR_COUNT - 1. */ + uint32_t startAddress; /*!< Memory region start address. Note: bit0 ~ bit4 always be marked as 0 by MPU. The actual + start address is 0-modulo-32 byte address. */ + uint32_t endAddress; /*!< Memory region end address. Note: bit0 ~ bit4 always be marked as 1 by MPU. The actual end + address is 31-modulo-32 byte address. */ + mpu_rwxrights_master_access_control_t accessRights1[4]; /*!< Masters with read, write and execute rights setting. */ + mpu_rwrights_master_access_control_t accessRights2[4]; /*!< Masters with normal read write rights setting. */ +#if FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER + uint8_t processIdentifier; /*!< Process identifier used when "processIdentifierEnable" set with true. */ + uint8_t + processIdMask; /*!< Process identifier mask. The setting bit will ignore the same bit in process identifier. */ +#endif /* FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER */ +} mpu_region_config_t; + +/*! + * @brief The configuration structure for the MPU initialization. + * + * This structure is used when calling the MPU_Init function. + */ +typedef struct _mpu_config +{ + mpu_region_config_t regionConfig; /*!< region access permission. */ + struct _mpu_config *next; /*!< pointer to the next structure. */ +} mpu_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* _cplusplus */ + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Initializes the MPU with the user configuration structure. + * + * This function configures the MPU module with the user-defined configuration. + * + * @param base MPU peripheral base address. + * @param config The pointer to the configuration structure. + */ +void MPU_Init(MPU_Type *base, const mpu_config_t *config); + +/*! + * @brief Deinitializes the MPU regions. + * + * @param base MPU peripheral base address. + */ +void MPU_Deinit(MPU_Type *base); + +/* @}*/ + +/*! + * @name Basic Control Operations + * @{ + */ + +/*! + * @brief Enables/disables the MPU globally. + * + * Call this API to enable or disable the MPU module. + * + * @param base MPU peripheral base address. + * @param enable True enable MPU, false disable MPU. + */ +static inline void MPU_Enable(MPU_Type *base, bool enable) +{ + if (enable) + { + /* Enable the MPU globally. */ + base->CESR |= MPU_CESR_VLD_MASK; + } + else + { /* Disable the MPU globally. */ + base->CESR &= ~MPU_CESR_VLD_MASK; + } +} + +/*! + * @brief Enables/disables the MPU for a special region. + * + * When MPU is enabled, call this API to disable an unused region + * of an enabled MPU. Call this API to minimize the power dissipation. + * + * @param base MPU peripheral base address. + * @param number MPU region number. + * @param enable True enable the special region MPU, false disable the special region MPU. + */ +static inline void MPU_RegionEnable(MPU_Type *base, uint32_t number, bool enable) +{ + if (enable) + { + /* Enable the #number region MPU. */ + base->WORD[number][3] |= MPU_WORD_VLD_MASK; + } + else + { /* Disable the #number region MPU. */ + base->WORD[number][3] &= ~MPU_WORD_VLD_MASK; + } +} + +/*! + * @brief Gets the MPU basic hardware information. + * + * @param base MPU peripheral base address. + * @param hardwareInform The pointer to the MPU hardware information structure. See "mpu_hardware_info_t". + */ +void MPU_GetHardwareInfo(MPU_Type *base, mpu_hardware_info_t *hardwareInform); + +/*! + * @brief Sets the MPU region. + * + * Note: Due to the MPU protection, the Region number 0 does not allow writes from + * core to affect the start and end address nor the permissions associated with + * the debugger. It can only write the permission fields associated + * with the other masters. + * + * @param base MPU peripheral base address. + * @param regionConfig The pointer to the MPU user configuration structure. See "mpu_region_config_t". + */ +void MPU_SetRegionConfig(MPU_Type *base, const mpu_region_config_t *regionConfig); + +/*! + * @brief Sets the region start and end address. + * + * Memory region start address. Note: bit0 ~ bit4 is always marked as 0 by MPU. + * The actual start address by MPU is 0-modulo-32 byte address. + * Memory region end address. Note: bit0 ~ bit4 always be marked as 1 by MPU. + * The actual end address used by MPU is 31-modulo-32 byte address. + * Note: Due to the MPU protection, the startAddr and endAddr can't be + * changed by the core when regionNum is 0. + * + * @param base MPU peripheral base address. + * @param regionNum MPU region number. The range is from 0 to + * FSL_FEATURE_MPU_DESCRIPTOR_COUNT - 1. + * @param startAddr Region start address. + * @param endAddr Region end address. + */ +void MPU_SetRegionAddr(MPU_Type *base, uint32_t regionNum, uint32_t startAddr, uint32_t endAddr); + +/*! + * @brief Sets the MPU region access rights for masters with read, write and execute rights. + * The MPU access rights depend on two board classifications of bus masters. + * The privilege rights masters and the normal rights masters. + * The privilege rights masters have the read, write and execute access rights. + * So except the normal read and write rights, the execute rights is also + * allowed for these masters. The privilege rights masters are normally range from + * bus masters 0 - 3. However, the maximum master number is device-specific. + * See the "FSL_FEATURE_MPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX". + * The normal rights masters access rights control see + * "MPU_SetRegionRwMasterAccessRights()". + * + * @param base MPU peripheral base address. + * @param regionNum MPU region number. Should range from 0 to + * FSL_FEATURE_MPU_DESCRIPTOR_COUNT - 1. + * @param masterNum MPU bus master number. Should range from 0 to + * FSL_FEATURE_MPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX. + * @param accessRights The pointer to the MPU access rights configuration. See "mpu_rwxrights_master_access_control_t". + */ +void MPU_SetRegionRwxMasterAccessRights(MPU_Type *base, + uint32_t regionNum, + uint32_t masterNum, + const mpu_rwxrights_master_access_control_t *accessRights); + +/*! + * @brief Sets the MPU region access rights for masters with read and write rights. + * The MPU access rights depend on two board classifications of bus masters. + * The privilege rights masters and the normal rights masters. + * The normal rights masters only have the read and write access permissions. + * The privilege rights access control see "MPU_SetRegionRwxMasterAccessRights". + * + * @param base MPU peripheral base address. + * @param regionNum MPU region number. The range is from 0 to + * FSL_FEATURE_MPU_DESCRIPTOR_COUNT - 1. + * @param masterNum MPU bus master number. Should range from FSL_FEATURE_MPU_PRIVILEGED_RIGHTS_MASTER_COUNT + * to ~ FSL_FEATURE_MPU_MASTER_MAX_INDEX. + * @param accessRights The pointer to the MPU access rights configuration. See "mpu_rwrights_master_access_control_t". + */ +void MPU_SetRegionRwMasterAccessRights(MPU_Type *base, + uint32_t regionNum, + uint32_t masterNum, + const mpu_rwrights_master_access_control_t *accessRights); + +/*! + * @brief Gets the numbers of slave ports where errors occur. + * + * @param base MPU peripheral base address. + * @param slaveNum MPU slave port number. + * @return The slave ports error status. + * true - error happens in this slave port. + * false - error didn't happen in this slave port. + */ +bool MPU_GetSlavePortErrorStatus(MPU_Type *base, mpu_slave_t slaveNum); + +/*! + * @brief Gets the MPU detailed error access information. + * + * @param base MPU peripheral base address. + * @param slaveNum MPU slave port number. + * @param errInform The pointer to the MPU access error information. See "mpu_access_err_info_t". + */ +void MPU_GetDetailErrorAccessInfo(MPU_Type *base, mpu_slave_t slaveNum, mpu_access_err_info_t *errInform); + +/* @} */ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_MPU_H_ */ diff --git a/drivers/include/fsl_pdb.h b/drivers/include/fsl_pdb.h new file mode 100644 index 0000000..3dec946 --- /dev/null +++ b/drivers/include/fsl_pdb.h @@ -0,0 +1,576 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_PDB_H_ +#define _FSL_PDB_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup pdb + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief PDB driver version 2.0.1. */ +#define FSL_PDB_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) +/*@}*/ + +/*! + * @brief PDB flags. + */ +enum _pdb_status_flags +{ + kPDB_LoadOKFlag = PDB_SC_LDOK_MASK, /*!< This flag is automatically cleared when the values in buffers are + loaded into the internal registers after the LDOK bit is set or the + PDBEN is cleared. */ + kPDB_DelayEventFlag = PDB_SC_PDBIF_MASK, /*!< PDB timer delay event flag. */ +}; + +/*! + * @brief PDB ADC PreTrigger channel flags. + */ +enum _pdb_adc_pretrigger_flags +{ + /* PDB PreTrigger channel match flags. */ + kPDB_ADCPreTriggerChannel0Flag = PDB_S_CF(1U << 0), /*!< Pre-trigger 0 flag. */ + kPDB_ADCPreTriggerChannel1Flag = PDB_S_CF(1U << 1), /*!< Pre-trigger 1 flag. */ +#if (PDB_DLY_COUNT2 > 2) + kPDB_ADCPreTriggerChannel2Flag = PDB_S_CF(1U << 2), /*!< Pre-trigger 2 flag. */ + kPDB_ADCPreTriggerChannel3Flag = PDB_S_CF(1U << 3), /*!< Pre-trigger 3 flag. */ +#endif /* PDB_DLY_COUNT2 > 2 */ +#if (PDB_DLY_COUNT2 > 4) + kPDB_ADCPreTriggerChannel4Flag = PDB_S_CF(1U << 4), /*!< Pre-trigger 4 flag. */ + kPDB_ADCPreTriggerChannel5Flag = PDB_S_CF(1U << 5), /*!< Pre-trigger 5 flag. */ + kPDB_ADCPreTriggerChannel6Flag = PDB_S_CF(1U << 6), /*!< Pre-trigger 6 flag. */ + kPDB_ADCPreTriggerChannel7Flag = PDB_S_CF(1U << 7), /*!< Pre-trigger 7 flag. */ +#endif /* PDB_DLY_COUNT2 > 4 */ + + /* PDB PreTrigger channel error flags. */ + kPDB_ADCPreTriggerChannel0ErrorFlag = PDB_S_ERR(1U << 0), /*!< Pre-trigger 0 Error. */ + kPDB_ADCPreTriggerChannel1ErrorFlag = PDB_S_ERR(1U << 1), /*!< Pre-trigger 1 Error. */ +#if (PDB_DLY_COUNT2 > 2) + kPDB_ADCPreTriggerChannel2ErrorFlag = PDB_S_ERR(1U << 2), /*!< Pre-trigger 2 Error. */ + kPDB_ADCPreTriggerChannel3ErrorFlag = PDB_S_ERR(1U << 3), /*!< Pre-trigger 3 Error. */ +#endif /* PDB_DLY_COUNT2 > 2 */ +#if (PDB_DLY_COUNT2 > 4) + kPDB_ADCPreTriggerChannel4ErrorFlag = PDB_S_ERR(1U << 4), /*!< Pre-trigger 4 Error. */ + kPDB_ADCPreTriggerChannel5ErrorFlag = PDB_S_ERR(1U << 5), /*!< Pre-trigger 5 Error. */ + kPDB_ADCPreTriggerChannel6ErrorFlag = PDB_S_ERR(1U << 6), /*!< Pre-trigger 6 Error. */ + kPDB_ADCPreTriggerChannel7ErrorFlag = PDB_S_ERR(1U << 7), /*!< Pre-trigger 7 Error. */ +#endif /* PDB_DLY_COUNT2 > 4 */ +}; + +/*! + * @brief PDB buffer interrupts. + */ +enum _pdb_interrupt_enable +{ + kPDB_SequenceErrorInterruptEnable = PDB_SC_PDBEIE_MASK, /*!< PDB sequence error interrupt enable. */ + kPDB_DelayInterruptEnable = PDB_SC_PDBIE_MASK, /*!< PDB delay interrupt enable. */ +}; + +/*! + * @brief PDB load value mode. + * + * Selects the mode to load the internal values after doing the load operation (write 1 to PDBx_SC[LDOK]). + * These values are for the following operations. + * - PDB counter (PDBx_MOD, PDBx_IDLY) + * - ADC trigger (PDBx_CHnDLYm) + * - DAC trigger (PDBx_DACINTx) + * - CMP trigger (PDBx_POyDLY) + */ +typedef enum _pdb_load_value_mode +{ + kPDB_LoadValueImmediately = 0U, /*!< Load immediately after 1 is written to LDOK. */ + kPDB_LoadValueOnCounterOverflow = 1U, /*!< Load when the PDB counter overflows (reaches the MOD + register value). */ + kPDB_LoadValueOnTriggerInput = 2U, /*!< Load a trigger input event is detected. */ + kPDB_LoadValueOnCounterOverflowOrTriggerInput = 3U, /*!< Load either when the PDB counter overflows or a trigger + input is detected. */ +} pdb_load_value_mode_t; + +/*! + * @brief Prescaler divider. + * + * Counting uses the peripheral clock divided by multiplication factor selected by times of MULT. + */ +typedef enum _pdb_prescaler_divider +{ + kPDB_PrescalerDivider1 = 0U, /*!< Divider x1. */ + kPDB_PrescalerDivider2 = 1U, /*!< Divider x2. */ + kPDB_PrescalerDivider4 = 2U, /*!< Divider x4. */ + kPDB_PrescalerDivider8 = 3U, /*!< Divider x8. */ + kPDB_PrescalerDivider16 = 4U, /*!< Divider x16. */ + kPDB_PrescalerDivider32 = 5U, /*!< Divider x32. */ + kPDB_PrescalerDivider64 = 6U, /*!< Divider x64. */ + kPDB_PrescalerDivider128 = 7U, /*!< Divider x128. */ +} pdb_prescaler_divider_t; + +/*! + * @brief Multiplication factor select for prescaler. + * + * Selects the multiplication factor of the prescaler divider for the counter clock. + */ +typedef enum _pdb_divider_multiplication_factor +{ + kPDB_DividerMultiplicationFactor1 = 0U, /*!< Multiplication factor is 1. */ + kPDB_DividerMultiplicationFactor10 = 1U, /*!< Multiplication factor is 10. */ + kPDB_DividerMultiplicationFactor20 = 2U, /*!< Multiplication factor is 20. */ + kPDB_DividerMultiplicationFactor40 = 3U, /*!< Multiplication factor is 40. */ +} pdb_divider_multiplication_factor_t; + +/*! + * @brief Trigger input source + * + * Selects the trigger input source for the PDB. The trigger input source can be internal or external (EXTRG pin), or + * the software trigger. See chip configuration details for the actual PDB input trigger connections. + */ +typedef enum _pdb_trigger_input_source +{ + kPDB_TriggerInput0 = 0U, /*!< Trigger-In 0. */ + kPDB_TriggerInput1 = 1U, /*!< Trigger-In 1. */ + kPDB_TriggerInput2 = 2U, /*!< Trigger-In 2. */ + kPDB_TriggerInput3 = 3U, /*!< Trigger-In 3. */ + kPDB_TriggerInput4 = 4U, /*!< Trigger-In 4. */ + kPDB_TriggerInput5 = 5U, /*!< Trigger-In 5. */ + kPDB_TriggerInput6 = 6U, /*!< Trigger-In 6. */ + kPDB_TriggerInput7 = 7U, /*!< Trigger-In 7. */ + kPDB_TriggerInput8 = 8U, /*!< Trigger-In 8. */ + kPDB_TriggerInput9 = 9U, /*!< Trigger-In 9. */ + kPDB_TriggerInput10 = 10U, /*!< Trigger-In 10. */ + kPDB_TriggerInput11 = 11U, /*!< Trigger-In 11. */ + kPDB_TriggerInput12 = 12U, /*!< Trigger-In 12. */ + kPDB_TriggerInput13 = 13U, /*!< Trigger-In 13. */ + kPDB_TriggerInput14 = 14U, /*!< Trigger-In 14. */ + kPDB_TriggerSoftware = 15U, /*!< Trigger-In 15, software trigger. */ +} pdb_trigger_input_source_t; + +/*! + * @brief PDB module configuration. + */ +typedef struct _pdb_config +{ + pdb_load_value_mode_t loadValueMode; /*!< Select the load value mode. */ + pdb_prescaler_divider_t prescalerDivider; /*!< Select the prescaler divider. */ + pdb_divider_multiplication_factor_t dividerMultiplicationFactor; /*!< Multiplication factor select for prescaler. */ + pdb_trigger_input_source_t triggerInputSource; /*!< Select the trigger input source. */ + bool enableContinuousMode; /*!< Enable the PDB operation in Continuous mode.*/ +} pdb_config_t; + +/*! + * @brief PDB ADC Pre-trigger configuration. + */ +typedef struct _pdb_adc_pretrigger_config +{ + uint32_t enablePreTriggerMask; /*!< PDB Channel Pre-trigger Enable. */ + uint32_t enableOutputMask; /*!< PDB Channel Pre-trigger Output Select. + PDB channel's corresponding pre-trigger asserts when the counter + reaches the channel delay register. */ + uint32_t enableBackToBackOperationMask; /*!< PDB Channel pre-trigger Back-to-Back Operation Enable. + Back-to-back operation enables the ADC conversions complete to trigger + the next PDB channel pre-trigger and trigger output, so that the ADC + conversions can be triggered on next set of configuration and results + registers.*/ +} pdb_adc_pretrigger_config_t; + +/*! + * @brief PDB DAC trigger configuration. + */ +typedef struct _pdb_dac_trigger_config +{ + bool enableExternalTriggerInput; /*!< Enables the external trigger for DAC interval counter. */ + bool enableIntervalTrigger; /*!< Enables the DAC interval trigger. */ +} pdb_dac_trigger_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization + * @{ + */ + +/*! + * @brief Initializes the PDB module. + * + * This function initializes the PDB module. The operations included are as follows. + * - Enable the clock for PDB instance. + * - Configure the PDB module. + * - Enable the PDB module. + * + * @param base PDB peripheral base address. + * @param config Pointer to the configuration structure. See "pdb_config_t". + */ +void PDB_Init(PDB_Type *base, const pdb_config_t *config); + +/*! + * @brief De-initializes the PDB module. + * + * @param base PDB peripheral base address. + */ +void PDB_Deinit(PDB_Type *base); + +/*! + * @brief Initializes the PDB user configuration structure. + * + * This function initializes the user configuration structure to a default value. The default values are as follows. + * @code + * config->loadValueMode = kPDB_LoadValueImmediately; + * config->prescalerDivider = kPDB_PrescalerDivider1; + * config->dividerMultiplicationFactor = kPDB_DividerMultiplicationFactor1; + * config->triggerInputSource = kPDB_TriggerSoftware; + * config->enableContinuousMode = false; + * @endcode + * @param config Pointer to configuration structure. See "pdb_config_t". + */ +void PDB_GetDefaultConfig(pdb_config_t *config); + +/*! + * @brief Enables the PDB module. + * + * @param base PDB peripheral base address. + * @param enable Enable the module or not. + */ +static inline void PDB_Enable(PDB_Type *base, bool enable) +{ + if (enable) + { + base->SC |= PDB_SC_PDBEN_MASK; + } + else + { + base->SC &= ~PDB_SC_PDBEN_MASK; + } +} + +/* @} */ + +/*! + * @name Basic Counter + * @{ + */ + +/*! + * @brief Triggers the PDB counter by software. + * + * @param base PDB peripheral base address. + */ +static inline void PDB_DoSoftwareTrigger(PDB_Type *base) +{ + base->SC |= PDB_SC_SWTRIG_MASK; +} + +/*! + * @brief Loads the counter values. + * + * This function loads the counter values from the internal buffer. + * See "pdb_load_value_mode_t" about PDB's load mode. + * + * @param base PDB peripheral base address. + */ +static inline void PDB_DoLoadValues(PDB_Type *base) +{ + base->SC |= PDB_SC_LDOK_MASK; +} + +/*! + * @brief Enables the DMA for the PDB module. + * + * @param base PDB peripheral base address. + * @param enable Enable the feature or not. + */ +static inline void PDB_EnableDMA(PDB_Type *base, bool enable) +{ + if (enable) + { + base->SC |= PDB_SC_DMAEN_MASK; + } + else + { + base->SC &= ~PDB_SC_DMAEN_MASK; + } +} + +/*! + * @brief Enables the interrupts for the PDB module. + * + * @param base PDB peripheral base address. + * @param mask Mask value for interrupts. See "_pdb_interrupt_enable". + */ +static inline void PDB_EnableInterrupts(PDB_Type *base, uint32_t mask) +{ + assert(0U == (mask & ~(PDB_SC_PDBEIE_MASK | PDB_SC_PDBIE_MASK))); + + base->SC |= mask; +} + +/*! + * @brief Disables the interrupts for the PDB module. + * + * @param base PDB peripheral base address. + * @param mask Mask value for interrupts. See "_pdb_interrupt_enable". + */ +static inline void PDB_DisableInterrupts(PDB_Type *base, uint32_t mask) +{ + assert(0U == (mask & ~(PDB_SC_PDBEIE_MASK | PDB_SC_PDBIE_MASK))); + + base->SC &= ~mask; +} + +/*! + * @brief Gets the status flags of the PDB module. + * + * @param base PDB peripheral base address. + * + * @return Mask value for asserted flags. See "_pdb_status_flags". + */ +static inline uint32_t PDB_GetStatusFlags(PDB_Type *base) +{ + return base->SC & (PDB_SC_PDBIF_MASK | PDB_SC_LDOK_MASK); +} + +/*! + * @brief Clears the status flags of the PDB module. + * + * @param base PDB peripheral base address. + * @param mask Mask value of flags. See "_pdb_status_flags". + */ +static inline void PDB_ClearStatusFlags(PDB_Type *base, uint32_t mask) +{ + assert(0U == (mask & ~PDB_SC_PDBIF_MASK)); + + base->SC &= ~mask; +} + +/*! + * @brief Specifies the counter period. + * + * @param base PDB peripheral base address. + * @param value Setting value for the modulus. 16-bit is available. + */ +static inline void PDB_SetModulusValue(PDB_Type *base, uint32_t value) +{ + base->MOD = PDB_MOD_MOD(value); +} + +/*! + * @brief Gets the PDB counter's current value. + * + * @param base PDB peripheral base address. + * + * @return PDB counter's current value. + */ +static inline uint32_t PDB_GetCounterValue(PDB_Type *base) +{ + return base->CNT; +} + +/*! + * @brief Sets the value for the PDB counter delay event. + * + * @param base PDB peripheral base address. + * @param value Setting value for PDB counter delay event. 16-bit is available. + */ +static inline void PDB_SetCounterDelayValue(PDB_Type *base, uint32_t value) +{ + base->IDLY = PDB_IDLY_IDLY(value); +} +/* @} */ + +/*! + * @name ADC Pre-trigger + * @{ + */ + +/*! + * @brief Configures the ADC pre-trigger in the PDB module. + * + * @param base PDB peripheral base address. + * @param channel Channel index for ADC instance. + * @param config Pointer to the configuration structure. See "pdb_adc_pretrigger_config_t". + */ +static inline void PDB_SetADCPreTriggerConfig(PDB_Type *base, uint32_t channel, pdb_adc_pretrigger_config_t *config) +{ + assert(channel < PDB_C1_COUNT); + assert(NULL != config); + + base->CH[channel].C1 = PDB_C1_BB(config->enableBackToBackOperationMask) | PDB_C1_TOS(config->enableOutputMask) | + PDB_C1_EN(config->enablePreTriggerMask); +} + +/*! + * @brief Sets the value for the ADC pre-trigger delay event. + * + * This function sets the value for ADC pre-trigger delay event. It specifies the delay value for the channel's + * corresponding pre-trigger. The pre-trigger asserts when the PDB counter is equal to the set value. + * + * @param base PDB peripheral base address. + * @param channel Channel index for ADC instance. + * @param preChannel Channel group index for ADC instance. + * @param value Setting value for ADC pre-trigger delay event. 16-bit is available. + */ +static inline void PDB_SetADCPreTriggerDelayValue(PDB_Type *base, uint32_t channel, uint32_t preChannel, uint32_t value) +{ + assert(channel < PDB_C1_COUNT); + assert(preChannel < PDB_DLY_COUNT2); + /* xx_COUNT2 is actually the count for pre-triggers in header file. xx_COUNT is used for the count of channels. */ + + base->CH[channel].DLY[preChannel] = PDB_DLY_DLY(value); +} + +/*! + * @brief Gets the ADC pre-trigger's status flags. + * + * @param base PDB peripheral base address. + * @param channel Channel index for ADC instance. + * + * @return Mask value for asserted flags. See "_pdb_adc_pretrigger_flags". + */ +static inline uint32_t PDB_GetADCPreTriggerStatusFlags(PDB_Type *base, uint32_t channel) +{ + assert(channel < PDB_C1_COUNT); + + return base->CH[channel].S; +} + +/*! + * @brief Clears the ADC pre-trigger status flags. + * + * @param base PDB peripheral base address. + * @param channel Channel index for ADC instance. + * @param mask Mask value for flags. See "_pdb_adc_pretrigger_flags". + */ +static inline void PDB_ClearADCPreTriggerStatusFlags(PDB_Type *base, uint32_t channel, uint32_t mask) +{ + assert(channel < PDB_C1_COUNT); + + base->CH[channel].S &= ~mask; +} + +/* @} */ + +#if defined(FSL_FEATURE_PDB_HAS_DAC) && FSL_FEATURE_PDB_HAS_DAC +/*! + * @name DAC Interval Trigger + * @{ + */ + +/*! + * @brief Configures the DAC trigger in the PDB module. + * + * @param base PDB peripheral base address. + * @param channel Channel index for DAC instance. + * @param config Pointer to the configuration structure. See "pdb_dac_trigger_config_t". + */ +void PDB_SetDACTriggerConfig(PDB_Type *base, uint32_t channel, pdb_dac_trigger_config_t *config); + +/*! + * @brief Sets the value for the DAC interval event. + * + * This fucntion sets the value for DAC interval event. DAC interval trigger triggers the DAC module to update + * the buffer when the DAC interval counter is equal to the set value. + * + * @param base PDB peripheral base address. + * @param channel Channel index for DAC instance. + * @param value Setting value for the DAC interval event. + */ +static inline void PDB_SetDACTriggerIntervalValue(PDB_Type *base, uint32_t channel, uint32_t value) +{ + assert(channel < PDB_INT_COUNT); + + base->DAC[channel].INT = PDB_INT_INT(value); +} + +/* @} */ +#endif /* FSL_FEATURE_PDB_HAS_DAC */ + +/*! + * @name Pulse-Out Trigger + * @{ + */ + +/*! + * @brief Enables the pulse out trigger channels. + * + * @param base PDB peripheral base address. + * @param channelMask Channel mask value for multiple pulse out trigger channel. + * @param enable Whether the feature is enabled or not. + */ +static inline void PDB_EnablePulseOutTrigger(PDB_Type *base, uint32_t channelMask, bool enable) +{ + if (enable) + { + base->POEN |= PDB_POEN_POEN(channelMask); + } + else + { + base->POEN &= ~(PDB_POEN_POEN(channelMask)); + } +} + +/*! + * @brief Sets event values for the pulse out trigger. + * + * This function is used to set event values for the pulse output trigger. + * These pulse output trigger delay values specify the delay for the PDB Pulse-out. Pulse-out goes high when the PDB + * counter is equal to the pulse output high value (value1). Pulse-out goes low when the PDB counter is equal to the + * pulse output low value (value2). + * + * @param base PDB peripheral base address. + * @param channel Channel index for pulse out trigger channel. + * @param value1 Setting value for pulse out high. + * @param value2 Setting value for pulse out low. + */ +static inline void PDB_SetPulseOutTriggerDelayValue(PDB_Type *base, uint32_t channel, uint32_t value1, uint32_t value2) +{ + assert(channel < PDB_PODLY_COUNT); + + base->PODLY[channel] = PDB_PODLY_DLY1(value1) | PDB_PODLY_DLY2(value2); +} + +/* @} */ +#if defined(__cplusplus) +} +#endif +/*! + * @} + */ +#endif /* _FSL_PDB_H_ */ diff --git a/drivers/include/fsl_pit.h b/drivers/include/fsl_pit.h new file mode 100644 index 0000000..99c30e1 --- /dev/null +++ b/drivers/include/fsl_pit.h @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_PIT_H_ +#define _FSL_PIT_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup pit + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +#define FSL_PIT_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Version 2.0.0 */ +/*@}*/ + +/*! + * @brief List of PIT channels + * @note Actual number of available channels is SoC dependent + */ +typedef enum _pit_chnl +{ + kPIT_Chnl_0 = 0U, /*!< PIT channel number 0*/ + kPIT_Chnl_1, /*!< PIT channel number 1 */ + kPIT_Chnl_2, /*!< PIT channel number 2 */ + kPIT_Chnl_3, /*!< PIT channel number 3 */ +} pit_chnl_t; + +/*! @brief List of PIT interrupts */ +typedef enum _pit_interrupt_enable +{ + kPIT_TimerInterruptEnable = PIT_TCTRL_TIE_MASK, /*!< Timer interrupt enable*/ +} pit_interrupt_enable_t; + +/*! @brief List of PIT status flags */ +typedef enum _pit_status_flags +{ + kPIT_TimerFlag = PIT_TFLG_TIF_MASK, /*!< Timer flag */ +} pit_status_flags_t; + +/*! + * @brief PIT configuration structure + * + * This structure holds the configuration settings for the PIT peripheral. To initialize this + * structure to reasonable 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. + */ +typedef struct _pit_config +{ + bool enableRunInDebug; /*!< true: Timers run in debug mode; false: Timers stop in debug mode */ +} pit_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Ungates the PIT clock, enables the PIT module, and configures the peripheral for basic operations. + * + * @note This API should be called at the beginning of the application using the PIT driver. + * + * @param base PIT peripheral base address + * @param config Pointer to the user's PIT config structure + */ +void PIT_Init(PIT_Type *base, const pit_config_t *config); + +/*! + * @brief Gates the PIT clock and disables the PIT module. + * + * @param base PIT peripheral base address + */ +void PIT_Deinit(PIT_Type *base); + +/*! + * @brief Fills in the PIT configuration structure with the default settings. + * + * The default values are as follows. + * @code + * config->enableRunInDebug = false; + * @endcode + * @param config Pointer to the onfiguration structure. + */ +static inline void PIT_GetDefaultConfig(pit_config_t *config) +{ + assert(config); + + /* Timers are stopped in Debug mode */ + config->enableRunInDebug = false; +} + +#if defined(FSL_FEATURE_PIT_HAS_CHAIN_MODE) && FSL_FEATURE_PIT_HAS_CHAIN_MODE + +/*! + * @brief Enables or disables chaining a timer with the previous timer. + * + * 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. + * + * @param base PIT peripheral base address + * @param channel Timer channel number which is chained with the previous timer + * @param enable Enable or disable chain. + * true: Current timer is chained with the previous timer. + * false: Timer doesn't chain with other timers. + */ +static inline void PIT_SetTimerChainMode(PIT_Type *base, pit_chnl_t channel, bool enable) +{ + if (enable) + { + base->CHANNEL[channel].TCTRL |= PIT_TCTRL_CHN_MASK; + } + else + { + base->CHANNEL[channel].TCTRL &= ~PIT_TCTRL_CHN_MASK; + } +} + +#endif /* FSL_FEATURE_PIT_HAS_CHAIN_MODE */ + +/*! @}*/ + +/*! + * @name Interrupt Interface + * @{ + */ + +/*! + * @brief Enables the selected PIT interrupts. + * + * @param base PIT peripheral base address + * @param channel Timer channel number + * @param mask The interrupts to enable. This is a logical OR of members of the + * enumeration ::pit_interrupt_enable_t + */ +static inline void PIT_EnableInterrupts(PIT_Type *base, pit_chnl_t channel, uint32_t mask) +{ + base->CHANNEL[channel].TCTRL |= mask; +} + +/*! + * @brief Disables the selected PIT interrupts. + * + * @param base PIT peripheral base address + * @param channel Timer channel number + * @param mask The interrupts to disable. This is a logical OR of members of the + * enumeration ::pit_interrupt_enable_t + */ +static inline void PIT_DisableInterrupts(PIT_Type *base, pit_chnl_t channel, uint32_t mask) +{ + base->CHANNEL[channel].TCTRL &= ~mask; +} + +/*! + * @brief Gets the enabled PIT interrupts. + * + * @param base PIT peripheral base address + * @param channel Timer channel number + * + * @return The enabled interrupts. This is the logical OR of members of the + * enumeration ::pit_interrupt_enable_t + */ +static inline uint32_t PIT_GetEnabledInterrupts(PIT_Type *base, pit_chnl_t channel) +{ + return (base->CHANNEL[channel].TCTRL & PIT_TCTRL_TIE_MASK); +} + +/*! @}*/ + +/*! + * @name Status Interface + * @{ + */ + +/*! + * @brief Gets the PIT status flags. + * + * @param base PIT peripheral base address + * @param channel Timer channel number + * + * @return The status flags. This is the logical OR of members of the + * enumeration ::pit_status_flags_t + */ +static inline uint32_t PIT_GetStatusFlags(PIT_Type *base, pit_chnl_t channel) +{ + return (base->CHANNEL[channel].TFLG & PIT_TFLG_TIF_MASK); +} + +/*! + * @brief Clears the PIT status flags. + * + * @param base PIT peripheral base address + * @param channel Timer channel number + * @param mask The status flags to clear. This is a logical OR of members of the + * enumeration ::pit_status_flags_t + */ +static inline void PIT_ClearStatusFlags(PIT_Type *base, pit_chnl_t channel, uint32_t mask) +{ + base->CHANNEL[channel].TFLG = mask; +} + +/*! @}*/ + +/*! + * @name Read and Write the timer period + * @{ + */ + +/*! + * @brief Sets the timer period in units of count. + * + * 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. + * + * @param base PIT peripheral base address + * @param channel Timer channel number + * @param count Timer period in units of ticks + */ +static inline void PIT_SetTimerPeriod(PIT_Type *base, pit_chnl_t channel, uint32_t count) +{ + base->CHANNEL[channel].LDVAL = count; +} + +/*! + * @brief Reads the current timer counting value. + * + * 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. + * + * @param base PIT peripheral base address + * @param channel Timer channel number + * + * @return Current timer counting value in ticks + */ +static inline uint32_t PIT_GetCurrentTimerCount(PIT_Type *base, pit_chnl_t channel) +{ + return base->CHANNEL[channel].CVAL; +} + +/*! @}*/ + +/*! + * @name Timer Start and Stop + * @{ + */ + +/*! + * @brief Starts the timer counting. + * + * 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. + * + * @param base PIT peripheral base address + * @param channel Timer channel number. + */ +static inline void PIT_StartTimer(PIT_Type *base, pit_chnl_t channel) +{ + base->CHANNEL[channel].TCTRL |= PIT_TCTRL_TEN_MASK; +} + +/*! + * @brief Stops the timer counting. + * + * This function stops every timer counting. Timers reload their periods + * respectively after the next time they call the PIT_DRV_StartTimer. + * + * @param base PIT peripheral base address + * @param channel Timer channel number. + */ +static inline void PIT_StopTimer(PIT_Type *base, pit_chnl_t channel) +{ + base->CHANNEL[channel].TCTRL &= ~PIT_TCTRL_TEN_MASK; +} + +/*! @}*/ + +#if defined(FSL_FEATURE_PIT_HAS_LIFETIME_TIMER) && FSL_FEATURE_PIT_HAS_LIFETIME_TIMER + +/*! + * @brief Reads the current lifetime counter value. + * + * 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. + * + * @param base PIT peripheral base address + * + * @return Current lifetime timer value + */ +uint64_t PIT_GetLifetimeTimerCount(PIT_Type *base); + +#endif /* FSL_FEATURE_PIT_HAS_LIFETIME_TIMER */ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_PIT_H_ */ diff --git a/drivers/include/fsl_pmc.h b/drivers/include/fsl_pmc.h new file mode 100644 index 0000000..99fc149 --- /dev/null +++ b/drivers/include/fsl_pmc.h @@ -0,0 +1,421 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_PMC_H_ +#define _FSL_PMC_H_ + +#include "fsl_common.h" + +/*! @addtogroup pmc */ +/*! @{ */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief PMC driver version */ +#define FSL_PMC_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Version 2.0.0. */ +/*@}*/ + +#if (defined(FSL_FEATURE_PMC_HAS_LVDV) && FSL_FEATURE_PMC_HAS_LVDV) +/*! + * @brief Low-voltage Detect Voltage Select + */ +typedef enum _pmc_low_volt_detect_volt_select +{ + kPMC_LowVoltDetectLowTrip = 0U, /*!< Low-trip point selected (VLVD = VLVDL )*/ + kPMC_LowVoltDetectHighTrip = 1U /*!< High-trip point selected (VLVD = VLVDH )*/ +} pmc_low_volt_detect_volt_select_t; +#endif + +#if (defined(FSL_FEATURE_PMC_HAS_LVWV) && FSL_FEATURE_PMC_HAS_LVWV) +/*! + * @brief Low-voltage Warning Voltage Select + */ +typedef enum _pmc_low_volt_warning_volt_select +{ + kPMC_LowVoltWarningLowTrip = 0U, /*!< Low-trip point selected (VLVW = VLVW1)*/ + kPMC_LowVoltWarningMid1Trip = 1U, /*!< Mid 1 trip point selected (VLVW = VLVW2)*/ + kPMC_LowVoltWarningMid2Trip = 2U, /*!< Mid 2 trip point selected (VLVW = VLVW3)*/ + kPMC_LowVoltWarningHighTrip = 3U /*!< High-trip point selected (VLVW = VLVW4)*/ +} pmc_low_volt_warning_volt_select_t; +#endif + +#if (defined(FSL_FEATURE_PMC_HAS_HVDSC1) && FSL_FEATURE_PMC_HAS_HVDSC1) +/*! + * @brief High-voltage Detect Voltage Select + */ +typedef enum _pmc_high_volt_detect_volt_select +{ + kPMC_HighVoltDetectLowTrip = 0U, /*!< Low-trip point selected (VHVD = VHVDL )*/ + kPMC_HighVoltDetectHighTrip = 1U /*!< High-trip point selected (VHVD = VHVDH )*/ +} pmc_high_volt_detect_volt_select_t; +#endif /* FSL_FEATURE_PMC_HAS_HVDSC1 */ + +#if (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS) +/*! + * @brief Bandgap Buffer Drive Select. + */ +typedef enum _pmc_bandgap_buffer_drive_select +{ + kPMC_BandgapBufferDriveLow = 0U, /*!< Low-drive. */ + kPMC_BandgapBufferDriveHigh = 1U /*!< High-drive. */ +} pmc_bandgap_buffer_drive_select_t; +#endif /* FSL_FEATURE_PMC_HAS_BGBDS */ + +#if (defined(FSL_FEATURE_PMC_HAS_VLPO) && FSL_FEATURE_PMC_HAS_VLPO) +/*! + * @brief VLPx Option + */ +typedef enum _pmc_vlp_freq_option +{ + kPMC_FreqRestrict = 0U, /*!< Frequency is restricted in VLPx mode. */ + kPMC_FreqUnrestrict = 1U /*!< Frequency is unrestricted in VLPx mode. */ +} pmc_vlp_freq_mode_t; +#endif /* FSL_FEATURE_PMC_HAS_VLPO */ + +#if (defined(FSL_FEATURE_PMC_HAS_VERID) && FSL_FEATURE_PMC_HAS_VERID) +/*! + @brief IP version ID definition. + */ +typedef struct _pmc_version_id +{ + uint16_t feature; /*!< Feature Specification Number. */ + uint8_t minor; /*!< Minor version number. */ + uint8_t major; /*!< Major version number. */ +} pmc_version_id_t; +#endif /* FSL_FEATURE_PMC_HAS_VERID */ + +#if (defined(FSL_FEATURE_PMC_HAS_PARAM) && FSL_FEATURE_PMC_HAS_PARAM) +/*! @brief IP parameter definition. */ +typedef struct _pmc_param +{ + bool vlpoEnable; /*!< VLPO enable. */ + bool hvdEnable; /*!< HVD enable. */ +} pmc_param_t; +#endif /* FSL_FEATURE_PMC_HAS_PARAM */ + +/*! + * @brief Low-voltage Detect Configuration Structure + */ +typedef struct _pmc_low_volt_detect_config +{ + bool enableInt; /*!< Enable interrupt when Low-voltage detect*/ + bool enableReset; /*!< Enable system reset when Low-voltage detect*/ +#if (defined(FSL_FEATURE_PMC_HAS_LVDV) && FSL_FEATURE_PMC_HAS_LVDV) + pmc_low_volt_detect_volt_select_t voltSelect; /*!< Low-voltage detect trip point voltage selection*/ +#endif +} pmc_low_volt_detect_config_t; + +/*! + * @brief Low-voltage Warning Configuration Structure + */ +typedef struct _pmc_low_volt_warning_config +{ + bool enableInt; /*!< Enable interrupt when low-voltage warning*/ +#if (defined(FSL_FEATURE_PMC_HAS_LVWV) && FSL_FEATURE_PMC_HAS_LVWV) + pmc_low_volt_warning_volt_select_t voltSelect; /*!< Low-voltage warning trip point voltage selection*/ +#endif +} pmc_low_volt_warning_config_t; + +#if (defined(FSL_FEATURE_PMC_HAS_HVDSC1) && FSL_FEATURE_PMC_HAS_HVDSC1) +/*! + * @brief High-voltage Detect Configuration Structure + */ +typedef struct _pmc_high_volt_detect_config +{ + bool enableInt; /*!< Enable interrupt when high-voltage detect*/ + bool enableReset; /*!< Enable system reset when high-voltage detect*/ + pmc_high_volt_detect_volt_select_t voltSelect; /*!< High-voltage detect trip point voltage selection*/ +} pmc_high_volt_detect_config_t; +#endif /* FSL_FEATURE_PMC_HAS_HVDSC1 */ + +#if ((defined(FSL_FEATURE_PMC_HAS_BGBE) && FSL_FEATURE_PMC_HAS_BGBE) || \ + (defined(FSL_FEATURE_PMC_HAS_BGEN) && FSL_FEATURE_PMC_HAS_BGEN) || \ + (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS)) +/*! + * @brief Bandgap Buffer configuration. + */ +typedef struct _pmc_bandgap_buffer_config +{ +#if (defined(FSL_FEATURE_PMC_HAS_BGBE) && FSL_FEATURE_PMC_HAS_BGBE) + bool enable; /*!< Enable bandgap buffer. */ +#endif +#if (defined(FSL_FEATURE_PMC_HAS_BGEN) && FSL_FEATURE_PMC_HAS_BGEN) + bool enableInLowPowerMode; /*!< Enable bandgap buffer in low-power mode. */ +#endif /* FSL_FEATURE_PMC_HAS_BGEN */ +#if (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS) + pmc_bandgap_buffer_drive_select_t drive; /*!< Bandgap buffer drive select. */ +#endif /* FSL_FEATURE_PMC_HAS_BGBDS */ +} pmc_bandgap_buffer_config_t; +#endif + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +/*! @name Power Management Controller Control APIs*/ +/*@{*/ + +#if (defined(FSL_FEATURE_PMC_HAS_VERID) && FSL_FEATURE_PMC_HAS_VERID) +/*! + * @brief Gets the PMC version ID. + * + * This function gets the PMC version ID, including major version number, + * minor version number, and a feature specification number. + * + * @param base PMC peripheral base address. + * @param versionId Pointer to version ID structure. + */ +static inline void PMC_GetVersionId(PMC_Type *base, pmc_version_id_t *versionId) +{ + *((uint32_t *)versionId) = base->VERID; +} +#endif /* FSL_FEATURE_PMC_HAS_VERID */ + +#if (defined(FSL_FEATURE_PMC_HAS_PARAM) && FSL_FEATURE_PMC_HAS_PARAM) +/*! + * @brief Gets the PMC parameter. + * + * This function gets the PMC parameter including the VLPO enable and the HVD enable. + * + * @param base PMC peripheral base address. + * @param param Pointer to PMC param structure. + */ +void PMC_GetParam(PMC_Type *base, pmc_param_t *param); +#endif + +/*! + * @brief Configures the low-voltage detect setting. + * + * 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. + * + * @param base PMC peripheral base address. + * @param config Low-voltage detect configuration structure. + */ +void PMC_ConfigureLowVoltDetect(PMC_Type *base, const pmc_low_volt_detect_config_t *config); + +/*! + * @brief Gets the Low-voltage Detect Flag status. + * + * This function reads the current LVDF status. If it returns 1, a low-voltage event is detected. + * + * @param base PMC peripheral base address. + * @return Current low-voltage detect flag + * - true: Low-voltage detected + * - false: Low-voltage not detected + */ +static inline bool PMC_GetLowVoltDetectFlag(PMC_Type *base) +{ + return (bool)(base->LVDSC1 & PMC_LVDSC1_LVDF_MASK); +} + +/*! + * @brief Acknowledges clearing the Low-voltage Detect flag. + * + * This function acknowledges the low-voltage detection errors (write 1 to + * clear LVDF). + * + * @param base PMC peripheral base address. + */ +static inline void PMC_ClearLowVoltDetectFlag(PMC_Type *base) +{ + base->LVDSC1 |= PMC_LVDSC1_LVDACK_MASK; +} + +/*! + * @brief Configures the low-voltage warning setting. + * + * This function configures the low-voltage warning setting, including the trip + * point voltage setting and enabling or disabling the interrupt. + * + * @param base PMC peripheral base address. + * @param config Low-voltage warning configuration structure. + */ +void PMC_ConfigureLowVoltWarning(PMC_Type *base, const pmc_low_volt_warning_config_t *config); + +/*! + * @brief Gets the Low-voltage Warning Flag status. + * + * 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. + * + * @param base PMC peripheral base address. + * @return Current LVWF status + * - true: Low-voltage Warning Flag is set. + * - false: the Low-voltage Warning does not happen. + */ +static inline bool PMC_GetLowVoltWarningFlag(PMC_Type *base) +{ + return (bool)(base->LVDSC2 & PMC_LVDSC2_LVWF_MASK); +} + +/*! + * @brief Acknowledges the Low-voltage Warning flag. + * + * This function acknowledges the low voltage warning errors (write 1 to + * clear LVWF). + * + * @param base PMC peripheral base address. + */ +static inline void PMC_ClearLowVoltWarningFlag(PMC_Type *base) +{ + base->LVDSC2 |= PMC_LVDSC2_LVWACK_MASK; +} + +#if (defined(FSL_FEATURE_PMC_HAS_HVDSC1) && FSL_FEATURE_PMC_HAS_HVDSC1) +/*! + * @brief Configures the high-voltage detect setting. + * + * This function configures the high-voltage detect setting, including the trip + * point voltage setting, enabling or disabling the interrupt, enabling or disabling the system reset. + * + * @param base PMC peripheral base address. + * @param config High-voltage detect configuration structure. + */ +void PMC_ConfigureHighVoltDetect(PMC_Type *base, const pmc_high_volt_detect_config_t *config); + +/*! + * @brief Gets the High-voltage Detect Flag status. + * + * This function reads the current HVDF status. If it returns 1, a low + * voltage event is detected. + * + * @param base PMC peripheral base address. + * @return Current high-voltage detect flag + * - true: High-voltage detected + * - false: High-voltage not detected + */ +static inline bool PMC_GetHighVoltDetectFlag(PMC_Type *base) +{ + return (bool)(base->HVDSC1 & PMC_HVDSC1_HVDF_MASK); +} + +/*! + * @brief Acknowledges clearing the High-voltage Detect flag. + * + * This function acknowledges the high-voltage detection errors (write 1 to + * clear HVDF). + * + * @param base PMC peripheral base address. + */ +static inline void PMC_ClearHighVoltDetectFlag(PMC_Type *base) +{ + base->HVDSC1 |= PMC_HVDSC1_HVDACK_MASK; +} +#endif /* FSL_FEATURE_PMC_HAS_HVDSC1 */ + +#if ((defined(FSL_FEATURE_PMC_HAS_BGBE) && FSL_FEATURE_PMC_HAS_BGBE) || \ + (defined(FSL_FEATURE_PMC_HAS_BGEN) && FSL_FEATURE_PMC_HAS_BGEN) || \ + (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS)) +/*! + * @brief Configures the PMC bandgap. + * + * This function configures the PMC bandgap, including the drive select and + * behavior in low-power mode. + * + * @param base PMC peripheral base address. + * @param config Pointer to the configuration structure + */ +void PMC_ConfigureBandgapBuffer(PMC_Type *base, const pmc_bandgap_buffer_config_t *config); +#endif + +#if (defined(FSL_FEATURE_PMC_HAS_ACKISO) && FSL_FEATURE_PMC_HAS_ACKISO) +/*! + * @brief Gets the acknowledge Peripherals and I/O pads isolation flag. + * + * 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. + * + * @param base PMC peripheral base address. + * @param base Base address for current PMC instance. + * @return 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. + */ +static inline bool PMC_GetPeriphIOIsolationFlag(PMC_Type *base) +{ + return (bool)(base->REGSC & PMC_REGSC_ACKISO_MASK); +} + +/*! + * @brief Acknowledges the isolation flag to Peripherals and I/O pads. + * + * 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. + * + * @param base PMC peripheral base address. + */ +static inline void PMC_ClearPeriphIOIsolationFlag(PMC_Type *base) +{ + base->REGSC |= PMC_REGSC_ACKISO_MASK; +} +#endif /* FSL_FEATURE_PMC_HAS_ACKISO */ + +#if (defined(FSL_FEATURE_PMC_HAS_REGONS) && FSL_FEATURE_PMC_HAS_REGONS) +/*! + * @brief Gets the regulator regulation status. + * + * This function returns the regulator to run a regulation status. It provides + * the current status of the internal voltage regulator. + * + * @param base PMC peripheral base address. + * @param base Base address for current PMC instance. + * @return Regulation status + * 0 - Regulator is in a stop regulation or in transition to/from the regulation. + * 1 - Regulator is in a run regulation. + * + */ +static inline bool PMC_IsRegulatorInRunRegulation(PMC_Type *base) +{ + return (bool)(base->REGSC & PMC_REGSC_REGONS_MASK); +} +#endif /* FSL_FEATURE_PMC_HAS_REGONS */ + +/*@}*/ + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +/*! @}*/ + +#endif /* _FSL_PMC_H_*/ diff --git a/drivers/include/fsl_port.h b/drivers/include/fsl_port.h new file mode 100644 index 0000000..eb8e77e --- /dev/null +++ b/drivers/include/fsl_port.h @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_PORT_H_ +#define _FSL_PORT_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup port + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! Version 2.0.2. */ +#define FSL_PORT_DRIVER_VERSION (MAKE_VERSION(2, 0, 2)) +/*@}*/ + +#if defined(FSL_FEATURE_PORT_HAS_PULL_ENABLE) && FSL_FEATURE_PORT_HAS_PULL_ENABLE +/*! @brief Internal resistor pull feature selection */ +enum _port_pull +{ + kPORT_PullDisable = 0U, /*!< Internal pull-up/down resistor is disabled. */ + kPORT_PullDown = 2U, /*!< Internal pull-down resistor is enabled. */ + kPORT_PullUp = 3U, /*!< Internal pull-up resistor is enabled. */ +}; +#endif /* FSL_FEATURE_PORT_HAS_PULL_ENABLE */ + +#if defined(FSL_FEATURE_PORT_HAS_SLEW_RATE) && FSL_FEATURE_PORT_HAS_SLEW_RATE +/*! @brief Slew rate selection */ +enum _port_slew_rate +{ + kPORT_FastSlewRate = 0U, /*!< Fast slew rate is configured. */ + kPORT_SlowSlewRate = 1U, /*!< Slow slew rate is configured. */ +}; +#endif /* FSL_FEATURE_PORT_HAS_SLEW_RATE */ + +#if defined(FSL_FEATURE_PORT_HAS_OPEN_DRAIN) && FSL_FEATURE_PORT_HAS_OPEN_DRAIN +/*! @brief Open Drain feature enable/disable */ +enum _port_open_drain_enable +{ + kPORT_OpenDrainDisable = 0U, /*!< Open drain output is disabled. */ + kPORT_OpenDrainEnable = 1U, /*!< Open drain output is enabled. */ +}; +#endif /* FSL_FEATURE_PORT_HAS_OPEN_DRAIN */ + +#if defined(FSL_FEATURE_PORT_HAS_PASSIVE_FILTER) && FSL_FEATURE_PORT_HAS_PASSIVE_FILTER +/*! @brief Passive filter feature enable/disable */ +enum _port_passive_filter_enable +{ + kPORT_PassiveFilterDisable = 0U, /*!< Passive input filter is disabled. */ + kPORT_PassiveFilterEnable = 1U, /*!< Passive input filter is enabled. */ +}; +#endif + +#if defined(FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH) && FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH +/*! @brief Configures the drive strength. */ +enum _port_drive_strength +{ + kPORT_LowDriveStrength = 0U, /*!< Low-drive strength is configured. */ + kPORT_HighDriveStrength = 1U, /*!< High-drive strength is configured. */ +}; +#endif /* FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH */ + +#if defined(FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK) && FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK +/*! @brief Unlock/lock the pin control register field[15:0] */ +enum _port_lock_register +{ + kPORT_UnlockRegister = 0U, /*!< Pin Control Register fields [15:0] are not locked. */ + kPORT_LockRegister = 1U, /*!< Pin Control Register fields [15:0] are locked. */ +}; +#endif /* FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK */ + +#if defined(FSL_FEATURE_PORT_PCR_MUX_WIDTH) && FSL_FEATURE_PORT_PCR_MUX_WIDTH +/*! @brief Pin mux selection */ +typedef enum _port_mux +{ + kPORT_PinDisabledOrAnalog = 0U, /*!< Corresponding pin is disabled, but is used as an analog pin. */ + kPORT_MuxAsGpio = 1U, /*!< Corresponding pin is configured as GPIO. */ + kPORT_MuxAlt2 = 2U, /*!< Chip-specific */ + kPORT_MuxAlt3 = 3U, /*!< Chip-specific */ + kPORT_MuxAlt4 = 4U, /*!< Chip-specific */ + kPORT_MuxAlt5 = 5U, /*!< Chip-specific */ + kPORT_MuxAlt6 = 6U, /*!< Chip-specific */ + kPORT_MuxAlt7 = 7U, /*!< Chip-specific */ + kPORT_MuxAlt8 = 8U, /*!< Chip-specific */ + kPORT_MuxAlt9 = 9U, /*!< Chip-specific */ + kPORT_MuxAlt10 = 10U, /*!< Chip-specific */ + kPORT_MuxAlt11 = 11U, /*!< Chip-specific */ + kPORT_MuxAlt12 = 12U, /*!< Chip-specific */ + kPORT_MuxAlt13 = 13U, /*!< Chip-specific */ + kPORT_MuxAlt14 = 14U, /*!< Chip-specific */ + kPORT_MuxAlt15 = 15U, /*!< Chip-specific */ +} port_mux_t; +#endif /* FSL_FEATURE_PORT_PCR_MUX_WIDTH */ + +/*! @brief Configures the interrupt generation condition. */ +typedef enum _port_interrupt +{ + kPORT_InterruptOrDMADisabled = 0x0U, /*!< Interrupt/DMA request is disabled. */ +#if defined(FSL_FEATURE_PORT_HAS_DMA_REQUEST) && FSL_FEATURE_PORT_HAS_DMA_REQUEST + kPORT_DMARisingEdge = 0x1U, /*!< DMA request on rising edge. */ + kPORT_DMAFallingEdge = 0x2U, /*!< DMA request on falling edge. */ + kPORT_DMAEitherEdge = 0x3U, /*!< DMA request on either edge. */ +#endif +#if defined(FSL_FEATURE_PORT_HAS_IRQC_FLAG) && FSL_FEATURE_PORT_HAS_IRQC_FLAG + kPORT_FlagRisingEdge = 0x05U, /*!< Flag sets on rising edge. */ + kPORT_FlagFallingEdge = 0x06U, /*!< Flag sets on falling edge. */ + kPORT_FlagEitherEdge = 0x07U, /*!< Flag sets on either edge. */ +#endif + kPORT_InterruptLogicZero = 0x8U, /*!< Interrupt when logic zero. */ + kPORT_InterruptRisingEdge = 0x9U, /*!< Interrupt on rising edge. */ + kPORT_InterruptFallingEdge = 0xAU, /*!< Interrupt on falling edge. */ + kPORT_InterruptEitherEdge = 0xBU, /*!< Interrupt on either edge. */ + kPORT_InterruptLogicOne = 0xCU, /*!< Interrupt when logic one. */ +#if defined(FSL_FEATURE_PORT_HAS_IRQC_TRIGGER) && FSL_FEATURE_PORT_HAS_IRQC_TRIGGER + kPORT_ActiveHighTriggerOutputEnable = 0xDU, /*!< Enable active high-trigger output. */ + kPORT_ActiveLowTriggerOutputEnable = 0xEU, /*!< Enable active low-trigger output. */ +#endif +} port_interrupt_t; + +#if defined(FSL_FEATURE_PORT_HAS_DIGITAL_FILTER) && FSL_FEATURE_PORT_HAS_DIGITAL_FILTER +/*! @brief Digital filter clock source selection */ +typedef enum _port_digital_filter_clock_source +{ + kPORT_BusClock = 0U, /*!< Digital filters are clocked by the bus clock. */ + kPORT_LpoClock = 1U, /*!< Digital filters are clocked by the 1 kHz LPO clock. */ +} port_digital_filter_clock_source_t; + +/*! @brief PORT digital filter feature configuration definition */ +typedef struct _port_digital_filter_config +{ + uint32_t digitalFilterWidth; /*!< Set digital filter width */ + port_digital_filter_clock_source_t clockSource; /*!< Set digital filter clockSource */ +} port_digital_filter_config_t; +#endif /* FSL_FEATURE_PORT_HAS_DIGITAL_FILTER */ + +#if defined(FSL_FEATURE_PORT_PCR_MUX_WIDTH) && FSL_FEATURE_PORT_PCR_MUX_WIDTH +/*! @brief PORT pin configuration structure */ +typedef struct _port_pin_config +{ +#if defined(FSL_FEATURE_PORT_HAS_PULL_ENABLE) && FSL_FEATURE_PORT_HAS_PULL_ENABLE + uint16_t pullSelect : 2; /*!< No-pull/pull-down/pull-up select */ +#else + uint16_t : 2; +#endif /* FSL_FEATURE_PORT_HAS_PULL_ENABLE */ + +#if defined(FSL_FEATURE_PORT_HAS_SLEW_RATE) && FSL_FEATURE_PORT_HAS_SLEW_RATE + uint16_t slewRate : 1; /*!< Fast/slow slew rate Configure */ +#else + uint16_t : 1; +#endif /* FSL_FEATURE_PORT_HAS_SLEW_RATE */ + + uint16_t : 1; + +#if defined(FSL_FEATURE_PORT_HAS_PASSIVE_FILTER) && FSL_FEATURE_PORT_HAS_PASSIVE_FILTER + uint16_t passiveFilterEnable : 1; /*!< Passive filter enable/disable */ +#else + uint16_t : 1; +#endif /* FSL_FEATURE_PORT_HAS_PASSIVE_FILTER */ + +#if defined(FSL_FEATURE_PORT_HAS_OPEN_DRAIN) && FSL_FEATURE_PORT_HAS_OPEN_DRAIN + uint16_t openDrainEnable : 1; /*!< Open drain enable/disable */ +#else + uint16_t : 1; +#endif /* FSL_FEATURE_PORT_HAS_OPEN_DRAIN */ + +#if defined(FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH) && FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH + uint16_t driveStrength : 1; /*!< Fast/slow drive strength configure */ +#else + uint16_t : 1; +#endif + + uint16_t : 1; + +#if defined(FSL_FEATURE_PORT_PCR_MUX_WIDTH) && FSL_FEATURE_PORT_PCR_MUX_WIDTH + uint16_t mux : 3; /*!< Pin mux Configure */ +#else + uint16_t : 3; +#endif + + uint16_t : 4; + +#if defined(FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK) && FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK + uint16_t lockRegister : 1; /*!< Lock/unlock the PCR field[15:0] */ +#else + uint16_t : 1; +#endif /* FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK */ +} port_pin_config_t; +#endif /* FSL_FEATURE_PORT_PCR_MUX_WIDTH */ + +/******************************************************************************* +* API +******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +#if defined(FSL_FEATURE_PORT_PCR_MUX_WIDTH) && FSL_FEATURE_PORT_PCR_MUX_WIDTH +/*! @name Configuration */ +/*@{*/ + +/*! + * @brief Sets the port PCR register. + * + * This is an example to define an input pin or output pin PCR configuration. + * @code + * // Define a digital input pin PCR configuration + * port_pin_config_t config = { + * kPORT_PullUp, + * kPORT_FastSlewRate, + * kPORT_PassiveFilterDisable, + * kPORT_OpenDrainDisable, + * kPORT_LowDriveStrength, + * kPORT_MuxAsGpio, + * kPORT_UnLockRegister, + * }; + * @endcode + * + * @param base PORT peripheral base pointer. + * @param pin PORT pin number. + * @param config PORT PCR register configuration structure. + */ +static inline void PORT_SetPinConfig(PORT_Type *base, uint32_t pin, const port_pin_config_t *config) +{ + assert(config); + uint32_t addr = (uint32_t)&base->PCR[pin]; + *(volatile uint16_t *)(addr) = *((const uint16_t *)config); +} + +/*! + * @brief Sets the port PCR register for multiple pins. + * + * This is an example to define input pins or output pins PCR configuration. + * @code + * // Define a digital input pin PCR configuration + * port_pin_config_t config = { + * kPORT_PullUp , + * kPORT_PullEnable, + * kPORT_FastSlewRate, + * kPORT_PassiveFilterDisable, + * kPORT_OpenDrainDisable, + * kPORT_LowDriveStrength, + * kPORT_MuxAsGpio, + * kPORT_UnlockRegister, + * }; + * @endcode + * + * @param base PORT peripheral base pointer. + * @param mask PORT pin number macro. + * @param config PORT PCR register configuration structure. + */ +static inline void PORT_SetMultiplePinsConfig(PORT_Type *base, uint32_t mask, const port_pin_config_t *config) +{ + assert(config); + + uint16_t pcrl = *((const uint16_t *)config); + + if (mask & 0xffffU) + { + base->GPCLR = ((mask & 0xffffU) << 16) | pcrl; + } + if (mask >> 16) + { + base->GPCHR = (mask & 0xffff0000U) | pcrl; + } +} + +/*! + * @brief Configures the pin muxing. + * + * @param base PORT peripheral base pointer. + * @param pin PORT pin number. + * @param mux pin muxing slot selection. + * - #kPORT_PinDisabledOrAnalog: Pin disabled or work in analog function. + * - #kPORT_MuxAsGpio : Set 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. + * @Note : This function is NOT recommended to use together with the PORT_SetPinsConfig, because + * the PORT_SetPinsConfig need to configure the pin mux anyway (Otherwise the pin mux is + * reset to zero : kPORT_PinDisabledOrAnalog). + * This function is recommended to use to reset the pin mux + * + */ +static inline void PORT_SetPinMux(PORT_Type *base, uint32_t pin, port_mux_t mux) +{ + base->PCR[pin] = (base->PCR[pin] & ~PORT_PCR_MUX_MASK) | PORT_PCR_MUX(mux); +} +#endif /* FSL_FEATURE_PORT_PCR_MUX_WIDTH */ + +#if defined(FSL_FEATURE_PORT_HAS_DIGITAL_FILTER) && FSL_FEATURE_PORT_HAS_DIGITAL_FILTER + +/*! + * @brief Enables the digital filter in one port, each bit of the 32-bit register represents one pin. + * + * @param base PORT peripheral base pointer. + * @param mask PORT pin number macro. + */ +static inline void PORT_EnablePinsDigitalFilter(PORT_Type *base, uint32_t mask, bool enable) +{ + if (enable == true) + { + base->DFER |= mask; + } + else + { + base->DFER &= ~mask; + } +} + +/*! + * @brief Sets the digital filter in one port, each bit of the 32-bit register represents one pin. + * + * @param base PORT peripheral base pointer. + * @param config PORT digital filter configuration structure. + */ +static inline void PORT_SetDigitalFilterConfig(PORT_Type *base, const port_digital_filter_config_t *config) +{ + assert(config); + + base->DFCR = PORT_DFCR_CS(config->clockSource); + base->DFWR = PORT_DFWR_FILT(config->digitalFilterWidth); +} + +#endif /* FSL_FEATURE_PORT_HAS_DIGITAL_FILTER */ + +/*@}*/ + +/*! @name Interrupt */ +/*@{*/ + +/*! + * @brief Configures the port pin interrupt/DMA request. + * + * @param base PORT peripheral base pointer. + * @param pin PORT pin number. + * @param config PORT pin interrupt configuration. + * - #kPORT_InterruptOrDMADisabled: Interrupt/DMA request disabled. + * - #kPORT_DMARisingEdge : DMA request on rising edge(if the DMA requests exit). + * - #kPORT_DMAFallingEdge: DMA request on falling edge(if the DMA requests exit). + * - #kPORT_DMAEitherEdge : DMA request on either edge(if the DMA requests exit). + * - #kPORT_FlagRisingEdge : Flag sets on rising edge(if the Flag states exit). + * - #kPORT_FlagFallingEdge : Flag sets on falling edge(if the Flag states exit). + * - #kPORT_FlagEitherEdge : Flag sets on either edge(if the Flag states exit). + * - #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. + * - #kPORT_ActiveHighTriggerOutputEnable : Enable active high-trigger output (if the trigger states exit). + * - #kPORT_ActiveLowTriggerOutputEnable : Enable active low-trigger output (if the trigger states exit). + */ +static inline void PORT_SetPinInterruptConfig(PORT_Type *base, uint32_t pin, port_interrupt_t config) +{ + base->PCR[pin] = (base->PCR[pin] & ~PORT_PCR_IRQC_MASK) | PORT_PCR_IRQC(config); +} + +/*! + * @brief Reads the whole port status flag. + * + * 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. + * + * @param base PORT peripheral base pointer. + * @return Current port interrupt status flags, for example, 0x00010001 means the + * pin 0 and 16 have the interrupt. + */ +static inline uint32_t PORT_GetPinsInterruptFlags(PORT_Type *base) +{ + return base->ISFR; +} + +/*! + * @brief Clears the multiple pin interrupt status flag. + * + * @param base PORT peripheral base pointer. + * @param mask PORT pin number macro. + */ +static inline void PORT_ClearPinsInterruptFlags(PORT_Type *base, uint32_t mask) +{ + base->ISFR = mask; +} + +/*@}*/ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_PORT_H_ */ diff --git a/drivers/include/fsl_rcm.h b/drivers/include/fsl_rcm.h new file mode 100644 index 0000000..99b843a --- /dev/null +++ b/drivers/include/fsl_rcm.h @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_RCM_H_ +#define _FSL_RCM_H_ + +#include "fsl_common.h" + +/*! @addtogroup rcm */ +/*! @{*/ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief RCM driver version 2.0.1. */ +#define FSL_RCM_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) +/*@}*/ + +/*! + * @brief System Reset Source Name definitions + */ +typedef enum _rcm_reset_source +{ +#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) +/* RCM register bit width is 32. */ +#if (defined(FSL_FEATURE_RCM_HAS_WAKEUP) && FSL_FEATURE_RCM_HAS_WAKEUP) + kRCM_SourceWakeup = RCM_SRS_WAKEUP_MASK, /*!< Low-leakage wakeup reset */ +#endif + kRCM_SourceLvd = RCM_SRS_LVD_MASK, /*!< Low-voltage detect reset */ +#if (defined(FSL_FEATURE_RCM_HAS_LOC) && FSL_FEATURE_RCM_HAS_LOC) + kRCM_SourceLoc = RCM_SRS_LOC_MASK, /*!< Loss of clock reset */ +#endif /* FSL_FEATURE_RCM_HAS_LOC */ +#if (defined(FSL_FEATURE_RCM_HAS_LOL) && FSL_FEATURE_RCM_HAS_LOL) + kRCM_SourceLol = RCM_SRS_LOL_MASK, /*!< Loss of lock reset */ +#endif /* FSL_FEATURE_RCM_HAS_LOL */ + kRCM_SourceWdog = RCM_SRS_WDOG_MASK, /*!< Watchdog reset */ + kRCM_SourcePin = RCM_SRS_PIN_MASK, /*!< External pin reset */ + kRCM_SourcePor = RCM_SRS_POR_MASK, /*!< Power on reset */ +#if (defined(FSL_FEATURE_RCM_HAS_JTAG) && FSL_FEATURE_RCM_HAS_JTAG) + kRCM_SourceJtag = RCM_SRS_JTAG_MASK, /*!< JTAG generated reset */ +#endif /* FSL_FEATURE_RCM_HAS_JTAG */ + kRCM_SourceLockup = RCM_SRS_LOCKUP_MASK, /*!< Core lock up reset */ + kRCM_SourceSw = RCM_SRS_SW_MASK, /*!< Software reset */ +#if (defined(FSL_FEATURE_RCM_HAS_MDM_AP) && FSL_FEATURE_RCM_HAS_MDM_AP) + kRCM_SourceMdmap = RCM_SRS_MDM_AP_MASK, /*!< MDM-AP system reset */ +#endif /* FSL_FEATURE_RCM_HAS_MDM_AP */ +#if (defined(FSL_FEATURE_RCM_HAS_EZPORT) && FSL_FEATURE_RCM_HAS_EZPORT) + kRCM_SourceEzpt = RCM_SRS_EZPT_MASK, /*!< EzPort reset */ +#endif /* FSL_FEATURE_RCM_HAS_EZPORT */ + kRCM_SourceSackerr = RCM_SRS_SACKERR_MASK, /*!< Parameter could get all reset flags */ + +#else /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ +/* RCM register bit width is 8. */ +#if (defined(FSL_FEATURE_RCM_HAS_WAKEUP) && FSL_FEATURE_RCM_HAS_WAKEUP) + kRCM_SourceWakeup = RCM_SRS0_WAKEUP_MASK, /*!< Low-leakage wakeup reset */ +#endif + kRCM_SourceLvd = RCM_SRS0_LVD_MASK, /*!< Low-voltage detect reset */ +#if (defined(FSL_FEATURE_RCM_HAS_LOC) && FSL_FEATURE_RCM_HAS_LOC) + kRCM_SourceLoc = RCM_SRS0_LOC_MASK, /*!< Loss of clock reset */ +#endif /* FSL_FEATURE_RCM_HAS_LOC */ +#if (defined(FSL_FEATURE_RCM_HAS_LOL) && FSL_FEATURE_RCM_HAS_LOL) + kRCM_SourceLol = RCM_SRS0_LOL_MASK, /*!< Loss of lock reset */ +#endif /* FSL_FEATURE_RCM_HAS_LOL */ + kRCM_SourceWdog = RCM_SRS0_WDOG_MASK, /*!< Watchdog reset */ + kRCM_SourcePin = RCM_SRS0_PIN_MASK, /*!< External pin reset */ + kRCM_SourcePor = RCM_SRS0_POR_MASK, /*!< Power on reset */ +#if (defined(FSL_FEATURE_RCM_HAS_JTAG) && FSL_FEATURE_RCM_HAS_JTAG) + kRCM_SourceJtag = RCM_SRS1_JTAG_MASK << 8U, /*!< JTAG generated reset */ +#endif /* FSL_FEATURE_RCM_HAS_JTAG */ + kRCM_SourceLockup = RCM_SRS1_LOCKUP_MASK << 8U, /*!< Core lock up reset */ + kRCM_SourceSw = RCM_SRS1_SW_MASK << 8U, /*!< Software reset */ +#if (defined(FSL_FEATURE_RCM_HAS_MDM_AP) && FSL_FEATURE_RCM_HAS_MDM_AP) + kRCM_SourceMdmap = RCM_SRS1_MDM_AP_MASK << 8U, /*!< MDM-AP system reset */ +#endif /* FSL_FEATURE_RCM_HAS_MDM_AP */ +#if (defined(FSL_FEATURE_RCM_HAS_EZPORT) && FSL_FEATURE_RCM_HAS_EZPORT) + kRCM_SourceEzpt = RCM_SRS1_EZPT_MASK << 8U, /*!< EzPort reset */ +#endif /* FSL_FEATURE_RCM_HAS_EZPORT */ + kRCM_SourceSackerr = RCM_SRS1_SACKERR_MASK << 8U, /*!< Parameter could get all reset flags */ +#endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ + kRCM_SourceAll = 0xffffffffU, +} rcm_reset_source_t; + +/*! + * @brief Reset pin filter select in Run and Wait modes. + */ +typedef enum _rcm_run_wait_filter_mode +{ + kRCM_FilterDisable = 0U, /*!< All filtering disabled */ + kRCM_FilterBusClock = 1U, /*!< Bus clock filter enabled */ + kRCM_FilterLpoClock = 2U /*!< LPO clock filter enabled */ +} rcm_run_wait_filter_mode_t; + +#if (defined(FSL_FEATURE_RCM_HAS_BOOTROM) && FSL_FEATURE_RCM_HAS_BOOTROM) +/*! + * @brief Boot from ROM configuration. + */ +typedef enum _rcm_boot_rom_config +{ + kRCM_BootFlash = 0U, /*!< Boot from flash */ + kRCM_BootRomCfg0 = 1U, /*!< Boot from boot ROM due to BOOTCFG0 */ + kRCM_BootRomFopt = 2U, /*!< Boot from boot ROM due to FOPT[7] */ + kRCM_BootRomBoth = 3U /*!< Boot from boot ROM due to both BOOTCFG0 and FOPT[7] */ +} rcm_boot_rom_config_t; +#endif /* FSL_FEATURE_RCM_HAS_BOOTROM */ + +#if (defined(FSL_FEATURE_RCM_HAS_SRIE) && FSL_FEATURE_RCM_HAS_SRIE) +/*! + * @brief Maximum delay time from interrupt asserts to system reset. + */ +typedef enum _rcm_reset_delay +{ + kRCM_ResetDelay8Lpo = 0U, /*!< Delay 8 LPO cycles. */ + kRCM_ResetDelay32Lpo = 1U, /*!< Delay 32 LPO cycles. */ + kRCM_ResetDelay128Lpo = 2U, /*!< Delay 128 LPO cycles. */ + kRCM_ResetDelay512Lpo = 3U /*!< Delay 512 LPO cycles. */ +} rcm_reset_delay_t; + +/*! + * @brief System reset interrupt enable bit definitions. + */ +typedef enum _rcm_interrupt_enable +{ + kRCM_IntNone = 0U, /*!< No interrupt enabled. */ + kRCM_IntLossOfClk = RCM_SRIE_LOC_MASK, /*!< Loss of clock interrupt. */ + kRCM_IntLossOfLock = RCM_SRIE_LOL_MASK, /*!< Loss of lock interrupt. */ + kRCM_IntWatchDog = RCM_SRIE_WDOG_MASK, /*!< Watch dog interrupt. */ + kRCM_IntExternalPin = RCM_SRIE_PIN_MASK, /*!< External pin interrupt. */ + kRCM_IntGlobal = RCM_SRIE_GIE_MASK, /*!< Global interrupts. */ + kRCM_IntCoreLockup = RCM_SRIE_LOCKUP_MASK, /*!< Core lock up interrupt */ + kRCM_IntSoftware = RCM_SRIE_SW_MASK, /*!< software interrupt */ + kRCM_IntStopModeAckErr = RCM_SRIE_SACKERR_MASK, /*!< Stop mode ACK error interrupt. */ +#if (defined(FSL_FEATURE_RCM_HAS_CORE1) && FSL_FEATURE_RCM_HAS_CORE1) + kRCM_IntCore1 = RCM_SRIE_CORE1_MASK, /*!< Core 1 interrupt. */ +#endif + kRCM_IntAll = RCM_SRIE_LOC_MASK /*!< Enable all interrupts. */ + | + RCM_SRIE_LOL_MASK | RCM_SRIE_WDOG_MASK | RCM_SRIE_PIN_MASK | RCM_SRIE_GIE_MASK | + RCM_SRIE_LOCKUP_MASK | RCM_SRIE_SW_MASK | RCM_SRIE_SACKERR_MASK +#if (defined(FSL_FEATURE_RCM_HAS_CORE1) && FSL_FEATURE_RCM_HAS_CORE1) + | + RCM_SRIE_CORE1_MASK +#endif +} rcm_interrupt_enable_t; +#endif /* FSL_FEATURE_RCM_HAS_SRIE */ + +#if (defined(FSL_FEATURE_RCM_HAS_VERID) && FSL_FEATURE_RCM_HAS_VERID) +/*! + * @brief IP version ID definition. + */ +typedef struct _rcm_version_id +{ + uint16_t feature; /*!< Feature Specification Number. */ + uint8_t minor; /*!< Minor version number. */ + uint8_t major; /*!< Major version number. */ +} rcm_version_id_t; +#endif + +/*! + * @brief Reset pin filter configuration. + */ +typedef struct _rcm_reset_pin_filter_config +{ + 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. */ +} rcm_reset_pin_filter_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +/*! @name Reset Control Module APIs*/ +/*@{*/ + +#if (defined(FSL_FEATURE_RCM_HAS_VERID) && FSL_FEATURE_RCM_HAS_VERID) +/*! + * @brief Gets the RCM version ID. + * + * This function gets the RCM version ID including the major version number, + * the minor version number, and the feature specification number. + * + * @param base RCM peripheral base address. + * @param versionId Pointer to the version ID structure. + */ +static inline void RCM_GetVersionId(RCM_Type *base, rcm_version_id_t *versionId) +{ + *((uint32_t *)versionId) = base->VERID; +} +#endif + +#if (defined(FSL_FEATURE_RCM_HAS_PARAM) && FSL_FEATURE_RCM_HAS_PARAM) +/*! + * @brief Gets the reset source implemented status. + * + * This function gets the RCM parameter that indicates whether the corresponding reset source is implemented. + * Use source masks defined in the rcm_reset_source_t to get the desired source status. + * + * This is an example. + @code + uint32_t status; + + // To test whether the MCU is reset using Watchdog. + status = RCM_GetResetSourceImplementedStatus(RCM) & (kRCM_SourceWdog | kRCM_SourcePin); + @endcode + * + * @param base RCM peripheral base address. + * @return All reset source implemented status bit map. + */ +static inline uint32_t RCM_GetResetSourceImplementedStatus(RCM_Type *base) +{ + return base->PARAM; +} +#endif /* FSL_FEATURE_RCM_HAS_PARAM */ + +/*! + * @brief Gets the reset source status which caused a previous reset. + * + * 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. + @code + uint32_t resetStatus; + + // To get all reset source statuses. + resetStatus = RCM_GetPreviousResetSources(RCM) & kRCM_SourceAll; + + // To test whether the MCU is reset using Watchdog. + resetStatus = RCM_GetPreviousResetSources(RCM) & kRCM_SourceWdog; + + // To test multiple reset sources. + resetStatus = RCM_GetPreviousResetSources(RCM) & (kRCM_SourceWdog | kRCM_SourcePin); + @endcode + * + * @param base RCM peripheral base address. + * @return All reset source status bit map. + */ +static inline uint32_t RCM_GetPreviousResetSources(RCM_Type *base) +{ +#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) + return base->SRS; +#else + return (uint32_t)((uint32_t)base->SRS0 | ((uint32_t)base->SRS1 << 8U)); +#endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ +} + +#if (defined(FSL_FEATURE_RCM_HAS_SSRS) && FSL_FEATURE_RCM_HAS_SSRS) +/*! + * @brief Gets the sticky reset source status. + * + * This function gets the current reset source status that has not been cleared + * by software for a specific source. + * + * This is an example. + @code + uint32_t resetStatus; + + // To get all reset source statuses. + resetStatus = RCM_GetStickyResetSources(RCM) & kRCM_SourceAll; + + // To test whether the MCU is reset using Watchdog. + resetStatus = RCM_GetStickyResetSources(RCM) & kRCM_SourceWdog; + + // To test multiple reset sources. + resetStatus = RCM_GetStickyResetSources(RCM) & (kRCM_SourceWdog | kRCM_SourcePin); + @endcode + * + * @param base RCM peripheral base address. + * @return All reset source status bit map. + */ +static inline uint32_t RCM_GetStickyResetSources(RCM_Type *base) +{ +#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) + return base->SSRS; +#else + return (base->SSRS0 | ((uint32_t)base->SSRS1 << 8U)); +#endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ +} + +/*! + * @brief Clears the sticky reset source status. + * + * This function clears the sticky system reset flags indicated by source masks. + * + * This is an example. + @code + // Clears multiple reset sources. + RCM_ClearStickyResetSources(kRCM_SourceWdog | kRCM_SourcePin); + @endcode + * + * @param base RCM peripheral base address. + * @param sourceMasks reset source status bit map + */ +static inline void RCM_ClearStickyResetSources(RCM_Type *base, uint32_t sourceMasks) +{ +#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) + base->SSRS = sourceMasks; +#else + base->SSRS0 = (sourceMasks & 0xffU); + base->SSRS1 = ((sourceMasks >> 8U) & 0xffU); +#endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ +} +#endif /* FSL_FEATURE_RCM_HAS_SSRS */ + +/*! + * @brief Configures the reset pin filter. + * + * This function sets the reset pin filter including the filter source, filter + * width, and so on. + * + * @param base RCM peripheral base address. + * @param config Pointer to the configuration structure. + */ +void RCM_ConfigureResetPinFilter(RCM_Type *base, const rcm_reset_pin_filter_config_t *config); + +#if (defined(FSL_FEATURE_RCM_HAS_EZPMS) && FSL_FEATURE_RCM_HAS_EZPMS) +/*! + * @brief Gets the EZP_MS_B pin assert status. + * + * This function gets the easy port mode status (EZP_MS_B) pin assert status. + * + * @param base RCM peripheral base address. + * @return status true - asserted, false - reasserted + */ +static inline bool RCM_GetEasyPortModePinStatus(RCM_Type *base) +{ + return (bool)(base->MR & RCM_MR_EZP_MS_MASK); +} +#endif /* FSL_FEATURE_RCM_HAS_EZPMS */ + +#if (defined(FSL_FEATURE_RCM_HAS_BOOTROM) && FSL_FEATURE_RCM_HAS_BOOTROM) +/*! + * @brief Gets the ROM boot source. + * + * This function gets the ROM boot source during the last chip reset. + * + * @param base RCM peripheral base address. + * @return The ROM boot source. + */ +static inline rcm_boot_rom_config_t RCM_GetBootRomSource(RCM_Type *base) +{ + return (rcm_boot_rom_config_t)((base->MR & RCM_MR_BOOTROM_MASK) >> RCM_MR_BOOTROM_SHIFT); +} + +/*! + * @brief Clears the ROM boot source flag. + * + * This function clears the ROM boot source flag. + * + * @param base Register base address of RCM + */ +static inline void RCM_ClearBootRomSource(RCM_Type *base) +{ + base->MR |= RCM_MR_BOOTROM_MASK; +} + +/*! + * @brief Forces the boot from ROM. + * + * This function forces booting from ROM during all subsequent system resets. + * + * @param base RCM peripheral base address. + * @param config Boot configuration. + */ +void RCM_SetForceBootRomSource(RCM_Type *base, rcm_boot_rom_config_t config); +#endif /* FSL_FEATURE_RCM_HAS_BOOTROM */ + +#if (defined(FSL_FEATURE_RCM_HAS_SRIE) && FSL_FEATURE_RCM_HAS_SRIE) +/*! + * @brief Sets the system reset interrupt configuration. + * + * For a graceful shut down, the RCM supports delaying the assertion of the system + * reset for a period of time when the reset interrupt is generated. This function + * can be used to enable the interrupt and the delay period. The interrupts + * are passed in as bit mask. See rcm_int_t for details. For example, to + * delay a reset for 512 LPO cycles after the WDOG timeout or loss-of-clock occurs, + * configure as follows: + * RCM_SetSystemResetInterruptConfig(kRCM_IntWatchDog | kRCM_IntLossOfClk, kRCM_ResetDelay512Lpo); + * + * @param base RCM peripheral base address. + * @param intMask Bit mask of the system reset interrupts to enable. See + * rcm_interrupt_enable_t for details. + * @param Delay Bit mask of the system reset interrupts to enable. + */ +static inline void RCM_SetSystemResetInterruptConfig(RCM_Type *base, uint32_t intMask, rcm_reset_delay_t delay) +{ + base->SRIE = (intMask | delay); +} +#endif /* FSL_FEATURE_RCM_HAS_SRIE */ +/*@}*/ + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +/*! @}*/ + +#endif /* _FSL_RCM_H_ */ diff --git a/drivers/include/fsl_rtc.h b/drivers/include/fsl_rtc.h new file mode 100644 index 0000000..99effc6 --- /dev/null +++ b/drivers/include/fsl_rtc.h @@ -0,0 +1,414 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_RTC_H_ +#define _FSL_RTC_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup rtc + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +#define FSL_RTC_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Version 2.0.0 */ +/*@}*/ + +/*! @brief List of RTC interrupts */ +typedef enum _rtc_interrupt_enable +{ + kRTC_TimeInvalidInterruptEnable = RTC_IER_TIIE_MASK, /*!< Time invalid interrupt.*/ + kRTC_TimeOverflowInterruptEnable = RTC_IER_TOIE_MASK, /*!< Time overflow interrupt.*/ + kRTC_AlarmInterruptEnable = RTC_IER_TAIE_MASK, /*!< Alarm interrupt.*/ + kRTC_SecondsInterruptEnable = RTC_IER_TSIE_MASK /*!< Seconds interrupt.*/ +} rtc_interrupt_enable_t; + +/*! @brief List of RTC flags */ +typedef enum _rtc_status_flags +{ + kRTC_TimeInvalidFlag = RTC_SR_TIF_MASK, /*!< Time invalid flag */ + kRTC_TimeOverflowFlag = RTC_SR_TOF_MASK, /*!< Time overflow flag */ + kRTC_AlarmFlag = RTC_SR_TAF_MASK /*!< Alarm flag*/ +} rtc_status_flags_t; + +#if (defined(FSL_FEATURE_RTC_HAS_OSC_SCXP) && FSL_FEATURE_RTC_HAS_OSC_SCXP) + +/*! @brief List of RTC Oscillator capacitor load settings */ +typedef enum _rtc_osc_cap_load +{ + kRTC_Capacitor_2p = RTC_CR_SC2P_MASK, /*!< 2 pF capacitor load */ + kRTC_Capacitor_4p = RTC_CR_SC4P_MASK, /*!< 4 pF capacitor load */ + kRTC_Capacitor_8p = RTC_CR_SC8P_MASK, /*!< 8 pF capacitor load */ + kRTC_Capacitor_16p = RTC_CR_SC16P_MASK /*!< 16 pF capacitor load */ +} rtc_osc_cap_load_t; + +#endif /* FSL_FEATURE_SCG_HAS_OSC_SCXP */ + +/*! @brief Structure is used to hold the date and time */ +typedef struct _rtc_datetime +{ + uint16_t year; /*!< Range from 1970 to 2099.*/ + uint8_t month; /*!< Range from 1 to 12.*/ + uint8_t day; /*!< Range from 1 to 31 (depending on month).*/ + uint8_t hour; /*!< Range from 0 to 23.*/ + uint8_t minute; /*!< Range from 0 to 59.*/ + uint8_t second; /*!< Range from 0 to 59.*/ +} rtc_datetime_t; + +/*! + * @brief RTC config structure + * + * This structure holds the configuration settings for the RTC peripheral. To initialize this + * structure to reasonable 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 + */ +typedef struct _rtc_config +{ + 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 */ +} rtc_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Ungates the RTC clock and configures the peripheral for basic operation. + * + * 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. + * + * @param base RTC peripheral base address + * @param config Pointer to the user's RTC configuration structure. + */ +void RTC_Init(RTC_Type *base, const rtc_config_t *config); + +/*! + * @brief Stops the timer and gate the RTC clock. + * + * @param base RTC peripheral base address + */ +static inline void RTC_Deinit(RTC_Type *base) +{ + /* Stop the RTC timer */ + base->SR &= ~RTC_SR_TCE_MASK; + +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) + /* Gate the module clock */ + CLOCK_DisableClock(kCLOCK_Rtc0); +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ +} + +/*! + * @brief Fills in the RTC config struct with the default settings. + * + * The default values are as follows. + * @code + * config->wakeupSelect = false; + * config->updateMode = false; + * config->supervisorAccess = false; + * config->compensationInterval = 0; + * config->compensationTime = 0; + * @endcode + * @param config Pointer to the user's RTC configuration structure. + */ +void RTC_GetDefaultConfig(rtc_config_t *config); + +/*! @}*/ + +/*! + * @name Current Time & Alarm + * @{ + */ + +/*! + * @brief Sets the RTC date and time according to the given time structure. + * + * 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. + * + * @param base RTC peripheral base address + * @param datetime Pointer to the structure where the date and time details are stored. + * + * @return kStatus_Success: Success in setting the time and starting the RTC + * kStatus_InvalidArgument: Error because the datetime format is incorrect + */ +status_t RTC_SetDatetime(RTC_Type *base, const rtc_datetime_t *datetime); + +/*! + * @brief Gets the RTC time and stores it in the given time structure. + * + * @param base RTC peripheral base address + * @param datetime Pointer to the structure where the date and time details are stored. + */ +void RTC_GetDatetime(RTC_Type *base, rtc_datetime_t *datetime); + +/*! + * @brief Sets the RTC alarm time. + * + * 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. + * + * @param base RTC peripheral base address + * @param alarmTime Pointer to the structure where the alarm time is stored. + * + * @return 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 + */ +status_t RTC_SetAlarm(RTC_Type *base, const rtc_datetime_t *alarmTime); + +/*! + * @brief Returns the RTC alarm time. + * + * @param base RTC peripheral base address + * @param datetime Pointer to the structure where the alarm date and time details are stored. + */ +void RTC_GetAlarm(RTC_Type *base, rtc_datetime_t *datetime); + +/*! @}*/ + +/*! + * @name Interrupt Interface + * @{ + */ + +/*! + * @brief Enables the selected RTC interrupts. + * + * @param base RTC peripheral base address + * @param mask The interrupts to enable. This is a logical OR of members of the + * enumeration ::rtc_interrupt_enable_t + */ +static inline void RTC_EnableInterrupts(RTC_Type *base, uint32_t mask) +{ + base->IER |= mask; +} + +/*! + * @brief Disables the selected RTC interrupts. + * + * @param base RTC peripheral base address + * @param mask The interrupts to enable. This is a logical OR of members of the + * enumeration ::rtc_interrupt_enable_t + */ +static inline void RTC_DisableInterrupts(RTC_Type *base, uint32_t mask) +{ + base->IER &= ~mask; +} + +/*! + * @brief Gets the enabled RTC interrupts. + * + * @param base RTC peripheral base address + * + * @return The enabled interrupts. This is the logical OR of members of the + * enumeration ::rtc_interrupt_enable_t + */ +static inline uint32_t RTC_GetEnabledInterrupts(RTC_Type *base) +{ + return (base->IER & (RTC_IER_TIIE_MASK | RTC_IER_TOIE_MASK | RTC_IER_TAIE_MASK | RTC_IER_TSIE_MASK)); +} + +/*! @}*/ + +/*! + * @name Status Interface + * @{ + */ + +/*! + * @brief Gets the RTC status flags. + * + * @param base RTC peripheral base address + * + * @return The status flags. This is the logical OR of members of the + * enumeration ::rtc_status_flags_t + */ +static inline uint32_t RTC_GetStatusFlags(RTC_Type *base) +{ + return (base->SR & (RTC_SR_TIF_MASK | RTC_SR_TOF_MASK | RTC_SR_TAF_MASK)); +} + +/*! + * @brief Clears the RTC status flags. + * + * @param base RTC peripheral base address + * @param mask The status flags to clear. This is a logical OR of members of the + * enumeration ::rtc_status_flags_t + */ +void RTC_ClearStatusFlags(RTC_Type *base, uint32_t mask); + +/*! @}*/ + +/*! + * @name Timer Start and Stop + * @{ + */ + +/*! + * @brief Starts the RTC time counter. + * + * After calling this function, the timer counter increments once a second provided SR[TOF] or + * SR[TIF] are not set. + * + * @param base RTC peripheral base address + */ +static inline void RTC_StartTimer(RTC_Type *base) +{ + base->SR |= RTC_SR_TCE_MASK; +} + +/*! + * @brief Stops the RTC time counter. + * + * RTC's seconds register can be written to only when the timer is stopped. + * + * @param base RTC peripheral base address + */ +static inline void RTC_StopTimer(RTC_Type *base) +{ + base->SR &= ~RTC_SR_TCE_MASK; +} + +/*! @}*/ + +#if (defined(FSL_FEATURE_RTC_HAS_OSC_SCXP) && FSL_FEATURE_RTC_HAS_OSC_SCXP) + +/*! + * @brief This function sets the specified capacitor configuration for the RTC oscillator. + * + * @param base RTC peripheral base address + * @param capLoad Oscillator loads to enable. This is a logical OR of members of the + * enumeration ::rtc_osc_cap_load_t + */ +static inline void RTC_SetOscCapLoad(RTC_Type *base, uint32_t capLoad) +{ + uint32_t reg = base->CR; + + reg &= ~(RTC_CR_SC2P_MASK | RTC_CR_SC4P_MASK | RTC_CR_SC8P_MASK | RTC_CR_SC16P_MASK); + reg |= capLoad; + + base->CR = reg; +} + +#endif /* FSL_FEATURE_SCG_HAS_OSC_SCXP */ + +/*! + * @brief Performs a software reset on the RTC module. + * + * 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. + * + * @param base RTC peripheral base address + */ +static inline void RTC_Reset(RTC_Type *base) +{ + base->CR |= RTC_CR_SWR_MASK; + base->CR &= ~RTC_CR_SWR_MASK; + + /* Set TSR register to 0x1 to avoid the timer invalid (TIF) bit being set in the SR register */ + base->TSR = 1U; +} + +#if defined(FSL_FEATURE_RTC_HAS_MONOTONIC) && (FSL_FEATURE_RTC_HAS_MONOTONIC) + +/*! + * @name Monotonic counter functions + * @{ + */ + +/*! + * @brief Reads the values of the Monotonic Counter High and Monotonic Counter Low and returns + * them as a single value. + * + * @param base RTC peripheral base address + * @param counter Pointer to variable where the value is stored. + */ +void RTC_GetMonotonicCounter(RTC_Type *base, uint64_t *counter); + +/*! + * @brief Writes values Monotonic Counter High and Monotonic Counter Low by decomposing + * the given single value. + * + * @param base RTC peripheral base address + * @param counter Counter value + */ +void RTC_SetMonotonicCounter(RTC_Type *base, uint64_t counter); + +/*! + * @brief Increments the Monotonic Counter by one. + * + * Increments the Monotonic Counter (registers RTC_MCLR and RTC_MCHR accordingly) by setting + * the monotonic counter enable (MER[MCE]) and then writing to the RTC_MCLR register. A write to the + * monotonic counter low that causes it to overflow also increments the monotonic counter high. + * + * @param base RTC peripheral base address + * + * @return kStatus_Success: success + * kStatus_Fail: error occurred, either time invalid or monotonic overflow flag was found + */ +status_t RTC_IncrementMonotonicCounter(RTC_Type *base); + +/*! @}*/ + +#endif /* FSL_FEATURE_RTC_HAS_MONOTONIC */ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_RTC_H_ */ diff --git a/drivers/include/fsl_sai.h b/drivers/include/fsl_sai.h new file mode 100644 index 0000000..d40c575 --- /dev/null +++ b/drivers/include/fsl_sai.h @@ -0,0 +1,849 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of Freescale Semiconductor, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_SAI_H_ +#define _FSL_SAI_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup sai + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +#define FSL_SAI_DRIVER_VERSION (MAKE_VERSION(2, 1, 1)) /*!< Version 2.1.1 */ +/*@}*/ + +/*! @brief SAI return status*/ +enum _sai_status_t +{ + kStatus_SAI_TxBusy = MAKE_STATUS(kStatusGroup_SAI, 0), /*!< SAI Tx is busy. */ + kStatus_SAI_RxBusy = MAKE_STATUS(kStatusGroup_SAI, 1), /*!< SAI Rx is busy. */ + kStatus_SAI_TxError = MAKE_STATUS(kStatusGroup_SAI, 2), /*!< SAI Tx FIFO error. */ + kStatus_SAI_RxError = MAKE_STATUS(kStatusGroup_SAI, 3), /*!< SAI Rx FIFO error. */ + kStatus_SAI_QueueFull = MAKE_STATUS(kStatusGroup_SAI, 4), /*!< SAI transfer queue is full. */ + kStatus_SAI_TxIdle = MAKE_STATUS(kStatusGroup_SAI, 5), /*!< SAI Tx is idle */ + kStatus_SAI_RxIdle = MAKE_STATUS(kStatusGroup_SAI, 6) /*!< SAI Rx is idle */ +}; + +/*! @brief Define the SAI bus type */ +typedef enum _sai_protocol +{ + kSAI_BusLeftJustified = 0x0U, /*!< 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. */ +} sai_protocol_t; + +/*! @brief Master or slave mode */ +typedef enum _sai_master_slave +{ + kSAI_Master = 0x0U, /*!< Master mode */ + kSAI_Slave = 0x1U /*!< Slave mode */ +} sai_master_slave_t; + +/*! @brief Mono or stereo audio format */ +typedef enum _sai_mono_stereo +{ + kSAI_Stereo = 0x0U, /*!< Stereo sound. */ + kSAI_MonoLeft, /*!< Only left channel have sound. */ + kSAI_MonoRight /*!< Only Right channel have sound. */ +} sai_mono_stereo_t; + +/*! @brief Synchronous or asynchronous mode */ +typedef enum _sai_sync_mode +{ + kSAI_ModeAsync = 0x0U, /*!< Asynchronous mode */ + kSAI_ModeSync, /*!< Synchronous mode (with receiver or transmit) */ + kSAI_ModeSyncWithOtherTx, /*!< Synchronous with another SAI transmit */ + kSAI_ModeSyncWithOtherRx /*!< Synchronous with another SAI receiver */ +} sai_sync_mode_t; + +/*! @brief Mater clock source */ +typedef enum _sai_mclk_source +{ + kSAI_MclkSourceSysclk = 0x0U, /*!< 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 */ +} sai_mclk_source_t; + +/*! @brief Bit clock source */ +typedef enum _sai_bclk_source +{ + kSAI_BclkSourceBusclk = 0x0U, /*!< 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 */ +} sai_bclk_source_t; + +/*! @brief The SAI interrupt enable flag */ +enum _sai_interrupt_enable_t +{ + kSAI_WordStartInterruptEnable = + I2S_TCSR_WSIE_MASK, /*!< Word start flag, means the first word in a frame detected */ + kSAI_SyncErrorInterruptEnable = I2S_TCSR_SEIE_MASK, /*!< Sync error flag, means the sync error is detected */ + kSAI_FIFOWarningInterruptEnable = I2S_TCSR_FWIE_MASK, /*!< FIFO warning flag, means the FIFO is empty */ + kSAI_FIFOErrorInterruptEnable = I2S_TCSR_FEIE_MASK, /*!< FIFO error flag */ +#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) + kSAI_FIFORequestInterruptEnable = I2S_TCSR_FRIE_MASK, /*!< FIFO request, means reached watermark */ +#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ +}; + +/*! @brief The DMA request sources */ +enum _sai_dma_enable_t +{ + kSAI_FIFOWarningDMAEnable = I2S_TCSR_FWDE_MASK, /*!< FIFO warning caused by the DMA request */ +#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) + kSAI_FIFORequestDMAEnable = I2S_TCSR_FRDE_MASK, /*!< FIFO request caused by the DMA request */ +#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ +}; + +/*! @brief The SAI status flag */ +enum _sai_flags +{ + kSAI_WordStartFlag = I2S_TCSR_WSF_MASK, /*!< Word start flag, means the first word in a frame detected */ + kSAI_SyncErrorFlag = I2S_TCSR_SEF_MASK, /*!< Sync error flag, means the sync error is detected */ + kSAI_FIFOErrorFlag = I2S_TCSR_FEF_MASK, /*!< FIFO error flag */ +#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) + kSAI_FIFORequestFlag = I2S_TCSR_FRF_MASK, /*!< FIFO request flag. */ +#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ + kSAI_FIFOWarningFlag = I2S_TCSR_FWF_MASK, /*!< FIFO warning flag */ +}; + +/*! @brief The reset type */ +typedef enum _sai_reset_type +{ + kSAI_ResetTypeSoftware = I2S_TCSR_SR_MASK, /*!< Software reset, reset the logic state */ + kSAI_ResetTypeFIFO = I2S_TCSR_FR_MASK, /*!< FIFO reset, reset the FIFO read and write pointer */ + kSAI_ResetAll = I2S_TCSR_SR_MASK | I2S_TCSR_FR_MASK /*!< All reset. */ +} sai_reset_type_t; + +#if defined(FSL_FEATURE_SAI_HAS_FIFO_PACKING) && FSL_FEATURE_SAI_HAS_FIFO_PACKING +/*! + * @brief The SAI packing mode + * The mode includes 8 bit and 16 bit packing. + */ +typedef enum _sai_fifo_packing +{ + kSAI_FifoPackingDisabled = 0x0U, /*!< Packing disabled */ + kSAI_FifoPacking8bit = 0x2U, /*!< 8 bit packing enabled */ + kSAI_FifoPacking16bit = 0x3U /*!< 16bit packing enabled */ +} sai_fifo_packing_t; +#endif /* FSL_FEATURE_SAI_HAS_FIFO_PACKING */ + +/*! @brief SAI user configuration structure */ +typedef struct _sai_config +{ + sai_protocol_t protocol; /*!< Audio bus protocol in SAI */ + sai_sync_mode_t syncMode; /*!< SAI sync mode, control Tx/Rx clock sync */ +#if defined(FSL_FEATURE_SAI_HAS_MCR) && (FSL_FEATURE_SAI_HAS_MCR) + bool mclkOutputEnable; /*!< Master clock output enable, true means master clock divider enabled */ +#endif /* FSL_FEATURE_SAI_HAS_MCR */ + sai_mclk_source_t mclkSource; /*!< Master Clock source */ + sai_bclk_source_t bclkSource; /*!< Bit Clock source */ + sai_master_slave_t masterSlave; /*!< Master or slave */ +} sai_config_t; + +/*!@brief SAI transfer queue size, user can refine it according to use case. */ +#define SAI_XFER_QUEUE_SIZE (4) + +/*! @brief Audio sample rate */ +typedef enum _sai_sample_rate +{ + kSAI_SampleRate8KHz = 8000U, /*!< Sample rate 8000 Hz */ + kSAI_SampleRate11025Hz = 11025U, /*!< Sample rate 11025 Hz */ + kSAI_SampleRate12KHz = 12000U, /*!< Sample rate 12000 Hz */ + kSAI_SampleRate16KHz = 16000U, /*!< Sample rate 16000 Hz */ + kSAI_SampleRate22050Hz = 22050U, /*!< Sample rate 22050 Hz */ + kSAI_SampleRate24KHz = 24000U, /*!< Sample rate 24000 Hz */ + kSAI_SampleRate32KHz = 32000U, /*!< Sample rate 32000 Hz */ + kSAI_SampleRate44100Hz = 44100U, /*!< Sample rate 44100 Hz */ + kSAI_SampleRate48KHz = 48000U, /*!< Sample rate 48000 Hz */ + kSAI_SampleRate96KHz = 96000U /*!< Sample rate 96000 Hz */ +} sai_sample_rate_t; + +/*! @brief Audio word width */ +typedef enum _sai_word_width +{ + kSAI_WordWidth8bits = 8U, /*!< Audio data width 8 bits */ + kSAI_WordWidth16bits = 16U, /*!< Audio data width 16 bits */ + kSAI_WordWidth24bits = 24U, /*!< Audio data width 24 bits */ + kSAI_WordWidth32bits = 32U /*!< Audio data width 32 bits */ +} sai_word_width_t; + +/*! @brief sai transfer format */ +typedef struct _sai_transfer_format +{ + 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 */ +#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) + uint8_t watermark; /*!< Watermark value */ +#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ + uint8_t channel; /*!< Data channel used in transfer.*/ + sai_protocol_t protocol; /*!< Which audio protocol used */ +} sai_transfer_format_t; + +/*! @brief SAI transfer structure */ +typedef struct _sai_transfer +{ + uint8_t *data; /*!< Data start address to transfer. */ + size_t dataSize; /*!< Transfer size. */ +} sai_transfer_t; + +typedef struct _sai_handle sai_handle_t; + +/*! @brief SAI transfer callback prototype */ +typedef void (*sai_transfer_callback_t)(I2S_Type *base, sai_handle_t *handle, status_t status, void *userData); + +/*! @brief SAI handle structure */ +struct _sai_handle +{ + 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 */ +#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) + uint8_t watermark; /*!< Watermark value */ +#endif +}; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /*_cplusplus*/ + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Initializes the SAI Tx peripheral. + * + * 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. + * + * @param base SAI base pointer + * @param config SAI configuration structure. +*/ +void SAI_TxInit(I2S_Type *base, const sai_config_t *config); + +/*! + * @brief Initializes the the SAI Rx peripheral. + * + * 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. + * + * @param base SAI base pointer + * @param config SAI configuration structure. + */ +void SAI_RxInit(I2S_Type *base, const sai_config_t *config); + +/*! + * @brief Sets the SAI Tx configuration structure to default values. + * + * 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(). + * Example: + @code + sai_config_t config; + SAI_TxGetDefaultConfig(&config); + @endcode + * + * @param config pointer to master configuration structure + */ +void SAI_TxGetDefaultConfig(sai_config_t *config); + +/*! + * @brief Sets the SAI Rx configuration structure to default values. + * + * 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(). + * Example: + @code + sai_config_t config; + SAI_RxGetDefaultConfig(&config); + @endcode + * + * @param config pointer to master configuration structure + */ +void SAI_RxGetDefaultConfig(sai_config_t *config); + +/*! + * @brief De-initializes the SAI peripheral. + * + * This API gates the SAI clock. The SAI module can't operate unless SAI_TxInit + * or SAI_RxInit is called to enable the clock. + * + * @param base SAI base pointer +*/ +void SAI_Deinit(I2S_Type *base); + +/*! + * @brief Resets the SAI Tx. + * + * This function enables the software reset and FIFO reset of SAI Tx. After reset, clear the reset bit. + * + * @param base SAI base pointer + */ +void SAI_TxReset(I2S_Type *base); + +/*! + * @brief Resets the SAI Rx. + * + * This function enables the software reset and FIFO reset of SAI Rx. After reset, clear the reset bit. + * + * @param base SAI base pointer + */ +void SAI_RxReset(I2S_Type *base); + +/*! + * @brief Enables/disables SAI Tx. + * + * @param base SAI base pointer + * @param enable True means enable SAI Tx, false means disable. + */ +void SAI_TxEnable(I2S_Type *base, bool enable); + +/*! + * @brief Enables/disables SAI Rx. + * + * @param base SAI base pointer + * @param enable True means enable SAI Rx, false means disable. + */ +void SAI_RxEnable(I2S_Type *base, bool enable); + +/*! @} */ + +/*! + * @name Status + * @{ + */ + +/*! + * @brief Gets the SAI Tx status flag state. + * + * @param base SAI base pointer + * @return SAI Tx status flag value. Use the Status Mask to get the status value needed. + */ +static inline uint32_t SAI_TxGetStatusFlag(I2S_Type *base) +{ + return base->TCSR; +} + +/*! + * @brief Clears the SAI Tx status flag state. + * + * @param base SAI base pointer + * @param mask State mask. It can be a combination of the following source if defined: + * @arg kSAI_WordStartFlag + * @arg kSAI_SyncErrorFlag + * @arg kSAI_FIFOErrorFlag + */ +static inline void SAI_TxClearStatusFlags(I2S_Type *base, uint32_t mask) +{ + base->TCSR = ((base->TCSR & 0xFFE3FFFFU) | mask); +} + +/*! + * @brief Gets the SAI Tx status flag state. + * + * @param base SAI base pointer + * @return SAI Rx status flag value. Use the Status Mask to get the status value needed. + */ +static inline uint32_t SAI_RxGetStatusFlag(I2S_Type *base) +{ + return base->RCSR; +} + +/*! + * @brief Clears the SAI Rx status flag state. + * + * @param base SAI base pointer + * @param mask State mask. It can be a combination of the following source if defined: + * @arg kSAI_WordStartFlag + * @arg kSAI_SyncErrorFlag + * @arg kSAI_FIFOErrorFlag + */ +static inline void SAI_RxClearStatusFlags(I2S_Type *base, uint32_t mask) +{ + base->RCSR = ((base->RCSR & 0xFFE3FFFFU) | mask); +} + +/*! @} */ + +/*! + * @name Interrupts + * @{ + */ + +/*! + * @brief Enables SAI Tx interrupt requests. + * + * @param base SAI base pointer + * @param mask interrupt source + * The parameter can be a combination of the following source if defined: + * @arg kSAI_WordStartInterruptEnable + * @arg kSAI_SyncErrorInterruptEnable + * @arg kSAI_FIFOWarningInterruptEnable + * @arg kSAI_FIFORequestInterruptEnable + * @arg kSAI_FIFOErrorInterruptEnable + */ +static inline void SAI_TxEnableInterrupts(I2S_Type *base, uint32_t mask) +{ + base->TCSR = ((base->TCSR & 0xFFE3FFFFU) | mask); +} + +/*! + * @brief Enables SAI Rx interrupt requests. + * + * @param base SAI base pointer + * @param mask interrupt source + * The parameter can be a combination of the following source if defined: + * @arg kSAI_WordStartInterruptEnable + * @arg kSAI_SyncErrorInterruptEnable + * @arg kSAI_FIFOWarningInterruptEnable + * @arg kSAI_FIFORequestInterruptEnable + * @arg kSAI_FIFOErrorInterruptEnable + */ +static inline void SAI_RxEnableInterrupts(I2S_Type *base, uint32_t mask) +{ + base->RCSR = ((base->RCSR & 0xFFE3FFFFU) | mask); +} + +/*! + * @brief Disables SAI Tx interrupt requests. + * + * @param base SAI base pointer + * @param mask interrupt source + * The parameter can be a combination of the following source if defined: + * @arg kSAI_WordStartInterruptEnable + * @arg kSAI_SyncErrorInterruptEnable + * @arg kSAI_FIFOWarningInterruptEnable + * @arg kSAI_FIFORequestInterruptEnable + * @arg kSAI_FIFOErrorInterruptEnable + */ +static inline void SAI_TxDisableInterrupts(I2S_Type *base, uint32_t mask) +{ + base->TCSR = ((base->TCSR & 0xFFE3FFFFU) & (~mask)); +} + +/*! + * @brief Disables SAI Rx interrupt requests. + * + * @param base SAI base pointer + * @param mask interrupt source + * The parameter can be a combination of the following source if defined: + * @arg kSAI_WordStartInterruptEnable + * @arg kSAI_SyncErrorInterruptEnable + * @arg kSAI_FIFOWarningInterruptEnable + * @arg kSAI_FIFORequestInterruptEnable + * @arg kSAI_FIFOErrorInterruptEnable + */ +static inline void SAI_RxDisableInterrupts(I2S_Type *base, uint32_t mask) +{ + base->RCSR = ((base->RCSR & 0xFFE3FFFFU) & (~mask)); +} + +/*! @} */ + +/*! + * @name DMA Control + * @{ + */ + +/*! + * @brief Enables/disables SAI Tx DMA requests. + * @param base SAI base pointer + * @param mask DMA source + * The parameter can be combination of the following source if defined: + * @arg kSAI_FIFOWarningDMAEnable + * @arg kSAI_FIFORequestDMAEnable + * @param enable True means enable DMA, false means disable DMA. + */ +static inline void SAI_TxEnableDMA(I2S_Type *base, uint32_t mask, bool enable) +{ + if (enable) + { + base->TCSR = ((base->TCSR & 0xFFE3FFFFU) | mask); + } + else + { + base->TCSR = ((base->TCSR & 0xFFE3FFFFU) & (~mask)); + } +} + +/*! + * @brief Enables/disables SAI Rx DMA requests. + * @param base SAI base pointer + * @param mask DMA source + * The parameter can be a combination of the following source if defined: + * @arg kSAI_FIFOWarningDMAEnable + * @arg kSAI_FIFORequestDMAEnable + * @param enable True means enable DMA, false means disable DMA. + */ +static inline void SAI_RxEnableDMA(I2S_Type *base, uint32_t mask, bool enable) +{ + if (enable) + { + base->RCSR = ((base->RCSR & 0xFFE3FFFFU) | mask); + } + else + { + base->RCSR = ((base->RCSR & 0xFFE3FFFFU) & (~mask)); + } +} + +/*! + * @brief Gets the SAI Tx data register address. + * + * This API is used to provide a transfer address for SAI DMA transfer configuration. + * + * @param base SAI base pointer. + * @param channel Which data channel used. + * @return data register address. + */ +static inline uint32_t SAI_TxGetDataRegisterAddress(I2S_Type *base, uint32_t channel) +{ + return (uint32_t)(&(base->TDR)[channel]); +} + +/*! + * @brief Gets the SAI Rx data register address. + * + * This API is used to provide a transfer address for SAI DMA transfer configuration. + * + * @param base SAI base pointer. + * @param channel Which data channel used. + * @return data register address. + */ +static inline uint32_t SAI_RxGetDataRegisterAddress(I2S_Type *base, uint32_t channel) +{ + return (uint32_t)(&(base->RDR)[channel]); +} + +/*! @} */ + +/*! + * @name Bus Operations + * @{ + */ + +/*! + * @brief Configures the SAI Tx audio format. + * + * The audio format can be changed at run-time. This function configures the sample rate and audio data + * format to be transferred. + * + * @param base SAI base pointer. + * @param format Pointer to SAI audio data format structure. + * @param mclkSourceClockHz SAI master clock source frequency in Hz. + * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If bit clock source is master + * clock, this value should equals to masterClockHz in format. +*/ +void SAI_TxSetFormat(I2S_Type *base, + sai_transfer_format_t *format, + uint32_t mclkSourceClockHz, + uint32_t bclkSourceClockHz); + +/*! + * @brief Configures the SAI Rx audio format. + * + * The audio format can be changed at run-time. This function configures the sample rate and audio data + * format to be transferred. + * + * @param base SAI base pointer. + * @param format Pointer to SAI audio data format structure. + * @param mclkSourceClockHz SAI master clock source frequency in Hz. + * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If bit clock source is master + * clock, this value should equals to masterClockHz in format. +*/ +void SAI_RxSetFormat(I2S_Type *base, + sai_transfer_format_t *format, + uint32_t mclkSourceClockHz, + uint32_t bclkSourceClockHz); + +/*! + * @brief Sends data using a blocking method. + * + * @note This function blocks by polling until data is ready to be sent. + * + * @param base SAI base pointer. + * @param channel Data channel used. + * @param bitWidth How many bits in a audio word, usually 8/16/24/32 bits. + * @param buffer Pointer to the data to be written. + * @param size Bytes to be written. + */ +void SAI_WriteBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size); + +/*! + * @brief Writes data into SAI FIFO. + * + * @param base SAI base pointer. + * @param channel Data channel used. + * @param data Data needs to be written. + */ +static inline void SAI_WriteData(I2S_Type *base, uint32_t channel, uint32_t data) +{ + base->TDR[channel] = data; +} + +/*! + * @brief Receives data using a blocking method. + * + * @note This function blocks by polling until data is ready to be sent. + * + * @param base SAI base pointer. + * @param channel Data channel used. + * @param bitWidth How many bits in a audio word, usually 8/16/24/32 bits. + * @param buffer Pointer to the data to be read. + * @param size Bytes to be read. + */ +void SAI_ReadBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size); + +/*! + * @brief Reads data from SAI FIFO. + * + * @param base SAI base pointer. + * @param channel Data channel used. + * @return Data in SAI FIFO. + */ +static inline uint32_t SAI_ReadData(I2S_Type *base, uint32_t channel) +{ + return base->RDR[channel]; +} + +/*! @} */ + +/*! + * @name Transactional + * @{ + */ + +/*! + * @brief Initializes the SAI Tx handle. + * + * This function initializes the Tx handle for SAI Tx transactional APIs. Call + * this function one time to get the handle initialized. + * + * @param base SAI base pointer + * @param handle SAI handle pointer. + * @param callback pointer to user callback function + * @param userData user parameter passed to the callback function + */ +void SAI_TransferTxCreateHandle(I2S_Type *base, sai_handle_t *handle, sai_transfer_callback_t callback, void *userData); + +/*! + * @brief Initializes the SAI Rx handle. + * + * This function initializes the Rx handle for SAI Rx transactional APIs. Call + * this function one time to get the handle initialized. + * + * @param base SAI base pointer. + * @param handle SAI handle pointer. + * @param callback pointer to user callback function + * @param userData user parameter passed to the callback function + */ +void SAI_TransferRxCreateHandle(I2S_Type *base, sai_handle_t *handle, sai_transfer_callback_t callback, void *userData); + +/*! + * @brief Configures the SAI Tx audio format. + * + * The audio format can be changed at run-time. This function configures the sample rate and audio data + * format to be transferred. + * + * @param base SAI base pointer. + * @param handle SAI handle pointer. + * @param format Pointer to SAI audio data format structure. + * @param mclkSourceClockHz SAI master clock source frequency in Hz. + * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If a bit clock source is a master + * clock, this value should equal to masterClockHz in format. + * @return Status of this function. Return value is one of status_t. +*/ +status_t SAI_TransferTxSetFormat(I2S_Type *base, + sai_handle_t *handle, + sai_transfer_format_t *format, + uint32_t mclkSourceClockHz, + uint32_t bclkSourceClockHz); + +/*! + * @brief Configures the SAI Rx audio format. + * + * The audio format can be changed at run-time. This function configures the sample rate and audio data + * format to be transferred. + * + * @param base SAI base pointer. + * @param handle SAI handle pointer. + * @param format Pointer to SAI audio data format structure. + * @param mclkSourceClockHz SAI master clock source frequency in Hz. + * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If bit clock source is master + * clock, this value should equals to masterClockHz in format. + * @return Status of this function. Return value is one of status_t. +*/ +status_t SAI_TransferRxSetFormat(I2S_Type *base, + sai_handle_t *handle, + sai_transfer_format_t *format, + uint32_t mclkSourceClockHz, + uint32_t bclkSourceClockHz); + +/*! + * @brief Performs an interrupt non-blocking send transfer on SAI. + * + * @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. + * + * @param base SAI base pointer + * @param handle pointer to sai_handle_t structure which stores the transfer state + * @param xfer pointer to sai_transfer_t structure + * @retval kStatus_Success Successfully started the data receive. + * @retval kStatus_SAI_TxBusy Previous receive still not finished. + * @retval kStatus_InvalidArgument The input parameter is invalid. + */ +status_t SAI_TransferSendNonBlocking(I2S_Type *base, sai_handle_t *handle, sai_transfer_t *xfer); + +/*! + * @brief Performs an interrupt non-blocking receive transfer on SAI. + * + * @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. + * + * @param base SAI base pointer + * @param handle pointer to sai_handle_t structure which stores the transfer state + * @param xfer pointer to sai_transfer_t structure + * @retval kStatus_Success Successfully started the data receive. + * @retval kStatus_SAI_RxBusy Previous receive still not finished. + * @retval kStatus_InvalidArgument The input parameter is invalid. + */ +status_t SAI_TransferReceiveNonBlocking(I2S_Type *base, sai_handle_t *handle, sai_transfer_t *xfer); + +/*! + * @brief Gets a set byte count. + * + * @param base SAI base pointer. + * @param handle pointer to sai_handle_t structure which stores the transfer state. + * @param count Bytes count sent. + * @retval kStatus_Success Succeed get the transfer count. + * @retval kStatus_NoTransferInProgress There is not a non-blocking transaction currently in progress. + */ +status_t SAI_TransferGetSendCount(I2S_Type *base, sai_handle_t *handle, size_t *count); + +/*! + * @brief Gets a received byte count. + * + * @param base SAI base pointer. + * @param handle pointer to sai_handle_t structure which stores the transfer state. + * @param count Bytes count received. + * @retval kStatus_Success Succeed get the transfer count. + * @retval kStatus_NoTransferInProgress There is not a non-blocking transaction currently in progress. + */ +status_t SAI_TransferGetReceiveCount(I2S_Type *base, sai_handle_t *handle, size_t *count); + +/*! + * @brief Aborts the current send. + * + * @note This API can be called any time when an interrupt non-blocking transfer initiates + * to abort the transfer early. + * + * @param base SAI base pointer. + * @param handle pointer to sai_handle_t structure which stores the transfer state. + */ +void SAI_TransferAbortSend(I2S_Type *base, sai_handle_t *handle); + +/*! + * @brief Aborts the the current IRQ receive. + * + * @note This API can be called any time when an interrupt non-blocking transfer initiates + * to abort the transfer early. + * + * @param base SAI base pointer + * @param handle pointer to sai_handle_t structure which stores the transfer state. + */ +void SAI_TransferAbortReceive(I2S_Type *base, sai_handle_t *handle); + +/*! + * @brief Tx interrupt handler. + * + * @param base SAI base pointer. + * @param handle pointer to sai_handle_t structure. + */ +void SAI_TransferTxHandleIRQ(I2S_Type *base, sai_handle_t *handle); + +/*! + * @brief Tx interrupt handler. + * + * @param base SAI base pointer. + * @param handle pointer to sai_handle_t structure. + */ +void SAI_TransferRxHandleIRQ(I2S_Type *base, sai_handle_t *handle); + +/*! @} */ + +#if defined(__cplusplus) +} +#endif /*_cplusplus*/ + +/*! @} */ + +#endif /* _FSL_SAI_H_ */ diff --git a/drivers/include/fsl_sai_edma.h b/drivers/include/fsl_sai_edma.h new file mode 100644 index 0000000..03c2e51 --- /dev/null +++ b/drivers/include/fsl_sai_edma.h @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of Freescale Semiconductor, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_SAI_EDMA_H_ +#define _FSL_SAI_EDMA_H_ + +#include "fsl_sai.h" +#include "fsl_edma.h" + +/*! + * @addtogroup sai_edma + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +typedef struct _sai_edma_handle sai_edma_handle_t; + +/*! @brief SAI eDMA transfer callback function for finish and error */ +typedef void (*sai_edma_callback_t)(I2S_Type *base, sai_edma_handle_t *handle, status_t status, void *userData); + +/*! @brief SAI DMA transfer handle, users should not touch the content of the handle.*/ +struct _sai_edma_handle +{ + edma_handle_t *dmaHandle; /*!< DMA handler for SAI send */ + 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 */ +}; + +/******************************************************************************* + * APIs + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name eDMA Transactional + * @{ + */ + +/*! + * @brief Initializes the SAI eDMA handle. + * + * 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. + * + * @param base SAI base pointer. + * @param handle SAI eDMA handle pointer. + * @param base SAI peripheral base address. + * @param callback Pointer to user callback function. + * @param userData User parameter passed to the callback function. + * @param dmaHandle eDMA handle pointer, this handle shall be static allocated by users. + */ +void SAI_TransferTxCreateHandleEDMA( + I2S_Type *base, sai_edma_handle_t *handle, sai_edma_callback_t callback, void *userData, edma_handle_t *dmaHandle); + +/*! + * @brief Initializes the SAI Rx eDMA handle. + * + * 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. + * + * @param base SAI base pointer. + * @param handle SAI eDMA handle pointer. + * @param base SAI peripheral base address. + * @param callback Pointer to user callback function. + * @param userData User parameter passed to the callback function. + * @param dmaHandle eDMA handle pointer, this handle shall be static allocated by users. + */ +void SAI_TransferRxCreateHandleEDMA( + I2S_Type *base, sai_edma_handle_t *handle, sai_edma_callback_t callback, void *userData, edma_handle_t *dmaHandle); + +/*! + * @brief Configures the SAI Tx audio format. + * + * 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 formatting requirements. + * + * @param base SAI base pointer. + * @param handle SAI eDMA handle pointer. + * @param format Pointer to SAI audio data format structure. + * @param mclkSourceClockHz SAI master clock source frequency in Hz. + * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If bit clock source is master + * clock, this value should equals to masterClockHz in format. + * @retval kStatus_Success Audio format set successfully. + * @retval kStatus_InvalidArgument The input argument is invalid. +*/ +void SAI_TransferTxSetFormatEDMA(I2S_Type *base, + sai_edma_handle_t *handle, + sai_transfer_format_t *format, + uint32_t mclkSourceClockHz, + uint32_t bclkSourceClockHz); + +/*! + * @brief Configures the SAI Rx audio format. + * + * 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 formatting requirements. + * + * @param base SAI base pointer. + * @param handle SAI eDMA handle pointer. + * @param format Pointer to SAI audio data format structure. + * @param mclkSourceClockHz SAI master clock source frequency in Hz. + * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If a bit clock source is the master + * clock, this value should equal to masterClockHz in format. + * @retval kStatus_Success Audio format set successfully. + * @retval kStatus_InvalidArgument The input argument is invalid. +*/ +void SAI_TransferRxSetFormatEDMA(I2S_Type *base, + sai_edma_handle_t *handle, + sai_transfer_format_t *format, + uint32_t mclkSourceClockHz, + uint32_t bclkSourceClockHz); + +/*! + * @brief Performs a non-blocking SAI transfer using DMA. + * + * @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. + * + * @param base SAI base pointer. + * @param handle SAI eDMA handle pointer. + * @param xfer Pointer to the DMA transfer structure. + * @retval kStatus_Success Start a SAI eDMA send successfully. + * @retval kStatus_InvalidArgument The input argument is invalid. + * @retval kStatus_TxBusy SAI is busy sending data. + */ +status_t SAI_TransferSendEDMA(I2S_Type *base, sai_edma_handle_t *handle, sai_transfer_t *xfer); + +/*! + * @brief Performs a non-blocking SAI receive using eDMA. + * + * @note This interface returns immediately after the transfer initiates. Call + * the SAI_GetReceiveRemainingBytes to poll the transfer status and check whether the SAI transfer is finished. + * + * @param base SAI base pointer + * @param handle SAI eDMA handle pointer. + * @param xfer Pointer to DMA transfer structure. + * @retval kStatus_Success Start a SAI eDMA receive successfully. + * @retval kStatus_InvalidArgument The input argument is invalid. + * @retval kStatus_RxBusy SAI is busy receiving data. + */ +status_t SAI_TransferReceiveEDMA(I2S_Type *base, sai_edma_handle_t *handle, sai_transfer_t *xfer); + +/*! + * @brief Aborts a SAI transfer using eDMA. + * + * @param base SAI base pointer. + * @param handle SAI eDMA handle pointer. + */ +void SAI_TransferAbortSendEDMA(I2S_Type *base, sai_edma_handle_t *handle); + +/*! + * @brief Aborts a SAI receive using eDMA. + * + * @param base SAI base pointer + * @param handle SAI eDMA handle pointer. + */ +void SAI_TransferAbortReceiveEDMA(I2S_Type *base, sai_edma_handle_t *handle); + +/*! + * @brief Gets byte count sent by SAI. + * + * @param base SAI base pointer. + * @param handle SAI eDMA handle pointer. + * @param count Bytes count sent by SAI. + * @retval kStatus_Success Succeed get the transfer count. + * @retval kStatus_NoTransferInProgress There is no non-blocking transaction in progress. + */ +status_t SAI_TransferGetSendCountEDMA(I2S_Type *base, sai_edma_handle_t *handle, size_t *count); + +/*! + * @brief Gets byte count received by SAI. + * + * @param base SAI base pointer + * @param handle SAI eDMA handle pointer. + * @param count Bytes count received by SAI. + * @retval kStatus_Success Succeed get the transfer count. + * @retval kStatus_NoTransferInProgress There is no non-blocking transaction in progress. + */ +status_t SAI_TransferGetReceiveCountEDMA(I2S_Type *base, sai_edma_handle_t *handle, size_t *count); + +/*! @} */ + +#if defined(__cplusplus) +} +#endif + +/*! + * @} + */ +#endif diff --git a/drivers/include/fsl_sdhc.h b/drivers/include/fsl_sdhc.h new file mode 100644 index 0000000..336b961 --- /dev/null +++ b/drivers/include/fsl_sdhc.h @@ -0,0 +1,1095 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_SDHC_H_ +#define _FSL_SDHC_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup sdhc + * @{ + */ + +/****************************************************************************** + * Definitions. + *****************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief Driver version 2.1.5. */ +#define FSL_SDHC_DRIVER_VERSION (MAKE_VERSION(2U, 1U, 5U)) +/*@}*/ + +/*! @brief Maximum block count can be set one time */ +#define SDHC_MAX_BLOCK_COUNT (SDHC_BLKATTR_BLKCNT_MASK >> SDHC_BLKATTR_BLKCNT_SHIFT) + +/*! @brief SDHC status */ +enum _sdhc_status +{ + kStatus_SDHC_BusyTransferring = MAKE_STATUS(kStatusGroup_SDHC, 0U), /*!< Transfer is on-going */ + kStatus_SDHC_PrepareAdmaDescriptorFailed = MAKE_STATUS(kStatusGroup_SDHC, 1U), /*!< Set DMA descriptor failed */ + kStatus_SDHC_SendCommandFailed = MAKE_STATUS(kStatusGroup_SDHC, 2U), /*!< Send command failed */ + kStatus_SDHC_TransferDataFailed = MAKE_STATUS(kStatusGroup_SDHC, 3U), /*!< Transfer data failed */ + kStatus_SDHC_DMADataBufferAddrNotAlign = + MAKE_STATUS(kStatusGroup_SDHC, 4U), /*!< data buffer addr not align in DMA mode */ +}; + +/*! @brief Host controller capabilities flag mask */ +enum _sdhc_capability_flag +{ + kSDHC_SupportAdmaFlag = SDHC_HTCAPBLT_ADMAS_MASK, /*!< Support ADMA */ + kSDHC_SupportHighSpeedFlag = SDHC_HTCAPBLT_HSS_MASK, /*!< Support high-speed */ + kSDHC_SupportDmaFlag = SDHC_HTCAPBLT_DMAS_MASK, /*!< Support DMA */ + kSDHC_SupportSuspendResumeFlag = SDHC_HTCAPBLT_SRS_MASK, /*!< Support suspend/resume */ + kSDHC_SupportV330Flag = SDHC_HTCAPBLT_VS33_MASK, /*!< Support voltage 3.3V */ +#if defined FSL_FEATURE_SDHC_HAS_V300_SUPPORT && FSL_FEATURE_SDHC_HAS_V300_SUPPORT + kSDHC_SupportV300Flag = SDHC_HTCAPBLT_VS30_MASK, /*!< Support voltage 3.0V */ +#endif +#if defined FSL_FEATURE_SDHC_HAS_V180_SUPPORT && FSL_FEATURE_SDHC_HAS_V180_SUPPORT + kSDHC_SupportV180Flag = SDHC_HTCAPBLT_VS18_MASK, /*!< Support voltage 1.8V */ +#endif + /* Put additional two flags in HTCAPBLT_MBL's position. */ + kSDHC_Support4BitFlag = (SDHC_HTCAPBLT_MBL_SHIFT << 0U), /*!< Support 4 bit mode */ + kSDHC_Support8BitFlag = (SDHC_HTCAPBLT_MBL_SHIFT << 1U), /*!< Support 8 bit mode */ +}; + +/*! @brief Wakeup event mask */ +enum _sdhc_wakeup_event +{ + kSDHC_WakeupEventOnCardInt = SDHC_PROCTL_WECINT_MASK, /*!< Wakeup on card interrupt */ + kSDHC_WakeupEventOnCardInsert = SDHC_PROCTL_WECINS_MASK, /*!< Wakeup on card insertion */ + kSDHC_WakeupEventOnCardRemove = SDHC_PROCTL_WECRM_MASK, /*!< Wakeup on card removal */ + + kSDHC_WakeupEventsAll = (kSDHC_WakeupEventOnCardInt | kSDHC_WakeupEventOnCardInsert | + kSDHC_WakeupEventOnCardRemove), /*!< All wakeup events */ +}; + +/*! @brief Reset type mask */ +enum _sdhc_reset +{ + kSDHC_ResetAll = SDHC_SYSCTL_RSTA_MASK, /*!< Reset all except card detection */ + kSDHC_ResetCommand = SDHC_SYSCTL_RSTC_MASK, /*!< Reset command line */ + kSDHC_ResetData = SDHC_SYSCTL_RSTD_MASK, /*!< Reset data line */ + + kSDHC_ResetsAll = (kSDHC_ResetAll | kSDHC_ResetCommand | kSDHC_ResetData), /*!< All reset types */ +}; + +/*! @brief Transfer flag mask */ +enum _sdhc_transfer_flag +{ + kSDHC_EnableDmaFlag = SDHC_XFERTYP_DMAEN_MASK, /*!< Enable DMA */ + + kSDHC_CommandTypeSuspendFlag = (SDHC_XFERTYP_CMDTYP(1U)), /*!< Suspend command */ + kSDHC_CommandTypeResumeFlag = (SDHC_XFERTYP_CMDTYP(2U)), /*!< Resume command */ + kSDHC_CommandTypeAbortFlag = (SDHC_XFERTYP_CMDTYP(3U)), /*!< Abort command */ + + kSDHC_EnableBlockCountFlag = SDHC_XFERTYP_BCEN_MASK, /*!< Enable block count */ + kSDHC_EnableAutoCommand12Flag = SDHC_XFERTYP_AC12EN_MASK, /*!< Enable auto CMD12 */ + kSDHC_DataReadFlag = SDHC_XFERTYP_DTDSEL_MASK, /*!< Enable data read */ + kSDHC_MultipleBlockFlag = SDHC_XFERTYP_MSBSEL_MASK, /*!< Multiple block data read/write */ + + kSDHC_ResponseLength136Flag = SDHC_XFERTYP_RSPTYP(1U), /*!< 136 bit response length */ + kSDHC_ResponseLength48Flag = SDHC_XFERTYP_RSPTYP(2U), /*!< 48 bit response length */ + kSDHC_ResponseLength48BusyFlag = SDHC_XFERTYP_RSPTYP(3U), /*!< 48 bit response length with busy status */ + + kSDHC_EnableCrcCheckFlag = SDHC_XFERTYP_CCCEN_MASK, /*!< Enable CRC check */ + kSDHC_EnableIndexCheckFlag = SDHC_XFERTYP_CICEN_MASK, /*!< Enable index check */ + kSDHC_DataPresentFlag = SDHC_XFERTYP_DPSEL_MASK, /*!< Data present flag */ +}; + +/*! @brief Present status flag mask */ +enum _sdhc_present_status_flag +{ + kSDHC_CommandInhibitFlag = SDHC_PRSSTAT_CIHB_MASK, /*!< Command inhibit */ + kSDHC_DataInhibitFlag = SDHC_PRSSTAT_CDIHB_MASK, /*!< Data inhibit */ + kSDHC_DataLineActiveFlag = SDHC_PRSSTAT_DLA_MASK, /*!< Data line active */ + kSDHC_SdClockStableFlag = SDHC_PRSSTAT_SDSTB_MASK, /*!< SD bus clock stable */ + kSDHC_WriteTransferActiveFlag = SDHC_PRSSTAT_WTA_MASK, /*!< Write transfer active */ + kSDHC_ReadTransferActiveFlag = SDHC_PRSSTAT_RTA_MASK, /*!< Read transfer active */ + kSDHC_BufferWriteEnableFlag = SDHC_PRSSTAT_BWEN_MASK, /*!< Buffer write enable */ + kSDHC_BufferReadEnableFlag = SDHC_PRSSTAT_BREN_MASK, /*!< Buffer read enable */ + kSDHC_CardInsertedFlag = SDHC_PRSSTAT_CINS_MASK, /*!< Card inserted */ + kSDHC_CommandLineLevelFlag = SDHC_PRSSTAT_CLSL_MASK, /*!< Command line signal level */ + kSDHC_Data0LineLevelFlag = (1U << 24U), /*!< Data0 line signal level */ + kSDHC_Data1LineLevelFlag = (1U << 25U), /*!< Data1 line signal level */ + kSDHC_Data2LineLevelFlag = (1U << 26U), /*!< Data2 line signal level */ + kSDHC_Data3LineLevelFlag = (1U << 27U), /*!< Data3 line signal level */ + kSDHC_Data4LineLevelFlag = (1U << 28U), /*!< Data4 line signal level */ + kSDHC_Data5LineLevelFlag = (1U << 29U), /*!< Data5 line signal level */ + kSDHC_Data6LineLevelFlag = (1U << 30U), /*!< Data6 line signal level */ + kSDHC_Data7LineLevelFlag = (1U << 31U), /*!< Data7 line signal level */ +}; + +/*! @brief Interrupt status flag mask */ +enum _sdhc_interrupt_status_flag +{ + kSDHC_CommandCompleteFlag = SDHC_IRQSTAT_CC_MASK, /*!< Command complete */ + kSDHC_DataCompleteFlag = SDHC_IRQSTAT_TC_MASK, /*!< Data complete */ + kSDHC_BlockGapEventFlag = SDHC_IRQSTAT_BGE_MASK, /*!< Block gap event */ + kSDHC_DmaCompleteFlag = SDHC_IRQSTAT_DINT_MASK, /*!< DMA interrupt */ + kSDHC_BufferWriteReadyFlag = SDHC_IRQSTAT_BWR_MASK, /*!< Buffer write ready */ + kSDHC_BufferReadReadyFlag = SDHC_IRQSTAT_BRR_MASK, /*!< Buffer read ready */ + kSDHC_CardInsertionFlag = SDHC_IRQSTAT_CINS_MASK, /*!< Card inserted */ + kSDHC_CardRemovalFlag = SDHC_IRQSTAT_CRM_MASK, /*!< Card removed */ + kSDHC_CardInterruptFlag = SDHC_IRQSTAT_CINT_MASK, /*!< Card interrupt */ + kSDHC_CommandTimeoutFlag = SDHC_IRQSTAT_CTOE_MASK, /*!< Command timeout error */ + kSDHC_CommandCrcErrorFlag = SDHC_IRQSTAT_CCE_MASK, /*!< Command CRC error */ + kSDHC_CommandEndBitErrorFlag = SDHC_IRQSTAT_CEBE_MASK, /*!< Command end bit error */ + kSDHC_CommandIndexErrorFlag = SDHC_IRQSTAT_CIE_MASK, /*!< Command index error */ + kSDHC_DataTimeoutFlag = SDHC_IRQSTAT_DTOE_MASK, /*!< Data timeout error */ + kSDHC_DataCrcErrorFlag = SDHC_IRQSTAT_DCE_MASK, /*!< Data CRC error */ + kSDHC_DataEndBitErrorFlag = SDHC_IRQSTAT_DEBE_MASK, /*!< Data end bit error */ + kSDHC_AutoCommand12ErrorFlag = SDHC_IRQSTAT_AC12E_MASK, /*!< Auto CMD12 error */ + kSDHC_DmaErrorFlag = SDHC_IRQSTAT_DMAE_MASK, /*!< DMA error */ + + kSDHC_CommandErrorFlag = (kSDHC_CommandTimeoutFlag | kSDHC_CommandCrcErrorFlag | kSDHC_CommandEndBitErrorFlag | + kSDHC_CommandIndexErrorFlag), /*!< Command error */ + kSDHC_DataErrorFlag = (kSDHC_DataTimeoutFlag | kSDHC_DataCrcErrorFlag | kSDHC_DataEndBitErrorFlag | + kSDHC_AutoCommand12ErrorFlag), /*!< Data error */ + kSDHC_ErrorFlag = (kSDHC_CommandErrorFlag | kSDHC_DataErrorFlag | kSDHC_DmaErrorFlag), /*!< All error */ + kSDHC_DataFlag = (kSDHC_DataCompleteFlag | kSDHC_DmaCompleteFlag | kSDHC_BufferWriteReadyFlag | + kSDHC_BufferReadReadyFlag | kSDHC_DataErrorFlag | kSDHC_DmaErrorFlag), /*!< Data interrupts */ + kSDHC_CommandFlag = (kSDHC_CommandErrorFlag | kSDHC_CommandCompleteFlag), /*!< Command interrupts */ + kSDHC_CardDetectFlag = (kSDHC_CardInsertionFlag | kSDHC_CardRemovalFlag), /*!< Card detection interrupts */ + + kSDHC_AllInterruptFlags = (kSDHC_BlockGapEventFlag | kSDHC_CardInterruptFlag | kSDHC_CommandFlag | kSDHC_DataFlag | + kSDHC_ErrorFlag), /*!< All flags mask */ +}; + +/*! @brief Auto CMD12 error status flag mask */ +enum _sdhc_auto_command12_error_status_flag +{ + kSDHC_AutoCommand12NotExecutedFlag = SDHC_AC12ERR_AC12NE_MASK, /*!< Not executed error */ + kSDHC_AutoCommand12TimeoutFlag = SDHC_AC12ERR_AC12TOE_MASK, /*!< Timeout error */ + kSDHC_AutoCommand12EndBitErrorFlag = SDHC_AC12ERR_AC12EBE_MASK, /*!< End bit error */ + kSDHC_AutoCommand12CrcErrorFlag = SDHC_AC12ERR_AC12CE_MASK, /*!< CRC error */ + kSDHC_AutoCommand12IndexErrorFlag = SDHC_AC12ERR_AC12IE_MASK, /*!< Index error */ + kSDHC_AutoCommand12NotIssuedFlag = SDHC_AC12ERR_CNIBAC12E_MASK, /*!< Not issued error */ +}; + +/*! @brief ADMA error status flag mask */ +enum _sdhc_adma_error_status_flag +{ + kSDHC_AdmaLenghMismatchFlag = SDHC_ADMAES_ADMALME_MASK, /*!< Length mismatch error */ + kSDHC_AdmaDescriptorErrorFlag = SDHC_ADMAES_ADMADCE_MASK, /*!< Descriptor error */ +}; + +/*! + * @brief ADMA error state + * + * This state is the detail state when ADMA error has occurred. + */ +typedef enum _sdhc_adma_error_state +{ + kSDHC_AdmaErrorStateStopDma = 0x00U, /*!< Stop DMA */ + kSDHC_AdmaErrorStateFetchDescriptor = 0x01U, /*!< Fetch descriptor */ + kSDHC_AdmaErrorStateChangeAddress = 0x02U, /*!< Change address */ + kSDHC_AdmaErrorStateTransferData = 0x03U, /*!< Transfer data */ +} sdhc_adma_error_state_t; + +/*! @brief Force event mask */ +enum _sdhc_force_event +{ + kSDHC_ForceEventAutoCommand12NotExecuted = SDHC_FEVT_AC12NE_MASK, /*!< Auto CMD12 not executed error */ + kSDHC_ForceEventAutoCommand12Timeout = SDHC_FEVT_AC12TOE_MASK, /*!< Auto CMD12 timeout error */ + kSDHC_ForceEventAutoCommand12CrcError = SDHC_FEVT_AC12CE_MASK, /*!< Auto CMD12 CRC error */ + kSDHC_ForceEventEndBitError = SDHC_FEVT_AC12EBE_MASK, /*!< Auto CMD12 end bit error */ + kSDHC_ForceEventAutoCommand12IndexError = SDHC_FEVT_AC12IE_MASK, /*!< Auto CMD12 index error */ + kSDHC_ForceEventAutoCommand12NotIssued = SDHC_FEVT_CNIBAC12E_MASK, /*!< Auto CMD12 not issued error */ + kSDHC_ForceEventCommandTimeout = SDHC_FEVT_CTOE_MASK, /*!< Command timeout error */ + kSDHC_ForceEventCommandCrcError = SDHC_FEVT_CCE_MASK, /*!< Command CRC error */ + kSDHC_ForceEventCommandEndBitError = SDHC_FEVT_CEBE_MASK, /*!< Command end bit error */ + kSDHC_ForceEventCommandIndexError = SDHC_FEVT_CIE_MASK, /*!< Command index error */ + kSDHC_ForceEventDataTimeout = SDHC_FEVT_DTOE_MASK, /*!< Data timeout error */ + kSDHC_ForceEventDataCrcError = SDHC_FEVT_DCE_MASK, /*!< Data CRC error */ + kSDHC_ForceEventDataEndBitError = SDHC_FEVT_DEBE_MASK, /*!< Data end bit error */ + kSDHC_ForceEventAutoCommand12Error = SDHC_FEVT_AC12E_MASK, /*!< Auto CMD12 error */ + kSDHC_ForceEventCardInt = SDHC_FEVT_CINT_MASK, /*!< Card interrupt */ + kSDHC_ForceEventDmaError = SDHC_FEVT_DMAE_MASK, /*!< Dma error */ + + kSDHC_ForceEventsAll = + (kSDHC_ForceEventAutoCommand12NotExecuted | kSDHC_ForceEventAutoCommand12Timeout | + kSDHC_ForceEventAutoCommand12CrcError | kSDHC_ForceEventEndBitError | kSDHC_ForceEventAutoCommand12IndexError | + kSDHC_ForceEventAutoCommand12NotIssued | kSDHC_ForceEventCommandTimeout | kSDHC_ForceEventCommandCrcError | + kSDHC_ForceEventCommandEndBitError | kSDHC_ForceEventCommandIndexError | kSDHC_ForceEventDataTimeout | + kSDHC_ForceEventDataCrcError | kSDHC_ForceEventDataEndBitError | kSDHC_ForceEventAutoCommand12Error | + kSDHC_ForceEventCardInt | kSDHC_ForceEventDmaError), /*!< All force event flags mask */ +}; + +/*! @brief Data transfer width */ +typedef enum _sdhc_data_bus_width +{ + kSDHC_DataBusWidth1Bit = 0U, /*!< 1-bit mode */ + kSDHC_DataBusWidth4Bit = 1U, /*!< 4-bit mode */ + kSDHC_DataBusWidth8Bit = 2U, /*!< 8-bit mode */ +} sdhc_data_bus_width_t; + +/*! @brief Endian mode */ +typedef enum _sdhc_endian_mode +{ + kSDHC_EndianModeBig = 0U, /*!< Big endian mode */ + kSDHC_EndianModeHalfWordBig = 1U, /*!< Half word big endian mode */ + kSDHC_EndianModeLittle = 2U, /*!< Little endian mode */ +} sdhc_endian_mode_t; + +/*! @brief DMA mode */ +typedef enum _sdhc_dma_mode +{ + kSDHC_DmaModeNo = 0U, /*!< No DMA */ + kSDHC_DmaModeAdma1 = 1U, /*!< ADMA1 is selected */ + kSDHC_DmaModeAdma2 = 2U, /*!< ADMA2 is selected */ +} sdhc_dma_mode_t; + +/*! @brief SDIO control flag mask */ +enum _sdhc_sdio_control_flag +{ + kSDHC_StopAtBlockGapFlag = 0x01, /*!< Stop at block gap */ + kSDHC_ReadWaitControlFlag = 0x02, /*!< Read wait control */ + kSDHC_InterruptAtBlockGapFlag = 0x04, /*!< Interrupt at block gap */ + kSDHC_ExactBlockNumberReadFlag = 0x08, /*!< Exact block number read */ +}; + +/*! @brief MMC card boot mode */ +typedef enum _sdhc_boot_mode +{ + kSDHC_BootModeNormal = 0U, /*!< Normal boot */ + kSDHC_BootModeAlternative = 1U, /*!< Alternative boot */ +} sdhc_boot_mode_t; + +/*! @brief The command type */ +typedef enum _sdhc_card_command_type +{ + kCARD_CommandTypeNormal = 0U, /*!< Normal command */ + kCARD_CommandTypeSuspend = 1U, /*!< Suspend command */ + kCARD_CommandTypeResume = 2U, /*!< Resume command */ + kCARD_CommandTypeAbort = 3U, /*!< Abort command */ +} sdhc_card_command_type_t; + +/*! + * @brief The command response type. + * + * Define the command response type from card to host controller. + */ +typedef enum _sdhc_card_response_type +{ + kCARD_ResponseTypeNone = 0U, /*!< Response type: none */ + kCARD_ResponseTypeR1 = 1U, /*!< Response type: R1 */ + kCARD_ResponseTypeR1b = 2U, /*!< Response type: R1b */ + kCARD_ResponseTypeR2 = 3U, /*!< Response type: R2 */ + kCARD_ResponseTypeR3 = 4U, /*!< Response type: R3 */ + kCARD_ResponseTypeR4 = 5U, /*!< Response type: R4 */ + kCARD_ResponseTypeR5 = 6U, /*!< Response type: R5 */ + kCARD_ResponseTypeR5b = 7U, /*!< Response type: R5b */ + kCARD_ResponseTypeR6 = 8U, /*!< Response type: R6 */ + kCARD_ResponseTypeR7 = 9U, /*!< Response type: R7 */ +} sdhc_card_response_type_t; + +/*! @brief The alignment size for ADDRESS filed in ADMA1's descriptor */ +#define SDHC_ADMA1_ADDRESS_ALIGN (4096U) +/*! @brief The alignment size for LENGTH field in ADMA1's descriptor */ +#define SDHC_ADMA1_LENGTH_ALIGN (4096U) +/*! @brief The alignment size for ADDRESS field in ADMA2's descriptor */ +#define SDHC_ADMA2_ADDRESS_ALIGN (4U) +/*! @brief The alignment size for LENGTH filed in ADMA2's descriptor */ +#define SDHC_ADMA2_LENGTH_ALIGN (4U) + +/* ADMA1 descriptor table + * |------------------------|---------|--------------------------| + * | Address/page field |Reserved | Attribute | + * |------------------------|---------|--------------------------| + * |31 12|11 6|05 |04 |03|02 |01 |00 | + * |------------------------|---------|----|----|--|---|---|-----| + * | address or data length | 000000 |Act2|Act1| 0|Int|End|Valid| + * |------------------------|---------|----|----|--|---|---|-----| + * + * + * |------|------|-----------------|-------|-------------| + * | Act2 | Act1 | Comment | 31-28 | 27 - 12 | + * |------|------|-----------------|---------------------| + * | 0 | 0 | No op | Don't care | + * |------|------|-----------------|-------|-------------| + * | 0 | 1 | Set data length | 0000 | Data Length | + * |------|------|-----------------|-------|-------------| + * | 1 | 0 | Transfer data | Data address | + * |------|------|-----------------|---------------------| + * | 1 | 1 | Link descriptor | Descriptor address | + * |------|------|-----------------|---------------------| + */ +/*! @brief The bit shift for ADDRESS filed in ADMA1's descriptor */ +#define SDHC_ADMA1_DESCRIPTOR_ADDRESS_SHIFT (12U) +/*! @brief The bit mask for ADDRESS field in ADMA1's descriptor */ +#define SDHC_ADMA1_DESCRIPTOR_ADDRESS_MASK (0xFFFFFU) +/*! @brief The bit shift for LENGTH filed in ADMA1's descriptor */ +#define SDHC_ADMA1_DESCRIPTOR_LENGTH_SHIFT (12U) +/*! @brief The mask for LENGTH field in ADMA1's descriptor */ +#define SDHC_ADMA1_DESCRIPTOR_LENGTH_MASK (0xFFFFU) +/*! @brief The maximum value of LENGTH filed in ADMA1's descriptor */ +#define SDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY (SDHC_ADMA1_DESCRIPTOR_LENGTH_MASK + 1U) + +/*! @brief The mask for the control/status field in ADMA1 descriptor */ +enum _sdhc_adma1_descriptor_flag +{ + kSDHC_Adma1DescriptorValidFlag = (1U << 0U), /*!< Valid flag */ + kSDHC_Adma1DescriptorEndFlag = (1U << 1U), /*!< End flag */ + kSDHC_Adma1DescriptorInterrupFlag = (1U << 2U), /*!< Interrupt flag */ + kSDHC_Adma1DescriptorActivity1Flag = (1U << 4U), /*!< Activity 1 flag */ + kSDHC_Adma1DescriptorActivity2Flag = (1U << 5U), /*!< Activity 2 flag */ + kSDHC_Adma1DescriptorTypeNop = (kSDHC_Adma1DescriptorValidFlag), /*!< No operation */ + kSDHC_Adma1DescriptorTypeTransfer = + (kSDHC_Adma1DescriptorActivity2Flag | kSDHC_Adma1DescriptorValidFlag), /*!< Transfer data */ + kSDHC_Adma1DescriptorTypeLink = (kSDHC_Adma1DescriptorActivity1Flag | kSDHC_Adma1DescriptorActivity2Flag | + kSDHC_Adma1DescriptorValidFlag), /*!< Link descriptor */ + kSDHC_Adma1DescriptorTypeSetLength = + (kSDHC_Adma1DescriptorActivity1Flag | kSDHC_Adma1DescriptorValidFlag), /*!< Set data length */ +}; + +/* ADMA2 descriptor table + * |----------------|---------------|-------------|--------------------------| + * | Address field | Length | Reserved | Attribute | + * |----------------|---------------|-------------|--------------------------| + * |63 32|31 16|15 06|05 |04 |03|02 |01 |00 | + * |----------------|---------------|-------------|----|----|--|---|---|-----| + * | 32-bit address | 16-bit length | 0000000000 |Act2|Act1| 0|Int|End|Valid| + * |----------------|---------------|-------------|----|----|--|---|---|-----| + * + * + * | Act2 | Act1 | Comment | Operation | + * |------|------|-----------------|-------------------------------------------------------------------| + * | 0 | 0 | No op | Don't care | + * |------|------|-----------------|-------------------------------------------------------------------| + * | 0 | 1 | Reserved | Read this line and go to next one | + * |------|------|-----------------|-------------------------------------------------------------------| + * | 1 | 0 | Transfer data | Transfer data with address and length set in this descriptor line | + * |------|------|-----------------|-------------------------------------------------------------------| + * | 1 | 1 | Link descriptor | Link to another descriptor | + * |------|------|-----------------|-------------------------------------------------------------------| + */ +/*! @brief The bit shift for LENGTH field in ADMA2's descriptor */ +#define SDHC_ADMA2_DESCRIPTOR_LENGTH_SHIFT (16U) +/*! @brief The bit mask for LENGTH field in ADMA2's descriptor */ +#define SDHC_ADMA2_DESCRIPTOR_LENGTH_MASK (0xFFFFU) +/*! @brief The maximum value of LENGTH field in ADMA2's descriptor */ +#define SDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY (SDHC_ADMA2_DESCRIPTOR_LENGTH_MASK) + +/*! @brief ADMA1 descriptor control and status mask */ +enum _sdhc_adma2_descriptor_flag +{ + kSDHC_Adma2DescriptorValidFlag = (1U << 0U), /*!< Valid flag */ + kSDHC_Adma2DescriptorEndFlag = (1U << 1U), /*!< End flag */ + kSDHC_Adma2DescriptorInterruptFlag = (1U << 2U), /*!< Interrupt flag */ + kSDHC_Adma2DescriptorActivity1Flag = (1U << 4U), /*!< Activity 1 mask */ + kSDHC_Adma2DescriptorActivity2Flag = (1U << 5U), /*!< Activity 2 mask */ + + kSDHC_Adma2DescriptorTypeNop = (kSDHC_Adma2DescriptorValidFlag), /*!< No operation */ + kSDHC_Adma2DescriptorTypeReserved = + (kSDHC_Adma2DescriptorActivity1Flag | kSDHC_Adma2DescriptorValidFlag), /*!< Reserved */ + kSDHC_Adma2DescriptorTypeTransfer = + (kSDHC_Adma2DescriptorActivity2Flag | kSDHC_Adma2DescriptorValidFlag), /*!< Transfer type */ + kSDHC_Adma2DescriptorTypeLink = (kSDHC_Adma2DescriptorActivity1Flag | kSDHC_Adma2DescriptorActivity2Flag | + kSDHC_Adma2DescriptorValidFlag), /*!< Link type */ +}; + +/*! @brief Defines the adma1 descriptor structure. */ +typedef uint32_t sdhc_adma1_descriptor_t; + +/*! @brief Defines the ADMA2 descriptor structure. */ +typedef struct _sdhc_adma2_descriptor +{ + uint32_t attribute; /*!< The control and status field */ + const uint32_t *address; /*!< The address field */ +} sdhc_adma2_descriptor_t; + +/*! + * @brief SDHC capability information. + * + * Defines a structure to save the capability information of SDHC. + */ +typedef struct _sdhc_capability +{ + uint32_t specVersion; /*!< Specification version */ + uint32_t vendorVersion; /*!< Vendor version */ + uint32_t maxBlockLength; /*!< Maximum block length united as byte */ + uint32_t maxBlockCount; /*!< Maximum block count can be set one time */ + uint32_t flags; /*!< Capability flags to indicate the support information(_sdhc_capability_flag) */ +} sdhc_capability_t; + +/*! @brief Card transfer configuration. + * + * Define structure to configure the transfer-related command index/argument/flags and data block + * size/data block numbers. This structure needs to be filled each time a command is sent to the card. + */ +typedef struct _sdhc_transfer_config +{ + size_t dataBlockSize; /*!< Data block size */ + uint32_t dataBlockCount; /*!< Data block count */ + uint32_t commandArgument; /*!< Command argument */ + uint32_t commandIndex; /*!< Command index */ + uint32_t flags; /*!< Transfer flags(_sdhc_transfer_flag) */ +} sdhc_transfer_config_t; + +/*! @brief Data structure to configure the MMC boot feature */ +typedef struct _sdhc_boot_config +{ + uint32_t ackTimeoutCount; /*!< Timeout value for the boot ACK. The available range is 0 ~ 15. */ + sdhc_boot_mode_t bootMode; /*!< Boot mode selection. */ + uint32_t blockCount; /*!< Stop at block gap value of automatic mode. Available range is 0 ~ 65535. */ + bool enableBootAck; /*!< Enable or disable boot ACK */ + bool enableBoot; /*!< Enable or disable fast boot */ + bool enableAutoStopAtBlockGap; /*!< Enable or disable auto stop at block gap function in boot period */ +} sdhc_boot_config_t; + +/*! @brief Data structure to initialize the SDHC */ +typedef struct _sdhc_config +{ + bool cardDetectDat3; /*!< Enable DAT3 as card detection pin */ + sdhc_endian_mode_t endianMode; /*!< Endian mode */ + sdhc_dma_mode_t dmaMode; /*!< DMA mode */ + uint32_t readWatermarkLevel; /*!< Watermark level for DMA read operation. Available range is 1 ~ 128. */ + uint32_t writeWatermarkLevel; /*!< Watermark level for DMA write operation. Available range is 1 ~ 128. */ +} sdhc_config_t; + +/*! + * @brief Card data descriptor + * + * Defines a structure to contain data-related attribute. 'enableIgnoreError' is used for the case that upper card + * driver + * want to ignore the error event to read/write all the data not to stop read/write immediately when error event + * happen for example bus testing procedure for MMC card. + */ +typedef struct _sdhc_data +{ + bool enableAutoCommand12; /*!< Enable auto CMD12 */ + bool enableIgnoreError; /*!< Enable to ignore error event to read/write all the data */ + size_t blockSize; /*!< Block size */ + uint32_t blockCount; /*!< Block count */ + uint32_t *rxData; /*!< Buffer to save data read */ + const uint32_t *txData; /*!< Data buffer to write */ +} sdhc_data_t; + +/*! + * @brief Card command descriptor + * + * Define card command-related attribute. + */ +typedef struct _sdhc_command +{ + uint32_t index; /*!< Command index */ + uint32_t argument; /*!< Command argument */ + sdhc_card_command_type_t type; /*!< Command type */ + sdhc_card_response_type_t responseType; /*!< Command response type */ + uint32_t response[4U]; /*!< Response for this command */ + uint32_t responseErrorFlags; /*!< response error flag, the flag which need to check + the command reponse*/ +} sdhc_command_t; + +/*! @brief Transfer state */ +typedef struct _sdhc_transfer +{ + sdhc_data_t *data; /*!< Data to transfer */ + sdhc_command_t *command; /*!< Command to send */ +} sdhc_transfer_t; + +/*! @brief SDHC handle typedef */ +typedef struct _sdhc_handle sdhc_handle_t; + +/*! @brief SDHC callback functions. */ +typedef struct _sdhc_transfer_callback +{ + void (*CardInserted)(void); /*!< Card inserted occurs when DAT3/CD pin is for card detect */ + void (*CardRemoved)(void); /*!< Card removed occurs */ + void (*SdioInterrupt)(void); /*!< SDIO card interrupt occurs */ + void (*SdioBlockGap)(void); /*!< SDIO card stopped at block gap occurs */ + void (*TransferComplete)(SDHC_Type *base, + sdhc_handle_t *handle, + status_t status, + void *userData); /*!< Transfer complete callback */ +} sdhc_transfer_callback_t; + +/*! + * @brief SDHC handle + * + * Defines the structure to save the SDHC state information and callback function. The detailed interrupt status when + * sending a command or transfering data can be obtained from the interruptFlags field by using the mask defined in + * sdhc_interrupt_flag_t. + * + * @note All the fields except interruptFlags and transferredWords must be allocated by the user. + */ +struct _sdhc_handle +{ + /* Transfer parameter */ + sdhc_data_t *volatile data; /*!< Data to transfer */ + sdhc_command_t *volatile command; /*!< Command to send */ + + /* Transfer status */ + volatile uint32_t interruptFlags; /*!< Interrupt flags of last transaction */ + volatile uint32_t transferredWords; /*!< Words transferred by DATAPORT way */ + + /* Callback functions */ + sdhc_transfer_callback_t callback; /*!< Callback function */ + void *userData; /*!< Parameter for transfer complete callback */ +}; + +/*! @brief SDHC transfer function. */ +typedef status_t (*sdhc_transfer_function_t)(SDHC_Type *base, sdhc_transfer_t *content); + +/*! @brief SDHC host descriptor */ +typedef struct _sdhc_host +{ + SDHC_Type *base; /*!< SDHC peripheral base address */ + uint32_t sourceClock_Hz; /*!< SDHC source clock frequency united in Hz */ + sdhc_config_t config; /*!< SDHC configuration */ + sdhc_capability_t capability; /*!< SDHC capability information */ + sdhc_transfer_function_t transfer; /*!< SDHC transfer function */ +} sdhc_host_t; + +/************************************************************************************************* + * API + ************************************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief SDHC module initialization function. + * + * Configures the SDHC according to the user configuration. + * + * Example: + @code + sdhc_config_t config; + config.cardDetectDat3 = false; + config.endianMode = kSDHC_EndianModeLittle; + config.dmaMode = kSDHC_DmaModeAdma2; + config.readWatermarkLevel = 128U; + config.writeWatermarkLevel = 128U; + SDHC_Init(SDHC, &config); + @endcode + * + * @param base SDHC peripheral base address. + * @param config SDHC configuration information. + * @retval kStatus_Success Operate successfully. + */ +void SDHC_Init(SDHC_Type *base, const sdhc_config_t *config); + +/*! + * @brief Deinitializes the SDHC. + * + * @param base SDHC peripheral base address. + */ +void SDHC_Deinit(SDHC_Type *base); + +/*! + * @brief Resets the SDHC. + * + * @param base SDHC peripheral base address. + * @param mask The reset type mask(_sdhc_reset). + * @param timeout Timeout for reset. + * @retval true Reset successfully. + * @retval false Reset failed. + */ +bool SDHC_Reset(SDHC_Type *base, uint32_t mask, uint32_t timeout); + +/* @} */ + +/*! + * @name DMA Control + * @{ + */ + +/*! + * @brief Sets the ADMA descriptor table configuration. + * + * @param base SDHC peripheral base address. + * @param dmaMode DMA mode. + * @param table ADMA table address. + * @param tableWords ADMA table buffer length united as Words. + * @param data Data buffer address. + * @param dataBytes Data length united as bytes. + * @retval kStatus_OutOfRange ADMA descriptor table length isn't enough to describe data. + * @retval kStatus_Success Operate successfully. + */ +status_t SDHC_SetAdmaTableConfig(SDHC_Type *base, + sdhc_dma_mode_t dmaMode, + uint32_t *table, + uint32_t tableWords, + const uint32_t *data, + uint32_t dataBytes); + +/* @} */ + +/*! + * @name Interrupts + * @{ + */ + +/*! + * @brief Enables the interrupt status. + * + * @param base SDHC peripheral base address. + * @param mask Interrupt status flags mask(_sdhc_interrupt_status_flag). + */ +static inline void SDHC_EnableInterruptStatus(SDHC_Type *base, uint32_t mask) +{ + base->IRQSTATEN |= mask; +} + +/*! + * @brief Disables the interrupt status. + * + * @param base SDHC peripheral base address. + * @param mask The interrupt status flags mask(_sdhc_interrupt_status_flag). + */ +static inline void SDHC_DisableInterruptStatus(SDHC_Type *base, uint32_t mask) +{ + base->IRQSTATEN &= ~mask; +} + +/*! + * @brief Enables the interrupt signal corresponding to the interrupt status flag. + * + * @param base SDHC peripheral base address. + * @param mask The interrupt status flags mask(_sdhc_interrupt_status_flag). + */ +static inline void SDHC_EnableInterruptSignal(SDHC_Type *base, uint32_t mask) +{ + base->IRQSIGEN |= mask; +} + +/*! + * @brief Disables the interrupt signal corresponding to the interrupt status flag. + * + * @param base SDHC peripheral base address. + * @param mask The interrupt status flags mask(_sdhc_interrupt_status_flag). + */ +static inline void SDHC_DisableInterruptSignal(SDHC_Type *base, uint32_t mask) +{ + base->IRQSIGEN &= ~mask; +} + +/* @} */ + +/*! + * @name Status + * @{ + */ + +/*! + * @brief Gets the current interrupt status. + * + * @param base SDHC peripheral base address. + * @return Current interrupt status flags mask(_sdhc_interrupt_status_flag). + */ +static inline uint32_t SDHC_GetInterruptStatusFlags(SDHC_Type *base) +{ + return base->IRQSTAT; +} + +/*! + * @brief Clears a specified interrupt status. + * + * @param base SDHC peripheral base address. + * @param mask The interrupt status flags mask(_sdhc_interrupt_status_flag). + */ +static inline void SDHC_ClearInterruptStatusFlags(SDHC_Type *base, uint32_t mask) +{ + base->IRQSTAT = mask; +} + +/*! + * @brief Gets the status of auto command 12 error. + * + * @param base SDHC peripheral base address. + * @return Auto command 12 error status flags mask(_sdhc_auto_command12_error_status_flag). + */ +static inline uint32_t SDHC_GetAutoCommand12ErrorStatusFlags(SDHC_Type *base) +{ + return base->AC12ERR; +} + +/*! + * @brief Gets the status of the ADMA error. + * + * @param base SDHC peripheral base address. + * @return ADMA error status flags mask(_sdhc_adma_error_status_flag). + */ +static inline uint32_t SDHC_GetAdmaErrorStatusFlags(SDHC_Type *base) +{ + return base->ADMAES; +} + +/*! + * @brief Gets a present status. + * + * This function gets the present SDHC's status except for an interrupt status and an error status. + * + * @param base SDHC peripheral base address. + * @return Present SDHC's status flags mask(_sdhc_present_status_flag). + */ +static inline uint32_t SDHC_GetPresentStatusFlags(SDHC_Type *base) +{ + return base->PRSSTAT; +} + +/* @} */ + +/*! + * @name Bus Operations + * @{ + */ + +/*! + * @brief Gets the capability information. + * + * @param base SDHC peripheral base address. + * @param capability Structure to save capability information. + */ +void SDHC_GetCapability(SDHC_Type *base, sdhc_capability_t *capability); + +/*! + * @brief Enables or disables the SD bus clock. + * + * @param base SDHC peripheral base address. + * @param enable True to enable, false to disable. + */ +static inline void SDHC_EnableSdClock(SDHC_Type *base, bool enable) +{ + if (enable) + { + base->SYSCTL |= SDHC_SYSCTL_SDCLKEN_MASK; + } + else + { + base->SYSCTL &= ~SDHC_SYSCTL_SDCLKEN_MASK; + } +} + +/*! + * @brief Sets the SD bus clock frequency. + * + * @param base SDHC peripheral base address. + * @param srcClock_Hz SDHC source clock frequency united in Hz. + * @param busClock_Hz SD bus clock frequency united in Hz. + * + * @return The nearest frequency of busClock_Hz configured to SD bus. + */ +uint32_t SDHC_SetSdClock(SDHC_Type *base, uint32_t srcClock_Hz, uint32_t busClock_Hz); + +/*! + * @brief Sends 80 clocks to the card to set it to the active state. + * + * This function must be called each time the card is inserted to ensure that the card can receive the command + * correctly. + * + * @param base SDHC peripheral base address. + * @param timeout Timeout to initialize card. + * @retval true Set card active successfully. + * @retval false Set card active failed. + */ +bool SDHC_SetCardActive(SDHC_Type *base, uint32_t timeout); + +/*! + * @brief Sets the data transfer width. + * + * @param base SDHC peripheral base address. + * @param width Data transfer width. + */ +static inline void SDHC_SetDataBusWidth(SDHC_Type *base, sdhc_data_bus_width_t width) +{ + base->PROCTL = ((base->PROCTL & ~SDHC_PROCTL_DTW_MASK) | SDHC_PROCTL_DTW(width)); +} + +/*! + * @brief Sets the card transfer-related configuration. + * + * This function fills the card transfer-related command argument/transfer flag/data size. The command and data are sent + by + * SDHC after calling this function. + * + * Example: + @code + sdhc_transfer_config_t transferConfig; + transferConfig.dataBlockSize = 512U; + transferConfig.dataBlockCount = 2U; + transferConfig.commandArgument = 0x01AAU; + transferConfig.commandIndex = 8U; + transferConfig.flags |= (kSDHC_EnableDmaFlag | kSDHC_EnableAutoCommand12Flag | kSDHC_MultipleBlockFlag); + SDHC_SetTransferConfig(SDHC, &transferConfig); + @endcode + * + * @param base SDHC peripheral base address. + * @param config Command configuration structure. + */ +void SDHC_SetTransferConfig(SDHC_Type *base, const sdhc_transfer_config_t *config); + +/*! + * @brief Gets the command response. + * + * @param base SDHC peripheral base address. + * @param index The index of response register, range from 0 to 3. + * @return Response register transfer. + */ +static inline uint32_t SDHC_GetCommandResponse(SDHC_Type *base, uint32_t index) +{ + assert(index < 4U); + + return base->CMDRSP[index]; +} + +/*! + * @brief Fills the the data port. + * + * This function is used to implement the data transfer by Data Port instead of DMA. + * + * @param base SDHC peripheral base address. + * @param data The data about to be sent. + */ +static inline void SDHC_WriteData(SDHC_Type *base, uint32_t data) +{ + base->DATPORT = data; +} + +/*! + * @brief Retrieves the data from the data port. + * + * This function is used to implement the data transfer by Data Port instead of DMA. + * + * @param base SDHC peripheral base address. + * @return The data has been read. + */ +static inline uint32_t SDHC_ReadData(SDHC_Type *base) +{ + return base->DATPORT; +} + +/*! + * @brief Enables or disables a wakeup event in low-power mode. + * + * @param base SDHC peripheral base address. + * @param mask Wakeup events mask(_sdhc_wakeup_event). + * @param enable True to enable, false to disable. + */ +static inline void SDHC_EnableWakeupEvent(SDHC_Type *base, uint32_t mask, bool enable) +{ + if (enable) + { + base->PROCTL |= mask; + } + else + { + base->PROCTL &= ~mask; + } +} + +/*! + * @brief Enables or disables the card detection level for testing. + * + * @param base SDHC peripheral base address. + * @param enable True to enable, false to disable. + */ +static inline void SDHC_EnableCardDetectTest(SDHC_Type *base, bool enable) +{ + if (enable) + { + base->PROCTL |= SDHC_PROCTL_CDSS_MASK; + } + else + { + base->PROCTL &= ~SDHC_PROCTL_CDSS_MASK; + } +} + +/*! + * @brief Sets the card detection test level. + * + * This function sets the card detection test level to indicate whether the card is inserted into the SDHC when DAT[3]/ + * CD pin is selected as a card detection pin. This function can also assert the pin logic when DAT[3]/CD pin is + * selected + * as the card detection pin. + * + * @param base SDHC peripheral base address. + * @param high True to set the card detect level to high. + */ +static inline void SDHC_SetCardDetectTestLevel(SDHC_Type *base, bool high) +{ + if (high) + { + base->PROCTL |= SDHC_PROCTL_CDTL_MASK; + } + else + { + base->PROCTL &= ~SDHC_PROCTL_CDTL_MASK; + } +} + +/*! + * @brief Enables or disables the SDIO card control. + * + * @param base SDHC peripheral base address. + * @param mask SDIO card control flags mask(_sdhc_sdio_control_flag). + * @param enable True to enable, false to disable. + */ +void SDHC_EnableSdioControl(SDHC_Type *base, uint32_t mask, bool enable); + +/*! + * @brief Restarts a transaction which has stopped at the block GAP for the SDIO card. + * + * @param base SDHC peripheral base address. + */ +static inline void SDHC_SetContinueRequest(SDHC_Type *base) +{ + base->PROCTL |= SDHC_PROCTL_CREQ_MASK; +} + +/*! + * @brief Configures the MMC boot feature. + * + * Example: + @code + sdhc_boot_config_t config; + config.ackTimeoutCount = 4; + config.bootMode = kSDHC_BootModeNormal; + config.blockCount = 5; + config.enableBootAck = true; + config.enableBoot = true; + config.enableAutoStopAtBlockGap = true; + SDHC_SetMmcBootConfig(SDHC, &config); + @endcode + * + * @param base SDHC peripheral base address. + * @param config The MMC boot configuration information. + */ +void SDHC_SetMmcBootConfig(SDHC_Type *base, const sdhc_boot_config_t *config); + +/*! + * @brief Forces generating events according to the given mask. + * + * @param base SDHC peripheral base address. + * @param mask The force events mask(_sdhc_force_event). + */ +static inline void SDHC_SetForceEvent(SDHC_Type *base, uint32_t mask) +{ + base->FEVT = mask; +} + +/* @} */ + +/*! + * @name Transactional + * @{ + */ + +/*! + * @brief Transfers the command/data using a blocking method. + * + * This function waits until the command response/data is received or the SDHC encounters an error by polling the status + * flag. + * This function support non word align data addr transfer support, if data buffer addr is not align in DMA mode, + * the API will continue finish the transfer by polling IO directly + * The application must not call this API in multiple threads at the same time. Because of that this API doesn't support + * the re-entry mechanism. + * + * @note There is no need to call the API 'SDHC_TransferCreateHandle' when calling this API. + * + * @param base SDHC peripheral base address. + * @param admaTable ADMA table address, can't be null if transfer way is ADMA1/ADMA2. + * @param admaTableWords ADMA table length united as words, can't be 0 if transfer way is ADMA1/ADMA2. + * @param transfer Transfer content. + * @retval kStatus_InvalidArgument Argument is invalid. + * @retval kStatus_SDHC_PrepareAdmaDescriptorFailed Prepare ADMA descriptor failed. + * @retval kStatus_SDHC_SendCommandFailed Send command failed. + * @retval kStatus_SDHC_TransferDataFailed Transfer data failed. + * @retval kStatus_Success Operate successfully. + */ +status_t SDHC_TransferBlocking(SDHC_Type *base, + uint32_t *admaTable, + uint32_t admaTableWords, + sdhc_transfer_t *transfer); + +/*! + * @brief Creates the SDHC handle. + * + * @param base SDHC peripheral base address. + * @param handle SDHC handle pointer. + * @param callback Structure pointer to contain all callback functions. + * @param userData Callback function parameter. + */ +void SDHC_TransferCreateHandle(SDHC_Type *base, + sdhc_handle_t *handle, + const sdhc_transfer_callback_t *callback, + void *userData); + +/*! + * @brief Transfers the command/data using an interrupt and an asynchronous method. + * + * This function sends a command and data and returns immediately. It doesn't wait the transfer complete or encounter an + * error. + * This function support non word align data addr transfer support, if data buffer addr is not align in DMA mode, + * the API will continue finish the transfer by polling IO directly + * The application must not call this API in multiple threads at the same time. Because of that this API doesn't support + * the re-entry mechanism. + * + * @note Call the API 'SDHC_TransferCreateHandle' when calling this API. + * + * @param base SDHC peripheral base address. + * @param handle SDHC handle. + * @param admaTable ADMA table address, can't be null if transfer way is ADMA1/ADMA2. + * @param admaTableWords ADMA table length united as words, can't be 0 if transfer way is ADMA1/ADMA2. + * @param transfer Transfer content. + * @retval kStatus_InvalidArgument Argument is invalid. + * @retval kStatus_SDHC_BusyTransferring Busy transferring. + * @retval kStatus_SDHC_PrepareAdmaDescriptorFailed Prepare ADMA descriptor failed. + * @retval kStatus_Success Operate successfully. + */ +status_t SDHC_TransferNonBlocking( + SDHC_Type *base, sdhc_handle_t *handle, uint32_t *admaTable, uint32_t admaTableWords, sdhc_transfer_t *transfer); + +/*! + * @brief IRQ handler for the SDHC. + * + * This function deals with the IRQs on the given host controller. + * + * @param base SDHC peripheral base address. + * @param handle SDHC handle. + */ +void SDHC_TransferHandleIRQ(SDHC_Type *base, sdhc_handle_t *handle); + +/* @} */ + +#if defined(__cplusplus) +} +#endif +/*! @} */ + +#endif /* _FSL_SDHC_H_*/ diff --git a/drivers/include/fsl_sim.h b/drivers/include/fsl_sim.h new file mode 100644 index 0000000..0a0e4fb --- /dev/null +++ b/drivers/include/fsl_sim.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_SIM_H_ +#define _FSL_SIM_H_ + +#include "fsl_common.h" + +/*! @addtogroup sim */ +/*! @{*/ + + +/******************************************************************************* + * Definitions + *******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +#define FSL_SIM_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Driver version 2.0.0 */ +/*@}*/ + +#if (defined(FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) && FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) +/*!@brief USB voltage regulator enable setting. */ +enum _sim_usb_volt_reg_enable_mode +{ + kSIM_UsbVoltRegEnable = SIM_SOPT1_USBREGEN_MASK, /*!< Enable voltage regulator. */ + kSIM_UsbVoltRegEnableInLowPower = SIM_SOPT1_USBVSTBY_MASK, /*!< Enable voltage regulator in VLPR/VLPW modes. */ + kSIM_UsbVoltRegEnableInStop = SIM_SOPT1_USBSSTBY_MASK, /*!< Enable voltage regulator in STOP/VLPS/LLS/VLLS modes. */ + kSIM_UsbVoltRegEnableInAllModes = SIM_SOPT1_USBREGEN_MASK | SIM_SOPT1_USBSSTBY_MASK | + SIM_SOPT1_USBVSTBY_MASK /*!< Enable voltage regulator in all power modes. */ +}; +#endif /* (defined(FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) && FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) */ + +/*!@brief Unique ID. */ +typedef struct _sim_uid +{ +#if defined(SIM_UIDH) + uint32_t H; /*!< UIDH. */ +#endif + uint32_t MH; /*!< UIDMH. */ + uint32_t ML; /*!< UIDML. */ + uint32_t L; /*!< UIDL. */ +} sim_uid_t; + +/*!@brief Flash enable mode. */ +enum _sim_flash_mode +{ + kSIM_FlashDisableInWait = SIM_FCFG1_FLASHDOZE_MASK, /*!< Disable flash in wait mode. */ + kSIM_FlashDisable = SIM_FCFG1_FLASHDIS_MASK /*!< Disable flash in normal mode. */ +}; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +#if (defined(FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) && FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) +/*! + * @brief Sets the USB voltage regulator setting. + * + * 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 \ref _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_UsbVoltRegEnableInLowPower); + * + * @param mask USB voltage regulator enable setting. + */ +void SIM_SetUsbVoltRegulatorEnableMode(uint32_t mask); +#endif /* FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR */ + +/*! + * @brief Gets the unique identification register value. + * + * @param uid Pointer to the structure to save the UID value. + */ +void SIM_GetUniqueId(sim_uid_t *uid); + +/*! + * @brief Sets the flash enable mode. + * + * @param mode The mode to set; see \ref _sim_flash_mode for mode details. + */ +static inline void SIM_SetFlashMode(uint8_t mode) +{ + SIM->FCFG1 = mode; +} + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +/*! @}*/ + +#endif /* _FSL_SIM_H_ */ diff --git a/drivers/include/fsl_smc.h b/drivers/include/fsl_smc.h new file mode 100644 index 0000000..168ce83 --- /dev/null +++ b/drivers/include/fsl_smc.h @@ -0,0 +1,456 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_SMC_H_ +#define _FSL_SMC_H_ + +#include "fsl_common.h" + +/*! @addtogroup smc */ +/*! @{ */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief SMC driver version 2.0.3. */ +#define FSL_SMC_DRIVER_VERSION (MAKE_VERSION(2, 0, 3)) +/*@}*/ + +/*! + * @brief Power Modes Protection + */ +typedef enum _smc_power_mode_protection +{ +#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) + kSMC_AllowPowerModeVlls = SMC_PMPROT_AVLLS_MASK, /*!< Allow Very-low-leakage Stop Mode. */ +#endif +#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) + kSMC_AllowPowerModeLls = SMC_PMPROT_ALLS_MASK, /*!< Allow Low-leakage Stop Mode. */ +#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ + kSMC_AllowPowerModeVlp = SMC_PMPROT_AVLP_MASK, /*!< Allow Very-Low-power Mode. */ +#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) + kSMC_AllowPowerModeHsrun = SMC_PMPROT_AHSRUN_MASK, /*!< Allow High-speed Run mode. */ +#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ + kSMC_AllowPowerModeAll = (0U +#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) + | + SMC_PMPROT_AVLLS_MASK +#endif +#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) + | + SMC_PMPROT_ALLS_MASK +#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ + | + SMC_PMPROT_AVLP_MASK +#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) + | + kSMC_AllowPowerModeHsrun +#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ + ) /*!< Allow all power mode. */ +} smc_power_mode_protection_t; + +/*! + * @brief Power Modes in PMSTAT + */ +typedef enum _smc_power_state +{ + kSMC_PowerStateRun = 0x01U << 0U, /*!< 0000_0001 - Current power mode is RUN */ + kSMC_PowerStateStop = 0x01U << 1U, /*!< 0000_0010 - Current power mode is STOP */ + kSMC_PowerStateVlpr = 0x01U << 2U, /*!< 0000_0100 - Current power mode is VLPR */ + kSMC_PowerStateVlpw = 0x01U << 3U, /*!< 0000_1000 - Current power mode is VLPW */ + kSMC_PowerStateVlps = 0x01U << 4U, /*!< 0001_0000 - Current power mode is VLPS */ +#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) + kSMC_PowerStateLls = 0x01U << 5U, /*!< 0010_0000 - Current power mode is LLS */ +#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ +#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) + kSMC_PowerStateVlls = 0x01U << 6U, /*!< 0100_0000 - Current power mode is VLLS */ +#endif +#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) + kSMC_PowerStateHsrun = 0x01U << 7U /*!< 1000_0000 - Current power mode is HSRUN */ +#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ +} smc_power_state_t; + +/*! + * @brief Run mode definition + */ +typedef enum _smc_run_mode +{ + kSMC_RunNormal = 0U, /*!< Normal RUN mode. */ + kSMC_RunVlpr = 2U, /*!< Very-low-power RUN mode. */ +#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) + kSMC_Hsrun = 3U /*!< High-speed Run mode (HSRUN). */ +#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ +} smc_run_mode_t; + +/*! + * @brief Stop mode definition + */ +typedef enum _smc_stop_mode +{ + kSMC_StopNormal = 0U, /*!< Normal STOP mode. */ + kSMC_StopVlps = 2U, /*!< Very-low-power STOP mode. */ +#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) + kSMC_StopLls = 3U, /*!< Low-leakage Stop mode. */ +#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ +#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) + kSMC_StopVlls = 4U /*!< Very-low-leakage Stop mode. */ +#endif +} smc_stop_mode_t; + +#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) || \ + (defined(FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) && FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) || \ + (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) +/*! + * @brief VLLS/LLS stop sub mode definition + */ +typedef enum _smc_stop_submode +{ + kSMC_StopSub0 = 0U, /*!< Stop submode 0, for VLLS0/LLS0. */ + kSMC_StopSub1 = 1U, /*!< Stop submode 1, for VLLS1/LLS1. */ + kSMC_StopSub2 = 2U, /*!< Stop submode 2, for VLLS2/LLS2. */ + kSMC_StopSub3 = 3U /*!< Stop submode 3, for VLLS3/LLS3. */ +} smc_stop_submode_t; +#endif + +/*! + * @brief Partial STOP option + */ +typedef enum _smc_partial_stop_mode +{ + kSMC_PartialStop = 0U, /*!< STOP - Normal Stop mode*/ + kSMC_PartialStop1 = 1U, /*!< Partial Stop with both system and bus clocks disabled*/ + kSMC_PartialStop2 = 2U, /*!< Partial Stop with system clock disabled and bus clock enabled*/ +} smc_partial_stop_option_t; + +/*! + * @brief SMC configuration status. + */ +enum _smc_status +{ + kStatus_SMC_StopAbort = MAKE_STATUS(kStatusGroup_POWER, 0) /*!< Entering Stop mode is abort*/ +}; + +#if (defined(FSL_FEATURE_SMC_HAS_VERID) && FSL_FEATURE_SMC_HAS_VERID) +/*! + * @brief IP version ID definition. + */ +typedef struct _smc_version_id +{ + uint16_t feature; /*!< Feature Specification Number. */ + uint8_t minor; /*!< Minor version number. */ + uint8_t major; /*!< Major version number. */ +} smc_version_id_t; +#endif /* FSL_FEATURE_SMC_HAS_VERID */ + +#if (defined(FSL_FEATURE_SMC_HAS_PARAM) && FSL_FEATURE_SMC_HAS_PARAM) +/*! + * @brief IP parameter definition. + */ +typedef struct _smc_param +{ + bool hsrunEnable; /*!< HSRUN mode enable. */ + bool llsEnable; /*!< LLS mode enable. */ + bool lls2Enable; /*!< LLS2 mode enable. */ + bool vlls0Enable; /*!< VLLS0 mode enable. */ +} smc_param_t; +#endif /* FSL_FEATURE_SMC_HAS_PARAM */ + +#if (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) || \ + (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) +/*! + * @brief SMC Low-Leakage Stop power mode configuration. + */ +typedef struct _smc_power_mode_lls_config +{ +#if (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) + smc_stop_submode_t subMode; /*!< Low-leakage Stop sub-mode */ +#endif +#if (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) + bool enableLpoClock; /*!< Enable LPO clock in LLS mode */ +#endif +} smc_power_mode_lls_config_t; +#endif /* (FSL_FEATURE_SMC_HAS_LLS_SUBMODE || FSL_FEATURE_SMC_HAS_LPOPO) */ + +#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) +/*! + * @brief SMC Very Low-Leakage Stop power mode configuration. + */ +typedef struct _smc_power_mode_vlls_config +{ +#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) || \ + (defined(FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) && FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) || \ + (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) + smc_stop_submode_t subMode; /*!< Very Low-leakage Stop sub-mode */ +#endif +#if (defined(FSL_FEATURE_SMC_HAS_PORPO) && FSL_FEATURE_SMC_HAS_PORPO) + bool enablePorDetectInVlls0; /*!< Enable Power on reset detect in VLLS mode */ +#endif +#if (defined(FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION) && FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION) + bool enableRam2InVlls2; /*!< Enable RAM2 power in VLLS2 */ +#endif +#if (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) + bool enableLpoClock; /*!< Enable LPO clock in VLLS mode */ +#endif +} smc_power_mode_vlls_config_t; +#endif + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*! @name System mode controller APIs*/ +/*@{*/ + +#if (defined(FSL_FEATURE_SMC_HAS_VERID) && FSL_FEATURE_SMC_HAS_VERID) +/*! + * @brief Gets the SMC version ID. + * + * This function gets the SMC version ID, including major version number, + * minor version number, and feature specification number. + * + * @param base SMC peripheral base address. + * @param versionId Pointer to the version ID structure. + */ +static inline void SMC_GetVersionId(SMC_Type *base, smc_version_id_t *versionId) +{ + *((uint32_t *)versionId) = base->VERID; +} +#endif /* FSL_FEATURE_SMC_HAS_VERID */ + +#if (defined(FSL_FEATURE_SMC_HAS_PARAM) && FSL_FEATURE_SMC_HAS_PARAM) +/*! + * @brief Gets the SMC parameter. + * + * This function gets the SMC parameter including the enabled power mdoes. + * + * @param base SMC peripheral base address. + * @param param Pointer to the SMC param structure. + */ +void SMC_GetParam(SMC_Type *base, smc_param_t *param); +#endif + +/*! + * @brief Configures all power mode protection settings. + * + * 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_SetPowerModeProtection(kSMC_AllowPowerModeVlls | kSMC_AllowPowerModeVlps). + * To allow all modes, use SMC_SetPowerModeProtection(kSMC_AllowPowerModeAll). + * + * @param base SMC peripheral base address. + * @param allowedModes Bitmap of the allowed power modes. + */ +static inline void SMC_SetPowerModeProtection(SMC_Type *base, uint8_t allowedModes) +{ + base->PMPROT = allowedModes; +} + +/*! + * @brief Gets the current power mode status. + * + * 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. + * + * @param base SMC peripheral base address. + * @return Current power mode status. + */ +static inline smc_power_state_t SMC_GetPowerModeState(SMC_Type *base) +{ + return (smc_power_state_t)base->PMSTAT; +} + +/*! + * @brief Prepares to enter stop modes. + * + * This function should be called before entering STOP/VLPS/LLS/VLLS modes. + */ +void SMC_PreEnterStopModes(void); + +/*! + * @brief Recovers after wake up from stop modes. + * + * This function should be called after wake up from STOP/VLPS/LLS/VLLS modes. + * It is used with @ref SMC_PreEnterStopModes. + */ +void SMC_PostExitStopModes(void); + +/*! + * @brief Prepares to enter wait modes. + * + * This function should be called before entering WAIT/VLPW modes. + */ +static inline void SMC_PreEnterWaitModes(void) +{ + __disable_irq(); + __ISB(); +} + +/*! + * @brief Recovers after wake up from stop modes. + * + * This function should be called after wake up from WAIT/VLPW modes. + * It is used with @ref SMC_PreEnterWaitModes. + */ +static inline void SMC_PostExitWaitModes(void) +{ + __enable_irq(); + __ISB(); +} + +/*! + * @brief Configures the system to RUN power mode. + * + * @param base SMC peripheral base address. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeRun(SMC_Type *base); + +#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) +/*! + * @brief Configures the system to HSRUN power mode. + * + * @param base SMC peripheral base address. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeHsrun(SMC_Type *base); +#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ + +/*! + * @brief Configures the system to WAIT power mode. + * + * @param base SMC peripheral base address. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeWait(SMC_Type *base); + +/*! + * @brief Configures the system to Stop power mode. + * + * @param base SMC peripheral base address. + * @param option Partial Stop mode option. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeStop(SMC_Type *base, smc_partial_stop_option_t option); + +#if (defined(FSL_FEATURE_SMC_HAS_LPWUI) && FSL_FEATURE_SMC_HAS_LPWUI) +/*! + * @brief Configures the system to VLPR power mode. + * + * @param base SMC peripheral base address. + * @param wakeupMode Enter Normal Run mode if true, else stay in VLPR mode. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeVlpr(SMC_Type *base, bool wakeupMode); +#else +/*! + * @brief Configures the system to VLPR power mode. + * + * @param base SMC peripheral base address. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeVlpr(SMC_Type *base); +#endif /* FSL_FEATURE_SMC_HAS_LPWUI */ + +/*! + * @brief Configures the system to VLPW power mode. + * + * @param base SMC peripheral base address. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeVlpw(SMC_Type *base); + +/*! + * @brief Configures the system to VLPS power mode. + * + * @param base SMC peripheral base address. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeVlps(SMC_Type *base); + +#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) +#if ((defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) || \ + (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO)) +/*! + * @brief Configures the system to LLS power mode. + * + * @param base SMC peripheral base address. + * @param config The LLS power mode configuration structure + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeLls(SMC_Type *base, const smc_power_mode_lls_config_t *config); +#else +/*! + * @brief Configures the system to LLS power mode. + * + * @param base SMC peripheral base address. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeLls(SMC_Type *base); +#endif +#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ + +#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) +/*! + * @brief Configures the system to VLLS power mode. + * + * @param base SMC peripheral base address. + * @param config The VLLS power mode configuration structure. + * @return SMC configuration error code. + */ +status_t SMC_SetPowerModeVlls(SMC_Type *base, const smc_power_mode_vlls_config_t *config); +#endif /* FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE */ + +/*@}*/ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/*! @}*/ + +#endif /* _FSL_SMC_H_ */ diff --git a/drivers/include/fsl_sysmpu.h b/drivers/include/fsl_sysmpu.h new file mode 100644 index 0000000..6341a31 --- /dev/null +++ b/drivers/include/fsl_sysmpu.h @@ -0,0 +1,435 @@ +/* + * Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_SYSMPU_H_ +#define _FSL_SYSMPU_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup sysmpu + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief SYSMPU driver version 2.2.0. */ +#define FSL_SYSMPU_DRIVER_VERSION (MAKE_VERSION(2, 2, 0)) +/*@}*/ + +/*! @brief define the start master port with read and write attributes. */ +#define SYSMPU_MASTER_RWATTRIBUTE_START_PORT (4) + +/*! @brief SYSMPU the bit shift for masters with privilege rights: read write and execute. */ +#define SYSMPU_REGION_RWXRIGHTS_MASTER_SHIFT(n) (n * 6) + +/*! @brief SYSMPU masters with read, write and execute rights bit mask. */ +#define SYSMPU_REGION_RWXRIGHTS_MASTER_MASK(n) (0x1Fu << SYSMPU_REGION_RWXRIGHTS_MASTER_SHIFT(n)) + +/*! @brief SYSMPU masters with read, write and execute rights bit width. */ +#define SYSMPU_REGION_RWXRIGHTS_MASTER_WIDTH 5 + +/*! @brief SYSMPU masters with read, write and execute rights priority setting. */ +#define SYSMPU_REGION_RWXRIGHTS_MASTER(n, x) \ + (((uint32_t)(((uint32_t)(x)) << SYSMPU_REGION_RWXRIGHTS_MASTER_SHIFT(n))) & SYSMPU_REGION_RWXRIGHTS_MASTER_MASK(n)) + +/*! @brief SYSMPU masters with read, write and execute rights process enable bit shift. */ +#define SYSMPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n) (n * 6 + SYSMPU_REGION_RWXRIGHTS_MASTER_WIDTH) + +/*! @brief SYSMPU masters with read, write and execute rights process enable bit mask. */ +#define SYSMPU_REGION_RWXRIGHTS_MASTER_PE_MASK(n) (0x1u << SYSMPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n)) + +/*! @brief SYSMPU masters with read, write and execute rights process enable setting. */ +#define SYSMPU_REGION_RWXRIGHTS_MASTER_PE(n, x) \ + (((uint32_t)(((uint32_t)(x)) << SYSMPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n))) & SYSMPU_REGION_RWXRIGHTS_MASTER_PE_MASK(n)) + +/*! @brief SYSMPU masters with normal read write permission bit shift. */ +#define SYSMPU_REGION_RWRIGHTS_MASTER_SHIFT(n) ((n - SYSMPU_MASTER_RWATTRIBUTE_START_PORT) * 2 + 24) + +/*! @brief SYSMPU masters with normal read write rights bit mask. */ +#define SYSMPU_REGION_RWRIGHTS_MASTER_MASK(n) (0x3u << SYSMPU_REGION_RWRIGHTS_MASTER_SHIFT(n)) + +/*! @brief SYSMPU masters with normal read write rights priority setting. */ +#define SYSMPU_REGION_RWRIGHTS_MASTER(n, x) \ + (((uint32_t)(((uint32_t)(x)) << SYSMPU_REGION_RWRIGHTS_MASTER_SHIFT(n))) & SYSMPU_REGION_RWRIGHTS_MASTER_MASK(n)) + + +/*! @brief Describes the number of SYSMPU regions. */ +typedef enum _sysmpu_region_total_num +{ + kSYSMPU_8Regions = 0x0U, /*!< SYSMPU supports 8 regions. */ + kSYSMPU_12Regions = 0x1U, /*!< SYSMPU supports 12 regions. */ + kSYSMPU_16Regions = 0x2U /*!< SYSMPU supports 16 regions. */ +} sysmpu_region_total_num_t; + +/*! @brief SYSMPU slave port number. */ +typedef enum _sysmpu_slave +{ + kSYSMPU_Slave0 = 0U, /*!< SYSMPU slave port 0. */ + kSYSMPU_Slave1 = 1U, /*!< SYSMPU slave port 1. */ + kSYSMPU_Slave2 = 2U, /*!< SYSMPU slave port 2. */ + kSYSMPU_Slave3 = 3U, /*!< SYSMPU slave port 3. */ + kSYSMPU_Slave4 = 4U, /*!< SYSMPU slave port 4. */ +#if FSL_FEATURE_SYSMPU_SLAVE_COUNT > 5 + kSYSMPU_Slave5 = 5U, /*!< SYSMPU slave port 5. */ +#endif +#if FSL_FEATURE_SYSMPU_SLAVE_COUNT > 6 + kSYSMPU_Slave6 = 6U, /*!< SYSMPU slave port 6. */ +#endif +#if FSL_FEATURE_SYSMPU_SLAVE_COUNT > 7 + kSYSMPU_Slave7 = 7U, /*!< SYSMPU slave port 7. */ +#endif +} sysmpu_slave_t; + +/*! @brief SYSMPU error access control detail. */ +typedef enum _sysmpu_err_access_control +{ + kSYSMPU_NoRegionHit = 0U, /*!< No region hit error. */ + kSYSMPU_NoneOverlappRegion = 1U, /*!< Access single region error. */ + kSYSMPU_OverlappRegion = 2U /*!< Access overlapping region error. */ +} sysmpu_err_access_control_t; + +/*! @brief SYSMPU error access type. */ +typedef enum _sysmpu_err_access_type +{ + kSYSMPU_ErrTypeRead = 0U, /*!< SYSMPU error access type --- read. */ + kSYSMPU_ErrTypeWrite = 1U /*!< SYSMPU error access type --- write. */ +} sysmpu_err_access_type_t; + +/*! @brief SYSMPU access error attributes.*/ +typedef enum _sysmpu_err_attributes +{ + kSYSMPU_InstructionAccessInUserMode = 0U, /*!< Access instruction error in user mode. */ + kSYSMPU_DataAccessInUserMode = 1U, /*!< Access data error in user mode. */ + kSYSMPU_InstructionAccessInSupervisorMode = 2U, /*!< Access instruction error in supervisor mode. */ + kSYSMPU_DataAccessInSupervisorMode = 3U /*!< Access data error in supervisor mode. */ +} sysmpu_err_attributes_t; + +/*! @brief SYSMPU access rights in supervisor mode for bus master 0 ~ 3. */ +typedef enum _sysmpu_supervisor_access_rights +{ + kSYSMPU_SupervisorReadWriteExecute = 0U, /*!< Read write and execute operations are allowed in supervisor mode. */ + kSYSMPU_SupervisorReadExecute = 1U, /*!< Read and execute operations are allowed in supervisor mode. */ + kSYSMPU_SupervisorReadWrite = 2U, /*!< Read write operations are allowed in supervisor mode. */ + kSYSMPU_SupervisorEqualToUsermode = 3U /*!< Access permission equal to user mode. */ +} sysmpu_supervisor_access_rights_t; + +/*! @brief SYSMPU access rights in user mode for bus master 0 ~ 3. */ +typedef enum _sysmpu_user_access_rights +{ + kSYSMPU_UserNoAccessRights = 0U, /*!< No access allowed in user mode. */ + kSYSMPU_UserExecute = 1U, /*!< Execute operation is allowed in user mode. */ + kSYSMPU_UserWrite = 2U, /*!< Write operation is allowed in user mode. */ + kSYSMPU_UserWriteExecute = 3U, /*!< Write and execute operations are allowed in user mode. */ + kSYSMPU_UserRead = 4U, /*!< Read is allowed in user mode. */ + kSYSMPU_UserReadExecute = 5U, /*!< Read and execute operations are allowed in user mode. */ + kSYSMPU_UserReadWrite = 6U, /*!< Read and write operations are allowed in user mode. */ + kSYSMPU_UserReadWriteExecute = 7U /*!< Read write and execute operations are allowed in user mode. */ +} sysmpu_user_access_rights_t; + +/*! @brief SYSMPU hardware basic information. */ +typedef struct _sysmpu_hardware_info +{ + uint8_t hardwareRevisionLevel; /*!< Specifies the SYSMPU's hardware and definition reversion level. */ + uint8_t slavePortsNumbers; /*!< Specifies the number of slave ports connected to SYSMPU. */ + sysmpu_region_total_num_t regionsNumbers; /*!< Indicates the number of region descriptors implemented. */ +} sysmpu_hardware_info_t; + +/*! @brief SYSMPU detail error access information. */ +typedef struct _sysmpu_access_err_info +{ + uint32_t master; /*!< Access error master. */ + sysmpu_err_attributes_t attributes; /*!< Access error attributes. */ + sysmpu_err_access_type_t accessType; /*!< Access error type. */ + sysmpu_err_access_control_t accessControl; /*!< Access error control. */ + uint32_t address; /*!< Access error address. */ +#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER + uint8_t processorIdentification; /*!< Access error processor identification. */ +#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ +} sysmpu_access_err_info_t; + +/*! @brief SYSMPU read/write/execute rights control for bus master 0 ~ 3. */ +typedef struct _sysmpu_rwxrights_master_access_control +{ + sysmpu_supervisor_access_rights_t superAccessRights; /*!< Master access rights in supervisor mode. */ + sysmpu_user_access_rights_t userAccessRights; /*!< Master access rights in user mode. */ +#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER + bool processIdentifierEnable; /*!< Enables or disables process identifier. */ +#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ +} sysmpu_rwxrights_master_access_control_t; + +/*! @brief SYSMPU read/write access control for bus master 4 ~ 7. */ +typedef struct _sysmpu_rwrights_master_access_control +{ + bool writeEnable; /*!< Enables or disables write permission. */ + bool readEnable; /*!< Enables or disables read permission. */ +} sysmpu_rwrights_master_access_control_t; + +/*! + * @brief SYSMPU region configuration structure. + * + * This structure is used to configure the regionNum region. + * The accessRights1[0] ~ accessRights1[3] are used to configure the bus master + * 0 ~ 3 with the privilege rights setting. The accessRights2[0] ~ accessRights2[3] + * are used to configure the high master 4 ~ 7 with the normal read write permission. + * The master port assignment is the chip configuration. Normally, the core is the + * master 0, debugger is the master 1. + * Note that the SYSMPU assigns a priority scheme where the debugger is treated as the highest + * priority master followed by the core and then all the remaining masters. + * SYSMPU protection does not allow writes from the core to affect the "regionNum 0" start + * and end address nor the permissions associated with the debugger. It can only write + * the permission fields associated with the other masters. This protection guarantees that + * the debugger always has access to the entire address space and those rights can't + * be changed by the core or any other bus master. Prepare + * the region configuration when regionNum is 0. + */ +typedef struct _sysmpu_region_config +{ + uint32_t regionNum; /*!< SYSMPU region number, range form 0 ~ FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT - 1. */ + uint32_t startAddress; /*!< Memory region start address. Note: bit0 ~ bit4 always be marked as 0 by SYSMPU. The actual + start address is 0-modulo-32 byte address. */ + uint32_t endAddress; /*!< Memory region end address. Note: bit0 ~ bit4 always be marked as 1 by SYSMPU. The actual end + address is 31-modulo-32 byte address. */ + sysmpu_rwxrights_master_access_control_t accessRights1[4]; /*!< Masters with read, write and execute rights setting. */ + sysmpu_rwrights_master_access_control_t accessRights2[4]; /*!< Masters with normal read write rights setting. */ +#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER + uint8_t processIdentifier; /*!< Process identifier used when "processIdentifierEnable" set with true. */ + uint8_t + processIdMask; /*!< Process identifier mask. The setting bit will ignore the same bit in process identifier. */ +#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ +} sysmpu_region_config_t; + +/*! + * @brief The configuration structure for the SYSMPU initialization. + * + * This structure is used when calling the SYSMPU_Init function. + */ +typedef struct _sysmpu_config +{ + sysmpu_region_config_t regionConfig; /*!< Region access permission. */ + struct _sysmpu_config *next; /*!< Pointer to the next structure. */ +} sysmpu_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* _cplusplus */ + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Initializes the SYSMPU with the user configuration structure. + * + * This function configures the SYSMPU module with the user-defined configuration. + * + * @param base SYSMPU peripheral base address. + * @param config The pointer to the configuration structure. + */ +void SYSMPU_Init(SYSMPU_Type *base, const sysmpu_config_t *config); + +/*! + * @brief Deinitializes the SYSMPU regions. + * + * @param base SYSMPU peripheral base address. + */ +void SYSMPU_Deinit(SYSMPU_Type *base); + +/* @}*/ + +/*! + * @name Basic Control Operations + * @{ + */ + +/*! + * @brief Enables/disables the SYSMPU globally. + * + * Call this API to enable or disable the SYSMPU module. + * + * @param base SYSMPU peripheral base address. + * @param enable True enable SYSMPU, false disable SYSMPU. + */ +static inline void SYSMPU_Enable(SYSMPU_Type *base, bool enable) +{ + if (enable) + { + /* Enable the SYSMPU globally. */ + base->CESR |= SYSMPU_CESR_VLD_MASK; + } + else + { /* Disable the SYSMPU globally. */ + base->CESR &= ~SYSMPU_CESR_VLD_MASK; + } +} + +/*! + * @brief Enables/disables the SYSMPU for a special region. + * + * When SYSMPU is enabled, call this API to disable an unused region + * of an enabled SYSMPU. Call this API to minimize the power dissipation. + * + * @param base SYSMPU peripheral base address. + * @param number SYSMPU region number. + * @param enable True enable the special region SYSMPU, false disable the special region SYSMPU. + */ +static inline void SYSMPU_RegionEnable(SYSMPU_Type *base, uint32_t number, bool enable) +{ + if (enable) + { + /* Enable the #number region SYSMPU. */ + base->WORD[number][3] |= SYSMPU_WORD_VLD_MASK; + } + else + { /* Disable the #number region SYSMPU. */ + base->WORD[number][3] &= ~SYSMPU_WORD_VLD_MASK; + } +} + +/*! + * @brief Gets the SYSMPU basic hardware information. + * + * @param base SYSMPU peripheral base address. + * @param hardwareInform The pointer to the SYSMPU hardware information structure. See "sysmpu_hardware_info_t". + */ +void SYSMPU_GetHardwareInfo(SYSMPU_Type *base, sysmpu_hardware_info_t *hardwareInform); + +/*! + * @brief Sets the SYSMPU region. + * + * Note: Due to the SYSMPU protection, the region number 0 does not allow writes from + * core to affect the start and end address nor the permissions associated with + * the debugger. It can only write the permission fields associated + * with the other masters. + * + * @param base SYSMPU peripheral base address. + * @param regionConfig The pointer to the SYSMPU user configuration structure. See "sysmpu_region_config_t". + */ +void SYSMPU_SetRegionConfig(SYSMPU_Type *base, const sysmpu_region_config_t *regionConfig); + +/*! + * @brief Sets the region start and end address. + * + * Memory region start address. Note: bit0 ~ bit4 is always marked as 0 by SYSMPU. + * The actual start address by SYSMPU is 0-modulo-32 byte address. + * Memory region end address. Note: bit0 ~ bit4 always be marked as 1 by SYSMPU. + * The end address used by the SYSMPU is 31-modulo-32 byte address. + * Note: Due to the SYSMPU protection, the startAddr and endAddr can't be + * changed by the core when regionNum is 0. + * + * @param base SYSMPU peripheral base address. + * @param regionNum SYSMPU region number. The range is from 0 to + * FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT - 1. + * @param startAddr Region start address. + * @param endAddr Region end address. + */ +void SYSMPU_SetRegionAddr(SYSMPU_Type *base, uint32_t regionNum, uint32_t startAddr, uint32_t endAddr); + +/*! + * @brief Sets the SYSMPU region access rights for masters with read, write, and execute rights. + * The SYSMPU access rights depend on two board classifications of bus masters. + * The privilege rights masters and the normal rights masters. + * The privilege rights masters have the read, write, and execute access rights. + * Except the normal read and write rights, the execute rights are also + * allowed for these masters. The privilege rights masters normally range from + * bus masters 0 - 3. However, the maximum master number is device-specific. + * See the "SYSMPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX". + * The normal rights masters access rights control see + * "SYSMPU_SetRegionRwMasterAccessRights()". + * + * @param base SYSMPU peripheral base address. + * @param regionNum SYSMPU region number. Should range from 0 to + * FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT - 1. + * @param masterNum SYSMPU bus master number. Should range from 0 to + * SYSMPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX. + * @param accessRights The pointer to the SYSMPU access rights configuration. See "sysmpu_rwxrights_master_access_control_t". + */ +void SYSMPU_SetRegionRwxMasterAccessRights(SYSMPU_Type *base, + uint32_t regionNum, + uint32_t masterNum, + const sysmpu_rwxrights_master_access_control_t *accessRights); +#if FSL_FEATURE_SYSMPU_MASTER_COUNT > 4 +/*! + * @brief Sets the SYSMPU region access rights for masters with read and write rights. + * The SYSMPU access rights depend on two board classifications of bus masters. + * The privilege rights masters and the normal rights masters. + * The normal rights masters only have the read and write access permissions. + * The privilege rights access control see "SYSMPU_SetRegionRwxMasterAccessRights". + * + * @param base SYSMPU peripheral base address. + * @param regionNum SYSMPU region number. The range is from 0 to + * FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT - 1. + * @param masterNum SYSMPU bus master number. Should range from SYSMPU_MASTER_RWATTRIBUTE_START_PORT + * to ~ FSL_FEATURE_SYSMPU_MASTER_COUNT - 1. + * @param accessRights The pointer to the SYSMPU access rights configuration. See "sysmpu_rwrights_master_access_control_t". + */ +void SYSMPU_SetRegionRwMasterAccessRights(SYSMPU_Type *base, + uint32_t regionNum, + uint32_t masterNum, + const sysmpu_rwrights_master_access_control_t *accessRights); +#endif /* FSL_FEATURE_SYSMPU_MASTER_COUNT > 4 */ +/*! + * @brief Gets the numbers of slave ports where errors occur. + * + * @param base SYSMPU peripheral base address. + * @param slaveNum SYSMPU slave port number. + * @return The slave ports error status. + * true - error happens in this slave port. + * false - error didn't happen in this slave port. + */ +bool SYSMPU_GetSlavePortErrorStatus(SYSMPU_Type *base, sysmpu_slave_t slaveNum); + +/*! + * @brief Gets the SYSMPU detailed error access information. + * + * @param base SYSMPU peripheral base address. + * @param slaveNum SYSMPU slave port number. + * @param errInform The pointer to the SYSMPU access error information. See "sysmpu_access_err_info_t". + */ +void SYSMPU_GetDetailErrorAccessInfo(SYSMPU_Type *base, sysmpu_slave_t slaveNum, sysmpu_access_err_info_t *errInform); + +/* @} */ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_SYSMPU_H_ */ diff --git a/drivers/include/fsl_tsi_v2.h b/drivers/include/fsl_tsi_v2.h new file mode 100644 index 0000000..a173626 --- /dev/null +++ b/drivers/include/fsl_tsi_v2.h @@ -0,0 +1,777 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_TSI_V2_H_ +#define _FSL_TSI_V2_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup tsi_v2_driver + * @{ + */ + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief TSI driver version */ +#define FSL_TSI_DRIVER_VERSION (MAKE_VERSION(2, 1, 2)) +/*@}*/ + +/*! @brief TSI status flags macro collection */ +#define ALL_FLAGS_MASK (TSI_GENCS_EOSF_MASK |\ + TSI_GENCS_OUTRGF_MASK |\ + TSI_GENCS_EXTERF_MASK |\ + TSI_GENCS_OVRF_MASK) + + +/*! + * @brief TSI number of scan intervals for each electrode. + * + * These constants define the TSI number of consecutive scans in a TSI instance for each electrode. + */ +typedef enum _tsi_n_consecutive_scans +{ + kTSI_ConsecutiveScansNumber_1time = 0U, /*!< Once per electrode */ + kTSI_ConsecutiveScansNumber_2time = 1U, /*!< Twice per electrode */ + kTSI_ConsecutiveScansNumber_3time = 2U, /*!< 3 times consecutive scan */ + kTSI_ConsecutiveScansNumber_4time = 3U, /*!< 4 times consecutive scan */ + kTSI_ConsecutiveScansNumber_5time = 4U, /*!< 5 times consecutive scan */ + kTSI_ConsecutiveScansNumber_6time = 5U, /*!< 6 times consecutive scan */ + kTSI_ConsecutiveScansNumber_7time = 6U, /*!< 7 times consecutive scan */ + kTSI_ConsecutiveScansNumber_8time = 7U, /*!< 8 times consecutive scan */ + kTSI_ConsecutiveScansNumber_9time = 8U, /*!< 9 times consecutive scan */ + kTSI_ConsecutiveScansNumber_10time = 9U, /*!< 10 times consecutive scan */ + kTSI_ConsecutiveScansNumber_11time = 10U, /*!< 11 times consecutive scan */ + kTSI_ConsecutiveScansNumber_12time = 11U, /*!< 12 times consecutive scan */ + kTSI_ConsecutiveScansNumber_13time = 12U, /*!< 13 times consecutive scan */ + kTSI_ConsecutiveScansNumber_14time = 13U, /*!< 14 times consecutive scan */ + kTSI_ConsecutiveScansNumber_15time = 14U, /*!< 15 times consecutive scan */ + kTSI_ConsecutiveScansNumber_16time = 15U, /*!< 16 times consecutive scan */ + kTSI_ConsecutiveScansNumber_17time = 16U, /*!< 17 times consecutive scan */ + kTSI_ConsecutiveScansNumber_18time = 17U, /*!< 18 times consecutive scan */ + kTSI_ConsecutiveScansNumber_19time = 18U, /*!< 19 times consecutive scan */ + kTSI_ConsecutiveScansNumber_20time = 19U, /*!< 20 times consecutive scan */ + kTSI_ConsecutiveScansNumber_21time = 20U, /*!< 21 times consecutive scan */ + kTSI_ConsecutiveScansNumber_22time = 21U, /*!< 22 times consecutive scan */ + kTSI_ConsecutiveScansNumber_23time = 22U, /*!< 23 times consecutive scan */ + kTSI_ConsecutiveScansNumber_24time = 23U, /*!< 24 times consecutive scan */ + kTSI_ConsecutiveScansNumber_25time = 24U, /*!< 25 times consecutive scan */ + kTSI_ConsecutiveScansNumber_26time = 25U, /*!< 26 times consecutive scan */ + kTSI_ConsecutiveScansNumber_27time = 26U, /*!< 27 times consecutive scan */ + kTSI_ConsecutiveScansNumber_28time = 27U, /*!< 28 times consecutive scan */ + kTSI_ConsecutiveScansNumber_29time = 28U, /*!< 29 times consecutive scan */ + kTSI_ConsecutiveScansNumber_30time = 29U, /*!< 30 times consecutive scan */ + kTSI_ConsecutiveScansNumber_31time = 30U, /*!< 31 times consecutive scan */ + kTSI_ConsecutiveScansNumber_32time = 31U /*!< 32 times consecutive scan */ +} tsi_n_consecutive_scans_t; + +/*! + * @brief TSI electrode oscillator prescaler. + * + * These constants define the TSI electrode oscillator prescaler in a TSI instance. + */ +typedef enum _tsi_electrode_osc_prescaler +{ + kTSI_ElecOscPrescaler_1div = 0U, /*!< Electrode oscillator frequency divided by 1 */ + kTSI_ElecOscPrescaler_2div = 1U, /*!< Electrode oscillator frequency divided by 2 */ + kTSI_ElecOscPrescaler_4div = 2U, /*!< Electrode oscillator frequency divided by 4 */ + kTSI_ElecOscPrescaler_8div = 3U, /*!< Electrode oscillator frequency divided by 8 */ + kTSI_ElecOscPrescaler_16div = 4U, /*!< Electrode oscillator frequency divided by 16 */ + kTSI_ElecOscPrescaler_32div = 5U, /*!< Electrode oscillator frequency divided by 32 */ + kTSI_ElecOscPrescaler_64div = 6U, /*!< Electrode oscillator frequency divided by 64 */ + kTSI_ElecOscPrescaler_128div = 7U /*!< Electrode oscillator frequency divided by 128 */ +} tsi_electrode_osc_prescaler_t; + +/*! + * @brief TSI low power mode clock source. + */ +typedef enum _tsi_low_power_clock_source +{ + kTSI_LowPowerClockSource_LPOCLK = 0U, /*!< LPOCLK is selected */ + kTSI_LowPowerClockSource_VLPOSCCLK = 1U /*!< VLPOSCCLK is selected */ +} tsi_low_power_clock_source_t; + +/*! + * @brief TSI low power scan intervals. + * + * These constants define the TSI low power scan intervals in a TSI instance. + */ +typedef enum _tsi_low_power_scan_interval +{ + kTSI_LowPowerInterval_1ms = 0U, /*!< 1 ms scan interval */ + kTSI_LowPowerInterval_5ms = 1U, /*!< 5 ms scan interval */ + kTSI_LowPowerInterval_10ms = 2U, /*!< 10 ms scan interval */ + kTSI_LowPowerInterval_15ms = 3U, /*!< 15 ms scan interval */ + kTSI_LowPowerInterval_20ms = 4U, /*!< 20 ms scan interval */ + kTSI_LowPowerInterval_30ms = 5U, /*!< 30 ms scan interval */ + kTSI_LowPowerInterval_40ms = 6U, /*!< 40 ms scan interval */ + kTSI_LowPowerInterval_50ms = 7U, /*!< 50 ms scan interval */ + kTSI_LowPowerInterval_75ms = 8U, /*!< 75 ms scan interval */ + kTSI_LowPowerInterval_100ms = 9U, /*!< 100 ms scan interval */ + kTSI_LowPowerInterval_125ms = 10U, /*!< 125 ms scan interval */ + kTSI_LowPowerInterval_150ms = 11U, /*!< 150 ms scan interval */ + kTSI_LowPowerInterval_200ms = 12U, /*!< 200 ms scan interval */ + kTSI_LowPowerInterval_300ms = 13U, /*!< 300 ms scan interval */ + kTSI_LowPowerInterval_400ms = 14U, /*!< 400 ms scan interval */ + kTSI_LowPowerInterval_500ms = 15U /*!< 500 ms scan interval */ +} tsi_low_power_scan_interval_t; + +/*! + * @brief TSI Reference oscillator charge current select. + * + * These constants define the TSI Reference oscillator charge current select in a TSI instance. + */ +typedef enum _tsi_reference_osc_charge_current +{ + kTSI_RefOscChargeCurrent_2uA = 0U, /*!< Reference oscillator charge current is 2 µA */ + kTSI_RefOscChargeCurrent_4uA = 1U, /*!< Reference oscillator charge current is 4 µA */ + kTSI_RefOscChargeCurrent_6uA = 2U, /*!< Reference oscillator charge current is 6 µA */ + kTSI_RefOscChargeCurrent_8uA = 3U, /*!< Reference oscillator charge current is 8 µA */ + kTSI_RefOscChargeCurrent_10uA = 4U, /*!< Reference oscillator charge current is 10 µA */ + kTSI_RefOscChargeCurrent_12uA = 5U, /*!< Reference oscillator charge current is 12 µA */ + kTSI_RefOscChargeCurrent_14uA = 6U, /*!< Reference oscillator charge current is 14 µA */ + kTSI_RefOscChargeCurrent_16uA = 7U, /*!< Reference oscillator charge current is 16 µA */ + kTSI_RefOscChargeCurrent_18uA = 8U, /*!< Reference oscillator charge current is 18 µA */ + kTSI_RefOscChargeCurrent_20uA = 9U, /*!< Reference oscillator charge current is 20 µA */ + kTSI_RefOscChargeCurrent_22uA = 10U, /*!< Reference oscillator charge current is 22 µA */ + kTSI_RefOscChargeCurrent_24uA = 11U, /*!< Reference oscillator charge current is 24 µA */ + kTSI_RefOscChargeCurrent_26uA = 12U, /*!< Reference oscillator charge current is 26 µA */ + kTSI_RefOscChargeCurrent_28uA = 13U, /*!< Reference oscillator charge current is 28 µA */ + kTSI_RefOscChargeCurrent_30uA = 14U, /*!< Reference oscillator charge current is 30 µA */ + kTSI_RefOscChargeCurrent_32uA = 15U /*!< Reference oscillator charge current is 32 µA */ +} tsi_reference_osc_charge_current_t; + +/*! + * @brief TSI External oscillator charge current select. + * + * These constants define the TSI External oscillator charge current select in a TSI instance. + */ +typedef enum _tsi_external_osc_charge_current +{ + kTSI_ExtOscChargeCurrent_2uA = 0U, /*!< External oscillator charge current is 2 µA */ + kTSI_ExtOscChargeCurrent_4uA = 1U, /*!< External oscillator charge current is 4 µA */ + kTSI_ExtOscChargeCurrent_6uA = 2U, /*!< External oscillator charge current is 6 µA */ + kTSI_ExtOscChargeCurrent_8uA = 3U, /*!< External oscillator charge current is 8 µA */ + kTSI_ExtOscChargeCurrent_10uA = 4U, /*!< External oscillator charge current is 10 µA */ + kTSI_ExtOscChargeCurrent_12uA = 5U, /*!< External oscillator charge current is 12 µA */ + kTSI_ExtOscChargeCurrent_14uA = 6U, /*!< External oscillator charge current is 14 µA */ + kTSI_ExtOscChargeCurrent_16uA = 7U, /*!< External oscillator charge current is 16 µA */ + kTSI_ExtOscChargeCurrent_18uA = 8U, /*!< External oscillator charge current is 18 µA */ + kTSI_ExtOscChargeCurrent_20uA = 9U, /*!< External oscillator charge current is 20 µA */ + kTSI_ExtOscChargeCurrent_22uA = 10U, /*!< External oscillator charge current is 22 µA */ + kTSI_ExtOscChargeCurrent_24uA = 11U, /*!< External oscillator charge current is 24 µA */ + kTSI_ExtOscChargeCurrent_26uA = 12U, /*!< External oscillator charge current is 26 µA */ + kTSI_ExtOscChargeCurrent_28uA = 13U, /*!< External oscillator charge current is 28 µA */ + kTSI_ExtOscChargeCurrent_30uA = 14U, /*!< External oscillator charge current is 30 µA */ + kTSI_ExtOscChargeCurrent_32uA = 15U /*!< External oscillator charge current is 32 µA */ +} tsi_external_osc_charge_current_t; + +/*! + * @brief TSI Active mode clock source. + * + * These constants define the active mode clock source in a TSI instance. + */ +typedef enum _tsi_active_mode_clock_source +{ + kTSI_ActiveClkSource_LPOSCCLK = 0U, /*!< Active mode clock source is set to LPOOSC Clock */ + kTSI_ActiveClkSource_MCGIRCLK = 1U, /*!< Active mode clock source is set to MCG Internal reference clock */ + kTSI_ActiveClkSource_OSCERCLK = 2U /*!< Active mode clock source is set to System oscillator output */ +} tsi_active_mode_clock_source_t; + +/*! + * @brief TSI active mode prescaler. + * + * These constants define the TSI active mode prescaler in a TSI instance. + */ +typedef enum _tsi_active_mode_prescaler +{ + kTSI_ActiveModePrescaler_1div = 0U, /*!< Input clock source divided by 1 */ + kTSI_ActiveModePrescaler_2div = 1U, /*!< Input clock source divided by 2 */ + kTSI_ActiveModePrescaler_4div = 2U, /*!< Input clock source divided by 4 */ + kTSI_ActiveModePrescaler_8div = 3U, /*!< Input clock source divided by 8 */ + kTSI_ActiveModePrescaler_16div = 4U, /*!< Input clock source divided by 16 */ + kTSI_ActiveModePrescaler_32div = 5U, /*!< Input clock source divided by 32 */ + kTSI_ActiveModePrescaler_64div = 6U, /*!< Input clock source divided by 64 */ + kTSI_ActiveModePrescaler_128div = 7U /*!< Input clock source divided by 128 */ +} tsi_active_mode_prescaler_t; + +/*! @brief TSI status flags. */ +typedef enum _tsi_status_flags +{ + kTSI_EndOfScanFlag = TSI_GENCS_EOSF_MASK, /*!< End-Of-Scan flag */ + kTSI_OutOfRangeFlag = TSI_GENCS_OUTRGF_MASK, /*!< Out-Of-Range flag */ + kTSI_ExternalElectrodeErrorFlag = TSI_GENCS_EXTERF_MASK, /*!< External electrode error flag */ + kTSI_OverrunErrorFlag = TSI_GENCS_OVRF_MASK /*!< Overrun error flag */ +} tsi_status_flags_t; + +/*! @brief TSI feature interrupt source.*/ +typedef enum _tsi_interrupt_enable +{ + kTSI_GlobalInterruptEnable = 1U, /*!< TSI module global interrupt */ + kTSI_OutOfRangeInterruptEnable = 2U, /*!< Out-Of-Range interrupt */ + kTSI_EndOfScanInterruptEnable = 4U, /*!< End-Of-Scan interrupt */ + kTSI_ErrorInterrruptEnable = 8U /*!< Error interrupt */ +} tsi_interrupt_enable_t; + +/*! @brief TSI calibration data storage. */ +typedef struct _tsi_calibration_data +{ + uint16_t calibratedData[FSL_FEATURE_TSI_CHANNEL_COUNT]; /*!< TSI calibration data storage buffer */ +} tsi_calibration_data_t; + +/*! + * @brief TSI configuration structure. + * + * This structure contains the settings for the most common TSI configurations including + * the TSI module charge currents, number of scans, thresholds, and so on. + */ +typedef struct _tsi_config +{ + uint16_t thresh; /*!< High threshold. */ + uint16_t thresl; /*!< Low threshold. */ + tsi_low_power_clock_source_t lpclks; /*!< Low power clock. */ + tsi_low_power_scan_interval_t lpscnitv; /*!< Low power scan interval. */ + tsi_active_mode_clock_source_t amclks; /*!< Active mode clock source. */ + tsi_active_mode_prescaler_t ampsc; /*!< Active mode prescaler. */ + tsi_electrode_osc_prescaler_t ps; /*!< Electrode Oscillator Prescaler */ + tsi_external_osc_charge_current_t extchrg; /*!< External Oscillator charge current */ + tsi_reference_osc_charge_current_t refchrg; /*!< Reference Oscillator charge current */ + tsi_n_consecutive_scans_t nscn; /*!< Number of scans. */ +} tsi_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +/*! + * @brief Initializes hardware. + * + * @details Initializes the peripheral to the targeted state specified by the parameter configuration, + * such as initialize and set prescalers, number of scans, clocks, delta voltage + * capacitance trimmer, reference, and electrode charge current and threshold. + * + * @param base TSI peripheral base address. + * @param config Pointer to the TSI peripheral configuration structure. + * @return none + */ +void TSI_Init(TSI_Type *base, const tsi_config_t *config); + +/*! + * @brief De-initializes hardware. + * + * @details De-initializes the peripheral to default state. + * + * @param base TSI peripheral base address. + * @return none + */ +void TSI_Deinit(TSI_Type *base); + +/*! + * @brief Gets TSI normal mode user configuration structure. + * This interface sets the 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: + * @code + userConfig.lpclks = kTSI_LowPowerClockSource_LPOCLK; + userConfig.lpscnitv = kTSI_LowPowerInterval_100ms; + userConfig.amclks = kTSI_ActiveClkSource_LPOSCCLK; + userConfig.ampsc = kTSI_ActiveModePrescaler_8div; + userConfig.ps = kTSI_ElecOscPrescaler_2div; + userConfig.extchrg = kTSI_ExtOscChargeCurrent_10uA; + userConfig.refchrg = kTSI_RefOscChargeCurrent_10uA; + userConfig.nscn = kTSI_ConsecutiveScansNumber_8time; + userConfig.thresh = 0U; + userConfig.thresl = 0U; + @endcode + * + * @param userConfig Pointer to the TSI user configuration structure. + */ +void TSI_GetNormalModeDefaultConfig(tsi_config_t *userConfig); + +/*! + * @brief Gets the TSI low power mode default user configuration structure. + * 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: + * @code + userConfig.lpclks = kTSI_LowPowerClockSource_LPOCLK; + userConfig.lpscnitv = kTSI_LowPowerInterval_100ms; + userConfig.amclks = kTSI_ActiveClkSource_LPOSCCLK; + userConfig.ampsc = kTSI_ActiveModePrescaler_64div; + userConfig.ps = kTSI_ElecOscPrescaler_1div; + userConfig.extchrg = kTSI_ExtOscChargeCurrent_2uA; + userConfig.refchrg = kTSI_RefOscChargeCurrent_32uA; + userConfig.nscn = kTSI_ConsecutiveScansNumber_26time; + userConfig.thresh = 15000U; + userConfig.thresl = 1000U; + @endcode + * + * @param userConfig Pointer to the TSI user configuration structure. + */ +void TSI_GetLowPowerModeDefaultConfig(tsi_config_t *userConfig); + +/*! + * @brief Hardware calibration. + * + * @details Calibrates the peripheral to fetch the initial counter value of the enabled electrodes. + * This API is mostly used at the initial application setup. Call this function after the \ref TSI_Init API + * and use the calibrated counter values to set up applications + * (such as to determine under which counter value a touch event occurs). + * + * @note This API is called in normal power modes. + * @note For K60 series, the calibrated baseline counter value CANNOT be used in low power modes. To obtain + * the calibrated counter values in low power modes, see K60 Mask Set Errata for Mask 5N22D. + * @param base TSI peripheral base address. + * @param calBuff Data buffer that store the calibrated counter value. + * @return none + * + */ +void TSI_Calibrate(TSI_Type *base, tsi_calibration_data_t *calBuff); + +/*! + * @brief Enables the TSI interrupt requests. + * @param base TSI peripheral base address. + * @param mask interrupt source + * The parameter can be a combination of the following source if defined: + * @arg kTSI_GlobalInterruptEnable + * @arg kTSI_EndOfScanInterruptEnable + * @arg kTSI_OutOfRangeInterruptEnable + * @arg kTSI_ErrorInterrruptEnable + */ +void TSI_EnableInterrupts(TSI_Type *base, uint32_t mask); + +/*! + * @brief Disables the TSI interrupt requests. + * @param base TSI peripheral base address. + * @param mask interrupt source + * The parameter can be a combination of the following source if defined: + * @arg kTSI_GlobalInterruptEnable + * @arg kTSI_EndOfScanInterruptEnable + * @arg kTSI_OutOfRangeInterruptEnable + * @arg kTSI_ErrorInterrruptEnable + */ +void TSI_DisableInterrupts(TSI_Type *base, uint32_t mask); + +/*! +* @brief Gets the interrupt flags. +* This function get TSI interrupt flags. +* +* @param base TSI peripheral base address. +* @return The mask of these status flag bits. +*/ +static inline uint32_t TSI_GetStatusFlags(TSI_Type *base) +{ + return (base->GENCS & + (kTSI_EndOfScanFlag | kTSI_OutOfRangeFlag | kTSI_ExternalElectrodeErrorFlag | kTSI_OverrunErrorFlag)); +} + +/*! + * @brief Clears the interrupt flags. + * + * This function clears the TSI interrupt flags. + * @note The automatically cleared flags can't be cleared by this function. + * + * @param base TSI peripheral base address. + * @param mask the status flags to clear. + */ +void TSI_ClearStatusFlags(TSI_Type *base, uint32_t mask); + +/*! +* @brief Gets the TSI scan trigger mode. +* +* @param base TSI peripheral base address. +* @return Scan trigger mode. +*/ +static inline uint32_t TSI_GetScanTriggerMode(TSI_Type *base) +{ + return (base->GENCS & TSI_GENCS_STM_MASK); +} + +/*! +* @brief Gets the scan in progress flag. +* +* @param base TSI peripheral base address. +* @return True - if scan is in progress. +* False - if scan is not in progress. +*/ +static inline bool TSI_IsScanInProgress(TSI_Type *base) +{ + return (base->GENCS & TSI_GENCS_SCNIP_MASK); +} + +/*! +* @brief Sets the electrode oscillator prescaler. +* +* @param base TSI peripheral base address. +* @param prescaler Prescaler value. +* @return none. +*/ +static inline void TSI_SetElectrodeOSCPrescaler(TSI_Type *base, tsi_electrode_osc_prescaler_t prescaler) +{ + base->GENCS = (base->GENCS & ~(TSI_GENCS_PS_MASK | ALL_FLAGS_MASK)) | (TSI_GENCS_PS(prescaler)); +} + +/*! +* @brief Sets the number of scans (NSCN). +* +* @param base TSI peripheral base address. +* @param number Number of scans. +* @return none. +*/ +static inline void TSI_SetNumberOfScans(TSI_Type *base, tsi_n_consecutive_scans_t number) +{ + base->GENCS = (base->GENCS & ~(TSI_GENCS_NSCN_MASK | ALL_FLAGS_MASK)) | (TSI_GENCS_NSCN(number)); +} + +/*! +* @brief Enables/disables the TSI module. +* +* @param base TSI peripheral base address. +* @param enable Choose whether to enable TSI module. +* - true Enable module; +* - false Disable module; +* @return none. +*/ +static inline void TSI_EnableModule(TSI_Type *base, bool enable) +{ + if (enable) + { + base->GENCS = (base->GENCS & ~ALL_FLAGS_MASK) | TSI_GENCS_TSIEN_MASK; /* Enable module */ + } + else + { + base->GENCS = (base->GENCS & ~ALL_FLAGS_MASK) & (~TSI_GENCS_TSIEN_MASK); /* Disable module */ + } +} + +/*! +* @brief Enables/disables the TSI module in low power stop mode. +* +* @param base TSI peripheral base address. +* @param enable Choose whether to enable TSI module in low power modes. +* - true Enable module in low power modes; +* - false Disable module in low power modes; +* @return none. +*/ +static inline void TSI_EnableLowPower(TSI_Type *base, bool enable) +{ + if (enable) + { + base->GENCS = (base->GENCS & ~ALL_FLAGS_MASK) | TSI_GENCS_STPE_MASK; /* Enable module in low power stop mode */ + } + else + { + base->GENCS = (base->GENCS & ~ALL_FLAGS_MASK) & (~TSI_GENCS_STPE_MASK); /* Disable module in low power stop mode */ + } +} + +/*! +* @brief Enables/disables the periodical (hardware) trigger scan. +* +* @param base TSI peripheral base address. +* @param enable Choose whether to enable periodical trigger scan. +* - true Enable periodical trigger scan; +* - false Enable software trigger scan; +* @return none. +*/ +static inline void TSI_EnablePeriodicalScan(TSI_Type *base, bool enable) +{ + if (enable) + { + base->GENCS = (base->GENCS & ~ALL_FLAGS_MASK) | TSI_GENCS_STM_MASK; /* Enable period trigger scan */ + } + else + { + base->GENCS = (base->GENCS & ~ALL_FLAGS_MASK) & (~TSI_GENCS_STM_MASK); /* Enable software trigger scan */ + } +} + +/*! +* @brief Starts a measurement (trigger a new measurement). +* +* @param base TSI peripheral base address. +* @return none. +*/ +static inline void TSI_StartSoftwareTrigger(TSI_Type *base) +{ + base->GENCS = (base->GENCS & ~ALL_FLAGS_MASK) | TSI_GENCS_SWTS_MASK; +} + +/*! +* @brief Sets a low power scan interval. +* +* @param base TSI peripheral base address. +* @param interval Interval for low power scan. +* @return none. +*/ +static inline void TSI_SetLowPowerScanInterval(TSI_Type *base, tsi_low_power_scan_interval_t interval) +{ + base->GENCS = (base->GENCS & ~(TSI_GENCS_LPSCNITV_MASK | ALL_FLAGS_MASK)) | (TSI_GENCS_LPSCNITV(interval)); +} + +/*! +* @brief Sets a low power clock. +* +* @param base TSI peripheral base address. +* @param clock Low power clock selection. +*/ +static inline void TSI_SetLowPowerClock(TSI_Type *base, uint32_t clock) +{ + base->GENCS = (base->GENCS & ~(TSI_GENCS_LPCLKS_MASK | ALL_FLAGS_MASK)) | (TSI_GENCS_LPCLKS(clock)); +} + +/*! +* @brief Sets the reference oscillator charge current. +* +* @param base TSI peripheral base address. +* @param current The reference oscillator charge current. +* @return none. +*/ +static inline void TSI_SetReferenceChargeCurrent(TSI_Type *base, tsi_reference_osc_charge_current_t current) +{ + base->SCANC = ((base->SCANC) & ~TSI_SCANC_REFCHRG_MASK) | (TSI_SCANC_REFCHRG(current)); +} + +/*! +* @brief Sets the electrode charge current. +* +* @param base TSI peripheral base address. +* @param current The external electrode charge current. +* @return none. +*/ +static inline void TSI_SetElectrodeChargeCurrent(TSI_Type *base, tsi_external_osc_charge_current_t current) +{ + base->SCANC = ((base->SCANC) & ~TSI_SCANC_EXTCHRG_MASK) | (TSI_SCANC_EXTCHRG(current)); +} + +/*! +* @brief Sets the scan modulo value. +* +* @param base TSI peripheral base address. +* @param modulo Scan modulo value. +* @return none. +*/ +static inline void TSI_SetScanModulo(TSI_Type *base, uint32_t modulo) +{ + base->SCANC = ((base->SCANC) & ~TSI_SCANC_SMOD_MASK) | (TSI_SCANC_SMOD(modulo)); +} + +/*! +* @brief Sets the active mode source. +* +* @param base TSI peripheral base address. +* @param source Active mode clock source (LPOSCCLK, MCGIRCLK, OSCERCLK). +* @return none. +*/ +static inline void TSI_SetActiveModeSource(TSI_Type *base, uint32_t source) +{ + base->SCANC = ((base->SCANC) & ~TSI_SCANC_AMCLKS_MASK) | (TSI_SCANC_AMCLKS(source)); +} + +/*! +* @brief Sets the active mode prescaler. +* +* @param base TSI peripheral base address. +* @param prescaler Prescaler value. +* @return none. +*/ +static inline void TSI_SetActiveModePrescaler(TSI_Type *base, tsi_active_mode_prescaler_t prescaler) +{ + base->SCANC = ((base->SCANC) & ~TSI_SCANC_AMPSC_MASK) | (TSI_SCANC_AMPSC(prescaler)); +} + +/*! +* @brief Sets the low power channel. +* Only one channel can be enabled in low power mode. +* +* @param base TSI peripheral base address. +* @param channel Channel number. +* @return none. +*/ +static inline void TSI_SetLowPowerChannel(TSI_Type *base, uint16_t channel) +{ + assert(channel < FSL_FEATURE_TSI_CHANNEL_COUNT); + + base->PEN = ((base->PEN) & ~TSI_PEN_LPSP_MASK) | (TSI_PEN_LPSP(channel)); +} + +/*! + * @brief Gets the enabled channel in low power modes. + * @note Only one channel can be enabled in low power mode. + * + * @param base TSI peripheral base address. + * @return Channel number. + */ +static inline uint32_t TSI_GetLowPowerChannel(TSI_Type *base) +{ + return ((base->PEN & TSI_PEN_LPSP_MASK) >> TSI_PEN_LPSP_SHIFT); +} + +/*! +* @brief Enables/disables a channel. +* +* @param base TSI peripheral base address. +* @param channel Channel to be enabled. +* @param enable Choose whether to enable specific channel. +* - true Enable the specific channel; +* - false Disable the specific channel; +* @return none. +*/ +static inline void TSI_EnableChannel(TSI_Type *base, uint16_t channel, bool enable) +{ + assert(channel < FSL_FEATURE_TSI_CHANNEL_COUNT); + + if (enable) + { + base->PEN |= (1U << channel); /* Enable this specific channel */ + } + else + { + base->PEN &= ~(1U << channel); /* Disable this specific channel */ + } +} + +/*! +* @brief Enables/disables channels. +* The function enables or disables channels by mask. It can enable/disable all channels at once. +* +* @param base TSI peripheral base address. +* @param channelsMask Channels mask that indicate channels that are to be enabled/disabled. +* @param enable Choose to enable or disable the specified channels. +* - true Enable the specified channels; +* - false Disable the specified channels; +* @return none. +*/ +static inline void TSI_EnableChannels(TSI_Type *base, uint16_t channelsMask, bool enable) +{ + if (enable) + { + base->PEN |= channelsMask; /* Enable these specified channels */ + } + else + { + base->PEN &= ~(0x0000FFFFU & (uint32_t)channelsMask); /* Disable these specified channels */ + } +} + +/*! + * @brief Returns if a channel is enabled. + * + * @param base TSI peripheral base address. + * @param channel Channel to be checked. + * + * @return true - if the channel is enabled; + * false - if the channel is disabled; + */ +static inline bool TSI_IsChannelEnabled(TSI_Type *base, uint16_t channel) +{ + assert(channel < FSL_FEATURE_TSI_CHANNEL_COUNT); + + return ((base->PEN) & (1U << channel)); +} + +/*! +* @brief Returns the mask of enabled channels. +* +* @param base TSI peripheral base address. +* @return Channels mask that indicates currently enabled channels. +*/ +static inline uint16_t TSI_GetEnabledChannels(TSI_Type *base) +{ + return (uint16_t)(base->PEN & 0x0000FFFFU); +} + +/*! +* @brief Gets the wake up channel counter for low-power mode usage. +* +* @param base TSI peripheral base address. +* @return Wake up counter value. +*/ +static inline uint16_t TSI_GetWakeUpChannelCounter(TSI_Type *base) +{ + return (uint16_t)base->WUCNTR; +} + +/*! +* @brief Gets the TSI conversion counter of a specific channel in normal mode. +* @note This API can only be used in normal active modes. +* +* @param base TSI peripheral base address. +* @param channel Index of the specific TSI channel. +* +* @return The counter value of the specific channel. +*/ +static inline uint16_t TSI_GetNormalModeCounter(TSI_Type *base, uint16_t channel) +{ + assert(channel < FSL_FEATURE_TSI_CHANNEL_COUNT); + + uint16_t *counter = (uint16_t *)((uint32_t)(&(((base)->CNTR1))) + (channel * 2U)); + return (uint16_t)(*counter); +} + +/*! +* @brief Sets a low threshold. +* +* @param base TSI peripheral base address. +* @param low_threshold Low counter threshold. +* @return none. +*/ +static inline void TSI_SetLowThreshold(TSI_Type *base, uint16_t low_threshold) +{ + base->THRESHOLD = ((base->THRESHOLD) & ~TSI_THRESHOLD_LTHH_MASK) | (TSI_THRESHOLD_LTHH(low_threshold)); +} + +/*! +* @brief Sets a high threshold. +* +* @param base TSI peripheral base address. +* @param high_threshold High counter threshold. +* @return none. +*/ +static inline void TSI_SetHighThreshold(TSI_Type *base, uint16_t high_threshold) +{ + base->THRESHOLD = ((base->THRESHOLD) & ~TSI_THRESHOLD_HTHH_MASK) | (TSI_THRESHOLD_HTHH(high_threshold)); +} + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +/*! @}*/ + +#endif /* _FSL_TSI_V2_H_*/ diff --git a/drivers/include/fsl_uart.h b/drivers/include/fsl_uart.h new file mode 100644 index 0000000..451baa9 --- /dev/null +++ b/drivers/include/fsl_uart.h @@ -0,0 +1,777 @@ +/* + * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_UART_H_ +#define _FSL_UART_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup uart_driver + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief UART driver version 2.1.4. */ +#define FSL_UART_DRIVER_VERSION (MAKE_VERSION(2, 1, 4)) +/*@}*/ + +/*! @brief Error codes for the UART driver. */ +enum _uart_status +{ + kStatus_UART_TxBusy = MAKE_STATUS(kStatusGroup_UART, 0), /*!< Transmitter is busy. */ + kStatus_UART_RxBusy = MAKE_STATUS(kStatusGroup_UART, 1), /*!< Receiver is busy. */ + kStatus_UART_TxIdle = MAKE_STATUS(kStatusGroup_UART, 2), /*!< UART transmitter is idle. */ + kStatus_UART_RxIdle = MAKE_STATUS(kStatusGroup_UART, 3), /*!< UART receiver is idle. */ + kStatus_UART_TxWatermarkTooLarge = MAKE_STATUS(kStatusGroup_UART, 4), /*!< TX FIFO watermark too large */ + kStatus_UART_RxWatermarkTooLarge = MAKE_STATUS(kStatusGroup_UART, 5), /*!< RX FIFO watermark too large */ + kStatus_UART_FlagCannotClearManually = + MAKE_STATUS(kStatusGroup_UART, 6), /*!< UART flag can't be manually cleared. */ + kStatus_UART_Error = MAKE_STATUS(kStatusGroup_UART, 7), /*!< Error happens on UART. */ + kStatus_UART_RxRingBufferOverrun = MAKE_STATUS(kStatusGroup_UART, 8), /*!< UART RX software ring buffer overrun. */ + kStatus_UART_RxHardwareOverrun = MAKE_STATUS(kStatusGroup_UART, 9), /*!< UART RX receiver overrun. */ + kStatus_UART_NoiseError = MAKE_STATUS(kStatusGroup_UART, 10), /*!< UART noise error. */ + kStatus_UART_FramingError = MAKE_STATUS(kStatusGroup_UART, 11), /*!< UART framing error. */ + kStatus_UART_ParityError = MAKE_STATUS(kStatusGroup_UART, 12), /*!< UART parity error. */ + kStatus_UART_BaudrateNotSupport = + MAKE_STATUS(kStatusGroup_UART, 13), /*!< Baudrate is not support in current clock source */ +}; + +/*! @brief UART parity mode. */ +typedef enum _uart_parity_mode +{ + kUART_ParityDisabled = 0x0U, /*!< Parity disabled */ + kUART_ParityEven = 0x2U, /*!< Parity enabled, type even, bit setting: PE|PT = 10 */ + kUART_ParityOdd = 0x3U, /*!< Parity enabled, type odd, bit setting: PE|PT = 11 */ +} uart_parity_mode_t; + +/*! @brief UART stop bit count. */ +typedef enum _uart_stop_bit_count +{ + kUART_OneStopBit = 0U, /*!< One stop bit */ + kUART_TwoStopBit = 1U, /*!< Two stop bits */ +} uart_stop_bit_count_t; + +/*! + * @brief UART interrupt configuration structure, default settings all disabled. + * + * This structure contains the settings for all of the UART interrupt configurations. + */ +enum _uart_interrupt_enable +{ +#if defined(FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT + kUART_LinBreakInterruptEnable = (UART_BDH_LBKDIE_MASK), /*!< LIN break detect interrupt. */ +#endif + kUART_RxActiveEdgeInterruptEnable = (UART_BDH_RXEDGIE_MASK), /*!< RX active edge interrupt. */ + kUART_TxDataRegEmptyInterruptEnable = (UART_C2_TIE_MASK << 8), /*!< Transmit data register empty interrupt. */ + kUART_TransmissionCompleteInterruptEnable = (UART_C2_TCIE_MASK << 8), /*!< Transmission complete interrupt. */ + kUART_RxDataRegFullInterruptEnable = (UART_C2_RIE_MASK << 8), /*!< Receiver data register full interrupt. */ + kUART_IdleLineInterruptEnable = (UART_C2_ILIE_MASK << 8), /*!< Idle line interrupt. */ + kUART_RxOverrunInterruptEnable = (UART_C3_ORIE_MASK << 16), /*!< Receiver overrun interrupt. */ + kUART_NoiseErrorInterruptEnable = (UART_C3_NEIE_MASK << 16), /*!< Noise error flag interrupt. */ + kUART_FramingErrorInterruptEnable = (UART_C3_FEIE_MASK << 16), /*!< Framing error flag interrupt. */ + kUART_ParityErrorInterruptEnable = (UART_C3_PEIE_MASK << 16), /*!< Parity error flag interrupt. */ +#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO + kUART_RxFifoOverflowInterruptEnable = (UART_CFIFO_RXOFE_MASK << 24), /*!< RX FIFO overflow interrupt. */ + kUART_TxFifoOverflowInterruptEnable = (UART_CFIFO_TXOFE_MASK << 24), /*!< TX FIFO overflow interrupt. */ + kUART_RxFifoUnderflowInterruptEnable = (UART_CFIFO_RXUFE_MASK << 24), /*!< RX FIFO underflow interrupt. */ +#endif + kUART_AllInterruptsEnable = +#if defined(FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT + kUART_LinBreakInterruptEnable | +#endif + kUART_RxActiveEdgeInterruptEnable | kUART_TxDataRegEmptyInterruptEnable | + kUART_TransmissionCompleteInterruptEnable | kUART_RxDataRegFullInterruptEnable | kUART_IdleLineInterruptEnable | + kUART_RxOverrunInterruptEnable | kUART_NoiseErrorInterruptEnable | kUART_FramingErrorInterruptEnable | + kUART_ParityErrorInterruptEnable +#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO + | + kUART_RxFifoOverflowInterruptEnable | kUART_TxFifoOverflowInterruptEnable | kUART_RxFifoUnderflowInterruptEnable +#endif + , +}; + +/*! + * @brief UART status flags. + * + * This provides constants for the UART status flags for use in the UART functions. + */ +enum _uart_flags +{ + kUART_TxDataRegEmptyFlag = (UART_S1_TDRE_MASK), /*!< TX data register empty flag. */ + kUART_TransmissionCompleteFlag = (UART_S1_TC_MASK), /*!< Transmission complete flag. */ + kUART_RxDataRegFullFlag = (UART_S1_RDRF_MASK), /*!< RX data register full flag. */ + kUART_IdleLineFlag = (UART_S1_IDLE_MASK), /*!< Idle line detect flag. */ + kUART_RxOverrunFlag = (UART_S1_OR_MASK), /*!< RX overrun flag. */ + kUART_NoiseErrorFlag = (UART_S1_NF_MASK), /*!< RX takes 3 samples of each received bit. + If any of these samples differ, noise flag sets */ + kUART_FramingErrorFlag = (UART_S1_FE_MASK), /*!< Frame error flag, sets if logic 0 was detected + where stop bit expected */ + kUART_ParityErrorFlag = (UART_S1_PF_MASK), /*!< If parity enabled, sets upon parity error detection */ +#if defined(FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT + kUART_LinBreakFlag = + (UART_S2_LBKDIF_MASK + << 8), /*!< LIN break detect interrupt flag, sets when + LIN break char detected and LIN circuit enabled */ +#endif + kUART_RxActiveEdgeFlag = + (UART_S2_RXEDGIF_MASK << 8), /*!< RX pin active edge interrupt flag, + sets when active edge detected */ + kUART_RxActiveFlag = + (UART_S2_RAF_MASK << 8), /*!< Receiver Active Flag (RAF), + sets at beginning of valid start bit */ +#if defined(FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS) && FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS + kUART_NoiseErrorInRxDataRegFlag = (UART_ED_NOISY_MASK << 16), /*!< Noisy bit, sets if noise detected. */ + kUART_ParityErrorInRxDataRegFlag = (UART_ED_PARITYE_MASK << 16), /*!< Paritye bit, sets if parity error detected. */ +#endif +#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO + kUART_TxFifoEmptyFlag = (UART_SFIFO_TXEMPT_MASK << 24), /*!< TXEMPT bit, sets if TX buffer is empty */ + kUART_RxFifoEmptyFlag = (UART_SFIFO_RXEMPT_MASK << 24), /*!< RXEMPT bit, sets if RX buffer is empty */ + kUART_TxFifoOverflowFlag = (UART_SFIFO_TXOF_MASK << 24), /*!< TXOF bit, sets if TX buffer overflow occurred */ + kUART_RxFifoOverflowFlag = (UART_SFIFO_RXOF_MASK << 24), /*!< RXOF bit, sets if receive buffer overflow */ + kUART_RxFifoUnderflowFlag = (UART_SFIFO_RXUF_MASK << 24), /*!< RXUF bit, sets if receive buffer underflow */ +#endif +}; + +/*! @brief UART configuration structure. */ +typedef struct _uart_config +{ + uint32_t baudRate_Bps; /*!< UART baud rate */ + uart_parity_mode_t parityMode; /*!< Parity mode, disabled (default), even, odd */ +#if defined(FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT) && FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT + uart_stop_bit_count_t stopBitCount; /*!< Number of stop bits, 1 stop bit (default) or 2 stop bits */ +#endif +#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO + uint8_t txFifoWatermark; /*!< TX FIFO watermark */ + uint8_t rxFifoWatermark; /*!< RX FIFO watermark */ +#endif + bool enableTx; /*!< Enable TX */ + bool enableRx; /*!< Enable RX */ +} uart_config_t; + +/*! @brief UART transfer structure. */ +typedef struct _uart_transfer +{ + uint8_t *data; /*!< The buffer of data to be transfer.*/ + size_t dataSize; /*!< The byte count to be transfer. */ +} uart_transfer_t; + +/* Forward declaration of the handle typedef. */ +typedef struct _uart_handle uart_handle_t; + +/*! @brief UART transfer callback function. */ +typedef void (*uart_transfer_callback_t)(UART_Type *base, uart_handle_t *handle, status_t status, void *userData); + +/*! @brief UART handle structure. */ +struct _uart_handle +{ + 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 */ +}; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* _cplusplus */ + +/*! + * @name Initialization and deinitialization + * @{ + */ + +/*! + * @brief Initializes a UART instance with a user configuration structure and peripheral clock. + * + * 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. + * @code + * 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); + * @endcode + * + * @param base UART peripheral base address. + * @param config Pointer to the user-defined configuration structure. + * @param srcClock_Hz UART clock source frequency in HZ. + * @retval kStatus_UART_BaudrateNotSupport Baudrate is not support in current clock source. + * @retval kStatus_Success Status UART initialize succeed + */ +status_t UART_Init(UART_Type *base, const uart_config_t *config, uint32_t srcClock_Hz); + +/*! + * @brief Deinitializes a UART instance. + * + * This function waits for TX complete, disables TX and RX, and disables the UART clock. + * + * @param base UART peripheral base address. + */ +void UART_Deinit(UART_Type *base); + +/*! + * @brief Gets the default configuration structure. + * + * This function initializes the UART configuration structure to a default value. The default + * values are as follows. + * uartConfig->baudRate_Bps = 115200U; + * uartConfig->bitCountPerChar = kUART_8BitsPerChar; + * uartConfig->parityMode = kUART_ParityDisabled; + * uartConfig->stopBitCount = kUART_OneStopBit; + * uartConfig->txFifoWatermark = 0; + * uartConfig->rxFifoWatermark = 1; + * uartConfig->enableTx = false; + * uartConfig->enableRx = false; + * + * @param config Pointer to configuration structure. + */ +void UART_GetDefaultConfig(uart_config_t *config); + +/*! + * @brief Sets the UART instance baud rate. + * + * 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. + * @code + * UART_SetBaudRate(UART1, 115200U, 20000000U); + * @endcode + * + * @param base UART peripheral base address. + * @param baudRate_Bps UART baudrate to be set. + * @param srcClock_Hz UART clock source freqency in Hz. + * @retval kStatus_UART_BaudrateNotSupport Baudrate is not support in the current clock source. + * @retval kStatus_Success Set baudrate succeeded. + */ +status_t UART_SetBaudRate(UART_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz); + +/* @} */ + +/*! + * @name Status + * @{ + */ + +/*! + * @brief Gets UART status flags. + * + * This function gets all UART status flags. The flags are returned as the logical + * OR value of the enumerators @ref _uart_flags. To check a specific status, + * compare the return value with enumerators in @ref _uart_flags. + * For example, to check whether the TX is empty, do the following. + * @code + * if (kUART_TxDataRegEmptyFlag & UART_GetStatusFlags(UART1)) + * { + * ... + * } + * @endcode + * + * @param base UART peripheral base address. + * @return UART status flags which are ORed by the enumerators in the _uart_flags. + */ +uint32_t UART_GetStatusFlags(UART_Type *base); + +/*! + * @brief Clears status flags with the provided mask. + * + * 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_TxDataRegEmptyFlag, kUART_TransmissionCompleteFlag, kUART_RxDataRegFullFlag, + * kUART_RxActiveFlag, kUART_NoiseErrorInRxDataRegFlag, kUART_ParityErrorInRxDataRegFlag, + * kUART_TxFifoEmptyFlag,kUART_RxFifoEmptyFlag + * Note that this API should be called when the Tx/Rx is idle. Otherwise it has no effect. + * + * @param base UART peripheral base address. + * @param mask The status flags to be cleared; it is logical OR value of @ref _uart_flags. + * @retval kStatus_UART_FlagCannotClearManually The flag can't be cleared by this function but + * it is cleared automatically by hardware. + * @retval kStatus_Success Status in the mask is cleared. + */ +status_t UART_ClearStatusFlags(UART_Type *base, uint32_t mask); + +/* @} */ + +/*! + * @name Interrupts + * @{ + */ + +/*! + * @brief Enables UART interrupts according to the provided mask. + * + * This function enables the UART interrupts according to the provided mask. The mask + * is a logical OR of enumeration members. See @ref _uart_interrupt_enable. + * For example, to enable TX empty interrupt and RX full interrupt, do the following. + * @code + * UART_EnableInterrupts(UART1,kUART_TxDataRegEmptyInterruptEnable | kUART_RxDataRegFullInterruptEnable); + * @endcode + * + * @param base UART peripheral base address. + * @param mask The interrupts to enable. Logical OR of @ref _uart_interrupt_enable. + */ +void UART_EnableInterrupts(UART_Type *base, uint32_t mask); + +/*! + * @brief Disables the UART interrupts according to the provided mask. + * + * This function disables the UART interrupts according to the provided mask. The mask + * is a logical OR of enumeration members. See @ref _uart_interrupt_enable. + * For example, to disable TX empty interrupt and RX full interrupt do the following. + * @code + * UART_DisableInterrupts(UART1,kUART_TxDataRegEmptyInterruptEnable | kUART_RxDataRegFullInterruptEnable); + * @endcode + * + * @param base UART peripheral base address. + * @param mask The interrupts to disable. Logical OR of @ref _uart_interrupt_enable. + */ +void UART_DisableInterrupts(UART_Type *base, uint32_t mask); + +/*! + * @brief Gets the enabled UART interrupts. + * + * This function gets the enabled UART interrupts. The enabled interrupts are returned + * as the logical OR value of the enumerators @ref _uart_interrupt_enable. To check + * a specific interrupts enable status, compare the return value with enumerators + * in @ref _uart_interrupt_enable. + * For example, to check whether TX empty interrupt is enabled, do the following. + * @code + * uint32_t enabledInterrupts = UART_GetEnabledInterrupts(UART1); + * + * if (kUART_TxDataRegEmptyInterruptEnable & enabledInterrupts) + * { + * ... + * } + * @endcode + * + * @param base UART peripheral base address. + * @return UART interrupt flags which are logical OR of the enumerators in @ref _uart_interrupt_enable. + */ +uint32_t UART_GetEnabledInterrupts(UART_Type *base); + +/* @} */ + +#if defined(FSL_FEATURE_UART_HAS_DMA_SELECT) && FSL_FEATURE_UART_HAS_DMA_SELECT +/*! + * @name DMA Control + * @{ + */ + +/*! + * @brief Gets the UART data register address. + * + * This function returns the UART data register address, which is mainly used by DMA/eDMA. + * + * @param base UART peripheral base address. + * @return UART data register addresses which are used both by the transmitter and the receiver. + */ +static inline uint32_t UART_GetDataRegisterAddress(UART_Type *base) +{ + return (uint32_t) & (base->D); +} + +/*! + * @brief Enables or disables the UART transmitter DMA request. + * + * This function enables or disables the transmit data register empty flag, S1[TDRE], to generate the DMA requests. + * + * @param base UART peripheral base address. + * @param enable True to enable, false to disable. + */ +static inline void UART_EnableTxDMA(UART_Type *base, bool enable) +{ + if (enable) + { +#if (defined(FSL_FEATURE_UART_IS_SCI) && FSL_FEATURE_UART_IS_SCI) + base->C4 |= UART_C4_TDMAS_MASK; +#else + base->C5 |= UART_C5_TDMAS_MASK; +#endif + base->C2 |= UART_C2_TIE_MASK; + } + else + { +#if (defined(FSL_FEATURE_UART_IS_SCI) && FSL_FEATURE_UART_IS_SCI) + base->C4 &= ~UART_C4_TDMAS_MASK; +#else + base->C5 &= ~UART_C5_TDMAS_MASK; +#endif + base->C2 &= ~UART_C2_TIE_MASK; + } +} + +/*! + * @brief Enables or disables the UART receiver DMA. + * + * This function enables or disables the receiver data register full flag, S1[RDRF], to generate DMA requests. + * + * @param base UART peripheral base address. + * @param enable True to enable, false to disable. + */ +static inline void UART_EnableRxDMA(UART_Type *base, bool enable) +{ + if (enable) + { +#if (defined(FSL_FEATURE_UART_IS_SCI) && FSL_FEATURE_UART_IS_SCI) + base->C4 |= UART_C4_RDMAS_MASK; +#else + base->C5 |= UART_C5_RDMAS_MASK; +#endif + base->C2 |= UART_C2_RIE_MASK; + } + else + { +#if (defined(FSL_FEATURE_UART_IS_SCI) && FSL_FEATURE_UART_IS_SCI) + base->C4 &= ~UART_C4_RDMAS_MASK; +#else + base->C5 &= ~UART_C5_RDMAS_MASK; +#endif + base->C2 &= ~UART_C2_RIE_MASK; + } +} + +/* @} */ +#endif /* FSL_FEATURE_UART_HAS_DMA_SELECT */ + +/*! + * @name Bus Operations + * @{ + */ + +/*! + * @brief Enables or disables the UART transmitter. + * + * This function enables or disables the UART transmitter. + * + * @param base UART peripheral base address. + * @param enable True to enable, false to disable. + */ +static inline void UART_EnableTx(UART_Type *base, bool enable) +{ + if (enable) + { + base->C2 |= UART_C2_TE_MASK; + } + else + { + base->C2 &= ~UART_C2_TE_MASK; + } +} + +/*! + * @brief Enables or disables the UART receiver. + * + * This function enables or disables the UART receiver. + * + * @param base UART peripheral base address. + * @param enable True to enable, false to disable. + */ +static inline void UART_EnableRx(UART_Type *base, bool enable) +{ + if (enable) + { + base->C2 |= UART_C2_RE_MASK; + } + else + { + base->C2 &= ~UART_C2_RE_MASK; + } +} + +/*! + * @brief Writes to the TX register. + * + * 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. + * + * @param base UART peripheral base address. + * @param data The byte to write. + */ +static inline void UART_WriteByte(UART_Type *base, uint8_t data) +{ + base->D = data; +} + +/*! + * @brief Reads the RX register directly. + * + * 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. + * + * @param base UART peripheral base address. + * @return The byte read from UART data register. + */ +static inline uint8_t UART_ReadByte(UART_Type *base) +{ + return base->D; +} + +/*! + * @brief Writes to the TX register using a blocking method. + * + * 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. + * + * @param base UART peripheral base address. + * @param data Start address of the data to write. + * @param length Size of the data to write. + */ +void UART_WriteBlocking(UART_Type *base, const uint8_t *data, size_t length); + +/*! + * @brief Read RX data register using a blocking method. + * + * 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. + * + * @param base UART peripheral base address. + * @param data Start address of the buffer to store the received data. + * @param length Size of the buffer. + * @retval kStatus_UART_RxHardwareOverrun Receiver overrun occurred while receiving data. + * @retval kStatus_UART_NoiseError A noise error occurred while receiving data. + * @retval kStatus_UART_FramingError A framing error occurred while receiving data. + * @retval kStatus_UART_ParityError A parity error occurred while receiving data. + * @retval kStatus_Success Successfully received all data. + */ +status_t UART_ReadBlocking(UART_Type *base, uint8_t *data, size_t length); + +/* @} */ + +/*! + * @name Transactional + * @{ + */ + +/*! + * @brief Initializes the UART handle. + * + * 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. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param callback The callback function. + * @param userData The parameter of the callback function. + */ +void UART_TransferCreateHandle(UART_Type *base, + uart_handle_t *handle, + uart_transfer_callback_t callback, + void *userData); + +/*! + * @brief Sets up the RX ring buffer. + * + * This function sets up the RX ring buffer to a specific UART handle. + * + * When the RX ring buffer is used, data received are stored into the ring buffer even when the + * user doesn't call the UART_TransferReceiveNonBlocking() API. If data is already received + * in the ring buffer, the user can get the received data from the ring buffer directly. + * + * @note When using the RX ring buffer, one byte is reserved for internal use. In other + * words, if @p ringBufferSize is 32, only 31 bytes are used for saving data. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param ringBuffer Start address of the ring buffer for background receiving. Pass NULL to disable the ring buffer. + * @param ringBufferSize Size of the ring buffer. + */ +void UART_TransferStartRingBuffer(UART_Type *base, uart_handle_t *handle, uint8_t *ringBuffer, size_t ringBufferSize); + +/*! + * @brief Aborts the background transfer and uninstalls the ring buffer. + * + * This function aborts the background transfer and uninstalls the ring buffer. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + */ +void UART_TransferStopRingBuffer(UART_Type *base, uart_handle_t *handle); + +/*! + * @brief Transmits a buffer of data using the interrupt method. + * + * 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 @ref 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. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param xfer UART transfer structure. See #uart_transfer_t. + * @retval kStatus_Success Successfully start the data transmission. + * @retval kStatus_UART_TxBusy Previous transmission still not finished; data not all written to TX register yet. + * @retval kStatus_InvalidArgument Invalid argument. + */ +status_t UART_TransferSendNonBlocking(UART_Type *base, uart_handle_t *handle, uart_transfer_t *xfer); + +/*! + * @brief Aborts the interrupt-driven data transmit. + * + * This function aborts the interrupt-driven data sending. The user can get the remainBytes to find out + * how many bytes are not sent out. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + */ +void UART_TransferAbortSend(UART_Type *base, uart_handle_t *handle); + +/*! + * @brief Gets the number of bytes written to the UART TX register. + * + * This function gets the number of bytes written to the UART TX + * register by using the interrupt method. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param count Send bytes count. + * @retval kStatus_NoTransferInProgress No send in progress. + * @retval kStatus_InvalidArgument The parameter is invalid. + * @retval kStatus_Success Get successfully through the parameter \p count; + */ +status_t UART_TransferGetSendCount(UART_Type *base, uart_handle_t *handle, uint32_t *count); + +/*! + * @brief Receives a buffer of data using an interrupt method. + * + * 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 @p 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 @ref kStatus_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 @p receivedBytes 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. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param xfer UART transfer structure, see #uart_transfer_t. + * @param receivedBytes Bytes received from the ring buffer directly. + * @retval kStatus_Success Successfully queue the transfer into transmit queue. + * @retval kStatus_UART_RxBusy Previous receive request is not finished. + * @retval kStatus_InvalidArgument Invalid argument. + */ +status_t UART_TransferReceiveNonBlocking(UART_Type *base, + uart_handle_t *handle, + uart_transfer_t *xfer, + size_t *receivedBytes); + +/*! + * @brief Aborts the interrupt-driven data receiving. + * + * This function aborts the interrupt-driven data receiving. The user can get the remainBytes to know + * how many bytes are not received yet. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + */ +void UART_TransferAbortReceive(UART_Type *base, uart_handle_t *handle); + +/*! + * @brief Gets the number of bytes that have been received. + * + * This function gets the number of bytes that have been received. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param count Receive bytes count. + * @retval kStatus_NoTransferInProgress No receive in progress. + * @retval kStatus_InvalidArgument Parameter is invalid. + * @retval kStatus_Success Get successfully through the parameter \p count; + */ +status_t UART_TransferGetReceiveCount(UART_Type *base, uart_handle_t *handle, uint32_t *count); + +/*! + * @brief UART IRQ handle function. + * + * This function handles the UART transmit and receive IRQ request. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + */ +void UART_TransferHandleIRQ(UART_Type *base, uart_handle_t *handle); + +/*! + * @brief UART Error IRQ handle function. + * + * This function handles the UART error IRQ request. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + */ +void UART_TransferHandleErrorIRQ(UART_Type *base, uart_handle_t *handle); + +/* @} */ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_UART_H_ */ diff --git a/drivers/include/fsl_uart_edma.h b/drivers/include/fsl_uart_edma.h new file mode 100644 index 0000000..e411ffd --- /dev/null +++ b/drivers/include/fsl_uart_edma.h @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_UART_EDMA_H_ +#define _FSL_UART_EDMA_H_ + +#include "fsl_uart.h" +#include "fsl_dmamux.h" +#include "fsl_edma.h" + +/*! + * @addtogroup uart_edma_driver + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/* Forward declaration of the handle typedef. */ +typedef struct _uart_edma_handle uart_edma_handle_t; + +/*! @brief UART transfer callback function. */ +typedef void (*uart_edma_transfer_callback_t)(UART_Type *base, + uart_edma_handle_t *handle, + status_t status, + void *userData); + +/*! +* @brief UART eDMA handle +*/ +struct _uart_edma_handle +{ + 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 */ +}; + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name eDMA transactional + * @{ + */ + +/*! + * @brief Initializes the UART handle which is used in transactional functions. + * @param base UART peripheral base address. + * @param handle Pointer to the uart_edma_handle_t structure. + * @param callback UART callback, NULL means no callback. + * @param userData User callback function data. + * @param rxEdmaHandle User-requested DMA handle for RX DMA transfer. + * @param txEdmaHandle User-requested DMA handle for TX DMA transfer. + */ +void UART_TransferCreateHandleEDMA(UART_Type *base, + uart_edma_handle_t *handle, + uart_edma_transfer_callback_t callback, + void *userData, + edma_handle_t *txEdmaHandle, + edma_handle_t *rxEdmaHandle); + +/*! + * @brief Sends data using eDMA. + * + * 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. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param xfer UART eDMA transfer structure. See #uart_transfer_t. + * @retval kStatus_Success if succeeded; otherwise failed. + * @retval kStatus_UART_TxBusy Previous transfer ongoing. + * @retval kStatus_InvalidArgument Invalid argument. + */ +status_t UART_SendEDMA(UART_Type *base, uart_edma_handle_t *handle, uart_transfer_t *xfer); + +/*! + * @brief Receives data using eDMA. + * + * 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. + * + * @param base UART peripheral base address. + * @param handle Pointer to the uart_edma_handle_t structure. + * @param xfer UART eDMA transfer structure. See #uart_transfer_t. + * @retval kStatus_Success if succeeded; otherwise failed. + * @retval kStatus_UART_RxBusy Previous transfer ongoing. + * @retval kStatus_InvalidArgument Invalid argument. + */ +status_t UART_ReceiveEDMA(UART_Type *base, uart_edma_handle_t *handle, uart_transfer_t *xfer); + +/*! + * @brief Aborts the sent data using eDMA. + * + * This function aborts sent data using eDMA. + * + * @param base UART peripheral base address. + * @param handle Pointer to the uart_edma_handle_t structure. + */ +void UART_TransferAbortSendEDMA(UART_Type *base, uart_edma_handle_t *handle); + +/*! + * @brief Aborts the receive data using eDMA. + * + * This function aborts receive data using eDMA. + * + * @param base UART peripheral base address. + * @param handle Pointer to the uart_edma_handle_t structure. + */ +void UART_TransferAbortReceiveEDMA(UART_Type *base, uart_edma_handle_t *handle); + +/*! + * @brief Gets the number of bytes that have been written to UART TX register. + * + * This function gets the number of bytes that have been written to UART TX + * register by DMA. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param count Send bytes count. + * @retval kStatus_NoTransferInProgress No send in progress. + * @retval kStatus_InvalidArgument Parameter is invalid. + * @retval kStatus_Success Get successfully through the parameter \p count; + */ +status_t UART_TransferGetSendCountEDMA(UART_Type *base, uart_edma_handle_t *handle, uint32_t *count); + +/*! + * @brief Gets the number of received bytes. + * + * This function gets the number of received bytes. + * + * @param base UART peripheral base address. + * @param handle UART handle pointer. + * @param count Receive bytes count. + * @retval kStatus_NoTransferInProgress No receive in progress. + * @retval kStatus_InvalidArgument Parameter is invalid. + * @retval kStatus_Success Get successfully through the parameter \p count; + */ +status_t UART_TransferGetReceiveCountEDMA(UART_Type *base, uart_edma_handle_t *handle, uint32_t *count); + +/*@}*/ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* _FSL_UART_EDMA_H_ */ diff --git a/drivers/include/fsl_uart_freertos.h b/drivers/include/fsl_uart_freertos.h new file mode 100644 index 0000000..0525e23 --- /dev/null +++ b/drivers/include/fsl_uart_freertos.h @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef __FSL_UART_RTOS_H__ +#define __FSL_UART_RTOS_H__ + +#include "FreeRTOSConfig.h" +#include "fsl_uart.h" +#include +#include +#include + +/*! + * @addtogroup uart_freertos_driver + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @brief UART configuration structure */ +typedef struct _uart_rtos_config +{ + 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 */ +} uart_rtos_config_t; + +/*! +* @cond RTOS_PRIVATE +* @name UART FreeRTOS handler +* +* These are the only valid states for txEvent and rxEvent (uart_rtos_handle_t). +*/ +/*@{*/ +/*! @brief Event flag - transfer complete. */ +#define RTOS_UART_COMPLETE 0x1 +/*! @brief Event flag - ring buffer overrun. */ +#define RTOS_UART_RING_BUFFER_OVERRUN 0x2 +/*! @brief Event flag - hardware buffer overrun. */ +#define RTOS_UART_HARDWARE_BUFFER_OVERRUN 0x4 +/*@}*/ + +/*! @brief UART FreeRTOS transfer structure. */ +typedef struct _uart_rtos_handle +{ + UART_Type *base; /*!< UART base address */ + uart_transfer_t txTransfer; /*!< TX transfer structure */ + uart_transfer_t rxTransfer; /*!< RX transfer structure */ + SemaphoreHandle_t rxSemaphore; /*!< RX semaphore for resource sharing */ + SemaphoreHandle_t txSemaphore; /*!< TX semaphore for resource sharing */ + EventGroupHandle_t rxEvent; /*!< RX completion event */ + EventGroupHandle_t txEvent; /*!< TX completion event */ + void *t_state; /*!< Transactional state of the underlying driver */ +#if (configSUPPORT_STATIC_ALLOCATION == 1) + StaticSemaphore_t txSemaphoreBuffer; /*!< Statically allocated memory for txSemaphore */ + StaticSemaphore_t rxSemaphoreBuffer; /*!< Statically allocated memory for rxSemaphore */ + StaticEventGroup_t txEventBuffer; /*!< Statically allocated memory for txEvent */ + StaticEventGroup_t rxEventBuffer; /*!< Statically allocated memory for rxEvent */ +#endif +} uart_rtos_handle_t; +/*! \endcond */ + +/******************************************************************************* + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @name UART RTOS Operation + * @{ + */ + +/*! + * @brief Initializes a UART instance for operation in RTOS. + * + * @param handle The RTOS UART handle, the pointer to an allocated space for RTOS context. + * @param t_handle The pointer to the allocated space to store the transactional layer internal state. + * @param cfg The pointer to the parameters required to configure the UART after initialization. + * @return 0 succeed; otherwise fail. + */ +int UART_RTOS_Init(uart_rtos_handle_t *handle, uart_handle_t *t_handle, const uart_rtos_config_t *cfg); + +/*! + * @brief Deinitializes a UART instance for operation. + * + * This function deinitializes the UART module, sets all register values to reset value, + * and frees the resources. + * + * @param handle The RTOS UART handle. + */ +int UART_RTOS_Deinit(uart_rtos_handle_t *handle); + +/*! + * @name UART transactional Operation + * @{ + */ + +/*! + * @brief Sends data in the background. + * + * This function sends data. It is a synchronous API. + * If the hardware buffer is full, the task is in the blocked state. + * + * @param handle The RTOS UART handle. + * @param buffer The pointer to the buffer to send. + * @param length The number of bytes to send. + */ +int UART_RTOS_Send(uart_rtos_handle_t *handle, const uint8_t *buffer, uint32_t length); + +/*! + * @brief Receives data. + * + * 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. + * + * @param handle The RTOS UART handle. + * @param buffer The pointer to the buffer to write received data. + * @param length The number of bytes to receive. + * @param received The pointer to a variable of size_t where the number of received data is filled. + */ +int UART_RTOS_Receive(uart_rtos_handle_t *handle, uint8_t *buffer, uint32_t length, size_t *received); + +/* @} */ + +#if defined(__cplusplus) +} +#endif + +/*! @}*/ + +#endif /* __FSL_UART_RTOS_H__ */ diff --git a/drivers/include/fsl_vref.h b/drivers/include/fsl_vref.h new file mode 100644 index 0000000..6c6c014 --- /dev/null +++ b/drivers/include/fsl_vref.h @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _FSL_VREF_H_ +#define _FSL_VREF_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup vref + * @{ + */ + + +/****************************************************************************** + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +#define FSL_VREF_DRIVER_VERSION (MAKE_VERSION(2, 1, 0)) /*!< Version 2.1.0. */ +/*@}*/ + +/* Those macros below defined to support SoC family which have VREFL (0.4V) reference */ +#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE +#define VREF_SC_MODE_LV VREF_VREFH_SC_MODE_LV +#define VREF_SC_REGEN VREF_VREFH_SC_REGEN +#define VREF_SC_VREFEN VREF_VREFH_SC_VREFEN +#define VREF_SC_ICOMPEN VREF_VREFH_SC_ICOMPEN +#define VREF_SC_REGEN_MASK VREF_VREFH_SC_REGEN_MASK +#define VREF_SC_VREFST_MASK VREF_VREFH_SC_VREFST_MASK +#define VREF_SC_VREFEN_MASK VREF_VREFH_SC_VREFEN_MASK +#define VREF_SC_MODE_LV_MASK VREF_VREFH_SC_MODE_LV_MASK +#define VREF_SC_ICOMPEN_MASK VREF_VREFH_SC_ICOMPEN_MASK +#define TRM VREFH_TRM +#define VREF_TRM_TRIM VREF_VREFH_TRM_TRIM +#define VREF_TRM_CHOPEN_MASK VREF_VREFH_TRM_CHOPEN_MASK +#define VREF_TRM_TRIM_MASK VREF_VREFH_TRM_TRIM_MASK +#define VREF_TRM_CHOPEN_SHIFT VREF_VREFH_TRM_CHOPEN_SHIFT +#define VREF_TRM_TRIM_SHIFT VREF_VREFH_TRM_TRIM_SHIFT +#define VREF_SC_MODE_LV_SHIFT VREF_VREFH_SC_MODE_LV_SHIFT +#define VREF_SC_REGEN_SHIFT VREF_VREFH_SC_REGEN_SHIFT +#define VREF_SC_VREFST_SHIFT VREF_VREFH_SC_VREFST_SHIFT +#define VREF_SC_ICOMPEN_SHIFT VREF_VREFH_SC_ICOMPEN_SHIFT +#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ + +/*! + * @brief VREF modes. + */ +typedef enum _vref_buffer_mode +{ + kVREF_ModeBandgapOnly = 0U, /*!< Bandgap on only, for stabilization and startup */ +#if defined(FSL_FEATURE_VREF_MODE_LV_TYPE) && FSL_FEATURE_VREF_MODE_LV_TYPE + kVREF_ModeHighPowerBuffer = 1U, /*!< High-power buffer mode enabled */ + kVREF_ModeLowPowerBuffer = 2U /*!< Low-power buffer mode enabled */ +#else + kVREF_ModeTightRegulationBuffer = 2U /*!< Tight regulation buffer enabled */ +#endif /* FSL_FEATURE_VREF_MODE_LV_TYPE */ +} vref_buffer_mode_t; + +/*! + * @brief The description structure for the VREF module. + */ +typedef struct _vref_config +{ + vref_buffer_mode_t bufferMode; /*!< Buffer mode selection */ +#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE + bool enableLowRef; /*!< Set VREFL (0.4 V) reference buffer enable or disable */ + bool enableExternalVoltRef; /*!< Select external voltage reference or not (internal) */ +#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ +#if defined(FSL_FEATURE_VREF_HAS_TRM4) && FSL_FEATURE_VREF_HAS_TRM4 + bool enable2V1VoltRef; /*!< Enable Internal Voltage Reference (2.1V) */ +#endif /* FSL_FEATURE_VREF_HAS_TRM4 */ +} vref_config_t; + +/****************************************************************************** + * API + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*! + * @name VREF functional operation + * @{ + */ + +/*! + * @brief Enables the clock gate and configures the VREF module according to the configuration structure. + * + * This function must be called before calling all other VREF driver functions, + * read/write registers, and configurations with user-defined settings. + * The example below shows how to set up vref_config_t parameters and + * how to call the VREF_Init function by passing in these parameters. + * This is an example. + * @code + * vref_config_t vrefConfig; + * vrefConfig.bufferMode = kVREF_ModeHighPowerBuffer; + * vrefConfig.enableExternalVoltRef = false; + * vrefConfig.enableLowRef = false; + * VREF_Init(VREF, &vrefConfig); + * @endcode + * + * @param base VREF peripheral address. + * @param config Pointer to the configuration structure. + */ +void VREF_Init(VREF_Type *base, const vref_config_t *config); + +/*! + * @brief Stops and disables the clock for the VREF module. + * + * This function should be called to shut down the module. + * This is an example. + * @code + * vref_config_t vrefUserConfig; + * VREF_Init(VREF); + * VREF_GetDefaultConfig(&vrefUserConfig); + * ... + * VREF_Deinit(VREF); + * @endcode + * + * @param base VREF peripheral address. + */ +void VREF_Deinit(VREF_Type *base); + +/*! + * @brief Initializes the VREF configuration structure. + * + * This function initializes the VREF configuration structure to default values. + * This is an example. + * @code + * vrefConfig->bufferMode = kVREF_ModeHighPowerBuffer; + * vrefConfig->enableExternalVoltRef = false; + * vrefConfig->enableLowRef = false; + * @endcode + * + * @param config Pointer to the initialization structure. + */ +void VREF_GetDefaultConfig(vref_config_t *config); + +/*! + * @brief Sets a TRIM value for the reference voltage. + * + * This function sets a TRIM value for the reference voltage. + * Note that the TRIM value maximum is 0x3F. + * + * @param base VREF peripheral address. + * @param trimValue Value of the trim register to set the output reference voltage (maximum 0x3F (6-bit)). + */ +void VREF_SetTrimVal(VREF_Type *base, uint8_t trimValue); + +/*! + * @brief Reads the value of the TRIM meaning output voltage. + * + * This function gets the TRIM value from the TRM register. + * + * @param base VREF peripheral address. + * @return Six-bit value of trim setting. + */ +static inline uint8_t VREF_GetTrimVal(VREF_Type *base) +{ + return (base->TRM & VREF_TRM_TRIM_MASK); +} + +#if defined(FSL_FEATURE_VREF_HAS_TRM4) && FSL_FEATURE_VREF_HAS_TRM4 +/*! + * @brief Sets a TRIM value for the reference voltage (2V1). + * + * This function sets a TRIM value for the reference voltage (2V1). + * Note that the TRIM value maximum is 0x3F. + * + * @param base VREF peripheral address. + * @param trimValue Value of the trim register to set the output reference voltage (maximum 0x3F (6-bit)). + */ +void VREF_SetTrim2V1Val(VREF_Type *base, uint8_t trimValue); + +/*! + * @brief Reads the value of the TRIM meaning output voltage (2V1). + * + * This function gets the TRIM value from the VREF_TRM4 register. + * + * @param base VREF peripheral address. + * @return Six-bit value of trim setting. + */ +static inline uint8_t VREF_GetTrim2V1Val(VREF_Type *base) +{ + return (base->TRM4 & VREF_TRM4_TRIM2V1_MASK); +} +#endif /* FSL_FEATURE_VREF_HAS_TRM4 */ + +#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE + +/*! + * @brief Sets the TRIM value for the low voltage reference. + * + * This function sets the TRIM value for low reference voltage. + * Note the following. + * - The TRIM value maximum is 0x05U + * - The values 111b and 110b are not valid/allowed. + * + * @param base VREF peripheral address. + * @param trimValue Value of the trim register to set output low reference voltage (maximum 0x05U (3-bit)). + */ +void VREF_SetLowReferenceTrimVal(VREF_Type *base, uint8_t trimValue); + +/*! + * @brief Reads the value of the TRIM meaning output voltage. + * + * This function gets the TRIM value from the VREFL_TRM register. + * + * @param base VREF peripheral address. + * @return Three-bit value of the trim setting. + */ +static inline uint8_t VREF_GetLowReferenceTrimVal(VREF_Type *base) +{ + return (base->VREFL_TRM & VREF_VREFL_TRM_VREFL_TRIM_MASK); +} +#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ + +/*@}*/ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/*! @}*/ + +#endif /* _FSL_VREF_H_ */ diff --git a/drivers/include/fsl_wdog.h b/drivers/include/fsl_wdog.h new file mode 100644 index 0000000..580adb9 --- /dev/null +++ b/drivers/include/fsl_wdog.h @@ -0,0 +1,433 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _FSL_WDOG_H_ +#define _FSL_WDOG_H_ + +#include "fsl_common.h" + +/*! + * @addtogroup wdog + * @{ + */ + + +/******************************************************************************* + * Definitions + *******************************************************************************/ + +/*! @name Driver version */ +/*@{*/ +/*! @brief Defines WDOG driver version 2.0.0. */ +#define FSL_WDOG_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/*! @name Unlock sequence */ +/*@{*/ +#define WDOG_FIRST_WORD_OF_UNLOCK (0xC520U) /*!< First word of unlock sequence */ +#define WDOG_SECOND_WORD_OF_UNLOCK (0xD928U) /*!< Second word of unlock sequence */ +/*@}*/ + +/*! @name Refresh sequence */ +/*@{*/ +#define WDOG_FIRST_WORD_OF_REFRESH (0xA602U) /*!< First word of refresh sequence */ +#define WDOG_SECOND_WORD_OF_REFRESH (0xB480U) /*!< Second word of refresh sequence */ +/*@}*/ + +/*! @brief Describes WDOG clock source. */ +typedef enum _wdog_clock_source +{ + kWDOG_LpoClockSource = 0U, /*!< WDOG clock sourced from LPO*/ + kWDOG_AlternateClockSource = 1U, /*!< WDOG clock sourced from alternate clock source*/ +} wdog_clock_source_t; + +/*! @brief Defines WDOG work mode. */ +typedef struct _wdog_work_mode +{ +#if defined(FSL_FEATURE_WDOG_HAS_WAITEN) && FSL_FEATURE_WDOG_HAS_WAITEN + bool enableWait; /*!< Enables or disables WDOG in wait mode */ +#endif /* FSL_FEATURE_WDOG_HAS_WAITEN */ + bool enableStop; /*!< Enables or disables WDOG in stop mode */ + bool enableDebug; /*!< Enables or disables WDOG in debug mode */ +} wdog_work_mode_t; + +/*! @brief Describes the selection of the clock prescaler. */ +typedef enum _wdog_clock_prescaler +{ + kWDOG_ClockPrescalerDivide1 = 0x0U, /*!< Divided by 1 */ + kWDOG_ClockPrescalerDivide2 = 0x1U, /*!< Divided by 2 */ + kWDOG_ClockPrescalerDivide3 = 0x2U, /*!< Divided by 3 */ + kWDOG_ClockPrescalerDivide4 = 0x3U, /*!< Divided by 4 */ + kWDOG_ClockPrescalerDivide5 = 0x4U, /*!< Divided by 5 */ + kWDOG_ClockPrescalerDivide6 = 0x5U, /*!< Divided by 6 */ + kWDOG_ClockPrescalerDivide7 = 0x6U, /*!< Divided by 7 */ + kWDOG_ClockPrescalerDivide8 = 0x7U, /*!< Divided by 8 */ +} wdog_clock_prescaler_t; + +/*! @brief Describes WDOG configuration structure. */ +typedef struct _wdog_config +{ + bool enableWdog; /*!< Enables or disables WDOG */ + wdog_clock_source_t clockSource; /*!< Clock source select */ + wdog_clock_prescaler_t prescaler; /*!< Clock prescaler value */ + wdog_work_mode_t workMode; /*!< Configures WDOG work mode in debug stop and wait mode */ + bool enableUpdate; /*!< Update write-once register enable */ + bool enableInterrupt; /*!< Enables or disables WDOG interrupt */ + bool enableWindowMode; /*!< Enables or disables WDOG window mode */ + uint32_t windowValue; /*!< Window value */ + uint32_t timeoutValue; /*!< Timeout value */ +} wdog_config_t; + +/*! @brief Describes WDOG test mode. */ +typedef enum _wdog_test_mode +{ + kWDOG_QuickTest = 0U, /*!< Selects quick test */ + kWDOG_ByteTest = 1U, /*!< Selects byte test */ +} wdog_test_mode_t; + +/*! @brief Describes WDOG tested byte selection in byte test mode. */ +typedef enum _wdog_tested_byte +{ + kWDOG_TestByte0 = 0U, /*!< Byte 0 selected in byte test mode */ + kWDOG_TestByte1 = 1U, /*!< Byte 1 selected in byte test mode */ + kWDOG_TestByte2 = 2U, /*!< Byte 2 selected in byte test mode */ + kWDOG_TestByte3 = 3U, /*!< Byte 3 selected in byte test mode */ +} wdog_tested_byte_t; + +/*! @brief Describes WDOG test mode configuration structure. */ +typedef struct _wdog_test_config +{ + wdog_test_mode_t testMode; /*!< Selects test mode */ + wdog_tested_byte_t testedByte; /*!< Selects tested byte in byte test mode */ + uint32_t timeoutValue; /*!< Timeout value */ +} wdog_test_config_t; + +/*! + * @brief WDOG interrupt configuration structure, default settings all disabled. + * + * This structure contains the settings for all of the WDOG interrupt configurations. + */ +enum _wdog_interrupt_enable_t +{ + kWDOG_InterruptEnable = WDOG_STCTRLH_IRQRSTEN_MASK, /*!< WDOG timeout generates an interrupt before reset*/ +}; + +/*! + * @brief WDOG status flags. + * + * This structure contains the WDOG status flags for use in the WDOG functions. + */ +enum _wdog_status_flags_t +{ + kWDOG_RunningFlag = WDOG_STCTRLH_WDOGEN_MASK, /*!< Running flag, set when WDOG is enabled*/ + kWDOG_TimeoutFlag = WDOG_STCTRLL_INTFLG_MASK, /*!< Interrupt flag, set when an exception occurs*/ +}; + +/******************************************************************************* + * API + *******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*! + * @name WDOG Initialization and De-initialization + * @{ + */ + +/*! + * @brief Initializes the WDOG configuration sturcture. + * + * This function initializes the WDOG configuration structure to default values. The default + * values are as follows. + * @code + * wdogConfig->enableWdog = true; + * wdogConfig->clockSource = kWDOG_LpoClockSource; + * wdogConfig->prescaler = kWDOG_ClockPrescalerDivide1; + * wdogConfig->workMode.enableWait = true; + * wdogConfig->workMode.enableStop = false; + * wdogConfig->workMode.enableDebug = false; + * wdogConfig->enableUpdate = true; + * wdogConfig->enableInterrupt = false; + * wdogConfig->enableWindowMode = false; + * wdogConfig->windowValue = 0; + * wdogConfig->timeoutValue = 0xFFFFU; + * @endcode + * + * @param config Pointer to the WDOG configuration structure. + * @see wdog_config_t + */ +void WDOG_GetDefaultConfig(wdog_config_t *config); + +/*! + * @brief Initializes the WDOG. + * + * This function initializes the WDOG. When called, the WDOG runs according to the configuration. + * To reconfigure WDOG without forcing a reset first, enableUpdate must be set to true + * in the configuration. + * + * This is an example. + * @code + * wdog_config_t config; + * WDOG_GetDefaultConfig(&config); + * config.timeoutValue = 0x7ffU; + * config.enableUpdate = true; + * WDOG_Init(wdog_base,&config); + * @endcode + * + * @param base WDOG peripheral base address + * @param config The configuration of WDOG + */ +void WDOG_Init(WDOG_Type *base, const wdog_config_t *config); + +/*! + * @brief Shuts down the WDOG. + * + * This function shuts down the WDOG. + * Ensure that the WDOG_STCTRLH.ALLOWUPDATE is 1 which indicates that the register update is enabled. + */ +void WDOG_Deinit(WDOG_Type *base); + +/*! + * @brief Configures the WDOG functional test. + * + * This function is used to configure the WDOG functional test. When called, the WDOG goes into test mode + * and runs according to the configuration. + * Ensure that the WDOG_STCTRLH.ALLOWUPDATE is 1 which means that the register update is enabled. + * + * This is an example. + * @code + * wdog_test_config_t test_config; + * test_config.testMode = kWDOG_QuickTest; + * test_config.timeoutValue = 0xfffffu; + * WDOG_SetTestModeConfig(wdog_base, &test_config); + * @endcode + * @param base WDOG peripheral base address + * @param config The functional test configuration of WDOG + */ +void WDOG_SetTestModeConfig(WDOG_Type *base, wdog_test_config_t *config); + +/* @} */ + +/*! + * @name WDOG Functional Operation + * @{ + */ + +/*! + * @brief Enables the WDOG module. + * + * This function write value into WDOG_STCTRLH register to enable the WDOG, it is a write-once register, + * make sure that the WCT window is still open and this register has not been written in this WCT + * while this function is called. + * + * @param base WDOG peripheral base address + */ +static inline void WDOG_Enable(WDOG_Type *base) +{ + base->STCTRLH |= WDOG_STCTRLH_WDOGEN_MASK; +} + +/*! + * @brief Disables the WDOG module. + * + * This function writes a value into the WDOG_STCTRLH register to disable the WDOG. It is a write-once register. + * Ensure that the WCT window is still open and that register has not been written to in this WCT + * while the function is called. + * + * @param base WDOG peripheral base address + */ +static inline void WDOG_Disable(WDOG_Type *base) +{ + base->STCTRLH &= ~WDOG_STCTRLH_WDOGEN_MASK; +} + +/*! + * @brief Enables the WDOG interrupt. + * + * This function writes a value into the WDOG_STCTRLH register to enable the WDOG interrupt. It is a write-once register. + * Ensure that the WCT window is still open and the register has not been written to in this WCT + * while the function is called. + * + * @param base WDOG peripheral base address + * @param mask The interrupts to enable + * The parameter can be combination of the following source if defined. + * @arg kWDOG_InterruptEnable + */ +static inline void WDOG_EnableInterrupts(WDOG_Type *base, uint32_t mask) +{ + base->STCTRLH |= mask; +} + +/*! + * @brief Disables the WDOG interrupt. + * + * This function writes a value into the WDOG_STCTRLH register to disable the WDOG interrupt. It is a write-once register. + * Ensure that the WCT window is still open and the register has not been written to in this WCT + * while the function is called. + * + * @param base WDOG peripheral base address + * @param mask The interrupts to disable + * The parameter can be combination of the following source if defined. + * @arg kWDOG_InterruptEnable + */ +static inline void WDOG_DisableInterrupts(WDOG_Type *base, uint32_t mask) +{ + base->STCTRLH &= ~mask; +} + +/*! + * @brief Gets the WDOG all status flags. + * + * This function gets all status flags. + * + * This is an example for getting the Running Flag. + * @code + * uint32_t status; + * status = WDOG_GetStatusFlags (wdog_base) & kWDOG_RunningFlag; + * @endcode + * @param base WDOG peripheral base address + * @return State of the status flag: asserted (true) or not-asserted (false).@see _wdog_status_flags_t + * - true: a related status flag has been set. + * - false: a related status flag is not set. + */ +uint32_t WDOG_GetStatusFlags(WDOG_Type *base); + +/*! + * @brief Clears the WDOG flag. + * + * This function clears the WDOG status flag. + * + * This is an example for clearing the timeout (interrupt) flag. + * @code + * WDOG_ClearStatusFlags(wdog_base,kWDOG_TimeoutFlag); + * @endcode + * @param base WDOG peripheral base address + * @param mask The status flags to clear. + * The parameter could be any combination of the following values. + * kWDOG_TimeoutFlag + */ +void WDOG_ClearStatusFlags(WDOG_Type *base, uint32_t mask); + +/*! + * @brief Sets the WDOG timeout value. + * + * This function sets the timeout value. + * It should be ensured that the time-out value for the WDOG is always greater than + * 2xWCT time + 20 bus clock cycles. + * This function writes a value into WDOG_TOVALH and WDOG_TOVALL registers which are wirte-once. + * Ensure the WCT window is still open and the two registers have not been written to in this WCT + * while the function is called. + * + * @param base WDOG peripheral base address + * @param timeoutCount WDOG timeout value; count of WDOG clock tick. + */ +static inline void WDOG_SetTimeoutValue(WDOG_Type *base, uint32_t timeoutCount) +{ + base->TOVALH = (uint16_t)((timeoutCount >> 16U) & 0xFFFFU); + base->TOVALL = (uint16_t)((timeoutCount)&0xFFFFU); +} + +/*! + * @brief Sets the WDOG window value. + * + * This function sets the WDOG window value. + * This function writes a value into WDOG_WINH and WDOG_WINL registers which are wirte-once. + * Ensure the WCT window is still open and the two registers have not been written to in this WCT + * while the function is called. + * + * @param base WDOG peripheral base address + * @param windowValue WDOG window value. + */ +static inline void WDOG_SetWindowValue(WDOG_Type *base, uint32_t windowValue) +{ + base->WINH = (uint16_t)((windowValue >> 16U) & 0xFFFFU); + base->WINL = (uint16_t)((windowValue)&0xFFFFU); +} + +/*! + * @brief Unlocks the WDOG register written. + * + * This function unlocks the WDOG register written. + * Before starting the unlock sequence and following congfiguration, disable the global interrupts. + * Otherwise, an interrupt may invalidate the unlocking sequence and the WCT may expire. + * After the configuration finishes, re-enable the global interrupts. + * + * @param base WDOG peripheral base address + */ +static inline void WDOG_Unlock(WDOG_Type *base) +{ + base->UNLOCK = WDOG_FIRST_WORD_OF_UNLOCK; + base->UNLOCK = WDOG_SECOND_WORD_OF_UNLOCK; +} + +/*! + * @brief Refreshes the WDOG timer. + * + * This function feeds the WDOG. + * This function should be called before the WDOG timer is in timeout. Otherwise, a reset is asserted. + * + * @param base WDOG peripheral base address + */ +void WDOG_Refresh(WDOG_Type *base); + +/*! + * @brief Gets the WDOG reset count. + * + * This function gets the WDOG reset count value. + * + * @param base WDOG peripheral base address + * @return WDOG reset count value. + */ +static inline uint16_t WDOG_GetResetCount(WDOG_Type *base) +{ + return base->RSTCNT; +} +/*! + * @brief Clears the WDOG reset count. + * + * This function clears the WDOG reset count value. + * + * @param base WDOG peripheral base address + */ +static inline void WDOG_ClearResetCount(WDOG_Type *base) +{ + base->RSTCNT |= UINT16_MAX; +} + +/*@}*/ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/*! @}*/ + +#endif /* _FSL_WDOG_H_ */ -- cgit v1.2.3