#define ADDR24C02 0x50
#define R 1
#define W 0
sbit SCL=P3^4;
sbit SDA=P3^5;
sbit feleer=P3^3; //探针
struct dats
{
unsigned char dats[16];
};
unsigned char dats[2]="A";
struct dats Read_Dats(unsigned char addr_dive,unsigned char addr_word);
void Write_Dats(unsigned char addr_dive,unsigned char addr_word,unsigned char *dats);
void Start();
void Stop();
bit Addr_Dive(unsigned char addr_dive);
bit Addr_Word(unsigned char addr_word);
unsigned char Read();
void Write(unsigned char dat);
bit ACK();
void NACK();
void Delay();
void Feleer();
void main()
{
struct dats dats;
Init_IO();
Write_Dats(ADDR24C02,0x00,dats);
Delay();
Feleer(); //这里会闪
Write_Dats(ADDR24C02,0x01,dats);
Delay();
Feleer(); //这里不闪,运行不到这里
Read_Dats(ADDR24C02,0x00);
if(dats.dats[0]=='A')
{
......
}
while(1);
}
void Init_IO()
{
P3M1=0x30;
P3M0=0x30;
}
struct dats Read_Dats(unsigned char addr_dive,unsigned char addr_word)
{
struct dats dats;
bit ack;
unsigned char i;
unsigned char num=1;
Start();
do
{
ack=Addr_Dive(addr_dive<<1|W);
}
while(ack!=0);
do
{
ack=Addr_Word(addr_word);
}
while(ack!=0);
do
{
ack=Addr_Dive(addr_dive<<1|R);
}
while(ack!=0);
for(i=0;i<num;i++)
{
dats.dats[i]=Read();
}
NACK();
Stop();
return(dats);
}
void Write_Dats(unsigned char addr_dive,unsigned char addr_word,unsigned char *dats)
{
bit ack=0;
unsigned char *ptr=dats;
Start();
do
{
ack=Addr_Dive(addr_dive);
}
while(ack!=0);
do
{
ack=Addr_Dive(addr_word);
}
while(ack!=0);
while(*ptr!=0)
{
do
{
Write(*ptr);
ack=ACK();
}
while(ack!=0);
ptr++;
}
Stop();
}
void Start()
{
SDA=1;
Delay();
SCL=1;
Delay();
SDA=0;
Delay();
SCL=0;
}
void Stop()
{
SDA=0;
Delay();
SCL=1;
Delay();
SDA=1;
Delay();
SCL=0;
}
bit Addr_Dive(unsigned char addr_dive)
{
bit ack=0;
Write(addr_dive);
ack=ACK();
return(ack);
}
bit Addr_Word(unsigned char addr_word)
{
bit ack;
Write(addr_word);
ack=ACK();
return(ack);
}
unsigned char Read()
{
unsigned char i;
unsigned char dat=0;
SDA=1;
for(i=0;i<8;i++)
{
SCL=1;
Delay();
dat=(dat<<1)|SDA;
SCL=0;
}
return(dat);
}
void Write(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
if(dat&(0x80>>i))
{
SDA=1;
}
else
{
SDA=0;
}
Delay();
SCL=1;
Delay();
SCL=0;
}
}
bit ACK()
{
bit ack=0;
SDA=1;
Delay();
SCL=1;
Delay();
if(SDA==1)
{
ack=1;
}
SCL=0;
return(ack);
}
void NACK()
{
SDA=1;
Delay();
SCL=1;
Delay();
SCL=0;
Delay();
SDA=0;
}
void Delay()
{
;
}
void Feleer()
{
unsigned int i;
for(i=0;i<24000;i++)
{
if(i%6000==0)
{
feleer=~feleer;
}
}
}
这是我昨天写的IIC测试程序,不懂得怎么回事,同样的函数只能运行1次,写数据第一次后,再读或再写都不成功了。用的是STC15W104单片机:
只有本站会员才能查看附件,请 登录
哪位高手帮我看一下,问题出在哪里?谢谢!!!
[此贴子已经被作者于2020-4-4 14:33编辑过]