#include <reg51.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
#define srl_W 0xae
#define srl_R 0xaf
sbit SCL=P2^0;
sbit SDL=P2^1;
sbit warn=P2^5;
void delay(uint x)
{ for(;x>0;x--) _nop_;
}
//開始
void iic_start()
{ SDL=1;
delay(2);
SCL=1;
delay(5);
SDL=0;
delay(5);
}
void iic_stop()
{ SDL=0;
delay(2);
SCL=1;
delay(5);
SDL=1;
delay(5);
}
void receive_ack()
{ uchar ACK;
uint j;
j=0;
SDL=1;
SCL=1;
while((SDL==1) && j<150) j++;
ACK=SDL;
delay(3);
SCL=0;
if(ACK) warn=1;
}
void input_noack()
{ SCL=0;
delay(2);
SDL=1;
SCL=1;
delay(5);
}
void write_data(uchar str)
{ uint i,j;
uchar temp;
temp=str;
SCL=0;
delay(2);
for(i=0;i<8;i++)
{if((temp<<i) & 0x80) SDL=1;
// {if((temp>>i) & 0x01) SDL=1;
else SDL=0;
delay(3);
SCL=1;
delay(5);
SCL=0;
delay(2);
}
}
uchar read_data()
{ uchar str_data;
uint i,j;
SCL=0;
delay(5);
for(i=0;i<8;i++)
{ SCL=1;
delay(3);
if(SDL==1) str_data |= 1 << i;
else str_data &= ~(1 << i);
delay(2);
SCL=0;
delay(5);
}
return str_data;
}
void iic_init()
{ SCL=1;
delay(5);
SDL=1;
delay(5);
}
void write_str(uchar dress_data,uchar str_data)
{ iic_start();
write_data(srl_W);
receive_ack();
write_data(dress_data);
receive_ack();
write_data(str_data);
receive_ack();
iic_stop();
}
uchar read_str(uchar data_dress)
{ uchar data_str;
iic_start();
write_data(srl_W);
receive_ack();
write_data(data_dress);
receive_ack();
iic_start();
write_data(srl_R);
receive_ack();
data_str = read_data();
input_noack();
iic_stop();
return data_str;
}
void main()
{ iic_init();
write_str(0x05,0xaa);
delay(500);
delay(500);
P1 = read_str(0x05);
}
程序調試通過了,但是有一點不懂的地方:
1、{if((temp<<i) & 0x80) SDL=1;
2、{if((temp>>i) & 0x01) SDL=1;
上面的1條是程序里有的,執行沒有問題,2條是我注釋掉的語句,如果把2條換成1條,寫的全是11111111。
我不太理解,1條應該是先發高位,在發地位。2條應該是先發低位,再發高位。
雖然說IIC是先發高位,再發低位。但是就程序本身來說只是把數據高低位搞反了,不會存在寫讀錯誤的情況。
|