018 - STM32学习笔记 - SPI访问Flash(三)- 写入字符串、小数与整数
上节对Flash的跨页写入数据进行了完善,但是数据写入都是以Byte数组的方式进行写入,这节分别进行字符串的写入和小数整数的写入,本节内容对SPI的函数不需要进行修改,在主函数的调用中会完善如何写入字符串、小数和整数。
1、字符串写入
u8 ReadBuffer[4096] = {0x00};
u8 WriteBuffer[] = "STM32学习笔记\r\nSPI读写Flash测试例程!";
int main(void)
{
u32 TransferStatus = 0;
u32 device_id = 0;
LED_Config();
DEBUG_USART1_Config();
SPI_GPIO_Config();
printf("\r\n这是SPI读取FLASH_Device_ID的测试实验!\r\n");
SPI_Flash_WakeUp(); //掉电唤醒
device_id = SPI_FLASH_ReadID(); //获取设备ID
if(device_id == sFLASH_ID)
{
printf("\r\n检测到SPI FLASH W25Q128 !设备号为:0x%X \r\n",device_id);
SPI_Flash_Erase(FLASH_SectorErass); //扇区擦除,FLASH_SectorErass为宏定义,值为0x00
SPI_FLASH_BufferWrite(WriteBuffer,FLASH_WriteAddress,sizeof(WriteBuffer)); //写入字符串
printf("\r\n写入的数据为:\r\t%s\r\n",WriteBuffer);
SPI_Flash_ReadDate(ReadBuffer,FLASH_ReadAddress,sizeof(WriteBuffer)); //读取写入的数据
printf("\r\n读出的数据为:\r\t%s\r\n",ReadBuffer);
TransferStatus = strcmp((char *)WriteBuffer,(char *)ReadBuffer);
if(TransferStatus == 0)
{
LED_GREEN;
printf("\r\n 16M串行Flash(W24Q128)测试成功! \r\n");
}
else
{
LED_RED;
printf("\r\n 16M串行Flash(W24Q128)测试失败! \r\n");
}
}
while(1)
{
}
}
测试效果:
2、小数、整数读写
int main(void)
{
uint8_t cal_flag = 0;
u32 device_id = 0;
u32 i = 0;
long double doubleBuffer[7] = {0};
int intBuffer[7] = {0};
DEBUG_USART1_Config();
SPI_GPIO_Config();
printf("\r\n这是SPI读取FLASH_Device_ID的测试实验!\r\n");
SPI_Flash_WakeUp(); //掉电唤醒
device_id = SPI_FLASH_ReadID(); //获取FlashID
printf("\r\ndevice_id = 0x%X\r\n",device_id);
if(device_id == sFLASH_ID)
{
SPI_Flash_ReadDate(&cal_flag, SPI_FLASH_PageSize*0, 1); //读取数据标志位
if(cal_flag == 0xFE)
{
for(i = 0;i < 7;i++) //先将浮点数数组和整数数组清空
{
doubleBuffer[i] = 0;
intBuffer[i] = 0 ;
}
printf("\r\n检测到数据标志\r\n");
SPI_Flash_ReadDate((void*)doubleBuffer, SPI_FLASH_PageSize*1, sizeof(doubleBuffer)); //读取小数数据,写入是首地址为256
SPI_Flash_ReadDate((void*)intBuffer, SPI_FLASH_PageSize*2, sizeof(intBuffer)); //读取整数数据,写入时首地址为512
printf("\r\n从芯片读到数据:\r\n");
for( i=0; i<7; i++ )
{
printf("读取小数 = %LF \r\n",doubleBuffer[i]);
printf("读取整数 = %d \r\n",intBuffer[i]);
}
printf("\r\nFLASH存在数据,复位将清除小数写入实验\r\n");
SPI_Flash_Erase(0);
}
else //若未读取到数据标志位,则首先写入
{
printf("\r\n没有检测到数据标志,FLASH没有存储数据,即将进行小数写入实验\r\n");
cal_flag =0xFE;
SPI_Flash_Erase(0); //写入前先擦除扇区
SPI_FLASH_BufferWrite(&cal_flag, SPI_FLASH_PageSize*0, 1); //往第0页写入,即起始地址为0x00
for( i=0; i<7; i++ )
{
doubleBuffer[i] = i +0.1;
intBuffer[i]=i*100+1 ;
}
SPI_FLASH_BufferWrite((void*)doubleBuffer, SPI_FLASH_PageSize*1, sizeof(doubleBuffer)); //写入地址为256
SPI_FLASH_BufferWrite((void*)intBuffer, SPI_FLASH_PageSize*2, sizeof(intBuffer)); //写入地址为512
printf("向芯片写入数据:");
for( i=0; i<7; i++ )
{
printf("写入小数 = %LF\r\n",doubleBuffer[i]);
printf("写入整数 = %d\r\n",intBuffer[i]);
}
printf("\r\n请复位开发板,以读取数据进行检验\r\n");
}
}
SPI_Flash_PowerDown();
while(1)
{
}
}
无数据,写入数据:
读取数据: