8051单片机以SPI总线读写MicroChip的25AA320 EEPROM的电路和源码:
# include <reg51.h> //包含单片机寄存器的头文件
# include <intrins.h> //包含_nop_()函数定义的头文件
sbit CS=P1^3;
sbit SO=P1^2;
sbit SI=P1^1;
sbit SCK=P1^0;
//SCK=0;
//CS=1;
/**************延时n微秒***************/
void delaynus(unsigned char n,unsigned char i)
{
for(i=0;i<n;i++);
}
/**************写允许函数**************/
void wren(unsigned char enable,unsigned char i)
{
CS=0;
enable=0x06;
SCK=0;
delaynus(1,2);
for(i=0;i<8;i++)
{
SI=enable&0x80;
delaynus(1,2);
SCK=1;
enable<<=1;
delaynus(1,2);
SCK=0;
}
CS=1;
delaynus(1,5);
}
/****************写禁止函数***************/
/**void wrds(unsigned char dis,unsigned char i)
{
CS=0;
dis=0x04;
SCK=0;
delaynus(1,2);
for(i=0;i<8;i++)
{
SI=dis&0x80;
delaynus(1,2);
SCK=1;
dis<<=1;
delaynus(1,2);
SCK=0;
}
CS=1;
}
/****************写指令函数***************/
void wrin(unsigned char write,unsigned char i)
{
CS=0;
write=0x02;
SCK=0;
delaynus(1,2);
for(i=0;i<8;i++)
{
SI=write&0x80;
delaynus(1,2);
SCK=1;
write<<=1;
delaynus(1,2);
SCK=0;
}
}
/****************写地址函数***************/
void wrad(unsigned char adh,unsigned char adl,unsigned char i)
{
CS=0;
SCK=0;
delaynus(1,2);
for(i=0;i<8;i++)
{
SI=adh&0x80;
delaynus(1,2);
SCK=1;
adh<<=1;
delaynus(1,2);
SCK=0;
}
for(i=0;i<8;i++)
{
SI=adl&0x80;
delaynus(1,2);
SCK=1;
adl<<=1;
delaynus(1,2);
SCK=0;
}
}
/****************写数据函数***************/
void wrda(unsigned char i,unsigned char dataa)
{
CS=0;
SCK=0;
delaynus(1,2);
for(i=0;i<8;i++)
{
SI=(dataa&0x80);
delaynus(1,2);
SCK=1;
dataa=(dataa<<1);
delaynus(1,2);
SCK=0;
}
}
/****************读命令函数***************/
void rdin(unsigned char read,unsigned char i)
{
CS=0;
SCK=0;
delaynus(1,2);
read=0x03;
for(i=0;i<8;i++)
{
SI=read&0x80;
delaynus(1,2);
SCK=1;
read=(read<<=1);
delaynus(1,2);
SCK=0;
}
}
/****************读数据函数***************/
unsigned char rdda()
{
unsigned char i;
unsigned char dat=0;
delaynus(1,2);
SCK=0;
CS=0;
for(i=0;i<8;i++)
{
SCK=1;
dat<<=1;
if (SO==1)
dat|=0x01;
delaynus(1,2);
SCK=0;
delaynus(1,2);
}
CS=1;
return dat;
}
main()
{
CS=0;
wren(0x06,0x00);
wrin(0x02,0);
wrad(0x00,0x00,0);
wrda(0,0x80);
CS=1;
delaynus(1,20);
CS=0;
rdin(0x03,0);
wrad(0x00,0x00,0);
delaynus(1,2);
ACC=rdda();
P3=ACC;
CS=1;
}