proteus仿真图
程序
#include <reg51.h> // ??8051?????
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit SCK=P2^0;
sbit SI=P2^1;
sbit SO=P2^2;
sbit CS=P2^3;
// ???SPI??????
void SPI_Init(void); // SPI???
void SPI_SendByte(unsigned char byte); // SPI??????
unsigned char SPI_ReceiveByte(void); // SPI??????
void SPI_CS_Low(void); // ??????
void SPI_CS_High(void); // ??????
unsigned char readData,readData1,readData2;
// 25LC040???
#define READ_INSTRUCTION 0x03 // ???(??25LC040,????????????)
#define WRITE_INSTRUCTION 0x02 // ???(??,??????????)
#define WREN_INSTRUCTION 0x06 // ?????
// ????
void EEPROM_WriteByte(unsigned char address, unsigned char date) {
SPI_CS_Low(); // ??????
SPI_SendByte(WREN_INSTRUCTION); // ???????
SPI_CS_High(); // ??????,???????(??????)
SPI_CS_Low(); // ????????
SPI_SendByte(WRITE_INSTRUCTION); // ?????
//SPI_SendByte((address >> 8) & 0xFF); // ???????(??25LC040,?????)
SPI_SendByte(address); // ???????
SPI_SendByte(date); // ????
SPI_CS_High(); // ??????,?????
// ???????????,?????EEPROM????
}
unsigned char EEPROM_ReadByte(unsigned char address) {
unsigned char date;
SPI_CS_Low(); // ??????
SPI_SendByte(READ_INSTRUCTION); // ?????
//SPI_SendByte((address >> 8) & 0xFF); // ???????(??25LC040,?????)
SPI_SendByte(address ); // ???????
date = SPI_ReceiveByte(); // ????
SPI_CS_High(); // ??????,?????
return date;
}
void EEPROM_ReadByte1(unsigned char address) {
unsigned char date;
SPI_CS_Low(); // ??????
SPI_SendByte(READ_INSTRUCTION); // ?????
//SPI_SendByte((address >> 8) & 0xFF); // ???????(??25LC040,?????)
SPI_SendByte(address ); // ???????
readData = SPI_ReceiveByte(); // ????
readData1 = SPI_ReceiveByte();
readData2 = SPI_ReceiveByte();
SPI_CS_High(); // ??????,?????
// return date;
}
void main(void) {
uint i;
SPI_Init(); // ???SPI??
// ??:?????EEPROM
EEPROM_WriteByte(0x00, 0xAB); // ???0x0000??0xAB
for(i=0;i<10000;i++);
EEPROM_WriteByte(0x01, 0x55); // ???0x0000??0xAB
for(i=0;i<10000;i++);
EEPROM_WriteByte(0x02, 0x66); // ???0x0000??0xAB
for(i=0;i<10000;i++);
// ??:?EEPROM????
EEPROM_ReadByte1(0); // ???0x0000????
P1= readData;
_nop_();
_nop_();
//readData1 = EEPROM_ReadByte(0x01); // ???0x0000????
P3= readData1;
_nop_();
_nop_();
//readData2 = EEPROM_ReadByte(0x02); // ???0x0000????
P0= readData2;
// ?????????????????
while (1) {
// ???
}
}
// ????????SPI???????
void SPI_Init(void) {
// ???SPI??,????????
}
void SPI_SendByte(unsigned char byte) {
// ??SPI??????
uchar i;
for(i=0;i<8;i++)
{
SCK=0;
_nop_();
_nop_();
if((byte&0x80)==0x80)
SI=1;
else
SI=0;
_nop_();
_nop_();
byte<<=1;
SCK=1;
_nop_();
_nop_();
}
}
unsigned char SPI_ReceiveByte(void) {
// ??SPI??????
uchar i,dat=0;
for(i;i<8;i++)
{
dat<<=1;
SCK=1; //第一位
_nop_();
_nop_();
SCK=0;
_nop_();
_nop_();
SO=1;
if(SO)
dat|=1;
_nop_();
_nop_();
}
return dat; // ??????????????
}
void SPI_CS_Low(void) {
// ???????
CS = 0; // ?????????P1.0??
}
void SPI_CS_High(void) {
// ???????
CS = 1; // ?????????P1.0??
}
只有第一次读的是对的。
请问高手,哪里错了?谢谢
|