sd卡程序
#include
#include
#define uint unsigned int
#define uchar unsigned char
//错误码定义//
#define cmd0_error 0x01
#define cmd1_error 0x02
#define write_error 0x03
#define read_error 0x04
/*位定义*/
sbit so=P1^0; //定义主机接收位
sbit clk=P1^1; //定义时钟位
sbit si=P1^2; //定义主机发送数据位
sbi...
#include
#include
#define uint unsigned int
#define uchar unsigned char
//错误码定义//
#define cmd0_error 0x01
#define cmd1_error 0x02
#define write_error 0x03
#define read_error 0x04
/*位定义*/
sbit so=P1^0; //定义主机接收位
sbit clk=P1^1; //定义时钟位
sbit si=P1^2; //定义主机发送数据位
sbit cs=P1^3; //定义片选位
uchar xdata shuju[512]={0}; //定义数据缓冲数组
uchar flag_time;
//定义标志时间,因为当 sd 卡进行初始化时需要降低
//通信速度,所以通过该标志来写 1来降低速度
void delay(uint x) //通信延时函数
{
while(x--)
_nop_();
}
void delay1(uint a)
{
uint i,j;
for(i=0;i>24);
table[2]=((add&0x00ff0000)>>16);
table[3]=((add&0x0000ff00)>>8);
cs=0;
time=0;
do
{
temp=write_cmd(table); //写入写扇区命令
time++;
if(time==100)
{
return(write_error);
}
}
while(temp!=0x00); //判断命令是否写入成功成功时返回
0x00
for(i=0;i<20;i++) //补充若干时钟
{
write_sd(0xff);
}
write_sd(0xfe); //写入开始字节 0xfe,后面要写入 512 字节数据
for(i=0;i<512;i++)
{
write_sd(buffer[i]);
}
write_sd(0xff);
write_sd(0xff); //两字节奇偶校验
temp=read_sd(); //读取返回值
if((temp&0x1f)!=0x05) //如果返回值是 xxx00101 说明数据已经
被写入
{
cs=1;
return(write_error);
}
while(read_sd()!=0xff); //等待 sd 卡不忙 数据写入成功
cs=1; //关闭片选
write_sd(0xff); //补偿 8 个时钟
return 0;
}
//读取 sd 卡扇区//
uchar duqushanqu(unsigned long add,uchar *buffer)
{
uchar temp,time=0;
uint i;
uchar table[]={0x51,0x00,0x00,0x00,0x00,0xff};
add=add<<9;
table[1]=((add&0xff000000)>>24);
table[2]=((add&0x00ff0000)>>16);
table[3]=((add&0x0000ff00)>>8);
cs=0; //打开片选
do
{
temp=write_cmd(table); //写命令
time++;
if(time==100)
{
return read_error;
}
}
while(temp!=0);
write_sd(0xff); //补偿 8个时钟
while(read_sd()!=0xfe); //一直读取等待 0xfe
for(i=0;i<512;i++)
{
buffer[i]=read_sd();
}
write_sd(0xff); //两字节奇偶校验位
write_sd(0xff);
cs=1;
write_sd(0xff); //补偿 8个时钟
return 0;
}
/*在 P0 上接八个发光二极管用来显示读取到的数据
首先在数组(shuju)里面放入 i用于显示,再将其
写入 SD 卡扇区,然后在读取出 SD 卡里的数据*/
void main()
{
uint i=0;
P2=0x00;
P0=0xff;
sd_reset();
sd_init(); ///初始化 sd 卡
for(i=0;i<512;i++)
{
shuju[i]=i; //向数据数组里面写入数据
}
xie_sd_shanqu(1,shuju); //将数据数组里面的数据写入 sd 卡
for(i=0;i<2;i++)
{
shuju[i]=0; //清零数据数组用来存储从 sd 卡读取到的数据
}
duqushanqu(1,shuju); //读取扇区数据
while(1)
{
for(i=0;i<512;i++)
{
P0=shuju[i]; //显示扇区数据
delay1(200);
}
}
}
本文档为【sd卡程序】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。