#include"i2c.h"
#include <STC15F2K60S2.H>
#define uchar unsigned char
#define uint unsigned int
sbit scl=P0^4;
sbit sda=P0^5;
void delay10(uint x)
{
uchar i;
while(x--)
for(i=0;i<120;i++);
}
void Delay5us()
{
uchar n = 25;
while (n--)
{
_nop_();
_nop_();
}
}
/********************
*开始
***********************/
void start()
{
sda=1;
scl=1;
Delay5us();
sda=0;
Delay5us();
scl=0;
}
/*****************
*停止
**********************/
void stop()
{
sda=0;
scl=0;
Delay5us();
scl=1;
Delay5us();
sda=1;
}
//读取答应
/************************
*应答
*****************************/
void rack()
{
sda=1;
Delay5us();
scl=1;
Delay5us();
scl=0;
}
/**********************
*发送非答应信号
****************************/
void no_ack()
{
sda=1;
scl=1;
Delay5us();
scl=0;
sda=0;
}
/***************************
*向24c04中写一字节数据
******************************/
void write_a_byte(uchar b)
{
uchar i;
for(i=0;i<8;i++)
{
//b<<=1;sda=CY;_nop_();scl=1;nop4();scl=0;
sda=(bit)(b&0x80);
Delay5us();
scl=1;
Delay5us();
scl=0;
b<<=1;
}
rack();
}
/****************************
*向指定地址写数据
********************************/
void At24c02Write(uchar addr,uchar dat)
{
start();
rack();
write_a_byte(0xa0);
rack();
write_a_byte(addr);
rack();
write_a_byte(dat);
stop();
delay10(2);
}
/***************************************
*从24c04中读取一字节
****************************************/
uchar read_a_byte()
{
uchar i,b;
for(i=0;i<8;i++)
{
scl=1;
Delay5us();
b<<=1;
Delay5us();
b|=sda;
Delay5us();
scl=0;
}
return b;
}
/***********************************
*从当前地址读取数据
*************************************/
uchar read_current()
{
uchar d;
start();
write_a_byte(0xa1);
d=read_a_byte();
no_ack();
stop();
return d;
}
/****************************
*从任意地址读取数据
*********************************/
uchar random_read(uchar addr)
{
start();
rack();
write_a_byte(0xa0);
rack();
write_a_byte(addr);
rack();
return read_current();
}
评论0