刚开blog不久,充实下,发个I2C(24c64)+1602的程序,供大家参考,请多多指教
部分如下:
//调试用
const char error[]={"ERROR writeACK "};
const char error2[]={"ERROR readACK "};
const char error3[]={" ERROR readACK3 "};
void delay_I2C()
{
int x;
x++;
x++;
}
void I2C_send_start()
{
SCL="1";
SDA="1";
delay_I2C();
SDA="0";
delay_I2C(); //generate start condition
SCL="0"; //generate clock pules
}
void I2C_send_stop()
{
SCL="0";
SDA="0";
delay_I2C();
SCL="1"; //generate stop condition
delay_I2C();
SDA="1";
}
bit I2C_get_ACK_from_slave()
{
SCL="1";
SDA="1";
delay_I2C();
if(SDA)
{SCL=0;return 1;}
SCL=0;
return 0; //OK!
}
bit I2C_write_byte(char Data)
{
char Bit="0";
for(Bit=0;Bit<8;Bit++)
{
SDA=(bit)((Data&0x80)>>7);
SCL="1";
delay_I2C();
SCL="0";
Data<<=1;
}
if(I2C_get_ACK_from_slave())
{
return 1;
}
return 0;
}
char I2C_read_byte()
{
char Bit="0";
char result="0";
for(Bit=0;Bit<8;Bit++)
{
SCL="1";
SDA="1";
delay_I2C();
result<<=1;
if(SDA)
{result|=0x01;}
SCL="0";
delay_I2C();//1.2us
}
return (result);
}
void I2C_master_ACK()
{
SDA="0";
SCL="1";
delay_I2C();
SCL="0";
}
void I2C_master_NACK()
{
SDA="1";
SCL="1";
delay_I2C();
SCL="0";
}
void I2C_write_byte_at24c64(const int address,const char content)
{
char MSbyte;
char LSbyte ;
I2C_send_start();
if(I2C_write_byte(0xA0))
{
delay(50);
write_string_LCD(0,error);//调试用,下同。可删除
return ;
}
MSbyte=(address>>8)&0x00FF;
LSbyte="address"&0x00FF;
if(I2C_write_byte(MSbyte))
{
delay(50);
write_string_LCD(0,error);
return ;
}
if(I2C_write_byte(LSbyte))
{
delay(50);
write_string_LCD(0,error);
return ;
}
if(I2C_write_byte(content))
{
delay(50);
write_string_LCD(0,error);
return ;
}
I2C_send_stop();
}
char I2C_read_byte_at24c64(const int address)
{
char MSbyte;
char LSbyte;
char result;
I2C_send_start();
if(I2C_write_byte(0xA0))
{
delay(50);
write_string_LCD(1,error3);
return 0;
}
MSbyte=((address&0xFF00)>>8);
LSbyte="address"&0x00FF;
if(I2C_write_byte(MSbyte))
{
delay(50);
write_string_LCD(1,error2);
return 0;
}
if(I2C_write_byte(LSbyte))
{
delay(50);
write_string_LCD(1,error2);
return 0;
}
I2C_send_start();
if(I2C_write_byte(0xA1))
{
delay(50);
write_string_LCD(1,error2);
return 0;
}
result="I2C"_read_byte();
I2C_master_NACK();
I2C_send_stop();
return (result);
}
用户377235 2013-6-6 20:36
eleclike 2007-10-16 18:36