自己刚学i2c,用24c02c存储一个8位数据,然后读出来,灯亮表示正确读出数据,但就是灯不亮,里面有一些修改痕迹,求大神指出错误,指导一下
#include "config.h"
#define LED1CON 0x00000400
#define SDA 1<<3
#define SCL 1<<2
void DelayNS(unsigned char dly)//US延时
{
while(--dly)
{}
}
void init()
{
IO0SET=SDA;
DelayNS(5);
IO0SET=SCL;
DelayNS(5);
IO0CLR=SDA;
}
void start(void)
{
IO0SET = SDA;
DelayNS(1);
IO0SET = SCL;
DelayNS(5);
IO0CLR=SDA;
DelayNS(5);
IO0CLR = SCL;
DelayNS(2);
}
/*
void Ask(bit temp)
{
IO0SET=SDA;
IO0SET=SCL;
DelayNS(4);
IO0CLR=SCL;
}
*/
void stop(void)
{
IO0CLR=SDA;
IO0SET=SCL;
DelayNS(5);
IO0SET=SDA;
DelayNS(5);
// IO0CLR=SDA;
// IO0CLR=SCL;
}
void Write(unsigned char i)
{
unsigned char j;
for(j=0;j<8;j++)
{ if(i&0x80)
{IO0SET=SDA;}
else
{IO0CLR=SDA;}
DelayNS(1);
IO0SET=SCL;
i=i<<1;
DelayNS(1);
IO0CLR=SCL;
DelayNS(1);
}
IO0CLR=SDA;
DelayNS(2);
IO0SET=SCL;
DelayNS(3);
IO0CLR=SCL;
DelayNS(1);
}
unsigned char Read()
{
unsigned char k,t=0;
for(k=0;k<8;k++)
{
t=t<<1;
IO0SET=SDA;
IO0SET=SCL;
DelayNS(5);
if(SDA==1)
t=t|0x01;
else
t=t&0xfe;
IO0CLR=SCL;
DelayNS(5);
}
IO0CLR=SDA;
return t;
}
/*发送完一个字节后检验设备的应答信号****************
int Check(void)
{ int F0;
IO0SET=SDA;
IO0SET=SCL;
DelayNS(1);
F0=SDA;
DelayNS(1);
IO0CLR=SCL;
DelayNS(1);
if(F0==1)
return FALSE;
else
return TRUE;
}
****************************/
/*向24c02写?入数据*/
void WriteTo2402( unsigned char DataAdd ,unsigned char Data)
{
start();
Write(0xa0);
// while(!Check());
//Ask();
Write(DataAdd);
// while(!Check());
//Ask();
Write(Data);
// while(!Check());
// Ask();
stop();
}
unsigned char ReadTo2402( unsigned char DataAdd)
{ unsigned char buf;
start();
Write(0xa0);
//while(!Check());
//Ask();
Write(DataAdd);
// while(!Check());
//Ask();
start();
Write(0xa1);
// while(!Check());
//Ask();
buf=Read();
//while(Ask());
stop();
return(buf);
}
int main(void)
{
unsigned char y;
IO0DIR=SCL|SDA|LED1CON;
init();
WriteTo2402(0xff,0XAA);
y=ReadTo2402(0xff);
if(y==0Xaa)
{
IO0CLR=LED1CON;
}
else
{
IO0SET=LED1CON;
}
}
-
程序图
一周热门 更多>