#include "src/W25QXXArduino/w25qxx.h"
#include "src/FATS/ff.h"
/***FATS 这几个变量设置为全局变量，不然会栈溢出错误***/
BYTE work[4096]; //FATFS工作缓冲区
FATFS fs;   //文件系统对象
FIL fil;    //文件对象
FRESULT res;//操作返回对象
UINT bw, i; //临时变量
BYTE mm[500]; //临时数组
/***FATS***/
void setup() {
  // put your setup code here, to run once:
  uint8_t table[256]={0};
  Serial.setRxBufferSize(256);
  Serial.setTimeout(10);
  Serial.onReceive(SerialRe,true);
  Serial.begin(115200);
  delay(1000*9);
  W25QXX_Init();
  Serial.printf("flash is %X\n",W25QXX_ReadID());
  ///写文件测试文件//
	 res = f_mount(&fs, "0:",1);
	 if(res == 0X0D) //FLASH磁盘，FAT文件系统错误，重新格式化FLASH
	 {
		 Serial.printf("Flash Disk Formatting...\n"); //格式化FLASH
		 res = f_mkfs("0:",FM_ANY,0,work,sizeof(work));
		 if(res != FR_OK)
			Serial.printf("mkfs error.\n");
	 }
	 if(res == FR_OK)
		 Serial.printf("FATFS Init ok!\n");
	 res = f_open(&fil,"0:/test.txt",FA_CREATE_NEW);
	 if(res != FR_OK && res != FR_EXIST)
		 Serial.printf("create file error.\n");
	 if(res == FR_EXIST)
		 res = f_open(&fil,"0:test.txt",FA_WRITE|FA_READ|FA_OPEN_APPEND);
	 if(res != FR_OK)
		 Serial.printf("open file error.\n");
	 else{
		Serial.printf("open file ok.\n");
		f_puts("Hello,World!\n你好世界\n",&fil);
		Serial.printf("file size:%lu Bytes.\n", f_size(&fil));
		memset(mm,0x0,500);
		f_lseek(&fil,0);
		res = f_read(&fil,mm,500,&i);
		if(res == FR_OK)  printf("read size:%d Bytes.\n%s",i,mm);
		else     Serial.printf("read error!\r\n");
		f_close(&fil);
		/*卸载文件系统*/
		f_mount(0,"0:",0);
	 }
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(1000);
}
void SerialRe(){
  // uint8_t buffer[256]={0};
  // static int pagecnt = 0;
  // if(Serial.available()){  
  //   Serial.readBytes(buffer,256);  
  // }  
  //   W25QXX_Write_Page(buffer,256*pagecnt,256);
  //   pagecnt++;
  //   Serial.printf("page %02d\n",pagecnt);
    int i;
    uint8_t buffer[16]={0};
    if(Serial.available()){
     i = Serial.parseInt();
     Serial.printf("read %0d\n",i);
     W25QXX_Read(buffer,i,16);
     for(uint8_t temp:buffer){
       Serial.printf("%02X ",temp);
     }
  }
}
