📄 51i2c.c
字号:
#include <reg51.h>
#include <At89x51.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
#define AddWr 0xa0 /*器件地址选择及写标志*/
#define AddRd 0xa1 /*器件地址选择及读标志*/
/*有关全局变量*/
sbit Scl=P2^1;
sbit Sda=P2^0;
//延时子程序
void mDelay(uchar j)
{ uint i;
for(;j>0;j--)
{ for(i=0;i<125;i--)
{;}
}
}
/*发送起始条件*/
void Start(void) /*起始条件*/
{
Sda=1;
Scl=1;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
Sda=0;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
}
void Stop(void) /*停止条件*/
{
Sda=0;
Scl=1;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
Sda=1;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
}
void Ack(void) /*应答位*/
{
Sda=0;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
Scl=1;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
Scl=0;
}
void NoAck(void) /*反向应答位*/
{
Sda=1;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
Scl=1;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
Scl=0;
}
void Send(uchar Data) /*发送数据子程序,Data为要求发送的数据*/
{
uchar BitCounter=8; /*位数控制*/
uchar temp; /*中间变量控制*/
do
{
temp=Data;
Scl=0;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
if((temp&0x80)==0x80)/* 如果最高位是1*/
Sda=1;
else
Sda=0;
Scl=1;
temp=Data<<1; /*RLC*/
Data=temp;
BitCounter--;
}while(BitCounter);
Scl=0;
}
uchar Read(void) /*读一个字节的数据,并返回该字节值*/
{
uchar temp=0;
uchar temp1=0;
uchar BitCounter=8;
Sda=1;
do{
Scl=0;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
Scl=1;
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
if(Sda) /*如果Sda=1;*/
temp=temp|0x01; /*temp的最低位置1*/
else
temp=temp&0xfe; /*否则temp的最低位清0*/
if(BitCounter-1)
{ temp1=temp<<1;
temp=temp1;
}
BitCounter--;
}while(BitCounter);
return(temp);
}
//=====发送单字节数据=====//
void WrToROM(uchar Data,uchar Address)
{
Start(); /*发送启动信号*/
Send(0xa0); /*发送SLA+W*/
Ack();
Send(Address); /*发送地址*/
Ack();
Send(Data);
Ack();
Stop();
mDelay(20);
}
//接收单字节数据
RdFromROM(uchar Data,uchar Address)
{
Start();
Send(0xa0);
Ack();
Send(Address);
Ack();
Start();
Send(0xa1);
Ack();
Data=Read();
Scl=0;
NoAck();
Stop();
return(Data);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -