void SPI_Flash_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA|RCC_APB2Periph_SPI1, ENABLE );
//CS片选
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA, GPIO_Pin_2); //CS引脚PA2置高电平
//SCK
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init( GPIOA, &GPIO_InitStructure );
//MISO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入
GPIO_Init( GPIOA, &GPIO_InitStructure );
//MOSI
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init( GPIOA, &GPIO_InitStructure );
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //设置SPI通讯方向为双线全双工方式
SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //设置SPI为主机端模式
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //设置SPI通讯的数据帧大小为8位
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; //设置SPI的时钟极性为高电平
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //设置SPI的时钟相位为在SCK的偶数边沿采集数据
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //设置NSS引脚(即片选引脚)的使用模式为软件模式
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4; //设置波特率分频因子为4分频
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //设置数据传输为高位数据在前
SPI_InitStructure.SPI_CRCPolynomial = 7; //SPI的CRC校验中多项式的值
SPI_Init(SPI1, &SPI_InitStructure); //初始化SPI
SPI_Cmd(SPI1, ENABLE); //使能SPI1外设
}
上面是SPI外设进行配置函数,其他函数见附件,也可以在评估板例程找的到。
下面是测试函数的实现。
/* Global Variable */
const u8 TEXT_Buf[]={"CH32V103 SPI FLASH W25Q16 test!"};
/* Global define */
#define TEXT_BUF_SIZE sizeof(TEXT_Buf)
void SPI_FLASH_WR_Test(void)
{
u8 datap[TEXT_BUF_SIZE];
u16 Flash_Model;
u8 Tflag=0;
u16 i = 0;
Delay_Init();
USART_Printf_Init(115200);
SPI_Flash_Init();
/******************spi Flash test********************/
Flash_Model = SPI_Flash_ReadID();
if(Flash_Model == W25Q16)
{
printf("read W25Q16 OK!\r\n");
}
else
{
printf("read W25Q16 Fail!\r\n");
}
printf("Start Erase W25Qxx....\r\n");
SPI_Flash_Erase_Sector(0);
printf("W25Qxx Erase Finished!\r\n");
Delay_Ms(500);
printf("Start Write W25Qxx....\r\n");
SPI_Flash_Write((u8*)TEXT_Buf,0,TEXT_BUF_SIZE);
printf("W25Qxx Write Finished!\r\n");
Delay_Ms(500);
printf("Start Read W25Qxx....\r\n");
SPI_Flash_Read(datap,0x0,TEXT_BUF_SIZE);
printf("READ:%s\r\n", datap );
while(TEXT_Buf != '\0')
{
if(TEXT_Buf != datap)
{
printf("errnum:%d,%s ",i,datap);
Tflag++;
}
i++;
}
if(Tflag == 0)
{
printf("spi Flash OK!\r\n");
}
else
{
printf("spi Flash ERR!\r\n");
}
/******************spi Flash test complete********************/
}
最后附上运行结果。