單片機I2C驅(qū)動子程序
/*******************I2C模擬通信及AT24C02底層驅(qū)動程序****************/
/********************************************************************/
//AT24C02
//delayus: 延時約5us
void delayus()
{
;;
}
//i2c:init I2C總線初始化
void i2c_init()
{
SCL = 1;
delayus();
SDA = 1;
delayus();
}
//lcd:start 起始信號
void start()
{
SCL = 1;
SDA = 1;
delayus();
SDA = 0;
delayus();
}
//i2c:stop 停止信號
void stop()
{
SCL = 1;
SDA = 0;
delayus();
SDA = 1;
delayus();
}
//i2c:ack 從機應(yīng)答信號
void ack()
{
uchar i = 0;
//在SCL = 1時,讀取SDA的數(shù)據(jù)判忙
SCL = 1;
delayus();
while((SDA == 1)&& i < 250)
i++;
//判忙之后,等待發(fā)送數(shù)據(jù)/命令
SCL = 0;
delayus();
}
//nack: 主機非應(yīng)答信號
void nack()
{
//主機發(fā)送非應(yīng)答信號1
SCL = 1;
delayus();
SDA = 1;
delayus();
//等待發(fā)送數(shù)據(jù)/命令
SCL = 0;
delayus();
}
//write:byte 寫一個字節(jié)數(shù)據(jù)
void write_byte(uchar date)
{ //從最高位發(fā)送
uchar i, temp;
temp = date;
for(i = 0; i < 8; i++)
{
temp <<= 1;
SCL = 0;
delayus();
SDA = CY;
delayus();
SCL = 1;
delayus();
SCL = 0;
delayus();
}
//等待從機應(yīng)答
SCL = 0;
delayus();
SDA = 1;//置1,等待從機應(yīng)答0
delayus();
}
//read:byte 讀一個字節(jié)數(shù)據(jù)
uchar read_byte()
{
uchar i, j, k;
SCL = 0;
delayus();
for(i =0; i < 8; i++)
{
SCL = 1;
delayus();
j = SDA;
k = (k << 1) | j;
delayus();
SCL = 0;
delayus();
}
delayus();
return (k);
}
//write:AT24C02 寫AT24C02
void write_c02(uchar address, uchar date)
{
start();
write_byte(write_add);
ack();
write_byte(address);
ack();
write_byte(date);
ack();
stop();
delay(12);
}
//read:AT24C02 讀AT24C02
uchar read_c02(uchar add)
{
uchar date = 0;
start();
write_byte(write_add);
ack();
write_byte(add);
ack();
start();
write_byte(read_add);
ack();
date = read_byte();
nack();
return (date);
}
評論