Added the porting for i.MX RT1010 and i.MX RT1050

Signed-off-by: Howard Liu <howardliu7874@hotmail.com>
This commit is contained in:
Howard Liu
2020-01-15 14:58:06 +08:00
parent 88bfbe999a
commit 6f8edaa5c5
1572 changed files with 1491417 additions and 0 deletions

View File

@@ -0,0 +1,245 @@
/*
* Copyright 2017-2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_codec_common.h"
#include "fsl_codec_adapter.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief codec play and record capability */
#define GET_PLAY_CHANNEL_CAPABILITY(capability) (capability & 0xFFU)
#define GET_PLAY_SOURCE_CAPABILITY(capability) (capability >> 8U)
#define GET_RECORD_SOURCE_CAPABILITY(capability) (capability & 0x3FU)
#define GET_RECORD_CHANNEL_CAPABILITY(capability) (capability >> 6U)
/*******************************************************************************
* Variables
******************************************************************************/
/*******************************************************************************
* Code
******************************************************************************/
/*!
* brief Codec initilization.
*
* param handle codec handle.
* param config codec configuration.
* return kStatus_Success is success, else initial failed.
*/
status_t CODEC_Init(codec_handle_t *handle, codec_config_t *config)
{
assert((config != NULL) && (handle != NULL));
/* Set the handle information */
handle->codecConfig = config;
return HAL_CODEC_Init(handle, config);
}
/*!
* brief Codec de-initilization.
*
* param handle codec handle.
* return kStatus_Success is success, else de-initial failed.
*/
status_t CODEC_Deinit(codec_handle_t *handle)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
return HAL_CODEC_Deinit(handle);
}
/*!
* brief set audio data format.
*
* param handle codec handle.
* param mclk master clock frequency in HZ.
* param sampleRate sample rate in HZ.
* param bitWidth bit width.
* return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetFormat(codec_handle_t *handle, uint32_t mclk, uint32_t sampleRate, uint32_t bitWidth)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
return HAL_CODEC_SetFormat(handle, mclk, sampleRate, bitWidth);
}
/*!
* brief codec module control.
*
* This function is used for codec module control, support switch digital interface cmd, can be expand to support codec
* module specific feature
*
* param handle codec handle.
* param cmd module control cmd, reference _codec_module_ctrl_cmd.
* param data value to write, when cmd is kCODEC_ModuleRecordSourceChannel, the data should be a value combine
* of channel and source, please reference macro CODEC_MODULE_RECORD_SOURCE_CHANNEL(source, LP, LN, RP, RN), reference
* codec specific driver for detail configurations.
* return kStatus_Success is success, else configure failed.
*/
status_t CODEC_ModuleControl(codec_handle_t *handle, codec_module_ctrl_cmd_t cmd, uint32_t data)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
assert(handle->codecCapability != NULL);
switch (cmd)
{
case kCODEC_ModuleSwitchI2SInInterface:
if ((handle->codecCapability->codecModuleCapability & kCODEC_SupportModuleI2SInSwitchInterface) == 0U)
{
return kStatus_CODEC_NotSupport;
}
break;
default:
return kStatus_CODEC_NotSupport;
}
return HAL_CODEC_ModuleControl(handle, cmd, data);
}
/*!
* brief set audio codec module volume.
*
* param handle codec handle.
* param channel audio codec play channel, can be a value or combine value of _codec_play_channel.
* param volume volume value, support 0 ~ 100, 0 is mute, 100 is the maximum volume value.
* return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetVolume(codec_handle_t *handle, uint32_t playChannel, uint32_t volume)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
assert(volume <= CODEC_VOLUME_MAX_VALUE);
assert(handle->codecCapability != NULL);
/* check capability of set volume */
if ((GET_PLAY_CHANNEL_CAPABILITY(handle->codecCapability->codecPlayCapability) & playChannel) == 0U)
{
return kStatus_CODEC_NotSupport;
}
return HAL_CODEC_SetVolume(handle, playChannel, volume);
}
/*!
* brief set audio codec module mute.
*
* param handle codec handle.
* param channel audio codec play channel, can be a value or combine value of _codec_play_channel.
* param mute true is mute, false is unmute.
* return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetMute(codec_handle_t *handle, uint32_t playChannel, bool mute)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
assert(handle->codecCapability != NULL);
/* check capability of mute */
if ((GET_PLAY_CHANNEL_CAPABILITY(handle->codecCapability->codecPlayCapability) & playChannel) == 0U)
{
return kStatus_CODEC_NotSupport;
}
return HAL_CODEC_SetMute(handle, playChannel, mute);
}
/*!
* brief set audio codec module power.
*
* param handle codec handle.
* param module audio codec module.
* param powerOn true is power on, false is power down.
* return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetPower(codec_handle_t *handle, codec_module_t module, bool powerOn)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
assert(handle->codecCapability != NULL);
/* check capability of power switch */
if ((handle->codecCapability->codecModuleCapability & (1U << module)) == 0U)
{
return kStatus_CODEC_NotSupport;
}
return HAL_CODEC_SetPower(handle, module, powerOn);
}
/*!
* brief codec set record source.
*
* param handle codec handle.
* param source audio codec record source, can be a value or combine value of _codec_record_source.
*
* return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetRecord(codec_handle_t *handle, uint32_t recordSource)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
assert(handle->codecCapability != NULL);
/* check capability of record capability */
if ((GET_RECORD_SOURCE_CAPABILITY(handle->codecCapability->codecRecordCapability) & recordSource) == 0U)
{
return kStatus_CODEC_NotSupport;
}
return HAL_CODEC_SetRecord(handle, recordSource);
}
/*!
* brief codec set record channel.
*
* param handle codec handle.
* param leftRecordChannel audio codec record channel, reference _codec_record_channel, can be a value or combine value
of member in _codec_record_channel.
* param rightRecordChannel audio codec record channel, reference _codec_record_channel, can be a value combine of
member in _codec_record_channel.
* return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetRecordChannel(codec_handle_t *handle, uint32_t leftRecordChannel, uint32_t rightRecordChannel)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
assert(handle->codecCapability != NULL);
/* check capability of record capability */
if ((GET_RECORD_CHANNEL_CAPABILITY(handle->codecCapability->codecRecordCapability) & leftRecordChannel) == 0U)
{
return kStatus_CODEC_NotSupport;
}
if ((GET_RECORD_CHANNEL_CAPABILITY(handle->codecCapability->codecRecordCapability) & rightRecordChannel) == 0U)
{
return kStatus_CODEC_NotSupport;
}
return HAL_CODEC_SetRecordChannel(handle, leftRecordChannel, rightRecordChannel);
}
/*!
* brief codec set play source.
*
* param handle codec handle.
* param playSource audio codec play source, can be a value or combine value of _codec_play_source.
*
* return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetPlay(codec_handle_t *handle, uint32_t playSource)
{
assert((handle != NULL) && (handle->codecConfig != NULL));
assert(handle->codecCapability != NULL);
/* check capability of record capability */
if ((GET_PLAY_SOURCE_CAPABILITY(handle->codecCapability->codecPlayCapability) & playSource) == 0U)
{
return kStatus_CODEC_NotSupport;
}
return HAL_CODEC_SetPlay(handle, playSource);
}

View File

@@ -0,0 +1,363 @@
/*
* Copyright 2017- 2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _FSL_CODEC_COMMON_H_
#define _FSL_CODEC_COMMON_H_
#include "fsl_common.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @name Driver version */
/*@{*/
/*! @brief CLOCK driver version 2.1.1. */
#define FSL_CODEC_DRIVER_VERSION (MAKE_VERSION(2, 1, 1))
/*@}*/
/*! @brief CODEC handle buffer size */
#ifndef CODEC_HANDLE_SIZE
#define CODEC_HANDLE_SIZE (128U)
#endif
/*! @brief codec maximum volume range */
#define CODEC_VOLUME_MAX_VALUE (100U)
/*! @brief CODEC status */
enum _codec_status
{
kStatus_CODEC_NotSupport = MAKE_STATUS(kStatusGroup_CODEC, 0U), /*!< CODEC not support status */
kStatus_CODEC_DeviceNotRegistered = MAKE_STATUS(kStatusGroup_CODEC, 1U), /*!< CODEC device register failed status */
kStatus_CODEC_I2CBusInitialFailed =
MAKE_STATUS(kStatusGroup_CODEC, 2U), /*!< CODEC i2c bus initialization failed status */
kStatus_CODEC_I2CCommandTransferFailed =
MAKE_STATUS(kStatusGroup_CODEC, 3U), /*!< CODEC i2c bus command transfer failed status */
};
/*! @brief AUDIO format definition. */
typedef enum _codec_audio_protocol
{
kCODEC_BusI2S = 0U, /*!< I2S type */
kCODEC_BusLeftJustified = 1U, /*!< Left justified mode */
kCODEC_BusRightJustified = 2U, /*!< Right justified mode */
kCODEC_BusPCMA = 3U, /*!< DSP/PCM A mode */
kCODEC_BusPCMB = 4U, /*!< DSP/PCM B mode */
kCODEC_BusTDM = 5U, /*!< TDM mode */
} codec_audio_protocol_t;
/*! @brief audio sample rate definition */
enum _codec_audio_sample_rate
{
kCODEC_AudioSampleRate8KHz = 8000U, /*!< Sample rate 8000 Hz */
kCODEC_AudioSampleRate11025Hz = 11025U, /*!< Sample rate 11025 Hz */
kCODEC_AudioSampleRate12KHz = 12000U, /*!< Sample rate 12000 Hz */
kCODEC_AudioSampleRate16KHz = 16000U, /*!< Sample rate 16000 Hz */
kCODEC_AudioSampleRate22050Hz = 22050U, /*!< Sample rate 22050 Hz */
kCODEC_AudioSampleRate24KHz = 24000U, /*!< Sample rate 24000 Hz */
kCODEC_AudioSampleRate32KHz = 32000U, /*!< Sample rate 32000 Hz */
kCODEC_AudioSampleRate44100Hz = 44100U, /*!< Sample rate 44100 Hz */
kCODEC_AudioSampleRate48KHz = 48000U, /*!< Sample rate 48000 Hz */
kCODEC_AudioSampleRate96KHz = 96000U, /*!< Sample rate 96000 Hz */
kCODEC_AudioSampleRate192KHz = 192000U, /*!< Sample rate 192000 Hz */
kCODEC_AudioSampleRate384KHz = 384000U, /*!< Sample rate 384000 Hz */
};
/*! @brief audio bit width */
enum _codec_audio_bit_width
{
kCODEC_AudioBitWidth16bit = 16U, /*!< audio bit width 16 */
kCODEC_AudioBitWidth20bit = 20U, /*!< audio bit width 20 */
kCODEC_AudioBitWidth24bit = 24U, /*!< audio bit width 24 */
kCODEC_AudioBitWidth32bit = 32U, /*!< audio bit width 32 */
};
/*! @brief audio codec module*/
typedef enum _codec_module
{
kCODEC_ModuleADC = 0U, /*!< codec module ADC */
kCODEC_ModuleDAC = 1U, /*!< codec module DAC */
kCODEC_ModulePGA = 2U, /*!< codec module PGA */
kCODEC_ModuleHeadphone = 3U, /*!< codec module headphone */
kCODEC_ModuleSpeaker = 4U, /*!< codec module speaker */
kCODEC_ModuleLinein = 5U, /*!< codec module linein */
kCODEC_ModuleLineout = 6U, /*!< codec module lineout */
kCODEC_ModuleVref = 7U, /*!< codec module VREF */
kCODEC_ModuleMicbias = 8U, /*!< codec module MIC BIAS */
kCODEC_ModuleMic = 9U, /*!< codec module MIC */
kCODEC_ModuleI2SIn = 10U, /*!< codec module I2S in */
kCODEC_ModuleI2SOut = 11U, /*!< codec module I2S out */
kCODEC_ModuleMxier = 12U, /*!< codec module mixer */
} codec_module_t;
/*! @brief audio codec module control cmd */
typedef enum _codec_module_ctrl_cmd
{
kCODEC_ModuleSwitchI2SInInterface = 0U, /*!< module digital interface siwtch. */
} codec_module_ctrl_cmd_t;
/*! @brief audio codec module digital interface */
enum _codec_module_ctrl_i2s_in_interface
{
kCODEC_ModuleI2SInInterfacePCM = 0U, /*!< Pcm interface*/
kCODEC_ModuleI2SInInterfaceDSD = 1U, /*!< DSD interface */
};
/*! @brief audio codec module record source value */
enum _codec_record_source
{
kCODEC_RecordSourceDifferentialLine = 1U, /*!< record source from differential line */
kCODEC_RecordSourceLineInput = 2U, /*!< record source from line input */
kCODEC_RecordSourceDifferentialMic = 4U, /*!< record source from differential mic */
kCODEC_RecordSourceDigitalMic = 8U, /*!< record source from digital microphone */
kCODEC_RecordSourceSingleEndMic = 16U, /*!< record source from single microphone */
};
/*! @brief audio codec record channel */
enum _codec_reocrd_channel
{
kCODEC_RecordChannelLeft1 = 1U, /*!< left record channel 1 */
kCODEC_RecordChannelLeft2 = 2U, /*!< left record channel 2 */
kCODEC_RecordChannelLeft3 = 4U, /*!< left record channel 3 */
kCODEC_RecordChannelRight1 = 1U, /*!< right record channel 1 */
kCODEC_RecordChannelRight2 = 2U, /*!< right record channel 2 */
kCODEC_RecordChannelRight3 = 4U, /*!< right record channel 3 */
kCODEC_RecordChannelDifferentialPositive1 = 1U, /*!< differential positive record channel 1 */
kCODEC_RecordChannelDifferentialPositive2 = 2U, /*!< differential positive record channel 2 */
kCODEC_RecordChannelDifferentialPositive3 = 4U, /*!< differential positive record channel 3 */
kCODEC_RecordChannelDifferentialNegative1 = 8U, /*!< differential negative record channel 1 */
kCODEC_RecordChannelDifferentialNegative2 = 16U, /*!< differential negative record channel 2 */
kCODEC_RecordChannelDifferentialNegative3 = 32U, /*!< differential negative record channel 3 */
};
/*! @brief audio codec module play source value */
enum _codec_play_source
{
kCODEC_PlaySourcePGA = 1U, /*!< play source PGA, bypass ADC */
kCODEC_PlaySourceInput = 2U, /*!< play source Input3 */
kCODEC_PlaySourceDAC = 4U, /*!< play source DAC */
kCODEC_PlaySourceMixerIn = 1U, /*!< play source mixer in */
kCODEC_PlaySourceMixerInLeft = 2U, /*!< play source mixer in left */
kCODEC_PlaySourceMixerInRight = 4U, /*!< play source mixer in right */
kCODEC_PlaySourceAux = 8U, /*!< play source mixer in AUx */
};
/*! @brief codec play channel */
enum _codec_play_channel
{
kCODEC_PlayChannelHeadphoneLeft = 1U, /*!< play channel headphone left */
kCODEC_PlayChannelHeadphoneRight = 2U, /*!< play channel headphone right */
kCODEC_PlayChannelSpeakerLeft = 4U, /*!< play channel speaker left */
kCODEC_PlayChannelSpeakerRight = 8U, /*!< play channel speaker right */
kCODEC_PlayChannelLineOutLeft = 16U, /*!< play channel lineout left */
kCODEC_PlayChannelLineOutRight = 32U, /*!< play channel lineout right */
kCODEC_PlayChannelLeft0 = 1U, /*!< play channel left0 */
kCODEC_PlayChannelRight0 = 2U, /*!< play channel right0 */
kCODEC_PlayChannelLeft1 = 4U, /*!< play channel left1 */
kCODEC_PlayChannelRight1 = 8U, /*!< play channel right1 */
kCODEC_PlayChannelLeft2 = 16U, /*!< play channel left2 */
kCODEC_PlayChannelRight2 = 32U, /*!< play channel right2 */
kCODEC_PlayChannelLeft3 = 64U, /*!< play channel left3 */
kCODEC_PlayChannelRight3 = 128U, /*!< play channel right3 */
};
/*! @brief audio codec capability */
enum _codec_capability_flag
{
kCODEC_SupportModuleADC = 1U << 0U, /*!< codec capability of module ADC */
kCODEC_SupportModuleDAC = 1U << 1U, /*!< codec capability of module DAC */
kCODEC_SupportModulePGA = 1U << 2U, /*!< codec capability of module PGA */
kCODEC_SupportModuleHeadphone = 1U << 3U, /*!< codec capability of module headphone */
kCODEC_SupportModuleSpeaker = 1U << 4U, /*!< codec capability of module speaker */
kCODEC_SupportModuleLinein = 1U << 5U, /*!< codec capability of module linein */
kCODEC_SupportModuleLineout = 1U << 6U, /*!< codec capability of module lineout */
kCODEC_SupportModuleVref = 1U << 7U, /*!< codec capability of module vref */
kCODEC_SupportModuleMicbias = 1U << 8U, /*!< codec capability of module mic bias */
kCODEC_SupportModuleMic = 1U << 9U, /*!< codec capability of module mic bias */
kCODEC_SupportModuleI2SIn = 1U << 10U, /*!< codec capability of module I2S in */
kCODEC_SupportModuleI2SOut = 1U << 11U, /*!< codec capability of module I2S out */
kCODEC_SupportModuleMixer = 1U << 12U, /*!< codec capability of module mixer */
kCODEC_SupportModuleI2SInSwitchInterface = 1U << 13U, /*!< codec capability of module I2S in switch interface */
kCODEC_SupportPlayChannelLeft0 = 1U << 0U, /*!< codec capability of play channel left 0 */
kCODEC_SupportPlayChannelRight0 = 1U << 1U, /*!< codec capability of play channel right 0 */
kCODEC_SupportPlayChannelLeft1 = 1U << 2U, /*!< codec capability of play channel left 1 */
kCODEC_SupportPlayChannelRight1 = 1U << 3U, /*!< codec capability of play channel right 1 */
kCODEC_SupportPlayChannelLeft2 = 1U << 4U, /*!< codec capability of play channel left 2 */
kCODEC_SupportPlayChannelRight2 = 1U << 5U, /*!< codec capability of play channel right 2 */
kCODEC_SupportPlayChannelLeft3 = 1U << 6U, /*!< codec capability of play channel left 3 */
kCODEC_SupportPlayChannelRight3 = 1U << 7U, /*!< codec capability of play channel right 3 */
kCODEC_SupportPlaySourcePGA = 1U << 8U, /*!< codec capability of set playback source PGA */
kCODEC_SupportPlaySourceInput = 1U << 9U, /*!< codec capability of set playback source INPUT */
kCODEC_SupportPlaySourceDAC = 1U << 10U, /*!< codec capability of set playback source DAC */
kCODEC_SupportPlaySourceMixerIn = 1U << 11U, /*!< codec capability of set play source Mixer in */
kCODEC_SupportPlaySourceMixerInLeft = 1U << 12U, /*!< codec capability of set play source Mixer in left */
kCODEC_SupportPlaySourceMixerInRight = 1U << 13U, /*!< codec capability of set play source Mixer in right */
kCODEC_SupportPlaySourceAux = 1U << 14U, /*!< codec capability of set play source aux */
kCODEC_SupportRecordSourceDifferentialLine = 1U << 0U, /*!< codec capability of record source differential line */
kCODEC_SupportRecordSourceLineInput = 1U << 1U, /*!< codec capability of record source line input */
kCODEC_SupportRecordSourceDifferentialMic = 1U << 2U, /*!< codec capability of record source differential mic */
kCODEC_SupportRecordSourceDigitalMic = 1U << 3U, /*!< codec capability of record digital mic */
kCODEC_SupportRecordSourceSingleEndMic = 1U << 4U, /*!< codec capability of single end mic */
kCODEC_SupportRecordChannelLeft1 = 1U << 6U, /*!< left record channel 1 */
kCODEC_SupportRecordChannelLeft2 = 1U << 7U, /*!< left record channel 2 */
kCODEC_SupportRecordChannelLeft3 = 1U << 8U, /*!< left record channel 3 */
kCODEC_SupportRecordChannelRight1 = 1U << 9U, /*!< right record channel 1 */
kCODEC_SupportRecordChannelRight2 = 1U << 10U, /*!< right record channel 2 */
kCODEC_SupportRecordChannelRight3 = 1U << 11U, /*!< right record channel 3 */
};
/*!@brief codec handle declaration */
typedef struct _codec_handle codec_handle_t;
/*! @brief Initialize structure of the codec */
typedef struct _codec_config
{
uint32_t codecDevType; /*!< codec type */
void *codecDevConfig; /*!< Codec device specific configuration */
} codec_config_t;
/*! @brief codec capability */
typedef struct _codec_capability
{
uint32_t codecModuleCapability; /*!< codec module capability */
uint32_t codecPlayCapability; /*!< codec play capability */
uint32_t codecRecordCapability; /*!< codec record capability */
} codec_capability_t;
/*! @brief Codec handle definition.
* * Application should allocate a buffer with CODEC_HANDLE_SIZE for handle definition, such as
* uint8_t codecHandleBuffer[CODEC_HANDLE_SIZE];
* codec_handle_t *codecHandle = codecHandleBuffer;
*/
struct _codec_handle
{
codec_config_t *codecConfig; /*!< codec configuration function pointer */
const codec_capability_t *codecCapability; /*!< codec capability */
uint8_t codecDevHandle[CODEC_HANDLE_SIZE]; /*!< codec device handle */
};
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @brief Codec initilization.
*
* @param handle codec handle.
* @param config codec configurations.
* @return kStatus_Success is success, else de-initial failed.
*/
status_t CODEC_Init(codec_handle_t *handle, codec_config_t *config);
/*!
* @brief Codec de-initilization.
*
* @param handle codec handle.
* @return kStatus_Success is success, else de-initial failed.
*/
status_t CODEC_Deinit(codec_handle_t *handle);
/*!
* @brief set audio data format.
*
* @param handle codec handle.
* @param mclk master clock frequency in HZ.
* @param sampleRate sample rate in HZ.
* @param bitWidth bit width.
* @return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetFormat(codec_handle_t *handle, uint32_t mclk, uint32_t sampleRate, uint32_t bitWidth);
/*!
* @brief codec module control.
*
* This function is used for codec module control, support switch digital interface cmd, can be expand to support codec
* module specific feature.
*
* @param handle codec handle.
* @param cmd module control cmd, reference _codec_module_ctrl_cmd.
* @param data value to write, when cmd is kCODEC_ModuleRecordSourceChannel, the data should be a value combine
* of channel and source, please reference macro CODEC_MODULE_RECORD_SOURCE_CHANNEL(source, LP, LN, RP, RN), reference
* codec specific driver for detail configurations.
* @return kStatus_Success is success, else configure failed.
*/
status_t CODEC_ModuleControl(codec_handle_t *handle, codec_module_ctrl_cmd_t cmd, uint32_t data);
/*!
* @brief set audio codec pl volume.
*
* @param handle codec handle.
* @param channel audio codec play channel, can be a value or combine value of _codec_play_channel.
* @param volume volume value, support 0 ~ 100, 0 is mute, 100 is the maximum volume value.
* @return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetVolume(codec_handle_t *handle, uint32_t channel, uint32_t volume);
/*!
* @brief set audio codec module mute.
*
* @param handle codec handle.
* @param channel audio codec play channel, can be a value or combine value of _codec_play_channel.
* @param mute true is mute, false is unmute.
* @return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetMute(codec_handle_t *handle, uint32_t channel, bool mute);
/*!
* @brief set audio codec power.
*
* @param handle codec handle.
* @param module audio codec module.
* @param powerOn true is power on, false is power down.
* @return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetPower(codec_handle_t *handle, codec_module_t module, bool powerOn);
/*!
* @brief codec set record source.
*
* @param handle codec handle.
* @param source audio codec record source, can be a value or combine value of _codec_record_source.
*
* @return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetRecord(codec_handle_t *handle, uint32_t recordRource);
/*!
* @brief codec set record channel.
*
* @param handle codec handle.
* @param leftRecordChannel audio codec record channel, reference _codec_record_channel, can be a value combine of
member in _codec_record_channel.
* @param rightRecordChannel audio codec record channel, reference _codec_record_channel, can be a value combine of
member in _codec_record_channel.
* @return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetRecordChannel(codec_handle_t *handle, uint32_t leftRecordChannel, uint32_t rightRecordChannel);
/*!
* @brief codec set play source.
*
* @param handle codec handle.
* @param playSource audio codec play source, can be a value or combine value of _codec_play_source.
*
* @return kStatus_Success is success, else configure failed.
*/
status_t CODEC_SetPlay(codec_handle_t *handle, uint32_t playSource);
#if defined(__cplusplus)
}
#endif
#endif /* _FSL_CODEC_COMMON_H_ */

View File

@@ -0,0 +1,113 @@
/*
* Copyright 2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_codec_i2c.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*******************************************************************************
* Variables
******************************************************************************/
/*******************************************************************************
* Code
******************************************************************************/
/*!
* brief Codec i2c bus initilization.
*
* param handle i2c master handle.
* param i2CInstance instance number of the i2c bus, such as 0 is corresponding to I2C0.
* param i2cBaudrate i2c baudrate.
* param i2cSourceClockHz i2c source clock frequency.
* return kStatus_HAL_I2cSuccess is success, else initial failed.
*/
status_t CODEC_I2C_Init(void *handle, uint32_t i2cInstance, uint32_t i2cBaudrate, uint32_t i2cSourceClockHz)
{
hal_i2c_master_config_t masterConfig;
masterConfig.enableMaster = true;
masterConfig.baudRate_Bps = i2cBaudrate;
masterConfig.srcClock_Hz = i2cSourceClockHz;
masterConfig.instance = i2cInstance;
return HAL_I2cMasterInit((hal_i2c_master_handle_t *)handle, &masterConfig);
}
/*!
* brief Codec i2c de-initilization.
*
* param handle i2c master handle.
* return kStatus_HAL_I2cSuccess is success, else deinitial failed.
*/
status_t CODEC_I2C_Deinit(void *handle)
{
return HAL_I2cMasterDeinit((hal_i2c_master_handle_t *)handle);
}
/*!
* brief codec i2c send function.
*
* param handle i2c master handle.
* param deviceAddress codec device address.
* param subAddress register address.
* param subaddressSize register address width.
* param txBuff tx buffer pointer.
* param txBuffSize tx buffer size.
* return kStatus_HAL_I2cSuccess is success, else send failed.
*/
status_t CODEC_I2C_Send(void *handle,
uint8_t deviceAddress,
uint32_t subAddress,
uint8_t subaddressSize,
uint8_t *txBuff,
uint8_t txBuffSize)
{
hal_i2c_master_transfer_t masterXfer;
masterXfer.slaveAddress = deviceAddress;
masterXfer.direction = kHAL_I2cWrite;
masterXfer.subaddress = (uint32_t)subAddress;
masterXfer.subaddressSize = subaddressSize;
masterXfer.data = txBuff;
masterXfer.dataSize = txBuffSize;
masterXfer.flags = kHAL_I2cTransferDefaultFlag;
return HAL_I2cMasterTransferBlocking((hal_i2c_master_handle_t *)handle, &masterXfer);
}
/*!
* brief codec i2c receive function.
*
* param handle i2c master handle.
* param deviceAddress codec device address.
* param subAddress register address.
* param subaddressSize register address width.
* param rxBuff rx buffer pointer.
* param rxBuffSize rx buffer size.
* return kStatus_HAL_I2cSuccess is success, else receive failed.
*/
status_t CODEC_I2C_Receive(void *handle,
uint8_t deviceAddress,
uint32_t subAddress,
uint8_t subaddressSize,
uint8_t *rxBuff,
uint8_t rxBuffSize)
{
hal_i2c_master_transfer_t masterXfer;
masterXfer.slaveAddress = deviceAddress;
masterXfer.direction = kHAL_I2cRead;
masterXfer.subaddress = (uint32_t)subAddress;
masterXfer.subaddressSize = subaddressSize;
masterXfer.data = rxBuff;
masterXfer.dataSize = rxBuffSize;
masterXfer.flags = kHAL_I2cTransferDefaultFlag;
return HAL_I2cMasterTransferBlocking((hal_i2c_master_handle_t *)handle, &masterXfer);
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright 2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _FSL_CODEC_I2C_H_
#define _FSL_CODEC_I2C_H_
#include "fsl_common.h"
#include "i2c.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief codec i2c handler */
#ifndef CODEC_I2C_MASTER_HANDLER_SIZE
#define CODEC_I2C_MASTER_HANDLER_SIZE HAL_I2C_MASTER_HANDLE_SIZE
#endif
/*! @brief CODEC device register address type. */
typedef enum _codec_reg_addr
{
kCODEC_RegAddr8Bit = 1U, /*!< 8-bit register address. */
kCODEC_RegAddr16Bit = 2U, /*!< 16-bit register address. */
} codec_reg_addr_t;
/*! @brief CODEC device register width. */
typedef enum _codec_reg_width
{
kCODEC_RegWidth8Bit = 1U, /*!< 8-bit register width. */
kCODEC_RegWidth16Bit = 2U, /*!< 16-bit register width. */
kCODEC_RegWidth32Bit = 4U, /*!< 32-bit register width. */
} codec_reg_width_t;
/*! @brief CODEC I2C configurations structure */
typedef struct _codec_i2c_config
{
uint32_t codecI2CInstance; /*!< i2c bus instance */
uint32_t codecI2CSourceClock; /*!< i2c bus source clock frequency */
} codec_i2c_config_t;
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @brief Codec i2c bus initilization.
*
* @param handle i2c master handle.
* @param i2CInstance instance number of the i2c bus, such as 0 is corresponding to I2C0.
* @param i2cBaudrate i2c baudrate.
* @param i2cSourceClockHz i2c source clock frequency.
* @return kStatus_HAL_I2cSuccess is success, else initial failed.
*/
status_t CODEC_I2C_Init(void *handle, uint32_t i2cInstance, uint32_t i2cBaudrate, uint32_t i2cSourceClockHz);
/*!
* @brief Codec i2c de-initilization.
*
* @param handle i2c master handle.
* @return kStatus_HAL_I2cSuccess is success, else deinitial failed.
*/
status_t CODEC_I2C_Deinit(void *handle);
/*!
* @brief codec i2c send function.
*
* @param handle i2c master handle.
* @param deviceAddress codec device address.
* @param subAddress register address.
* @param subaddressSize register address width.
* @param txBuff tx buffer pointer.
* @param txBuffSize tx buffer size.
* @return kStatus_HAL_I2cSuccess is success, else send failed.
*/
status_t CODEC_I2C_Send(void *handle,
uint8_t deviceAddress,
uint32_t subAddress,
uint8_t subaddressSize,
uint8_t *txBuff,
uint8_t txBuffSize);
/*!
* @brief codec i2c receive function.
*
* @param handle i2c master handle.
* @param deviceAddress codec device address.
* @param subAddress register address.
* @param subaddressSize register address width.
* @param rxBuff rx buffer pointer.
* @param rxBuffSize rx buffer size.
* @return kStatus_HAL_I2cSuccess is success, else receive failed.
*/
status_t CODEC_I2C_Receive(void *handle,
uint8_t deviceAddress,
uint32_t subAddress,
uint8_t subaddressSize,
uint8_t *rxBuff,
uint8_t rxBuffSize);
#if defined(__cplusplus)
}
#endif
#endif /* _FSL_CODEC_I2C_H_ */

View File

@@ -0,0 +1,145 @@
/*
* Copyright 2017- 2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _FSL_CODEC_ADAPTER_H_
#define _FSL_CODEC_ADAPTER_H_
#include "fsl_codec_common.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief codec type */
enum _codec_type
{
kCODEC_WM8904, /*!< wm8904 */
kCODEC_WM8960, /*!< wm8960 */
kCODEC_WM8524, /*!< wm8524 */
kCODEC_SGTL5000, /*!< sgtl5000 */
kCODEC_DA7212, /*!< da7212 */
kCODEC_CS42888, /*!< CS42888 */
kCODEC_AK4497, /*!< AK4497 */
kCODEC_AK4458, /*!< ak4458 */
};
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @brief Codec initilization.
*
* @param handle codec handle.
* @param config codec configuration.
* @return kStatus_Success is success, else initial failed.
*/
status_t HAL_CODEC_Init(codec_handle_t *handle, void *config);
/*!
* @brief Codec de-initilization.
*
* @param handle codec handle.
* @return kStatus_Success is success, else de-initial failed.
*/
status_t HAL_CODEC_Deinit(codec_handle_t *handle);
/*!
* @brief set audio data format.
*
* @param handle codec handle.
* @param mclk master clock frequency in HZ.
* @param sampleRate sample rate in HZ.
* @param bitWidth bit width.
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetFormat(codec_handle_t *handle, uint32_t mclk, uint32_t sampleRate, uint32_t bitWidth);
/*!
* @brief set audio codec module volume.
*
* @param handle codec handle.
* @param channel audio codec play channel, can be a value or combine value of _codec_play_channel.
* @param volume volume value, support 0 ~ 100, 0 is mute, 100 is the maximum volume value.
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetVolume(codec_handle_t *handle, uint32_t playChannel, uint32_t volume);
/*!
* @brief set audio codec module mute.
*
* @param handle codec handle.
* @param channel audio codec play channel, can be a value or combine value of _codec_play_channel.
* @param isMute true is mute, false is unmute.
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetMute(codec_handle_t *handle, uint32_t playChannel, bool isMute);
/*!
* @brief set audio codec module power.
*
* @param handle codec handle.
* @param module audio codec module.
* @param powerOn true is power on, false is power down.
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetPower(codec_handle_t *handle, codec_module_t module, bool powerOn);
/*!
* @brief codec set record source.
*
* @param handle codec handle.
* @param source audio codec record source, can be a value or combine value of _codec_record_source.
*
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetRecord(codec_handle_t *handle, uint32_t recordSource);
/*!
* @brief codec set record channel.
*
* @param handle codec handle.
* @param leftRecordChannel audio codec record channel, reference _codec_record_channel, can be a value or combine value
of member in _codec_record_channel.
* @param rightRecordChannel audio codec record channel, reference _codec_record_channel, can be a value combine of
member in _codec_record_channel.
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetRecordChannel(codec_handle_t *handle, uint32_t leftRecordChannel, uint32_t rightRecordChannel);
/*!
* @brief codec set play source.
*
* @param handle codec handle.
* @param playSource audio codec play source, can be a value or combine value of _codec_play_source.
*
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetPlay(codec_handle_t *handle, uint32_t playSource);
/*!
* @brief codec module control.
*
* This function is used for codec module control, support switch digital interface cmd, can be expand to support codec
* module specific feature
*
* @param handle codec handle.
* @param cmd module control cmd, reference _codec_module_ctrl_cmd.
* @param data value to write, when cmd is kCODEC_ModuleRecordSourceChannel, the data should be a value combine
* of channel and source, please reference macro CODEC_MODULE_RECORD_SOURCE_CHANNEL(source, LP, LN, RP, RN), reference
* codec specific driver for detail configurations.
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_ModuleControl(codec_handle_t *handle, codec_module_ctrl_cmd_t cmd, uint32_t data);
#if defined(__cplusplus)
}
#endif
#endif /* _FSL_CODEC_ADAPTER_H_ */

View File

@@ -0,0 +1,253 @@
/*
* Copyright 2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_wm8960.h"
#include "fsl_codec_adapter.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief module capability definition */
#define HAL_WM8960_MODULE_CAPABILITY \
(kCODEC_SupportModuleADC | kCODEC_SupportModuleDAC | kCODEC_SupportModulePGA | kCODEC_SupportModuleHeadphone | \
kCODEC_SupportModuleLineout | kCODEC_SupportModuleSpeaker)
#define HAL_WM8960_PLAY_CAPABILITY \
(kCODEC_SupportPlayChannelLeft0 | kCODEC_SupportPlayChannelRight0 | kCODEC_SupportPlayChannelLeft1 | \
kCODEC_SupportPlayChannelRight1 | kCODEC_SupportPlaySourcePGA | kCODEC_SupportPlaySourceDAC | \
kCODEC_SupportPlaySourceInput)
#define HAL_WM8960_RECORD_CAPABILITY \
(kCODEC_SupportPlayChannelLeft0 | kCODEC_SupportPlayChannelLeft1 | kCODEC_SupportPlayChannelLeft2 | \
kCODEC_SupportPlayChannelRight0 | kCODEC_SupportPlayChannelRight1 | kCODEC_SupportPlayChannelRight2)
/*! @brief wm8960 map protocol */
#define HAL_WM8960_MAP_PROTOCOL(protocol) \
(protocol == kCODEC_BusI2S ? \
kWM8960_BusI2S : \
protocol == kCODEC_BusLeftJustified ? \
kWM8960_BusLeftJustified : \
protocol == kCODEC_BusRightJustified ? \
kWM8960_BusRightJustified : \
protocol == kCODEC_BusPCMA ? kWM8960_BusPCMA : protocol == kCODEC_BusPCMB ? kWM8960_BusPCMB : kWM8960_BusI2S)
/*! @brief wm8960 map module */
#define HAL_WM8960_MAP_MODULE(module) \
(module == kCODEC_ModuleADC ? \
kWM8960_ModuleADC : \
module == kCODEC_ModuleDAC ? \
kWM8960_ModuleDAC : \
module == kCODEC_ModuleVref ? \
kWM8960_ModuleVREF : \
module == kCODEC_ModuleHeadphone ? \
kWM8960_ModuleHP : \
module == kCODEC_ModuleMicbias ? \
kWM8960_ModuleMICB : \
module == kCODEC_ModuleMic ? \
kWM8960_ModuleMIC : \
module == kCODEC_ModuleLinein ? \
kWM8960_ModuleLineIn : \
module == kCODEC_ModuleSpeaker ? \
kWM8960_ModuleSpeaker : \
module == kCODEC_ModuleMxier ? kWM8960_ModuleOMIX : \
module == kCODEC_ModuleLineout ? kWM8960_ModuleLineOut : kWM8960_ModuleADC)
/*******************************************************************************
* Prototypes
******************************************************************************/
/*******************************************************************************
* Variables
******************************************************************************/
static const codec_capability_t s_wm8960_capability = {
.codecPlayCapability = HAL_WM8960_PLAY_CAPABILITY,
.codecModuleCapability = HAL_WM8960_MODULE_CAPABILITY,
.codecRecordCapability = HAL_WM8960_RECORD_CAPABILITY,
};
/*******************************************************************************
* Code
******************************************************************************/
/*!
* brief Codec initilization.
*
* param handle codec handle.
* param config codec configuration.
* return kStatus_Success is success, else initial failed.
*/
status_t HAL_CODEC_Init(codec_handle_t *handle, void *config)
{
assert((config != NULL) && (handle != NULL));
codec_config_t *codecConfig = (codec_config_t *)config;
wm8960_config_t *wm8960Config = (wm8960_config_t *)(codecConfig->codecDevConfig);
wm8960_handle_t *wm8960Handle = (wm8960_handle_t *)((uint32_t)(handle->codecDevHandle));
handle->codecCapability = &s_wm8960_capability;
/* codec device initialization */
return WM8960_Init(wm8960Handle, wm8960Config);
}
/*!
* brief Codec de-initilization.
*
* param handle codec handle.
* return kStatus_Success is success, else de-initial failed.
*/
status_t HAL_CODEC_Deinit(codec_handle_t *handle)
{
assert(handle != NULL);
return WM8960_Deinit((wm8960_handle_t *)((uint32_t)(handle->codecDevHandle)));
}
/*!
* brief set audio data format.
*
* param handle codec handle.
* param mclk master clock frequency in HZ.
* param sampleRate sample rate in HZ.
* param bitWidth bit width.
* return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetFormat(codec_handle_t *handle, uint32_t mclk, uint32_t sampleRate, uint32_t bitWidth)
{
assert(handle != NULL);
return WM8960_ConfigDataFormat((wm8960_handle_t *)((uint32_t)(handle->codecDevHandle)), mclk, sampleRate, bitWidth);
}
/*!
* brief set audio codec module volume.
*
* param handle codec handle.
* param channel audio codec play channel, can be a value or combine value of _codec_play_channel.
* param volume volume value, support 0 ~ 100, 0 is mute, 100 is the maximum volume value.
* return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetVolume(codec_handle_t *handle, uint32_t playChannel, uint32_t volume)
{
assert(handle != NULL);
status_t retVal = kStatus_Success;
if ((playChannel & kWM8960_HeadphoneLeft) || (playChannel & kWM8960_HeadphoneRight))
{
retVal = WM8960_SetVolume((wm8960_handle_t *)((uint32_t)(handle->codecDevHandle)), kWM8960_ModuleHP, volume);
}
if ((playChannel & kWM8960_SpeakerLeft) || (playChannel & kWM8960_SpeakerRight))
{
retVal =
WM8960_SetVolume((wm8960_handle_t *)((uint32_t)(handle->codecDevHandle)), kWM8960_ModuleSpeaker, volume);
}
return retVal;
}
/*!
* brief set audio codec module mute.
*
* param handle codec handle.
* param channel audio codec play channel, can be a value or combine value of _codec_play_channel.
* param isMute true is mute, false is unmute.
* return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetMute(codec_handle_t *handle, uint32_t playChannel, bool isMute)
{
assert(handle != NULL);
status_t retVal = kStatus_Success;
if ((playChannel & kWM8960_HeadphoneLeft) || (playChannel & kWM8960_HeadphoneRight))
{
retVal = WM8960_SetMute((wm8960_handle_t *)((uint32_t)(handle->codecDevHandle)), kWM8960_ModuleHP, isMute);
}
if ((playChannel & kWM8960_SpeakerLeft) || (playChannel & kWM8960_SpeakerRight))
{
retVal = WM8960_SetMute((wm8960_handle_t *)((uint32_t)(handle->codecDevHandle)), kWM8960_ModuleSpeaker, isMute);
}
return retVal;
}
/*!
* brief set audio codec module power.
*
* param handle codec handle.
* param module audio codec module.
* param powerOn true is power on, false is power down.
* return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetPower(codec_handle_t *handle, codec_module_t module, bool powerOn)
{
assert(handle != NULL);
return WM8960_SetModule((wm8960_handle_t *)((uint32_t)(handle->codecDevHandle)), HAL_WM8960_MAP_MODULE(module),
powerOn);
}
/*!
* brief codec set record channel.
*
* param handle codec handle.
* param leftRecordChannel audio codec record channel, reference _codec_record_channel, can be a value or combine value
of member in _codec_record_channel.
* param rightRecordChannel audio codec record channel, reference _codec_record_channel, can be a value combine of
member in _codec_record_channel.
* return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetRecordChannel(codec_handle_t *handle, uint32_t leftRecordChannel, uint32_t rightRecordChannel)
{
return kStatus_CODEC_NotSupport;
}
/*!
* brief codec set record source.
*
* param handle codec handle.
* param source audio codec record source, can be a value or combine value of _codec_record_source.
*
* @return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetRecord(codec_handle_t *handle, uint32_t recordSource)
{
return kStatus_CODEC_NotSupport;
}
/*!
* brief codec set play source.
*
* param handle codec handle.
* param playSource audio codec play source, can be a value or combine value of _codec_play_source.
*
* return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_SetPlay(codec_handle_t *handle, uint32_t playSource)
{
assert(handle != NULL);
return WM8960_SetPlay((wm8960_handle_t *)((uint32_t)(handle->codecDevHandle)), playSource);
}
/*!
* brief codec module control.
*
* param handle codec handle.
* param cmd module control cmd, reference _codec_module_ctrl_cmd.
* param data value to write, when cmd is kCODEC_ModuleRecordSourceChannel, the data should be a value combine
* of channel and source, please reference macro CODEC_MODULE_RECORD_SOURCE_CHANNEL(source, LP, LN, RP, RN), reference
* codec specific driver for detail configurations.
* return kStatus_Success is success, else configure failed.
*/
status_t HAL_CODEC_ModuleControl(codec_handle_t *handle, codec_module_ctrl_cmd_t cmd, uint32_t data)
{
return kStatus_CODEC_NotSupport;
}

View File

@@ -0,0 +1,678 @@
/*
* Copyright (c) 2016, Freescale Semiconductor, Inc.
* Copyright 2016-2019 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_wm8960.h"
/*******************************************************************************
* Definitations
******************************************************************************/
/*******************************************************************************
* Prototypes
******************************************************************************/
/*******************************************************************************
* Variables
******************************************************************************/
/*
* wm8960 register cache
* We can't read the WM8960 register space when we are
* using 2 wire for device control, so we cache them instead.
*/
static const uint16_t wm8960_reg[WM8960_CACHEREGNUM] = {
0x0097, 0x0097, 0x0000, 0x0000, 0x0000, 0x0008, 0x0000, 0x000a, 0x01c0, 0x0000, 0x00ff, 0x00ff, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x007b, 0x0100, 0x0032, 0x0000, 0x00c3, 0x00c3, 0x01c0, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0100, 0x0100, 0x0050, 0x0050, 0x0050, 0x0050, 0x0000, 0x0000, 0x0000, 0x0000,
0x0040, 0x0000, 0x0000, 0x0050, 0x0050, 0x0000, 0x0002, 0x0037, 0x004d, 0x0080, 0x0008, 0x0031, 0x0026, 0x00e9,
};
static uint16_t reg_cache[WM8960_CACHEREGNUM];
/*******************************************************************************
* Code
******************************************************************************/
status_t WM8960_Init(wm8960_handle_t *handle, const wm8960_config_t *wm8960Config)
{
const wm8960_config_t *config = wm8960Config;
handle->config = config;
/* i2c bus initialization */
if (CODEC_I2C_Init(handle->i2cHandle, config->i2cConfig.codecI2CInstance, WM8960_I2C_BAUDRATE,
config->i2cConfig.codecI2CSourceClock) != kStatus_HAL_I2cSuccess)
{
return kStatus_Fail;
}
/* load wm8960 register map */
memcpy(reg_cache, wm8960_reg, sizeof(wm8960_reg));
/* Reset the codec */
WM8960_WriteReg(handle, WM8960_RESET, 0x00);
/*
* VMID=50K, Enable VREF, AINL, AINR, ADCL and ADCR
* I2S_IN (bit 0), I2S_OUT (bit 1), DAP (bit 4), DAC (bit 5), ADC (bit 6) are powered on
*/
WM8960_WriteReg(handle, WM8960_POWER1, 0xFE);
/*
* Enable DACL, DACR, LOUT1, ROUT1, PLL down
*/
WM8960_WriteReg(handle, WM8960_POWER2, 0x1E0);
/*
* Enable left and right channel input PGA, left and right output mixer
*/
WM8960_WriteReg(handle, WM8960_POWER3, 0x3C);
/* ADC and DAC uses same clock */
WM8960_WriteReg(handle, WM8960_IFACE2, 0x40);
/* set data route */
WM8960_SetDataRoute(handle, config->route);
/* set data protocol */
WM8960_SetProtocol(handle, config->bus);
/* set master or slave */
WM8960_SetMasterSlave(handle, config->master_slave);
/* select left input */
WM8960_SetLeftInput(handle, config->leftInputSource);
/* select right input */
WM8960_SetRightInput(handle, config->rightInputSource);
/* speaker power */
if (config->enableSpeaker)
{
WM8960_SetModule(handle, kWM8960_ModuleSpeaker, true);
}
WM8960_WriteReg(handle, WM8960_ADDCTL1, 0x0C0);
WM8960_WriteReg(handle, WM8960_ADDCTL4, 0x40);
WM8960_WriteReg(handle, WM8960_BYPASS1, 0x0);
WM8960_WriteReg(handle, WM8960_BYPASS2, 0x0);
/*
* ADC volume, 0dB
*/
WM8960_WriteReg(handle, WM8960_LADC, 0x1C3);
WM8960_WriteReg(handle, WM8960_RADC, 0x1C3);
/*
* Digital DAC volume, 0dB
*/
WM8960_WriteReg(handle, WM8960_LDAC, 0x1E0);
WM8960_WriteReg(handle, WM8960_RDAC, 0x1E0);
/*
* Headphone volume, LOUT1 and ROUT1, 0dB
*/
WM8960_WriteReg(handle, WM8960_LOUT1, 0x16F);
WM8960_WriteReg(handle, WM8960_ROUT1, 0x16F);
/* Unmute DAC. */
WM8960_WriteReg(handle, WM8960_DACCTL1, 0x0000);
WM8960_WriteReg(handle, WM8960_LINVOL, 0x117);
WM8960_WriteReg(handle, WM8960_RINVOL, 0x117);
return WM8960_ConfigDataFormat(handle, config->format.mclk_HZ, config->format.sampleRate, config->format.bitWidth);
}
status_t WM8960_Deinit(wm8960_handle_t *handle)
{
WM8960_SetModule(handle, kWM8960_ModuleADC, false);
WM8960_SetModule(handle, kWM8960_ModuleDAC, false);
WM8960_SetModule(handle, kWM8960_ModuleVREF, false);
WM8960_SetModule(handle, kWM8960_ModuleLineIn, false);
WM8960_SetModule(handle, kWM8960_ModuleLineOut, false);
WM8960_SetModule(handle, kWM8960_ModuleSpeaker, false);
return CODEC_I2C_Deinit(handle->i2cHandle);
}
void WM8960_SetMasterSlave(wm8960_handle_t *handle, bool master)
{
if (master == 1)
{
WM8960_ModifyReg(handle, WM8960_IFACE1, WM8960_IFACE1_MS_MASK, WM8960_IFACE1_MS(WM8960_IFACE1_MASTER));
}
else
{
WM8960_ModifyReg(handle, WM8960_IFACE1, WM8960_IFACE1_MS_MASK, WM8960_IFACE1_MS(WM8960_IFACE1_SLAVE));
}
}
status_t WM8960_SetModule(wm8960_handle_t *handle, wm8960_module_t module, bool isEnabled)
{
status_t ret = kStatus_Success;
switch (module)
{
case kWM8960_ModuleADC:
WM8960_ModifyReg(handle, WM8960_POWER1, WM8960_POWER1_ADCL_MASK,
((uint16_t)isEnabled << WM8960_POWER1_ADCL_SHIFT));
WM8960_ModifyReg(handle, WM8960_POWER1, WM8960_POWER1_ADCR_MASK,
((uint16_t)isEnabled << WM8960_POWER1_ADCR_SHIFT));
break;
case kWM8960_ModuleDAC:
WM8960_ModifyReg(handle, WM8960_POWER2, WM8960_POWER2_DACL_MASK,
((uint16_t)isEnabled << WM8960_POWER2_DACL_SHIFT));
WM8960_ModifyReg(handle, WM8960_POWER2, WM8960_POWER2_DACR_MASK,
((uint16_t)isEnabled << WM8960_POWER2_DACR_SHIFT));
break;
case kWM8960_ModuleVREF:
WM8960_ModifyReg(handle, WM8960_POWER1, WM8960_POWER1_VREF_MASK,
((uint16_t)isEnabled << WM8960_POWER1_VREF_SHIFT));
break;
case kWM8960_ModuleLineIn:
WM8960_ModifyReg(handle, WM8960_POWER1, WM8960_POWER1_AINL_MASK,
((uint16_t)isEnabled << WM8960_POWER1_AINL_SHIFT));
WM8960_ModifyReg(handle, WM8960_POWER1, WM8960_POWER1_AINR_MASK,
((uint16_t)isEnabled << WM8960_POWER1_AINR_SHIFT));
WM8960_ModifyReg(handle, WM8960_POWER3, WM8960_POWER3_LMIC_MASK,
((uint16_t)isEnabled << WM8960_POWER3_LMIC_SHIFT));
WM8960_ModifyReg(handle, WM8960_POWER3, WM8960_POWER3_RMIC_MASK,
((uint16_t)isEnabled << WM8960_POWER3_RMIC_SHIFT));
break;
case kWM8960_ModuleLineOut:
WM8960_ModifyReg(handle, WM8960_POWER2, WM8960_POWER2_LOUT1_MASK,
((uint16_t)isEnabled << WM8960_POWER2_LOUT1_SHIFT));
WM8960_ModifyReg(handle, WM8960_POWER2, WM8960_POWER2_ROUT1_MASK,
((uint16_t)isEnabled << WM8960_POWER2_ROUT1_SHIFT));
break;
case kWM8960_ModuleMICB:
WM8960_ModifyReg(handle, WM8960_POWER1, WM8960_POWER1_MICB_MASK,
((uint16_t)isEnabled << WM8960_POWER1_MICB_SHIFT));
break;
case kWM8960_ModuleSpeaker:
WM8960_ModifyReg(handle, WM8960_POWER2, WM8960_POWER2_SPKL_MASK,
((uint16_t)isEnabled << WM8960_POWER2_SPKL_SHIFT));
WM8960_ModifyReg(handle, WM8960_POWER2, WM8960_POWER2_SPKR_MASK,
((uint16_t)isEnabled << WM8960_POWER2_SPKR_SHIFT));
WM8960_WriteReg(handle, WM8960_CLASSD1, 0xF7);
break;
case kWM8960_ModuleOMIX:
WM8960_ModifyReg(handle, WM8960_POWER3, WM8960_POWER3_LOMIX_MASK,
((uint16_t)isEnabled << WM8960_POWER3_LOMIX_SHIFT));
WM8960_ModifyReg(handle, WM8960_POWER3, WM8960_POWER3_ROMIX_MASK,
((uint16_t)isEnabled << WM8960_POWER3_ROMIX_SHIFT));
break;
default:
ret = kStatus_InvalidArgument;
break;
}
return ret;
}
status_t WM8960_SetDataRoute(wm8960_handle_t *handle, wm8960_route_t route)
{
status_t ret = kStatus_Success;
switch (route)
{
case kWM8960_RouteBypass:
/* Bypass means from line-in to HP*/
/*
* Left LINPUT3 to left output mixer, LINPUT3 left output mixer volume = 0dB
*/
WM8960_WriteReg(handle, WM8960_LOUTMIX, 0x80);
/*
* Right RINPUT3 to right output mixer, RINPUT3 right output mixer volume = 0dB
*/
WM8960_WriteReg(handle, WM8960_ROUTMIX, 0x80);
break;
case kWM8960_RoutePlayback:
/* Data route I2S_IN-> DAC-> HP */
/*
* Left DAC to left output mixer, LINPUT3 left output mixer volume = 0dB
*/
WM8960_WriteReg(handle, WM8960_LOUTMIX, 0x100);
/*
* Right DAC to right output mixer, RINPUT3 right output mixer volume = 0dB
*/
WM8960_WriteReg(handle, WM8960_ROUTMIX, 0x100);
WM8960_WriteReg(handle, WM8960_POWER3, 0x0C);
/* Set power for DAC */
WM8960_SetModule(handle, kWM8960_ModuleDAC, true);
WM8960_SetModule(handle, kWM8960_ModuleOMIX, true);
WM8960_SetModule(handle, kWM8960_ModuleLineOut, true);
break;
case kWM8960_RoutePlaybackandRecord:
/*
* Left DAC to left output mixer, LINPUT3 left output mixer volume = 0dB
*/
WM8960_WriteReg(handle, WM8960_LOUTMIX, 0x100);
/*
* Right DAC to right output mixer, RINPUT3 right output mixer volume = 0dB
*/
WM8960_WriteReg(handle, WM8960_ROUTMIX, 0x100);
WM8960_WriteReg(handle, WM8960_POWER3, 0x3C);
WM8960_SetModule(handle, kWM8960_ModuleDAC, true);
WM8960_SetModule(handle, kWM8960_ModuleADC, true);
WM8960_SetModule(handle, kWM8960_ModuleLineIn, true);
WM8960_SetModule(handle, kWM8960_ModuleOMIX, true);
WM8960_SetModule(handle, kWM8960_ModuleLineOut, true);
break;
case kWM8960_RouteRecord:
/* LINE_IN->ADC->I2S_OUT */
/*
* Left and right input boost, LIN3BOOST and RIN3BOOST = 0dB
*/
WM8960_WriteReg(handle, WM8960_POWER3, 0x30);
/* Power up ADC and AIN */
WM8960_SetModule(handle, kWM8960_ModuleLineIn, true);
WM8960_SetModule(handle, kWM8960_ModuleADC, true);
break;
default:
ret = kStatus_InvalidArgument;
break;
}
return ret;
}
status_t WM8960_SetLeftInput(wm8960_handle_t *handle, wm8960_input_t input)
{
status_t ret = kStatus_Success;
uint16_t val = 0;
switch (input)
{
case kWM8960_InputSingleEndedMic:
/* Only LMN1 enabled, LMICBOOST to 13db, LMIC2B enabled */
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINL_MASK | WM8960_POWER1_ADCL_MASK | WM8960_POWER1_MICB_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
ret = WM8960_WriteReg(handle, WM8960_LINPATH, 0x138);
ret = WM8960_WriteReg(handle, WM8960_LINVOL, 0x117);
break;
case kWM8960_InputDifferentialMicInput2:
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINL_MASK | WM8960_POWER1_ADCL_MASK | WM8960_POWER1_MICB_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
ret = WM8960_WriteReg(handle, WM8960_LINPATH, 0x178);
ret = WM8960_WriteReg(handle, WM8960_LINVOL, 0x117);
break;
case kWM8960_InputDifferentialMicInput3:
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINL_MASK | WM8960_POWER1_ADCL_MASK | WM8960_POWER1_MICB_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
ret = WM8960_WriteReg(handle, WM8960_LINPATH, 0x1B8);
ret = WM8960_WriteReg(handle, WM8960_LINVOL, 0x117);
break;
case kWM8960_InputLineINPUT2:
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINL_MASK | WM8960_POWER1_ADCL_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
WM8960_ReadReg(WM8960_INBMIX1, &val);
val |= 0xE;
ret = WM8960_WriteReg(handle, WM8960_INBMIX1, val);
break;
case kWM8960_InputLineINPUT3:
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINL_MASK | WM8960_POWER1_ADCL_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
WM8960_ReadReg(WM8960_INBMIX1, &val);
val |= 0x70;
ret = WM8960_WriteReg(handle, WM8960_INBMIX1, val);
break;
default:
break;
}
return ret;
}
status_t WM8960_SetRightInput(wm8960_handle_t *handle, wm8960_input_t input)
{
status_t ret = kStatus_Success;
uint16_t val = 0;
switch (input)
{
case kWM8960_InputSingleEndedMic:
/* Only LMN1 enabled, LMICBOOST to 13db, LMIC2B enabled */
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINR_MASK | WM8960_POWER1_ADCR_MASK | WM8960_POWER1_MICB_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
ret = WM8960_WriteReg(handle, WM8960_RINPATH, 0x138);
ret = WM8960_WriteReg(handle, WM8960_RINVOL, 0x117);
break;
case kWM8960_InputDifferentialMicInput2:
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINR_MASK | WM8960_POWER1_ADCR_MASK | WM8960_POWER1_MICB_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
ret = WM8960_WriteReg(handle, WM8960_RINPATH, 0x178);
ret = WM8960_WriteReg(handle, WM8960_RINVOL, 0x117);
break;
case kWM8960_InputDifferentialMicInput3:
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINR_MASK | WM8960_POWER1_ADCR_MASK | WM8960_POWER1_MICB_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
ret = WM8960_WriteReg(handle, WM8960_RINPATH, 0x1B8);
ret = WM8960_WriteReg(handle, WM8960_RINVOL, 0x117);
break;
case kWM8960_InputLineINPUT2:
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINR_MASK | WM8960_POWER1_ADCR_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
WM8960_ReadReg(WM8960_INBMIX2, &val);
val |= 0xE;
ret = WM8960_WriteReg(handle, WM8960_INBMIX2, val);
break;
case kWM8960_InputLineINPUT3:
WM8960_ReadReg(WM8960_POWER1, &val);
val |= (WM8960_POWER1_AINR_MASK | WM8960_POWER1_ADCR_MASK);
ret = WM8960_WriteReg(handle, WM8960_POWER1, val);
WM8960_ReadReg(WM8960_INBMIX2, &val);
val |= 0x70;
ret = WM8960_WriteReg(handle, WM8960_INBMIX2, val);
break;
default:
break;
}
return ret;
}
status_t WM8960_SetProtocol(wm8960_handle_t *handle, wm8960_protocol_t protocol)
{
return WM8960_ModifyReg(handle, WM8960_IFACE1, WM8960_IFACE1_FORMAT_MASK | WM8960_IFACE1_LRP_MASK, protocol);
}
status_t WM8960_SetVolume(wm8960_handle_t *handle, wm8960_module_t module, uint32_t volume)
{
uint16_t vol = 0;
status_t ret = kStatus_Success;
switch (module)
{
case kWM8960_ModuleADC:
vol = volume;
ret = WM8960_WriteReg(handle, WM8960_LADC, vol);
ret = WM8960_WriteReg(handle, WM8960_RADC, vol);
/* Update volume */
vol = 0x100 | volume;
ret = WM8960_WriteReg(handle, WM8960_LADC, vol);
ret = WM8960_WriteReg(handle, WM8960_RADC, vol);
break;
case kWM8960_ModuleDAC:
vol = volume;
ret = WM8960_WriteReg(handle, WM8960_LDAC, vol);
ret = WM8960_WriteReg(handle, WM8960_RDAC, vol);
vol = 0x100 | volume;
ret = WM8960_WriteReg(handle, WM8960_LDAC, vol);
ret = WM8960_WriteReg(handle, WM8960_RDAC, vol);
break;
case kWM8960_ModuleHP:
vol = volume;
ret = WM8960_WriteReg(handle, WM8960_LOUT1, vol);
ret = WM8960_WriteReg(handle, WM8960_ROUT1, vol);
vol = 0x100 | volume;
ret = WM8960_WriteReg(handle, WM8960_LOUT1, vol);
ret = WM8960_WriteReg(handle, WM8960_ROUT1, vol);
break;
case kWM8960_ModuleLineIn:
vol = volume;
ret = WM8960_WriteReg(handle, WM8960_LINVOL, vol);
ret = WM8960_WriteReg(handle, WM8960_RINVOL, vol);
vol = 0x100 | volume;
ret = WM8960_WriteReg(handle, WM8960_LINVOL, vol);
ret = WM8960_WriteReg(handle, WM8960_RINVOL, vol);
break;
case kWM8960_ModuleSpeaker:
vol = volume;
ret = WM8960_WriteReg(handle, WM8960_LOUT2, vol);
ret = WM8960_WriteReg(handle, WM8960_ROUT2, vol);
vol = 0x100 | volume;
ret = WM8960_WriteReg(handle, WM8960_LOUT2, vol);
ret = WM8960_WriteReg(handle, WM8960_ROUT2, vol);
break;
default:
ret = kStatus_InvalidArgument;
break;
}
return ret;
}
uint32_t WM8960_GetVolume(wm8960_handle_t *handle, wm8960_module_t module)
{
uint16_t vol = 0;
switch (module)
{
case kWM8960_ModuleADC:
WM8960_ReadReg(WM8960_LADC, &vol);
vol &= 0xFF;
break;
case kWM8960_ModuleDAC:
WM8960_ReadReg(WM8960_LDAC, &vol);
vol &= 0xFF;
break;
case kWM8960_ModuleHP:
WM8960_ReadReg(WM8960_LOUT1, &vol);
vol &= 0x7F;
break;
case kWM8960_ModuleLineOut:
WM8960_ReadReg(WM8960_LINVOL, &vol);
vol &= 0x3F;
break;
default:
vol = 0;
break;
}
return vol;
}
status_t WM8960_SetMute(wm8960_handle_t *handle, wm8960_module_t module, bool isEnabled)
{
status_t ret = kStatus_Success;
switch (module)
{
case kWM8960_ModuleADC:
/*
* Digital Mute
*/
if (isEnabled)
{
ret = WM8960_WriteReg(handle, WM8960_LADC, 0x100);
ret = WM8960_WriteReg(handle, WM8960_RADC, 0x100);
}
else
{
ret = WM8960_WriteReg(handle, WM8960_LADC, 0x1C3);
ret = WM8960_WriteReg(handle, WM8960_RADC, 0x1C3);
}
break;
case kWM8960_ModuleDAC:
/*
* Digital mute
*/
if (isEnabled)
{
ret = WM8960_WriteReg(handle, WM8960_LDAC, 0x100);
ret = WM8960_WriteReg(handle, WM8960_RDAC, 0x100);
}
else
{
ret = WM8960_WriteReg(handle, WM8960_LDAC, 0x1FF);
ret = WM8960_WriteReg(handle, WM8960_RDAC, 0x1FF);
}
break;
case kWM8960_ModuleHP:
/*
* Analog mute
*/
if (isEnabled)
{
ret = WM8960_WriteReg(handle, WM8960_LOUT1, 0x100);
ret = WM8960_WriteReg(handle, WM8960_ROUT1, 0x100);
}
else
{
ret = WM8960_WriteReg(handle, WM8960_LOUT1, 0x16F);
ret = WM8960_WriteReg(handle, WM8960_ROUT1, 0x16F);
}
break;
case kWM8960_ModuleSpeaker:
if (isEnabled)
{
ret = WM8960_WriteReg(handle, WM8960_LOUT2, 0x100);
ret = WM8960_WriteReg(handle, WM8960_ROUT2, 0x100);
}
else
{
ret = WM8960_WriteReg(handle, WM8960_LOUT2, 0x16F);
ret = WM8960_WriteReg(handle, WM8960_ROUT2, 0x16f);
}
break;
case kWM8960_ModuleLineOut:
break;
default:
ret = kStatus_InvalidArgument;
break;
}
return ret;
}
status_t WM8960_ConfigDataFormat(wm8960_handle_t *handle, uint32_t sysclk, uint32_t sample_rate, uint32_t bits)
{
status_t retval = kStatus_Success;
uint32_t divider = 0;
uint16_t val = 0;
/* Compute sample rate divider, dac and adc are the same sample rate */
divider = sysclk / sample_rate;
if (divider == 256)
{
val = 0;
}
else if (divider > 256)
{
val = (((divider / 256U) << 6U) | ((divider / 256U) << 3U));
}
else
{
return kStatus_InvalidArgument;
}
retval = WM8960_WriteReg(handle, WM8960_CLOCK1, val);
/*
* Slave mode (MS = 0), LRP = 0, 32bit WL, left justified (FORMAT[1:0]=0b01)
*/
switch (bits)
{
case 16:
retval = WM8960_ModifyReg(handle, WM8960_IFACE1, WM8960_IFACE1_WL_MASK,
WM8960_IFACE1_WL(WM8960_IFACE1_WL_16BITS));
break;
case 20:
retval = WM8960_ModifyReg(handle, WM8960_IFACE1, WM8960_IFACE1_WL_MASK,
WM8960_IFACE1_WL(WM8960_IFACE1_WL_20BITS));
break;
case 24:
retval = WM8960_ModifyReg(handle, WM8960_IFACE1, WM8960_IFACE1_WL_MASK,
WM8960_IFACE1_WL(WM8960_IFACE1_WL_24BITS));
break;
case 32:
retval = WM8960_ModifyReg(handle, WM8960_IFACE1, WM8960_IFACE1_WL_MASK,
WM8960_IFACE1_WL(WM8960_IFACE1_WL_32BITS));
break;
default:
return kStatus_InvalidArgument;
}
return retval;
}
status_t WM8960_SetJackDetect(wm8960_handle_t *handle, bool isEnabled)
{
uint8_t retval = 0;
uint16_t val = 0;
WM8960_ReadReg(WM8960_ADDCTL2, &val);
if (isEnabled)
{
val |= 0x40U;
}
else
{
val &= 0xCF;
}
retval = WM8960_WriteReg(handle, WM8960_ADDCTL2, val);
return retval;
}
status_t WM8960_WriteReg(wm8960_handle_t *handle, uint8_t reg, uint16_t val)
{
uint8_t cmd;
uint16_t buff = val;
/* The register address */
cmd = (reg << 1) | ((val >> 8U) & 0x0001U);
reg_cache[reg] = buff;
return CODEC_I2C_Send(handle->i2cHandle, handle->config->slaveAddress, cmd, 1U, (uint8_t *)&buff, 2U);
}
status_t WM8960_ReadReg(uint8_t reg, uint16_t *val)
{
if (reg >= WM8960_CACHEREGNUM)
{
return kStatus_InvalidArgument;
}
*val = reg_cache[reg];
return kStatus_Success;
}
status_t WM8960_ModifyReg(wm8960_handle_t *handle, uint8_t reg, uint16_t mask, uint16_t val)
{
uint8_t retval = 0;
uint16_t reg_val = 0;
retval = WM8960_ReadReg(reg, &reg_val);
if (retval != kStatus_Success)
{
return kStatus_Fail;
}
reg_val &= (uint16_t)~mask;
reg_val |= val;
retval = WM8960_WriteReg(handle, reg, reg_val);
if (retval != kStatus_Success)
{
return kStatus_Fail;
}
return kStatus_Success;
}
status_t WM8960_SetPlay(wm8960_handle_t *handle, uint32_t playSource)
{
status_t ret = kStatus_Success;
if (kWM8960_PlaySourcePGA & playSource)
{
ret = WM8960_ModifyReg(handle, WM8960_BYPASS1, 0x80U, 0x80U);
ret = WM8960_ModifyReg(handle, WM8960_BYPASS2, 0x80U, 0x80U);
ret = WM8960_ModifyReg(handle, WM8960_LOUTMIX, 0x180U, 0U);
ret = WM8960_ModifyReg(handle, WM8960_ROUTMIX, 0x180U, 0U);
}
if (playSource & kWM8960_PlaySourceDAC)
{
ret = WM8960_ModifyReg(handle, WM8960_BYPASS1, 0x80U, 0x00U);
ret = WM8960_ModifyReg(handle, WM8960_BYPASS2, 0x80U, 0x00U);
ret = WM8960_ModifyReg(handle, WM8960_LOUTMIX, 0x180U, 0x100U);
ret = WM8960_ModifyReg(handle, WM8960_ROUTMIX, 0x180U, 0x100U);
}
if (playSource & kWM8960_PlaySourceInput)
{
ret = WM8960_ModifyReg(handle, WM8960_BYPASS1, 0x80U, 0x0U);
ret = WM8960_ModifyReg(handle, WM8960_BYPASS2, 0x80U, 0x0U);
ret = WM8960_ModifyReg(handle, WM8960_LOUTMIX, 0x180U, 0x80U);
ret = WM8960_ModifyReg(handle, WM8960_ROUTMIX, 0x180U, 0x80U);
}
return ret;
}

View File

@@ -0,0 +1,516 @@
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016-2019 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _FSL_WM8960_H_
#define _FSL_WM8960_H_
#include "fsl_codec_i2c.h"
#include "fsl_common.h"
/*!
* @addtogroup wm8960
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @name Driver version */
/*@{*/
/*! @brief CLOCK driver version 2.1.1 */
#define FSL_WM8960_DRIVER_VERSION (MAKE_VERSION(2, 1, 1))
/*@}*/
/*! @brief wm8960 handle size */
#ifndef WM8960_I2C_HANDLER_SIZE
#define WM8960_I2C_HANDLER_SIZE CODEC_I2C_MASTER_HANDLER_SIZE
#endif
/*! @brief Define the register address of WM8960. */
#define WM8960_LINVOL 0x0
#define WM8960_RINVOL 0x1
#define WM8960_LOUT1 0x2
#define WM8960_ROUT1 0x3
#define WM8960_CLOCK1 0x4
#define WM8960_DACCTL1 0x5
#define WM8960_DACCTL2 0x6
#define WM8960_IFACE1 0x7
#define WM8960_CLOCK2 0x8
#define WM8960_IFACE2 0x9
#define WM8960_LDAC 0xa
#define WM8960_RDAC 0xb
#define WM8960_RESET 0xf
#define WM8960_3D 0x10
#define WM8960_ALC1 0x11
#define WM8960_ALC2 0x12
#define WM8960_ALC3 0x13
#define WM8960_NOISEG 0x14
#define WM8960_LADC 0x15
#define WM8960_RADC 0x16
#define WM8960_ADDCTL1 0x17
#define WM8960_ADDCTL2 0x18
#define WM8960_POWER1 0x19
#define WM8960_POWER2 0x1a
#define WM8960_ADDCTL3 0x1b
#define WM8960_APOP1 0x1c
#define WM8960_APOP2 0x1d
#define WM8960_LINPATH 0x20
#define WM8960_RINPATH 0x21
#define WM8960_LOUTMIX 0x22
#define WM8960_ROUTMIX 0x25
#define WM8960_MONOMIX1 0x26
#define WM8960_MONOMIX2 0x27
#define WM8960_LOUT2 0x28
#define WM8960_ROUT2 0x29
#define WM8960_MONO 0x2a
#define WM8960_INBMIX1 0x2b
#define WM8960_INBMIX2 0x2c
#define WM8960_BYPASS1 0x2d
#define WM8960_BYPASS2 0x2e
#define WM8960_POWER3 0x2f
#define WM8960_ADDCTL4 0x30
#define WM8960_CLASSD1 0x31
#define WM8960_CLASSD3 0x33
#define WM8960_PLL1 0x34
#define WM8960_PLL2 0x35
#define WM8960_PLL3 0x36
#define WM8960_PLL4 0x37
/*! @brief Cache register number */
#define WM8960_CACHEREGNUM 56
/*! @brief WM8960_IFACE1 FORMAT bits */
#define WM8960_IFACE1_FORMAT_MASK 0x03
#define WM8960_IFACE1_FORMAT_SHIFT 0x00
#define WM8960_IFACE1_FORMAT_RJ 0x00
#define WM8960_IFACE1_FORMAT_LJ 0x01
#define WM8960_IFACE1_FORMAT_I2S 0x02
#define WM8960_IFACE1_FORMAT_DSP 0x03
#define WM8960_IFACE1_FORMAT(x) ((x << WM8960_IFACE1_FORMAT_SHIFT) & WM8960_IFACE1_FORMAT_MASK)
/*! @brief WM8960_IFACE1 WL bits */
#define WM8960_IFACE1_WL_MASK 0x0C
#define WM8960_IFACE1_WL_SHIFT 0x02
#define WM8960_IFACE1_WL_16BITS 0x00
#define WM8960_IFACE1_WL_20BITS 0x01
#define WM8960_IFACE1_WL_24BITS 0x02
#define WM8960_IFACE1_WL_32BITS 0x03
#define WM8960_IFACE1_WL(x) ((x << WM8960_IFACE1_WL_SHIFT) & WM8960_IFACE1_WL_MASK)
/*! @brief WM8960_IFACE1 LRP bit */
#define WM8960_IFACE1_LRP_MASK 0x10
#define WM8960_IFACE1_LRP_SHIFT 0x04
#define WM8960_IFACE1_LRCLK_NORMAL_POL 0x00
#define WM8960_IFACE1_LRCLK_INVERT_POL 0x01
#define WM8960_IFACE1_DSP_MODEA 0x00
#define WM8960_IFACE1_DSP_MODEB 0x01
#define WM8960_IFACE1_LRP(x) ((x << WM8960_IFACE1_LRP_SHIFT) & WM8960_IFACE1_LRP_MASK)
/*! @brief WM8960_IFACE1 DLRSWAP bit */
#define WM8960_IFACE1_DLRSWAP_MASK 0x20
#define WM8960_IFACE1_DLRSWAP_SHIFT 0x05
#define WM8960_IFACE1_DACCH_NORMAL 0x00
#define WM8960_IFACE1_DACCH_SWAP 0x01
#define WM8960_IFACE1_DLRSWAP(x) ((x << WM8960_IFACE1_DLRSWAP_SHIFT) & WM8960_IFACE1_DLRSWAP_MASK)
/*! @brief WM8960_IFACE1 MS bit */
#define WM8960_IFACE1_MS_MASK 0x40
#define WM8960_IFACE1_MS_SHIFT 0x06
#define WM8960_IFACE1_SLAVE 0x00
#define WM8960_IFACE1_MASTER 0x01
#define WM8960_IFACE1_MS(x) ((x << WM8960_IFACE1_MS_SHIFT) & WM8960_IFACE1_MS_MASK)
/*! @brief WM8960_IFACE1 BCLKINV bit */
#define WM8960_IFACE1_BCLKINV_MASK 0x80
#define WM8960_IFACE1_BCLKINV_SHIFT 0x07
#define WM8960_IFACE1_BCLK_NONINVERT 0x00
#define WM8960_IFACE1_BCLK_INVERT 0x01
#define WM8960_IFACE1_BCLKINV(x) ((x << WM8960_IFACE1_BCLKINV_SHIFT) & WM8960_IFACE1_BCLKINV_MASK)
/*! @brief WM8960_IFACE1 ALRSWAP bit */
#define WM8960_IFACE1_ALRSWAP_MASK 0x100
#define WM8960_IFACE1_ALRSWAP_SHIFT 0x08
#define WM8960_IFACE1_ADCCH_NORMAL 0x00
#define WM8960_IFACE1_ADCCH_SWAP 0x01
#define WM8960_IFACE1_ALRSWAP(x) ((x << WM8960_IFACE1_ALRSWAP_SHIFT) & WM8960_IFACE1_ALRSWAP_MASK)
/*! @brief WM8960_POWER1 */
#define WM8960_POWER1_VREF_MASK 0x40
#define WM8960_POWER1_VREF_SHIFT 0x06
#define WM8960_POWER1_AINL_MASK 0x20
#define WM8960_POWER1_AINL_SHIFT 0x05
#define WM8960_POWER1_AINR_MASK 0x10
#define WM8960_POWER1_AINR_SHIFT 0x04
#define WM8960_POWER1_ADCL_MASK 0x08
#define WM8960_POWER1_ADCL_SHIFT 0x03
#define WM8960_POWER1_ADCR_MASK 0x0
#define WM8960_POWER1_ADCR_SHIFT 0x02
#define WM8960_POWER1_MICB_MASK 0x02
#define WM8960_POWER1_MICB_SHIFT 0x01
#define WM8960_POWER1_DIGENB_MASK 0x01
#define WM8960_POWER1_DIGENB_SHIFT 0x00
/*! @brief WM8960_POWER2 */
#define WM8960_POWER2_DACL_MASK 0x100
#define WM8960_POWER2_DACL_SHIFT 0x08
#define WM8960_POWER2_DACR_MASK 0x80
#define WM8960_POWER2_DACR_SHIFT 0x07
#define WM8960_POWER2_LOUT1_MASK 0x40
#define WM8960_POWER2_LOUT1_SHIFT 0x06
#define WM8960_POWER2_ROUT1_MASK 0x20
#define WM8960_POWER2_ROUT1_SHIFT 0x05
#define WM8960_POWER2_SPKL_MASK 0x10
#define WM8960_POWER2_SPKL_SHIFT 0x04
#define WM8960_POWER2_SPKR_MASK 0x08
#define WM8960_POWER2_SPKR_SHIFT 0x03
#define WM8960_POWER3_LMIC_MASK 0x20
#define WM8960_POWER3_LMIC_SHIFT 0x05
#define WM8960_POWER3_RMIC_MASK 0x10
#define WM8960_POWER3_RMIC_SHIFT 0x04
#define WM8960_POWER3_LOMIX_MASK 0x08
#define WM8960_POWER3_LOMIX_SHIFT 0x03
#define WM8960_POWER3_ROMIX_MASK 0x04
#define WM8960_POWER3_ROMIX_SHIFT 0x02
/*! @brief WM8960 I2C address. */
#define WM8960_I2C_ADDR 0x1A
/*! @brief WM8960 I2C baudrate */
#define WM8960_I2C_BAUDRATE (100000U)
/*! @brief Modules in WM8960 board. */
typedef enum _wm8960_module
{
kWM8960_ModuleADC = 0, /*!< ADC module in WM8960 */
kWM8960_ModuleDAC = 1, /*!< DAC module in WM8960 */
kWM8960_ModuleVREF = 2, /*!< VREF module */
kWM8960_ModuleHP = 3, /*!< Headphone */
kWM8960_ModuleMICB = 4, /*!< Mic bias */
kWM8960_ModuleMIC = 5, /*!< Input Mic */
kWM8960_ModuleLineIn = 6, /*!< Analog in PGA */
kWM8960_ModuleLineOut = 7, /*!< Line out module */
kWM8960_ModuleSpeaker = 8, /*!< Speaker module */
kWM8960_ModuleOMIX = 9, /*!< Output mixer */
} wm8960_module_t;
/*! @brief wm8960 play channel */
enum _wm8960_play_channel
{
kWM8960_HeadphoneLeft = 1, /*!< wm8960 headphone left channel */
kWM8960_HeadphoneRight = 2, /*!< wm8960 headphone right channel */
kWM8960_SpeakerLeft = 4, /*!< wm8960 speaker left channel */
kWM8960_SpeakerRight = 8, /*!< wm8960 speaker right channel */
};
/*! @brief wm8960 play source */
typedef enum _wm8960_play_source
{
kWM8960_PlaySourcePGA = 1, /*!< wm8960 play source PGA */
kWM8960_PlaySourceInput = 2, /*!< wm8960 play source Input */
kWM8960_PlaySourceDAC = 4, /*!< wm8960 play source DAC */
} wm8960_play_source_t;
/*!
* @brief WM8960 data route.
* Only provide some typical data route, not all route listed.
* Note: Users cannot combine any routes, once a new route is set, the previous one would be replaced.
*/
typedef enum _wm8960_route
{
kWM8960_RouteBypass = 0, /*!< LINEIN->Headphone. */
kWM8960_RoutePlayback = 1, /*!< I2SIN->DAC->Headphone. */
kWM8960_RoutePlaybackandRecord = 2, /*!< I2SIN->DAC->Headphone, LINEIN->ADC->I2SOUT. */
kWM8960_RouteRecord = 5 /*!< LINEIN->ADC->I2SOUT. */
} wm8960_route_t;
/*!
* @brief The audio data transfer protocol choice.
* WM8960 only supports I2S format and PCM format.
*/
typedef enum _wm8960_protocol
{
kWM8960_BusI2S = 2, /*!< I2S type */
kWM8960_BusLeftJustified = 1, /*!< Left justified mode */
kWM8960_BusRightJustified = 0, /*!< Right justified mode */
kWM8960_BusPCMA = 3, /*!< PCM A mode */
kWM8960_BusPCMB = 3 | (1 << 4) /*!< PCM B mode */
} wm8960_protocol_t;
/*! @brief wm8960 input source */
typedef enum _wm8960_input
{
kWM8960_InputClosed = 0, /*!< Input device is closed */
kWM8960_InputSingleEndedMic = 1, /*!< Input as single ended mic, only use L/RINPUT1 */
kWM8960_InputDifferentialMicInput2 = 2, /*!< Input as differential mic, use L/RINPUT1 and L/RINPUT2 */
kWM8960_InputDifferentialMicInput3 = 3, /*!< Input as differential mic, use L/RINPUT1 and L/RINPUT3*/
kWM8960_InputLineINPUT2 = 4, /*!< Input as line input, only use L/RINPUT2 */
kWM8960_InputLineINPUT3 = 5 /*!< Input as line input, only use L/RINPUT3 */
} wm8960_input_t;
/*! @brief audio sample rate definition */
enum _wm8960_sample_rate
{
kWM8960_AudioSampleRate8KHz = 8000U, /*!< Sample rate 8000 Hz */
kWM8960_AudioSampleRate11025Hz = 11025U, /*!< Sample rate 11025 Hz */
kWM8960_AudioSampleRate12KHz = 12000U, /*!< Sample rate 12000 Hz */
kWM8960_AudioSampleRate16KHz = 16000U, /*!< Sample rate 16000 Hz */
kWM8960_AudioSampleRate22050Hz = 22050U, /*!< Sample rate 22050 Hz */
kWM8960_AudioSampleRate24KHz = 24000U, /*!< Sample rate 24000 Hz */
kWM8960_AudioSampleRate32KHz = 32000U, /*!< Sample rate 32000 Hz */
kWM8960_AudioSampleRate44100Hz = 44100U, /*!< Sample rate 44100 Hz */
kWM8960_AudioSampleRate48KHz = 48000U, /*!< Sample rate 48000 Hz */
kWM8960_AudioSampleRate96KHz = 96000U, /*!< Sample rate 96000 Hz */
kWM8960_AudioSampleRate192KHz = 192000U, /*!< Sample rate 192000 Hz */
kWM8960_AudioSampleRate384KHz = 384000U, /*!< Sample rate 384000 Hz */
};
/*! @brief audio bit width */
enum _wm8960_audio_bit_width
{
kWM8960_AudioBitWidth16bit = 16U, /*!< audio bit width 16 */
kWM8960_AudioBitWidth20bit = 20U, /*!< audio bit width 20 */
kWM8960_AudioBitWidth24bit = 24U, /*!< audio bit width 24 */
kWM8960_AudioBitWidth32bit = 32U, /*!< audio bit width 32 */
};
/*! @brief wm8960 audio format */
typedef struct _wm8960_audio_format
{
uint32_t mclk_HZ; /*!< master clock frequency */
uint32_t sampleRate; /*!< sample rate */
uint32_t bitWidth; /*!< bit width */
} wm8960_audio_format_t;
/*! @brief Initialize structure of WM8960 */
typedef struct wm8960_config
{
wm8960_route_t route; /*!< Audio data route.*/
wm8960_protocol_t bus; /*!< Audio transfer protocol */
wm8960_audio_format_t format; /*!< Audio format */
bool master_slave; /*!< Master or slave. */
bool enableSpeaker; /*!< True means enable class D speaker as output, false means no */
wm8960_input_t leftInputSource; /*!< Left input source for WM8960 */
wm8960_input_t rightInputSource; /*!< Right input source for wm8960 */
wm8960_play_source_t playSource; /*!< play source */
uint8_t slaveAddress; /*!< wm8960 device address */
codec_i2c_config_t i2cConfig; /*!< i2c configuration */
} wm8960_config_t;
/*! @brief wm8960 codec handler
*/
typedef struct _wm8960_handle
{
const wm8960_config_t *config; /*!< wm8904 config pointer */
uint8_t i2cHandle[WM8960_I2C_HANDLER_SIZE]; /*!< i2c handle */
} wm8960_handle_t;
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @brief WM8960 initialize function.
*
* The second parameter is NULL to WM8960 in this version. If users want
* to change the settings, they have to use wm8960_write_reg() or wm8960_modify_reg()
* to set the register value of WM8960.
* Note: If the codec_config is NULL, it would initialize WM8960 using default settings.
* The default setting:
* codec_config->route = kWM8960_RoutePlaybackandRecord
* codec_config->bus = kWM8960_BusI2S
* codec_config->master = slave
*
* @param handle WM8960 handle structure.
* @param wm8960Config WM8960 configuration structure.
*/
status_t WM8960_Init(wm8960_handle_t *handle, const wm8960_config_t *wm8960Config);
/*!
* @brief Deinit the WM8960 codec.
*
* This function close all modules in WM8960 to save power.
*
* @param handle WM8960 handle structure pointer.
*/
status_t WM8960_Deinit(wm8960_handle_t *handle);
/*!
* @brief Set audio data route in WM8960.
*
* This function would set the data route according to route. The route cannot be combined,
* as all route would enable different modules.
* Note: If a new route is set, the previous route would not work.
*
* @param handle WM8960 handle structure.
* @param route Audio data route in WM8960.
*/
status_t WM8960_SetDataRoute(wm8960_handle_t *handle, wm8960_route_t route);
/*!
* @brief Set left audio input source in WM8960.
*
* @param handle WM8960 handle structure.
* @param input Audio input source.
*/
status_t WM8960_SetLeftInput(wm8960_handle_t *handle, wm8960_input_t input);
/*!
* @brief Set right audio input source in WM8960.
*
* @param handle WM8960 handle structure.
* @param input Audio input source.
*/
status_t WM8960_SetRightInput(wm8960_handle_t *handle, wm8960_input_t input);
/*!
* @brief Set the audio transfer protocol.
*
* WM8960 only supports I2S, left justified, right justified, PCM A, PCM B format.
*
* @param handle WM8960 handle structure.
* @param bus Audio data transfer protocol.
*/
status_t WM8960_SetProtocol(wm8960_handle_t *handle, wm8960_protocol_t protocol);
/*!
* @brief Set WM8960 as master or slave.
*
* @param handle WM8960 handle structure.
* @param master 1 represent master, 0 represent slave.
*/
void WM8960_SetMasterSlave(wm8960_handle_t *handle, bool master);
/*!
* @brief Set the volume of different modules in WM8960.
*
* This function would set the volume of WM8960 modules. Uses need to appoint the module.
* The function assume that left channel and right channel has the same volume.
*
* @param handle WM8960 handle structure.
* @param module Module to set volume, it can be ADC, DAC, Headphone and so on.
* @param volume Volume value need to be set.
*/
status_t WM8960_SetVolume(wm8960_handle_t *handle, wm8960_module_t module, uint32_t volume);
/*!
* @brief Get the volume of different modules in WM8960.
*
* This function gets the volume of WM8960 modules. Uses need to appoint the module.
* The function assume that left channel and right channel has the same volume.
*
* @param handle WM8960 handle structure.
* @param module Module to set volume, it can be ADC, DAC, Headphone and so on.
* @return Volume value of the module.
*/
uint32_t WM8960_GetVolume(wm8960_handle_t *handle, wm8960_module_t module);
/*!
* @brief Mute modules in WM8960.
*
* @param handle WM8960 handle structure.
* @param module Modules need to be mute.
* @param isEnabled Mute or unmute, 1 represent mute.
*/
status_t WM8960_SetMute(wm8960_handle_t *handle, wm8960_module_t module, bool isEnabled);
/*!
* @brief Enable/disable expected devices.
*
* @param handle WM8960 handle structure.
* @param module Module expected to enable.
* @param isEnabled Enable or disable moudles.
*/
status_t WM8960_SetModule(wm8960_handle_t *handle, wm8960_module_t module, bool isEnabled);
/*!
* @brief SET the WM8960 play source.
*
* @param handle WM8960 handle structure.
* @param playSource play source , can be a value combine of kWM8960_ModuleHeadphoneSourcePGA,
* kWM8960_ModuleHeadphoneSourceDAC, kWM8960_ModulePlaySourceInput, kWM8960_ModulePlayMonoRight,
* kWM8960_ModulePlayMonoLeft.
*
* @return kStatus_WM8904_Success if successful, different code otherwise..
*/
status_t WM8960_SetPlay(wm8960_handle_t *handle, uint32_t playSource);
/*!
* @brief Configure the data format of audio data.
*
* This function would configure the registers about the sample rate, bit depths.
*
* @param handle WM8960 handle structure pointer.
* @param sysclk system clock of the codec which can be generated by MCLK or PLL output.
* @param sample_rate Sample rate of audio file running in WM8960. WM8960 now
* supports 8k, 11.025k, 12k, 16k, 22.05k, 24k, 32k, 44.1k, 48k and 96k sample rate.
* @param bits Bit depth of audio file (WM8960 only supports 16bit, 20bit, 24bit
* and 32 bit in HW).
*/
status_t WM8960_ConfigDataFormat(wm8960_handle_t *handle, uint32_t sysclk, uint32_t sample_rate, uint32_t bits);
/*!
* @brief Enable/disable jack detect feature.
*
* @param handle WM8960 handle structure.
* @param isEnabled Enable or disable moudles.
*/
status_t WM8960_SetJackDetect(wm8960_handle_t *handle, bool isEnabled);
/*!
* @brief Write register to WM8960 using I2C.
*
* @param handle WM8960 handle structure.
* @param reg The register address in WM8960.
* @param val Value needs to write into the register.
*/
status_t WM8960_WriteReg(wm8960_handle_t *handle, uint8_t reg, uint16_t val);
/*!
* @brief Read register from WM8960 using I2C.
* @param handle WM8960 handle structure.
* @param reg The register address in WM8960.
* @param val Value written to.
*/
status_t WM8960_ReadReg(uint8_t reg, uint16_t *val);
/*!
* @brief Modify some bits in the register using I2C.
* @param handle WM8960 handle structure.
* @param reg The register address in WM8960.
* @param mask The mask code for the bits want to write. The bit you want to write should be 0.
* @param val Value needs to write into the register.
*/
status_t WM8960_ModifyReg(wm8960_handle_t *handle, uint8_t reg, uint16_t mask, uint16_t val);
#if defined(__cplusplus)
}
#endif
/*! @} */
#endif /* _FSL_WM8960_H_ */
/*******************************************************************************
* API
******************************************************************************/

View File

@@ -0,0 +1,206 @@
/*
* Copyright (c) 2016, Freescale Semiconductor, Inc.
* Copyright 2016-2019 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_common.h"
#include "fsl_ft6x06.h"
typedef struct _ft6x06_touch_point
{
uint8_t XH;
uint8_t XL;
uint8_t YH;
uint8_t YL;
uint8_t WEIGHT;
uint8_t MISC;
} ft6x06_touch_point_t;
typedef struct _ft6x06_touch_data
{
uint8_t GEST_ID;
uint8_t TD_STATUS;
ft6x06_touch_point_t TOUCH[FT6X06_MAX_TOUCHES];
} ft6x06_touch_data_t;
#define TOUCH_POINT_GET_EVENT(T) ((touch_event_t)((T).XH >> 6))
#define TOUCH_POINT_GET_ID(T) ((T).YH >> 4)
#define TOUCH_POINT_GET_X(T) ((((T).XH & 0x0f) << 8) | (T).XL)
#define TOUCH_POINT_GET_Y(T) ((((T).YH & 0x0f) << 8) | (T).YL)
void FT6X06_EventHandler(ft6x06_handle_t *handle, uint32_t i2c_event)
{
handle->i2c_event = i2c_event;
handle->i2c_event_received = true;
}
static uint32_t FT_6X06_WaitEvent(ft6x06_handle_t *handle)
{
uint32_t i2c_event;
while (!(handle->i2c_event_received))
;
i2c_event = handle->i2c_event;
handle->i2c_event_received = false;
return i2c_event;
}
status_t FT6X06_Init(ft6x06_handle_t *handle, ARM_DRIVER_I2C *i2c_driver)
{
status_t status = kStatus_Success;
uint8_t i2c_buf[2];
assert(handle);
assert(i2c_driver);
if (!handle || !i2c_driver)
{
return kStatus_InvalidArgument;
}
handle->i2c_driver = i2c_driver;
/* clear transfer structure and buffer */
memset(handle->touch_buf, 0, FT6X06_TOUCH_DATA_LEN);
/* set device mode to normal operation */
i2c_buf[0] = 0; /* mode register address */
i2c_buf[1] = 0; /* normal operation mode */
if (handle->i2c_driver->MasterTransmit(FT6X06_I2C_ADDRESS, i2c_buf, 2, false) != ARM_DRIVER_OK)
{
status = kStatus_Fail;
}
else if (FT_6X06_WaitEvent(handle) != ARM_I2C_EVENT_TRANSFER_DONE)
{
status = kStatus_Fail;
}
return status;
}
status_t FT6X06_Denit(ft6x06_handle_t *handle)
{
assert(handle);
if (!handle)
{
return kStatus_InvalidArgument;
}
handle->i2c_driver = NULL;
return kStatus_Success;
}
status_t FT6X06_ReadTouchData(ft6x06_handle_t *handle)
{
status_t status = kStatus_Success;
uint8_t i2c_buf[1];
assert(handle);
if (!handle || !(handle->i2c_driver))
{
return kStatus_InvalidArgument;
}
i2c_buf[0] = F6X06_TOUCH_DATA_SUBADDR;
if (handle->i2c_driver->MasterTransmit(FT6X06_I2C_ADDRESS, i2c_buf, 1, true) != ARM_DRIVER_OK)
{
status = kStatus_Fail;
}
else if (FT_6X06_WaitEvent(handle) != ARM_I2C_EVENT_TRANSFER_DONE)
{
status = kStatus_Fail;
}
else if (handle->i2c_driver->MasterReceive(FT6X06_I2C_ADDRESS, handle->touch_buf, FT6X06_TOUCH_DATA_LEN, false) !=
ARM_DRIVER_OK)
{
status = kStatus_Fail;
}
else if (FT_6X06_WaitEvent(handle) != ARM_I2C_EVENT_TRANSFER_DONE)
{
status = kStatus_Fail;
}
return status;
}
status_t FT6X06_GetSingleTouch(ft6x06_handle_t *handle, touch_event_t *touch_event, int *touch_x, int *touch_y)
{
status_t status;
touch_event_t touch_event_local;
status = FT6X06_ReadTouchData(handle);
if (status == kStatus_Success)
{
ft6x06_touch_data_t *touch_data = (ft6x06_touch_data_t *)(void *)(handle->touch_buf);
if (touch_event == NULL)
{
touch_event = &touch_event_local;
}
*touch_event = TOUCH_POINT_GET_EVENT(touch_data->TOUCH[0]);
/* Update coordinates only if there is touch detected */
if ((*touch_event == kTouch_Down) || (*touch_event == kTouch_Contact))
{
if (touch_x)
{
*touch_x = TOUCH_POINT_GET_X(touch_data->TOUCH[0]);
}
if (touch_y)
{
*touch_y = TOUCH_POINT_GET_Y(touch_data->TOUCH[0]);
}
}
}
return status;
}
status_t FT6X06_GetMultiTouch(ft6x06_handle_t *handle, int *touch_count, touch_point_t touch_array[FT6X06_MAX_TOUCHES])
{
status_t status;
status = FT6X06_ReadTouchData(handle);
if (status == kStatus_Success)
{
ft6x06_touch_data_t *touch_data = (ft6x06_touch_data_t *)(void *)(handle->touch_buf);
int i;
/* Decode number of touches */
if (touch_count)
{
*touch_count = touch_data->TD_STATUS;
}
/* Decode valid touch points */
for (i = 0; i < touch_data->TD_STATUS; i++)
{
touch_array[i].TOUCH_ID = TOUCH_POINT_GET_ID(touch_data->TOUCH[i]);
touch_array[i].TOUCH_EVENT = TOUCH_POINT_GET_EVENT(touch_data->TOUCH[i]);
touch_array[i].TOUCH_X = TOUCH_POINT_GET_X(touch_data->TOUCH[i]);
touch_array[i].TOUCH_Y = TOUCH_POINT_GET_Y(touch_data->TOUCH[i]);
}
/* Clear vacant elements of touch_array */
for (; i < FT6X06_MAX_TOUCHES; i++)
{
touch_array[i].TOUCH_ID = 0;
touch_array[i].TOUCH_EVENT = kTouch_Reserved;
touch_array[i].TOUCH_X = 0;
touch_array[i].TOUCH_Y = 0;
}
}
return status;
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (c) 2016, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _FSL_FT6X06_H_
#define _FSL_FT6X06_H_
#include "fsl_common.h"
#include "Driver_I2C.h"
/*!
* @addtogroup ft6x06
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief FT6X06 I2C address. */
#define FT6X06_I2C_ADDRESS (0x38)
/*! @brief FT6X06 maximum number of simultaneously detected touches. */
#define FT6X06_MAX_TOUCHES (2U)
/*! @brief FT6X06 register address where touch data begin. */
#define F6X06_TOUCH_DATA_SUBADDR (1)
/*! @brief FT6X06 raw touch data length. */
#define FT6X06_TOUCH_DATA_LEN (2 + (FT6X06_MAX_TOUCHES)*6)
typedef enum _touch_event
{
kTouch_Down = 0, /*!< The state changed to touched. */
kTouch_Up = 1, /*!< The state changed to not touched. */
kTouch_Contact = 2, /*!< There is a continuous touch being detected. */
kTouch_Reserved = 3 /*!< No touch information available. */
} touch_event_t;
typedef struct _touch_point
{
touch_event_t TOUCH_EVENT; /*!< Indicates the state or event of the touch point. */
uint8_t TOUCH_ID; /*!< Id of the touch point. This numeric value stays constant between down and up event. */
uint16_t TOUCH_X; /*!< X coordinate of the touch point */
uint16_t TOUCH_Y; /*!< Y coordinate of the touch point */
} touch_point_t;
typedef struct _ft6x06_handle
{
ARM_DRIVER_I2C *i2c_driver;
volatile uint32_t i2c_event;
volatile bool i2c_event_received;
uint8_t touch_buf[FT6X06_TOUCH_DATA_LEN];
} ft6x06_handle_t;
status_t FT6X06_Init(ft6x06_handle_t *handle, ARM_DRIVER_I2C *i2c_driver);
status_t FT6X06_Denit(ft6x06_handle_t *handle);
void FT6X06_EventHandler(ft6x06_handle_t *handle, uint32_t i2c_event);
status_t FT6X06_GetSingleTouch(ft6x06_handle_t *handle, touch_event_t *touch_event, int *touch_x, int *touch_y);
status_t FT6X06_GetMultiTouch(ft6x06_handle_t *handle, int *touch_count, touch_point_t touch_array[FT6X06_MAX_TOUCHES]);
#endif

View File

@@ -0,0 +1,227 @@
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_fxos.h"
/******************************************************************************
* Code
******************************************************************************/
status_t FXOS_Init(fxos_handle_t *fxos_handle, fxos_config_t *config)
{
assert(fxos_handle);
assert(config);
assert(config->I2C_SendFunc);
assert(config->I2C_ReceiveFunc);
uint8_t tmp[1] = {0};
/* Initialize the I2C access function. */
fxos_handle->I2C_SendFunc = config->I2C_SendFunc;
fxos_handle->I2C_ReceiveFunc = config->I2C_ReceiveFunc;
/* Set Slave Address. */
fxos_handle->slaveAddress = config->slaveAddress;
if (FXOS_ReadReg(fxos_handle, WHO_AM_I_REG, tmp, 1) != kStatus_Success)
{
return kStatus_Fail;
}
if (tmp[0] != kFXOS_WHO_AM_I_Device_ID)
{
return kStatus_Fail;
}
/* setup auto sleep with FFMT trigger */
/* go to standby */
if (FXOS_ReadReg(fxos_handle, CTRL_REG1, tmp, 1) != kStatus_Success)
{
return kStatus_Fail;
}
if (FXOS_WriteReg(fxos_handle, CTRL_REG1, tmp[0] & (uint8_t)~ACTIVE_MASK) != kStatus_Success)
{
return kStatus_Fail;
}
/* Read again to make sure we are in standby mode. */
if (FXOS_ReadReg(fxos_handle, CTRL_REG1, tmp, 1) != kStatus_Success)
{
return kStatus_Fail;
}
if ((tmp[0] & ACTIVE_MASK) == ACTIVE_MASK)
{
return kStatus_Fail;
}
/* Disable the FIFO */
if (FXOS_WriteReg(fxos_handle, F_SETUP_REG, F_MODE_DISABLED) != kStatus_Success)
{
return kStatus_Fail;
}
#ifdef LPSLEEP_HIRES
/* enable auto-sleep, low power in sleep, high res in wake */
if (FXOS_WriteReg(fxos_handle, CTRL_REG2, SLPE_MASK | SMOD_LOW_POWER | MOD_HIGH_RES) != kStatus_Success)
{
return kStatus_Fail;
}
#else
/* enable auto-sleep, low power in sleep, high res in wake */
if (FXOS_WriteReg(fxos_handle, CTRL_REG2, MOD_HIGH_RES) != kStatus_Success)
{
return kStatus_Fail;
}
#endif
/* set up Mag OSR and Hybrid mode using M_CTRL_REG1, use default for Acc */
if (FXOS_WriteReg(fxos_handle, M_CTRL_REG1, (M_RST_MASK | M_OSR_MASK | M_HMS_MASK)) != kStatus_Success)
{
return kStatus_Fail;
}
/* Enable hyrid mode auto increment using M_CTRL_REG2 */
if (FXOS_WriteReg(fxos_handle, M_CTRL_REG2, (M_HYB_AUTOINC_MASK)) != kStatus_Success)
{
return kStatus_Fail;
}
#ifdef EN_FFMT
/* enable FFMT for motion detect for X and Y axes, latch enable */
if (FXOS_WriteReg(fxos_handle, FF_MT_CFG_REG, XEFE_MASK | YEFE_MASK | ELE_MASK | OAE_MASK) != kStatus_Success)
{
return kStatus_Fail;
}
#endif
#ifdef SET_THRESHOLD
/* set threshold to about 0.25g */
if (FXOS_WriteReg(fxos_handle, FT_MT_THS_REG, 0x04) != kStatus_Success)
{
return kStatus_Fail;
}
#endif
#ifdef SET_DEBOUNCE
/* set debounce to zero */
if (FXOS_WriteReg(fxos_handle, FF_MT_COUNT_REG, 0x00) != kStatus_Success)
{
return kStatus_Fail;
}
#endif
#ifdef EN_AUTO_SLEEP
/* set auto-sleep wait period to 5s (=5/0.64=~8) */
if (FXOS_WriteReg(fxos_handle, ASLP_COUNT_REG, 8) != kStatus_Success)
{
return kStatus_Fail;
}
#endif
/* default set to 4g mode */
if (FXOS_WriteReg(fxos_handle, XYZ_DATA_CFG_REG, FULL_SCALE_4G) != kStatus_Success)
{
return kStatus_Fail;
}
#ifdef EN_INTERRUPTS
/* enable data-ready, auto-sleep and motion detection interrupts */
/* FXOS1_WriteRegister(CTRL_REG4, INT_EN_DRDY_MASK | INT_EN_ASLP_MASK | INT_EN_FF_MT_MASK); */
if (FXOS_WriteReg(fxos_handle, CTRL_REG4, 0x0) != kStatus_Success)
{
return kStatus_Fail;
}
/* route data-ready interrupts to INT1, others INT2 (default) */
if (FXOS_WriteReg(fxos_handle, CTRL_REG5, INT_CFG_DRDY_MASK) != kStatus_Success)
{
return kStatus_Fail;
}
/* enable ffmt as a wake-up source */
if (FXOS_WriteReg(fxos_handle, CTRL_REG3, WAKE_FF_MT_MASK) != kStatus_Success)
{
return kStatus_Fail;
}
/* finally activate accel_device with ASLP ODR=0.8Hz, ODR=100Hz, FSR=2g */
if (FXOS_WriteReg(fxos_handle, CTRL_REG1, HYB_ASLP_RATE_0_8HZ | HYB_DATA_RATE_100HZ | ACTIVE_MASK) !=
kStatus_Success)
{
return kStatus_Fail;
}
#else
/* Setup the ODR for 50 Hz and activate the accelerometer */
if (FXOS_WriteReg(fxos_handle, CTRL_REG1, (HYB_DATA_RATE_200HZ | ACTIVE_MASK)) != kStatus_Success)
{
return kStatus_Fail;
}
#endif
/* Read Control register again to ensure we are in active mode */
if (FXOS_ReadReg(fxos_handle, CTRL_REG1, tmp, 1) != kStatus_Success)
{
return kStatus_Fail;
}
if ((tmp[0] & ACTIVE_MASK) != ACTIVE_MASK)
{
return kStatus_Fail;
}
return kStatus_Success;
}
status_t FXOS_ReadSensorData(fxos_handle_t *fxos_handle, fxos_data_t *sensorData)
{
status_t status = kStatus_Success;
uint8_t tmp_buff[6] = {0};
uint8_t i = 0;
if (!FXOS_ReadReg(fxos_handle, OUT_X_MSB_REG, tmp_buff, 6) == kStatus_Success)
{
status = kStatus_Fail;
}
for (i = 0; i < 6; i++)
{
((int8_t *)sensorData)[i] = tmp_buff[i];
}
if (!FXOS_ReadReg(fxos_handle, M_OUT_X_MSB_REG, tmp_buff, 6) == kStatus_Success)
{
status = kStatus_Fail;
}
for (i = 0; i < 6; i++)
{
((int8_t *)sensorData)[i + 6] = tmp_buff[i];
}
return status;
}
status_t FXOS_ReadReg(fxos_handle_t *handle, uint8_t reg, uint8_t *val, uint8_t bytesNumber)
{
assert(handle);
assert(val);
if (!handle->I2C_ReceiveFunc)
{
return kStatus_Fail;
}
return handle->I2C_ReceiveFunc(handle->slaveAddress, reg, 1, val, bytesNumber);
}
status_t FXOS_WriteReg(fxos_handle_t *handle, uint8_t reg, uint8_t val)
{
assert(handle);
if (!handle->I2C_SendFunc)
{
return kStatus_Fail;
}
return handle->I2C_SendFunc(handle->slaveAddress, reg, 1, val);
}

View File

@@ -0,0 +1,780 @@
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _FSL_FXOS_H_
#define _FSL_FXOS_H_
#include "fsl_common.h"
#define FXOS8700CQ_ACCEL_RESOLUTION_BITS 14
/*
* STATUS Register
*/
#define STATUS_00_REG 0x00
#define ZYXOW_MASK 0x80
#define ZOW_MASK 0x40
#define YOW_MASK 0x20
#define XOW_MASK 0x10
#define ZYXDR_MASK 0x08
#define ZDR_MASK 0x04
#define YDR_MASK 0x02
#define XDR_MASK 0x01
/*
* F_STATUS FIFO Status Register
*/
#define F_STATUS_REG 0x00
#define F_OVF_MASK 0x80
#define F_WMRK_FLAG_MASK 0x40
#define F_CNT5_MASK 0x20
#define F_CNT4_MASK 0x10
#define F_CNT3_MASK 0x08
#define F_CNT2_MASK 0x04
#define F_CNT1_MASK 0x02
#define F_CNT0_MASK 0x01
#define F_CNT_MASK 0x3F
/*
* XYZ Data Registers
*/
#define OUT_X_MSB_REG 0x01
#define OUT_X_LSB_REG 0x02
#define OUT_Y_MSB_REG 0x03
#define OUT_Y_LSB_REG 0x04
#define OUT_Z_MSB_REG 0x05
#define OUT_Z_LSB_REG 0x06
/*
* F_SETUP FIFO Setup Register
*/
#define F_SETUP_REG 0x09
#define F_MODE1_MASK 0x80
#define F_MODE0_MASK 0x40
#define F_WMRK5_MASK 0x20
#define F_WMRK4_MASK 0x10
#define F_WMRK3_MASK 0x08
#define F_WMRK2_MASK 0x04
#define F_WMRK1_MASK 0x02
#define F_WMRK0_MASK 0x01
#define F_MODE_MASK 0xC0
#define F_WMRK_MASK 0x3F
#define F_MODE_DISABLED 0x00
#define F_MODE_CIRCULAR (F_MODE0_MASK)
#define F_MODE_FILL (F_MODE1_MASK)
#define F_MODE_TRIGGER (F_MODE1_MASK + F_MODE0_MASK)
/*
* TRIG_CFG FIFO Trigger Configuration Register
*/
#define TRIG_CFG_REG 0x0A
#define TRIG_TRANS_MASK 0x20
#define TRIG_LNDPRT_MASK 0x10
#define TRIG_PULSE_MASK 0x08
#define TRIG_FF_MT_MASK 0x04
/*
* SYSMOD System Mode Register
*/
#define SYSMOD_REG 0x0B
#define FGERR_MASK 0x80 /* MMA8451 only */
#define FGT_4_MASK 0x40 /* MMA8451 only */
#define FGT_3_MASK 0x20 /* MMA8451 only */
#define FGT_2_MASK 0x10 /* MMA8451 only */
#define FGT_1_MASK 0x08 /* MMA8451 only */
#define FGT_0_MASK 0x04 /* MMA8451 only */
#define FGT_MASK 0x7C /* MMA8451 only */
#define SYSMOD1_MASK 0x02
#define SYSMOD0_MASK 0x01
#define SYSMOD_MASK 0x03
#define SYSMOD_STANDBY 0x00
#define SYSMOD_WAKE (SYSMOD0_MASK)
#define SYSMOD_SLEEP (SYSMOD1_MASK)
/*
* INT_SOURCE System Interrupt Status Register
*/
#define INT_SOURCE_REG 0x0C
#define SRC_ASLP_MASK 0x80
#define SRC_FIFO_MASK 0x40
#define SRC_TRANS_MASK 0x20
#define SRC_LNDPRT_MASK 0x10
#define SRC_PULSE_MASK 0x08
#define SRC_FF_MT_MASK 0x04
#define SRC_DRDY_MASK 0x01
/*
* WHO_AM_I Device ID Register
*/
#define WHO_AM_I_REG 0x0D
/* Content */
#define kFXOS_WHO_AM_I_Device_ID 0xC7
/* XYZ_DATA_CFG Sensor Data Configuration Register */
#define XYZ_DATA_CFG_REG 0x0E
#define HPF_OUT_MASK 0x10
#define FS1_MASK 0x02
#define FS0_MASK 0x01
#define FS_MASK 0x03
#define FULL_SCALE_2G 0x00
#define FULL_SCALE_4G (FS0_MASK)
#define FULL_SCALE_8G (FS1_MASK)
/* HP_FILTER_CUTOFF High Pass Filter Register */
#define HP_FILTER_CUTOFF_REG 0x0F
#define PULSE_HPF_BYP_MASK 0x20
#define PULSE_LPF_EN_MASK 0x10
#define SEL1_MASK 0x02
#define SEL0_MASK 0x01
#define SEL_MASK 0x03
/*
* PL_STATUS Portrait/Landscape Status Register
*/
#define PL_STATUS_REG 0x10
#define NEWLP_MASK 0x80
#define LO_MASK 0x40
#define LAPO1_MASK 0x04
#define LAPO0_MASK 0x02
#define BAFRO_MASK 0x01
#define LAPO_MASK 0x06
/*
* PL_CFG Portrait/Landscape Configuration Register
*/
#define PL_CFG_REG 0x11
#define DBCNTM_MASK 0x80
#define PL_EN_MASK 0x40
/*
* PL_COUNT Portrait/Landscape Debounce Register
*/
#define PL_COUNT_REG 0x12
/*
* PL_BF_ZCOMP Back/Front and Z Compensation Register
*/
#define PL_BF_ZCOMP_REG 0x13
#define BKFR1_MASK 0x80
#define BKFR0_MASK 0x40
#define ZLOCK2_MASK 0x04
#define ZLOCK1_MASK 0x02
#define ZLOCK0_MASK 0x01
#define BKFR_MASK 0xC0
#define ZLOCK_MASK 0x07
/*
* PL_P_L_THS Portrait to Landscape Threshold Register
*/
#define PL_P_L_THS_REG 0x14
#define P_L_THS4_MASK 0x80
#define P_L_THS3_MASK 0x40
#define P_L_THS2_MASK 0x20
#define P_L_THS1_MASK 0x10
#define P_L_THS0_MASK 0x08
#define HYS2_MASK 0x04
#define HYS1_MASK 0x02
#define HYS0_MASK 0x01
#define P_L_THS_MASK 0xF8
#define HYS_MASK 0x07
/*
* FF_MT_CFG Freefall and Motion Configuration Register
*/
#define FF_MT_CFG_REG 0x15
#define ELE_MASK 0x80
#define OAE_MASK 0x40
#define ZEFE_MASK 0x20
#define YEFE_MASK 0x10
#define XEFE_MASK 0x08
/*
* FF_MT_SRC Freefall and Motion Source Registers
*/
#define FF_MT_SRC_REG 0x16
#define EA_MASK 0x80
#define ZHE_MASK 0x20
#define ZHP_MASK 0x10
#define YHE_MASK 0x08
#define YHP_MASK 0x04
#define XHE_MASK 0x02
#define XHP_MASK 0x01
/*
* FF_MT_THS Freefall and Motion Threshold Registers
* TRANSIENT_THS Transient Threshold Register
*/
#define FT_MT_THS_REG 0x17
#define TRANSIENT_THS_REG 0x1F
#define DBCNTM_MASK 0x80
#define THS6_MASK 0x40
#define THS5_MASK 0x20
#define THS4_MASK 0x10
#define THS3_MASK 0x08
#define THS2_MASK 0x04
#define TXS1_MASK 0x02
#define THS0_MASK 0x01
#define THS_MASK 0x7F
/* FF_MT_COUNT Freefall Motion Count Registers */
#define FF_MT_COUNT_REG 0x18
/* TRANSIENT_CFG Transient Configuration Register */
#define TRANSIENT_CFG_REG 0x1D
#define TELE_MASK 0x10
#define ZTEFE_MASK 0x08
#define YTEFE_MASK 0x04
#define XTEFE_MASK 0x02
#define HPF_BYP_MASK 0x01
/* TRANSIENT_SRC Transient Source Register */
#define TRANSIENT_SRC_REG 0x1E
#define TEA_MASK 0x40
#define ZTRANSE_MASK 0x20
#define Z_TRANS_POL_MASK 0x10
#define YTRANSE_MASK 0x08
#define Y_TRANS_POL_MASK 0x04
#define XTRANSE_MASK 0x02
#define X_TRANS_POL_MASK 0x01
/* TRANSIENT_COUNT Transient Debounce Register */
#define TRANSIENT_COUNT_REG 0x20
/* PULSE_CFG Pulse Configuration Register */
#define PULSE_CFG_REG 0x21
#define DPA_MASK 0x80
#define PELE_MASK 0x40
#define ZDPEFE_MASK 0x20
#define ZSPEFE_MASK 0x10
#define YDPEFE_MASK 0x08
#define YSPEFE_MASK 0x04
#define XDPEFE_MASK 0x02
#define XSPEFE_MASK 0x01
/* PULSE_SRC Pulse Source Register */
#define PULSE_SRC_REG 0x22
#define PEA_MASK 0x80
#define AXZ_MASK 0x40
#define AXY_MASK 0x20
#define AXX_MASK 0x10
#define DPE_MASK 0x08
#define POLZ_MASK 0x04
#define POLY_MASK 0x02
#define POLX_MASK 0x01
/* PULSE_THS XYZ Pulse Threshold Registers */
#define PULSE_THSX_REG 0x23
#define PULSE_THSY_REG 0x24
#define PULSE_THSZ_REG 0x25
#define PTHS_MASK 0x7F
/* PULSE_TMLT Pulse Time Window Register */
#define PULSE_TMLT_REG 0x26
/* PULSE_LTCY Pulse Latency Timer Register */
#define PULSE_LTCY_REG 0x27
/* PULSE_WIND Second Pulse Time Window Register */
#define PULSE_WIND_REG 0x28
/* ASLP_COUNT Auto Sleep Inactivity Timer Register */
#define ASLP_COUNT_REG 0x29
/* CTRL_REG1 System Control 1 Register */
#define CTRL_REG1 0x2A
#define ASLP_RATE1_MASK 0x80
#define ASLP_RATE0_MASK 0x40
#define DR2_MASK 0x20
#define DR1_MASK 0x10
#define DR0_MASK 0x08
#define LNOISE_MASK 0x04
#define FREAD_MASK 0x02
#define ACTIVE_MASK 0x01
#define ASLP_RATE_MASK 0xC0
#define DR_MASK 0x38
#define ASLP_RATE_20MS 0x00
#define ASLP_RATE_80MS (ASLP_RATE0_MASK)
#define ASLP_RATE_160MS (ASLP_RATE1_MASK)
#define ASLP_RATE_640MS (ASLP_RATE1_MASK + ASLP_RATE0_MASK)
#define ASLP_RATE_50HZ (ASLP_RATE_20MS)
#define ASLP_RATE_12_5HZ (ASLP_RATE_80MS)
#define ASLP_RATE_6_25HZ (ASLP_RATE_160MS)
#define ASLP_RATE_1_56HZ (ASLP_RATE_640MS)
#define HYB_ASLP_RATE_25HZ (ASLP_RATE_20MS)
#define HYB_ASLP_RATE_6_25HZ (ASLP_RATE_80MS)
#define HYB_ASLP_RATE_1_56HZ (ASLP_RATE_160MS)
#define HYB_ASLP_RATE_0_8HZ (ASLP_RATE_640MS)
#define DATA_RATE_1250US 0x00
#define DATA_RATE_2500US (DR0_MASK)
#define DATA_RATE_5MS (DR1_MASK)
#define DATA_RATE_10MS (DR1_MASK + DR0_MASK)
#define DATA_RATE_20MS (DR2_MASK)
#define DATA_RATE_80MS (DR2_MASK + DR0_MASK)
#define DATA_RATE_160MS (DR2_MASK + DR1_MASK)
#define DATA_RATE_640MS (DR2_MASK + DR1_MASK + DR0_MASK)
#define DATA_RATE_800HZ (DATA_RATE_1250US)
#define DATA_RATE_400HZ (DATA_RATE_2500US)
#define DATA_RATE_200HZ (DATA_RATE_5MS)
#define DATA_RATE_100HZ (DATA_RATE_10MS)
#define DATA_RATE_50HZ (DATA_RATE_20MS)
#define DATA_RATE_12_5HZ (DATA_RATE_80MS)
#define DATA_RATE_6_25HZ (DATA_RATE_160MS)
#define DATA_RATE_1_56HZ (DATA_RATE_640MS)
/* for hybrid (TO, Aug 2012) */
#define HYB_DATA_RATE_400HZ (DATA_RATE_1250US)
#define HYB_DATA_RATE_200HZ (DATA_RATE_2500US)
#define HYB_DATA_RATE_100HZ (DATA_RATE_5MS)
#define HYB_DATA_RATE_50HZ (DATA_RATE_10MS)
#define HYB_DATA_RATE_25HZ (DATA_RATE_20MS)
#define HYB_DATA_RATE_6_25HZ (DATA_RATE_80MS)
#define HYB_DATA_RATE_3_15HZ (DATA_RATE_160MS)
#define HYB_DATA_RATE_0_8HZ (DATA_RATE_640MS)
#define ACTIVE (ACTIVE_MASK)
#define STANDBY 0x00
/* CTRL_REG2 System Control 2 Register */
#define CTRL_REG2 0x2B
#define ST_MASK 0x80
#define RST_MASK 0x40
#define SMODS1_MASK 0x10
#define SMODS0_MASK 0x08
#define SLPE_MASK 0x04
#define MODS1_MASK 0x02
#define MODS0_MASK 0x01
#define SMODS_MASK 0x18
#define MODS_MASK 0x03
#define SMOD_NORMAL 0x00
#define SMOD_LOW_NOISE (SMODS0_MASK)
#define SMOD_HIGH_RES (SMODS1_MASK)
#define SMOD_LOW_POWER (SMODS1_MASK + SMODS0_MASK)
#define MOD_NORMAL 0x00
#define MOD_LOW_NOISE (MODS0_MASK)
#define MOD_HIGH_RES (MODS1_MASK)
#define MOD_LOW_POWER (MODS1_MASK + MODS0_MASK)
/* CTRL_REG3 Interrupt Control Register */
#define CTRL_REG3 0x2C
#define FIFO_GATE_MASK 0x80
#define WAKE_TRANS_MASK 0x40
#define WAKE_LNDPRT_MASK 0x20
#define WAKE_PULSE_MASK 0x10
#define WAKE_FF_MT_MASK 0x08
#define IPOL_MASK 0x02
#define PP_OD_MASK 0x01
/* CTRL_REG4 Interrupt Enable Register */
#define CTRL_REG4 0x2D
#define INT_EN_ASLP_MASK 0x80
#define INT_EN_FIFO_MASK 0x40
#define INT_EN_TRANS_MASK 0x20
#define INT_EN_LNDPRT_MASK 0x10
#define INT_EN_PULSE_MASK 0x08
#define INT_EN_FF_MT_MASK 0x04
#define INT_EN_DRDY_MASK 0x01
/* CTRL_REG5 Interrupt Configuration Register */
#define CTRL_REG5 0x2E
#define INT_CFG_ASLP_MASK 0x80
#define INT_CFG_FIFO_MASK 0x40
#define INT_CFG_TRANS_MASK 0x20
#define INT_CFG_LNDPRT_MASK 0x10
#define INT_CFG_PULSE_MASK 0x08
#define INT_CFG_FF_MT_MASK 0x04
#define INT_CFG_DRDY_MASK 0x01
/* XYZ Offset Correction Registers */
#define OFF_X_REG 0x2F
#define OFF_Y_REG 0x30
#define OFF_Z_REG 0x31
/* M_DR_STATUS Register */
#define M_DR_STATUS_REG 0x32
#define ZYXOW_MASK 0x80
#define ZOW_MASK 0x40
#define YOW_MASK 0x20
#define XOW_MASK 0x10
#define ZYXDR_MASK 0x08
#define ZDR_MASK 0x04
#define YDR_MASK 0x02
#define XDR_MASK 0x01
/* MAG XYZ Data Registers */
#define M_OUT_X_MSB_REG 0x33
#define M_OUT_X_LSB_REG 0x34
#define M_OUT_Y_MSB_REG 0x35
#define M_OUT_Y_LSB_REG 0x36
#define M_OUT_Z_MSB_REG 0x37
#define M_OUT_Z_LSB_REG 0x38
/* MAG CMP Data Registers */
#define CMP_X_MSB_REG 0x39
#define CMP_X_LSB_REG 0x3A
#define CMP_Y_MSB_REG 0x3B
#define CMP_Y_LSB_REG 0x3C
#define CMP_Z_MSB_REG 0x3D
#define CMP_Z_LSB_REG 0x3E
/* MAG XYZ Offset Correction Registers */
#define M_OFF_X_MSB_REG 0x3F
#define M_OFF_X_LSB_REG 0x40
#define M_OFF_Y_MSB_REG 0x41
#define M_OFF_Y_LSB_REG 0x42
#define M_OFF_Z_MSB_REG 0x43
#define M_OFF_Z_LSB_REG 0x44
/* MAG MAX XYZ Registers */
#define MAX_X_MSB_REG 0x45
#define MAX_X_LSB_REG 0x46
#define MAX_Y_MSB_REG 0x47
#define MAX_Y_LSB_REG 0x48
#define MAX_Z_MSB_REG 0x49
#define MAX_Z_LSB_REG 0x4A
/* MAG MIN XYZ Registers */
#define MIN_X_MSB_REG 0x4B
#define MIN_X_LSB_REG 0x4C
#define MIN_Y_MSB_REG 0x4D
#define MIN_Y_LSB_REG 0x4E
#define MIN_Z_MSB_REG 0x4F
#define MIN_Z_LSB_REG 0x50
/* TEMP Registers */
#define TEMP_REG 0x51
/* M_THS CONFIG Registers */
#define M_THS_CFG_REG 0x52
/* M_THS SRC Registers */
#define M_THS_SRC_REG 0x53
/* MAG THRESHOLD XYZ Registers */
#define M_THS_X_MSB_REG 0x54
#define M_THS_X_LSB_REG 0x55
#define M_THS_Y_MSB_REG 0x56
#define M_THS_Y_LSB_REG 0x57
#define M_THS_Z_MSB_REG 0x58
#define M_THS_Z_LSB_REG 0x59
/* M_THS COUNT Registers */
#define M_THS_COUNT 0x5A
/* MAG CTRL_REG1 System Control 1 Register */
#define M_CTRL_REG1 0x5B
#define M_ACAL_MASK 0x80
#define M_RST_MASK 0x40
#define M_OST_MASK 0x20
#define M_OSR2_MASK 0x10
#define M_OSR1_MASK 0x08
#define M_OSR0_MASK 0x04
#define M_HMS1_MASK 0x02
#define M_HMS0_MASK 0x01
#define M_OSR_MASK 0x1C
#define M_HMS_MASK 0x03
/* OSR Selections */
#define M_OSR_1_56_HZ 0x00
#define M_OSR_6_25_HZ M_OSR0_MASK
#define M_OSR_12_5_HZ M_OSR1_MASK
#define M_OSR_50_HZ M_OSR1_MASK + M_OSR0_MASK
#define M_OSR_100_HZ M_OSR2_MASK
#define M_OSR_200_HZ M_OSR2_MASK + M_OSR0_MASK
#define M_OSR_400_HZ M_OSR2_MASK + M_OSR1_MASK
#define M_OSR_800_HZ M_OSR2_MASK + M_OSR1_MASK + M_OSR0_MASK
/* Hybrid Mode Selection */
#define ACCEL_ACTIVE 0x00
#define MAG_ACTIVE M_HMS0_MASK
#define HYBRID_ACTIVE (M_HMS1_MASK | M_HMS0_MASK)
/* MAG CTRL_REG2 System Control 2 Register */
#define M_CTRL_REG2 0x5C
#define M_HYB_AUTOINC_MASK 0x20
#define M_MAXMIN_DIS_MASK 0x10
#define M_MAXMIN_DIS_THS_MASK 0x08
#define M_MAXMIN_RST_MASK 0x04
#define M_RST_CNT1_MASK 0x02
#define M_RST_CNT0_MASK 0x01
/* Mag Auto-Reset De-Gauss Frequency */
#define RST_ODR_CYCLE 0x00
#define RST_16_ODR_CYCLE M_RST_CNT0_MASK
#define RST_512_ODR_CYCLE M_RST_CNT1_MASK
#define RST_DISABLED M_RST_CNT1_MASK + M_RST_CNT0_MASK
/* MAG CTRL_REG3 System Control 3 Register */
#define M_CTRL_REG3 0x5D
#define M_RAW_MASK 0x80
#define M_ASLP_OS_2_MASK 0x40
#define M_ASLP_OS_1_MASK 0x20
#define M_ASLP_OS_0_MASK 0x10
#define M_THS_XYZ_MASK 0x08
#define M_ST_Z_MASK 0x04
#define M_ST_XY1_MASK 0x02
#define M_ST_XY0_MASK 0x01
#define M_ASLP_OSR_MASK 0x70
#define M_ST_XY_MASK 0x03
/* OSR Selections */
#define M_ASLP_OSR_1_56_HZ 0x00
#define M_ASLP_OSR_6_25_HZ M_ASLP_OS_0_MASK
#define M_ASLP_OSR_12_5_HZ M_ASLP_OS_1_MASK
#define M_ASLP_OSR_50_HZ M_ASLP_OS_1_MASK + M_ASLP_OS_0_MASK
#define M_ASLP_OSR_100_HZ M_ASLP_OS_2_MASK
#define M_ASLP_OSR_200_HZ M_ASLP_OS_2_MASK + M_ASLP_OS_0_MASK
#define M_ASLP_OSR_400_HZ M_ASLP_OS_2_MASK + M_ASLP_OS_1_MASK
#define M_ASLP_OSR_800_HZ M_ASLP_OS_2_MASK + M_ASLP_OS_1_MASK + M_ASLP_OS_0_MASK
/* MAG INT SOURCE Register */
#define M_INT_SOURCE 0x5E
#define SRC_M_DRDY_MASK 0x04
#define SRC_M_VECM_MASK 0x02
#define SRC_M_THS_MASK 0x01
/* ACCEL VECTOR CONFIG Register */
#define A_VECM_CFG 0x5F
#define A_VECM_INIT_CFG_MASK 0x40
#define A_VECM_INIT_EN_MASK 0x20
#define A_VECM_WAKE_EN_MASK 0x10
#define A_VECM_EN_MASK 0x08
#define A_VECM_UPDM_MASK 0x04
#define A_VECM_INITM_MASK 0x02
#define A_VECM_ELE_MASK 0x01
/* ACCEL VECTOR THS MSB AND LSB Register */
#define A_VECM_THS_MSB 0x60
#define A_VECM_DBCNTM_MASK 0x80
#define A_VECM_THS_LSB 0x61
/* ACCEL VECTOR CNT Register */
#define A_VECM_CNT 0x62
/* ACCEL INITIAL XYZ VECTORS Register */
#define A_VECM_INITX_MSB 0x63
#define A_VECM_INITX_LSB 0x64
#define A_VECM_INITY_MSB 0x65
#define A_VECM_INITY_LSB 0x66
#define A_VECM_INITZ_MSB 0x67
#define A_VECM_INITZ_LSB 0x68
/* MAG VECTOR CONFIG Register */
#define M_VECM_CFG 0x69
#define M_VECM_INIT_CFG_MASK 0x40
#define M_VECM_INIT_EN_MASK 0x20
#define M_VECM_WAKE_EN_MASK 0x10
#define M_VECM_EN_MASK 0x08
#define M_VECM_UPDM_MASK 0x04
#define M_VECM_INITM_MASK 0x02
#define M_VECM_ELE_MASK 0x01
/* MAG VECTOR THS MSB AND LSB Register */
#define M_VECM_THS_MSB 0x6A
#define M_VECM_DBCNTM_MASK 0x80
#define M_VECM_THS_LSB 0x6B
/* MAG VECTOR CNT Register */
#define M_VECM_CNT 0x6C
/* MAG INITIAL XYZ VECTORS Register */
#define M_VECM_INITX_MSB 0x6D
#define M_VECM_INITX_LSB 0x6E
#define M_VECM_INITY_MSB 0x6F
#define M_VECM_INITY_LSB 0x70
#define M_VECM_INITZ_MSB 0x71
#define M_VECM_INITZ_LSB 0x72
/* ACCEL FFMT THS X MSB AND LSB Register */
#define A_FFMT_THS_X_MSB 0x73
#define A_FFMT_THS_XYZ_EN_MASK 0x80
#define A_FFMT_THS_X_LSB 0x74
#define A_FFMT_THS_X_LSB_MASK 0xFC
/* ACCEL FFMT THS Y MSB AND LSB Register */
#define A_FFMT_THS_Y_MSB 0x75
#define A_FFMT_THS_Y_EN_MASK 0x80
#define A_FFMT_THS_Y_LSB 0x76
#define A_FFMT_THS_Y_LSB_MASK 0xFC
/* ACCEL FFMT THS Z MSB AND LSB Register */
#define A_FFMT_THS_Z_MSB 0x77
#define A_FFMT_THS_Z_EN_MASK 0x80
#define A_FFMT_THS_Z_LSB 0x78
#define A_FFMT_THS_Z_LSB_MASK 0xFC
/* ACCEL TRANSIENT INIT Register */
#define A_TRAN_INIT_XYZ_MSB 0x79
#define A_TRAN_INIT_X_LSB 0x7A
#define A_TRAN_INIT_Y_LSB 0x7B
#define A_TRAN_INIT_Z_LSB 0x7C
/*! @brief Define I2C access function. */
typedef status_t (*I2C_SendFunc_t)(uint8_t deviceAddress, uint32_t subAddress, uint8_t subaddressSize, uint32_t txBuff);
typedef status_t (*I2C_ReceiveFunc_t)(
uint8_t deviceAddress, uint32_t subAddress, uint8_t subaddressSize, uint8_t *rxBuff, uint8_t rxBuffSize);
/*! @brief fxos8700cq configure definition. This structure should be global.*/
typedef struct _fxos_handle
{
/* Pointer to the user-defined I2C Send Data function. */
I2C_SendFunc_t I2C_SendFunc;
/* Pointer to the user-defined I2C Receive Data function. */
I2C_ReceiveFunc_t I2C_ReceiveFunc;
/* The I2C slave address . */
uint8_t slaveAddress;
} fxos_handle_t;
typedef struct _fxos8700cq_data
{
uint8_t accelXMSB;
uint8_t accelXLSB;
uint8_t accelYMSB;
uint8_t accelYLSB;
uint8_t accelZMSB;
uint8_t accelZLSB;
uint8_t magXMSB;
uint8_t magXLSB;
uint8_t magYMSB;
uint8_t magYLSB;
uint8_t magZMSB;
uint8_t magZLSB;
} fxos_data_t;
/*! @brief fxos8700cq configure structure.*/
typedef struct _fxos_config
{
/* Pointer to the user-defined I2C Send Data function. */
I2C_SendFunc_t I2C_SendFunc;
/* Pointer to the user-defined I2C Receive Data function. */
I2C_ReceiveFunc_t I2C_ReceiveFunc;
/* The I2C slave address . */
uint8_t slaveAddress;
} fxos_config_t;
/*!
* @addtogroup fxos_common
* @{
*/
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @brief Verify and initialize fxos_handleice: Hybrid mode with ODR=50Hz, Mag OSR=32, Acc OSR=Normal.
*
* @param fxos_handle The pointer to accel driver handle.
* @param config The configuration structure pointer to accel.
*
* @return kStatus_Success if success or kStatus_Fail if error.
*/
status_t FXOS_Init(fxos_handle_t *fxos_handle, fxos_config_t *config);
/*!
* @brief Read data from sensors, assumes hyb_autoinc_mode is set in M_CTRL_REG2
*
* @param fxos_handle The pointer to accel driver handle.
* @param sensorData The pointer to the buffer to hold sensor data
*
* @return kStatus_Success if success or kStatus_Fail if error.
*/
status_t FXOS_ReadSensorData(fxos_handle_t *fxos_handle, fxos_data_t *sensorData);
/*!
* @brief Write value to register of sensor.
*
* @param handle The pointer to fxos8700cq driver handle.
* @param reg Register address.
* @param val Data want to write.
*
* @return kStatus_Success if success or kStatus_Fail if error.
*/
status_t FXOS_WriteReg(fxos_handle_t *handle, uint8_t reg, uint8_t val);
/*!
* @brief Read n bytes start at register from sensor.
*
* @param handle The pointer to fxos8700cq driver handle.
* @param reg Register address.
* @param val The pointer to address which store data.
* @param bytesNumber Number of bytes receiver.
*
* @return kStatus_Success if success or kStatus_Fail if error.
*/
status_t FXOS_ReadReg(fxos_handle_t *handle, uint8_t reg, uint8_t *val, uint8_t bytesNumber);
/*!
* @brief Get device accelerator resolution bits.
*
* @return accelerator resolution bits.
*/
static inline uint8_t FXOS_GetResolutionBits(void)
{
return FXOS8700CQ_ACCEL_RESOLUTION_BITS;
}
#if defined(__cplusplus)
}
#endif /* __cplusplus */
#endif /* _FSL_FXOS_H_ */

View File

@@ -0,0 +1,451 @@
/*
* Copyright 2018 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __HAL_I2C_ADAPTER_H__
#define __HAL_I2C_ADAPTER_H__
/*!
* @addtogroup hal_i2c_driver
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
#define HAL_I2C_MASTER_HANDLE_SIZE (80U)
#define HAL_I2C_SLAVE_HANDLE_SIZE (80U)
typedef enum _hal_i2c_status
{
kStatus_HAL_I2cSuccess = kStatus_Success, /*!< Successfully */
kStatus_HAL_I2cError = MAKE_STATUS(kStatusGroup_HAL_I2C, 1), /*!< Error occurs on HAL I2C */
kStatus_HAL_I2cBusy = MAKE_STATUS(kStatusGroup_HAL_I2C, 2), /*!< HAL I2C is busy with current transfer */
kStatus_HAL_I2cIdle = MAKE_STATUS(kStatusGroup_HAL_I2C, 3), /*!< HAL I2C transmitter is idle */
kStatus_HAL_I2cNak = MAKE_STATUS(kStatusGroup_HAL_I2C, 4), /*!< NAK received during transfer */
kStatus_HAL_I2cArbitrationLost = MAKE_STATUS(kStatusGroup_HAL_I2C, 5), /*!< Arbitration lost during transfer */
kStatus_HAL_I2cTimeout = MAKE_STATUS(kStatusGroup_HAL_I2C, 6), /*!< Timeout */
kStatus_HAL_I2cAddrressNak = MAKE_STATUS(kStatusGroup_HAL_I2C, 7), /*!< NAK received during the address probe */
} hal_i2c_status_t;
/*! @brief HAL I2C master user configuration. */
typedef struct _hal_i2c_master_config
{
uint32_t srcClock_Hz; /*!< Clock source for I2C in Hz */
uint32_t baudRate_Bps; /*!< Baud rate configuration of HAL I2C peripheral. */
bool enableMaster; /*!< Enables the HAL I2C peripheral at initialization time. */
uint8_t instance; /*!< Instance of the i2c */
} hal_i2c_master_config_t;
/*! @brief HAL I2C slave user configuration. */
typedef struct _hal_i2c_slave_config
{
uint32_t srcClock_Hz; /*!< Clock source for I2C in Hz */
uint16_t slaveAddress; /*!< A slave address configuration. */
bool enableSlave; /*!< Enables the HAL I2C peripheral at initialization time. */
uint8_t instance; /*!< Instance of the i2c */
} hal_i2c_slave_config_t;
/*! @brief Direction of master and slave transfers. */
typedef enum _hal_i2c_direction
{
kHAL_I2cWrite = 0U, /*!< Master transmit. */
kHAL_I2cRead = 1U /*!< Master receive. */
} hal_i2c_direction_t;
/*! @brief I2C transfer control flag. */
typedef enum _hal_i2c_master_transfer_flag
{
kHAL_I2cTransferDefaultFlag = 0x0U, /*!< A transfer starts with a start signal, stops with a stop signal. */
kHAL_I2cTransferNoStartFlag = 0x1U, /*!< A transfer starts without a start signal, only support write only or
write+read with no start flag, do not support read only with no start flag. */
kHAL_I2cTransferRepeatedStartFlag = 0x2U, /*!< A transfer starts with a repeated start signal. */
kHAL_I2cTransferNoStopFlag = 0x4U, /*!< A transfer ends without a stop signal. */
} hal_i2c_master_transfer_flag_t;
/*!
* @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 _hal_i2c_slave_transfer_event
{
kHAL_I2cSlaveAddressMatchEvent = 0x01U, /*!< Received the slave address after a start or repeated start. */
kHAL_I2cSlaveTransmitEvent = 0x02U, /*!< A callback is requested to provide data to transmit
(slave-transmitter role). */
kHAL_I2cSlaveReceiveEvent = 0x04U, /*!< A callback is requested to provide a buffer in which to place received
data (slave-receiver role). */
kHAL_I2cSlaveTransmitAckEvent = 0x08U, /*!< A callback needs to either transmit an ACK or NACK. */
kHAL_I2cSlaveCompletionEvent = 0x20U, /*!< A stop was detected or finished transfer, completing the transfer. */
kHAL_I2cSlaveStartEvent = 0x10U, /*!< A start/repeated start was detected. */
kHAL_I2cSlaveGenaralcallEvent = 0x40U, /*!< Received the general call address after a start or repeated start. */
/*! A bit mask of all available events. */
kHAL_I2cSlaveAllEvents = kHAL_I2cSlaveAddressMatchEvent | kHAL_I2cSlaveTransmitEvent | kHAL_I2cSlaveReceiveEvent |
kHAL_I2cSlaveTransmitAckEvent | kHAL_I2cSlaveCompletionEvent | kHAL_I2cSlaveStartEvent |
kHAL_I2cSlaveGenaralcallEvent,
} hal_i2c_slave_transfer_event_t;
/*! @brief HAL I2C master transfer structure. */
typedef struct _hal_i2c_master_transfer
{
uint8_t *volatile data; /*!< A transfer buffer. */
volatile size_t dataSize; /*!< A transfer size. */
uint32_t flags; /*!< A transfer flag which controls the transfer. */
uint32_t subaddress; /*!< A sub address. Transferred MSB first. */
uint8_t subaddressSize; /*!< A size of the command buffer. */
uint8_t slaveAddress; /*!< 7-bit slave address. */
hal_i2c_direction_t direction; /*!< A transfer direction, read or write. */
} hal_i2c_master_transfer_t;
/*! @brief HAL I2C slave transfer structure. */
typedef struct _hal_i2c_slave_transfer
{
hal_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. */
hal_i2c_status_t completionStatus; /*!< Success or error code describing how the transfer completed. Only applies
for #kHAL_I2cSlaveCompletionEvent. */
size_t transferredCount; /*!< A number of bytes actually transferred since the start or since the last repeated
start. */
} hal_i2c_slave_transfer_t;
typedef void *hal_i2c_master_handle_t;
typedef void *hal_i2c_slave_handle_t;
/*!
* @brief Master completion callback function pointer type.
*
* This callback is used only for the non-blocking master transfer API. Specify the callback you wish to use
* in the call to HAL_I2cMasterTransferInstallCallback().
*
* @param handle i2c master handle pointer, this should be a static variable.
* @param completionStatus Either #kStatus_HAL_I2cSuccess or an error code describing how the transfer completed.
* @param callbackParam Arbitrary pointer-sized value passed from the application.
*/
typedef void (*hal_i2c_master_transfer_callback_t)(hal_i2c_master_handle_t handle,
hal_i2c_status_t completionStatus,
void *callbackParam);
/*!
* @brief Slave event callback function pointer type.
*
* This callback is used only for the slave non-blocking transfer API. Specify the callback you wish to use
* in the call to HAL_I2cSlaveTransferInstallCallback().
*
* @param handle i2c slave master handle pointer, this should be a static variable.
* @param transfer Pointer to transfer descriptor containing values passed to and/or from the callback.
* @param callbackParam Arbitrary pointer-sized value passed from the application.
*/
typedef void (*hal_i2c_slave_transfer_callback_t)(hal_i2c_slave_handle_t handle,
hal_i2c_slave_transfer_t *transfer,
void *callbackParam);
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif /*_cplusplus. */
/*!
* @name Initialization and de-initialization
* @{
*/
/*!
* @brief Initializes the HAL I2C master peripheral.
*
* @note This API should be called at the beginning of the application.
* Otherwise, any operation to the HAL I2C module can cause a hard fault
* because the clock is not enabled. This function configures the i2c master
* with user-defined settings. The user can configure the configuration
* structure. The parameter handle is a pointer to point to a memory space
* of size #HAL_I2C_MASTER_HANDLE_SIZE allocated by the caller.
*
* This is an example.
* @code
* uint8_t g_i2cMasterHandleBuffer[HAL_I2C_MASTER_HANDLE_SIZE];
* hal_i2c_master_handle_t g_i2cMasterHandle = (hal_i2c_master_handle_t)&g_i2cMasterHandleBuffer[0];
* hal_i2c_master_config_t masterConfig;
* masterConfig.enableMaster = true;
* masterConfig.baudRate_Bps = 100000U;
* masterConfig.srcClock_Hz = 12000000U;
* masterConfig.instance = 0;
* HAL_I2cMasterInit(g_i2cMasterHandle, &masterConfig);
* @endcode
*
* @param handle Pointer to point to a memory space of size #HAL_I2C_MASTER_HANDLE_SIZE allocated by the caller.
* @param config A pointer to the master configuration structure
* @retval kStatus_HAL_I2cError An error occurred.
* @retval kStatus_HAL_I2cSuccess i2c master initialization succeed
*/
hal_i2c_status_t HAL_I2cMasterInit(hal_i2c_master_handle_t handle, const hal_i2c_master_config_t *config);
/*!
* @brief Initializes the HAL I2C peripheral.
*
* @note This API should be called at the beginning of the application.
* Otherwise, any operation to the HAL I2C module can cause a hard fault
* because the clock is not enabled. This function configures the i2c slave
* with user-defined settings. The user can configure the configuration
* structure. The parameter handle is a pointer to point to a memory space
* of size #HAL_I2C_SLAVE_HANDLE_SIZE allocated by the caller.
*
* This is an example.
* @code
* uint8_t g_i2cSlaveHandleBuffer[HAL_I2C_SLAVE_HANDLE_SIZE];
* hal_i2c_slave_handle_t g_i2cSlaveHandle = (hal_i2c_slave_handle_t)&g_i2cSlaveHandleBuffer[0];
* hal_i2c_slave_config_t slaveConfig;
* slaveConfig.enableSlave = true;
* slaveConfig.slaveAddress = 0x01U;
* slaveConfig.srcClock_Hz = 12000000U;
* slaveConfig.instance = 0;
* HAL_I2cSlaveInit(g_i2cSlaveHandle, &slaveConfig);
* @endcode
*
* @param handle Pointer to point to a memory space of size #HAL_I2C_SLAVE_HANDLE_SIZE allocated by the caller.
* @param config A pointer to the slave configuration structure
* @retval kStatus_HAL_I2cError An error occurred.
* @retval kStatus_HAL_I2cSuccess i2c slave initialization succeed
*/
hal_i2c_status_t HAL_I2cSlaveInit(hal_i2c_slave_handle_t handle, const hal_i2c_slave_config_t *config);
/*!
* @brief De-initializes the HAL I2C master peripheral. Call this API to gate the HAL I2C clock.
* The HAL I2C master module can't work unless the HAL_I2cMasterInit is called.
*
* @param handle i2c master handle pointer, this should be a static variable.
* @retval kStatus_HAL_I2cSuccess i2c master de-initialization succeed */
hal_i2c_status_t HAL_I2cMasterDeinit(hal_i2c_master_handle_t handle);
/*!
* @brief De-initializes the HAL I2C slave peripheral. Calling this API gates the HAL I2C clock.
* The HAL I2C slave module can't work unless the HAL_I2cSlaveInit is called to enable the clock.
*
* @param handle i2c slave handle pointer, this should be a static variable.
* @retval kStatus_HAL_I2cSuccess i2c slave de-initialization succeed
*/
hal_i2c_status_t HAL_I2cSlaveDeinit(hal_i2c_slave_handle_t handle);
/*! @} */
/*!
* @name Bus Operations
* @{
*/
/*!
* @brief Performs a polling send transaction on the HAL I2C bus.
*
* @param handle i2c master handle pointer, this should be a static variable.
* @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 kHAL_I2cTransferDefaultFlag
* to issue a stop and kHAL_I2cTransferNoStopFlag to not send a stop.
* @retval kStatus_HAL_I2cSuccess Successfully complete the data transmission.
* @retval kStatus_HAL_I2cArbitrationLost Transfer error, arbitration lost.
* @retval kStatus_HAL_I2cNak Transfer error, receive NAK during transfer.
*/
hal_i2c_status_t HAL_I2cMasterWriteBlocking(hal_i2c_master_handle_t handle,
const uint8_t *txBuff,
size_t txSize,
uint32_t flags);
/*!
* @brief Performs a polling receive transaction on the HAL I2C bus.
*
* @note The HAL_I2cMasterReadBlocking 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 handle i2c master handle pointer, this should be a static variable.
* @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 kHAL_I2cTransferDefaultFlag
* to issue a stop and kHAL_I2cTransferNoStopFlag to not send a stop.
* @retval kStatus_HAL_I2cSuccess Successfully complete the data transmission.
* @retval kStatus_HAL_I2cTimeout Send stop signal failed, timeout.
*/
hal_i2c_status_t HAL_I2cMasterReadBlocking(hal_i2c_master_handle_t handle,
uint8_t *rxBuff,
size_t rxSize,
uint32_t flags);
/*!
* @brief Performs a polling send transaction on the HAL I2C bus.
*
* @param handle i2c slave handle pointer, this should be a static variable.
* @param txBuff The pointer to the data to be transferred.
* @param txSize The length in bytes of the data to be transferred.
* @retval kStatus_HAL_I2cSuccess Successfully complete the data transmission.
* @retval kStatus_HAL_I2cArbitrationLost Transfer error, arbitration lost.
* @retval kStatus_HAL_I2cNak Transfer error, receive NAK during transfer.
*/
hal_i2c_status_t HAL_I2cSlaveWriteBlocking(hal_i2c_slave_handle_t handle, const uint8_t *txBuff, size_t txSize);
/*!
* @brief Performs a polling receive transaction on the HAL I2C bus.
*
* @param handle i2c slave handle pointer, this should be a static variable.
* @param rxBuff The pointer to the data to store the received data.
* @param rxSize The length in bytes of the data to be received.
* @retval kStatus_HAL_I2cSuccess Successfully complete data receive.
* @retval kStatus_HAL_I2cTimeout Wait status flag timeout.
*/
hal_i2c_status_t HAL_I2cSlaveReadBlocking(hal_i2c_slave_handle_t handle, uint8_t *rxBuff, size_t rxSize);
/*!
* @brief Performs a master polling transfer on the HAL I2C bus.
*
* @note The API does not return until the transfer succeeds or fails due
* to arbitration lost or receiving a NAK.
*
* @param handle i2c master handle pointer, this should be a static variable.
* @param xfer Pointer to the transfer structure.
* @retval kStatus_HAL_I2cSuccess Successfully complete the data transmission.
* @retval kStatus_HAL_I2cBusy Previous transmission still not finished.
* @retval kStatus_HAL_I2cTimeout Transfer error, wait signal timeout.
* @retval kStatus_HAL_I2cArbitrationLost Transfer error, arbitration lost.
* @retval kStatus_HAL_I2cNak Transfer error, receive NAK during transfer.
*/
hal_i2c_status_t HAL_I2cMasterTransferBlocking(hal_i2c_master_handle_t handle, hal_i2c_master_transfer_t *xfer);
/*! @} */
/*!
* @name Transactional
* @{
*/
/*!
* @brief Installs a callback and callback parameter.
*
* This function is used to install the callback and callback parameter for i2c master module.
* When any status of the i2c master changed, the driver will notify the upper layer by the installed callback
* function. And the status is also passed as status parameter when the callback is called.
*
* @param handle i2c master handle pointer, this should be a static variable.
* @param callback pointer to user callback function.
* @param callbackParam user parameter passed to the callback function.
* @retval kStatus_HAL_I2cSuccess i2c master handle created
*/
hal_i2c_status_t HAL_I2cMasterTransferInstallCallback(hal_i2c_master_handle_t handle,
hal_i2c_master_transfer_callback_t callback,
void *callbackParam);
/*!
* @brief Performs a master interrupt non-blocking transfer on the HAL I2C bus.
*
* @note Calling the API returns immediately after transfer initiates. The user needs
* to call HAL_I2cMasterGetTransferCount to poll the transfer status to check whether
* the transfer is finished. If the return status is not kStatus_HAL_I2cBusy, the transfer
* is finished.
*
* @param handle i2c master handle pointer, this should be a static variable.
* @param xfer pointer to hal_i2c_master_transfer_t structure.
* @retval kStatus_HAL_I2cSuccess Successfully start the data transmission.
* @retval kStatus_HAL_I2cBusy Previous transmission still not finished.
* @retval kStatus_HAL_I2cTimeout Transfer error, wait signal timeout.
*/
hal_i2c_status_t HAL_I2cMasterTransferNonBlocking(hal_i2c_master_handle_t handle, hal_i2c_master_transfer_t *xfer);
/*!
* @brief Gets the master transfer status during a interrupt non-blocking transfer.
*
* @param handle i2c master handle pointer, this should be a static variable.
* @param count Number of bytes transferred so far by the non-blocking transaction.
* @retval kStatus_HAL_I2cError An error occurred.
* @retval kStatus_HAL_I2cSuccess Successfully return the count.
*/
hal_i2c_status_t HAL_I2cMasterTransferGetCount(hal_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 handle i2c master handle pointer, this should be a static variable.
* @retval kStatus_HAL_I2cTimeout Timeout during polling flag.
* @retval kStatus_HAL_I2cSuccess Successfully abort the transfer.
*/
hal_i2c_status_t HAL_I2cMasterTransferAbort(hal_i2c_master_handle_t handle);
/*!
* @brief Installs a callback and callback parameter.
*
* This function is used to install the callback and callback parameter for i2c slave module.
* When any status of the i2c slave changed, the driver will notify the upper layer by the installed callback
* function. And the status is also passed as status parameter when the callback is called.
*
* @param handle i2c slave handle pointer, this should be a static variable.
* @param callback pointer to user callback function.
* @param callbackParam user parameter passed to the callback function.
* @retval kStatus_HAL_I2cSuccess i2c slave handle created
*/
hal_i2c_status_t HAL_I2cSlaveTransferInstallCallback(hal_i2c_slave_handle_t handle,
hal_i2c_slave_transfer_callback_t callback,
void *callbackParam);
/*!
* @brief Starts accepting slave transfers.
*
* Call this API after calling the HAL_I2cSlaveInit() and HAL_I2cSlaveTransferInstallCallback() to start processing
* transactions driven by an HAL I2C slave. The slave monitors the HAL I2C bus and passes events to the
* callback that was passed into the call to HAL_I2cSlaveTransferInstallCallback(). 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 #hal_i2c_slave_transfer_event_t enumerators for the events you wish to receive.
* The #kHAL_I2cSlaveTransmitEvent and #kLPHAL_I2cSlaveReceiveEvent 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 #kHAL_I2cSlaveAllEvents constant is provided as
* a convenient way to enable all events.
*
* @param handle i2c slave handle pointer, this should be a static variable.
* @param eventMask Bit mask formed by OR'ing together #hal_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 #kHAL_I2cSlaveAllEvents to enable all events.
*
* @retval #kStatus_HAL_I2cSuccess Slave transfers were successfully started.
* @retval #kStatus_HAL_I2cBusy Slave transfers have already been started on this handle.
*/
hal_i2c_status_t HAL_I2cSlaveTransferNonBlocking(hal_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 handle i2c slave handle pointer, this should be a static variable.
* @retval kStatus_HAL_I2cSuccess Successfully return the count.
*/
hal_i2c_status_t HAL_I2cSlaveTransferAbort(hal_i2c_slave_handle_t handle);
/*!
* @brief Gets the slave transfer remaining bytes during a interrupt non-blocking transfer.
*
* @param handle i2c slave handle pointer, this should be a static variable.
* @param count Number of bytes transferred so far by the non-blocking transaction.
* @retval kStatus_HAL_I2cError An error occurred.
* @retval kStatus_HAL_I2cSuccess Successfully return the count.
*/
hal_i2c_status_t HAL_I2cSlaveTransferGetCount(hal_i2c_slave_handle_t handle, size_t *count);
/*! @} */
#if defined(__cplusplus)
}
#endif /*_cplusplus. */
/*! @} */
#endif /* __HAL_I2C_ADAPTER_H__*/

View File

@@ -0,0 +1,369 @@
/*
* Copyright 2018 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_common.h"
#include "fsl_lpi2c.h"
#include "i2c.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief i2c master state structure. */
typedef struct _hal_i2c_master
{
hal_i2c_master_transfer_callback_t callback;
void *callbackParam;
lpi2c_master_handle_t hardwareHandle;
uint8_t instance;
} hal_i2c_master_t;
/*! @brief i2c slave state structure. */
typedef struct _hal_i2c_slave
{
hal_i2c_slave_transfer_callback_t callback;
void *callbackParam;
hal_i2c_slave_transfer_t transfer;
lpi2c_slave_handle_t hardwareHandle;
uint8_t instance;
} hal_i2c_slave_t;
/*******************************************************************************
* Prototypes
******************************************************************************/
/*******************************************************************************
* Variables
******************************************************************************/
/*! @brief Pointers to i2c bases for each instance. */
static LPI2C_Type *const s_i2cBases[] = LPI2C_BASE_PTRS;
/*******************************************************************************
* Code
******************************************************************************/
hal_i2c_status_t HAL_I2cGetStatus(status_t status)
{
hal_i2c_status_t returnStatus;
switch (status)
{
case kStatus_Success:
{
returnStatus = kStatus_HAL_I2cSuccess;
break;
}
case kStatus_LPI2C_Busy:
{
returnStatus = kStatus_HAL_I2cBusy;
break;
}
case kStatus_LPI2C_Idle:
{
returnStatus = kStatus_HAL_I2cIdle;
break;
}
case kStatus_LPI2C_Nak:
{
returnStatus = kStatus_HAL_I2cNak;
break;
}
case kStatus_LPI2C_ArbitrationLost:
{
returnStatus = kStatus_HAL_I2cArbitrationLost;
break;
}
case kStatus_LPI2C_Timeout:
{
returnStatus = kStatus_HAL_I2cTimeout;
break;
}
default:
{
returnStatus = kStatus_HAL_I2cError;
break;
}
}
return returnStatus;
}
static void HAL_I2cMasterCallback(LPI2C_Type *base, lpi2c_master_handle_t *handle, status_t status, void *callbackParam)
{
hal_i2c_master_t *i2cMasterHandle;
assert(callbackParam);
i2cMasterHandle = (hal_i2c_master_t *)callbackParam;
if (i2cMasterHandle->callback)
{
i2cMasterHandle->callback(i2cMasterHandle, HAL_I2cGetStatus(status), i2cMasterHandle->callbackParam);
}
}
static void HAL_I2cSlaveCallback(LPI2C_Type *base, lpi2c_slave_transfer_t *xfer, void *callbackParam)
{
hal_i2c_slave_t *i2cSlaveHandle;
assert(callbackParam);
i2cSlaveHandle = (hal_i2c_slave_t *)callbackParam;
if (i2cSlaveHandle->callback)
{
i2cSlaveHandle->transfer.event = (hal_i2c_slave_transfer_event_t)xfer->event;
i2cSlaveHandle->transfer.data = xfer->data;
i2cSlaveHandle->transfer.dataSize = xfer->dataSize;
i2cSlaveHandle->transfer.completionStatus = HAL_I2cGetStatus(xfer->completionStatus);
i2cSlaveHandle->transfer.transferredCount = xfer->transferredCount;
i2cSlaveHandle->callback(i2cSlaveHandle, &i2cSlaveHandle->transfer, i2cSlaveHandle->callbackParam);
xfer->data = i2cSlaveHandle->transfer.data;
xfer->dataSize = i2cSlaveHandle->transfer.dataSize;
}
}
hal_i2c_status_t HAL_I2cMasterInit(hal_i2c_master_handle_t handle, const hal_i2c_master_config_t *config)
{
hal_i2c_master_t *i2cMasterHandle;
lpi2c_master_config_t i2cConfig;
assert(handle);
assert(config);
if (HAL_I2C_MASTER_HANDLE_SIZE < sizeof(hal_i2c_master_t))
{
return kStatus_HAL_I2cError;
}
i2cMasterHandle = (hal_i2c_master_t *)handle;
LPI2C_MasterGetDefaultConfig(&i2cConfig);
i2cConfig.enableMaster = config->enableMaster;
i2cConfig.baudRate_Hz = config->baudRate_Bps;
i2cMasterHandle->instance = config->instance;
LPI2C_MasterInit(s_i2cBases[i2cMasterHandle->instance], &i2cConfig, config->srcClock_Hz);
return kStatus_HAL_I2cSuccess;
}
hal_i2c_status_t HAL_I2cSlaveInit(hal_i2c_slave_handle_t handle, const hal_i2c_slave_config_t *config)
{
hal_i2c_slave_t *i2cSlaveHandle;
lpi2c_slave_config_t i2cConfig;
assert(handle);
assert(config);
if (HAL_I2C_SLAVE_HANDLE_SIZE < sizeof(hal_i2c_slave_t))
{
return kStatus_HAL_I2cError;
}
i2cSlaveHandle = (hal_i2c_slave_t *)handle;
LPI2C_SlaveGetDefaultConfig(&i2cConfig);
i2cConfig.enableSlave = config->enableSlave;
i2cConfig.address0 = config->slaveAddress;
i2cSlaveHandle->instance = config->instance;
LPI2C_SlaveInit(s_i2cBases[i2cSlaveHandle->instance], &i2cConfig, config->srcClock_Hz);
return kStatus_HAL_I2cSuccess;
}
hal_i2c_status_t HAL_I2cMasterDeinit(hal_i2c_master_handle_t handle)
{
hal_i2c_master_t *i2cMasterHandle;
assert(handle);
i2cMasterHandle = (hal_i2c_master_t *)handle;
LPI2C_MasterDeinit(s_i2cBases[i2cMasterHandle->instance]);
return kStatus_HAL_I2cSuccess;
}
hal_i2c_status_t HAL_I2cSlaveDeinit(hal_i2c_slave_handle_t handle)
{
hal_i2c_slave_t *i2cSlaveHandle;
assert(handle);
i2cSlaveHandle = (hal_i2c_slave_t *)handle;
LPI2C_SlaveDeinit(s_i2cBases[i2cSlaveHandle->instance]);
return kStatus_HAL_I2cSuccess;
}
hal_i2c_status_t HAL_I2cMasterWriteBlocking(hal_i2c_master_handle_t handle,
const uint8_t *txBuff,
size_t txSize,
uint32_t flags)
{
return kStatus_HAL_I2cError;
}
hal_i2c_status_t HAL_I2cMasterReadBlocking(hal_i2c_master_handle_t handle,
uint8_t *rxBuff,
size_t rxSize,
uint32_t flags)
{
return kStatus_HAL_I2cError;
}
hal_i2c_status_t HAL_I2cSlaveWriteBlocking(hal_i2c_slave_handle_t handle, const uint8_t *txBuff, size_t txSize)
{
return kStatus_HAL_I2cError;
}
hal_i2c_status_t HAL_I2cSlaveReadBlocking(hal_i2c_slave_handle_t handle, uint8_t *rxBuff, size_t rxSize)
{
return kStatus_HAL_I2cError;
}
hal_i2c_status_t HAL_I2cMasterTransferBlocking(hal_i2c_master_handle_t handle, hal_i2c_master_transfer_t *xfer)
{
hal_i2c_master_t *i2cMasterHandle;
lpi2c_master_transfer_t transfer;
assert(handle);
assert(xfer);
i2cMasterHandle = (hal_i2c_master_t *)handle;
transfer.flags = xfer->flags;
transfer.slaveAddress = xfer->slaveAddress;
transfer.direction = (kHAL_I2cRead == xfer->direction) ? kLPI2C_Read : kLPI2C_Write;
transfer.subaddress = xfer->subaddress;
transfer.subaddressSize = xfer->subaddressSize;
transfer.data = xfer->data;
transfer.dataSize = xfer->dataSize;
return HAL_I2cGetStatus(LPI2C_MasterTransferBlocking(s_i2cBases[i2cMasterHandle->instance], &transfer));
}
hal_i2c_status_t HAL_I2cMasterTransferInstallCallback(hal_i2c_master_handle_t handle,
hal_i2c_master_transfer_callback_t callback,
void *callbackParam)
{
hal_i2c_master_t *i2cMasterHandle;
assert(handle);
i2cMasterHandle = (hal_i2c_master_t *)handle;
i2cMasterHandle->callback = callback;
i2cMasterHandle->callbackParam = callbackParam;
LPI2C_MasterTransferCreateHandle(s_i2cBases[i2cMasterHandle->instance], &i2cMasterHandle->hardwareHandle,
HAL_I2cMasterCallback, i2cMasterHandle);
return kStatus_HAL_I2cSuccess;
}
hal_i2c_status_t HAL_I2cMasterTransferNonBlocking(hal_i2c_master_handle_t handle, hal_i2c_master_transfer_t *xfer)
{
hal_i2c_master_t *i2cMasterHandle;
lpi2c_master_transfer_t transfer;
assert(handle);
assert(xfer);
i2cMasterHandle = (hal_i2c_master_t *)handle;
transfer.flags = xfer->flags;
transfer.slaveAddress = xfer->slaveAddress;
transfer.direction = (kHAL_I2cRead == xfer->direction) ? kLPI2C_Read : kLPI2C_Write;
transfer.subaddress = xfer->subaddress;
transfer.subaddressSize = xfer->subaddressSize;
transfer.data = xfer->data;
transfer.dataSize = xfer->dataSize;
return HAL_I2cGetStatus(LPI2C_MasterTransferNonBlocking(s_i2cBases[i2cMasterHandle->instance],
&i2cMasterHandle->hardwareHandle, &transfer));
}
hal_i2c_status_t HAL_I2cMasterTransferGetCount(hal_i2c_master_handle_t handle, size_t *count)
{
hal_i2c_master_t *i2cMasterHandle;
assert(handle);
assert(count);
i2cMasterHandle = (hal_i2c_master_t *)handle;
return HAL_I2cGetStatus(
LPI2C_MasterTransferGetCount(s_i2cBases[i2cMasterHandle->instance], &i2cMasterHandle->hardwareHandle, count));
}
hal_i2c_status_t HAL_I2cMasterTransferAbort(hal_i2c_master_handle_t handle)
{
hal_i2c_master_t *i2cMasterHandle;
assert(handle);
i2cMasterHandle = (hal_i2c_master_t *)handle;
LPI2C_MasterTransferAbort(s_i2cBases[i2cMasterHandle->instance], &i2cMasterHandle->hardwareHandle);
return kStatus_HAL_I2cSuccess;
}
hal_i2c_status_t HAL_I2cSlaveTransferInstallCallback(hal_i2c_slave_handle_t handle,
hal_i2c_slave_transfer_callback_t callback,
void *callbackParam)
{
hal_i2c_slave_t *i2cSlaveHandle;
assert(handle);
i2cSlaveHandle = (hal_i2c_slave_t *)handle;
i2cSlaveHandle->callback = callback;
i2cSlaveHandle->callbackParam = callbackParam;
LPI2C_SlaveTransferCreateHandle(s_i2cBases[i2cSlaveHandle->instance], &i2cSlaveHandle->hardwareHandle,
HAL_I2cSlaveCallback, i2cSlaveHandle);
return kStatus_HAL_I2cSuccess;
}
hal_i2c_status_t HAL_I2cSlaveTransferNonBlocking(hal_i2c_slave_handle_t handle, uint32_t eventMask)
{
hal_i2c_slave_t *i2cSlaveHandle;
assert(handle);
i2cSlaveHandle = (hal_i2c_slave_t *)handle;
return HAL_I2cGetStatus(LPI2C_SlaveTransferNonBlocking(s_i2cBases[i2cSlaveHandle->instance],
&i2cSlaveHandle->hardwareHandle, eventMask));
}
hal_i2c_status_t HAL_I2cSlaveTransferAbort(hal_i2c_slave_handle_t handle)
{
hal_i2c_slave_t *i2cSlaveHandle;
assert(handle);
i2cSlaveHandle = (hal_i2c_slave_t *)handle;
LPI2C_SlaveTransferAbort(s_i2cBases[i2cSlaveHandle->instance], &i2cSlaveHandle->hardwareHandle);
return kStatus_HAL_I2cSuccess;
}
hal_i2c_status_t HAL_I2cSlaveTransferGetCount(hal_i2c_slave_handle_t handle, size_t *count)
{
hal_i2c_slave_t *i2cSlaveHandle;
assert(handle);
assert(count);
i2cSlaveHandle = (hal_i2c_slave_t *)handle;
return HAL_I2cGetStatus(
LPI2C_SlaveTransferGetCount(s_i2cBases[i2cSlaveHandle->instance], &i2cSlaveHandle->hardwareHandle, count));
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2016, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_ili9341.h"
void FT9341_Init(ili9341_send_byte_t _writeData, ili9341_send_byte_t _writeCommand)
{
_writeCommand(ILI9341_CMD_PWRA);
_writeData(0x39);
_writeData(0x2C);
_writeData(0x00);
_writeData(0x34);
_writeData(0x02);
_writeCommand(ILI9341_CMD_PWRB);
_writeData(0x00);
_writeData(0xC1);
_writeData(0x30);
_writeCommand(ILI9341_CMD_DTCA);
_writeData(0x85);
_writeData(0x00);
_writeData(0x78);
_writeCommand(ILI9341_CMD_DTCB);
_writeData(0x00);
_writeData(0x00);
_writeCommand(ILI9341_CMD_PWRSEQ);
_writeData(0x64);
_writeData(0x03);
_writeData(0x12);
_writeData(0x81);
_writeCommand(ILI9341_CMD_PRC);
_writeData(0x20);
_writeCommand(ILI9341_CMD_PWR1);
_writeData(0x23);
_writeCommand(ILI9341_CMD_PWR2);
_writeData(0x10);
_writeCommand(ILI9341_CMD_VCOM1);
_writeData(0x3E);
_writeData(0x28);
_writeCommand(ILI9341_CMD_VCOM2);
_writeData(0x86);
_writeCommand(ILI9341_CMD_MAC);
_writeData(0x40);
_writeCommand(ILI9341_CMD_PIXELFORMAT);
_writeData(0x55);
_writeCommand(ILI9341_CMD_FRC);
_writeData(0x00);
_writeData(0x18);
_writeCommand(ILI9341_CMD_DFC);
_writeData(0x08);
_writeData(0x82);
_writeData(0x27);
_writeCommand(ILI9341_CMD_3GAMMAEN);
_writeData(0x00);
_writeCommand(ILI9341_CMD_COLADDR);
_writeData(0x00);
_writeData(0x00);
_writeData(0x00);
_writeData(0xEF);
_writeCommand(ILI9341_CMD_PAGEADDR);
_writeData(0x00);
_writeData(0x00);
_writeData(0x01);
_writeData(0x3F);
_writeCommand(ILI9341_CMD_GAMMA);
_writeData(0x01);
_writeCommand(ILI9341_CMD_PGAMMA);
_writeData(0x0F);
_writeData(0x31);
_writeData(0x2B);
_writeData(0x0C);
_writeData(0x0E);
_writeData(0x08);
_writeData(0x4E);
_writeData(0xF1);
_writeData(0x37);
_writeData(0x07);
_writeData(0x10);
_writeData(0x03);
_writeData(0x0E);
_writeData(0x09);
_writeData(0x00);
_writeCommand(ILI9341_CMD_NGAMMA);
_writeData(0x00);
_writeData(0x0E);
_writeData(0x14);
_writeData(0x03);
_writeData(0x11);
_writeData(0x07);
_writeData(0x31);
_writeData(0xC1);
_writeData(0x48);
_writeData(0x08);
_writeData(0x0F);
_writeData(0x0C);
_writeData(0x31);
_writeData(0x36);
_writeData(0x0F);
_writeCommand(ILI9341_CMD_SLEEPOUT);
_writeCommand(ILI9341_CMD_DISPLAYON);
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 2016, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _FSL_ILI9341_H_
#define _FSL_ILI9341_H_
#include "fsl_common.h"
/*!
* @addtogroup ili9341
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
/* Register defines */
#define ILI9341_CMD_RST 0x01
#define ILI9341_CMD_SLEEPOUT 0x11
#define ILI9341_CMD_GAMMA 0x26
#define ILI9341_CMD_DISPLAYOFF 0x28
#define ILI9341_CMD_DISPLAYON 0x29
#define ILI9341_CMD_COLADDR 0x2A
#define ILI9341_CMD_PAGEADDR 0x2B
#define ILI9341_CMD_GRAM 0x2C
#define ILI9341_CMD_MAC 0x36
#define ILI9341_CMD_PIXELFORMAT 0x3A
#define ILI9341_CMD_WDB 0x51
#define ILI9341_CMD_WCD 0x53
#define ILI9341_CMD_RGBINTERFACE 0xB0
#define ILI9341_CMD_FRC 0xB1
#define ILI9341_CMD_BPC 0xB5
#define ILI9341_CMD_DFC 0xB6
#define ILI9341_CMD_PWR1 0xC0
#define ILI9341_CMD_PWR2 0xC1
#define ILI9341_CMD_VCOM1 0xC5
#define ILI9341_CMD_VCOM2 0xC7
#define ILI9341_CMD_PWRA 0xCB
#define ILI9341_CMD_PWRB 0xCF
#define ILI9341_CMD_PGAMMA 0xE0
#define ILI9341_CMD_NGAMMA 0xE1
#define ILI9341_CMD_DTCA 0xE8
#define ILI9341_CMD_DTCB 0xEA
#define ILI9341_CMD_PWRSEQ 0xED
#define ILI9341_CMD_3GAMMAEN 0xF2
#define ILI9341_CMD_INTERFACE 0xF6
#define ILI9341_CMD_PRC 0xF7
#define ILI9341_CMD_INVON 0x21
#define ILI9341_CMD_INVOFF 0x20
typedef void (*ili9341_send_byte_t)(uint8_t);
void FT9341_Init(ili9341_send_byte_t _writeData, ili9341_send_byte_t _writeCommand);
#endif

View File

@@ -0,0 +1,423 @@
/*
* Copyright 2018-2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/*! *********************************************************************************
*************************************************************************************
* Include
*************************************************************************************
********************************************************************************** */
#include "fsl_common.h"
#include "generic_list.h"
static list_status_t LIST_Scan(list_handle_t list, list_element_handle_t newElement)
{
list_element_handle_t element = list->head;
while (element != NULL)
{
if (element == newElement)
{
return kLIST_DuplicateError;
}
element = element->next;
}
return kLIST_Ok;
}
/*! *********************************************************************************
*************************************************************************************
* Public functions
*************************************************************************************
********************************************************************************** */
/*! *********************************************************************************
* \brief Initialises the list descriptor.
*
* \param[in] list - LIST_ handle to init.
* max - Maximum number of elements in list. 0 for unlimited.
*
* \return void.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
void LIST_Init(list_handle_t list, uint32_t max)
{
list->head = NULL;
list->tail = NULL;
list->max = (uint16_t)max;
list->size = 0;
}
/*! *********************************************************************************
* \brief Gets the list that contains the given element.
*
* \param[in] element - Handle of the element.
*
* \return NULL if element is orphan.
* Handle of the list the element is inserted into.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_handle_t LIST_GetList(list_element_handle_t element)
{
return element->list;
}
/*! *********************************************************************************
* \brief Links element to the tail of the list.
*
* \param[in] list - ID of list to insert into.
* element - element to add
*
* \return kLIST_Full if list is full.
* kLIST_Ok if insertion was successful.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_status_t LIST_AddTail(list_handle_t list, list_element_handle_t element)
{
uint32_t regPrimask = DisableGlobalIRQ();
if ((list->max != 0U) && (list->max == list->size))
{
EnableGlobalIRQ(regPrimask);
return kLIST_Full;
}
if (kLIST_DuplicateError == LIST_Scan(list, element))
{
EnableGlobalIRQ(regPrimask);
return kLIST_DuplicateError;
}
if (list->size == 0U)
{
list->head = element;
}
else
{
list->tail->next = element;
}
element->prev = list->tail;
element->next = NULL;
element->list = list;
list->tail = element;
list->size++;
EnableGlobalIRQ(regPrimask);
return kLIST_Ok;
}
/*! *********************************************************************************
* \brief Links element to the head of the list.
*
* \param[in] list - ID of list to insert into.
* element - element to add
*
* \return kLIST_Full if list is full.
* kLIST_Ok if insertion was successful.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_status_t LIST_AddHead(list_handle_t list, list_element_handle_t element)
{
uint32_t regPrimask = DisableGlobalIRQ();
if ((list->max != 0U) && (list->max == list->size))
{
EnableGlobalIRQ(regPrimask);
return kLIST_Full;
}
if (kLIST_DuplicateError == LIST_Scan(list, element))
{
EnableGlobalIRQ(regPrimask);
return kLIST_DuplicateError;
}
if (list->size == 0U)
{
list->tail = element;
}
else
{
list->head->prev = element;
}
element->next = list->head;
element->prev = NULL;
element->list = list;
list->head = element;
list->size++;
EnableGlobalIRQ(regPrimask);
return kLIST_Ok;
}
/*! *********************************************************************************
* \brief Unlinks element from the head of the list.
*
* \param[in] list - ID of list to remove from.
*
* \return NULL if list is empty.
* ID of removed element(pointer) if removal was successful.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_element_handle_t LIST_RemoveHead(list_handle_t list)
{
list_element_handle_t element;
uint32_t regPrimask = DisableGlobalIRQ();
if ((NULL == list) || (list->size == 0U))
{
EnableGlobalIRQ(regPrimask);
return NULL; /*LIST_ is empty*/
}
element = list->head;
list->size--;
if (list->size == 0U)
{
list->tail = NULL;
}
else
{
element->next->prev = NULL;
}
list->head = element->next; /*Is NULL if element is head*/
element->list = NULL;
EnableGlobalIRQ(regPrimask);
return element;
}
/*! *********************************************************************************
* \brief Gets head element ID.
*
* \param[in] list - ID of list.
*
* \return NULL if list is empty.
* ID of head element if list is not empty.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_element_handle_t LIST_GetHead(list_handle_t list)
{
return list->head;
}
/*! *********************************************************************************
* \brief Gets next element ID.
*
* \param[in] element - ID of the element.
*
* \return NULL if element is tail.
* ID of next element if exists.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_element_handle_t LIST_GetNext(list_element_handle_t element)
{
return element->next;
}
/*! *********************************************************************************
* \brief Gets previous element ID.
*
* \param[in] element - ID of the element.
*
* \return NULL if element is head.
* ID of previous element if exists.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_element_handle_t LIST_GetPrev(list_element_handle_t element)
{
return element->prev;
}
/*! *********************************************************************************
* \brief Unlinks an element from its list.
*
* \param[in] element - ID of the element to remove.
*
* \return kLIST_OrphanElement if element is not part of any list.
* kLIST_Ok if removal was successful.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_status_t LIST_RemoveElement(list_element_handle_t element)
{
if (element->list == NULL)
{
return kLIST_OrphanElement; /*Element was previusly removed or never added*/
}
uint32_t regPrimask = DisableGlobalIRQ();
if (element->prev == NULL) /*Element is head or solo*/
{
element->list->head = element->next; /*is null if solo*/
}
if (element->next == NULL) /*Element is tail or solo*/
{
element->list->tail = element->prev; /*is null if solo*/
}
if (element->prev != NULL) /*Element is not head*/
{
element->prev->next = element->next;
}
if (element->next != NULL) /*Element is not tail*/
{
element->next->prev = element->prev;
}
element->list->size--;
element->list = NULL;
EnableGlobalIRQ(regPrimask);
return kLIST_Ok;
}
/*! *********************************************************************************
* \brief Links an element in the previous position relative to a given member
* of a list.
*
* \param[in] element - ID of a member of a list.
* newElement - new element to insert before the given member.
*
* \return kLIST_OrphanElement if element is not part of any list.
* kLIST_Full if list is full.
* kLIST_Ok if insertion was successful.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
list_status_t LIST_AddPrevElement(list_element_handle_t element, list_element_handle_t newElement)
{
if (element->list == NULL)
{
return kLIST_OrphanElement; /*Element was previusly removed or never added*/
}
uint32_t regPrimask = DisableGlobalIRQ();
if ((element->list->max != 0U) && (element->list->max == element->list->size))
{
EnableGlobalIRQ(regPrimask);
return kLIST_Full;
}
if (kLIST_DuplicateError == LIST_Scan(element->list, newElement))
{
EnableGlobalIRQ(regPrimask);
return kLIST_DuplicateError;
}
if (element->prev == NULL) /*Element is list head*/
{
element->list->head = newElement;
}
else
{
element->prev->next = newElement;
}
newElement->list = element->list;
element->list->size++;
newElement->next = element;
newElement->prev = element->prev;
element->prev = newElement;
EnableGlobalIRQ(regPrimask);
return kLIST_Ok;
}
/*! *********************************************************************************
* \brief Gets the current size of a list.
*
* \param[in] list - ID of the list.
*
* \return Current size of the list.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
uint32_t LIST_GetSize(list_handle_t list)
{
return list->size;
}
/*! *********************************************************************************
* \brief Gets the number of free places in the list.
*
* \param[in] list - ID of the list.
*
* \return Available size of the list.
*
* \pre
*
* \post
*
* \remarks
*
********************************************************************************** */
uint32_t LIST_GetAvailableSize(list_handle_t list)
{
return ((uint32_t)list->max - (uint32_t)list->size);
}

View File

@@ -0,0 +1,191 @@
/*
* Copyright 2018-2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _GENERIC_LIST_H_
#define _GENERIC_LIST_H_
/*!
* @addtogroup GenericList
* @{
*/
/*!*********************************************************************************
*************************************************************************************
* Include
*************************************************************************************
********************************************************************************** */
/*! *********************************************************************************
*************************************************************************************
* Public macro definitions
*************************************************************************************
********************************************************************************** */
/*! *********************************************************************************
*************************************************************************************
* Public type definitions
*************************************************************************************
********************************************************************************** */
/*! @brief The list status */
typedef enum _list_status
{
kLIST_Ok = kStatus_Success, /*!< Success */
kLIST_DuplicateError = MAKE_STATUS(kStatusGroup_LIST, 1), /*!< Duplicate Error */
kLIST_Full = MAKE_STATUS(kStatusGroup_LIST, 2), /*!< FULL */
kLIST_Empty = MAKE_STATUS(kStatusGroup_LIST, 3), /*!< Empty */
kLIST_OrphanElement = MAKE_STATUS(kStatusGroup_LIST, 4), /*!< Orphan Element */
} list_status_t;
/*! @brief The list structure*/
typedef struct list_label
{
struct list_element_tag *head; /*!< list head */
struct list_element_tag *tail; /*!< list tail */
uint16_t size; /*!< list size */
uint16_t max; /*!< list max number of elements */
} list_label_t, *list_handle_t;
/*! @brief The list element*/
typedef struct list_element_tag
{
struct list_element_tag *next; /*!< next list element */
struct list_element_tag *prev; /*!< previous list element */
struct list_label *list; /*!< pointer to the list */
} list_element_t, *list_element_handle_t;
/*! *********************************************************************************
*************************************************************************************
* Public prototypes
*************************************************************************************
********************************************************************************** */
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif /* _cplusplus */
/*!
* @brief Initialize the list.
*
* This function initialize the list.
*
* @param list - List handle to initialize.
* @param max - Maximum number of elements in list. 0 for unlimited.
*/
void LIST_Init(list_handle_t list, uint32_t max);
/*!
* @brief Gets the list that contains the given element.
*
*
* @param element - Handle of the element.
* @retval NULL if element is orphan, Handle of the list the element is inserted into.
*/
list_handle_t LIST_GetList(list_element_handle_t element);
/*!
* @brief Links element to the head of the list.
*
* @param list - Handle of the list.
* @param element - Handle of the element.
* @retval kLIST_Full if list is full, kLIST_Ok if insertion was successful.
*/
list_status_t LIST_AddHead(list_handle_t list, list_element_handle_t element);
/*!
* @brief Links element to the tail of the list.
*
* @param list - Handle of the list.
* @param element - Handle of the element.
* @retval kLIST_Full if list is full, kLIST_Ok if insertion was successful.
*/
list_status_t LIST_AddTail(list_handle_t list, list_element_handle_t element);
/*!
* @brief Unlinks element from the head of the list.
*
* @param list - Handle of the list.
*
* @retval NULL if list is empty, handle of removed element(pointer) if removal was successful.
*/
list_element_handle_t LIST_RemoveHead(list_handle_t list);
/*!
* @brief Gets head element handle.
*
* @param list - Handle of the list.
*
* @retval NULL if list is empty, handle of removed element(pointer) if removal was successful.
*/
list_element_handle_t LIST_GetHead(list_handle_t list);
/*!
* @brief Gets next element handle for given element handle.
*
* @param element - Handle of the element.
*
* @retval NULL if list is empty, handle of removed element(pointer) if removal was successful.
*/
list_element_handle_t LIST_GetNext(list_element_handle_t element);
/*!
* @brief Gets previous element handle for given element handle.
*
* @param element - Handle of the element.
*
* @retval NULL if list is empty, handle of removed element(pointer) if removal was successful.
*/
list_element_handle_t LIST_GetPrev(list_element_handle_t element);
/*!
* @brief Unlinks an element from its list.
*
* @param element - Handle of the element.
*
* @retval kLIST_OrphanElement if element is not part of any list.
* @retval kLIST_Ok if removal was successful.
*/
list_status_t LIST_RemoveElement(list_element_handle_t element);
/*!
* @brief Links an element in the previous position relative to a given member of a list.
*
* @param element - Handle of the element.
* @param newElement - New element to insert before the given member.
*
* @retval kLIST_OrphanElement if element is not part of any list.
* @retval kLIST_Ok if removal was successful.
*/
list_status_t LIST_AddPrevElement(list_element_handle_t element, list_element_handle_t newElement);
/*!
* @brief Gets the current size of a list.
*
* @param list - Handle of the list.
*
* @retval Current size of the list.
*/
uint32_t LIST_GetSize(list_handle_t list);
/*!
* @brief Gets the number of free places in the list.
*
* @param list - Handle of the list.
*
* @retval Available size of the list.
*/
uint32_t LIST_GetAvailableSize(list_handle_t list);
/* @} */
#if defined(__cplusplus)
}
#endif
/*! @}*/
#endif /*_GENERIC_LIST_H_*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,548 @@
/*
* Copyright 2018 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __SERIAL_MANAGER_H__
#define __SERIAL_MANAGER_H__
/*!
* @addtogroup serialmanager
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
#ifdef DEBUG_CONSOLE_TRANSFER_NON_BLOCKING
/*! @brief Enable or disable serial manager non-blocking mode (1 - enable, 0 - disable) */
#define SERIAL_MANAGER_NON_BLOCKING_MODE (1U)
#else
#ifndef SERIAL_MANAGER_NON_BLOCKING_MODE
#define SERIAL_MANAGER_NON_BLOCKING_MODE (0U)
#endif
#endif
/*! @brief Enable or disable uart port (1 - enable, 0 - disable) */
#ifndef SERIAL_PORT_TYPE_UART
#define SERIAL_PORT_TYPE_UART (1U)
#endif
/*! @brief Enable or disable USB CDC port (1 - enable, 0 - disable) */
#ifndef SERIAL_PORT_TYPE_USBCDC
#define SERIAL_PORT_TYPE_USBCDC (0U)
#endif
/*! @brief Enable or disable SWO port (1 - enable, 0 - disable) */
#ifndef SERIAL_PORT_TYPE_SWO
#define SERIAL_PORT_TYPE_SWO (0U)
#endif
/*! @brief Enable or disable USB CDC virtual port (1 - enable, 0 - disable) */
#ifndef SERIAL_PORT_TYPE_USBCDC_VIRTUAL
#define SERIAL_PORT_TYPE_USBCDC_VIRTUAL (0U)
#endif
/*! @brief Set serial manager write handle size */
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#define SERIAL_MANAGER_WRITE_HANDLE_SIZE (44U)
#define SERIAL_MANAGER_READ_HANDLE_SIZE (44U)
#else
#define SERIAL_MANAGER_WRITE_HANDLE_SIZE (4U)
#define SERIAL_MANAGER_READ_HANDLE_SIZE (4U)
#endif
#if (defined(SERIAL_PORT_TYPE_UART) && (SERIAL_PORT_TYPE_UART > 0U))
#include "serial_port_uart.h"
#endif
#if (defined(SERIAL_PORT_TYPE_USBCDC) && (SERIAL_PORT_TYPE_USBCDC > 0U))
#if !(defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#error The serial manager blocking mode cannot be supported for USB CDC.
#endif
#include "serial_port_usb.h"
#endif
#if (defined(SERIAL_PORT_TYPE_SWO) && (SERIAL_PORT_TYPE_SWO > 0U))
#include "serial_port_swo.h"
#endif
#if (defined(SERIAL_PORT_TYPE_USBCDC_VIRTUAL) && (SERIAL_PORT_TYPE_USBCDC_VIRTUAL > 0U))
#if !(defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#error The serial manager blocking mode cannot be supported for USB CDC.
#endif
#include "serial_port_usb_virtual.h"
#endif
#define SERIAL_MANAGER_HANDLE_SIZE_TEMP 0U
#if (defined(SERIAL_PORT_TYPE_UART) && (SERIAL_PORT_TYPE_UART > 0U))
#if (SERIAL_PORT_UART_HANDLE_SIZE > SERIAL_MANAGER_HANDLE_SIZE_TEMP)
#undef SERIAL_MANAGER_HANDLE_SIZE_TEMP
#define SERIAL_MANAGER_HANDLE_SIZE_TEMP SERIAL_PORT_UART_HANDLE_SIZE
#endif
#endif
#if (defined(SERIAL_PORT_TYPE_USBCDC) && (SERIAL_PORT_TYPE_USBCDC > 0U))
#if (SERIAL_PORT_USB_CDC_HANDLE_SIZE > SERIAL_MANAGER_HANDLE_SIZE_TEMP)
#undef SERIAL_MANAGER_HANDLE_SIZE_TEMP
#define SERIAL_MANAGER_HANDLE_SIZE_TEMP SERIAL_PORT_USB_CDC_HANDLE_SIZE
#endif
#endif
#if (defined(SERIAL_PORT_TYPE_SWO) && (SERIAL_PORT_TYPE_SWO > 0U))
#if (SERIAL_PORT_SWO_HANDLE_SIZE > SERIAL_MANAGER_HANDLE_SIZE_TEMP)
#undef SERIAL_MANAGER_HANDLE_SIZE_TEMP
#define SERIAL_MANAGER_HANDLE_SIZE_TEMP SERIAL_PORT_SWO_HANDLE_SIZE
#endif
#endif
#if (defined(SERIAL_PORT_TYPE_USBCDC_VIRTUAL) && (SERIAL_PORT_TYPE_USBCDC_VIRTUAL > 0U))
#if (SERIAL_PORT_USB_VIRTUAL_HANDLE_SIZE > SERIAL_MANAGER_HANDLE_SIZE_TEMP)
#undef SERIAL_MANAGER_HANDLE_SIZE_TEMP
#define SERIAL_MANAGER_HANDLE_SIZE_TEMP SERIAL_PORT_USB_VIRTUAL_HANDLE_SIZE
#endif
#endif
/*! @brief SERIAL_PORT_UART_HANDLE_SIZE/SERIAL_PORT_USB_CDC_HANDLE_SIZE + serial manager dedicated size */
#if ((defined(SERIAL_MANAGER_HANDLE_SIZE_TEMP) && (SERIAL_MANAGER_HANDLE_SIZE_TEMP > 0U)))
#else
#error SERIAL_PORT_TYPE_UART, SERIAL_PORT_TYPE_USBCDC, SERIAL_PORT_TYPE_SWO and SERIAL_PORT_TYPE_USBCDC_VIRTUAL should not be cleared at same time.
#endif
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#define SERIAL_MANAGER_HANDLE_SIZE (SERIAL_MANAGER_HANDLE_SIZE_TEMP + 120U)
#else
#define SERIAL_MANAGER_HANDLE_SIZE (SERIAL_MANAGER_HANDLE_SIZE_TEMP + 12U)
#endif
#define SERIAL_MANAGER_USE_COMMON_TASK (1U)
#define SERIAL_MANAGER_TASK_PRIORITY (2U)
#define SERIAL_MANAGER_TASK_STACK_SIZE (1000U)
typedef void *serial_handle_t;
typedef void *serial_write_handle_t;
typedef void *serial_read_handle_t;
/*! @brief serial port type*/
typedef enum _serial_port_type
{
kSerialPort_Uart = 1U, /*!< Serial port UART */
kSerialPort_UsbCdc, /*!< Serial port USB CDC */
kSerialPort_Swo, /*!< Serial port SWO */
kSerialPort_UsbCdcVirtual, /*!< Serial port USB CDC Virtual */
} serial_port_type_t;
/*! @brief serial manager config structure*/
typedef struct _serial_manager_config
{
uint8_t *ringBuffer; /*!< Ring buffer address, it is used to buffer data received by the hardware.
Besides, the memory space cannot be free during the lifetime of the serial
manager module. */
uint32_t ringBufferSize; /*!< The size of the ring buffer */
serial_port_type_t type; /*!< Serial port type */
void *portConfig; /*!< Serial port configuration */
} serial_manager_config_t;
/*! @brief serial manager error code*/
typedef enum _serial_manager_status
{
kStatus_SerialManager_Success = kStatus_Success, /*!< Success */
kStatus_SerialManager_Error = MAKE_STATUS(kStatusGroup_SERIALMANAGER, 1), /*!< Failed */
kStatus_SerialManager_Busy = MAKE_STATUS(kStatusGroup_SERIALMANAGER, 2), /*!< Busy */
kStatus_SerialManager_Notify = MAKE_STATUS(kStatusGroup_SERIALMANAGER, 3), /*!< Ring buffer is not empty */
kStatus_SerialManager_Canceled =
MAKE_STATUS(kStatusGroup_SERIALMANAGER, 4), /*!< the non-blocking request is canceled */
kStatus_SerialManager_HandleConflict = MAKE_STATUS(kStatusGroup_SERIALMANAGER, 5), /*!< The handle is opened */
kStatus_SerialManager_RingBufferOverflow =
MAKE_STATUS(kStatusGroup_SERIALMANAGER, 6), /*!< The ring buffer is overflowed */
} serial_manager_status_t;
/*! @brief Callback message structure */
typedef struct _serial_manager_callback_message
{
uint8_t *buffer; /*!< Transferred buffer */
uint32_t length; /*!< Transferred data length */
} serial_manager_callback_message_t;
/*! @brief callback function */
typedef void (*serial_manager_callback_t)(void *callbackParam,
serial_manager_callback_message_t *message,
serial_manager_status_t status);
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif /* _cplusplus */
/*!
* @brief Initializes a serial manager module with the serial manager handle and the user configuration structure.
*
* This function configures the Serial Manager module with user-defined settings. The user can configure the
* configuration
* structure. The parameter serialHandle is a pointer to point to a memory space of size #SERIAL_MANAGER_HANDLE_SIZE
* allocated by the caller.
* The Serial Manager module supports two types of serial port, UART (includes UART, USART, LPSCI, LPUART, etc) and USB
* CDC.
* Please refer to #serial_port_type_t for serial port setting. These two types can be set by using
* #serial_manager_config_t.
*
* Example below shows how to use this API to configure the Serial Manager.
* For UART,
* @code
* #define SERIAL_MANAGER_RING_BUFFER_SIZE (256U)
* static uint8_t s_serialHandleBuffer[SERIAL_MANAGER_HANDLE_SIZE];
* static serial_handle_t s_serialHandle = &s_serialHandleBuffer[0];
* static uint8_t s_ringBuffer[SERIAL_MANAGER_RING_BUFFER_SIZE];
*
* serial_manager_config_t config;
* serial_port_uart_config_t uartConfig;
* config.type = kSerialPort_Uart;
* config.ringBuffer = &s_ringBuffer[0];
* config.ringBufferSize = SERIAL_MANAGER_RING_BUFFER_SIZE;
* uartConfig.instance = 0;
* uartConfig.clockRate = 24000000;
* uartConfig.baudRate = 115200;
* uartConfig.parityMode = kSerialManager_UartParityDisabled;
* uartConfig.stopBitCount = kSerialManager_UartOneStopBit;
* uartConfig.enableRx = 1;
* uartConfig.enableTx = 1;
* config.portConfig = &uartConfig;
* SerialManager_Init(s_serialHandle, &config);
* @endcode
* For USB CDC,
* @code
* #define SERIAL_MANAGER_RING_BUFFER_SIZE (256U)
* static uint8_t s_serialHandleBuffer[SERIAL_MANAGER_HANDLE_SIZE];
* static serial_handle_t s_serialHandle = &s_serialHandleBuffer[0];
* static uint8_t s_ringBuffer[SERIAL_MANAGER_RING_BUFFER_SIZE];
*
* serial_manager_config_t config;
* serial_port_usb_cdc_config_t usbCdcConfig;
* config.type = kSerialPort_UsbCdc;
* config.ringBuffer = &s_ringBuffer[0];
* config.ringBufferSize = SERIAL_MANAGER_RING_BUFFER_SIZE;
* usbCdcConfig.controllerIndex = kSerialManager_UsbControllerKhci0;
* config.portConfig = &usbCdcConfig;
* SerialManager_Init(s_serialHandle, &config);
* @endcode
*
* @param serialHandle Pointer to point to a memory space of size #SERIAL_MANAGER_HANDLE_SIZE allocated by the caller.
* @param config Pointer to user-defined configuration structure.
* @retval kStatus_SerialManager_Error An error occurred.
* @retval kStatus_SerialManager_Success The Serial Manager module initialization succeed.
*/
serial_manager_status_t SerialManager_Init(serial_handle_t serialHandle, serial_manager_config_t *config);
/*!
* @brief De-initializes the serial manager module instance.
*
* This function de-initializes the serial manager module instance. If the opened writing or
* reading handle is not closed, the function will return kStatus_SerialManager_Busy.
*
* @param serialHandle The serial manager module handle pointer.
* @retval kStatus_SerialManager_Success The serial manager de-initialization succeed.
* @retval kStatus_SerialManager_Busy Opened reading or writing handle is not closed.
*/
serial_manager_status_t SerialManager_Deinit(serial_handle_t serialHandle);
/*!
* @brief Opens a writing handle for the serial manager module.
*
* This function Opens a writing handle for the serial manager module. If the serial manager needs to
* be used in different tasks, the task should open a dedicated write handle for itself by calling
* #SerialManager_OpenWriteHandle. Since there can only one buffer for transmission for the writing
* handle at the same time, multiple writing handles need to be opened when the multiple transmission
* is needed for a task.
*
* @param serialHandle The serial manager module handle pointer.
* @param writeHandle The serial manager module writing handle pointer.
* @retval kStatus_SerialManager_Error An error occurred.
* @retval kStatus_SerialManager_HandleConflict The writing handle was opened.
* @retval kStatus_SerialManager_Success The writing handle is opened.
*
* Example below shows how to use this API to write data.
* For task 1,
* @code
* static uint8_t s_serialWriteHandleBuffer1[SERIAL_MANAGER_WRITE_HANDLE_SIZE];
* static serial_write_handle_t s_serialWriteHandle1 = &s_serialWriteHandleBuffer1[0];
* static uint8_t s_nonBlockingWelcome1[] = "This is non-blocking writing log for task1!\r\n";
* SerialManager_OpenWriteHandle(serialHandle, s_serialWriteHandle1);
* SerialManager_InstallTxCallback(s_serialWriteHandle1, Task1_SerialManagerTxCallback, s_serialWriteHandle1);
* SerialManager_WriteNonBlocking(s_serialWriteHandle1, s_nonBlockingWelcome1, sizeof(s_nonBlockingWelcome1) - 1);
* @endcode
* For task 2,
* @code
* static uint8_t s_serialWriteHandleBuffer2[SERIAL_MANAGER_WRITE_HANDLE_SIZE];
* static serial_write_handle_t s_serialWriteHandle2 = &s_serialWriteHandleBuffer2[0];
* static uint8_t s_nonBlockingWelcome2[] = "This is non-blocking writing log for task2!\r\n";
* SerialManager_OpenWriteHandle(serialHandle, s_serialWriteHandle2);
* SerialManager_InstallTxCallback(s_serialWriteHandle2, Task2_SerialManagerTxCallback, s_serialWriteHandle2);
* SerialManager_WriteNonBlocking(s_serialWriteHandle2, s_nonBlockingWelcome2, sizeof(s_nonBlockingWelcome2) - 1);
* @endcode
*/
serial_manager_status_t SerialManager_OpenWriteHandle(serial_handle_t serialHandle, serial_write_handle_t writeHandle);
/*!
* @brief Closes a writing handle for the serial manager module.
*
* This function Closes a writing handle for the serial manager module.
*
* @param writeHandle The serial manager module writing handle pointer.
* @retval kStatus_SerialManager_Success The writing handle is closed.
*/
serial_manager_status_t SerialManager_CloseWriteHandle(serial_write_handle_t writeHandle);
/*!
* @brief Opens a reading handle for the serial manager module.
*
* This function Opens a reading handle for the serial manager module. The reading handle can not be
* opened multiple at the same time. The error code kStatus_SerialManager_Busy would be returned when
* the previous reading handle is not closed. And There can only be one buffer for receiving for the
* reading handle at the same time.
*
* @param serialHandle The serial manager module handle pointer.
* @param readHandle The serial manager module reading handle pointer.
* @retval kStatus_SerialManager_Error An error occurred.
* @retval kStatus_SerialManager_Success The reading handle is opened.
* @retval kStatus_SerialManager_Busy Previous reading handle is not closed.
*
* Example below shows how to use this API to read data.
* @code
* static uint8_t s_serialReadHandleBuffer[SERIAL_MANAGER_READ_HANDLE_SIZE];
* static serial_read_handle_t s_serialReadHandle = &s_serialReadHandleBuffer[0];
* SerialManager_OpenReadHandle(serialHandle, s_serialReadHandle);
* static uint8_t s_nonBlockingBuffer[64];
* SerialManager_InstallRxCallback(s_serialReadHandle, APP_SerialManagerRxCallback, s_serialReadHandle);
* SerialManager_ReadNonBlocking(s_serialReadHandle, s_nonBlockingBuffer, sizeof(s_nonBlockingBuffer));
* @endcode
*/
serial_manager_status_t SerialManager_OpenReadHandle(serial_handle_t serialHandle, serial_read_handle_t readHandle);
/*!
* @brief Closes a reading for the serial manager module.
*
* This function Closes a reading for the serial manager module.
*
* @param readHandle The serial manager module reading handle pointer.
* @retval kStatus_SerialManager_Success The reading handle is closed.
*/
serial_manager_status_t SerialManager_CloseReadHandle(serial_read_handle_t readHandle);
/*!
* @brief Transmits data with the blocking mode.
*
* This is a blocking function, which polls the sending queue, waits for the sending queue to be empty.
* This function sends data using an interrupt method. The interrupt of the hardware could not be disabled.
* And There can only one buffer for transmission for the writing handle at the same time.
*
* @note The function #SerialManager_WriteBlocking and the function #SerialManager_WriteNonBlocking
* cannot be used at the same time.
* And, the function #SerialManager_CancelWriting cannot be used to abort the transmission of this function.
*
* @param writeHandle The serial manager module handle pointer.
* @param buffer Start address of the data to write.
* @param length Length of the data to write.
* @retval kStatus_SerialManager_Success Successfully sent all data.
* @retval kStatus_SerialManager_Busy Previous transmission still not finished; data not all sent yet.
* @retval kStatus_SerialManager_Error An error occurred.
*/
serial_manager_status_t SerialManager_WriteBlocking(serial_write_handle_t writeHandle,
uint8_t *buffer,
uint32_t length);
/*!
* @brief Reads data with the blocking mode.
*
* This is a blocking function, which polls the receiving buffer, waits for the receiving buffer to be full.
* This function receives data using an interrupt method. The interrupt of the hardware could not be disabled.
* And There can only one buffer for receiving for the reading handle at the same time.
*
* @note The function #SerialManager_ReadBlocking and the function #SerialManager_ReadNonBlocking
* cannot be used at the same time.
* And, the function #SerialManager_CancelReading cannot be used to abort the transmission of this function.
*
* @param readHandle The serial manager module handle pointer.
* @param buffer Start address of the data to store the received data.
* @param length The length of the data to be received.
* @retval kStatus_SerialManager_Success Successfully received all data.
* @retval kStatus_SerialManager_Busy Previous transmission still not finished; data not all received yet.
* @retval kStatus_SerialManager_Error An error occurred.
*/
serial_manager_status_t SerialManager_ReadBlocking(serial_read_handle_t readHandle, uint8_t *buffer, uint32_t length);
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
/*!
* @brief Transmits data with the non-blocking mode.
*
* This is a non-blocking function, which returns directly without waiting for all data to be sent.
* When all data is sent, the module notifies the upper layer through a TX callback function and passes
* the status parameter @ref kStatus_SerialManager_Success.
* This function sends data using an interrupt method. The interrupt of the hardware could not be disabled.
* And There can only one buffer for transmission for the writing handle at the same time.
*
* @note The function #SerialManager_WriteBlocking and the function #SerialManager_WriteNonBlocking
* cannot be used at the same time. And, the TX callback is mandatory before the function could be used.
*
* @param writeHandle The serial manager module handle pointer.
* @param buffer Start address of the data to write.
* @param length Length of the data to write.
* @retval kStatus_SerialManager_Success Successfully sent all data.
* @retval kStatus_SerialManager_Busy Previous transmission still not finished; data not all sent yet.
* @retval kStatus_SerialManager_Error An error occurred.
*/
serial_manager_status_t SerialManager_WriteNonBlocking(serial_write_handle_t writeHandle,
uint8_t *buffer,
uint32_t length);
/*!
* @brief Reads data with the non-blocking mode.
*
* This is a non-blocking function, which returns directly without waiting for all data to be received.
* When all data is received, the module driver notifies the upper layer
* through a RX callback function and passes the status parameter @ref kStatus_SerialManager_Success.
* This function receives data using an interrupt method. The interrupt of the hardware could not be disabled.
* And There can only one buffer for receiving for the reading handle at the same time.
*
* @note The function #SerialManager_ReadBlocking and the function #SerialManager_ReadNonBlocking
* cannot be used at the same time. And, the RX callback is mandatory before the function could be used.
*
* @param readHandle The serial manager module handle pointer.
* @param buffer Start address of the data to store the received data.
* @param length The length of the data to be received.
* @retval kStatus_SerialManager_Success Successfully received all data.
* @retval kStatus_SerialManager_Busy Previous transmission still not finished; data not all received yet.
* @retval kStatus_SerialManager_Error An error occurred.
*/
serial_manager_status_t SerialManager_ReadNonBlocking(serial_read_handle_t readHandle,
uint8_t *buffer,
uint32_t length);
/*!
* @brief Tries to read data.
*
* The function tries to read data from internal ring buffer. If the ring buffer is not empty, the data will be
* copied from ring buffer to up layer buffer. The copied length is the minimum of the ring buffer and up layer length.
* After the data is copied, the actual data length is passed by the parameter length.
* And There can only one buffer for receiving for the reading handle at the same time.
*
* @param readHandle The serial manager module handle pointer.
* @param buffer Start address of the data to store the received data.
* @param length The length of the data to be received.
* @param receivedLength Length received from the ring buffer directly.
* @retval kStatus_SerialManager_Success Successfully received all data.
* @retval kStatus_SerialManager_Busy Previous transmission still not finished; data not all received yet.
* @retval kStatus_SerialManager_Error An error occurred.
*/
serial_manager_status_t SerialManager_TryRead(serial_read_handle_t readHandle,
uint8_t *buffer,
uint32_t length,
uint32_t *receivedLength);
/*!
* @brief Cancels unfinished send transmission.
*
* The function cancels unfinished send transmission. When the transfer is canceled, the module notifies the upper layer
* through a TX callback function and passes the status parameter @ref kStatus_SerialManager_Canceled.
*
* @note The function #SerialManager_CancelWriting cannot be used to abort the transmission of
* the function #SerialManager_WriteBlocking.
*
* @param writeHandle The serial manager module handle pointer.
* @retval kStatus_SerialManager_Success Get successfully abort the sending.
* @retval kStatus_SerialManager_Error An error occurred.
*/
serial_manager_status_t SerialManager_CancelWriting(serial_write_handle_t writeHandle);
/*!
* @brief Cancels unfinished receive transmission.
*
* The function cancels unfinished receive transmission. When the transfer is canceled, the module notifies the upper
* layer
* through a RX callback function and passes the status parameter @ref kStatus_SerialManager_Canceled.
*
* @note The function #SerialManager_CancelReading cannot be used to abort the transmission of
* the function #SerialManager_ReadBlocking.
*
* @param readHandle The serial manager module handle pointer.
* @retval kStatus_SerialManager_Success Get successfully abort the receiving.
* @retval kStatus_SerialManager_Error An error occurred.
*/
serial_manager_status_t SerialManager_CancelReading(serial_read_handle_t readHandle);
/*!
* @brief Installs a TX callback and callback parameter.
*
* This function is used to install the TX callback and callback parameter for the serial manager module.
* When any status of TX transmission changed, the driver will notify the upper layer by the installed callback
* function. And the status is also passed as status parameter when the callback is called.
*
* @param writeHandle The serial manager module handle pointer.
* @param callback The callback function.
* @param callbackParam The parameter of the callback function.
* @retval kStatus_SerialManager_Success Successfully install the callback.
*/
serial_manager_status_t SerialManager_InstallTxCallback(serial_write_handle_t writeHandle,
serial_manager_callback_t callback,
void *callbackParam);
/*!
* @brief Installs a RX callback and callback parameter.
*
* This function is used to install the RX callback and callback parameter for the serial manager module.
* When any status of RX transmission changed, the driver will notify the upper layer by the installed callback
* function. And the status is also passed as status parameter when the callback is called.
*
* @param readHandle The serial manager module handle pointer.
* @param callback The callback function.
* @param callbackParam The parameter of the callback function.
* @retval kStatus_SerialManager_Success Successfully install the callback.
*/
serial_manager_status_t SerialManager_InstallRxCallback(serial_read_handle_t readHandle,
serial_manager_callback_t callback,
void *callbackParam);
#endif
/*!
* @brief Prepares to enter low power consumption.
*
* This function is used to prepare to enter low power consumption.
*
* @param serialHandle The serial manager module handle pointer.
* @retval kStatus_SerialManager_Success Successful operation.
*/
serial_manager_status_t SerialManager_EnterLowpower(serial_handle_t serialHandle);
/*!
* @brief Restores from low power consumption.
*
* This function is used to restore from low power consumption.
*
* @param serialHandle The serial manager module handle pointer.
* @retval kStatus_SerialManager_Success Successful operation.
*/
serial_manager_status_t SerialManager_ExitLowpower(serial_handle_t serialHandle);
#if defined(__cplusplus)
}
#endif
/*! @} */
#endif /* __SERIAL_MANAGER_H__ */

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2019 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __SERIAL_PORT_INTERNAL_H__
#define __SERIAL_PORT_INTERNAL_H__
/*******************************************************************************
* Definitions
******************************************************************************/
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif /* _cplusplus */
#if (defined(SERIAL_PORT_TYPE_UART) && (SERIAL_PORT_TYPE_UART > 0U))
serial_manager_status_t Serial_UartInit(serial_handle_t serialHandle, void *serialConfig);
serial_manager_status_t Serial_UartDeinit(serial_handle_t serialHandle);
serial_manager_status_t Serial_UartWrite(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length);
#if !(defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
serial_manager_status_t Serial_UartRead(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length);
#endif
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
serial_manager_status_t Serial_UartCancelWrite(serial_handle_t serialHandle);
serial_manager_status_t Serial_UartInstallTxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam);
serial_manager_status_t Serial_UartInstallRxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam);
void Serial_UartIsrFunction(serial_handle_t serialHandle);
#endif
#endif
#if (defined(SERIAL_PORT_TYPE_USBCDC) && (SERIAL_PORT_TYPE_USBCDC > 0U))
serial_manager_status_t Serial_UsbCdcInit(serial_handle_t serialHandle, void *config);
serial_manager_status_t Serial_UsbCdcDeinit(serial_handle_t serialHandle);
serial_manager_status_t Serial_UsbCdcWrite(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length);
serial_manager_status_t Serial_UsbCdcRead(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length);
serial_manager_status_t Serial_UsbCdcCancelWrite(serial_handle_t serialHandle);
serial_manager_status_t Serial_UsbCdcInstallTxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam);
serial_manager_status_t Serial_UsbCdcInstallRxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam);
void Serial_UsbCdcIsrFunction(serial_handle_t serialHandle);
#endif
#if (defined(SERIAL_PORT_TYPE_SWO) && (SERIAL_PORT_TYPE_SWO > 0U))
serial_manager_status_t Serial_SwoInit(serial_handle_t serialHandle, void *config);
serial_manager_status_t Serial_SwoDeinit(serial_handle_t serialHandle);
serial_manager_status_t Serial_SwoWrite(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length);
#if !(defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
serial_manager_status_t Serial_SwoRead(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length);
#endif
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
serial_manager_status_t Serial_SwoCancelWrite(serial_handle_t serialHandle);
serial_manager_status_t Serial_SwoInstallTxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam);
serial_manager_status_t Serial_SwoInstallRxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam);
void Serial_SwoIsrFunction(serial_handle_t serialHandle);
#endif
#endif
#if (defined(SERIAL_PORT_TYPE_USBCDC_VIRTUAL) && (SERIAL_PORT_TYPE_USBCDC_VIRTUAL > 0U))
serial_manager_status_t Serial_UsbCdcVirtualInit(serial_handle_t serialHandle, void *config);
serial_manager_status_t Serial_UsbCdcVirtualDeinit(serial_handle_t serialHandle);
serial_manager_status_t Serial_UsbCdcVirtualWrite(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length);
serial_manager_status_t Serial_UsbCdcVirtualRead(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length);
serial_manager_status_t Serial_UsbCdcVirtualCancelWrite(serial_handle_t serialHandle);
serial_manager_status_t Serial_UsbCdcVirtualInstallTxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam);
serial_manager_status_t Serial_UsbCdcVirtualInstallRxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam);
void Serial_UsbCdcVirtualIsrFunction(serial_handle_t serialHandle);
#endif
#if defined(__cplusplus)
}
#endif
#endif /* __SERIAL_PORT_INTERNAL_H__ */

View File

@@ -0,0 +1,371 @@
/*
* Copyright 2018 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_common.h"
#include "serial_manager.h"
#include "serial_port_internal.h"
#if (defined(SERIAL_PORT_TYPE_UART) && (SERIAL_PORT_TYPE_UART > 0U))
#include "uart.h"
#include "serial_port_uart.h"
/*******************************************************************************
* Definitions
******************************************************************************/
#ifndef NDEBUG
#if (defined(DEBUG_CONSOLE_ASSERT_DISABLE) && (DEBUG_CONSOLE_ASSERT_DISABLE > 0U))
#undef assert
#define assert(n)
#endif
#endif
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#define SERIAL_PORT_UART_RECEIVE_DATA_LENGTH 1U
typedef struct _serial_uart_send_state
{
serial_manager_callback_t callback;
void *callbackParam;
uint8_t *buffer;
uint32_t length;
volatile uint8_t busy;
} serial_uart_send_state_t;
typedef struct _serial_uart_recv_state
{
serial_manager_callback_t callback;
void *callbackParam;
volatile uint8_t busy;
uint8_t readBuffer[SERIAL_PORT_UART_RECEIVE_DATA_LENGTH];
} serial_uart_recv_state_t;
#endif
typedef struct _serial_uart_state
{
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
serial_uart_send_state_t tx;
serial_uart_recv_state_t rx;
#endif
uint8_t usartHandleBuffer[HAL_UART_HANDLE_SIZE];
} serial_uart_state_t;
/*******************************************************************************
* Prototypes
******************************************************************************/
/*******************************************************************************
* Code
******************************************************************************/
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
/* UART user callback */
static void Serial_UartCallback(hal_uart_handle_t handle, hal_uart_status_t status, void *userData)
{
serial_uart_state_t *serialUartHandle;
serial_manager_callback_message_t msg;
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
hal_uart_transfer_t transfer;
#endif
if (NULL == userData)
{
return;
}
serialUartHandle = (serial_uart_state_t *)userData;
if ((hal_uart_status_t)kStatus_HAL_UartRxIdle == status)
{
if ((NULL != serialUartHandle->rx.callback))
{
msg.buffer = &serialUartHandle->rx.readBuffer[0];
msg.length = sizeof(serialUartHandle->rx.readBuffer);
serialUartHandle->rx.callback(serialUartHandle->rx.callbackParam, &msg, kStatus_SerialManager_Success);
}
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
transfer.data = &serialUartHandle->rx.readBuffer[0];
transfer.dataSize = sizeof(serialUartHandle->rx.readBuffer);
if (kStatus_HAL_UartSuccess ==
HAL_UartTransferReceiveNonBlocking(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]), &transfer))
#else
if ((hal_uart_status_t)kStatus_HAL_UartSuccess ==
HAL_UartReceiveNonBlocking(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]),
&serialUartHandle->rx.readBuffer[0], sizeof(serialUartHandle->rx.readBuffer)))
#endif
{
serialUartHandle->rx.busy = 1U;
}
else
{
serialUartHandle->rx.busy = 0U;
}
}
else if ((hal_uart_status_t)kStatus_HAL_UartTxIdle == status)
{
if (serialUartHandle->tx.busy != 0U)
{
serialUartHandle->tx.busy = 0U;
if ((NULL != serialUartHandle->tx.callback))
{
msg.buffer = serialUartHandle->tx.buffer;
msg.length = serialUartHandle->tx.length;
serialUartHandle->tx.callback(serialUartHandle->tx.callbackParam, &msg, kStatus_SerialManager_Success);
}
}
}
else
{
}
}
#endif
serial_manager_status_t Serial_UartInit(serial_handle_t serialHandle, void *serialConfig)
{
serial_uart_state_t *serialUartHandle;
serial_port_uart_config_t *uartConfig;
hal_uart_config_t config;
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
hal_uart_transfer_t transfer;
#endif
#endif
assert(serialConfig);
assert(serialHandle);
assert(SERIAL_PORT_UART_HANDLE_SIZE >= sizeof(serial_uart_state_t));
uartConfig = (serial_port_uart_config_t *)serialConfig;
serialUartHandle = (serial_uart_state_t *)serialHandle;
config.baudRate_Bps = uartConfig->baudRate;
config.parityMode = (hal_uart_parity_mode_t)uartConfig->parityMode;
config.stopBitCount = (hal_uart_stop_bit_count_t)uartConfig->stopBitCount;
config.enableRx = uartConfig->enableRx;
config.enableTx = uartConfig->enableTx;
config.srcClock_Hz = uartConfig->clockRate;
config.instance = uartConfig->instance;
if (kStatus_HAL_UartSuccess != HAL_UartInit(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]), &config))
{
return kStatus_SerialManager_Error;
}
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
if (kStatus_HAL_UartSuccess !=
HAL_UartTransferInstallCallback(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]),
Serial_UartCallback, serialUartHandle))
#else
if (kStatus_HAL_UartSuccess != HAL_UartInstallCallback(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]),
Serial_UartCallback, serialUartHandle))
#endif
{
return kStatus_SerialManager_Error;
}
if (uartConfig->enableRx != 0U)
{
serialUartHandle->rx.busy = 1U;
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
transfer.data = &serialUartHandle->rx.readBuffer[0];
transfer.dataSize = sizeof(serialUartHandle->rx.readBuffer);
if (kStatus_HAL_UartSuccess !=
HAL_UartTransferReceiveNonBlocking(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]), &transfer))
#else
if (kStatus_HAL_UartSuccess !=
HAL_UartReceiveNonBlocking(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]),
&serialUartHandle->rx.readBuffer[0], sizeof(serialUartHandle->rx.readBuffer)))
#endif
{
serialUartHandle->rx.busy = 0U;
return kStatus_SerialManager_Error;
}
}
#endif
return kStatus_SerialManager_Success;
}
serial_manager_status_t Serial_UartDeinit(serial_handle_t serialHandle)
{
serial_uart_state_t *serialUartHandle;
assert(serialHandle);
serialUartHandle = (serial_uart_state_t *)serialHandle;
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
(void)HAL_UartTransferAbortReceive(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]));
#else
(void)HAL_UartAbortReceive(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]));
#endif
#endif
(void)HAL_UartDeinit(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]));
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
serialUartHandle->tx.busy = 0U;
serialUartHandle->rx.busy = 0U;
#endif
return kStatus_SerialManager_Success;
}
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
serial_manager_status_t Serial_UartWrite(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length)
{
serial_uart_state_t *serialUartHandle;
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
hal_uart_transfer_t transfer;
#endif
assert(serialHandle);
assert(buffer);
assert(length);
serialUartHandle = (serial_uart_state_t *)serialHandle;
if (serialUartHandle->tx.busy != 0U)
{
return kStatus_SerialManager_Busy;
}
serialUartHandle->tx.busy = 1U;
serialUartHandle->tx.buffer = buffer;
serialUartHandle->tx.length = length;
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
transfer.data = buffer;
transfer.dataSize = length;
if (kStatus_HAL_UartSuccess !=
HAL_UartTransferSendNonBlocking(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]), &transfer))
#else
if (kStatus_HAL_UartSuccess !=
HAL_UartSendNonBlocking(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]), buffer, length))
#endif
{
serialUartHandle->tx.busy = 0U;
return kStatus_SerialManager_Error;
}
return kStatus_SerialManager_Success;
}
#else
serial_manager_status_t Serial_UartWrite(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length)
{
serial_uart_state_t *serialUartHandle;
assert(serialHandle);
assert(buffer);
assert(length);
serialUartHandle = (serial_uart_state_t *)serialHandle;
return (serial_manager_status_t)HAL_UartSendBlocking(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]),
buffer, length);
}
serial_manager_status_t Serial_UartRead(serial_handle_t serialHandle, uint8_t *buffer, uint32_t length)
{
serial_uart_state_t *serialUartHandle;
assert(serialHandle);
assert(buffer);
assert(length);
serialUartHandle = (serial_uart_state_t *)serialHandle;
return (serial_manager_status_t)HAL_UartReceiveBlocking(
((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]), buffer, length);
}
#endif
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
serial_manager_status_t Serial_UartCancelWrite(serial_handle_t serialHandle)
{
serial_uart_state_t *serialUartHandle;
serial_manager_callback_message_t msg;
uint32_t primask;
uint8_t isBusy = 0U;
assert(serialHandle);
serialUartHandle = (serial_uart_state_t *)serialHandle;
primask = DisableGlobalIRQ();
isBusy = serialUartHandle->tx.busy;
serialUartHandle->tx.busy = 0U;
EnableGlobalIRQ(primask);
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
(void)HAL_UartTransferAbortSend(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]));
#else
(void)HAL_UartAbortSend(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]));
#endif
if (isBusy != 0U)
{
if ((NULL != serialUartHandle->tx.callback))
{
msg.buffer = serialUartHandle->tx.buffer;
msg.length = serialUartHandle->tx.length;
serialUartHandle->tx.callback(serialUartHandle->tx.callbackParam, &msg, kStatus_SerialManager_Canceled);
}
}
return kStatus_SerialManager_Success;
}
serial_manager_status_t Serial_UartInstallTxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam)
{
serial_uart_state_t *serialUartHandle;
assert(serialHandle);
serialUartHandle = (serial_uart_state_t *)serialHandle;
serialUartHandle->tx.callback = callback;
serialUartHandle->tx.callbackParam = callbackParam;
return kStatus_SerialManager_Success;
}
serial_manager_status_t Serial_UartInstallRxCallback(serial_handle_t serialHandle,
serial_manager_callback_t callback,
void *callbackParam)
{
serial_uart_state_t *serialUartHandle;
assert(serialHandle);
serialUartHandle = (serial_uart_state_t *)serialHandle;
serialUartHandle->rx.callback = callback;
serialUartHandle->rx.callbackParam = callbackParam;
return kStatus_SerialManager_Success;
}
void Serial_UartIsrFunction(serial_handle_t serialHandle)
{
serial_uart_state_t *serialUartHandle;
assert(serialHandle);
serialUartHandle = (serial_uart_state_t *)serialHandle;
HAL_UartIsrFunction(((hal_uart_handle_t)&serialUartHandle->usartHandleBuffer[0]));
}
#endif
#endif

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2018 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __SERIAL_PORT_UART_H__
#define __SERIAL_PORT_UART_H__
/*!
* @addtogroup serial_port_uart
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief serial port uart handle size*/
#if (defined(SERIAL_MANAGER_NON_BLOCKING_MODE) && (SERIAL_MANAGER_NON_BLOCKING_MODE > 0U))
#define SERIAL_PORT_UART_HANDLE_SIZE (166U)
#else
#define SERIAL_PORT_UART_HANDLE_SIZE (4U)
#endif
/*! @brief serial port uart parity mode*/
typedef enum _serial_port_uart_parity_mode
{
kSerialManager_UartParityDisabled = 0x0U, /*!< Parity disabled */
kSerialManager_UartParityEven = 0x1U, /*!< Parity even enabled */
kSerialManager_UartParityOdd = 0x2U, /*!< Parity odd enabled */
} serial_port_uart_parity_mode_t;
/*! @brief serial port uart stop bit count*/
typedef enum _serial_port_uart_stop_bit_count
{
kSerialManager_UartOneStopBit = 0U, /*!< One stop bit */
kSerialManager_UartTwoStopBit = 1U, /*!< Two stop bits */
} serial_port_uart_stop_bit_count_t;
/*! @brief serial port uart config struct*/
typedef struct _serial_port_uart_config
{
uint32_t clockRate; /*!< clock rate */
uint32_t baudRate; /*!< baud rate */
serial_port_uart_parity_mode_t parityMode; /*!< Parity mode, disabled (default), even, odd */
serial_port_uart_stop_bit_count_t stopBitCount; /*!< Number of stop bits, 1 stop bit (default) or 2 stop bits */
uint8_t instance; /*!< Instance (0 - UART0, 1 - UART1, ...), detail information
please refer to the SOC corresponding RM. */
uint8_t enableRx; /*!< Enable RX */
uint8_t enableTx; /*!< Enable TX */
} serial_port_uart_config_t;
/*! @} */
#endif /* __SERIAL_PORT_UART_H__ */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,76 @@
/*
* Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc.
* Copyright 2016 - 2018 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __SERIAL_PORT_USB_H__
#define __SERIAL_PORT_USB_H__
#if defined(FSL_RTOS_FREE_RTOS)
#include "FreeRTOS.h"
#endif
/*!
* @addtogroup serial_port_usb
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief serial port usb handle size*/
#define SERIAL_PORT_USB_CDC_HANDLE_SIZE (72)
/*! @brief USB interrupt priority*/
#if defined(__GIC_PRIO_BITS)
#define USB_DEVICE_INTERRUPT_PRIORITY (25U)
#else
#if defined(configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY)
#define USB_DEVICE_INTERRUPT_PRIORITY (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY)
#else
/* The default value 3 is used to support different ARM Core, such as CM0P, CM4, CM7, and CM33, etc.
* The minimum number of priority bits implemented in the NVIC is 2 on these SOCs. The value of mininum
* priority is 3 (2^2 - 1). So, the default value is 3.
*/
#define USB_DEVICE_INTERRUPT_PRIORITY (3U)
#endif
#endif
/*! @brief USB controller ID */
typedef enum _serial_port_usb_cdc_controller_index
{
kSerialManager_UsbControllerKhci0 = 0U, /*!< KHCI 0U */
kSerialManager_UsbControllerKhci1 = 1U, /*!< KHCI 1U, Currently, there are no platforms which have two KHCI IPs,
this is reserved to be used in the future. */
kSerialManager_UsbControllerEhci0 = 2U, /*!< EHCI 0U */
kSerialManager_UsbControllerEhci1 = 3U, /*!< EHCI 1U, Currently, there are no platforms which have two EHCI IPs,
this is reserved to be used in the future. */
kSerialManager_UsbControllerLpcIp3511Fs0 = 4U, /*!< LPC USB IP3511 FS controller 0 */
kSerialManager_UsbControllerLpcIp3511Fs1 = 5U, /*!< LPC USB IP3511 FS controller 1, there are no platforms which
have two IP3511 IPs, this is reserved to be used in the future. */
kSerialManager_UsbControllerLpcIp3511Hs0 = 6U, /*!< LPC USB IP3511 HS controller 0 */
kSerialManager_UsbControllerLpcIp3511Hs1 = 7U, /*!< LPC USB IP3511 HS controller 1, there are no platforms which
have two IP3511 IPs, this is reserved to be used in the future. */
kSerialManager_UsbControllerOhci0 = 8U, /*!< OHCI 0U */
kSerialManager_UsbControllerOhci1 = 9U, /*!< OHCI 1U, Currently, there are no platforms which have two OHCI IPs,
this is reserved to be used in the future. */
kSerialManager_UsbControllerIp3516Hs0 = 10U, /*!< IP3516HS 0U */
kSerialManager_UsbControllerIp3516Hs1 = 11U, /*!< IP3516HS 1U, Currently, there are no platforms which have two
IP3516HS IPs, this is reserved to be used in the future. */
} serial_port_usb_cdc_controller_index_t;
/*! @brief serial port usb config struct*/
typedef struct _serial_port_usb_cdc_config
{
serial_port_usb_cdc_controller_index_t controllerIndex; /*!< controller index */
} serial_port_usb_cdc_config_t;
/*! @} */
#endif /* __SERIAL_PORT_USB_H__ */

View File

@@ -0,0 +1,103 @@
;
; NXP Communication Device Class driver installation file
; Copyright 2016 NXP
;
[Version]
Signature="$Windows NT$"
Class=Ports
ClassGuid={4D36E978-E325-11CE-BFC1-08002BE10318}
Provider=%MFGNAME%
CatalogFile=%MFGFILENAME%.cat
DriverVer=02/16/2011,1.0
[Manufacturer]
%MFGNAME%=DeviceList, NTamd64
[DestinationDirs]
DefaultDestDir=12
;------------------------------------------------------------------------------
; Windows 2000/XP/Vista-32bit Sections
;------------------------------------------------------------------------------
[DriverInstall.nt]
include=mdmcpq.inf
AddReg=DriverInstall.nt.AddReg
[DriverInstall.nt.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,%DRIVERFILENAME%.sys
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
[DriverInstall.nt.Services]
AddService=usbser, 0x00000002, DriverService.nt
[DriverService.nt]
DisplayName=%SERVICE%
ServiceType=1
StartType=3
ErrorControl=1
ServiceBinary=%12%\%DRIVERFILENAME%.sys
;------------------------------------------------------------------------------
; Vista-64bit Sections
;------------------------------------------------------------------------------
[DriverInstall.NTamd64]
include=mdmcpq.inf
AddReg=DriverInstall.NTamd64.AddReg
[DriverInstall.NTamd64.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,%DRIVERFILENAME%.sys
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
[DriverInstall.NTamd64.Services]
AddService=usbser, 0x00000002, DriverService.NTamd64
[DriverService.NTamd64]
DisplayName=%SERVICE%
ServiceType=1
StartType=3
ErrorControl=1
ServiceBinary=%12%\%DRIVERFILENAME%.sys
;------------------------------------------------------------------------------
; Vendor and Product ID Definitions
;------------------------------------------------------------------------------
; When developing your USB device, the VID and PID used in the PC side
; application program and the firmware on the microcontroller must match.
; Modify the below line to use your VID and PID. Use the format as shown below.
; Note: One INF file can be used for multiple devices with different VID and PIDs.
; For each supported device, append ",USB\VID_xxxx&PID_yyyy" to the end of the line.
;------------------------------------------------------------------------------
[SourceDisksFiles]
[SourceDisksNames]
[DeviceList]
%DESCRIPTION%=DriverInstall, USB\VID_1FC9&PID_0094
%DESCRIPTION%=DriverInstall, USB\VID_1FC9&PID_009E&MI_00
%DESCRIPTION%=DriverInstall, USB\VID_1FC9&PID_009F&MI_00
%DESCRIPTION%=DriverInstall, USB\VID_1FC9&PID_00A3&MI_00
[DeviceList.NTamd64]
%DESCRIPTION% = DriverInstall, USB\VID_1FC9&PID_0094
%DESCRIPTION% = DriverInstall, USB\VID_1FC9&PID_009E&MI_00
%DESCRIPTION% = DriverInstall, USB\VID_1FC9&PID_009F&MI_00
%DESCRIPTION% = DriverInstall, USB\VID_1FC9&PID_00A3&MI_00
;------------------------------------------------------------------------------
; String Definitions
;------------------------------------------------------------------------------
;Modify these strings to customize your device
;------------------------------------------------------------------------------
[Strings]
MFGFILENAME="CDC"
DRIVERFILENAME ="usbser"
MFGNAME="NXP"
INSTDISK="NXP CDC Driver Installer"
DESCRIPTION="Virtual Com Port"
SERVICE="NXP Virtual COM Driver"

View File

@@ -0,0 +1,869 @@
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016, 2019 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <stdio.h>
#include <stdlib.h>
#include "usb_device_config.h"
#include "usb.h"
#include "usb_device.h"
#include "usb_device_class.h"
#if USB_DEVICE_CONFIG_CDC_ACM
#include "usb_device_cdc_acm.h"
/*******************************************************************************
* Definitions
******************************************************************************/
#define USB_CDC_ACM_ENTER_CRITICAL() \
USB_OSA_SR_ALLOC(); \
USB_OSA_ENTER_CRITICAL()
#define USB_CDC_ACM_EXIT_CRITICAL() USB_OSA_EXIT_CRITICAL()
/*******************************************************************************
* Variables
******************************************************************************/
/* CDC ACM device instance */
USB_GLOBAL USB_RAM_ADDRESS_ALIGNMENT(USB_DATA_ALIGN_SIZE)
usb_device_cdc_acm_struct_t g_cdcAcmHandle[USB_DEVICE_CONFIG_CDC_ACM];
/*******************************************************************************
* Code
******************************************************************************/
/*!
* @brief Allocates the CDC ACM device handle.
*
* This function allocates the CDC ACM device handle.
*
* @param handle The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
*/
static usb_status_t USB_DeviceCdcAcmAllocateHandle(usb_device_cdc_acm_struct_t **handle)
{
uint32_t count;
for (count = 0; count < USB_DEVICE_CONFIG_CDC_ACM; count++)
{
if (NULL == g_cdcAcmHandle[count].handle)
{
*handle = &g_cdcAcmHandle[count];
return kStatus_USB_Success;
}
}
return kStatus_USB_Busy;
}
/*!
* @brief Frees the CDC ACM device handle.
*
* This function frees the CDC ACM device handle.
*
* @param handle The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
*/
static usb_status_t USB_DeviceCdcAcmFreeHandle(usb_device_cdc_acm_struct_t *handle)
{
handle->handle = NULL;
handle->configStruct = NULL;
handle->configuration = 0;
handle->alternate = 0;
return kStatus_USB_Success;
}
/*!
* @brief Responds to the interrupt in endpoint event.
*
* This function responds to the interrupt in endpoint event.
*
* @param handle The device handle of the CDC ACM device.
* @param message The pointer to the message of the endpoint callback.
* @param callbackParam The pointer to the parameter of the callback.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmInterruptIn(usb_device_handle handle,
usb_device_endpoint_callback_message_struct_t *message,
void *callbackParam)
{
usb_device_cdc_acm_struct_t *cdcAcmHandle;
usb_status_t error = kStatus_USB_Error;
cdcAcmHandle = (usb_device_cdc_acm_struct_t *)callbackParam;
if (!cdcAcmHandle)
{
return kStatus_USB_InvalidHandle;
}
cdcAcmHandle->interruptIn.isBusy = 0;
if ((NULL != cdcAcmHandle->configStruct) && (cdcAcmHandle->configStruct->classCallback))
{
/*classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback((class_handle_t)cdcAcmHandle,
kUSB_DeviceCdcEventSerialStateNotif, message);
}
return error;
}
/*!
* @brief Responds to the bulk in endpoint event.
*
* This function responds to the bulk in endpoint event.
*
* @param handle The device handle of the CDC ACM device.
* @param message The pointer to the message of the endpoint callback.
* @param callbackParam The pointer to the parameter of the callback.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmBulkIn(usb_device_handle handle,
usb_device_endpoint_callback_message_struct_t *message,
void *callbackParam)
{
usb_device_cdc_acm_struct_t *cdcAcmHandle;
usb_status_t error = kStatus_USB_Error;
cdcAcmHandle = (usb_device_cdc_acm_struct_t *)callbackParam;
if (!cdcAcmHandle)
{
return kStatus_USB_InvalidHandle;
}
cdcAcmHandle->bulkIn.isBusy = 0;
if ((NULL != cdcAcmHandle->configStruct) && (cdcAcmHandle->configStruct->classCallback))
{
/*classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback((class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventSendResponse,
message);
}
return error;
}
/*!
* @brief Responds to the bulk out endpoint event.
*
* This function responds to the bulk out endpoint event.
*
* @param handle The device handle of the CDC ACM device.
* @param message The pointer to the message of the endpoint callback.
* @param callbackParam The pointer to the parameter of the callback.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmBulkOut(usb_device_handle handle,
usb_device_endpoint_callback_message_struct_t *message,
void *callbackParam)
{
usb_device_cdc_acm_struct_t *cdcAcmHandle;
usb_status_t error = kStatus_USB_Error;
cdcAcmHandle = (usb_device_cdc_acm_struct_t *)callbackParam;
if (!cdcAcmHandle)
{
return kStatus_USB_InvalidHandle;
}
cdcAcmHandle->bulkOut.isBusy = 0;
if ((NULL != cdcAcmHandle->configStruct) && (cdcAcmHandle->configStruct->classCallback))
{
/*classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback((class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventRecvResponse,
message);
}
return error;
}
/*!
* @brief Initializes the endpoints in CDC ACM class.
*
* This function initializes the endpoints in CDC ACM class.
*
* @param cdcAcmHandle The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmEndpointsInit(usb_device_cdc_acm_struct_t *cdcAcmHandle)
{
usb_device_interface_list_t *interfaceList;
usb_device_interface_struct_t *interface = NULL;
usb_status_t error = kStatus_USB_Error;
if (!cdcAcmHandle)
{
return error;
}
/* return error when configuration is invalid (0 or more than the configuration number) */
if ((cdcAcmHandle->configuration == 0U) ||
(cdcAcmHandle->configuration > cdcAcmHandle->configStruct->classInfomation->configurations))
{
return error;
}
interfaceList = &cdcAcmHandle->configStruct->classInfomation->interfaceList[cdcAcmHandle->configuration - 1];
for (uint32_t count = 0; count < interfaceList->count; count++)
{
if (USB_DEVICE_CONFIG_CDC_COMM_CLASS_CODE == interfaceList->interfaces[count].classCode)
{
for (uint32_t index = 0; index < interfaceList->interfaces[count].count; index++)
{
if (interfaceList->interfaces[count].interface[index].alternateSetting == cdcAcmHandle->alternate)
{
interface = &interfaceList->interfaces[count].interface[index];
break;
}
}
cdcAcmHandle->interfaceNumber = interfaceList->interfaces[count].interfaceNumber;
break;
}
}
if (!interface)
{
return error;
}
cdcAcmHandle->commInterfaceHandle = interface;
for (uint32_t count = 0; count < interface->endpointList.count; count++)
{
usb_device_endpoint_init_struct_t epInitStruct;
usb_device_endpoint_callback_struct_t epCallback;
epInitStruct.zlt = 0;
epInitStruct.interval = interface->endpointList.endpoint[count].interval;
epInitStruct.endpointAddress = interface->endpointList.endpoint[count].endpointAddress;
epInitStruct.maxPacketSize = interface->endpointList.endpoint[count].maxPacketSize;
epInitStruct.transferType = interface->endpointList.endpoint[count].transferType;
if ((USB_IN == ((epInitStruct.endpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) >>
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT)) &&
(USB_ENDPOINT_INTERRUPT == epInitStruct.transferType))
{
cdcAcmHandle->interruptIn.ep = (epInitStruct.endpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_NUMBER_MASK);
cdcAcmHandle->interruptIn.isBusy = 0;
cdcAcmHandle->interruptIn.pipeDataBuffer = (uint8_t *)USB_UNINITIALIZED_VAL_32;
cdcAcmHandle->interruptIn.pipeStall = 0U;
cdcAcmHandle->interruptIn.pipeDataLen = 0U;
epCallback.callbackFn = USB_DeviceCdcAcmInterruptIn;
}
epCallback.callbackParam = cdcAcmHandle;
error = USB_DeviceInitEndpoint(cdcAcmHandle->handle, &epInitStruct, &epCallback);
if (kStatus_USB_Success != error)
{
return error;
}
}
for (uint32_t count = 0; count < interfaceList->count; count++)
{
if (USB_DEVICE_CONFIG_CDC_DATA_CLASS_CODE == interfaceList->interfaces[count].classCode)
{
for (uint32_t index = 0; index < interfaceList->interfaces[count].count; index++)
{
if (interfaceList->interfaces[count].interface[index].alternateSetting == cdcAcmHandle->alternate)
{
interface = &interfaceList->interfaces[count].interface[index];
break;
}
}
break;
}
}
cdcAcmHandle->dataInterfaceHandle = interface;
for (uint32_t count = 0; count < interface->endpointList.count; count++)
{
usb_device_endpoint_init_struct_t epInitStruct;
usb_device_endpoint_callback_struct_t epCallback;
epInitStruct.zlt = 0;
epInitStruct.interval = interface->endpointList.endpoint[count].interval;
epInitStruct.endpointAddress = interface->endpointList.endpoint[count].endpointAddress;
epInitStruct.maxPacketSize = interface->endpointList.endpoint[count].maxPacketSize;
epInitStruct.transferType = interface->endpointList.endpoint[count].transferType;
if ((USB_IN == ((epInitStruct.endpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) >>
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT)) &&
(USB_ENDPOINT_BULK == epInitStruct.transferType))
{
cdcAcmHandle->bulkIn.ep = (epInitStruct.endpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_NUMBER_MASK);
cdcAcmHandle->bulkIn.isBusy = 0;
cdcAcmHandle->bulkIn.pipeDataBuffer = (uint8_t *)USB_UNINITIALIZED_VAL_32;
cdcAcmHandle->bulkIn.pipeStall = 0U;
cdcAcmHandle->bulkIn.pipeDataLen = 0U;
epCallback.callbackFn = USB_DeviceCdcAcmBulkIn;
}
else if ((USB_OUT == ((epInitStruct.endpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) >>
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT)) &&
(USB_ENDPOINT_BULK == epInitStruct.transferType))
{
cdcAcmHandle->bulkOut.ep = (epInitStruct.endpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_NUMBER_MASK);
cdcAcmHandle->bulkOut.isBusy = 0;
cdcAcmHandle->bulkOut.pipeDataBuffer = (uint8_t *)USB_UNINITIALIZED_VAL_32;
cdcAcmHandle->bulkOut.pipeStall = 0U;
cdcAcmHandle->bulkOut.pipeDataLen = 0U;
epCallback.callbackFn = USB_DeviceCdcAcmBulkOut;
}
else
{
}
epCallback.callbackParam = cdcAcmHandle;
error = USB_DeviceInitEndpoint(cdcAcmHandle->handle, &epInitStruct, &epCallback);
}
return error;
}
/*!
* @brief De-initializes the endpoints in CDC ACM class.
*
* This function de-initializes the endpoints in CDC ACM class.
*
* @param cdcAcmHandle The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmEndpointsDeinit(usb_device_cdc_acm_struct_t *cdcAcmHandle)
{
usb_status_t error = kStatus_USB_Error;
if ((!cdcAcmHandle->commInterfaceHandle) || (!cdcAcmHandle->dataInterfaceHandle))
{
return error;
}
for (uint32_t count = 0; count < cdcAcmHandle->commInterfaceHandle->endpointList.count; count++)
{
error = USB_DeviceDeinitEndpoint(
cdcAcmHandle->handle, cdcAcmHandle->commInterfaceHandle->endpointList.endpoint[count].endpointAddress);
}
for (uint32_t count = 0; count < cdcAcmHandle->dataInterfaceHandle->endpointList.count; count++)
{
error = USB_DeviceDeinitEndpoint(
cdcAcmHandle->handle, cdcAcmHandle->dataInterfaceHandle->endpointList.endpoint[count].endpointAddress);
}
cdcAcmHandle->commInterfaceHandle = NULL;
cdcAcmHandle->dataInterfaceHandle = NULL;
return error;
}
/*!
* @brief Handles the CDC ACM class event.
*
* This function responses to various events including the common device events and the class specific events.
* For class specific events, it calls the class callback defined in the application to deal with the class specific
* event.
*
* @param handle The class handle of the CDC ACM class.
* @param event The event type.
* @param param The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmEvent(void *handle, uint32_t event, void *param)
{
usb_device_cdc_acm_struct_t *cdcAcmHandle;
usb_device_cdc_acm_request_param_struct_t reqParam;
usb_status_t error = kStatus_USB_Error;
uint16_t interfaceAlternate;
uint8_t *temp8;
uint8_t alternate;
if ((!param) || (!handle))
{
return kStatus_USB_InvalidHandle;
}
cdcAcmHandle = (usb_device_cdc_acm_struct_t *)handle;
switch (event)
{
case kUSB_DeviceClassEventDeviceReset:
/* Bus reset, clear the configuration. */
cdcAcmHandle->configuration = 0;
break;
case kUSB_DeviceClassEventSetConfiguration:
temp8 = ((uint8_t *)param);
if (!cdcAcmHandle->configStruct)
{
break;
}
if (*temp8 == cdcAcmHandle->configuration)
{
break;
}
error = USB_DeviceCdcAcmEndpointsDeinit(cdcAcmHandle);
cdcAcmHandle->configuration = *temp8;
cdcAcmHandle->alternate = 0;
error = USB_DeviceCdcAcmEndpointsInit(cdcAcmHandle);
if (kStatus_USB_Success != error)
{
#ifdef DEBUG
usb_echo("kUSB_DeviceClassEventSetConfiguration, USB_DeviceInitEndpoint fail\r\n");
#endif
}
break;
case kUSB_DeviceClassEventSetInterface:
if (!cdcAcmHandle->configStruct)
{
break;
}
interfaceAlternate = *((uint16_t *)param);
alternate = (uint8_t)(interfaceAlternate & 0xFFU);
if (cdcAcmHandle->interfaceNumber != ((uint8_t)(interfaceAlternate >> 8U)))
{
break;
}
if (alternate == cdcAcmHandle->alternate)
{
break;
}
error = USB_DeviceCdcAcmEndpointsDeinit(cdcAcmHandle);
cdcAcmHandle->alternate = alternate;
error = USB_DeviceCdcAcmEndpointsInit(cdcAcmHandle);
if (kStatus_USB_Success != error)
{
#ifdef DEBUG
usb_echo("kUSB_DeviceClassEventSetInterface, USB_DeviceInitEndpoint fail\r\n");
#endif
}
break;
case kUSB_DeviceClassEventSetEndpointHalt:
if ((!cdcAcmHandle->configStruct) || (!cdcAcmHandle->commInterfaceHandle) ||
(!cdcAcmHandle->dataInterfaceHandle))
{
break;
}
temp8 = ((uint8_t *)param);
for (uint32_t count = 0; count < cdcAcmHandle->commInterfaceHandle->endpointList.count; count++)
{
if (*temp8 == cdcAcmHandle->commInterfaceHandle->endpointList.endpoint[count].endpointAddress)
{
cdcAcmHandle->interruptIn.pipeStall = 1U;
error = USB_DeviceStallEndpoint(cdcAcmHandle->handle, *temp8);
}
}
for (uint32_t count = 0; count < cdcAcmHandle->dataInterfaceHandle->endpointList.count; count++)
{
if (*temp8 == cdcAcmHandle->dataInterfaceHandle->endpointList.endpoint[count].endpointAddress)
{
if (USB_IN == (((*temp8) & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) >>
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT))
{
cdcAcmHandle->bulkIn.pipeStall = 1U;
}
else
{
cdcAcmHandle->bulkOut.pipeStall = 1U;
}
error = USB_DeviceStallEndpoint(cdcAcmHandle->handle, *temp8);
}
}
break;
case kUSB_DeviceClassEventClearEndpointHalt:
if ((!cdcAcmHandle->configStruct) || (!cdcAcmHandle->commInterfaceHandle) ||
(!cdcAcmHandle->dataInterfaceHandle))
{
break;
}
temp8 = ((uint8_t *)param);
for (uint32_t count = 0; count < cdcAcmHandle->commInterfaceHandle->endpointList.count; count++)
{
if (*temp8 == cdcAcmHandle->commInterfaceHandle->endpointList.endpoint[count].endpointAddress)
{
error = USB_DeviceUnstallEndpoint(cdcAcmHandle->handle, *temp8);
if (USB_IN == (((*temp8) & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) >>
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT))
{
if (cdcAcmHandle->interruptIn.pipeStall)
{
cdcAcmHandle->interruptIn.pipeStall = 0U;
if ((uint8_t *)USB_UNINITIALIZED_VAL_32 != cdcAcmHandle->interruptIn.pipeDataBuffer)
{
error = USB_DeviceSendRequest(cdcAcmHandle->handle, (cdcAcmHandle->interruptIn.ep),
cdcAcmHandle->interruptIn.pipeDataBuffer,
cdcAcmHandle->interruptIn.pipeDataLen);
if (kStatus_USB_Success != error)
{
usb_device_endpoint_callback_message_struct_t endpointCallbackMessage;
endpointCallbackMessage.buffer = cdcAcmHandle->interruptIn.pipeDataBuffer;
endpointCallbackMessage.length = cdcAcmHandle->interruptIn.pipeDataLen;
endpointCallbackMessage.isSetup = 0U;
USB_DeviceCdcAcmBulkIn(cdcAcmHandle->handle, (void *)&endpointCallbackMessage,
handle);
}
cdcAcmHandle->interruptIn.pipeDataBuffer = (uint8_t *)USB_UNINITIALIZED_VAL_32;
cdcAcmHandle->interruptIn.pipeDataLen = 0U;
}
}
}
}
}
for (uint32_t count = 0; count < cdcAcmHandle->dataInterfaceHandle->endpointList.count; count++)
{
if (*temp8 == cdcAcmHandle->dataInterfaceHandle->endpointList.endpoint[count].endpointAddress)
{
error = USB_DeviceUnstallEndpoint(cdcAcmHandle->handle, *temp8);
if (USB_IN == (((*temp8) & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) >>
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT))
{
if (cdcAcmHandle->bulkIn.pipeStall)
{
cdcAcmHandle->bulkIn.pipeStall = 0U;
if ((uint8_t *)USB_UNINITIALIZED_VAL_32 != cdcAcmHandle->bulkIn.pipeDataBuffer)
{
error = USB_DeviceSendRequest(cdcAcmHandle->handle, (cdcAcmHandle->bulkIn.ep),
cdcAcmHandle->bulkIn.pipeDataBuffer,
cdcAcmHandle->bulkIn.pipeDataLen);
if (kStatus_USB_Success != error)
{
usb_device_endpoint_callback_message_struct_t endpointCallbackMessage;
endpointCallbackMessage.buffer = cdcAcmHandle->bulkIn.pipeDataBuffer;
endpointCallbackMessage.length = cdcAcmHandle->bulkIn.pipeDataLen;
endpointCallbackMessage.isSetup = 0U;
USB_DeviceCdcAcmBulkIn(cdcAcmHandle->handle, (void *)&endpointCallbackMessage,
handle);
}
cdcAcmHandle->bulkIn.pipeDataBuffer = (uint8_t *)USB_UNINITIALIZED_VAL_32;
cdcAcmHandle->bulkIn.pipeDataLen = 0U;
}
}
}
else
{
if (cdcAcmHandle->bulkOut.pipeStall)
{
cdcAcmHandle->bulkOut.pipeStall = 0U;
if ((uint8_t *)USB_UNINITIALIZED_VAL_32 != cdcAcmHandle->bulkOut.pipeDataBuffer)
{
error = USB_DeviceRecvRequest(cdcAcmHandle->handle, (cdcAcmHandle->bulkOut.ep),
cdcAcmHandle->bulkOut.pipeDataBuffer,
cdcAcmHandle->bulkOut.pipeDataLen);
if (kStatus_USB_Success != error)
{
usb_device_endpoint_callback_message_struct_t endpointCallbackMessage;
endpointCallbackMessage.buffer = cdcAcmHandle->bulkOut.pipeDataBuffer;
endpointCallbackMessage.length = cdcAcmHandle->bulkOut.pipeDataLen;
endpointCallbackMessage.isSetup = 0U;
USB_DeviceCdcAcmBulkOut(cdcAcmHandle->handle, (void *)&endpointCallbackMessage,
handle);
}
cdcAcmHandle->bulkOut.pipeDataBuffer = (uint8_t *)USB_UNINITIALIZED_VAL_32;
cdcAcmHandle->bulkOut.pipeDataLen = 0U;
}
}
}
}
}
break;
case kUSB_DeviceClassEventClassRequest:
if (param)
{
usb_device_control_request_struct_t *controlRequest = (usb_device_control_request_struct_t *)param;
if ((controlRequest->setup->wIndex & 0xFFU) != cdcAcmHandle->interfaceNumber)
{
break;
}
/* Standard CDC request */
if (USB_REQUEST_TYPE_TYPE_CLASS == (controlRequest->setup->bmRequestType & USB_REQUEST_TYPE_TYPE_MASK))
{
reqParam.buffer = &(controlRequest->buffer);
reqParam.length = &(controlRequest->length);
reqParam.interfaceIndex = controlRequest->setup->wIndex;
reqParam.setupValue = controlRequest->setup->wValue;
reqParam.isSetup = controlRequest->isSetup;
switch (controlRequest->setup->bRequest)
{
case USB_DEVICE_CDC_REQUEST_SEND_ENCAPSULATED_COMMAND:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback(
(class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventSendEncapsulatedCommand, &reqParam);
break;
case USB_DEVICE_CDC_REQUEST_GET_ENCAPSULATED_RESPONSE:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback(
(class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventGetEncapsulatedResponse, &reqParam);
break;
case USB_DEVICE_CDC_REQUEST_SET_COMM_FEATURE:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback(
(class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventSetCommFeature, &reqParam);
break;
case USB_DEVICE_CDC_REQUEST_GET_COMM_FEATURE:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback(
(class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventGetCommFeature, &reqParam);
break;
case USB_DEVICE_CDC_REQUEST_CLEAR_COMM_FEATURE:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback(
(class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventClearCommFeature, &reqParam);
break;
case USB_DEVICE_CDC_REQUEST_GET_LINE_CODING:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback(
(class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventGetLineCoding, &reqParam);
break;
case USB_DEVICE_CDC_REQUEST_SET_LINE_CODING:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback(
(class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventSetLineCoding, &reqParam);
break;
case USB_DEVICE_CDC_REQUEST_SET_CONTROL_LINE_STATE:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback(
(class_handle_t)cdcAcmHandle, kUSB_DeviceCdcEventSetControlLineState, &reqParam);
break;
case USB_DEVICE_CDC_REQUEST_SEND_BREAK:
/* classCallback is initialized in classInit of s_UsbDeviceClassInterfaceMap,
it is from the second parameter of classInit */
error = cdcAcmHandle->configStruct->classCallback((class_handle_t)cdcAcmHandle,
kUSB_DeviceCdcEventSendBreak, &reqParam);
break;
default:
error = kStatus_USB_InvalidRequest;
break;
}
}
}
break;
default:
break;
}
return error;
}
/*!
* @brief Initializes the USB CDC ACM class.
*
* This function obtains a usb device handle according to the controller id, initializes the CDC ACM class
* with the class configure parameters and creates the mutex for each pipe.
*
* @param controllerId The id of the controller. The value can be choosen from kUSB_ControllerKhci0,
* kUSB_ControllerKhci1, kUSB_ControllerEhci0 or kUSB_ControllerEhci1.
* @param config The user configuration structure of type usb_device_class_config_struct_t. The user
* populates the members of this structure and passes the pointer of this structure
* into this function.
* @param handle It is out parameter. The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmInit(uint8_t controllerId,
usb_device_class_config_struct_t *config,
class_handle_t *handle)
{
usb_device_cdc_acm_struct_t *cdcAcmHandle;
usb_status_t error = kStatus_USB_Error;
error = USB_DeviceCdcAcmAllocateHandle(&cdcAcmHandle);
if (kStatus_USB_Success != error)
{
return error;
}
error = USB_DeviceClassGetDeviceHandle(controllerId, &cdcAcmHandle->handle);
if (kStatus_USB_Success != error)
{
return error;
}
if (!cdcAcmHandle->handle)
{
return kStatus_USB_InvalidHandle;
}
cdcAcmHandle->configStruct = config;
cdcAcmHandle->configuration = 0;
cdcAcmHandle->alternate = 0xFF;
if (kStatus_USB_OSA_Success != USB_OsaMutexCreate(&(cdcAcmHandle->bulkIn.mutex)))
{
#ifdef DEBUG
usb_echo("mutex create error!");
#endif
}
if (kStatus_USB_OSA_Success != USB_OsaMutexCreate(&(cdcAcmHandle->bulkOut.mutex)))
{
#ifdef DEBUG
usb_echo("mutex create error!");
#endif
}
if (kStatus_USB_OSA_Success != USB_OsaMutexCreate(&(cdcAcmHandle->interruptIn.mutex)))
{
#ifdef DEBUG
usb_echo("mutex create error!");
#endif
}
*handle = (class_handle_t)cdcAcmHandle;
return error;
}
/*!
* @brief De-Initializes the USB CDC ACM class.
*
* This function destroys the mutex for each pipe, deinit each endpoint of the CDC ACM class and free
* the CDC ACM class handle.
*
* @param handle The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmDeinit(class_handle_t handle)
{
usb_device_cdc_acm_struct_t *cdcAcmHandle;
usb_status_t error = kStatus_USB_Error;
cdcAcmHandle = (usb_device_cdc_acm_struct_t *)handle;
if (!cdcAcmHandle)
{
return kStatus_USB_InvalidHandle;
}
if (kStatus_USB_OSA_Success != USB_OsaMutexDestroy((cdcAcmHandle->bulkIn.mutex)))
{
#ifdef DEBUG
usb_echo("mutex destroy error!");
#endif
}
if (kStatus_USB_OSA_Success != USB_OsaMutexDestroy((cdcAcmHandle->bulkOut.mutex)))
{
#ifdef DEBUG
usb_echo("mutex destroy error!");
#endif
}
if (kStatus_USB_OSA_Success != USB_OsaMutexDestroy((cdcAcmHandle->interruptIn.mutex)))
{
#ifdef DEBUG
usb_echo("mutex destroy error!");
#endif
}
error = USB_DeviceCdcAcmEndpointsDeinit(cdcAcmHandle);
USB_DeviceCdcAcmFreeHandle(cdcAcmHandle);
return error;
}
/*!
* @brief Prime the endpoint to send packet to host.
*
* This function checks whether the endpoint is sending packet, then it primes the endpoint
* with the buffer address and the buffer length if the pipe is not busy. Otherwise, it ignores this transfer by
* returning an error code.
*
* @param handle The class handle of the CDC ACM class.
* @param ep The endpoint number of the transfer.
* @param buffer The pointer to the buffer to be transferred.
* @param length The length of the buffer to be transferred.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmSend(class_handle_t handle, uint8_t ep, uint8_t *buffer, uint32_t length)
{
usb_device_cdc_acm_struct_t *cdcAcmHandle;
usb_status_t error = kStatus_USB_Error;
usb_device_cdc_acm_pipe_t *cdcAcmPipe = NULL;
if (!handle)
{
return kStatus_USB_InvalidHandle;
}
cdcAcmHandle = (usb_device_cdc_acm_struct_t *)handle;
if (cdcAcmHandle->bulkIn.ep == ep)
{
cdcAcmPipe = &(cdcAcmHandle->bulkIn);
}
else if (cdcAcmHandle->interruptIn.ep == ep)
{
cdcAcmPipe = &(cdcAcmHandle->interruptIn);
}
else
{
}
if (NULL != cdcAcmPipe)
{
if (1U == cdcAcmPipe->isBusy)
{
return kStatus_USB_Busy;
}
cdcAcmPipe->isBusy = 1U;
if (cdcAcmPipe->pipeStall)
{
cdcAcmPipe->pipeDataBuffer = buffer;
cdcAcmPipe->pipeDataLen = length;
return kStatus_USB_Success;
}
error = USB_DeviceSendRequest(cdcAcmHandle->handle, ep, buffer, length);
if (kStatus_USB_Success != error)
{
cdcAcmPipe->isBusy = 0U;
}
}
return error;
}
/*!
* @brief Prime the endpoint to receive packet from host.
*
* This function checks whether the endpoint is receiving packet, then it primes the endpoint
* with the buffer address and the buffer length if the pipe is not busy. Otherwise, it ignores this transfer by
* returning an error code.
*
* @param handle The class handle of the CDC ACM class.
* @param ep The endpoint number of the transfer.
* @param buffer The pointer to the buffer to be transferred.
* @param length The length of the buffer to be transferred.
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceCdcAcmRecv(class_handle_t handle, uint8_t ep, uint8_t *buffer, uint32_t length)
{
usb_device_cdc_acm_struct_t *cdcAcmHandle;
usb_status_t error = kStatus_USB_Error;
if (!handle)
{
return kStatus_USB_InvalidHandle;
}
cdcAcmHandle = (usb_device_cdc_acm_struct_t *)handle;
if (1U == cdcAcmHandle->bulkOut.isBusy)
{
return kStatus_USB_Busy;
}
cdcAcmHandle->bulkOut.isBusy = 1U;
if (cdcAcmHandle->bulkOut.pipeStall)
{
cdcAcmHandle->bulkOut.pipeDataBuffer = buffer;
cdcAcmHandle->bulkOut.pipeDataLen = length;
return kStatus_USB_Success;
}
error = USB_DeviceRecvRequest(cdcAcmHandle->handle, ep, buffer, length);
if (kStatus_USB_Success != error)
{
cdcAcmHandle->bulkOut.isBusy = 0U;
}
return error;
}
#endif /* USB_DEVICE_CONFIG_CDC_ACM */

View File

@@ -0,0 +1,269 @@
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _USB_DEVICE_CDC_ACM_H_
#define _USB_DEVICE_CDC_ACM_H_
/*!
* @addtogroup cdc_acm
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
#define USB_DEVICE_CONFIG_CDC_ACM_MAX_INSTANCE (1) /*!< The maximum number of CDC device instance. */
#define USB_DEVICE_CONFIG_CDC_COMM_CLASS_CODE (0x02) /*!< The CDC communication class code. */
#define USB_DEVICE_CONFIG_CDC_DATA_CLASS_CODE (0x0A) /*!< The CDC data class code. */
#define USB_DEVICE_CDC_REQUEST_SEND_ENCAPSULATED_COMMAND \
(0x00) /*!< The CDC class request code for SEND_ENCAPSULATED_COMMAND. */
#define USB_DEVICE_CDC_REQUEST_GET_ENCAPSULATED_RESPONSE \
(0x01) /*!< The CDC class request code for GET_ENCAPSULATED_RESPONSE. */
#define USB_DEVICE_CDC_REQUEST_SET_COMM_FEATURE (0x02) /*!< The CDC class request code for SET_COMM_FEATURE. */
#define USB_DEVICE_CDC_REQUEST_GET_COMM_FEATURE (0x03) /*!< The CDC class request code for GET_COMM_FEATURE. */
#define USB_DEVICE_CDC_REQUEST_CLEAR_COMM_FEATURE (0x04) /*!< The CDC class request code for CLEAR_COMM_FEATURE. */
#define USB_DEVICE_CDC_REQUEST_SET_AUX_LINE_STATE (0x10) /*!< The CDC class request code for SET_AUX_LINE_STATE. */
#define USB_DEVICE_CDC_REQUEST_SET_HOOK_STATE (0x11) /*!< The CDC class request code for SET_HOOK_STATE. */
#define USB_DEVICE_CDC_REQUEST_PULSE_SETUP (0x12) /*!< The CDC class request code for PULSE_SETUP. */
#define USB_DEVICE_CDC_REQUEST_SEND_PULSE (0x13) /*!< The CDC class request code for SEND_PULSE. */
#define USB_DEVICE_CDC_REQUEST_SET_PULSE_TIME (0x14) /*!< The CDC class request code for SET_PULSE_TIME. */
#define USB_DEVICE_CDC_REQUEST_RING_AUX_JACK (0x15) /*!< The CDC class request code for RING_AUX_JACK. */
#define USB_DEVICE_CDC_REQUEST_SET_LINE_CODING (0x20) /*!< The CDC class request code for SET_LINE_CODING. */
#define USB_DEVICE_CDC_REQUEST_GET_LINE_CODING (0x21) /*!< The CDC class request code for GET_LINE_CODING. */
#define USB_DEVICE_CDC_REQUEST_SET_CONTROL_LINE_STATE \
(0x22) /*!< The CDC class request code for SET_CONTROL_LINE_STATE. */
#define USB_DEVICE_CDC_REQUEST_SEND_BREAK (0x23) /*!< The CDC class request code for SEND_BREAK. */
#define USB_DEVICE_CDC_REQUEST_SET_RINGER_PARAMS (0x30) /*!< The CDC class request code for SET_RINGER_PARAMS. */
#define USB_DEVICE_CDC_REQUEST_GET_RINGER_PARAMS (0x31) /*!< The CDC class request code for GET_RINGER_PARAMS. */
#define USB_DEVICE_CDC_REQUEST_SET_OPERATION_PARAM (0x32) /*!< The CDC class request code for SET_OPERATION_PARAM. */
#define USB_DEVICE_CDC_REQUEST_GET_OPERATION_PARAM (0x33) /*!< The CDC class request code for GET_OPERATION_PARAM. */
#define USB_DEVICE_CDC_REQUEST_SET_LINE_PARAMS (0x34) /*!< The CDC class request code for SET_LINE_PARAMS. */
#define USB_DEVICE_CDC_REQUEST_GET_LINE_PARAMS (0x35) /*!< The CDC class request code for GET_LINE_PARAMS. */
#define USB_DEVICE_CDC_REQUEST_DIAL_DIGITS (0x36) /*!< The CDC class request code for DIAL_DIGITS. */
#define USB_DEVICE_CDC_REQUEST_SET_UNIT_PARAMETER (0x37) /*!< The CDC class request code for SET_UNIT_PARAMETER. */
#define USB_DEVICE_CDC_REQUEST_GET_UNIT_PARAMETER (0x38) /*!< The CDC class request code for GET_UNIT_PARAMETER. */
#define USB_DEVICE_CDC_REQUEST_CLEAR_UNIT_PARAMETER \
(0x39) /*!< The CDC class request code for CLEAR_UNIT_PARAMETER. */
#define USB_DEVICE_CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS \
(0x40) /*!< The CDC class request code for SET_ETHERNET_MULTICAST_FILTERS. */
#define USB_DEVICE_CDC_REQUEST_SET_ETHERNET_POW_PATTER_FILTER \
(0x41) /*!< The CDC class request code for SET_ETHERNET_POW_PATTER_FILTER. */
#define USB_DEVICE_CDC_REQUEST_GET_ETHERNET_POW_PATTER_FILTER \
(0x42) /*!< The CDC class request code for GET_ETHERNET_POW_PATTER_FILTER. */
#define USB_DEVICE_CDC_REQUEST_SET_ETHERNET_PACKET_FILTER \
(0x43) /*!< The CDC class request code for SET_ETHERNET_PACKET_FILTER. */
#define USB_DEVICE_CDC_REQUEST_GET_ETHERNET_STATISTIC \
(0x44) /*!< The CDC class request code for GET_ETHERNET_STATISTIC. */
#define USB_DEVICE_CDC_REQUEST_SET_ATM_DATA_FORMAT (0x50) /*!< The CDC class request code for SET_ATM_DATA_FORMAT. */
#define USB_DEVICE_CDC_REQUEST_GET_ATM_DEVICE_STATISTICS \
(0x51) /*!< The CDC class request code for GET_ATM_DEVICE_STATISTICS. */
#define USB_DEVICE_CDC_REQUEST_SET_ATM_DEFAULT_VC (0x52) /*!< The CDC class request code for SET_ATM_DEFAULT_VC. */
#define USB_DEVICE_CDC_REQUEST_GET_ATM_VC_STATISTICS \
(0x53) /*!< The CDC class request code for GET_ATM_VC_STATISTICS. */
#define USB_DEVICE_CDC_REQUEST_MDLM_SPECIFIC_REQUESTS_MASK \
(0x7F) /*!< The CDC class request code for MDLM_SPECIFIC_REQUESTS_MASK. */
#define USB_DEVICE_CDC_NOTIF_NETWORK_CONNECTION (0x00) /*!< The CDC class notify code for NETWORK_CONNECTION. */
#define USB_DEVICE_CDC_NOTIF_RESPONSE_AVAIL (0x01) /*!< The CDC class notify code for RESPONSE_AVAIL. */
#define USB_DEVICE_CDC_NOTIF_AUX_JACK_HOOK_STATE (0x08) /*!< The CDC class notify code for AUX_JACK_HOOK_STATE. */
#define USB_DEVICE_CDC_NOTIF_RING_DETECT (0x09) /*!< The CDC class notify code for RING_DETECT. */
#define USB_DEVICE_CDC_NOTIF_SERIAL_STATE (0x20) /*!< The CDC class notify code for SERIAL_STATE. */
#define USB_DEVICE_CDC_NOTIF_CALL_STATE_CHANGE (0x28) /*!< The CDC class notify code for CALL_STATE_CHANGE. */
#define USB_DEVICE_CDC_NOTIF_LINE_STATE_CHANGE (0x29) /*!< The CDC class notify code for LINE_STATE_CHANGE. */
#define USB_DEVICE_CDC_NOTIF_CONNECTION_SPEED_CHANGE \
(0x2A) /*!< The CDC class notify code for CONNECTION_SPEED_CHANGE. */
#define USB_DEVICE_CDC_FEATURE_ABSTRACT_STATE (0x01) /*!< The CDC class feature select code for ABSTRACT_STATE. */
#define USB_DEVICE_CDC_FEATURE_COUNTRY_SETTING (0x02) /*!< The CDC class feature select code for COUNTRY_SETTING. */
#define USB_DEVICE_CDC_CONTROL_SIG_BITMAP_CARRIER_ACTIVATION \
(0x02) /*!< The CDC class control signal bitmap value for CARRIER_ACTIVATION. */
#define USB_DEVICE_CDC_CONTROL_SIG_BITMAP_DTE_PRESENCE \
(0x01) /*!< The CDC class control signal bitmap value for DTE_PRESENCE. */
#define USB_DEVICE_CDC_UART_STATE_RX_CARRIER (0x01) /*!< The UART state bitmap value of RX_CARRIER. */
#define USB_DEVICE_CDC_UART_STATE_TX_CARRIER (0x02) /*!< The UART state bitmap value of TX_CARRIER. */
#define USB_DEVICE_CDC_UART_STATE_BREAK (0x04) /*!< The UART state bitmap value of BREAK. */
#define USB_DEVICE_CDC_UART_STATE_RING_SIGNAL (0x08) /*!< The UART state bitmap value of RING_SIGNAL. */
#define USB_DEVICE_CDC_UART_STATE_FRAMING (0x10) /*!< The UART state bitmap value of FRAMING. */
#define USB_DEVICE_CDC_UART_STATE_PARITY (0x20) /*!< The UART state bitmap value of PARITY. */
#define USB_DEVICE_CDC_UART_STATE_OVERRUN (0x40) /*!< The UART state bitmap value of OVERRUN. */
/*! @brief Definition of CDC class event. */
typedef enum _usb_device_cdc_acm_event
{
kUSB_DeviceCdcEventSendResponse = 0x01, /*!< This event indicates the bulk send transfer is complete or cancelled etc. */
kUSB_DeviceCdcEventRecvResponse, /*!< This event indicates the bulk receive transfer is complete or cancelled etc.. */
kUSB_DeviceCdcEventSerialStateNotif, /*!< This event indicates the serial state has been sent to the host. */
kUSB_DeviceCdcEventSendEncapsulatedCommand, /*!< This event indicates the device received the
SEND_ENCAPSULATED_COMMAND request. */
kUSB_DeviceCdcEventGetEncapsulatedResponse, /*!< This event indicates the device received the
GET_ENCAPSULATED_RESPONSE request. */
kUSB_DeviceCdcEventSetCommFeature, /*!< This event indicates the device received the SET_COMM_FEATURE request. */
kUSB_DeviceCdcEventGetCommFeature, /*!< This event indicates the device received the GET_COMM_FEATURE request. */
kUSB_DeviceCdcEventClearCommFeature, /*!< This event indicates the device received the CLEAR_COMM_FEATURE request.
*/
kUSB_DeviceCdcEventGetLineCoding, /*!< This event indicates the device received the GET_LINE_CODING request. */
kUSB_DeviceCdcEventSetLineCoding, /*!< This event indicates the device received the SET_LINE_CODING request. */
kUSB_DeviceCdcEventSetControlLineState, /*!< This event indicates the device received the SET_CONTRL_LINE_STATE
request. */
kUSB_DeviceCdcEventSendBreak /*!< This event indicates the device received the SEND_BREAK request. */
} usb_device_cdc_acm_event_t;
/*! @brief Definition of parameters for CDC ACM request. */
typedef struct _usb_device_cdc_acm_request_param_struct
{
uint8_t **buffer; /*!< The pointer to the address of the buffer for CDC class request. */
uint32_t *length; /*!< The pointer to the length of the buffer for CDC class request. */
uint16_t interfaceIndex; /*!< The interface index of the setup packet. */
uint16_t setupValue; /*!< The wValue field of the setup packet. */
uint8_t isSetup; /*!< The flag indicates if it is a setup packet, 1: yes, 0: no. */
} usb_device_cdc_acm_request_param_struct_t;
/*! @brief Definition of pipe structure. */
typedef struct _usb_device_cdc_acm_pipe
{
usb_osa_mutex_handle mutex; /*!< The mutex of the pipe. */
uint8_t *pipeDataBuffer; /*!< pipe data buffer backup when stall */
uint32_t pipeDataLen; /*!< pipe data length backup when stall */
uint8_t pipeStall; /*!< pipe is stall */
uint8_t ep; /*!< The endpoint number of the pipe. */
uint8_t isBusy; /*!< 1: The pipe is transferring packet, 0: The pipe is idle. */
} usb_device_cdc_acm_pipe_t;
/*! @brief Definition of structure for CDC ACM device. */
typedef struct _usb_device_cdc_acm_struct
{
usb_device_handle handle; /*!< The handle of the USB device. */
usb_device_class_config_struct_t *configStruct; /*!< The class configure structure. */
usb_device_interface_struct_t *commInterfaceHandle; /*!< The CDC communication interface handle. */
usb_device_interface_struct_t *dataInterfaceHandle; /*!< The CDC data interface handle. */
usb_device_cdc_acm_pipe_t bulkIn; /*!< The bulk in pipe for sending packet to host. */
usb_device_cdc_acm_pipe_t bulkOut; /*!< The bulk out pipe for receiving packet from host. */
usb_device_cdc_acm_pipe_t interruptIn; /*!< The interrupt in pipe for notifying the device state to host. */
uint8_t configuration; /*!< The current configuration value. */
uint8_t interfaceNumber; /*!< The current interface number. */
uint8_t alternate; /*!< The alternate setting value of the interface. */
uint8_t hasSentState; /*!< 1: The device has primed the state in interrupt pipe, 0: Not primed the state. */
} usb_device_cdc_acm_struct_t;
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @name USB CDC ACM Class Driver
* @{
*/
/*!
* @brief Initializes the USB CDC ACM class.
*
* This function obtains a USB device handle according to the controller ID, initializes the CDC ACM class
* with the class configure parameters and creates the mutex for each pipe.
*
* @param controllerId The ID of the controller. The value can be chosen from the kUSB_ControllerKhci0,
* kUSB_ControllerKhci1, kUSB_ControllerEhci0, or kUSB_ControllerEhci1.
* @param config The user configuration structure of type usb_device_class_config_struct_t. The user
* populates the members of this structure and passes the pointer of this structure
* into this function.
* @param handle It is out parameter. The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
* @retval kStatus_USB_Success The CDC ACM class is initialized successfully.
* @retval kStatus_USB_Busy No CDC ACM device handle available for allocation.
* @retval kStatus_USB_InvalidHandle The CDC ACM device handle allocation failure.
* @retval kStatus_USB_InvalidParameter The USB device handle allocation failure.
*/
extern usb_status_t USB_DeviceCdcAcmInit(uint8_t controllerId,
usb_device_class_config_struct_t *config,
class_handle_t *handle);
/*!
* @brief Deinitializes the USB CDC ACM class.
*
* This function destroys the mutex for each pipe, deinitializes each endpoint of the CDC ACM class and frees
* the CDC ACM class handle.
*
* @param handle The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
* @retval kStatus_USB_Success The CDC ACM class is de-initialized successfully.
* @retval kStatus_USB_Error The endpoint deinitialization failure.
* @retval kStatus_USB_InvalidHandle The CDC ACM device handle or the CDC ACM class handle is invalid.
* @retval kStatus_USB_InvalidParameter The endpoint number of the CDC ACM class handle is invalid.
*/
extern usb_status_t USB_DeviceCdcAcmDeinit(class_handle_t handle);
/*!
* @brief Handles the CDC ACM class event.
*
* This function responds to various events including the common device events and the class-specific events.
* For class-specific events, it calls the class callback defined in the application to deal with the class-specific
* event.
*
* @param handle The class handle of the CDC ACM class.
* @param event The event type.
* @param param The class handle of the CDC ACM class.
* @return A USB error code or kStatus_USB_Success.
* @retval kStatus_USB_Success The CDC ACM class is de-initialized successfully.
* @retval kStatus_USB_Error The configure structure of the CDC ACM class handle is invalid.
* @retval kStatus_USB_InvalidHandle The CDC ACM device handle or the CDC ACM class handle is invalid.
* @retval kStatus_USB_InvalidParameter The endpoint number of the CDC ACM class handle is invalid.
* @retval Others The error code returned by class callback in application.
*/
extern usb_status_t USB_DeviceCdcAcmEvent(void *handle, uint32_t event, void *param);
/*!
* @brief Primes the endpoint to send packet to host.
*
* This function checks whether the endpoint is sending packet, then it primes the endpoint
* with the buffer address and the buffer length if the pipe is not busy. Otherwise, it ignores this transfer by
* returning an error code.
*
* @param handle The class handle of the CDC ACM class.
* @param ep The endpoint number of the transfer.
* @param buffer The pointer to the buffer to be transferred.
* @param length The length of the buffer to be transferred.
* @return A USB error code or kStatus_USB_Success.
* @retval kStatus_USB_Success Prime to send packet successfully.
* @retval kStatus_USB_Busy The endpoint is busy in transferring.
* @retval kStatus_USB_InvalidHandle The CDC ACM device handle or the CDC ACM class handle is invalid.
* @retval kStatus_USB_ControllerNotFound The controller interface is invalid.
*
* @note The function can only be called in the same context.
*/
extern usb_status_t USB_DeviceCdcAcmSend(class_handle_t handle, uint8_t ep, uint8_t *buffer, uint32_t length);
/*!
* @brief Primes the endpoint to receive packet from host.
*
* This function checks whether the endpoint is receiving packet, then it primes the endpoint
* with the buffer address and the buffer length if the pipe is not busy. Otherwise, it ignores this transfer by
* returning an error code.
*
* @param handle The class handle of the CDC ACM class.
* @param ep The endpoint number of the transfer.
* @param buffer The pointer to the buffer to be transferred.
* @param length The length of the buffer to be transferred.
* @return A USB error code or kStatus_USB_Success.
* @retval kStatus_USB_Success Prime to receive packet successfully.
* @retval kStatus_USB_Busy The endpoint is busy in transferring.
* @retval kStatus_USB_InvalidHandle The CDC ACM device handle or the CDC ACM class handle is invalid.
* @retval kStatus_USB_ControllerNotFound The controller interface is invalid.
*
* @note The function can only be called in the same context.
*/
extern usb_status_t USB_DeviceCdcAcmRecv(class_handle_t handle, uint8_t ep, uint8_t *buffer, uint32_t length);
/*! @}*/
#if defined(__cplusplus)
}
#endif
/*! @}*/
#endif /* _USB_DEVICE_CDC_ACM_H_ */

View File

@@ -0,0 +1,952 @@
/*
* Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc.
* Copyright 2016 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "usb_device_config.h"
#include "usb.h"
#include "usb_device.h"
#include "usb_device_dci.h"
#include "usb_device_class.h"
#include "usb_device_ch9.h"
#if ((defined(USB_DEVICE_CONFIG_NUM)) && (USB_DEVICE_CONFIG_NUM > 0U))
/*******************************************************************************
* Definitions
******************************************************************************/
/*!
* @brief Standard request callback function typedef.
*
* This function is used to handle the standard request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @return A USB error code or kStatus_USB_Success.
*/
typedef usb_status_t (*usb_standard_request_callback_t)(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
/*******************************************************************************
* Prototypes
******************************************************************************/
static usb_status_t USB_DeviceCh9GetStatus(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
static usb_status_t USB_DeviceCh9SetClearFeature(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
static usb_status_t USB_DeviceCh9SetAddress(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
static usb_status_t USB_DeviceCh9GetDescriptor(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
static usb_status_t USB_DeviceCh9GetConfiguration(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
static usb_status_t USB_DeviceCh9SetConfiguration(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
static usb_status_t USB_DeviceCh9GetInterface(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
static usb_status_t USB_DeviceCh9SetInterface(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
static usb_status_t USB_DeviceCh9SynchFrame(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length);
/*******************************************************************************
* Variables
******************************************************************************/
/* The function list to handle the standard request. */
static const usb_standard_request_callback_t s_UsbDeviceStandardRequest[] = {
USB_DeviceCh9GetStatus,
USB_DeviceCh9SetClearFeature,
(usb_standard_request_callback_t)NULL,
USB_DeviceCh9SetClearFeature,
(usb_standard_request_callback_t)NULL,
USB_DeviceCh9SetAddress,
USB_DeviceCh9GetDescriptor,
(usb_standard_request_callback_t)NULL,
USB_DeviceCh9GetConfiguration,
USB_DeviceCh9SetConfiguration,
USB_DeviceCh9GetInterface,
USB_DeviceCh9SetInterface,
USB_DeviceCh9SynchFrame,
};
/*******************************************************************************
* Code
******************************************************************************/
/*!
* @brief Handle get status request.
*
* This function is used to handle get status request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state,
* or, the request is unsupported.
*/
static usb_status_t USB_DeviceCh9GetStatus(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
usb_status_t error = kStatus_USB_InvalidRequest;
uint8_t state;
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if ((kUSB_DeviceStateAddress != state) && (kUSB_DeviceStateConfigured != state))
{
return error;
}
if ((setup->bmRequestType & USB_REQUEST_TYPE_RECIPIENT_MASK) == USB_REQUEST_TYPE_RECIPIENT_DEVICE)
{
#if (defined(USB_DEVICE_CONFIG_OTG) && (USB_DEVICE_CONFIG_OTG))
if (setup->wIndex == USB_REQUEST_STANDARD_GET_STATUS_OTG_STATUS_SELECTOR)
{
error =
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusOtg, &classHandle->standardTranscationBuffer);
classHandle->standardTranscationBuffer = USB_SHORT_TO_LITTLE_ENDIAN(classHandle->standardTranscationBuffer);
/* The device status length must be USB_DEVICE_STATUS_SIZE. */
*length = 1;
}
else /* Get the device status */
{
#endif
error = USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDevice,
&classHandle->standardTranscationBuffer);
classHandle->standardTranscationBuffer =
classHandle->standardTranscationBuffer & USB_GET_STATUS_DEVICE_MASK;
classHandle->standardTranscationBuffer = USB_SHORT_TO_LITTLE_ENDIAN(classHandle->standardTranscationBuffer);
/* The device status length must be USB_DEVICE_STATUS_SIZE. */
*length = USB_DEVICE_STATUS_SIZE;
#if (defined(USB_DEVICE_CONFIG_OTG) && (USB_DEVICE_CONFIG_OTG))
}
#endif
}
else if ((setup->bmRequestType & USB_REQUEST_TYPE_RECIPIENT_MASK) == USB_REQUEST_TYPE_RECIPIENT_INTERFACE)
{
/* Get the interface status */
error = kStatus_USB_Success;
classHandle->standardTranscationBuffer = 0U;
/* The interface status length must be USB_INTERFACE_STATUS_SIZE. */
*length = USB_INTERFACE_STATUS_SIZE;
}
else if ((setup->bmRequestType & USB_REQUEST_TYPE_RECIPIENT_MASK) == USB_REQUEST_TYPE_RECIPIENT_ENDPOINT)
{
/* Get the endpoint status */
usb_device_endpoint_status_struct_t endpointStatus;
endpointStatus.endpointAddress = (uint8_t)setup->wIndex;
endpointStatus.endpointStatus = kUSB_DeviceEndpointStateIdle;
error = USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusEndpoint, &endpointStatus);
classHandle->standardTranscationBuffer = endpointStatus.endpointStatus & USB_GET_STATUS_ENDPOINT_MASK;
classHandle->standardTranscationBuffer = USB_SHORT_TO_LITTLE_ENDIAN(classHandle->standardTranscationBuffer);
/* The endpoint status length must be USB_INTERFACE_STATUS_SIZE. */
*length = USB_ENDPOINT_STATUS_SIZE;
}
else
{
}
*buffer = (uint8_t *)&classHandle->standardTranscationBuffer;
return error;
}
/*!
* @brief Handle set or clear device feature request.
*
* This function is used to handle set or clear device feature request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state,
* or, the request is unsupported.
*/
static usb_status_t USB_DeviceCh9SetClearFeature(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
usb_status_t error = kStatus_USB_InvalidRequest;
uint8_t state;
uint8_t isSet = 0U;
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if ((kUSB_DeviceStateAddress != state) && (kUSB_DeviceStateConfigured != state))
{
return error;
}
/* Identify the request is set or clear the feature. */
if (USB_REQUEST_STANDARD_SET_FEATURE == setup->bRequest)
{
isSet = 1U;
}
if ((setup->bmRequestType & USB_REQUEST_TYPE_RECIPIENT_MASK) == USB_REQUEST_TYPE_RECIPIENT_DEVICE)
{
/* Set or Clear the device feature. */
if (USB_REQUEST_STANDARD_FEATURE_SELECTOR_DEVICE_REMOTE_WAKEUP == setup->wValue)
{
#if ((defined(USB_DEVICE_CONFIG_REMOTE_WAKEUP)) && (USB_DEVICE_CONFIG_REMOTE_WAKEUP > 0U))
USB_DeviceSetStatus(classHandle->handle, kUSB_DeviceStatusRemoteWakeup, &isSet);
#endif
/* Set or Clear the device remote wakeup feature. */
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventSetRemoteWakeup, &isSet);
}
#if ((defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U)) || \
(defined(USB_DEVICE_CONFIG_LPCIP3511HS) && (USB_DEVICE_CONFIG_LPCIP3511HS > 0U))) && \
(defined(USB_DEVICE_CONFIG_USB20_TEST_MODE) && (USB_DEVICE_CONFIG_USB20_TEST_MODE > 0U))
else if (USB_REQUEST_STANDARD_FEATURE_SELECTOR_DEVICE_TEST_MODE == setup->wValue)
{
state = kUSB_DeviceStateTestMode;
error = USB_DeviceSetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
}
#endif
#if (defined(USB_DEVICE_CONFIG_OTG) && (USB_DEVICE_CONFIG_OTG))
else if (USB_REQUEST_STANDARD_FEATURE_SELECTOR_B_HNP_ENABLE == setup->wValue)
{
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventSetBHNPEnable, &isSet);
}
#endif
else
{
}
}
else if ((setup->bmRequestType & USB_REQUEST_TYPE_RECIPIENT_MASK) == USB_REQUEST_TYPE_RECIPIENT_ENDPOINT)
{
/* Set or Clear the endpoint feature. */
if (USB_REQUEST_STANDARD_FEATURE_SELECTOR_ENDPOINT_HALT == setup->wValue)
{
if (USB_CONTROL_ENDPOINT == (setup->wIndex & USB_ENDPOINT_NUMBER_MASK))
{
/* Set or Clear the control endpoint status(halt or not). */
if (isSet)
{
USB_DeviceStallEndpoint(classHandle->handle, (uint8_t)setup->wIndex);
}
else
{
USB_DeviceUnstallEndpoint(classHandle->handle, (uint8_t)setup->wIndex);
}
}
/* Set or Clear the endpoint status feature. */
if (isSet)
{
error = USB_DeviceClassEvent(classHandle->handle, kUSB_DeviceClassEventSetEndpointHalt, &setup->wIndex);
}
else
{
error =
USB_DeviceClassEvent(classHandle->handle, kUSB_DeviceClassEventClearEndpointHalt, &setup->wIndex);
}
}
else
{
}
}
else
{
}
return error;
}
/*!
* @brief Handle set address request.
*
* This function is used to handle set address request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state.
*/
static usb_status_t USB_DeviceCh9SetAddress(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
usb_status_t error = kStatus_USB_InvalidRequest;
uint8_t state;
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if ((kUSB_DeviceStateAddressing != state) && (kUSB_DeviceStateAddress != state) &&
(kUSB_DeviceStateDefault != state) && (kUSB_DeviceStateConfigured != state))
{
return error;
}
if (kUSB_DeviceStateAddressing != state)
{
/* If the device address is not setting, pass the address and the device state will change to
* kUSB_DeviceStateAddressing internally. */
state = setup->wValue & 0xFFU;
error = USB_DeviceSetStatus(classHandle->handle, kUSB_DeviceStatusAddress, &state);
}
else
{
/* If the device address is setting, set device address and the address will be write into the controller
* internally. */
error = USB_DeviceSetStatus(classHandle->handle, kUSB_DeviceStatusAddress, NULL);
/* And then change the device state to kUSB_DeviceStateAddress. */
if (kStatus_USB_Success == error)
{
state = kUSB_DeviceStateAddress;
error = USB_DeviceSetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
}
}
return error;
}
/*!
* @brief Handle get descriptor request.
*
* This function is used to handle get descriptor request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state,
* or, the request is unsupported.
*/
static usb_status_t USB_DeviceCh9GetDescriptor(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
usb_device_get_descriptor_common_union_t commonDescriptor;
usb_status_t error = kStatus_USB_InvalidRequest;
uint8_t state;
uint8_t descriptorType = (uint8_t)((setup->wValue & 0xFF00U) >> 8U);
uint8_t descriptorIndex = (uint8_t)((setup->wValue & 0x00FFU));
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if ((kUSB_DeviceStateAddress != state) && (kUSB_DeviceStateConfigured != state) &&
(kUSB_DeviceStateDefault != state))
{
return error;
}
commonDescriptor.commonDescriptor.length = setup->wLength;
if (USB_DESCRIPTOR_TYPE_DEVICE == descriptorType)
{
/* Get the device descriptor */
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetDeviceDescriptor,
&commonDescriptor.deviceDescriptor);
}
else if (USB_DESCRIPTOR_TYPE_CONFIGURE == descriptorType)
{
/* Get the configuration descriptor */
commonDescriptor.configurationDescriptor.configuration = descriptorIndex;
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetConfigurationDescriptor,
&commonDescriptor.configurationDescriptor);
}
else if (USB_DESCRIPTOR_TYPE_STRING == descriptorType)
{
/* Get the string descriptor */
commonDescriptor.stringDescriptor.stringIndex = descriptorIndex;
commonDescriptor.stringDescriptor.languageId = setup->wIndex;
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetStringDescriptor,
&commonDescriptor.stringDescriptor);
}
#if (defined(USB_DEVICE_CONFIG_HID) && (USB_DEVICE_CONFIG_HID > 0U))
else if (USB_DESCRIPTOR_TYPE_HID == descriptorType)
{
/* Get the hid descriptor */
commonDescriptor.hidDescriptor.interfaceNumber = setup->wIndex;
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetHidDescriptor,
&commonDescriptor.hidDescriptor);
}
else if (USB_DESCRIPTOR_TYPE_HID_REPORT == descriptorType)
{
/* Get the hid report descriptor */
commonDescriptor.hidReportDescriptor.interfaceNumber = setup->wIndex;
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetHidReportDescriptor,
&commonDescriptor.hidReportDescriptor);
}
else if (USB_DESCRIPTOR_TYPE_HID_PHYSICAL == descriptorType)
{
/* Get the hid physical descriptor */
commonDescriptor.hidPhysicalDescriptor.index = descriptorIndex;
commonDescriptor.hidPhysicalDescriptor.interfaceNumber = setup->wIndex;
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetHidPhysicalDescriptor,
&commonDescriptor.hidPhysicalDescriptor);
}
#endif
#if (defined(USB_DEVICE_CONFIG_CV_TEST) && (USB_DEVICE_CONFIG_CV_TEST > 0U))
else if (USB_DESCRIPTOR_TYPE_DEVICE_QUALITIER == descriptorType)
{
/* Get the device descriptor */
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetDeviceQualifierDescriptor,
&commonDescriptor.deviceDescriptor);
}
#endif
#if (defined(USB_DEVICE_CONFIG_LPM_L1) && (USB_DEVICE_CONFIG_LPM_L1 > 0U))
else if (USB_DESCRIPTOR_TYPE_BOS == descriptorType)
{
/* Get the configuration descriptor */
commonDescriptor.configurationDescriptor.configuration = descriptorIndex;
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetBOSDescriptor,
&commonDescriptor.configurationDescriptor);
}
#endif
else
{
}
*buffer = commonDescriptor.commonDescriptor.buffer;
*length = commonDescriptor.commonDescriptor.length;
return error;
}
/*!
* @brief Handle get current configuration request.
*
* This function is used to handle get current configuration request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state,
* or, the request is unsupported.
*/
static usb_status_t USB_DeviceCh9GetConfiguration(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
uint8_t state;
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if ((kUSB_DeviceStateAddress != state) && ((kUSB_DeviceStateConfigured != state)))
{
return kStatus_USB_InvalidRequest;
}
*length = USB_CONFIGURE_SIZE;
*buffer = (uint8_t *)&classHandle->standardTranscationBuffer;
return USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetConfiguration,
&classHandle->standardTranscationBuffer);
}
/*!
* @brief Handle set current configuration request.
*
* This function is used to handle set current configuration request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state,
* or, the request is unsupported.
*/
static usb_status_t USB_DeviceCh9SetConfiguration(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
uint8_t state;
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if ((kUSB_DeviceStateAddress != state) && (kUSB_DeviceStateConfigured != state))
{
return kStatus_USB_InvalidRequest;
}
/* The device state is changed to kUSB_DeviceStateConfigured */
state = kUSB_DeviceStateConfigured;
USB_DeviceSetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if (!setup->wValue)
{
/* If the new configuration is zero, the device state is changed to kUSB_DeviceStateAddress */
state = kUSB_DeviceStateAddress;
USB_DeviceSetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
}
/* Notify the class layer the configuration is changed */
USB_DeviceClassEvent(classHandle->handle, kUSB_DeviceClassEventSetConfiguration, &setup->wValue);
/* Notify the application the configuration is changed */
return USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventSetConfiguration, &setup->wValue);
}
/*!
* @brief Handle get the alternate setting of a interface request.
*
* This function is used to handle get the alternate setting of a interface request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state,
* or, the request is unsupported.
*/
static usb_status_t USB_DeviceCh9GetInterface(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
usb_status_t error = kStatus_USB_InvalidRequest;
uint8_t state;
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if (state != kUSB_DeviceStateConfigured)
{
return error;
}
*length = USB_INTERFACE_SIZE;
*buffer = (uint8_t *)&classHandle->standardTranscationBuffer;
classHandle->standardTranscationBuffer = (uint16_t)(((uint32_t)setup->wIndex & 0xFFU) << 8U);
/* The Bit[15~8] is used to save the interface index, and the alternate setting will be saved in Bit[7~0] by
* application. */
error = USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventGetInterface,
&classHandle->standardTranscationBuffer);
classHandle->standardTranscationBuffer = USB_SHORT_TO_LITTLE_ENDIAN(classHandle->standardTranscationBuffer);
return error;
}
/*!
* @brief Handle set the alternate setting of a interface request.
*
* This function is used to handle set the alternate setting of a interface request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state,
* or, the request is unsupported.
*/
static usb_status_t USB_DeviceCh9SetInterface(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
uint8_t state;
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if (state != kUSB_DeviceStateConfigured)
{
return kStatus_USB_InvalidRequest;
}
classHandle->standardTranscationBuffer = ((setup->wIndex & 0xFFU) << 8U) | (setup->wValue & 0xFFU);
/* Notify the class driver the alternate setting of the interface is changed. */
/* The Bit[15~8] is used to save the interface index, and the alternate setting is saved in Bit[7~0]. */
USB_DeviceClassEvent(classHandle->handle, kUSB_DeviceClassEventSetInterface,
&classHandle->standardTranscationBuffer);
/* Notify the application the alternate setting of the interface is changed. */
/* The Bit[15~8] is used to save the interface index, and the alternate setting will is saved in Bit[7~0]. */
return USB_DeviceClassCallback(classHandle->handle, kUSB_DeviceEventSetInterface,
&classHandle->standardTranscationBuffer);
}
/*!
* @brief Handle get sync frame request.
*
* This function is used to handle get sync frame request.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @retval kStatus_USB_Success The request is handled successfully.
* @retval kStatus_USB_InvalidRequest The request can not be handle in current device state,
* or, the request is unsupported.
*/
static usb_status_t USB_DeviceCh9SynchFrame(usb_device_common_class_struct_t *classHandle,
usb_setup_struct_t *setup,
uint8_t **buffer,
uint32_t *length)
{
usb_status_t error = kStatus_USB_InvalidRequest;
uint8_t state;
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusDeviceState, &state);
if (state != kUSB_DeviceStateConfigured)
{
return error;
}
classHandle->standardTranscationBuffer = USB_SHORT_FROM_LITTLE_ENDIAN(setup->wIndex);
/* Get the sync frame value */
error =
USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusSynchFrame, &classHandle->standardTranscationBuffer);
*buffer = (uint8_t *)&classHandle->standardTranscationBuffer;
*length = sizeof(classHandle->standardTranscationBuffer);
return error;
}
/*!
* @brief Send the response to the host.
*
* This function is used to send the response to the host.
*
* There are two cases this function will be called.
* Case one when a setup packet is received in control endpoint callback function:
* 1. If there is not data phase in the setup transfer, the function will prime an IN transfer with the data
* length is zero for status phase.
* 2. If there is an IN data phase, the function will prime an OUT transfer with the actual length to need to
* send for data phase. And then prime an IN transfer with the data length is zero for status phase.
* 3. If there is an OUT data phase, the function will prime an IN transfer with the actual length to want to
* receive for data phase.
*
* Case two when is not a setup packet received in control endpoint callback function:
* 1. The function will prime an IN transfer with data length is zero for status phase.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param setup The pointer of the setup packet.
* @param error The error code returned from the standard request function.
* @param stage The stage of the control transfer.
* @param buffer It is an out parameter, is used to save the buffer address to response the host's request.
* @param length It is an out parameter, the data length.
*
* @return A USB error code or kStatus_USB_Success.
*/
static usb_status_t USB_DeviceControlCallbackFeedback(usb_device_handle handle,
usb_setup_struct_t *setup,
usb_status_t error,
usb_device_control_read_write_sequence_t stage,
uint8_t **buffer,
uint32_t *length)
{
usb_status_t errorCode = kStatus_USB_Error;
uint8_t direction = USB_IN;
if (kStatus_USB_InvalidRequest == error)
{
/* Stall the control pipe when the request is unsupported. */
if ((!((setup->bmRequestType & USB_REQUEST_TYPE_TYPE_MASK) == USB_REQUEST_TYPE_TYPE_STANDARD)) &&
((setup->bmRequestType & USB_REQUEST_TYPE_DIR_MASK) == USB_REQUEST_TYPE_DIR_OUT) && (setup->wLength) &&
(kUSB_DeviceControlPipeSetupStage == stage))
{
direction = USB_OUT;
}
errorCode = USB_DeviceStallEndpoint(
handle,
(USB_CONTROL_ENDPOINT) | (uint8_t)((uint32_t)direction << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT));
}
else
{
if (*length > setup->wLength)
{
*length = setup->wLength;
}
errorCode = USB_DeviceSendRequest(handle, (USB_CONTROL_ENDPOINT), *buffer, *length);
if ((kStatus_USB_Success == errorCode) &&
(USB_REQUEST_TYPE_DIR_IN == (setup->bmRequestType & USB_REQUEST_TYPE_DIR_MASK)))
{
errorCode = USB_DeviceRecvRequest(handle, (USB_CONTROL_ENDPOINT), (uint8_t *)NULL, 0U);
}
}
return errorCode;
}
/*!
* @brief Control endpoint callback function.
*
* This callback function is used to notify uplayer the transfser result of a transfer.
* This callback pointer is passed when a specified endpoint initialized by calling API USB_DeviceInitEndpoint.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param message The result of a transfer, includes transfer buffer, transfer length and whether is in setup
* phase for control pipe.
* @param callbackParam The parameter for this callback. It is same with
* usb_device_endpoint_callback_struct_t::callbackParam.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceControlCallback(usb_device_handle handle,
usb_device_endpoint_callback_message_struct_t *message,
void *callbackParam)
{
usb_setup_struct_t *deviceSetup;
usb_device_common_class_struct_t *classHandle;
uint8_t *buffer = (uint8_t *)NULL;
uint32_t length = 0U;
usb_status_t error = kStatus_USB_InvalidRequest;
uint8_t state;
if ((0xFFFFFFFFU == message->length) || (NULL == callbackParam))
{
return error;
}
classHandle = (usb_device_common_class_struct_t *)callbackParam;
deviceSetup = (usb_setup_struct_t *)&classHandle->setupBuffer[0];
USB_DeviceGetStatus(handle, kUSB_DeviceStatusDeviceState, &state);
if (message->isSetup)
{
if ((USB_SETUP_PACKET_SIZE != message->length) || (NULL == message->buffer))
{
/* If a invalid setup is received, the control pipes should be de-init and init again.
* Due to the IP can not meet this require, it is reserved for feature.
*/
/*
USB_DeviceDeinitEndpoint(handle,
USB_CONTROL_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT));
USB_DeviceDeinitEndpoint(handle,
USB_CONTROL_ENDPOINT | (USB_OUT << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT));
USB_DeviceControlPipeInit(handle, callbackParam);
*/
return error;
}
/* Receive a setup request */
usb_setup_struct_t *setup = (usb_setup_struct_t *)(message->buffer);
/* Copy the setup packet to the application buffer */
deviceSetup->wValue = USB_SHORT_FROM_LITTLE_ENDIAN(setup->wValue);
deviceSetup->wIndex = USB_SHORT_FROM_LITTLE_ENDIAN(setup->wIndex);
deviceSetup->wLength = USB_SHORT_FROM_LITTLE_ENDIAN(setup->wLength);
deviceSetup->bRequest = setup->bRequest;
deviceSetup->bmRequestType = setup->bmRequestType;
if ((deviceSetup->bmRequestType & USB_REQUEST_TYPE_TYPE_MASK) == USB_REQUEST_TYPE_TYPE_STANDARD)
{
/* Handle the standard request, only handle the request in request array. */
if(deviceSetup->bRequest < (sizeof(s_UsbDeviceStandardRequest)/4))
{
if (s_UsbDeviceStandardRequest[deviceSetup->bRequest] != (usb_standard_request_callback_t)NULL)
{
error = s_UsbDeviceStandardRequest[deviceSetup->bRequest](classHandle, deviceSetup, &buffer, &length);
}
}
}
else
{
if ((deviceSetup->wLength) &&
((deviceSetup->bmRequestType & USB_REQUEST_TYPE_DIR_MASK) == USB_REQUEST_TYPE_DIR_OUT))
{
/* Class or vendor request with the OUT data phase. */
if ((deviceSetup->wLength) &&
((deviceSetup->bmRequestType & USB_REQUEST_TYPE_TYPE_CLASS) == USB_REQUEST_TYPE_TYPE_CLASS))
{
/* Get data buffer to receive the data from the host. */
usb_device_control_request_struct_t controlRequest;
controlRequest.buffer = (uint8_t *)NULL;
controlRequest.isSetup = 1U;
controlRequest.setup = deviceSetup;
controlRequest.length = deviceSetup->wLength;
error = USB_DeviceClassEvent(handle, kUSB_DeviceClassEventClassRequest, &controlRequest);
length = controlRequest.length;
buffer = controlRequest.buffer;
}
else if ((deviceSetup->wLength) &&
((deviceSetup->bmRequestType & USB_REQUEST_TYPE_TYPE_VENDOR) == USB_REQUEST_TYPE_TYPE_VENDOR))
{
/* Get data buffer to receive the data from the host. */
usb_device_control_request_struct_t controlRequest;
controlRequest.buffer = (uint8_t *)NULL;
controlRequest.isSetup = 1U;
controlRequest.setup = deviceSetup;
controlRequest.length = deviceSetup->wLength;
error = USB_DeviceClassCallback(handle, kUSB_DeviceEventVendorRequest, &controlRequest);
length = controlRequest.length;
buffer = controlRequest.buffer;
}
else
{
}
if (kStatus_USB_Success == error)
{
/* Prime an OUT transfer */
error = USB_DeviceRecvRequest(handle, USB_CONTROL_ENDPOINT, buffer, deviceSetup->wLength);
return error;
}
}
else
{
/* Class or vendor request with the IN data phase. */
if (((deviceSetup->bmRequestType & USB_REQUEST_TYPE_TYPE_CLASS) == USB_REQUEST_TYPE_TYPE_CLASS))
{
/* Get data buffer to response the host. */
usb_device_control_request_struct_t controlRequest;
controlRequest.buffer = (uint8_t *)NULL;
controlRequest.isSetup = 1U;
controlRequest.setup = deviceSetup;
controlRequest.length = deviceSetup->wLength;
error = USB_DeviceClassEvent(handle, kUSB_DeviceClassEventClassRequest, &controlRequest);
length = controlRequest.length;
buffer = controlRequest.buffer;
}
else if (((deviceSetup->bmRequestType & USB_REQUEST_TYPE_TYPE_VENDOR) == USB_REQUEST_TYPE_TYPE_VENDOR))
{
/* Get data buffer to response the host. */
usb_device_control_request_struct_t controlRequest;
controlRequest.buffer = (uint8_t *)NULL;
controlRequest.isSetup = 1U;
controlRequest.setup = deviceSetup;
controlRequest.length = deviceSetup->wLength;
error = USB_DeviceClassCallback(handle, kUSB_DeviceEventVendorRequest, &controlRequest);
length = controlRequest.length;
buffer = controlRequest.buffer;
}
else
{
}
}
}
/* Send the response to the host. */
error = USB_DeviceControlCallbackFeedback(handle, deviceSetup, error, kUSB_DeviceControlPipeSetupStage, &buffer,
&length);
}
else if (kUSB_DeviceStateAddressing == state)
{
/* Set the device address to controller. */
error = s_UsbDeviceStandardRequest[deviceSetup->bRequest](classHandle, deviceSetup, &buffer, &length);
}
#if ((defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U)) || \
(defined(USB_DEVICE_CONFIG_LPCIP3511HS) && (USB_DEVICE_CONFIG_LPCIP3511HS > 0U))) && \
(defined(USB_DEVICE_CONFIG_USB20_TEST_MODE) && (USB_DEVICE_CONFIG_USB20_TEST_MODE > 0U))
else if (kUSB_DeviceStateTestMode == state)
{
uint8_t portTestControl = (uint8_t)(deviceSetup->wIndex >> 8);
/* Set the controller.into test mode. */
error = USB_DeviceSetStatus(handle, kUSB_DeviceStatusTestMode, &portTestControl);
}
#endif
else if ((message->length) && (deviceSetup->wLength) &&
((deviceSetup->bmRequestType & USB_REQUEST_TYPE_DIR_MASK) == USB_REQUEST_TYPE_DIR_OUT))
{
if (((deviceSetup->bmRequestType & USB_REQUEST_TYPE_TYPE_CLASS) == USB_REQUEST_TYPE_TYPE_CLASS))
{
/* Data received in OUT phase, and notify the class driver. */
usb_device_control_request_struct_t controlRequest;
controlRequest.buffer = message->buffer;
controlRequest.isSetup = 0U;
controlRequest.setup = deviceSetup;
controlRequest.length = message->length;
error = USB_DeviceClassEvent(handle, kUSB_DeviceClassEventClassRequest, &controlRequest);
}
else if (((deviceSetup->bmRequestType & USB_REQUEST_TYPE_TYPE_VENDOR) == USB_REQUEST_TYPE_TYPE_VENDOR))
{
/* Data received in OUT phase, and notify the application. */
usb_device_control_request_struct_t controlRequest;
controlRequest.buffer = message->buffer;
controlRequest.isSetup = 0U;
controlRequest.setup = deviceSetup;
controlRequest.length = message->length;
error = USB_DeviceClassCallback(handle, kUSB_DeviceEventVendorRequest, &controlRequest);
}
else
{
}
/* Send the response to the host. */
error = USB_DeviceControlCallbackFeedback(handle, deviceSetup, error, kUSB_DeviceControlPipeDataStage, &buffer,
&length);
}
else
{
}
return error;
}
/*!
* @brief Control endpoint initialization function.
*
* This callback function is used to initialize the control pipes.
*
* @param handle The device handle. It equals the value returned from USB_DeviceInit.
* @param param The up layer handle.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceControlPipeInit(usb_device_handle handle, void *param)
{
usb_device_endpoint_init_struct_t epInitStruct;
usb_device_endpoint_callback_struct_t epCallback;
usb_status_t error;
epCallback.callbackFn = USB_DeviceControlCallback;
epCallback.callbackParam = param;
epInitStruct.zlt = 1U;
epInitStruct.transferType = USB_ENDPOINT_CONTROL;
epInitStruct.interval = 0;
epInitStruct.endpointAddress = USB_CONTROL_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT);
epInitStruct.maxPacketSize = USB_CONTROL_MAX_PACKET_SIZE;
/* Initialize the control IN pipe */
error = USB_DeviceInitEndpoint(handle, &epInitStruct, &epCallback);
if (kStatus_USB_Success != error)
{
return error;
}
epInitStruct.endpointAddress = USB_CONTROL_ENDPOINT | (USB_OUT << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT);
/* Initialize the control OUT pipe */
error = USB_DeviceInitEndpoint(handle, &epInitStruct, &epCallback);
if (kStatus_USB_Success != error)
{
USB_DeviceDeinitEndpoint(handle,
USB_CONTROL_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT));
return error;
}
return kStatus_USB_Success;
}
#endif /* USB_DEVICE_CONFIG_NUM */

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __USB_DEVICE_CH9_H__
#define __USB_DEVICE_CH9_H__
/*******************************************************************************
* Definitions
******************************************************************************/
/*!
* @addtogroup usb_device_ch9
* @{
*/
/*! @brief Defines USB device status size when the host request to get device status */
#define USB_DEVICE_STATUS_SIZE (0x02U)
/*! @brief Defines USB device interface status size when the host request to get interface status */
#define USB_INTERFACE_STATUS_SIZE (0x02U)
/*! @brief Defines USB device endpoint status size when the host request to get endpoint status */
#define USB_ENDPOINT_STATUS_SIZE (0x02U)
/*! @brief Defines USB device configuration size when the host request to get current configuration */
#define USB_CONFIGURE_SIZE (0X01U)
/*! @brief Defines USB device interface alternate setting size when the host request to get interface alternate setting
*/
#define USB_INTERFACE_SIZE (0X01U)
/*! @brief Defines USB device status mask */
#define USB_GET_STATUS_DEVICE_MASK (0x03U)
/*! @brief Defines USB device interface status mask */
#define USB_GET_STATUS_INTERFACE_MASK (0x03U)
/*! @brief Defines USB device endpoint status mask */
#define USB_GET_STATUS_ENDPOINT_MASK (0x03U)
/*! @brief Control read and write sequence */
typedef enum _usb_device_control_read_write_sequence
{
kUSB_DeviceControlPipeSetupStage = 0U, /*!< Setup stage */
kUSB_DeviceControlPipeDataStage, /*!< Data stage */
kUSB_DeviceControlPipeStatusStage, /*!< status stage */
} usb_device_control_read_write_sequence_t;
#if defined(__cplusplus)
extern "C" {
#endif
/*******************************************************************************
* API
******************************************************************************/
/*!
* @brief Initializes the control pipes.
*
* The function is used to initialize the control pipes. This function should be called when event
* kUSB_DeviceEventBusReset is received.
*
* @param[in] handle The device handle.
* @param[in] param The event parameter.
*
* @return A USB error code or kStatus_USB_Success.
*/
extern usb_status_t USB_DeviceControlPipeInit(usb_device_handle handle, void *param);
#if defined(__cplusplus)
}
#endif
/*! @}*/
#endif /* __USB_DEVICE_CH9_H__ */

View File

@@ -0,0 +1,552 @@
/*
* Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc.
* Copyright 2016, 2019 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "usb_device_config.h"
#include "usb.h"
#include "usb_device.h"
#include "usb_device_ch9.h"
#include "usb_device_class.h"
#if ((defined(USB_DEVICE_CONFIG_NUM)) && (USB_DEVICE_CONFIG_NUM > 0U))
/* Include the class drivers according to the usb_device_config.h. */
#if ((defined(USB_DEVICE_CONFIG_HID)) && (USB_DEVICE_CONFIG_HID > 0U))
#include "usb_device_hid.h"
#endif
#if ((defined(USB_DEVICE_CONFIG_CDC_ACM)) && (USB_DEVICE_CONFIG_CDC_ACM > 0U))
#include "usb_device_cdc_acm.h"
#endif
#if ((defined(USB_DEVICE_CONFIG_MSC)) && (USB_DEVICE_CONFIG_MSC > 0U))
#include "usb_device_msc.h"
#endif
#if ((defined(USB_DEVICE_CONFIG_AUDIO)) && (USB_DEVICE_CONFIG_AUDIO > 0U))
#include "usb_device_audio.h"
#endif
#if ((defined(USB_DEVICE_CONFIG_PHDC)) && (USB_DEVICE_CONFIG_PHDC > 0U))
#include "usb_device_phdc.h"
#endif
#if ((defined(USB_DEVICE_CONFIG_VIDEO)) && (USB_DEVICE_CONFIG_VIDEO > 0U))
#include "usb_device_video.h"
#endif
#if ((defined(USB_DEVICE_CONFIG_PRINTER)) && (USB_DEVICE_CONFIG_PRINTER > 0U))
#include "usb_device_printer.h"
#endif
#if ((defined(USB_DEVICE_CONFIG_DFU)) && (USB_DEVICE_CONFIG_DFU > 0U))
#include "usb_device_dfu.h"
#endif
#if ((defined(USB_DEVICE_CONFIG_CCID)) && (USB_DEVICE_CONFIG_CCID > 0U))
#include "usb_device_ccid.h"
#endif
/*******************************************************************************
* Definitions
******************************************************************************/
/*******************************************************************************
* Prototypes
******************************************************************************/
static usb_status_t USB_DeviceClassAllocateHandle(uint8_t controllerId, usb_device_common_class_struct_t **handle);
static usb_status_t USB_DeviceClassFreeHandle(uint8_t controllerId);
static usb_status_t USB_DeviceClassGetHandleByControllerId(uint8_t controllerId,
usb_device_common_class_struct_t **handle);
static usb_status_t USB_DeviceClassGetHandleByDeviceHandle(usb_device_handle deviceHandle,
usb_device_common_class_struct_t **handle);
/*******************************************************************************
* Variables
******************************************************************************/
/* The device class driver list. */
static const usb_device_class_map_t s_UsbDeviceClassInterfaceMap[] = {
#if ((defined(USB_DEVICE_CONFIG_HID)) && (USB_DEVICE_CONFIG_HID > 0U))
{USB_DeviceHidInit, USB_DeviceHidDeinit, USB_DeviceHidEvent, kUSB_DeviceClassTypeHid},
#endif
#if ((defined(USB_DEVICE_CONFIG_CDC_ACM)) && (USB_DEVICE_CONFIG_CDC_ACM > 0U))
{USB_DeviceCdcAcmInit, USB_DeviceCdcAcmDeinit, USB_DeviceCdcAcmEvent, kUSB_DeviceClassTypeCdc},
#endif
#if ((defined(USB_DEVICE_CONFIG_MSC)) && (USB_DEVICE_CONFIG_MSC > 0U))
{USB_DeviceMscInit, USB_DeviceMscDeinit, USB_DeviceMscEvent, kUSB_DeviceClassTypeMsc},
#endif
#if ((defined USB_DEVICE_CONFIG_AUDIO) && (USB_DEVICE_CONFIG_AUDIO > 0U))
{USB_DeviceAudioInit, USB_DeviceAudioDeinit, USB_DeviceAudioEvent, kUSB_DeviceClassTypeAudio},
#endif
#if ((defined USB_DEVICE_CONFIG_PHDC) && (USB_DEVICE_CONFIG_PHDC > 0U))
{USB_DevicePhdcInit, USB_DevicePhdcDeinit, USB_DevicePhdcEvent, kUSB_DeviceClassTypePhdc},
#endif
#if ((defined USB_DEVICE_CONFIG_VIDEO) && (USB_DEVICE_CONFIG_VIDEO > 0U))
{USB_DeviceVideoInit, USB_DeviceVideoDeinit, USB_DeviceVideoEvent, kUSB_DeviceClassTypeVideo},
#endif
#if ((defined USB_DEVICE_CONFIG_PRINTER) && (USB_DEVICE_CONFIG_PRINTER > 0U))
{USB_DevicePrinterInit, USB_DevicePrinterDeinit, USB_DevicePrinterEvent, kUSB_DeviceClassTypePrinter},
#endif
#if ((defined USB_DEVICE_CONFIG_DFU) && (USB_DEVICE_CONFIG_DFU > 0U))
{USB_DeviceDfuInit, USB_DeviceDfuDeinit, USB_DeviceDfuEvent, kUSB_DeviceClassTypeDfu},
#endif
#if ((defined USB_DEVICE_CONFIG_CCID) && (USB_DEVICE_CONFIG_CCID > 0U))
{USB_DeviceCcidInit, USB_DeviceCcidDeinit, USB_DeviceCcidEvent, kUSB_DeviceClassTypeCcid},
#endif
{(usb_device_class_init_call_t)NULL, (usb_device_class_deinit_call_t)NULL, (usb_device_class_event_callback_t)NULL,
(usb_device_class_type_t)0},
};
USB_GLOBAL USB_RAM_ADDRESS_ALIGNMENT(USB_DATA_ALIGN_SIZE) static usb_device_common_class_struct_t
s_UsbDeviceCommonClassStruct[USB_DEVICE_CONFIG_NUM];
USB_GLOBAL USB_RAM_ADDRESS_ALIGNMENT(USB_DATA_ALIGN_SIZE) static uint8_t
s_UsbDeviceSetupBuffer[USB_DEVICE_CONFIG_NUM][USB_DATA_ALIGN_SIZE_MULTIPLE(USB_SETUP_PACKET_SIZE)];
/*******************************************************************************
* Code
******************************************************************************/
/*!
* @brief Allocate a device common class handle.
*
* This function allocates a a device common class handle.
*
* @param controllerId The controller id of the USB IP. Please refer to the enumeration usb_controller_index_t.
* @param handle It is out parameter, is used to return pointer of the device common class handle to the
* caller.
*
* @retval kStatus_USB_Success Get a device handle successfully.
* @retval kStatus_USB_Busy Cannot allocate a common class handle.
* @retval kStatus_USB_Error The common class has been initialized.
*/
static usb_status_t USB_DeviceClassAllocateHandle(uint8_t controllerId, usb_device_common_class_struct_t **handle)
{
uint32_t count;
USB_OSA_SR_ALLOC();
USB_OSA_ENTER_CRITICAL();
/* Check the controller is initialized or not. */
for (count = 0U; count < USB_DEVICE_CONFIG_NUM; count++)
{
if ((NULL != s_UsbDeviceCommonClassStruct[count].handle) &&
(controllerId == s_UsbDeviceCommonClassStruct[count].controllerId))
{
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_Error;
}
}
/* Get a free common class handle. */
for (count = 0U; count < USB_DEVICE_CONFIG_NUM; count++)
{
if (NULL == s_UsbDeviceCommonClassStruct[count].handle)
{
s_UsbDeviceCommonClassStruct[count].controllerId = controllerId;
s_UsbDeviceCommonClassStruct[count].setupBuffer = s_UsbDeviceSetupBuffer[count];
*handle = &s_UsbDeviceCommonClassStruct[count];
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_Success;
}
}
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_Busy;
}
/*!
* @brief Free a device common class handle.
*
* This function frees a device common class handle.
*
* @param controllerId The controller id of the USB IP. Please refer to the enumeration usb_controller_index_t.
*
* @retval kStatus_USB_Success Free device handle successfully.
* @retval kStatus_USB_InvalidParameter The common class can not be found.
*/
static usb_status_t USB_DeviceClassFreeHandle(uint8_t controllerId)
{
uint32_t count = 0U;
USB_OSA_SR_ALLOC();
USB_OSA_ENTER_CRITICAL();
for (; count < USB_DEVICE_CONFIG_NUM; count++)
{
if ((NULL != s_UsbDeviceCommonClassStruct[count].handle) &&
(controllerId == s_UsbDeviceCommonClassStruct[count].controllerId))
{
s_UsbDeviceCommonClassStruct[count].handle = NULL;
s_UsbDeviceCommonClassStruct[count].configList = (usb_device_class_config_list_struct_t *)NULL;
s_UsbDeviceCommonClassStruct[count].controllerId = 0U;
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_Success;
}
}
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_InvalidParameter;
}
/*!
* @brief Get the device common class handle according to the controller id.
*
* This function gets the device common class handle according to the controller id.
*
* @param controllerId The controller id of the USB IP. Please refer to the enumeration usb_controller_index_t.
* @param handle It is out parameter, is used to return pointer of the device common class handle to the
* caller.
*
* @retval kStatus_USB_Success Free device handle successfully.
* @retval kStatus_USB_InvalidParameter The common class can not be found.
*/
static usb_status_t USB_DeviceClassGetHandleByControllerId(uint8_t controllerId,
usb_device_common_class_struct_t **handle)
{
uint32_t count = 0U;
USB_OSA_SR_ALLOC();
USB_OSA_ENTER_CRITICAL();
for (; count < USB_DEVICE_CONFIG_NUM; count++)
{
if ((NULL != s_UsbDeviceCommonClassStruct[count].handle) &&
(controllerId == s_UsbDeviceCommonClassStruct[count].controllerId))
{
*handle = &s_UsbDeviceCommonClassStruct[count];
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_Success;
}
}
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_InvalidParameter;
}
/*!
* @brief Get the device common class handle according to the device handle.
*
* This function gets the device common class handle according to the device handle.
*
* @param deviceHandle The device handle, got from the USB_DeviceInit.
* @param handle It is out parameter, is used to return pointer of the device common class handle to the
* caller.
*
* @retval kStatus_USB_Success Free device handle successfully.
* @retval kStatus_USB_InvalidParameter The common class can not be found.
*/
static usb_status_t USB_DeviceClassGetHandleByDeviceHandle(usb_device_handle deviceHandle,
usb_device_common_class_struct_t **handle)
{
uint32_t count = 0U;
USB_OSA_SR_ALLOC();
USB_OSA_ENTER_CRITICAL();
for (; count < USB_DEVICE_CONFIG_NUM; count++)
{
if (deviceHandle == s_UsbDeviceCommonClassStruct[count].handle)
{
*handle = &s_UsbDeviceCommonClassStruct[count];
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_Success;
}
}
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_InvalidParameter;
}
/*!
* @brief Get the device handle according to the controller id.
*
* This function gets the device handle according to the controller id.
*
* @param controllerId The controller id of the USB IP. Please refer to the enumeration usb_controller_index_t.
* @param handle It is out parameter, is used to return pointer of the device handle to the caller.
*
* @retval kStatus_USB_Success Free device handle successfully.
* @retval kStatus_USB_InvalidParameter The device handle not be found.
*/
usb_status_t USB_DeviceClassGetDeviceHandle(uint8_t controllerId, usb_device_handle *handle)
{
uint32_t count = 0U;
USB_OSA_SR_ALLOC();
USB_OSA_ENTER_CRITICAL();
for (; count < USB_DEVICE_CONFIG_NUM; count++)
{
if ((NULL != s_UsbDeviceCommonClassStruct[count].handle) &&
(controllerId == s_UsbDeviceCommonClassStruct[count].controllerId))
{
*handle = s_UsbDeviceCommonClassStruct[count].handle;
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_Success;
}
}
USB_OSA_EXIT_CRITICAL();
return kStatus_USB_InvalidParameter;
}
/*!
* @brief Handle the event passed to the class drivers.
*
* This function handles the event passed to the class drivers.
*
* @param handle The device handle, got from the USB_DeviceInit.
* @param event The event codes. Please refer to the enumeration usb_device_class_event_t.
* @param param The param type is determined by the event code.
*
* @return A USB error code or kStatus_USB_Success.
* @retval kStatus_USB_Success A valid request has been handled.
* @retval kStatus_USB_InvalidParameter The device handle not be found.
* @retval kStatus_USB_InvalidRequest The request is invalid, and the control pipe will be stalled by the caller.
*/
usb_status_t USB_DeviceClassEvent(usb_device_handle handle, usb_device_class_event_t event, void *param)
{
usb_device_common_class_struct_t *classHandle;
uint8_t mapIndex;
uint8_t classIndex;
usb_status_t errorReturn = kStatus_USB_Error;
usb_status_t error = kStatus_USB_Error;
if (NULL == param)
{
return kStatus_USB_InvalidParameter;
}
/* Get the common class handle according to the device handle. */
errorReturn = USB_DeviceClassGetHandleByDeviceHandle(handle, &classHandle);
if (kStatus_USB_Success != errorReturn)
{
return kStatus_USB_InvalidParameter;
}
for (classIndex = 0U; classIndex < classHandle->configList->count; classIndex++)
{
for (mapIndex = 0U; mapIndex < (sizeof(s_UsbDeviceClassInterfaceMap) / sizeof(usb_device_class_map_t));
mapIndex++)
{
if (s_UsbDeviceClassInterfaceMap[mapIndex].type ==
classHandle->configList->config[classIndex].classInfomation->type)
{
/* Call class event callback of supported class */
errorReturn = s_UsbDeviceClassInterfaceMap[mapIndex].classEventCallback(
(void *)classHandle->configList->config[classIndex].classHandle, event, param);
/* Return the error code kStatus_USB_InvalidRequest immediately, when a class returns
* kStatus_USB_InvalidRequest. */
if (kStatus_USB_InvalidRequest == errorReturn)
{
return kStatus_USB_InvalidRequest;
}
/* For composite device, it should return kStatus_USB_Success once a valid request has been handled */
if (kStatus_USB_Success == errorReturn)
{
error = kStatus_USB_Success;
}
break;
}
}
}
return error;
}
/*!
* @brief Handle the common class callback.
*
* This function handles the common class callback.
*
* @param handle The device handle, got from the USB_DeviceInit.
* @param event The event codes. Please refer to the enumeration usb_device_event_t.
* @param param The param type is determined by the event code.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceClassCallback(usb_device_handle handle, uint32_t event, void *param)
{
usb_device_common_class_struct_t *classHandle;
usb_status_t error = kStatus_USB_Error;
/* Get the common class handle according to the device handle. */
error = USB_DeviceClassGetHandleByDeviceHandle(handle, &classHandle);
if (kStatus_USB_Success != error)
{
return error;
}
if (kUSB_DeviceEventBusReset == event)
{
/* Initialize the control pipes */
USB_DeviceControlPipeInit(handle, classHandle);
/* Notify the classes the USB bus reset signal detected. */
USB_DeviceClassEvent(handle, kUSB_DeviceClassEventDeviceReset, classHandle);
}
/* Call the application device callback function. deviceCallback is from the second parameter of
USB_DeviceClassInit */
error = classHandle->configList->deviceCallback(handle, event, param);
return error;
}
/*!
* @brief Initialize the common class and the supported classes.
*
* This function is used to initialize the common class and the supported classes.
*
* @param[in] controllerId The controller id of the USB IP. Please refer to the enumeration #usb_controller_index_t.
* @param[in] configList The class configurations. The pointer must point to the global variable.
* Please refer to the structure #usb_device_class_config_list_struct_t.
* @param[out] handle It is out parameter, is used to return pointer of the device handle to the caller.
* The value of parameter is a pointer points the device handle, and this design is used to
* make simple device align with composite device. For composite device, there are many
* kinds of class handle, but there is only one device handle. So the handle points to
* a device instead of a class. And the class handle can be got from the
* #usb_device_class_config_struct_t::classHandle after the function successfully.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceClassInit(
uint8_t controllerId, /*!< [IN] Controller ID */
usb_device_class_config_list_struct_t *configList, /*!< [IN] Pointer to class configuration list */
usb_device_handle *handle /*!< [OUT] Pointer to the device handle */
)
{
usb_device_common_class_struct_t *classHandle;
usb_status_t error = kStatus_USB_Error;
uint8_t mapIndex;
uint8_t classIndex;
if ((NULL == handle) || (NULL == configList) || ((usb_device_callback_t)NULL == configList->deviceCallback))
{
return kStatus_USB_InvalidParameter;
}
/* Allocate a common class driver handle. */
error = USB_DeviceClassAllocateHandle(controllerId, &classHandle);
if (kStatus_USB_Success != error)
{
return error;
}
/* Save the configuration list */
classHandle->configList = configList;
/* Initialize the device stack. */
error = USB_DeviceInit(controllerId, USB_DeviceClassCallback, &classHandle->handle);
if (kStatus_USB_Success != error)
{
USB_DeviceDeinit(classHandle->handle);
USB_DeviceClassFreeHandle(controllerId);
return error;
}
/* Initialize the all supported classes according to the configuration list. */
for (classIndex = 0U; classIndex < classHandle->configList->count; classIndex++)
{
for (mapIndex = 0U; mapIndex < (sizeof(s_UsbDeviceClassInterfaceMap) / sizeof(usb_device_class_map_t));
mapIndex++)
{
if (classHandle->configList->config[classIndex].classInfomation->type ==
s_UsbDeviceClassInterfaceMap[mapIndex].type)
{
(void)s_UsbDeviceClassInterfaceMap[mapIndex].classInit(
controllerId, &classHandle->configList->config[classIndex],
&classHandle->configList->config[classIndex].classHandle);
}
}
}
*handle = classHandle->handle;
return error;
}
/*!
* @brief De-initialize the common class and the supported classes.
*
* This function is used to de-initialize the common class and the supported classes.
*
* @param controllerId The controller id of the USB IP. Please refer to the enumeration usb_controller_index_t.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceClassDeinit(uint8_t controllerId /*!< [IN] Controller ID */
)
{
usb_device_common_class_struct_t *classHandle;
usb_status_t error = kStatus_USB_Error;
uint8_t mapIndex;
uint8_t classIndex;
/* Get the common class handle according to the controller id. */
error = USB_DeviceClassGetHandleByControllerId(controllerId, &classHandle);
if (kStatus_USB_Success != error)
{
return error;
}
/* De-initialize the all supported classes according to the configuration list. */
for (classIndex = 0U; classIndex < classHandle->configList->count; classIndex++)
{
for (mapIndex = 0U; mapIndex < (sizeof(s_UsbDeviceClassInterfaceMap) / sizeof(usb_device_class_map_t));
mapIndex++)
{
if (classHandle->configList->config[classIndex].classInfomation->type ==
s_UsbDeviceClassInterfaceMap[mapIndex].type)
{
(void)s_UsbDeviceClassInterfaceMap[mapIndex].classDeinit(
classHandle->configList->config[classIndex].classHandle);
}
}
}
/* De-initialize the USB device stack. */
error = USB_DeviceDeinit(classHandle->handle);
if (kStatus_USB_Success == error)
{
/* Free the common class handle. */
(void)USB_DeviceClassFreeHandle(controllerId);
}
return error;
}
/*!
* @brief Get the USB bus speed.
*
* This function is used to get the USB bus speed.
*
* @param controllerId The controller id of the USB IP. Please refer to the enumeration usb_controller_index_t.
* @param speed It is an OUT parameter, return current speed of the controller.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceClassGetSpeed(uint8_t controllerId, /*!< [IN] Controller ID */
uint8_t *speed /*!< [OUT] Current speed */
)
{
usb_device_common_class_struct_t *classHandle;
usb_status_t error = kStatus_USB_Error;
/* Get the common class handle according to the controller id. */
error = USB_DeviceClassGetHandleByControllerId(controllerId, &classHandle);
if (kStatus_USB_Success != error)
{
return error;
}
/* Get the current speed. */
error = USB_DeviceGetStatus(classHandle->handle, kUSB_DeviceStatusSpeed, speed);
return error;
}
#endif /* USB_DEVICE_CONFIG_NUM */

View File

@@ -0,0 +1,421 @@
/*
* Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc.
* Copyright 2016 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __USB_DEVICE_CLASS_H__
#define __USB_DEVICE_CLASS_H__
/*!
* @addtogroup usb_device_class_driver
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief Macro to define class handle */
#define class_handle_t uint32_t
/*! @brief Available class types. */
typedef enum _usb_usb_device_class_type
{
kUSB_DeviceClassTypeHid = 1U,
kUSB_DeviceClassTypeCdc,
kUSB_DeviceClassTypeMsc,
kUSB_DeviceClassTypeAudio,
kUSB_DeviceClassTypePhdc,
kUSB_DeviceClassTypeVideo,
kUSB_DeviceClassTypePrinter,
kUSB_DeviceClassTypeDfu,
kUSB_DeviceClassTypeCcid,
} usb_device_class_type_t;
/*! @brief Available common class events. */
typedef enum _usb_device_class_event
{
kUSB_DeviceClassEventClassRequest = 1U,
kUSB_DeviceClassEventDeviceReset,
kUSB_DeviceClassEventSetConfiguration,
kUSB_DeviceClassEventSetInterface,
kUSB_DeviceClassEventSetEndpointHalt,
kUSB_DeviceClassEventClearEndpointHalt,
} usb_device_class_event_t;
/*!
* @brief Obtains the endpoint data structure.
*
* Define the endpoint data structure.
*
*/
typedef struct _usb_device_endpoint_struct
{
uint8_t endpointAddress; /*!< Endpoint address*/
uint8_t transferType; /*!< Endpoint transfer type*/
uint16_t maxPacketSize; /*!< Endpoint maximum packet size */
uint8_t interval; /*!< Endpoint interval*/
} usb_device_endpoint_struct_t;
/*!
* @brief Obtains the endpoint group.
*
* Structure representing endpoints and the number of endpoints that the user wants.
*
*/
typedef struct _usb_device_endpoint_list
{
uint8_t count; /*!< How many endpoints in current interface*/
usb_device_endpoint_struct_t *endpoint; /*!< Endpoint structure list*/
} usb_device_endpoint_list_t;
/*!
* @brief Obtains the interface list data structure.
*
* Structure representing an interface.
*
*/
typedef struct _usb_device_interface_struct
{
uint8_t alternateSetting; /*!< Alternate setting number*/
usb_device_endpoint_list_t endpointList; /*!< Endpoints of the interface*/
void *classSpecific; /*!< Class specific structure handle*/
} usb_device_interface_struct_t;
/*!
* @brief Obtains the interface data structure.
*
* Structure representing interface.
*
*/
typedef struct _usb_device_interfaces_struct
{
uint8_t classCode; /*!< Class code of the interface*/
uint8_t subclassCode; /*!< Subclass code of the interface*/
uint8_t protocolCode; /*!< Protocol code of the interface*/
uint8_t interfaceNumber; /*!< Interface number*/
usb_device_interface_struct_t *interface; /*!< Interface structure list*/
uint8_t count; /*!< Number of interfaces in the current interface*/
} usb_device_interfaces_struct_t;
/*!
* @brief Obtains the interface group.
*
* Structure representing how many interfaces in one class type.
*
*/
typedef struct _usb_device_interface_list
{
uint8_t count; /*!< Number of interfaces of the class*/
usb_device_interfaces_struct_t *interfaces; /*!< All interfaces*/
} usb_device_interface_list_t;
/*!
* @brief Obtains the class data structure.
*
* Structure representing how many configurations in one class type.
*
*/
typedef struct _usb_device_class_struct
{
usb_device_interface_list_t *interfaceList; /*!< Interfaces of the class*/
usb_device_class_type_t type; /*!< Class type*/
uint8_t configurations; /*!< Number of configurations of the class*/
} usb_device_class_struct_t;
/*callback function pointer structure for application to provide class parameters*/
typedef usb_status_t (*usb_device_class_callback_t)(class_handle_t classHandle,
uint32_t callbackEvent,
void *eventParam);
/*!
* @brief Obtains the device class information structure.
*
* Structure representing the device class information. This structure only can be stored in RAM space.
*
*/
typedef struct _usb_device_class_config_struct
{
usb_device_class_callback_t classCallback; /*!< Class callback function to handle the device status-related event
for the specified type of class*/
class_handle_t classHandle; /*!< The class handle of the class, filled by the common driver.*/
usb_device_class_struct_t *classInfomation; /*!< Detailed information of the class*/
} usb_device_class_config_struct_t;
/*!
* @brief Obtains the device class configuration structure.
*
* Structure representing the device class configuration information.
*
*/
typedef struct _usb_device_class_config_list_struct
{
usb_device_class_config_struct_t *config; /*!< Array of class configuration structures */
usb_device_callback_t deviceCallback; /*!< Device callback function */
uint8_t count; /*!< Number of class supported */
} usb_device_class_config_list_struct_t;
/*!
* @brief Obtains the control request structure.
*
* This structure is used to pass the control request information.
* The structure is used in following two cases.
* 1. Case one, the host wants to send data to the device in the control data stage: @n
* a. If a setup packet is received, the structure is used to pass the setup packet data and wants to get the
* buffer to receive data sent from the host.
* The field isSetup is 1.
* The length is the requested buffer length.
* The buffer is filled by the class or application by using the valid buffer address.
* The setup is the setup packet address.
* b. If the data received is sent by the host, the structure is used to pass the data buffer address and the
* data
* length sent by the host.
* In this way, the field isSetup is 0.
* The buffer is the address of the data sent from the host.
* The length is the received data length.
* The setup is the setup packet address. @n
* 2. Case two, the host wants to get data from the device in control data stage: @n
* If the setup packet is received, the structure is used to pass the setup packet data and wants to get the
* data buffer address to send data to the host.
* The field isSetup is 1.
* The length is the requested data length.
* The buffer is filled by the class or application by using the valid buffer address.
* The setup is the setup packet address.
*
*/
typedef struct _usb_device_control_request_struct
{
usb_setup_struct_t *setup; /*!< The pointer of the setup packet data. */
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length or requested length. */
uint8_t isSetup; /*!< Indicates whether a setup packet is received. */
} usb_device_control_request_struct_t;
/*! @brief Obtains the control get descriptor request common structure. */
typedef struct _usb_device_get_descriptor_common_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
} usb_device_get_descriptor_common_struct_t;
/*! @brief Obtains the control get device descriptor request structure. */
typedef struct _usb_device_get_device_descriptor_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
} usb_device_get_device_descriptor_struct_t;
/*! @brief Obtains the control get device qualifier descriptor request structure. */
typedef struct _usb_device_get_device_qualifier_descriptor_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
} usb_device_get_device_qualifier_descriptor_struct_t;
/*! @brief Obtains the control get configuration descriptor request structure. */
typedef struct _usb_device_get_configuration_descriptor_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
uint8_t configuration; /*!< The configuration number. */
} usb_device_get_configuration_descriptor_struct_t;
/*! @brief Obtains the control get bos descriptor request structure. */
typedef struct _usb_device_get_bos_descriptor_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
} usb_device_get_bos_descriptor_struct_t;
/*! @brief Obtains the control get string descriptor request structure. */
typedef struct _usb_device_get_string_descriptor_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
uint16_t languageId; /*!< Language ID. */
uint8_t stringIndex; /*!< String index. */
} usb_device_get_string_descriptor_struct_t;
/*! @brief Obtains the control get HID descriptor request structure. */
typedef struct _usb_device_get_hid_descriptor_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
uint8_t interfaceNumber; /*!< The interface number. */
} usb_device_get_hid_descriptor_struct_t;
/*! @brief Obtains the control get HID report descriptor request structure. */
typedef struct _usb_device_get_hid_report_descriptor_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
uint8_t interfaceNumber; /*!< The interface number. */
} usb_device_get_hid_report_descriptor_struct_t;
/*! @brief Obtains the control get HID physical descriptor request structure. */
typedef struct _usb_device_get_hid_physical_descriptor_struct
{
uint8_t *buffer; /*!< Pass the buffer address. */
uint32_t length; /*!< Pass the buffer length. */
uint8_t index; /*!< Physical index */
uint8_t interfaceNumber; /*!< The interface number. */
} usb_device_get_hid_physical_descriptor_struct_t;
/*! @brief Obtains the control get descriptor request common union. */
typedef union _usb_device_get_descriptor_common_union
{
usb_device_get_descriptor_common_struct_t commonDescriptor; /*!< Common structure. */
usb_device_get_device_descriptor_struct_t deviceDescriptor; /*!< The structure to get device descriptor. */
usb_device_get_device_qualifier_descriptor_struct_t
deviceQualifierDescriptor; /*!< The structure to get device qualifier descriptor. */
usb_device_get_configuration_descriptor_struct_t
configurationDescriptor; /*!< The structure to get configuration descriptor. */
usb_device_get_string_descriptor_struct_t stringDescriptor; /*!< The structure to get string descriptor. */
usb_device_get_hid_descriptor_struct_t hidDescriptor; /*!< The structure to get HID descriptor. */
usb_device_get_hid_report_descriptor_struct_t
hidReportDescriptor; /*!< The structure to get HID report descriptor. */
usb_device_get_hid_physical_descriptor_struct_t
hidPhysicalDescriptor; /*!< The structure to get HID physical descriptor. */
} usb_device_get_descriptor_common_union_t;
/*! @brief Define function type for class device instance initialization */
typedef usb_status_t (*usb_device_class_init_call_t)(uint8_t controllerId,
usb_device_class_config_struct_t *classConfig,
class_handle_t *classHandle);
/*! @brief Define function type for class device instance deinitialization, internal */
typedef usb_status_t (*usb_device_class_deinit_call_t)(class_handle_t handle);
/*! @brief Define function type for class device instance Event change */
typedef usb_status_t (*usb_device_class_event_callback_t)(void *classHandle, uint32_t event, void *param);
/*! @brief Define class driver interface structure. */
typedef struct _usb_device_class_map
{
usb_device_class_init_call_t classInit; /*!< Class driver initialization- entry of the class driver */
usb_device_class_deinit_call_t classDeinit; /*!< Class driver de-initialization*/
usb_device_class_event_callback_t classEventCallback; /*!< Class driver event callback*/
usb_device_class_type_t type; /*!< Class type*/
} usb_device_class_map_t;
/*! @brief Structure holding common class state information */
typedef struct _usb_device_common_class_struct
{
usb_device_handle handle; /*!< USB device handle*/
usb_device_class_config_list_struct_t *configList; /*!< USB device configure list*/
uint8_t *setupBuffer; /*!< Setup packet data buffer*/
uint16_t standardTranscationBuffer; /*!<
* This variable is used in:
* get status request
* get configuration request
* get interface request
* set interface request
* get sync frame request
*/
uint8_t controllerId; /*!< Controller ID*/
} usb_device_common_class_struct_t;
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @brief Initializes the common class and the supported classes.
*
* This function is used to initialize the common class and the supported classes.
*
* @param[in] controllerId The controller ID of the USB IP. See the enumeration #usb_controller_index_t.
* @param[in] configList The class configurations. The pointer must point to the global variable.
* See the structure #usb_device_class_config_list_struct_t.
* @param[out] handle A parameter used to return pointer of the device handle to the caller.
* The value of the parameter is a pointer to the device handle. This design is used to
* make a simple device align with the composite device. For the composite device, there are
* many
* kinds of class handles. However, there is only one device handle. Therefore, the handle
* points to
* a device instead of a class. The class handle can be received from the
* #usb_device_class_config_struct_t::classHandle after the function successfully.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceClassInit(uint8_t controllerId,
usb_device_class_config_list_struct_t *configList,
usb_device_handle *handle);
/*!
* @brief Deinitializes the common class and the supported classes.
*
* This function is used to deinitialize the common class and the supported classes.
*
* @param[in] controllerId The controller ID of the USB IP. See the enumeration #usb_controller_index_t.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceClassDeinit(uint8_t controllerId);
/*!
* @brief Gets the USB bus speed.
*
* This function is used to get the USB bus speed.
*
* @param[in] controllerId The controller ID of the USB IP. See the enumeration #usb_controller_index_t.
* @param[out] speed It is an OUT parameter, which returns the current speed of the controller.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceClassGetSpeed(uint8_t controllerId, uint8_t *speed);
/*!
* @brief Handles the event passed to the class drivers.
*
* This function handles the event passed to the class drivers.
*
* @param[in] handle The device handle received from the #USB_DeviceInit.
* @param[in] event The event codes. See the enumeration #usb_device_class_event_t.
* @param[in,out] param The parameter type is determined by the event code.
*
* @return A USB error code or kStatus_USB_Success.
* @retval kStatus_USB_Success A valid request has been handled.
* @retval kStatus_USB_InvalidParameter The device handle not be found.
* @retval kStatus_USB_InvalidRequest The request is invalid, and the control pipe is stalled by the caller.
*/
usb_status_t USB_DeviceClassEvent(usb_device_handle handle, usb_device_class_event_t event, void *param);
/*!
* @brief Handles the common class callback.
*
* This function handles the common class callback.
*
* @param[in] handle The device handle received from the #USB_DeviceInit.
* @param[in] event The event codes. See the enumeration #usb_device_event_t.
* @param[in,out] param The parameter type is determined by the event code.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceClassCallback(usb_device_handle handle, uint32_t event, void *param);
/*!
* @brief Gets the device handle according to the controller ID.
*
* This function gets the device handle according to the controller ID.
*
* @param[in] controllerId The controller ID of the USB IP. See the enumeration #usb_controller_index_t.
* @param[out] handle An out parameter used to return the pointer of the device handle to the caller.
*
* @retval kStatus_USB_Success Get device handle successfully.
* @retval kStatus_USB_InvalidParameter The device handle can't be found.
*/
usb_status_t USB_DeviceClassGetDeviceHandle(uint8_t controllerId, usb_device_handle *handle);
#if defined(__cplusplus)
}
#endif
/*! @}*/
#endif /* __USB_DEVICE_CLASS_H__ */

View File

@@ -0,0 +1,492 @@
/*
* Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc.
* Copyright 2016 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "usb_device_config.h"
#include "usb.h"
#include "usb_device.h"
#include "usb_device_class.h"
#include "usb_device_cdc_acm.h"
#include "usb_device_descriptor.h"
/*******************************************************************************
* Variables
******************************************************************************/
/* Define endpoint for communication class */
usb_device_endpoint_struct_t g_UsbDeviceCdcVcomCicEndpoints[USB_CDC_VCOM_ENDPOINT_CIC_COUNT] = {
{
USB_CDC_VCOM_INTERRUPT_IN_ENDPOINT | (USB_IN << 7U),
USB_ENDPOINT_INTERRUPT,
FS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE,
FS_CDC_VCOM_INTERRUPT_IN_INTERVAL,
},
};
/* Define endpoint for data class */
usb_device_endpoint_struct_t g_UsbDeviceCdcVcomDicEndpoints[USB_CDC_VCOM_ENDPOINT_DIC_COUNT] = {
{
USB_CDC_VCOM_BULK_IN_ENDPOINT | (USB_IN << 7U),
USB_ENDPOINT_BULK,
FS_CDC_VCOM_BULK_IN_PACKET_SIZE,
0U,
},
{
USB_CDC_VCOM_BULK_OUT_ENDPOINT | (USB_OUT << 7U),
USB_ENDPOINT_BULK,
FS_CDC_VCOM_BULK_OUT_PACKET_SIZE,
0U,
}};
/* Define interface for communication class */
usb_device_interface_struct_t g_UsbDeviceCdcVcomCommunicationInterface[] = {{0,
{
USB_CDC_VCOM_ENDPOINT_CIC_COUNT,
g_UsbDeviceCdcVcomCicEndpoints,
},
NULL}};
/* Define interface for data class */
usb_device_interface_struct_t g_UsbDeviceCdcVcomDataInterface[] = {{0,
{
USB_CDC_VCOM_ENDPOINT_DIC_COUNT,
g_UsbDeviceCdcVcomDicEndpoints,
},
NULL}};
/* Define interfaces for virtual com */
usb_device_interfaces_struct_t g_UsbDeviceCdcVcomInterfaces[USB_CDC_VCOM_INTERFACE_COUNT] = {
{USB_CDC_VCOM_CIC_CLASS, USB_CDC_VCOM_CIC_SUBCLASS, USB_CDC_VCOM_CIC_PROTOCOL, USB_CDC_VCOM_COMM_INTERFACE_INDEX,
g_UsbDeviceCdcVcomCommunicationInterface,
sizeof(g_UsbDeviceCdcVcomCommunicationInterface) / sizeof(usb_device_interfaces_struct_t)},
{USB_CDC_VCOM_DIC_CLASS, USB_CDC_VCOM_DIC_SUBCLASS, USB_CDC_VCOM_DIC_PROTOCOL, USB_CDC_VCOM_DATA_INTERFACE_INDEX,
g_UsbDeviceCdcVcomDataInterface, sizeof(g_UsbDeviceCdcVcomDataInterface) / sizeof(usb_device_interfaces_struct_t)},
};
/* Define configurations for virtual com */
usb_device_interface_list_t g_UsbDeviceCdcVcomInterfaceLIST_[USB_DEVICE_CONFIGURATION_COUNT] = {
{
USB_CDC_VCOM_INTERFACE_COUNT,
g_UsbDeviceCdcVcomInterfaces,
},
};
/* Define class information for virtual com */
usb_device_class_struct_t g_UsbDeviceCdcVcomConfig = {
g_UsbDeviceCdcVcomInterfaceLIST_,
kUSB_DeviceClassTypeCdc,
USB_DEVICE_CONFIGURATION_COUNT,
};
/* Define device descriptor */
USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE)
uint8_t g_UsbDeviceDescriptor[] = {
/* Size of this descriptor in bytes */
USB_DESCRIPTOR_LENGTH_DEVICE,
/* DEVICE Descriptor Type */
USB_DESCRIPTOR_TYPE_DEVICE,
/* USB Specification Release Number in Binary-Coded Decimal (i.e., 2.10 is 210H). */
USB_SHORT_GET_LOW(USB_DEVICE_SPECIFIC_BCD_VERSION),
USB_SHORT_GET_HIGH(USB_DEVICE_SPECIFIC_BCD_VERSION),
/* Class code (assigned by the USB-IF). */
USB_DEVICE_CLASS,
/* Subclass code (assigned by the USB-IF). */
USB_DEVICE_SUBCLASS,
/* Protocol code (assigned by the USB-IF). */
USB_DEVICE_PROTOCOL,
/* Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid) */
USB_CONTROL_MAX_PACKET_SIZE,
/* Vendor ID (assigned by the USB-IF) */
0xC9U,
0x1FU,
/* Product ID (assigned by the manufacturer) */
0x94,
0x00,
/* Device release number in binary-coded decimal */
USB_SHORT_GET_LOW(USB_DEVICE_DEMO_BCD_VERSION),
USB_SHORT_GET_HIGH(USB_DEVICE_DEMO_BCD_VERSION),
/* Index of string descriptor describing manufacturer */
0x01,
/* Index of string descriptor describing product */
0x02,
/* Index of string descriptor describing the device's serial number */
0x00,
/* Number of possible configurations */
USB_DEVICE_CONFIGURATION_COUNT,
};
/* Define configuration descriptor */
USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE)
uint8_t g_UsbDeviceConfigurationDescriptor[] = {
/* Size of this descriptor in bytes */
USB_DESCRIPTOR_LENGTH_CONFIGURE,
/* CONFIGURATION Descriptor Type */
USB_DESCRIPTOR_TYPE_CONFIGURE,
/* Total length of data returned for this configuration. */
USB_SHORT_GET_LOW(USB_DESCRIPTOR_LENGTH_CONFIGURE + USB_DESCRIPTOR_LENGTH_INTERFACE +
USB_DESCRIPTOR_LENGTH_CDC_HEADER_FUNC + USB_DESCRIPTOR_LENGTH_CDC_CALL_MANAG +
USB_DESCRIPTOR_LENGTH_CDC_ABSTRACT + USB_DESCRIPTOR_LENGTH_CDC_UNION_FUNC +
USB_DESCRIPTOR_LENGTH_ENDPOINT + USB_DESCRIPTOR_LENGTH_INTERFACE +
USB_DESCRIPTOR_LENGTH_ENDPOINT + USB_DESCRIPTOR_LENGTH_ENDPOINT),
USB_SHORT_GET_HIGH(USB_DESCRIPTOR_LENGTH_CONFIGURE + USB_DESCRIPTOR_LENGTH_INTERFACE +
USB_DESCRIPTOR_LENGTH_CDC_HEADER_FUNC + USB_DESCRIPTOR_LENGTH_CDC_CALL_MANAG +
USB_DESCRIPTOR_LENGTH_CDC_ABSTRACT + USB_DESCRIPTOR_LENGTH_CDC_UNION_FUNC +
USB_DESCRIPTOR_LENGTH_ENDPOINT + USB_DESCRIPTOR_LENGTH_INTERFACE +
USB_DESCRIPTOR_LENGTH_ENDPOINT + USB_DESCRIPTOR_LENGTH_ENDPOINT),
/* Number of interfaces supported by this configuration */
USB_CDC_VCOM_INTERFACE_COUNT,
/* Value to use as an argument to the SetConfiguration() request to select this configuration */
USB_CDC_VCOM_CONFIGURE_INDEX,
/* Index of string descriptor describing this configuration */
0,
/* Configuration characteristics D7: Reserved (set to one) D6: Self-powered D5: Remote Wakeup D4...0: Reserved
(reset to zero) */
(USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_D7_MASK) |
(USB_DEVICE_CONFIG_SELF_POWER << USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_SELF_POWERED_SHIFT) |
(USB_DEVICE_CONFIG_REMOTE_WAKEUP << USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_REMOTE_WAKEUP_SHIFT),
/* Maximum power consumption of the USB * device from the bus in this specific * configuration when the device is
fully * operational. Expressed in 2 mA units * (i.e., 50 = 100 mA). */
USB_DEVICE_MAX_POWER,
/* Communication Interface Descriptor */
USB_DESCRIPTOR_LENGTH_INTERFACE, USB_DESCRIPTOR_TYPE_INTERFACE, USB_CDC_VCOM_COMM_INTERFACE_INDEX, 0x00,
USB_CDC_VCOM_ENDPOINT_CIC_COUNT, USB_CDC_VCOM_CIC_CLASS, USB_CDC_VCOM_CIC_SUBCLASS, USB_CDC_VCOM_CIC_PROTOCOL,
0x00, /* Interface Description String Index*/
/* CDC Class-Specific descriptor */
USB_DESCRIPTOR_LENGTH_CDC_HEADER_FUNC, /* Size of this descriptor in bytes */
USB_DESCRIPTOR_TYPE_CDC_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */
USB_CDC_HEADER_FUNC_DESC, 0x10,
0x01, /* USB Class Definitions for Communications the Communication specification version 1.10 */
USB_DESCRIPTOR_LENGTH_CDC_CALL_MANAG, /* Size of this descriptor in bytes */
USB_DESCRIPTOR_TYPE_CDC_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */
USB_CDC_CALL_MANAGEMENT_FUNC_DESC,
0x01, /*Bit 0: Whether device handle call management itself 1, Bit 1: Whether device can send/receive call
management information over a Data Class Interface 0 */
0x01, /* Indicates multiplexed commands are handled via data interface */
USB_DESCRIPTOR_LENGTH_CDC_ABSTRACT, /* Size of this descriptor in bytes */
USB_DESCRIPTOR_TYPE_CDC_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */
USB_CDC_ABSTRACT_CONTROL_FUNC_DESC,
0x06, /* Bit 0: Whether device supports the request combination of Set_Comm_Feature, Clear_Comm_Feature, and
Get_Comm_Feature 0, Bit 1: Whether device supports the request combination of Set_Line_Coding,
Set_Control_Line_State, Get_Line_Coding, and the notification Serial_State 1, Bit ... */
USB_DESCRIPTOR_LENGTH_CDC_UNION_FUNC, /* Size of this descriptor in bytes */
USB_DESCRIPTOR_TYPE_CDC_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */
USB_CDC_UNION_FUNC_DESC, 0x00, /* The interface number of the Communications or Data Class interface */
0x01, /* Interface number of subordinate interface in the Union */
/*Notification Endpoint descriptor */
USB_DESCRIPTOR_LENGTH_ENDPOINT, USB_DESCRIPTOR_TYPE_ENDPOINT, USB_CDC_VCOM_INTERRUPT_IN_ENDPOINT | (USB_IN << 7U),
USB_ENDPOINT_INTERRUPT, USB_SHORT_GET_LOW(FS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE),
USB_SHORT_GET_HIGH(FS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE), FS_CDC_VCOM_INTERRUPT_IN_INTERVAL,
/* Data Interface Descriptor */
USB_DESCRIPTOR_LENGTH_INTERFACE, USB_DESCRIPTOR_TYPE_INTERFACE, USB_CDC_VCOM_DATA_INTERFACE_INDEX, 0x00,
USB_CDC_VCOM_ENDPOINT_DIC_COUNT, USB_CDC_VCOM_DIC_CLASS, USB_CDC_VCOM_DIC_SUBCLASS, USB_CDC_VCOM_DIC_PROTOCOL,
0x00, /* Interface Description String Index*/
/*Bulk IN Endpoint descriptor */
USB_DESCRIPTOR_LENGTH_ENDPOINT, USB_DESCRIPTOR_TYPE_ENDPOINT, USB_CDC_VCOM_BULK_IN_ENDPOINT | (USB_IN << 7U),
USB_ENDPOINT_BULK, USB_SHORT_GET_LOW(FS_CDC_VCOM_BULK_IN_PACKET_SIZE),
USB_SHORT_GET_HIGH(FS_CDC_VCOM_BULK_IN_PACKET_SIZE), 0x00, /* The polling interval value is every 0 Frames */
/*Bulk OUT Endpoint descriptor */
USB_DESCRIPTOR_LENGTH_ENDPOINT, USB_DESCRIPTOR_TYPE_ENDPOINT, USB_CDC_VCOM_BULK_OUT_ENDPOINT | (USB_OUT << 7U),
USB_ENDPOINT_BULK, USB_SHORT_GET_LOW(FS_CDC_VCOM_BULK_OUT_PACKET_SIZE),
USB_SHORT_GET_HIGH(FS_CDC_VCOM_BULK_OUT_PACKET_SIZE), 0x00, /* The polling interval value is every 0 Frames */
};
/* Define string descriptor */
USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE)
uint8_t g_UsbDeviceString0[] = {2U + 2U, USB_DESCRIPTOR_TYPE_STRING, 0x09, 0x04};
USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE)
uint8_t g_UsbDeviceString1[] = {
2U + 2U * 18U, USB_DESCRIPTOR_TYPE_STRING,
'N', 0x00U,
'X', 0x00U,
'P', 0x00U,
' ', 0x00U,
'S', 0x00U,
'E', 0x00U,
'M', 0x00U,
'I', 0x00U,
'C', 0x00U,
'O', 0x00U,
'N', 0x00U,
'D', 0x00U,
'U', 0x00U,
'C', 0x00U,
'T', 0x00U,
'O', 0x00U,
'R', 0x00U,
'S', 0x00U,
};
USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE)
uint8_t g_UsbDeviceString2[] = {2U + 2U * 20U, USB_DESCRIPTOR_TYPE_STRING,
'M', 0,
'C', 0,
'U', 0,
' ', 0,
'V', 0,
'I', 0,
'R', 0,
'T', 0,
'U', 0,
'A', 0,
'L', 0,
' ', 0,
'C', 0,
'O', 0,
'M', 0,
' ', 0,
'D', 0,
'E', 0,
'M', 0,
'O', 0};
uint8_t *g_UsbDeviceStringDescriptorArray[USB_DEVICE_STRING_COUNT] = {g_UsbDeviceString0, g_UsbDeviceString1,
g_UsbDeviceString2};
/* Define string descriptor size */
uint32_t g_UsbDeviceStringDescriptorLength[USB_DEVICE_STRING_COUNT] = {
sizeof(g_UsbDeviceString0), sizeof(g_UsbDeviceString1), sizeof(g_UsbDeviceString2)};
usb_language_t g_UsbDeviceLanguage[USB_DEVICE_LANGUAGE_COUNT] = {{
g_UsbDeviceStringDescriptorArray,
g_UsbDeviceStringDescriptorLength,
(uint16_t)0x0409,
}};
usb_language_list_t g_UsbDeviceLanguageList = {
g_UsbDeviceString0,
sizeof(g_UsbDeviceString0),
g_UsbDeviceLanguage,
USB_DEVICE_LANGUAGE_COUNT,
};
/*******************************************************************************
* Code
******************************************************************************/
/*!
* @brief USB device get device descriptor function.
*
* This function gets the device descriptor of the USB device.
*
* @param handle The USB device handle.
* @param deviceDescriptor The pointer to the device descriptor structure.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceGetDeviceDescriptor(usb_device_handle handle,
usb_device_get_device_descriptor_struct_t *deviceDescriptor)
{
deviceDescriptor->buffer = g_UsbDeviceDescriptor;
deviceDescriptor->length = USB_DESCRIPTOR_LENGTH_DEVICE;
return kStatus_USB_Success;
}
/*!
* @brief USB device get configuration descriptor function.
*
* This function gets the configuration descriptor of the USB device.
*
* @param handle The USB device handle.
* @param configurationDescriptor The pointer to the configuration descriptor structure.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceGetConfigurationDescriptor(
usb_device_handle handle, usb_device_get_configuration_descriptor_struct_t *configurationDescriptor)
{
if (USB_CDC_VCOM_CONFIGURE_INDEX > configurationDescriptor->configuration)
{
configurationDescriptor->buffer = g_UsbDeviceConfigurationDescriptor;
configurationDescriptor->length = USB_DESCRIPTOR_LENGTH_CONFIGURATION_ALL;
return kStatus_USB_Success;
}
return kStatus_USB_InvalidRequest;
}
/*!
* @brief USB device get string descriptor function.
*
* This function gets the string descriptor of the USB device.
*
* @param handle The USB device handle.
* @param stringDescriptor Pointer to the string descriptor structure.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceGetStringDescriptor(usb_device_handle handle,
usb_device_get_string_descriptor_struct_t *stringDescriptor)
{
if (stringDescriptor->stringIndex == 0U)
{
stringDescriptor->buffer = (uint8_t *)g_UsbDeviceLanguageList.languageString;
stringDescriptor->length = g_UsbDeviceLanguageList.stringLength;
}
else
{
uint8_t languageId = 0U;
uint8_t languageIndex = USB_DEVICE_STRING_COUNT;
for (; languageId < USB_DEVICE_LANGUAGE_COUNT; languageId++)
{
if (stringDescriptor->languageId == g_UsbDeviceLanguageList.languageList[languageId].languageId)
{
if (stringDescriptor->stringIndex < USB_DEVICE_STRING_COUNT)
{
languageIndex = stringDescriptor->stringIndex;
}
break;
}
}
if (USB_DEVICE_STRING_COUNT == languageIndex)
{
return kStatus_USB_InvalidRequest;
}
stringDescriptor->buffer = (uint8_t *)g_UsbDeviceLanguageList.languageList[languageId].string[languageIndex];
stringDescriptor->length = g_UsbDeviceLanguageList.languageList[languageId].length[languageIndex];
}
return kStatus_USB_Success;
}
/*!
* @brief USB device set speed function.
*
* This function sets the speed of the USB device.
*
* Due to the difference of HS and FS descriptors, the device descriptors and configurations need to be updated to match
* current speed.
* As the default, the device descriptors and configurations are configured by using FS parameters for both EHCI and
* KHCI.
* When the EHCI is enabled, the application needs to call this function to update device by using current speed.
* The updated information includes endpoint max packet size, endpoint interval, etc.
*
* @param handle The USB device handle.
* @param speed Speed type. USB_SPEED_HIGH/USB_SPEED_FULL/USB_SPEED_LOW.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceSetSpeed(usb_device_handle handle, uint8_t speed)
{
usb_descriptor_union_t *ptr1;
usb_descriptor_union_t *ptr2;
ptr1 = (usb_descriptor_union_t *)(&g_UsbDeviceConfigurationDescriptor[0]);
ptr2 = (usb_descriptor_union_t *)(&g_UsbDeviceConfigurationDescriptor[USB_DESCRIPTOR_LENGTH_CONFIGURATION_ALL - 1]);
while (ptr1 < ptr2)
{
if (ptr1->common.bDescriptorType == USB_DESCRIPTOR_TYPE_ENDPOINT)
{
if (USB_SPEED_HIGH == speed)
{
if (((ptr1->endpoint.bEndpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) ==
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_IN) &&
(USB_CDC_VCOM_INTERRUPT_IN_ENDPOINT ==
(ptr1->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)))
{
ptr1->endpoint.bInterval = HS_CDC_VCOM_INTERRUPT_IN_INTERVAL;
USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS(HS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE,
ptr1->endpoint.wMaxPacketSize);
}
else if (((ptr1->endpoint.bEndpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) ==
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_IN) &&
(USB_CDC_VCOM_BULK_IN_ENDPOINT ==
(ptr1->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)))
{
USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS(HS_CDC_VCOM_BULK_IN_PACKET_SIZE, ptr1->endpoint.wMaxPacketSize);
}
else if (((ptr1->endpoint.bEndpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) ==
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_OUT) &&
(USB_CDC_VCOM_BULK_OUT_ENDPOINT ==
(ptr1->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)))
{
USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS(HS_CDC_VCOM_BULK_OUT_PACKET_SIZE, ptr1->endpoint.wMaxPacketSize);
}
else
{
}
}
else
{
if (((ptr1->endpoint.bEndpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) ==
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_IN) &&
(USB_CDC_VCOM_INTERRUPT_IN_ENDPOINT ==
(ptr1->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)))
{
ptr1->endpoint.bInterval = FS_CDC_VCOM_INTERRUPT_IN_INTERVAL;
USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS(FS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE,
ptr1->endpoint.wMaxPacketSize);
}
else if (((ptr1->endpoint.bEndpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) ==
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_IN) &&
(USB_CDC_VCOM_BULK_IN_ENDPOINT ==
(ptr1->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)))
{
USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS(FS_CDC_VCOM_BULK_IN_PACKET_SIZE, ptr1->endpoint.wMaxPacketSize);
}
else if (((ptr1->endpoint.bEndpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK) ==
USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_OUT) &&
(USB_CDC_VCOM_BULK_OUT_ENDPOINT ==
(ptr1->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)))
{
USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS(FS_CDC_VCOM_BULK_OUT_PACKET_SIZE, ptr1->endpoint.wMaxPacketSize);
}
else
{
}
}
}
ptr1 = (usb_descriptor_union_t *)((uint8_t *)ptr1 + ptr1->common.bLength);
}
for (int i = 0; i < USB_CDC_VCOM_ENDPOINT_CIC_COUNT; i++)
{
if (USB_SPEED_HIGH == speed)
{
g_UsbDeviceCdcVcomCicEndpoints[i].maxPacketSize = HS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE;
}
else
{
g_UsbDeviceCdcVcomCicEndpoints[i].maxPacketSize = FS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE;
}
}
for (int i = 0; i < USB_CDC_VCOM_ENDPOINT_DIC_COUNT; i++)
{
if (USB_SPEED_HIGH == speed)
{
if (g_UsbDeviceCdcVcomDicEndpoints[i].endpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK)
{
g_UsbDeviceCdcVcomDicEndpoints[i].maxPacketSize = HS_CDC_VCOM_BULK_IN_PACKET_SIZE;
}
else
{
g_UsbDeviceCdcVcomDicEndpoints[i].maxPacketSize = HS_CDC_VCOM_BULK_OUT_PACKET_SIZE;
}
}
else
{
if (g_UsbDeviceCdcVcomDicEndpoints[i].endpointAddress & USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_MASK)
{
g_UsbDeviceCdcVcomDicEndpoints[i].maxPacketSize = FS_CDC_VCOM_BULK_IN_PACKET_SIZE;
}
else
{
g_UsbDeviceCdcVcomDicEndpoints[i].maxPacketSize = FS_CDC_VCOM_BULK_OUT_PACKET_SIZE;
}
}
}
return kStatus_USB_Success;
}

View File

@@ -0,0 +1,203 @@
/*
* Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc.
* Copyright 2016 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _USB_DEVICE_DESCRIPTOR_H_
#define _USB_DEVICE_DESCRIPTOR_H_ 1
/*******************************************************************************
* Definitions
******************************************************************************/
#define USB_DEVICE_SPECIFIC_BCD_VERSION (0x0200)
#define USB_DEVICE_DEMO_BCD_VERSION (0x0101U)
/* Communication Class Codes */
#define CDC_COMM_CLASS (0x02)
/* Data Class Codes */
#define CDC_DATA_CLASS (0x0A)
/* Communication Class SubClass Codes */
#define USB_CDC_DIRECT_LINE_CONTROL_MODEL (0x01)
#define USB_CDC_ABSTRACT_CONTROL_MODEL (0x02)
#define USB_CDC_TELEPHONE_CONTROL_MODEL (0x03)
#define USB_CDC_MULTI_CHANNEL_CONTROL_MODEL (0x04)
#define USB_CDC_CAPI_CONTROL_MOPDEL (0x05)
#define USB_CDC_ETHERNET_NETWORKING_CONTROL_MODEL (0x06)
#define USB_CDC_ATM_NETWORKING_CONTROL_MODEL (0x07)
#define USB_CDC_WIRELESS_HANDSET_CONTROL_MODEL (0x08)
#define USB_CDC_DEVICE_MANAGEMENT (0x09)
#define USB_CDC_MOBILE_DIRECT_LINE_MODEL (0x0A)
#define USB_CDC_OBEX (0x0B)
#define USB_CDC_ETHERNET_EMULATION_MODEL (0x0C)
/* Communication Class Protocol Codes */
#define USB_CDC_NO_CLASS_SPECIFIC_PROTOCOL (0x00) /*also for Data Class Protocol Code */
#define USB_CDC_AT_250_PROTOCOL (0x01)
#define USB_CDC_AT_PCCA_101_PROTOCOL (0x02)
#define USB_CDC_AT_PCCA_101_ANNEX_O (0x03)
#define USB_CDC_AT_GSM_7_07 (0x04)
#define USB_CDC_AT_3GPP_27_007 (0x05)
#define USB_CDC_AT_TIA_CDMA (0x06)
#define USB_CDC_ETHERNET_EMULATION_PROTOCOL (0x07)
#define USB_CDC_EXTERNAL_PROTOCOL (0xFE)
#define USB_CDC_VENDOR_SPECIFIC (0xFF) /*also for Data Class Protocol Code */
/* Data Class Protocol Codes */
#define USB_CDC_PYHSICAL_INTERFACE_PROTOCOL (0x30)
#define USB_CDC_HDLC_PROTOCOL (0x31)
#define USB_CDC_TRANSPARENT_PROTOCOL (0x32)
#define USB_CDC_MANAGEMENT_PROTOCOL (0x50)
#define USB_CDC_DATA_LINK_Q931_PROTOCOL (0x51)
#define USB_CDC_DATA_LINK_Q921_PROTOCOL (0x52)
#define USB_CDC_DATA_COMPRESSION_V42BIS (0x90)
#define USB_CDC_EURO_ISDN_PROTOCOL (0x91)
#define USB_CDC_RATE_ADAPTION_ISDN_V24 (0x92)
#define USB_CDC_CAPI_COMMANDS (0x93)
#define USB_CDC_HOST_BASED_DRIVER (0xFD)
#define USB_CDC_UNIT_FUNCTIONAL (0xFE)
/* Descriptor SubType in Communications Class Functional Descriptors */
#define USB_CDC_HEADER_FUNC_DESC (0x00)
#define USB_CDC_CALL_MANAGEMENT_FUNC_DESC (0x01)
#define USB_CDC_ABSTRACT_CONTROL_FUNC_DESC (0x02)
#define USB_CDC_DIRECT_LINE_FUNC_DESC (0x03)
#define USB_CDC_TELEPHONE_RINGER_FUNC_DESC (0x04)
#define USB_CDC_TELEPHONE_REPORT_FUNC_DESC (0x05)
#define USB_CDC_UNION_FUNC_DESC (0x06)
#define USB_CDC_COUNTRY_SELECT_FUNC_DESC (0x07)
#define USB_CDC_TELEPHONE_MODES_FUNC_DESC (0x08)
#define USB_CDC_TERMINAL_FUNC_DESC (0x09)
#define USB_CDC_NETWORK_CHANNEL_FUNC_DESC (0x0A)
#define USB_CDC_PROTOCOL_UNIT_FUNC_DESC (0x0B)
#define USB_CDC_EXTENSION_UNIT_FUNC_DESC (0x0C)
#define USB_CDC_MULTI_CHANNEL_FUNC_DESC (0x0D)
#define USB_CDC_CAPI_CONTROL_FUNC_DESC (0x0E)
#define USB_CDC_ETHERNET_NETWORKING_FUNC_DESC (0x0F)
#define USB_CDC_ATM_NETWORKING_FUNC_DESC (0x10)
#define USB_CDC_WIRELESS_CONTROL_FUNC_DESC (0x11)
#define USB_CDC_MOBILE_DIRECT_LINE_FUNC_DESC (0x12)
#define USB_CDC_MDLM_DETAIL_FUNC_DESC (0x13)
#define USB_CDC_DEVICE_MANAGEMENT_FUNC_DESC (0x14)
#define USB_CDC_OBEX_FUNC_DESC (0x15)
#define USB_CDC_COMMAND_SET_FUNC_DESC (0x16)
#define USB_CDC_COMMAND_SET_DETAIL_FUNC_DESC (0x17)
#define USB_CDC_TELEPHONE_CONTROL_FUNC_DESC (0x18)
#define USB_CDC_OBEX_SERVICE_ID_FUNC_DESC (0x19)
/* usb descritpor length */
#define USB_DESCRIPTOR_LENGTH_CONFIGURATION_ALL (sizeof(g_UsbDeviceConfigurationDescriptor))
#define USB_DESCRIPTOR_LENGTH_CDC_HEADER_FUNC (5)
#define USB_DESCRIPTOR_LENGTH_CDC_CALL_MANAG (5)
#define USB_DESCRIPTOR_LENGTH_CDC_ABSTRACT (4)
#define USB_DESCRIPTOR_LENGTH_CDC_UNION_FUNC (5)
/* Configuration, interface and endpoint. */
#define USB_DEVICE_CONFIGURATION_COUNT (1)
#define USB_DEVICE_STRING_COUNT (3)
#define USB_DEVICE_LANGUAGE_COUNT (1)
#define USB_CDC_VCOM_CONFIGURE_INDEX (1)
#define USB_CDC_VCOM_ENDPOINT_CIC_COUNT (1)
#define USB_CDC_VCOM_ENDPOINT_DIC_COUNT (2)
#define USB_CDC_VCOM_INTERRUPT_IN_ENDPOINT (1)
#define USB_CDC_VCOM_BULK_IN_ENDPOINT (2)
#define USB_CDC_VCOM_BULK_OUT_ENDPOINT (3)
#define USB_CDC_VCOM_INTERFACE_COUNT (2)
#define USB_CDC_VCOM_COMM_INTERFACE_INDEX (0)
#define USB_CDC_VCOM_DATA_INTERFACE_INDEX (1)
/* Packet size. */
#define HS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE (16)
#define FS_CDC_VCOM_INTERRUPT_IN_PACKET_SIZE (16)
#define HS_CDC_VCOM_INTERRUPT_IN_INTERVAL (0x07) /* 2^(7-1) = 8ms */
#define FS_CDC_VCOM_INTERRUPT_IN_INTERVAL (0x08)
#define HS_CDC_VCOM_BULK_IN_PACKET_SIZE (512)
#define FS_CDC_VCOM_BULK_IN_PACKET_SIZE (64)
#define HS_CDC_VCOM_BULK_OUT_PACKET_SIZE (512)
#define FS_CDC_VCOM_BULK_OUT_PACKET_SIZE (64)
/* String descriptor length. */
#define USB_DESCRIPTOR_LENGTH_STRING0 (sizeof(g_UsbDeviceString0))
#define USB_DESCRIPTOR_LENGTH_STRING1 (sizeof(g_UsbDeviceString1))
#define USB_DESCRIPTOR_LENGTH_STRING2 (sizeof(g_UsbDeviceString2))
#define USB_DESCRIPTOR_TYPE_CDC_CS_INTERFACE (0x24)
#define USB_DESCRIPTOR_TYPE_CDC_CS_ENDPOINT (0x25)
/* Class code. */
#define USB_DEVICE_CLASS (0x02)
#define USB_DEVICE_SUBCLASS (0x00)
#define USB_DEVICE_PROTOCOL (0x00)
#define USB_DEVICE_MAX_POWER (0x32)
#define USB_CDC_VCOM_CIC_CLASS (CDC_COMM_CLASS)
#define USB_CDC_VCOM_CIC_SUBCLASS (USB_CDC_ABSTRACT_CONTROL_MODEL)
#define USB_CDC_VCOM_CIC_PROTOCOL (USB_CDC_NO_CLASS_SPECIFIC_PROTOCOL)
#define USB_CDC_VCOM_DIC_CLASS (CDC_DATA_CLASS)
#define USB_CDC_VCOM_DIC_SUBCLASS (0x00)
#define USB_CDC_VCOM_DIC_PROTOCOL (USB_CDC_NO_CLASS_SPECIFIC_PROTOCOL)
/*******************************************************************************
* API
******************************************************************************/
/*!
* @brief USB device set speed function.
*
* This function sets the speed of the USB device.
*
* Due to the difference of HS and FS descriptors, the device descriptors and configurations need to be updated to match
* current speed.
* As the default, the device descriptors and configurations are configured by using FS parameters for both EHCI and
* KHCI.
* When the EHCI is enabled, the application needs to call this function to update device by using current speed.
* The updated information includes endpoint max packet size, endpoint interval, etc.
*
* @param handle The USB device handle.
* @param speed Speed type. USB_SPEED_HIGH/USB_SPEED_FULL/USB_SPEED_LOW.
*
* @return A USB error code or kStatus_USB_Success.
*/
extern usb_status_t USB_DeviceSetSpeed(usb_device_handle handle, uint8_t speed);
/*!
* @brief USB device get device descriptor function.
*
* This function gets the device descriptor of the USB device.
*
* @param handle The USB device handle.
* @param deviceDescriptor The pointer to the device descriptor structure.
*
* @return A USB error code or kStatus_USB_Success.
*/
extern usb_status_t USB_DeviceGetDeviceDescriptor(usb_device_handle handle,
usb_device_get_device_descriptor_struct_t *deviceDescriptor);
/*!
* @brief USB device get string descriptor function.
*
* This function gets the string descriptor of the USB device.
*
* @param handle The USB device handle.
* @param stringDescriptor Pointer to the string descriptor structure.
*
* @return A USB error code or kStatus_USB_Success.
*/
usb_status_t USB_DeviceGetStringDescriptor(usb_device_handle handle,
usb_device_get_string_descriptor_struct_t *stringDescriptor);
/*!
* @brief USB device get configuration descriptor function.
*
* This function gets the configuration descriptor of the USB device.
*
* @param handle The USB device handle.
* @param configurationDescriptor The pointer to the configuration descriptor structure.
*
* @return A USB error code or kStatus_USB_Success.
*/
extern usb_status_t USB_DeviceGetConfigurationDescriptor(
usb_device_handle handle, usb_device_get_configuration_descriptor_struct_t *configurationDescriptor);
#endif /* _USB_DEVICE_DESCRIPTOR_H_ */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,475 @@
/*
* Copyright 2018 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __HAL_UART_ADAPTER_H__
#define __HAL_UART_ADAPTER_H__
#if defined(FSL_RTOS_FREE_RTOS)
#include "FreeRTOS.h"
#endif
/*!
* @addtogroup UART_Adapter
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief Enable or disable UART adapter non-blocking mode (1 - enable, 0 - disable) */
#ifdef DEBUG_CONSOLE_TRANSFER_NON_BLOCKING
#define UART_ADAPTER_NON_BLOCKING_MODE (1U)
#else
#ifndef SERIAL_MANAGER_NON_BLOCKING_MODE
#define UART_ADAPTER_NON_BLOCKING_MODE (0U)
#else
#define UART_ADAPTER_NON_BLOCKING_MODE SERIAL_MANAGER_NON_BLOCKING_MODE
#endif
#endif
#if defined(__GIC_PRIO_BITS)
#define HAL_UART_ISR_PRIORITY (25U)
#else
#if defined(configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY)
#define HAL_UART_ISR_PRIORITY (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY)
#else
/* The default value 3 is used to support different ARM Core, such as CM0P, CM4, CM7, and CM33, etc.
* The minimum number of priority bits implemented in the NVIC is 2 on these SOCs. The value of mininum
* priority is 3 (2^2 - 1). So, the default value is 3.
*/
#define HAL_UART_ISR_PRIORITY (3U)
#endif
#endif
#if (defined(UART_ADAPTER_NON_BLOCKING_MODE) && (UART_ADAPTER_NON_BLOCKING_MODE > 0U))
#define HAL_UART_HANDLE_SIZE (90U)
#else
#define HAL_UART_HANDLE_SIZE (4U)
#endif
/*! @brief Whether enable transactional function of the UART. (0 - disable, 1 - enable) */
#define HAL_UART_TRANSFER_MODE (0U)
typedef void *hal_uart_handle_t;
/*! @brief UART status */
typedef enum _hal_uart_status
{
kStatus_HAL_UartSuccess = kStatus_Success, /*!< Successfully */
kStatus_HAL_UartTxBusy = MAKE_STATUS(kStatusGroup_HAL_UART, 1), /*!< TX busy */
kStatus_HAL_UartRxBusy = MAKE_STATUS(kStatusGroup_HAL_UART, 2), /*!< RX busy */
kStatus_HAL_UartTxIdle = MAKE_STATUS(kStatusGroup_HAL_UART, 3), /*!< HAL UART transmitter is idle. */
kStatus_HAL_UartRxIdle = MAKE_STATUS(kStatusGroup_HAL_UART, 4), /*!< HAL UART receiver is idle */
kStatus_HAL_UartBaudrateNotSupport =
MAKE_STATUS(kStatusGroup_HAL_UART, 5), /*!< Baudrate is not support in current clock source */
kStatus_HAL_UartProtocolError = MAKE_STATUS(
kStatusGroup_HAL_UART,
6), /*!< Error occurs for Noise, Framing, Parity, etc.
For transactional transfer, The up layer needs to abort the transfer and then starts again */
kStatus_HAL_UartError = MAKE_STATUS(kStatusGroup_HAL_UART, 7), /*!< Error occurs on HAL UART */
} hal_uart_status_t;
/*! @brief UART parity mode. */
typedef enum _hal_uart_parity_mode
{
kHAL_UartParityDisabled = 0x0U, /*!< Parity disabled */
kHAL_UartParityEven = 0x1U, /*!< Parity even enabled */
kHAL_UartParityOdd = 0x2U, /*!< Parity odd enabled */
} hal_uart_parity_mode_t;
/*! @brief UART stop bit count. */
typedef enum _hal_uart_stop_bit_count
{
kHAL_UartOneStopBit = 0U, /*!< One stop bit */
kHAL_UartTwoStopBit = 1U, /*!< Two stop bits */
} hal_uart_stop_bit_count_t;
/*! @brief UART configuration structure. */
typedef struct _hal_uart_config
{
uint32_t srcClock_Hz; /*!< Source clock */
uint32_t baudRate_Bps; /*!< Baud rate */
hal_uart_parity_mode_t parityMode; /*!< Parity mode, disabled (default), even, odd */
hal_uart_stop_bit_count_t stopBitCount; /*!< Number of stop bits, 1 stop bit (default) or 2 stop bits */
uint8_t enableRx; /*!< Enable RX */
uint8_t enableTx; /*!< Enable TX */
uint8_t instance; /*!< Instance (0 - UART0, 1 - UART1, ...), detail information please refer to the
SOC corresponding RM.
Invalid instance value will cause initialization failure. */
} hal_uart_config_t;
/*! @brief UART transfer callback function. */
typedef void (*hal_uart_transfer_callback_t)(hal_uart_handle_t handle, hal_uart_status_t status, void *callbackParam);
/*! @brief UART transfer structure. */
typedef struct _hal_uart_transfer
{
uint8_t *data; /*!< The buffer of data to be transfer.*/
size_t dataSize; /*!< The byte count to be transfer. */
} hal_uart_transfer_t;
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif /* _cplusplus */
/*!
* @name Initialization and deinitialization
* @{
*/
/*!
* @brief Initializes a UART instance with the UART handle and the user configuration structure.
*
* This function configures the UART module with user-defined settings. The user can configure the configuration
* structure. The parameter handle is a pointer to point to a memory space of size #HAL_UART_HANDLE_SIZE allocated by
* the caller. Example below shows how to use this API to configure the UART.
* @code
* uint8_t g_UartHandleBuffer[HAL_UART_HANDLE_SIZE];
* hal_uart_handle_t g_UartHandle = &g_UartHandleBuffer[0];
* hal_uart_config_t config;
* config.srcClock_Hz = 48000000;
* config.baudRate_Bps = 115200U;
* config.parityMode = kHAL_UartParityDisabled;
* config.stopBitCount = kHAL_UartOneStopBit;
* config.enableRx = 1;
* config.enableTx = 1;
* config.instance = 0;
* HAL_UartInit(g_UartHandle, &config);
* @endcode
*
* @param handle Pointer to point to a memory space of size #HAL_UART_HANDLE_SIZE allocated by the caller.
* @param config Pointer to user-defined configuration structure.
* @retval kStatus_HAL_UartBaudrateNotSupport Baudrate is not support in current clock source.
* @retval kStatus_HAL_UartSuccess UART initialization succeed
*/
hal_uart_status_t HAL_UartInit(hal_uart_handle_t handle, hal_uart_config_t *config);
/*!
* @brief Deinitializes a UART instance.
*
* This function waits for TX complete, disables TX and RX, and disables the UART clock.
*
* @param handle UART handle pointer.
* @retval kStatus_HAL_UartSuccess UART de-initialization succeed
*/
hal_uart_status_t HAL_UartDeinit(hal_uart_handle_t handle);
/*! @}*/
/*!
* @name Blocking bus Operations
* @{
*/
/*!
* @brief Reads 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 RX register.
*
* @note The function #HAL_UartReceiveBlocking and the function #HAL_UartTransferReceiveNonBlocking
* cannot be used at the same time.
* And, the function #HAL_UartTransferAbortReceive cannot be used to abort the transmission of this function.
*
* @param handle UART handle pointer.
* @param data Start address of the buffer to store the received data.
* @param length Size of the buffer.
* @retval kStatus_HAL_UartError An error occurred while receiving data.
* @retval kStatus_HAL_UartParityError A parity error occurred while receiving data.
* @retval kStatus_HAL_UartSuccess Successfully received all data.
*/
hal_uart_status_t HAL_UartReceiveBlocking(hal_uart_handle_t handle, uint8_t *data, size_t length);
/*!
* @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 The function #HAL_UartSendBlocking and the function #HAL_UartTransferSendNonBlocking
* cannot be used at the same time.
* And, the function #HAL_UartTransferAbortSend cannot be used to abort the transmission of this function.
*
* @param handle UART handle pointer.
* @param data Start address of the data to write.
* @param length Size of the data to write.
* @retval kStatus_HAL_UartSuccess Successfully sent all data.
*/
hal_uart_status_t HAL_UartSendBlocking(hal_uart_handle_t handle, const uint8_t *data, size_t length);
/*! @}*/
#if (defined(UART_ADAPTER_NON_BLOCKING_MODE) && (UART_ADAPTER_NON_BLOCKING_MODE > 0U))
#if (defined(HAL_UART_TRANSFER_MODE) && (HAL_UART_TRANSFER_MODE > 0U))
/*!
* @name Transactional
* @note The transactional API and the functional API cannot be used at the same time. The macro
* #HAL_UART_TRANSFER_MODE is used to set which one will be used. If #HAL_UART_TRANSFER_MODE is zero, the
* functional API with non-blocking mode will be used. Otherwise, transactional API will be used.
* @{
*/
/*!
* @brief Installs a callback and callback parameter.
*
* This function is used to install the callback and callback parameter for UART module.
* When any status of the UART changed, the driver will notify the upper layer by the installed callback
* function. And the status is also passed as status parameter when the callback is called.
*
* @param handle UART handle pointer.
* @param callback The callback function.
* @param callbackParam The parameter of the callback function.
* @retval kStatus_HAL_UartSuccess Successfully install the callback.
*/
hal_uart_status_t HAL_UartTransferInstallCallback(hal_uart_handle_t handle,
hal_uart_transfer_callback_t callback,
void *callbackParam);
/*!
* @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 directly without waiting for all data to be received.
* 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.
*
* @note The function #HAL_UartReceiveBlocking and the function #HAL_UartTransferReceiveNonBlocking
* cannot be used at the same time.
*
* @param handle UART handle pointer.
* @param transfer UART transfer structure, see #hal_uart_transfer_t.
* @retval kStatus_HAL_UartSuccess Successfully queue the transfer into transmit queue.
* @retval kStatus_HAL_UartRxBusy Previous receive request is not finished.
* @retval kStatus_HAL_UartError An error occurred.
*/
hal_uart_status_t HAL_UartTransferReceiveNonBlocking(hal_uart_handle_t handle, hal_uart_transfer_t *transfer);
/*!
* @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 function #HAL_UartSendBlocking and the function #HAL_UartTransferSendNonBlocking
* cannot be used at the same time.
*
* @param handle UART handle pointer.
* @param transfer UART transfer structure. See #hal_uart_transfer_t.
* @retval kStatus_HAL_UartSuccess Successfully start the data transmission.
* @retval kStatus_HAL_UartTxBusy Previous transmission still not finished; data not all written to TX register yet.
* @retval kStatus_HAL_UartError An error occurred.
*/
hal_uart_status_t HAL_UartTransferSendNonBlocking(hal_uart_handle_t handle, hal_uart_transfer_t *transfer);
/*!
* @brief Gets the number of bytes that have been received.
*
* This function gets the number of bytes that have been received.
*
* @param handle UART handle pointer.
* @param count Receive bytes count.
* @retval kStatus_HAL_UartError An error occurred.
* @retval kStatus_Success Get successfully through the parameter \p count.
*/
hal_uart_status_t HAL_UartTransferGetReceiveCount(hal_uart_handle_t handle, uint32_t *count);
/*!
* @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 handle UART handle pointer.
* @param count Send bytes count.
* @retval kStatus_HAL_UartError An error occurred.
* @retval kStatus_Success Get successfully through the parameter \p count.
*/
hal_uart_status_t HAL_UartTransferGetSendCount(hal_uart_handle_t handle, uint32_t *count);
/*!
* @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.
*
* @note The function #HAL_UartTransferAbortReceive cannot be used to abort the transmission of
* the function #HAL_UartReceiveBlocking.
*
* @param handle UART handle pointer.
* @retval kStatus_Success Get successfully abort the receiving.
*/
hal_uart_status_t HAL_UartTransferAbortReceive(hal_uart_handle_t handle);
/*!
* @brief Aborts the interrupt-driven data sending.
*
* This function aborts the interrupt-driven data sending. The user can get the remainBytes to find out
* how many bytes are not sent out.
*
* @note The function #HAL_UartTransferAbortSend cannot be used to abort the transmission of
* the function #HAL_UartSendBlocking.
*
* @param handle UART handle pointer.
* @retval kStatus_Success Get successfully abort the sending.
*/
hal_uart_status_t HAL_UartTransferAbortSend(hal_uart_handle_t handle);
/*! @}*/
#else
/*!
* @name Functional API with non-blocking mode.
* @note The functional API and the transactional API cannot be used at the same time. The macro
* #HAL_UART_TRANSFER_MODE is used to set which one will be used. If #HAL_UART_TRANSFER_MODE is zero, the
* functional API with non-blocking mode will be used. Otherwise, transactional API will be used.
* @{
*/
/*!
* @brief Installs a callback and callback parameter.
*
* This function is used to install the callback and callback parameter for UART module.
* When non-blocking sending or receiving finished, the adapter will notify the upper layer by the installed callback
* function. And the status is also passed as status parameter when the callback is called.
*
* @param handle UART handle pointer.
* @param callback The callback function.
* @param callbackParam The parameter of the callback function.
* @retval kStatus_HAL_UartSuccess Successfully install the callback.
*/
hal_uart_status_t HAL_UartInstallCallback(hal_uart_handle_t handle,
hal_uart_transfer_callback_t callback,
void *callbackParam);
/*!
* @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 directly without waiting for all data to be received.
* The receive request is saved by the UART adapter.
* When the new data arrives, the receive request is serviced first.
* When all data is received, the UART adapter notifies the upper layer
* through a callback function and passes the status parameter @ref kStatus_UART_RxIdle.
*
* @note The function #HAL_UartReceiveBlocking and the function #HAL_UartReceiveNonBlocking
* cannot be used at the same time.
*
* @param handle UART handle pointer.
* @param data Start address of the data to write.
* @param length Size of the data to write.
* @retval kStatus_HAL_UartSuccess Successfully queue the transfer into transmit queue.
* @retval kStatus_HAL_UartRxBusy Previous receive request is not finished.
* @retval kStatus_HAL_UartError An error occurred.
*/
hal_uart_status_t HAL_UartReceiveNonBlocking(hal_uart_handle_t handle, uint8_t *data, size_t length);
/*!
* @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 function #HAL_UartSendBlocking and the function #HAL_UartSendNonBlocking
* cannot be used at the same time.
*
* @param handle UART handle pointer.
* @param data Start address of the data to write.
* @param length Size of the data to write.
* @retval kStatus_HAL_UartSuccess Successfully start the data transmission.
* @retval kStatus_HAL_UartTxBusy Previous transmission still not finished; data not all written to TX register yet.
* @retval kStatus_HAL_UartError An error occurred.
*/
hal_uart_status_t HAL_UartSendNonBlocking(hal_uart_handle_t handle, uint8_t *data, size_t length);
/*!
* @brief Gets the number of bytes that have been received.
*
* This function gets the number of bytes that have been received.
*
* @param handle UART handle pointer.
* @param count Receive bytes count.
* @retval kStatus_HAL_UartError An error occurred.
* @retval kStatus_Success Get successfully through the parameter \p count.
*/
hal_uart_status_t HAL_UartGetReceiveCount(hal_uart_handle_t handle, uint32_t *reCount);
/*!
* @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 handle UART handle pointer.
* @param count Send bytes count.
* @retval kStatus_HAL_UartError An error occurred.
* @retval kStatus_Success Get successfully through the parameter \p count.
*/
hal_uart_status_t HAL_UartGetSendCount(hal_uart_handle_t handle, uint32_t *seCount);
/*!
* @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.
*
* @note The function #HAL_UartAbortReceive cannot be used to abort the transmission of
* the function #HAL_UartReceiveBlocking.
*
* @param handle UART handle pointer.
* @retval kStatus_Success Get successfully abort the receiving.
*/
hal_uart_status_t HAL_UartAbortReceive(hal_uart_handle_t handle);
/*!
* @brief Aborts the interrupt-driven data sending.
*
* This function aborts the interrupt-driven data sending. The user can get the remainBytes to find out
* how many bytes are not sent out.
*
* @note The function #HAL_UartAbortSend cannot be used to abort the transmission of
* the function #HAL_UartSendBlocking.
*
* @param handle UART handle pointer.
* @retval kStatus_Success Get successfully abort the sending.
*/
hal_uart_status_t HAL_UartAbortSend(hal_uart_handle_t handle);
/*! @}*/
#endif
#endif
#if (defined(UART_ADAPTER_NON_BLOCKING_MODE) && (UART_ADAPTER_NON_BLOCKING_MODE > 0U))
/*!
* @brief UART IRQ handle function.
*
* This function handles the UART transmit and receive IRQ request.
*
* @param handle UART handle pointer.
*/
void HAL_UartIsrFunction(hal_uart_handle_t handle);
#endif
#if defined(__cplusplus)
}
#endif
/*! @}*/
#endif /* __HAL_UART_ADAPTER_H__ */