
/******************************************************************************
*@file  : acm32g103_hal_msp.c
*@brief : HAL MSP module . not need header file 
******************************************************************************/

#include "main.h"

#define PHY_READY_TIMEOUT  (1000000)   

void HAL_MSP_Delay_Count(uint32_t count)
{
    volatile uint32_t  cnt; 
    
    cnt = count; 
    
    while(cnt--);      
    
}

/*********************************************************************************
* Function    : USB_PHY_Config
* Description : Configure USB PHY, such as clock select, pll...
* Input       : none  
* Output      : 0: fail, 1:success 
* Author      : xwl                         Date : 2021Äê
**********************************************************************************/
uint32_t USB_PHY_Config(void) 
{
    volatile uint32_t delay_count; 
    
    __HAL_RCC_SYSCFG_CLK_ENABLE();   
    SYSCFG->PHYCFG &= (~BIT2); // exit power down, auto select clock source 
    
    delay_count = PHY_READY_TIMEOUT;   
    while(delay_count--)
    {
        if (SYSCFG->PHYCFG & (BIT19)) // clksel_end flag = 1  
        {
            break;  
        }
    }  

    if (delay_count) 
    {
        return HAL_OK;   
    }
    else
    {
        return HAL_TIMEOUT;     
    }
} 


uint32_t HAL_FSUSB_MSP_Init(void)  
{
    GPIO_InitTypeDef    GPIO_init_para;  

//    __HAL_RCC_USB__RESET();   
    
    __HAL_RCC_USB_CLK_ENABLE();  
           
    if( HAL_OK != USB_PHY_Config()) 
    {
        return HAL_ERROR;    
    } 
    
    GPIO_init_para.Pin       = GPIO_PIN_11 | GPIO_PIN_12;
    GPIO_init_para.Mode      = GPIO_MODE_ANALOG;
    GPIO_init_para.Drive      = GPIO_DRIVE_LEVEL3;  
    GPIO_init_para.Pull      = GPIO_NOPULL;
    GPIO_init_para.Alternate = GPIO_FUNCTION_0; 
    HAL_GPIO_Init(GPIOA, &GPIO_init_para);  
    
    NVIC_ClearPendingIRQ(USB_IRQn);  
	NVIC_EnableIRQ(USB_IRQn); 
    
    return HAL_OK;    
}  

