正点原子STM32H743VIT6+CubeMX+FATFS+w25q128实现电脑U盘

本博客引用帖子:https://blog.csdn.net/chen18221987993/article/details/128953166
并补充自己开发经验

硬件平台说明

硬件平台:正点原子STM32H743VIT6
软件平台:CubeMX6.9.0+keil5.35
使用USB_SLAVE接口连接电脑USB,从而读取W25Q128里的文件

STM32CubeMX配置

关于CubeMX的时钟基本配置,这里就不过多赘述,不了解的同学可以自行学习

  1. FreeRTOS,将任务栈大小调到1024,给任务分配足够的空间,防止栈溢出
    在这里插入图片描述
    将系统堆、栈调到0x2000
    在这里插入图片描述
  2. UART配置,开启USART1,方便打印调试信息,波特率115200Bits/s
    在这里插入图片描述
  3. 配置硬件SPI,刚开始通讯速率调低点,W25Q256可以使用模式0(CPOL =0 CPOA=0 ) 或者模式3(CPOL=1 CPOA=1),这里配置为模式0。模式3可自行测试
    在这里插入图片描述
  4. USB_OTG_FS:全速模式 USB_OTG_HS:高速模式
    在这里插入图片描述
  5. USB_DEVICE,MSC_MEDIA_PACKET参数修改为4096
    在这里插入图片描述
  6. FAFTS
    在这里插入图片描述

代码说明

main.c添加下列代码,使用printf()打印

int fputc(int ch,FILE *f)
{
    HAL_UART_Transmit(&huart1,(uint8_t*)&ch,1,1000);
    return (ch);
}

int fgetc(FILE *f)
{
    int ch;
    HAL_UART_Receive(&huart1,(uint8_t*)&ch,1,1000);
    return ch;
}

printf()还可以打印一些系统信息


/*
* __LINE__:在源代码中插入当前源代码行号;

* __FILE__:在源文件中插入当前源文件名;

* __DATE__:在源文件中插入当前的编译日期

* __TIME__:在源文件中插入当前编译时间;

* __STDC__:当要求程序严格遵循ANSI C标准时该标识被赋值为1;

* __cplusplus:当编写C++程序时该标识符被定义。

*/
#if 1
    #define log(format, ...)   printf(format, ##__VA_ARGS__)
    //#define log(format,...) printf("FILE: "__FILE__", LINE: %d: "format"\r\n", __LINE__, ##__VA_ARGS__)
#else
    #define log(format, ...)
#endif

w25q128.c

  • 注:SPI CS不能一直拉低
#include "w25q128.h"
#include "userDelay.h"

uint16_t W25QXX_TYPE = 0;
uint32_t W25QXX_SIZE = 0;
uint8_t  W25QXX_UID[8];

//static void delay_us(uint32_t us)
//{
//    uint32_t delay = (HAL_RCC_GetHCLKFreq() / 4000000 * us);
//    while (delay--)
//    {
//        ;
//    }
//}

static void delay_us(uint32_t us)
{
    tim6_delay_us(us);
}

/**
*   @brief  写入一个字节
*   @param  TxData:写入字节
*   @return none
*/
static uint8_t W25QXX_SPI_ReadWriteByte(uint8_t TxData)
{
	uint8_t RxData = 0X00;
	if(HAL_SPI_TransmitReceive(W25QXX_SPI_Handle, &TxData, &RxData, 1, 10) != HAL_OK)
	{
		RxData = 0XFF;
	}
	return RxData;
}

/**
*   @brief  初始化SPI IO口
*   @param  none
*   @return none
*/
int W25QXX_Init(void)
{
    W25QXX_CS_L(); /* 拉低选中 */
    W25QXX_SPI_ReadWriteByte(0XFF);
    W25QXX_CS_H(); /* 拉高取消 */
    W25QXX_TYPE = W25QXX_ReadID();          // 读取FLASH ID.
	W25QXX_SIZE = W25QXX_ReadCapacity();    // 读取容量
	W25QXX_ReadUniqueID(W25QXX_UID);        // 读取唯一ID
	if((W25QXX_TYPE & 0XEF00) != 0XEF00)
	{
		return -1;
	}
	return 0;
}

//读取W25QXX的状态寄存器
//BIT7  6   5   4   3   2   1   0
//SPR   RV  TB BP2 BP1 BP0 WEL BUSY
//SPR:默认0,状态寄存器保护位,配合WP使用
//TB,BP2,BP1,BP0:FLASH区域写保护设置
//WEL:写使能锁定
//BUSY:忙标记位(1,忙;0,空闲)
//默认:0x00
uint8_t W25QXX_ReadSR(void)
{
    uint8_t byte = 0;
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_ReadStatusReg); //发送读取状态寄存器命令
    byte = W25QXX_SPI_ReadWriteByte(0Xff);          //读取一个字节
    W25QXX_CS_H();  //取消片选
    return byte;
}
//写W25QXX状态寄存器
//只有SPR,TB,BP2,BP1,BP0(bit 7,5,4,3,2)可以写!!!
void W25QXX_Write_SR(uint8_t sr)
{
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_WriteStatusReg);                 //发送写取状态寄存器命令
    W25QXX_SPI_ReadWriteByte(sr);               	//写入一个字节
    W25QXX_CS_H();  //取消片选
}
//W25QXX写使能
//将WEL置位
void W25QXX_Write_Enable(void)
{
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_WriteEnable); 	//发送写使能
    W25QXX_CS_H();  //取消片选
}
//W25QXX写禁止
//将WEL清零
void W25QXX_Write_Disable(void)
{
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_WriteDisable);  //发送写禁止指令
    W25QXX_CS_H();  //取消片选
}
//读取芯片ID
//返回值如下:
//0XEF13,表示芯片型号为W25Q80
//0XEF14,表示芯片型号为W25Q16
//0XEF15,表示芯片型号为W25Q32
//0XEF16,表示芯片型号为W25Q64
//0XEF17,表示芯片型号为W25Q128
uint16_t W25QXX_ReadID(void)
{
    uint16_t Temp = 0;
    W25QXX_CS_L();
    W25QXX_SPI_ReadWriteByte(0x90);                            //发送读取ID命令
    W25QXX_SPI_ReadWriteByte(0x00);
    W25QXX_SPI_ReadWriteByte(0x00);
    W25QXX_SPI_ReadWriteByte(0x00);
    Temp |= W25QXX_SPI_ReadWriteByte(0xFF) << 8;
    Temp |= W25QXX_SPI_ReadWriteByte(0xFF);
    W25QXX_CS_H();
    return Temp;
}

uint32_t W25QXX_ReadCapacity(void)
{
	int i = 0;
	uint8_t arr[4] = {0,0,0,0};
    W25QXX_CS_L();
    W25QXX_SPI_ReadWriteByte(0x5A);
    W25QXX_SPI_ReadWriteByte(0x00);
    W25QXX_SPI_ReadWriteByte(0x00);
    W25QXX_SPI_ReadWriteByte(0x84);
	W25QXX_SPI_ReadWriteByte(0x00);
	for(i = 0; i < sizeof(arr); i++)
	{
		arr[i] = W25QXX_SPI_ReadWriteByte(0xFF);
	}
    W25QXX_CS_H();
    return ((((*(uint32_t *)arr)) + 1) >> 3);
}

void W25QXX_ReadUniqueID(uint8_t UID[8])
{
	int i = 0;
	W25QXX_CS_L();
    W25QXX_SPI_ReadWriteByte(0x4B);
    W25QXX_SPI_ReadWriteByte(0x00);
    W25QXX_SPI_ReadWriteByte(0x00);
    W25QXX_SPI_ReadWriteByte(0x00);
	W25QXX_SPI_ReadWriteByte(0x00);
    for(i = 0; i < 8; i++)
	{
		UID[i] = W25QXX_SPI_ReadWriteByte(0xFF);
	}
	W25QXX_CS_H();
}

//读取SPI FLASH
//在指定地址开始读取指定长度的数据
//pBuffer:数据存储区
//ReadAddr:开始读取的地址(24bit)
//NumByteToRead:要读取的字节数(最大65535)
void W25QXX_Read(uint8_t *pBuffer, uint32_t ReadAddr, uint16_t NumByteToRead)
{
    uint16_t i;
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_ReadData);         	//发送读取命令
    W25QXX_SPI_ReadWriteByte((uint8_t)((ReadAddr) >> 16));  	//发送24bit地址
    W25QXX_SPI_ReadWriteByte((uint8_t)((ReadAddr) >> 8));
    W25QXX_SPI_ReadWriteByte((uint8_t)ReadAddr);
    for (i = 0; i < NumByteToRead; i++)
    {
        pBuffer[i] = W25QXX_SPI_ReadWriteByte(0XFF);   	//循环读数
    }
    W25QXX_CS_H();
}
//SPI在一页(0~65535)内写入少于256个字节的数据
//在指定地址开始写入最大256字节的数据
//pBuffer:数据存储区
//WriteAddr:开始写入的地址(24bit)
//NumByteToWrite:要写入的字节数(最大256),该数不应该超过该页的剩余字节数!!!
void W25QXX_Write_Page(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite)
{
    uint16_t i;
    W25QXX_Write_Enable();                  	//SET WEL
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_PageProgram);      	//发送写页命令
    W25QXX_SPI_ReadWriteByte((uint8_t)((WriteAddr) >> 16)); 	//发送24bit地址
    W25QXX_SPI_ReadWriteByte((uint8_t)((WriteAddr) >> 8));
    W25QXX_SPI_ReadWriteByte((uint8_t)WriteAddr);
    for (i = 0; i < NumByteToWrite; i++)
        W25QXX_SPI_ReadWriteByte(pBuffer[i]); //循环写数
    W25QXX_CS_H();  //取消片选
    W25QXX_Wait_Busy();					   		//等待写入结束
}
//无检验写SPI FLASH
//必须确保所写的地址范围内的数据全部为0XFF,否则在非0XFF处写入的数据将失败!
//具有自动换页功能
//在指定地址开始写入指定长度的数据,但是要确保地址不越界!
//pBuffer:数据存储区
//WriteAddr:开始写入的地址(24bit)
//NumByteToWrite:要写入的字节数(最大65535)
//CHECK OK
void W25QXX_Write_NoCheck(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite)
{
    uint16_t pageremain;
    pageremain = 256 - WriteAddr % 256; //单页剩余的字节数
    if (NumByteToWrite <= pageremain)
        pageremain = NumByteToWrite; //不大于256个字节
    while (1)
    {
        W25QXX_Write_Page(pBuffer, WriteAddr, pageremain);
        if (NumByteToWrite == pageremain)
            break; //写入结束了
        else //NumByteToWrite>pageremain
        {
            pBuffer += pageremain;
            WriteAddr += pageremain;

            NumByteToWrite -= pageremain;			  //减去已经写入了的字节数
            if (NumByteToWrite > 256)
                pageremain = 256; //一次可以写入256个字节
            else
                pageremain = NumByteToWrite; 	  //不够256个字节了
        }
    };
}
//写SPI FLASH
//在指定地址开始写入指定长度的数据
//该函数带擦除操作!
//pBuffer:数据存储区
//WriteAddr:开始写入的地址(24bit)
//NumByteToWrite:要写入的字节数(最大65535)
uint8_t W25QXX_BUFFER[4096];
void W25QXX_Write(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite)
{
    uint32_t secpos;
    uint16_t secoff;
    uint16_t secremain;
    uint16_t i;
    uint8_t *W25QXX_BUF;
    W25QXX_BUF = W25QXX_BUFFER;
    secpos = WriteAddr / 4096; 	  //扇区地址
    secoff = WriteAddr % 4096; 	  //在扇区内的偏移
    secremain = 4096 - secoff; 	  //扇区剩余空间大小
    if (NumByteToWrite <= secremain)
        secremain = NumByteToWrite; 	  //不大于4096个字节
    while (1)
    {
        W25QXX_Read(W25QXX_BUF, secpos * 4096, 4096); 	  //读出整个扇区的内容
        for (i = 0; i < secremain; i++) //校验数据
        {
            if (W25QXX_BUF[secoff + i] != 0XFF)
                break; //需要擦除
        }
        if (i < secremain) //需要擦除
        {
            W25QXX_Erase_Sector(secpos);		//擦除这个扇区
            for (i = 0; i < secremain; i++)	   		//复制
            {
                W25QXX_BUF[i + secoff] = pBuffer[i];
            }
            W25QXX_Write_NoCheck(W25QXX_BUF, secpos * 4096, 4096);	   	//写入整个扇区

        }
        else
            W25QXX_Write_NoCheck(pBuffer, WriteAddr, secremain); //写已经擦除了的,直接写入扇区剩余区间.
        if (NumByteToWrite == secremain)
            break; //写入结束了
        else //写入未结束
        {
            secpos++; //扇区地址增1
            secoff = 0; //偏移位置为0

            pBuffer += secremain;  				//指针偏移
            WriteAddr += secremain;				//写地址偏移
            NumByteToWrite -= secremain;			//字节数递减
            if (NumByteToWrite > 4096)
                secremain = 4096;			//下一个扇区还是写不完
            else
                secremain = NumByteToWrite;		//下一个扇区可以写完了
        }
    };
}

//擦除整个芯片
//等待时间超长...
void W25QXX_Erase_Chip(void)
{
    W25QXX_Write_Enable();                 	 	//SET WEL
    W25QXX_Wait_Busy();
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_ChipErase);        	//发送片擦除命令
    W25QXX_CS_H();  //取消片选
    W25QXX_Wait_Busy();   				   		//等待芯片擦除结束
}
//擦除一个扇区
//Dst_Addr:扇区地址 根据实际容量设置
//擦除一个山区的最少时间:150ms
void W25QXX_Erase_Sector(uint32_t Dst_Addr)
{
    //监视falsh擦除情况,测试用
    Dst_Addr *= 4096;
    W25QXX_Write_Enable();                  	//SET WEL
    W25QXX_Wait_Busy();
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_SectorErase);      	//发送扇区擦除指令
    W25QXX_SPI_ReadWriteByte((uint8_t)((Dst_Addr) >> 16));  	//发送24bit地址
    W25QXX_SPI_ReadWriteByte((uint8_t)((Dst_Addr) >> 8));
    W25QXX_SPI_ReadWriteByte((uint8_t)Dst_Addr);
    W25QXX_CS_H();  //取消片选
    W25QXX_Wait_Busy();   				   		//等待擦除完成
}
//等待空闲
void W25QXX_Wait_Busy(void)
{
    while ((W25QXX_ReadSR() & 0x01) == 0x01);  		// 等待BUSY位清空
}
//进入掉电模式
void W25QXX_PowerDown(void)
{
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_PowerDown);        //发送掉电命令
    W25QXX_CS_H();  //取消片选
    delay_us(3);                               //等待TPD
}
//唤醒
void W25QXX_WAKEUP(void)
{
    W25QXX_CS_L(); //使能器件
    W25QXX_SPI_ReadWriteByte(W25X_ReleasePowerDown); //  send W25X_PowerDown command 0xAB
    W25QXX_CS_H();  //取消片选
    delay_us(3);                            	//等待TRES1
}

w25q128.h

#ifndef _W25Q128_H
#define _W25Q128_H
#include "bsp_uart.h"
#include "stm32h7xx_hal_spi.h"
#include "spi.h"
/**
* block:64KB

* sector:4KB

* page:256B

*/
#define W25QXX_CS_GPIO_Port   GPIOA
#define W25QXX_CS_Pin         GPIO_PIN_6

#define W25QXX_SPI_Handle (&hspi5)

//W25X系列/Q系列芯片列表
#define W25Q80 	0XEF13
#define W25Q16 	0XEF14
#define W25Q32 	0XEF15
#define W25Q64 	0XEF16
#define W25Q128	0XEF17

#define W25QXX_CS_L()  HAL_GPIO_WritePin(W25QXX_CS_GPIO_Port, W25QXX_CS_Pin, GPIO_PIN_RESET)
#define W25QXX_CS_H()  HAL_GPIO_WritePin(W25QXX_CS_GPIO_Port, W25QXX_CS_Pin, GPIO_PIN_SET)

//指令表
#define W25X_WriteEnable		0x06
#define W25X_WriteDisable		0x04
#define W25X_ReadStatusReg		0x05
#define W25X_WriteStatusReg		0x01
#define W25X_ReadData			0x03
#define W25X_FastReadData		0x0B
#define W25X_FastReadDual		0x3B
#define W25X_PageProgram		0x02
#define W25X_BlockErase			0xD8
#define W25X_SectorErase		0x20
#define W25X_ChipErase			0xC7
#define W25X_PowerDown			0xB9
#define W25X_ReleasePowerDown	0xAB
#define W25X_DeviceID			0xAB
#define W25X_ManufactDeviceID	0x90
#define W25X_JedecDeviceID		0x9F

extern uint16_t W25QXX_TYPE;
extern uint32_t W25QXX_SIZE;
extern uint8_t  W25QXX_UID[8];

int W25QXX_Init(void);
void W25QXX_ReadUniqueID(uint8_t UID[8]);
uint16_t  W25QXX_ReadID(void);  	    //读取FLASH ID
uint8_t	 W25QXX_ReadSR(void);        	//读取状态寄存器
void W25QXX_Write_SR(uint8_t sr);  		//写状态寄存器
void W25QXX_Write_Enable(void);  		//写使能
void W25QXX_Write_Disable(void);		//写保护
void W25QXX_Write_NoCheck(uint8_t* pBuffer,uint32_t WriteAddr,uint16_t NumByteToWrite);
void W25QXX_Read(uint8_t* pBuffer,uint32_t ReadAddr,uint16_t NumByteToRead);   //读取flash
void W25QXX_Write(uint8_t* pBuffer,uint32_t WriteAddr,uint16_t NumByteToWrite);//写入flash
void W25QXX_Erase_Chip(void);    	  	        //整片擦除
void W25QXX_Erase_Sector(uint32_t Dst_Addr);	//扇区擦除
void W25QXX_Wait_Busy(void);           	        //等待空闲
void W25QXX_PowerDown(void);        	        //进入掉电模式
void W25QXX_WAKEUP(void);				        //唤醒
uint32_t W25QXX_ReadCapacity(void);

#endif

user_diskio.c

/* USER CODE BEGIN Header */
/**
 ******************************************************************************
  * @file    user_diskio.c
  * @brief   This file includes a diskio driver skeleton to be completed by the user.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
 /* USER CODE END Header */

#ifdef USE_OBSOLETE_USER_CODE_SECTION_0
/*
 * Warning: the user section 0 is no more in use (starting from CubeMx version 4.16.0)
 * To be suppressed in the future.
 * Kept to ensure backward compatibility with previous CubeMx versions when
 * migrating projects.
 * User code previously added there should be copied in the new user sections before
 * the section contents can be deleted.
 */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
#endif

/* USER CODE BEGIN DECL */

/* Includes ------------------------------------------------------------------*/
#include <string.h>
#include "ff_gen_drv.h"

#include "bsp_uart.h"
#include "fatfs.h"
#include "w25q128.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/
/* Disk status */
static volatile DSTATUS Stat = STA_NOINIT;

#define PAGE_SIZE       256
#define SECTOR_SIZE     4096
#define SECTOR_COUNT	4096
#define BLOCK_SIZE	    65536
#define FLASH_PAGES_PER_SECTOR	SECTOR_SIZE/PAGE_SIZE

FRESULT f_res;                    /* 文件操作结果 */
UINT bw;
BYTE ReadBuffer[1024]={0};        /* 读缓冲区 */
BYTE WriteBuffer[]= "STM32CubeMX W25QXX FATFS FREERTOS Text\r\n";
BYTE work[4096];
 
void mount_disk(void)
{
   f_res = f_mount(&USERFatFS, USERPath, 1);
   log("f_mount=%d\r\n",f_res);
   return;
}

void format_disk(void)
{
  //这里根据版本不同函数输入参数不一样
  f_res = f_mkfs(USERPath, FM_FAT, 4096, work, sizeof(work));
  log("f_mkfs=%d\r\n",f_res);
}

void create_file(void)
{
  f_res = f_open(&USERFile, "test.txt", FA_OPEN_ALWAYS | FA_WRITE);
  f_res = f_write(&USERFile, WriteBuffer, sizeof(WriteBuffer), &bw);
  f_res = f_close(&USERFile);
}

void read_file(void)
{
  f_res = f_open(&USERFile, "test.txt", FA_READ);
  memset(ReadBuffer, 0, sizeof(ReadBuffer));
  f_res = f_read(&USERFile, ReadBuffer, sizeof(WriteBuffer), &bw);
  log("read data is : %s\r\n", ReadBuffer);
  f_res = f_close(&USERFile);
}

FRESULT  fileSystemInit()
{
    FRESULT res = FR_OK;
    res = f_mount(&USERFatFS, USERPath, 1);
    if (res != FR_OK)
    {
        //No Disk file system,format disk !
        res = f_mkfs(USERPath, FM_FAT, 4096, work, sizeof( work));
        if (res == FR_OK)
        {
            res = f_mount(&USERFatFS, USERPath, 1);
            if (res == 0)
            {
                return FR_OK;
            }
            else
                return FR_DISK_ERR;
        }
        else
            return FR_DISK_ERR;
    }
    else
        return FR_OK;
}

void FatfsTest(void)
{
	fileSystemInit();
    create_file();
	read_file();
}

/* USER CODE END DECL */

/* Private function prototypes -----------------------------------------------*/
DSTATUS USER_initialize (BYTE pdrv);
DSTATUS USER_status (BYTE pdrv);
DRESULT USER_read (BYTE pdrv, BYTE *buff, DWORD sector, UINT count);
#if _USE_WRITE == 1
  DRESULT USER_write (BYTE pdrv, const BYTE *buff, DWORD sector, UINT count);
#endif /* _USE_WRITE == 1 */
#if _USE_IOCTL == 1
  DRESULT USER_ioctl (BYTE pdrv, BYTE cmd, void *buff);
#endif /* _USE_IOCTL == 1 */

Diskio_drvTypeDef  USER_Driver =
{
  USER_initialize,
  USER_status,
  USER_read,
#if  _USE_WRITE
  USER_write,
#endif  /* _USE_WRITE == 1 */
#if  _USE_IOCTL == 1
  USER_ioctl,
#endif /* _USE_IOCTL == 1 */
};

/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Initializes a Drive
  * @param  pdrv: Physical drive number (0..)
  * @retval DSTATUS: Operation status
  */
DSTATUS USER_initialize (
	BYTE pdrv           /* Physical drive nmuber to identify the drive */
)
{
  /* USER CODE BEGIN INIT */
    Stat = STA_NOINIT;
    if(W25QXX_Init() == 0)
    {
        Stat &= ~STA_NOINIT;
    }
    return Stat;
  /* USER CODE END INIT */
}

/**
  * @brief  Gets Disk Status
  * @param  pdrv: Physical drive number (0..)
  * @retval DSTATUS: Operation status
  */
DSTATUS USER_status (
	BYTE pdrv       /* Physical drive number to identify the drive */
)
{
  /* USER CODE BEGIN STATUS */
    Stat &= ~STA_NOINIT;
    return Stat;
  /* USER CODE END STATUS */
}

/**
  * @brief  Reads Sector(s)
  * @param  pdrv: Physical drive number (0..)
  * @param  *buff: Data buffer to store read data
  * @param  sector: Sector address (LBA)
  * @param  count: Number of sectors to read (1..128)
  * @retval DRESULT: Operation result
  */
DRESULT USER_read (
	BYTE pdrv,      /* Physical drive nmuber to identify the drive */
	BYTE *buff,     /* Data buffer to store read data */
	DWORD sector,   /* Sector address in LBA */
	UINT count      /* Number of sectors to read */
)
{
  /* USER CODE BEGIN READ */
    DRESULT res = RES_ERROR;
    UINT i;
  
    for(i = 0;i < count;i++)
    {
        W25QXX_Read(buff + i * SECTOR_SIZE, sector * SECTOR_SIZE + i * SECTOR_SIZE, SECTOR_SIZE );
    }
	
    res = RES_OK;

    return res;
  /* USER CODE END READ */
}

/**
  * @brief  Writes Sector(s)
  * @param  pdrv: Physical drive number (0..)
  * @param  *buff: Data to be written
  * @param  sector: Sector address (LBA)
  * @param  count: Number of sectors to write (1..128)
  * @retval DRESULT: Operation result
  */
#if _USE_WRITE == 1
DRESULT USER_write (
	BYTE pdrv,          /* Physical drive nmuber to identify the drive */
	const BYTE *buff,   /* Data to be written */
	DWORD sector,       /* Sector address in LBA */
	UINT count          /* Number of sectors to write */
)
{
  /* USER CODE BEGIN WRITE */
    DRESULT res = RES_ERROR;
	
    UINT i;
    for(i = 0;i < count;i++)
    {
        W25QXX_Write((void *)(buff + i * SECTOR_SIZE), sector * SECTOR_SIZE + i * SECTOR_SIZE, SECTOR_SIZE );
    }
    res = RES_OK;	
  
  /* USER CODE HERE */
    return res;
  /* USER CODE END WRITE */
}
#endif /* _USE_WRITE == 1 */

/**
  * @brief  I/O control operation
  * @param  pdrv: Physical drive number (0..)
  * @param  cmd: Control code
  * @param  *buff: Buffer to send/receive control data
  * @retval DRESULT: Operation result
  */
#if _USE_IOCTL == 1
DRESULT USER_ioctl (
	BYTE pdrv,      /* Physical drive nmuber (0..) */
	BYTE cmd,       /* Control code */
	void *buff      /* Buffer to send/receive control data */
)
{
  /* USER CODE BEGIN IOCTL */
    DRESULT res = RES_OK;
  
    switch(cmd)
    {
        case CTRL_SYNC :
            break;	
 
        case CTRL_TRIM:
            break;
		
        case GET_BLOCK_SIZE:
        *(DWORD*)buff = BLOCK_SIZE; 
        break;
		
        case GET_SECTOR_SIZE:
        *(DWORD*)buff = SECTOR_SIZE;
        break;
		
        case GET_SECTOR_COUNT:
        *(DWORD*)buff = SECTOR_COUNT;
        break;
			
        default:
        res = RES_PARERR;
        break;
    }
    return res;
  /* USER CODE END IOCTL */
}
#endif /* _USE_IOCTL == 1 */

usbd_storage_if.c

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : usbd_storage_if.c
  * @version        : v1.0_Cube
  * @brief          : Memory management layer.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "usbd_storage_if.h"

/* USER CODE BEGIN INCLUDE */
#include "w25q128.h"
/* USER CODE END INCLUDE */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/

/* USER CODE END PV */

/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
  * @brief Usb device.
  * @{
  */

/** @defgroup USBD_STORAGE
  * @brief Usb mass storage device module
  * @{
  */

/** @defgroup USBD_STORAGE_Private_TypesDefinitions
  * @brief Private types.
  * @{
  */

/* USER CODE BEGIN PRIVATE_TYPES */

/* USER CODE END PRIVATE_TYPES */

/**
  * @}
  */

/** @defgroup USBD_STORAGE_Private_Defines
  * @brief Private defines.
  * @{
  */

#define STORAGE_LUN_NBR                  1
#define STORAGE_BLK_NBR                  0x10000
#define STORAGE_BLK_SIZ                  0x200

/* USER CODE BEGIN PRIVATE_DEFINES */
#define STORAGE_LUN_NBR                  1
#define STORAGE_BLK_NBR                  4096  //存储器扇区数量
#define STORAGE_BLK_SIZ                  4096  //存储器扇区大小
/* USER CODE END PRIVATE_DEFINES */

/**
  * @}
  */

/** @defgroup USBD_STORAGE_Private_Macros
  * @brief Private macros.
  * @{
  */

/* USER CODE BEGIN PRIVATE_MACRO */

/* USER CODE END PRIVATE_MACRO */

/**
  * @}
  */

/** @defgroup USBD_STORAGE_Private_Variables
  * @brief Private variables.
  * @{
  */

/* USER CODE BEGIN INQUIRY_DATA_FS */
/** USB Mass storage Standard Inquiry Data. */
const int8_t STORAGE_Inquirydata_FS[] = {/* 36 */

  /* LUN 0 */
  0x00,
  0x80,
  0x02,
  0x02,
  (STANDARD_INQUIRY_DATA_LEN - 5),
  0x00,
  0x00,
  0x00,
  'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer : 8 bytes */
  'P', 'r', 'o', 'd', 'u', 'c', 't', ' ', /* Product      : 16 Bytes */
  ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
  '0', '.', '0' ,'1'                      /* Version      : 4 Bytes */
};
/* USER CODE END INQUIRY_DATA_FS */

/* USER CODE BEGIN PRIVATE_VARIABLES */

/* USER CODE END PRIVATE_VARIABLES */

/**
  * @}
  */

/** @defgroup USBD_STORAGE_Exported_Variables
  * @brief Public variables.
  * @{
  */

extern USBD_HandleTypeDef hUsbDeviceFS;

/* USER CODE BEGIN EXPORTED_VARIABLES */

/* USER CODE END EXPORTED_VARIABLES */

/**
  * @}
  */

/** @defgroup USBD_STORAGE_Private_FunctionPrototypes
  * @brief Private functions declaration.
  * @{
  */

static int8_t STORAGE_Init_FS(uint8_t lun);
static int8_t STORAGE_GetCapacity_FS(uint8_t lun, uint32_t *block_num, uint16_t *block_size);
static int8_t STORAGE_IsReady_FS(uint8_t lun);
static int8_t STORAGE_IsWriteProtected_FS(uint8_t lun);
static int8_t STORAGE_Read_FS(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
static int8_t STORAGE_Write_FS(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
static int8_t STORAGE_GetMaxLun_FS(void);

/* USER CODE BEGIN PRIVATE_FUNCTIONS_DECLARATION */

/* USER CODE END PRIVATE_FUNCTIONS_DECLARATION */

/**
  * @}
  */

USBD_StorageTypeDef USBD_Storage_Interface_fops_FS =
{
  STORAGE_Init_FS,
  STORAGE_GetCapacity_FS,
  STORAGE_IsReady_FS,
  STORAGE_IsWriteProtected_FS,
  STORAGE_Read_FS,
  STORAGE_Write_FS,
  STORAGE_GetMaxLun_FS,
  (int8_t *)STORAGE_Inquirydata_FS
};

/* Private functions ---------------------------------------------------------*/
/**
  * @brief  Initializes the storage unit (medium) over USB FS IP
  * @param  lun: Logical unit number.
  * @retval USBD_OK if all operations are OK else USBD_FAIL
  */
int8_t STORAGE_Init_FS(uint8_t lun)
{
  /* USER CODE BEGIN 2 */
  UNUSED(lun);
    
  W25QXX_Init();
  return (USBD_OK);
  /* USER CODE END 2 */
}

/**
  * @brief  Returns the medium capacity.
  * @param  lun: Logical unit number.
  * @param  block_num: Number of total block number.
  * @param  block_size: Block size.
  * @retval USBD_OK if all operations are OK else USBD_FAIL
  */
int8_t STORAGE_GetCapacity_FS(uint8_t lun, uint32_t *block_num, uint16_t *block_size)
{
  /* USER CODE BEGIN 3 */
  UNUSED(lun);

  *block_num  = STORAGE_BLK_NBR;
  *block_size = STORAGE_BLK_SIZ;
  return (USBD_OK);
  /* USER CODE END 3 */
}

/**
  * @brief   Checks whether the medium is ready.
  * @param  lun:  Logical unit number.
  * @retval USBD_OK if all operations are OK else USBD_FAIL
  */
int8_t STORAGE_IsReady_FS(uint8_t lun)
{
  /* USER CODE BEGIN 4 */
  UNUSED(lun);
    
  if(W25QXX_ReadID() != 0)
    return (USBD_OK);
  else
    return -1;
  /* USER CODE END 4 */
}

/**
  * @brief  Checks whether the medium is write protected.
  * @param  lun: Logical unit number.
  * @retval USBD_OK if all operations are OK else USBD_FAIL
  */
int8_t STORAGE_IsWriteProtected_FS(uint8_t lun)
{
  /* USER CODE BEGIN 5 */
  UNUSED(lun);

  return (USBD_OK);
  /* USER CODE END 5 */
}

/**
  * @brief  Reads data from the medium.
  * @param  lun: Logical unit number.
  * @param  buf: data buffer.
  * @param  blk_addr: Logical block address.
  * @param  blk_len: Blocks number.
  * @retval USBD_OK if all operations are OK else USBD_FAIL
  */
int8_t STORAGE_Read_FS(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{
  /* USER CODE BEGIN 6 */
  UNUSED(lun);
  UNUSED(buf);
  UNUSED(blk_addr);
  UNUSED(blk_len);
    
  uint32_t i = 0; 
    
  for(i = 0;i < blk_len;i++)
  {
    W25QXX_Read(buf + i * STORAGE_BLK_SIZ, blk_addr * STORAGE_BLK_SIZ + i * STORAGE_BLK_SIZ, STORAGE_BLK_SIZ );
  }
  
  return (USBD_OK);
  /* USER CODE END 6 */
}

/**
  * @brief  Writes data into the medium.
  * @param  lun: Logical unit number.
  * @param  buf: data buffer.
  * @param  blk_addr: Logical block address.
  * @param  blk_len: Blocks number.
  * @retval USBD_OK if all operations are OK else USBD_FAIL
  */
int8_t STORAGE_Write_FS(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{
  /* USER CODE BEGIN 7 */
  UNUSED(lun);
  UNUSED(buf);
  UNUSED(blk_addr);
  UNUSED(blk_len);
    
  uint32_t i = 0;
    
  for(i = 0;i < blk_len;i++)
  {
    W25QXX_Write((void *)(buf + i * STORAGE_BLK_SIZ),blk_addr * STORAGE_BLK_SIZ + i * STORAGE_BLK_SIZ,STORAGE_BLK_SIZ );
  }
  
  return (USBD_OK);
  /* USER CODE END 7 */
}

/**
  * @brief  Returns the Max Supported LUNs.
  * @param  None
  * @retval Lun(s) number.
  */
int8_t STORAGE_GetMaxLun_FS(void)
{
  /* USER CODE BEGIN 8 */
  return (STORAGE_LUN_NBR - 1);
  /* USER CODE END 8 */
}

/* USER CODE BEGIN PRIVATE_FUNCTIONS_IMPLEMENTATION */

/* USER CODE END PRIVATE_FUNCTIONS_IMPLEMENTATION */

/**
  * @}
  */

/**
  * @}
  */

运行

调用FatfsTest()函数
在这里插入图片描述

注意

需要注意的是,使用freertos的情况下,电脑出现无法识别的USB设备,需要将USB中断优先级设置小于Freertos优先级

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值