#define I2C_CTRL_SCL TRISD7
#define I2C_CTRL_SDA TRISD6
#define I2C_LINE_SCL RD7
#define I2C_LINE_SDA RD6
//#define SCL 7
//#define SDA 6
//#define setbit(var, bit) ((var) |= (1 << (bit)))
//#define clrbit(var, bit) ((var) &= ~(1 << (bit)))
void I2C_Start(void)
{
I2C_CTRL_SDA=1;
I2C_Delay(5);
if(I2C_LINE_SDA!=1) LED=0; //return 0; 错误,绿灯亮 LED=0
I2C_CTRL_SCL=1;
I2C_Delay(5);
if(I2C_LINE_SCL!=1) LED1=0; //return 0; 错误,红灯亮 LED1=0
I2C_CTRL_SDA=0;
I2C_Delay(5);
I2C_CTRL_SCL=0;
// return 1;
}
void I2C_Stop(void)
{
I2C_CTRL_SDA=0;
I2C_CTRL_SCL=1;
I2C_Delay(5);
if(I2C_LINE_SCL!=1) LED1=0; //return 0; 错误,红灯亮 LED1=0
I2C_CTRL_SDA=1;
I2C_Delay(5);
if(I2C_LINE_SDA!=1) LED=0; //return 0; 错误,绿灯亮 LED=0
// return 1;
}
void I2C_Restart(void)
{
I2C_CTRL_SCL=0;
I2C_CTRL_SDA=1;
I2C_Delay(1);
I2C_CTRL_SCL=1;
I2C_Delay(1);
I2C_CTRL_SDA=0;
I2C_Delay(1);
I2C_CTRL_SCL=0;
}
void I2C_Ack(void)
{
I2C_CTRL_SDA=0;
I2C_CTRL_SCL=1;
I2C_Delay(1);
I2C_CTRL_SCL=0;
}
void I2C_Nack(void)
{
I2C_CTRL_SDA=1;
I2C_CTRL_SCL=1;
I2C_Delay(1);
I2C_CTRL_SCL=0;
}
void I2C_ByteOut(uchar dat)
{
asm("clrwdt");
uchar i;
for(i=0;i<8;i++)
{
if(dat&0x80==0x80) I2C_CTRL_SDA=1;
else I2C_CTRL_SDA=0; //在51中就可以写I2C_CTRL_SDA=dat&0x80;
I2C_Delay(5);
dat<<=1;
I2C_CTRL_SCL=1;
I2C_Delay(5);
I2C_CTRL_SCL=0;
}
I2C_Delay(5);
I2C_CTRL_SDA=1;
I2C_CTRL_SCL=1;
I2C_Delay(5);
if(I2C_LINE_SDA==1)LED2=1; //应答错误,绿灯亮
else LED2=0;
I2C_CTRL_SCL=0;
}
uchar I2C_ByteIn(void)
{
uchar I2C_buff=0,i;
I2C_CTRL_SDA=1;
for(i=0;i<8;i++)
{
I2C_buff<<=1;
I2C_Delay(1);
I2C_CTRL_SCL=1;
if(I2C_LINE_SDA==1) I2C_buff|=0x01;
I2C_Delay(1);
I2C_CTRL_SCL=0;
}
return I2C_buff;
}
说什么都写不进去数据,而且在对应答信号的检测时,那个LED3不亮,没有应答信号,有问题,请张工赐教! |