直接使用官方例程,有如下注意点:
1、USB的时钟是48MHz,需要根据自己的系统主频来分频。否则时钟频率不对,USB会枚举失败,电脑提示设备描述符获取失败。
在如下文件和位置设置宏定义来选择系统主频。
然后根据自己的主频来设置分频:
/*!
\brief configure the different system clocks
\param[in] none
\param[out] none
\retval none
*/
void rcu_config(void)
{
/* enable USB pull-up pin clock */
rcu_periph_clock_enable(RCU_GPIOA);
/* enable the power clock */
rcu_periph_clock_enable(RCU_PMU);
/* configure USB model clock from PLL clock */
rcu_usb_clock_config(RCU_CKUSB_CKPLL_DIV2); //主频96M,二分频就是48M
/* enable USB APB1 clock */
rcu_periph_clock_enable(RCU_USBD);
}
如上,主频是96M,二分频就是48M。
如果主频是72M,就是1.5分频。
/* use HXTAL (XD series CK_HXTAL = 8M, CL series CK_HXTAL = 25M) */
//#define __SYSTEM_CLOCK_HXTAL (uint32_t)(__HXTAL)
//#define __SYSTEM_CLOCK_24M_PLL_HXTAL (uint32_t)(24000000)
//#define __SYSTEM_CLOCK_36M_PLL_HXTAL (uint32_t)(36000000)
//#define __SYSTEM_CLOCK_48M_PLL_HXTAL (uint32_t)(48000000)
//#define __SYSTEM_CLOCK_56M_PLL_HXTAL (uint32_t)(56000000)
#define __SYSTEM_CLOCK_72M_PLL_HXTAL (uint32_t)(72000000)
//#define __SYSTEM_CLOCK_96M_PLL_HXTAL (uint32_t)(96000000)
//#define __SYSTEM_CLOCK_108M_PLL_HXTAL (uint32_t)(108000000)
/* enable USB pull-up pin clock */
rcu_periph_clock_enable(RCC_AHBPeriph_GPIO_PULLUP);
/* enable the power clock */
rcu_periph_clock_enable(RCU_PMU);
/* configure USB model clock from PLL clock */
rcu_usb_clock_config(RCU_CKUSB_CKPLL_DIV1_5);
/* enable USB APB1 clock */
rcu_periph_clock_enable(RCU_USBD);
2、需要根据自己的芯片型号更改Flash页面大小,比如GD32F103C8T6的页面大小为1K,GD32F103VCT6的页面大小为2K
#define PAGE_SIZE ((uint32_t)(1024))
#define NAND_FLASH_BASE_ADDRESS ((uint32_t)(0x08000000 + 0x04000))
#define NAND_FLASH_END_ADDRESS ((uint32_t)(0x08000000 + 0x10000))
修改了页面大小,同时还需要修改写扇区函数
比如页面大小为1K,那么写函数修改为:
/*!
\brief write data to multiple blocks of flash
\param[in] pBuf: pointer to user buffer
\param[in] write_addr: address to be write
\param[in] block_size: block size
\param[in] block_num: number of block
\param[out] none
\retval status
*/
uint32_t flash_write_multi_blocks (uint8_t *pBuf,
uint32_t write_addr,
uint16_t block_size,
uint32_t block_num)
{
uint32_t i, page;
uint32_t start_page = (write_addr / PAGE_SIZE) * PAGE_SIZE + NAND_FLASH_BASE_ADDRESS;
uint32_t *ptrs = (uint32_t *)pBuf;
page = block_num;
for(; page > 0; page--){
fmc_page_erase(start_page);
i = 0;
do{
fmc_word_program(start_page, *ptrs++);
start_page += 4;
}while(++i < 256);
}
return 0;
}
实验结果:
和普通的U盘效果一样,可以读写、格式化。