#ifndef __W25Qxx_H
#define __W25Qxx_H
#include "gpio.h"
#include "main.h"
#include "stm32l4xx_hal_gpio.h"

#ifdef __cplusplus
 extern "C" {
#endif
#define W25X_WriteEnable		      0x06    //FLASH 写使能
#define W25X_WriteDisable		      0x04 
#define W25X_ReadStatusReg		    0x05 		//FLASH 读取状态
#define W25X_WriteStatusReg		    0x01 		//FLASH 写状态
#define W25X_ReadData			        0x03    //可低速下读FLASH数据
#define W25X_FastReadData		      0x0B 		//快速读取
#define W25X_FastReadDual		      0x3B 
#define W25X_PageProgram		      0x02    //按页写FLASH
#define W25X_BlockErase			      0xD8 
#define W25X_SectorErase		      0x20    //擦除FLASH扇区
#define W25X_ChipErase			      0xC7    //擦除FLASH块
#define W25X_PowerDown			      0xB9 		//深度掉电模式功耗1uA
#define W25X_ReleasePowerDown	    0xAB 		//退出深度掉电模式
#define W25X_DeviceID			        0xAB 
#define W25X_ManufactDeviceID   	0x90 
#define W25X_JedecDeviceID		    0x9F 		//FLASH 读ID
#define FLASH_CS_PIN        GPIO_PIN_12
#define FLASH_CS_PORT       GPIOB
 
#define SPI_FLASH_CS_LOW()       HAL_GPIO_WritePin(FLASH_CS_PORT, FLASH_CS_PIN, GPIO_PIN_RESET);
#define SPI_FLASH_CS_HIGH()      HAL_GPIO_WritePin(FLASH_CS_PORT, FLASH_CS_PIN, GPIO_PIN_SET);


#define W25Q128_FLASH_SIZE        (16 * 1024 * 1024) // 16MB
#define W25Q128_SECTOR_SIZE       4096               // 每扇区4KB
#define W25Q128_PAGE_SIZE         256                // 每页256字节

#define W25Q128_TEMP_DATA_MAX_ADDR   (W25Q128_FLASH_SIZE)  // 最大可写地址
#define W25Q128_TEMP_DATA_BASE_ADDR  0x00000000          	 // 起始地址
#define W25Q128_TOTAL_PAGES   (W25Q128_FLASH_SIZE / W25Q128_PAGE_SIZE)
#define W25Q128_SECTOR_COUNT      (W25Q128_TEMP_DATA_MAX_ADDR / W25Q128_SECTOR_SIZE)
#define FLASH_PRINT_START_PAGE  0
#define FLASH_PRINT_END_PAGE    10  // 打印第0页到第10页，共11页

extern uint32_t W25_Tempaddress;


static uint8_t spi_flash_read_byte(void);
static uint8_t spi_flash_send_byte(uint8_t byte);
static void spi_flash_write_enable(void);
void spi_flash_wait_for_write_end(void) ;
uint32_t spi_flash_read_ID(void);
void spi_flash_read(uint32_t addr,uint8_t *pdata, uint16_t size);
void spi_flash_page_write(uint32_t addr, uint8_t *pdata, uint16_t size);
void spi_flash_write(uint32_t addr, uint8_t *pdata, uint32_t size);
void spi_flash_sector_erase(uint32_t sector_addr);
void spi_flash_block_erase(void);
void spi_flash_enter_deep_power_down(void);
void spi_flash_release_from_deep_power_down(void);
void flash_write_tempprecoh2_data(uint8_t* data, uint32_t length);
void flash_read_all_temp_data(void);
void flash_dma_print_all_pages_start(void);
void flash_dma_print_next_page(void);
void print_flash_pages(uint32_t start, uint32_t end);
void flash_clear_all_data(void);

#endif
