📄 i2c.h
字号:
//==========I2C时序==========
void delay(unsigned int i)//延时程序
{
for(;i>0;i--);
}
void I2C_start()//I2C起始函数
{
DDRC |= 0x30;//SDA,SCL设置为输出
SDA_PORT4 |= BIT(4);
delay(6);
SCL_PORT5 |= BIT(5);
delay(6);
SDA_PORT4 &= ~BIT(4);
delay(6);
SCL_PORT5 &= ~BIT(5);
delay(6);
}
void I2C_stop() //I2C停止函数
{
DDRC |= 0x30; //SDA,SCL设置为输出
SDA_PORT4 &= ~BIT(4);
delay(6);
SCL_PORT5 |= BIT(5);
delay(6);
SDA_PORT4 |= BIT(4);
delay(6);
SCL_PORT5 &= ~BIT(5);
delay(6);
}
void noAck() //I2C读数据,无作答
{
DDRC |= BIT(4);
DDRC |= BIT(5);
//SDA_PORT4 &= ~BIT(4); //不变化
SDA_PORT4 |= BIT(4);
delay(6);
SCL_PORT5 |= BIT(5);
delay(6);
SCL_PORT5 &= ~BIT(5);
delay(6);
}
uchar test_ack()//I2C检测应答
{
uchar testnum = 20;
DDRC |= BIT(5); //scl为输出
DDRC &= ~BIT(4); //sda为输入
delay(6);
SCL_PORT5 |= BIT(5);
delay(6);
while((PINC & 0x10))
{
testnum--;
if(!testnum)
{
I2C_stop();
return(0);
}
}
SCL_PORT5 &= ~BIT(5);
delay(6);
return(1);
}
//写数据(一个字节)时序
void writeByte(uchar wbyte)
{
uchar temp,i;
DDRC |= BIT(4); //scl为输出
DDRC |= BIT(5); //sda为输出
for(i=8;i>0;i--)
{
temp = wbyte & 0x80;
if(temp)
SDA_PORT4 |= BIT(4);
else
SDA_PORT4 &= ~BIT(4);
delay(6);
SCL_PORT5 |= BIT(5);
delay(6);
SCL_PORT5 &= ~BIT(5);
delay(6);
wbyte = wbyte << 1;
}
}
void writedata(uchar address,uchar wdata) //向I2C写数据
{
I2C_start();
writeByte(0xA2);
//test_ack(); //单个
writeByte(address);
//test_ack();
writeByte(wdata);
//test_ack();
I2C_stop();
}
//读数据(一个字节)时序
uchar readByte()
{
uchar i,rbyte,temp;
DDRC |= BIT(5); //SCL输出,SDA输入
DDRC &= ~BIT(4);
for(i=8;i>0;i--)
{
SCL_PORT5 |= BIT(5);
delay(6);
delay(6);
if((PINC & 0x10))
temp = 1;
else
temp = 0;
rbyte = rbyte << 1;
rbyte = rbyte | temp;
delay(6);
delay(6);
SCL_PORT5 &= ~BIT(5);
delay(6);
delay(6);
}
return (rbyte);
}
uchar readdata(uchar address) //从I2C苡片中读数据
{
uchar temp;
I2C_start();
writeByte(0xA2);
test_ack();
writeByte(address);
test_ack();
I2C_start();
writeByte(0xA3);
test_ack();
temp = readByte();
noAck();
I2C_stop();
return (temp);
}
void pfc8563_init() //I2C苡片初始化
{
writedata(0x00,0x00);
writedata(0x01,0x12);
//writedata(0x00,0x20);
}
uchar pfc8563_read(uchar address,uchar var)//=I2C时序
{
uchar temp,rdata;
temp = readdata(address);
temp = temp & var;
rdata = temp & 0x0f;
rdata = rdata + ((temp>>4)*10);
return (rdata);
}
void pfc8563_write(uchar address,uchar wtime)
{
uchar temp1,temp2;
temp1 = wtime / 10;
temp1 = temp1 << 4;
temp2 = wtime % 10;
temp1 = temp1 | temp2;
writedata(address, temp1);
}
//==========I2C时序==========
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -