#include <reg52.h>
#include <function.h>//详见第六章第8讲
#include <lcd.h> //详见第十一章第3讲
#include <intrins.h>
#define I2CDelay() {_nop_();_nop_();_nop_();_nop_();}
sbit I2C_SCL = P3^7;
sbit I2C_SDA = P3^6;
void I2CStart()
{
I2C_SDA = 1;
I2C_SCL = 1;
I2CDelay();
I2C_SDA = 0;
I2CDelay();
I2C_SCL = 0;
}
void I2CStop()
{
I2C_SCL = 0;
I2C_SDA = 0;
I2CDelay();
I2C_SCL = 1;
I2CDelay();
I2C_SDA = 1;
I2CDelay();
}
u8 I2CWrite(unsigned char dat)
{
u8 ack;
unsigned char mask;
for (mask=0x80; mask!=0; mask>>=1)
{
if ((mask&dat) == 0)
I2C_SDA = 0;
else
I2C_SDA = 1;
I2CDelay();
I2C_SCL = 1;
I2CDelay();
I2C_SCL = 0;
}
I2C_SDA = 1;
I2CDelay();
I2C_SCL = 1;
ack = I2C_SDA;
I2CDelay();
I2C_SCL = 0;
return (!ack);
}
unsigned char I2CReadNAK()
{
unsigned char mask;
unsigned char dat;
I2C_SDA = 1;
for (mask=0x80; mask!=0; mask>>=1)
{
I2CDelay();
I2C_SCL = 1;
if(I2C_SDA == 0)
dat &= ~mask;
else
dat |= mask;
I2CDelay();
I2C_SCL = 0;
}
I2C_SDA = 1;
I2CDelay();
I2C_SCL = 1;
I2CDelay();
I2C_SCL = 0;
return dat;
}
void main()
{
u8 str[2];
InitLcd1602();
while (1)
{
I2CStart();
I2CWrite(0x50<<1);
I2CWrite(0x55);
I2CWrite('G');
I2CStop();
delay_ms(1000);
I2CStart();
I2CWrite(0x50<<1);
I2CWrite(0x55);
I2CStart();
I2CWrite((0x50<<1)|0x01);
str[0] = I2CReadNAK();
I2CStop();
LcdShowStr_len(7, 0, str, 1);
while (1);
}
}