读写测试代码
读写测试代码

读写测试代码

使用随机数做读写测试

这段读写测试代码可以应用于 EEPROM、SPI Flash、Nand Flash 等存储设备的读写测试,在这里做一个总结,避免每次都重新编写。

#include "stdio.h"
#include "stdlib.h"

//测试长度定义
#define SECTOR_SIZE (2048)
#define RW_TEST_LEN (SECTOR_SIZE * 10)

//主函数
void main(void)
{
  //变量定义
  static unsigned char s_arrWriteBuf[RW_TEST_LEN] = {0};
  static unsigned char s_arrReadBuf[RW_TEST_LEN] = {0};
  unsigned int i, error, writeData;

  //填充写缓冲区
  srand(0);
  for(i = 0; i < RW_TEST_LEN; i++)
  {
    writeData = rand();
    s_arrWriteBuf[i] = writeData & 0xFF;
    srand(writeData);
  }

  //写入
  FTLWriteSectors(s_arrWriteBuf, 0, FTL_SECTOR_SIZE, RW_TEST_LEN / SECTOR_SIZE);
  
  //读取
  FTLReadSectors(s_arrReadBuf, 0, FTL_SECTOR_SIZE, RW_TEST_LEN / SECTOR_SIZE);

  //校验
  error = 0;
  for(i = 0; i < RW_TEST_LEN; i++)
  {
    if(s_arrReadBuf[i] != s_arrWriteBuf[i])
    {
      error = 1;
      break;
    }
  }
  
  //输出校验结果
  if(1 == error)
  {
    printf("Fail to check\r\n");
  }
  else
  {
    printf("Check OK\r\n");
  }

  while(1)
  {

  }
}

对于 FATFS,读写测试代码可以如下所示。

#include "stdio.h"
#include "stdlib.h"
#include "ff.h"

//测试长度定义
#define SECTOR_SIZE (2048)
#define RW_TEST_LEN (SECTOR_SIZE * 10)

//主函数
void main(void)
{
  //变量定义
  static FIL s_structFile;
  FRESULT result;
  unsigned int readNum, writeNum;
  static unsigned char s_arrWriteBuf[RW_TEST_LEN] = {0};
  static unsigned char s_arrReadBuf[RW_TEST_LEN] = {0};
  unsigned int i, error, writeData;
  
  //填充写缓冲区
  srand(0);
  for(i = 0; i < RW_TEST_LEN; i++)
  {
    writeData = rand();
    s_arrWriteBuf[i] = writeData & 0xFF;
    srand(writeData);
  }
  
  //创建文件,如果该文件已经存在,那么就覆盖该文件
  result = f_open(&s_structFile, "1:/NandFlashTest.txt", FA_CREATE_ALWAYS | FA_WRITE);
  if(FR_OK != result)
  {
    printf("NandFlasReadWrite: fail to create file\r\n");
    while(1){}
  }
  
  //写入数据
  result = f_write(&s_structFile, s_arrWriteBuf, RW_TEST_LEN, &writeNum);
  if(FR_OK != result)
  {
    printf("NandFlasReadWrite: fail to write data\r\n");
    while(1){}
  }
  
  //保存
  f_close(&s_structFile);
  
  //打开文件
  result = f_open(&s_structFile, "1:/NandFlashTest.txt", FA_READ);
  if(FR_OK != result)
  {
    printf("ReadFile: fail to open file\r\n");
    while(1){}
  }

  //读取数据
  result = f_read(&s_structFile, s_arrReadBuf, RW_TEST_LEN, &readNum);
  if(FR_OK != result)
  {
    printf("ReadFile: fail to read data from file\r\n");
    while(1){}
  }

  //关闭文件
  f_close(&s_structFile);
  
  //校验
  error = 0;
  for(i = 0; i < RW_TEST_LEN; i++)
  {
    if(s_arrReadBuf[i] != s_arrWriteBuf[i])
    {
      error = 1;
      break;
    }
  }
  
  //输出校验结果
  if(1 == error)
  {
    printf("Fail to check\r\n");
  }
  else
  {
    printf("Check OK\r\n");
  }

  while(1)
  {

  }
}