主设备:msp430F149 从设备24C256 上拉10K
程序从可用C51移植过来,调试N长时间就是检测不到ACK把SDA拉低。 求大侠看看。
void IICStart(void)
{
IIC_SDA_OUT;
IIC_SCL_OUT;
IIC_SCL_1;
Delay_us(Delay_Time);
IIC_SDA_1;
Delay_us(Delay_Time);
IIC_SDA_0;
Delay_us(Delay_Time);
IIC_SCL_0;
}
void IICStop(void)
{
IIC_SDA_OUT;
IIC_SCL_OUT;
IIC_SDA_0;
Delay_us(Delay_Time);
IIC_SCL_1;
Delay_us(Delay_Time);
IIC_SDA_1;
}
void IICNACK(void)
{
IIC_SDA_OUT;
IIC_SCL_OUT;
IIC_SDA_1;
Delay_us(Delay_Time);
IIC_SCL_1;
Delay_us(Delay_Time);
IIC_SCL_0;
Delay_us(Delay_Time); //NACK
}
void IICWrite(unsigned char Datasend)
{
unsigned int i;
IIC_SDA_OUT;
IIC_SCL_OUT;
for(i=0;i<8;i++)
{
if(Datasend&0x80)
IIC_SDA_1;
else
IIC_SDA_0;
Delay_us(Delay_Time);
IIC_SCL_1;
Delay_us(Delay_Time);
IIC_SCL_0;
Delay_us(Delay_Time);
Datasend <<= 1;
}
/*IIC_SDA_1; //可以试试直接IIC_SDA_0;Delay_us(Delay_Time);下面3句不用 相当于ACK
Delay_us(Delay_Time);
IIC_SDA_IN; //1
i = 100; //2
while((IIC_SDA_VAL) && (i>0)) i--; //3
IIC_SCL_1;
Delay_us(Delay_Time);
IIC_SCL_0;
Delay_us(Delay_Time);*/
IIC_SCL_1; //以下ACK检测
Delay_us(Delay_Time);
IIC_SDA_IN;
while(IIC_SDA_VAL);
IIC_SDA_OUT;
IIC_SCL_0;
Delay_us(Delay_Time);
}
unsigned char IICRead()
{
unsigned char i;
unsigned char temp = 0;
unsigned char Databit;
IIC_SDA_IN;
IIC_SCL_OUT;
for(i=0;i<8;i++)
{
Databit = IIC_SDA_VAL;
Delay_us(Delay_Time);
temp = (temp << 1) + Databit;
IIC_SCL_1;
Delay_us(Delay_Time);
IIC_SCL_0;
Delay_us(Delay_Time);
}
return(temp);
}
unsigned char ReadByte(unsigned int addr,unsigned char a) //a = 0 写X1227; a = 1 写 24C256; a = 2 写PCA9554A
{
unsigned char temp;
IICStart();
if(a==0) IICWrite(0xde);
else if(a==1) IICWrite(0xa0); //调试先写0xae 256写0xa0
else if(a==2) IICWrite(0x70);
if((a==0)||(a==1))
{
temp=(unsigned char)(addr>>8);
IICWrite(temp);
temp=(unsigned char)(addr&0xff);
IICWrite(temp);
}
else if(a==2)
{
temp = (unsigned char)(addr&0xFF);
IICWrite(temp);
}
IICStart();
if(a==0) IICWrite(0xdf);
else if(a==1) IICWrite(0xa1);//调试先写0xaf 256写0xa1
else if(a==2) IICWrite(0x71);
temp=IICRead();
//IICNACK();//也可以不发NACK 直接发停止
IICStop();
return(temp);
}
void WriteByte(unsigned int addr,unsigned char writedata,unsigned char a)
{
unsigned char temp;
IICStart();
if(a==0) IICWrite(0xde);
else if(a==1)IICWrite(0xa0);//调试先写0xae 256写0xa0
else if(a==2)IICWrite(0x70);
if((a==0)||(a==1))
{
temp=(unsigned char)(addr>>8);
IICWrite(temp);
temp=(unsigned char)(addr&0xff);
IICWrite(temp);
IICWrite(writedata);
}
else if(a==2)
{
temp=(unsigned char)(addr&0xff);
IICWrite(temp);
IICWrite(writedata);
}
IICStop();
// Delay_ms(10); //等待写周期
} |