您的位置:首页 > 其它

C51 GPIO口模拟IIC读写24CXX

2017-08-08 22:25 639 查看
#include <reg52.h>
#define delayNOP() {_nop_(); _nop_(); _nop_(); _nop_();}

//IIC 开始信号
void iic_start(void)
{
SDA = 1;
SCL = 1;
delayNOP();
SDA = 0;
delayNOP();
SCL = 0;
}
//IIC 停止信号
void iic_stop(void)
{
SDA = 0;
delayNOP();
SCL = 1;
delayNOP();
SDA = 1;
}

//IIC 写字节
bit iic_write(u8 dat)
{
bit ack;
int i=0;
SCL = 0;
for(i=0; i<8; i++)
{
SDA = (bit)((dat<<i)& 0x80);
_nop_();
SCL = 1;
delayNOP();
SCL = 0;
}
SDA = 1;//释放SDA
delayNOP();
SCL = 1;
delayNOP();
ack = SDA;  //读取应答位 从器件应答
SCL = 0;
return ack;
}

//IIC读字节
u8 iic_read(void)
{
u8 i, read_dat=0;
for (i=0; i<8; i++)
{
SCL = 1;
read_dat <<= 1;
read_dat |= SDA;
SCL = 0;
}
return read_dat;
}

void write_byte(u8 addr, u8 dat)
{
iic_start();
iic_write(0xa0);
iic_write(0x00);  //20C64  双地址 H L
iic_write(addr);
iic_write(dat);
iic_stop();
mdelay(10);
}

u8 read_byte(u8 addr)
{
u8 dat;
iic_start();
iic_write(0xa0);
iic_write(0x00); //20C64  双地址 H L
iic_write(addr);
iic_start();
iic_write(0xa1);
dat = iic_read();
iic_stop();
return dat;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: