📄 p8574.c
字号:
#include <intrins.h>
#include <reg52.h>
sbit SCL=P3^7;
sbit SDA=P3^6;
void NOP(void);
void I2cStartBit(void);
void I2cStopBit(void);
void I2cSendAck(void);
void I2cSendNAck(void);
void I2cTestAck(void);
void I2cWriteByte(unsigned char OneByte);
unsigned char I2cReadByte(void);
void I2cWriteStringA(unsigned char slaw,unsigned char *Buffer,unsigned char Index);
void I2cWriteString(unsigned char slaw,unsigned char *Buffer,unsigned char Length);
void I2cReadString(unsigned char slar,unsigned char *Buffer,unsigned char Length);
void NOP(void)
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
void I2cStartBit(void) //start the i2c bus
{
SDA=1;
SCL=1;
NOP();
SDA=0;
NOP();
SCL=0;
}
void I2cStopBit(void) //stop the i2c bus
{
SDA=0;
SCL=1;
NOP();
SDA=1;
NOP();
SCL=0;
}
void I2cSendAck(void) //send the answer bit
{
SDA=0;
SCL=1;
NOP();
SCL=0;
SDA=1;
}
void I2cSendNAck(void) //send the not answer bit
{
SDA=1;
SCL=1;
NOP();
SCL=0;
SDA=0;
}
void I2cTestAck(void) //test the answer bit
{
SDA=1;
SCL=1;
F0=0;
if(SDA==1)
F0=1;
SCL=0;
NOP();
}
void I2cWriteByte(unsigned char OneByte) //send one byte to i2c bus
{
unsigned char i;
for(i=0;i<8;i++)
{
if((OneByte&0x80)>0)
{
SDA=1;
SCL=1;
NOP();
NOP();
NOP();
NOP();
SCL=0;
SDA=0;
}
else
{
SDA=0;
SCL=1;
NOP();
NOP();
NOP();
NOP();
SCL=0;
}
OneByte=OneByte<<1;
}
}
unsigned char I2cReadByte(void) //read one byte from i2c bus
{
unsigned char nn=0xff,mm=0x80,uu=0x7f;
unsigned char j;
for(j=0;j<8;j++)
{
SDA=1;
SCL=1;
if(SDA==0)
nn=(nn&uu);
else
nn=(nn|mm);
nn=_crol_(nn,1);
SCL=0;
}
return(nn);
}
void I2cWriteStringA(unsigned char slaw,unsigned char *Buffer,unsigned char Index)
{
do
{
I2cStartBit();
I2cWriteByte(slaw);
I2cTestAck();
}
while(F0==1);
I2cWriteByte(Buffer[Index]);
I2cTestAck();
}
void I2cWriteString(unsigned char slaw,unsigned char *Buffer,unsigned char Length) //send n bytes to i2c bus
{
unsigned char k;
do
{
I2cStartBit();
I2cWriteByte(slaw);
I2cTestAck();
}
while(F0==1);
for(k=0;k<Length;k++)
{
I2cWriteByte(Buffer[k]); //////////////??????????
I2cTestAck();
while(F0==1)
I2cWriteStringA(slaw,Buffer,k);
}
I2cStopBit();
}
void I2cReadString(unsigned char slar,unsigned char *Buffer,unsigned char Length) //read n bytes from i2c bus
{
unsigned char OneByte;
unsigned char i;
do
{
I2cStartBit();
I2cWriteByte(slar);
I2cTestAck();
}
while(F0==1);
for(i=0;i<Length-1;i++)
{
OneByte=I2cReadByte();
Buffer[i]=OneByte;
I2cSendAck();
}
OneByte=I2cReadByte();
Buffer[i]=OneByte;
I2cSendNAck();
I2cStopBit();
}
void main(void)
{
//unsigned char temp3;
unsigned char temp[2];
temp[0]=0x55;
temp[1]=0x55;
//PCF8574_Init();
while(1)
{
//temp3=IC_Read_Data();
I2cWriteString(0x40,temp,2);
//Delay();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -