硬件环境:神州一号板
软件环境:MDK
1、sd卡硬件初始化
PA5---------CLK
PA6---------MISO
PA7---------MOSI
PB7---------CS
void TurnToSD(void)
{
SPI_InitTypeDef SPI_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB |
RCC_APB2Periph_GPIOC |
RCC_APB2Periph_AFIO |
RCC_APB2Periph_SPI1,
ENABLE);
/*A5=CLK,A6=MISO,A7=MOSI*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/*A5=CLK,A6=MISO,A7=MOSI*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Configure PB.7 as CS*/
//置高
GPIO_SetBits(GPIOB, GPIO_Pin_7);//置为高
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
/* SPI1 configuration */
SPI_Cmd(SPI1, DISABLE); //必须要有才能改变MODE
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //两线全双工
SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //主
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //8位
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; //CPOL=1 时钟悬空高
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //CPHA=1 数据捕获第二个
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //软件NSS
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_128; //256分频
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //高位在前
SPI_InitStructure.SPI_CRCPolynomial = 7; //CRC7
SPI_Init(SPI1, &SPI_InitStructure);
//SPI_SSOutputCmd(SPI1, ENABLE); //使能NSS脚可用
/* Enable SPI1 */
SPI_Cmd(SPI1, ENABLE);
SPI_Release(); //复位一下总线,这个比较重要
}
关于片选的宏定义:
#define MMC_SELECT() GPIO_ResetBits(GPIOB, GPIO_Pin_7) /* MMC CS = L */
#define MMC_DESELECT() GPIO_SetBits(GPIOB, GPIO_Pin_7) /* MMC CS = H */
2、每次都新建一个haha5.txt文档,并写入数据
如果文档存在,则覆盖之。
f_mount在for外
写步骤:打开文件---写文件---关闭文件
读步骤:打开文件---读文件---关闭文件
void TestSD1(void)
{
FATFS fs;
FIL fil;
FRESULT res; //文件系统返回信息
char rbyte[300];
char wbyte[]="男儿当自强!!!";
u32 rlen,wlen;
f_mount(0,&fs);//注册一个文件系统
for(;;)
{
//写
res = f_open(&fil, "haha5.txt", FA_CREATE_ALWAYS | FA_WRITE);
res = f_write(&fil, wbyte, sizeof(wbyte), &wlen);
if(res || wlen
{
USART1_Puts("write failed!!!\r\n");
//break;
}
USART1_Puts("write suc!\r\n");
f_close(&fil);
delay_ms(5000000);
//读
res = f_open(&fil, "haha5.txt", FA_READ);
res = f_read(&fil, rbyte, sizeof(rbyte)-1, &rlen);
if (res || rlen == 0)
// break; // error or eof
;
rbyte[rlen]='\0';
USART1_Puts(rbyte);
if( res==FR_OK )
USART1_Puts("f_read file suc!\r\n");
else
USART1_Puts("f_read file erro!\r\n");
f_close(&fil);
delay_ms(5000000);
}
f_mount(0, NULL);
}
效果图如下:
阅读(1679) | 评论(0) | 转发(0) |