初来咋到,前两天把帖子贴嵌入式了!
大致代码如下,用的是Znfat的代码,复位成功了,初始化不行。请大家帮忙看看。比较急
#include "STC12C5A32S2.H"
#define DELAY_TIME 10
#define TRY_TIME 200
void SD_spi_write(unsigned char x)
{
_dat=x;
SD_SI=_dat7;
SD_SCL=0;
if(is_init) delay(DELAY_TIME);
SD_SCL=1;
if(is_init) delay(DELAY_TIME);
SD_SI=_dat6;
SD_SCL=0;
if(is_init) delay(DELAY_TIME);
SD_SCL=1;
if(is_init) delay(DELAY_TIME);
SD_SI=_dat5;
SD_SCL=0;
if(is_init) delay(DELAY_TIME);
SD_SCL=1;
if(is_init) delay(DELAY_TIME);
SD_SI=_dat4;
SD_SCL=0;
if(is_init) delay(DELAY_TIME);
SD_SCL=1;
if(is_init) delay(DELAY_TIME);
SD_SI=_dat3;
SD_SCL=0;
if(is_init) delay(DELAY_TIME);
SD_SCL=1;
if(is_init) delay(DELAY_TIME);
SD_SI=_dat2;
SD_SCL=0;
if(is_init) delay(DELAY_TIME);
SD_SCL=1;
if(is_init) delay(DELAY_TIME);
SD_SI=_dat1;
SD_SCL=0;
if(is_init) delay(DELAY_TIME);
SD_SCL=1;
if(is_init) delay(DELAY_TIME);
SD_SI=_dat0;
SD_SCL=0;
if(is_init) delay(DELAY_TIME);
SD_SCL=1;
if(is_init) delay(DELAY_TIME);
}
读字节和这个函数刚好相反,字数有限就不贴了。
unsigned char SD_Write_Cmd(unsigned char *pcmd) //向SD卡写命令,pcmd是命令字节序列的首地址
{
unsigned char temp,time=0;
SD_CS=1;
SD_spi_write(0xff); //提高兼容性,如果没有这里,有些SD卡可能不支持
SD_CS=0;
SD_spi_write(pcmd[0]);
SD_spi_write(pcmd[1]);
SD_spi_write(pcmd[2]);
SD_spi_write(pcmd[3]);
SD_spi_write(pcmd[4]);
SD_spi_write(pcmd[5]);
do
{
temp = SD_spi_read();//一直读,直到读到的不是0xff或超时
//senddata(temp);
time++;
}while((temp==0xff)&&(time<TRY_TIME));
return(temp);
}
unsigned char SD_Init() //初始化,使用CMD1(命令1)
{
unsigned char time,temp;
unsigned char pcmd[] = {0x41,0x00,0x00,0x00,0x00,0xff}; //命令1的字节序列
SD_CS=0; //打开片选
time=0;
do
{
temp=SD_Write_Cmd(pcmd);
time++;
if(time==TRY_TIME)
{
SD_CS=1; //关闭片选
return(INIT_CMD1_ERROR);//CMD1写入失败
}
}while(temp!=0);
is_init=0; //初始化完毕,将is_init设置为0,为了提高以后的数据传输速度
SD_CS=1; //关闭片选
SD_spi_write(0xff); //按照SD卡的操作时序在这里补8个时钟
return(0); //返回0,说明初始化操作成功
}
unsigned char SD_Reset()
{
unsigned char time,temp,i;
unsigned char pcmd[] = {0x40,0x00,0x00,0x00,0x00,0x95};
is_init=1; //is_init置为1,让SPI速度慢下来
SD_CS=1;
for(i=0;i<0x0f;i++) //初始时,首先要发送最少74个时钟信号,这是必须的!!!
{
SD_spi_write(0xff); //120个时钟
}
SD_CS=0;
time=0;
do
{
temp=SD_Write_Cmd(pcmd);//写入CMD0
time++;
if(time==TRY_TIME)
{
return(INIT_CMD0_ERROR);//CMD0写入失败
}
}while(temp!=0x01);
SD_CS=1;
SD_spi_write(0xff); //按照SD卡的操作时序在这里补8个时钟
return 0;//返回0,说明复位操作成功
}
void main()
{
int i,j;
i=1;
serialinit();
j=SD_Reset();//SD卡复位
i=SD_Init(); //SD卡初始化
senddata(j);
//senddata(i);
while(1) {}
}
下面附件是原理图,现在搞不清楚是硬件问题还是软件问题了。
此帖出自
小平头技术问答
一周热门 更多>