端口设置:
sbit sda = P3^7;
sbit scl = P3^6;
端口配置:
void Port_IO_Init()
{
SFRPAGE = CONFIG_PAGE;
XBR0 = 0x14; //配置UART0 (TX0-P0^0,RX0-P0^1) UART1 (TX1-P0^2,RX1-P0^3)
XBR1 = 0X20; //PCA(CEX0-P0^4,CEX0-P0^5),定时器2(T2-P0^6),定时器4(T4-P0^7)
XBR2 = 0x4C; //定时器4 (T4EX-P0^5),交叉开关使能
P2MDOUT = 0x7f;
P3MDOUT = 0X3f;
P0MDOUT = 0Xff;
P6 = 0XFF;
P5 = 0XFF;
P4 = 0XFF;
I2C的相关操作:
void init()
{
sda = 1;
delay_nus(5);
scl = 1;
delay_nus(5);
}
void start()
{
scl = 0;
delay_1us();
sda = 1;
delay_1us();
scl = 1;
delay_nus(5);
sda = 0;
delay_nus(5);
}
void stop()
{
scl = 0;
delay_1us();
sda = 0;
delay_nus(5);
scl = 1;
delay_nus(5);
sda = 1;
delay_nus(5);
}
void respons()
{
scl = 0;
delay_nus(5);
sda = 0;
delay_nus(5);
scl = 1;
delay_nus(5);
scl = 0;
delay_nus(5);
sda = 1;
}
void write_byte(unsigned char date)
{
unsigned char i,temp;
temp = date;
for(i=0;i<8;i++)
{
temp = temp<<1;
scl = 0;
delay_nus(5);
sda = CY;
delay_nus(5);
scl = 1;
delay_nus(5);
}
scl = 0;
delay_nus(5);
sda = 1;
scl = 1;
delay_nus(5);
}
unsigned char read_byte()
{
unsigned char i,k;
for(i=0;i<8;i++)
{
scl = 0;
delay_nus(5);
k =(k<<1)|sda;
scl = 1;
delay_nus(5);
}
return k;
}
void write_add(unsigned char address,unsigned char date)
{
start();
write_byte(0xa0);
respons();
write_byte(address);
respons();
write_byte(date);
respons();
stop();
}
unsigned char read_add(unsigned char address)
{
unsigned char date;
start();
write_byte(0xa0);
respons();
write_byte(address);
respons();
start();
write_byte(0xa1);
respons();
date = read_byte();
stop();
return date;
}
我在主程序运行开始 读取at24c02 page = read_add(2);
在某一处往地址2里写数据: write_add(2,page); //往AT24C02写数据现在 读取的值都是FF
这是怎么回事啊 |