正好我小孩给51写了一个DS3231的头文件,你看看READ和WRITE 两个函数,就明白IIC通讯过程了,不过写的风格不好,看样子是半抄半写的。
#ifndef _DS3231_H_
#define _DS3231_H_
sbit DS3231_SDA=P0^5;
sbit DS3231_SCL=P0^6;
sbit DS3231_SQW=P0^7;
bit ack;
#define DS3231_Write 0xD0
#define DS3231_Read 0xD1
#define DS3231_SECOND 0x00
#define DS3231_MINUTE 0x01
#define DS3231_HOUR 0x02
#define DS3231_WEEK 0x03
#define DS3231_DAY 0x04
#define DS3231_MONTH 0x05
#define DS3231_YEAR 0x06
#define DS3231_CONTROL 0x0E //控制寄存器
#define DS3231_STATUS 0x0F //状态寄存器
#define DS3231_TEMPERATUREH 0x11 //温度高字节
#define DS3231_TEMPERATUREL 0x12 //温度低字节
void delay(uint us)
{
while (us--);
}
void Start_I2C()
{
DS3231_SDA=1;
delay(1);
DS3231_SCL=1;
delay(5);
DS3231_SDA=0;
delay(5);
DS3231_SCL=0;
delay(2);
}
void Stop_I2C()
{
DS3231_SDA=0;
delay(1);
DS3231_SCL=1;
delay(5);
DS3231_SDA=1;
delay(4);
}
void SendByte(uchar c)
{
uchar i;
for(i=0;i<8;i++)
{
if((c<<i)&0x80)
DS3231_SDA=1; //判断发送位
else
DS3231_SDA=0;
delay(1);
DS3231_SCL=1; //置高,通知接收数据位
delay(5);
DS3231_SCL=0;
}
delay(2);
DS3231_SDA=1; //释放总线,接收应答信号
delay(2);
DS3231_SCL=1;
delay(3);
//我写的
if (DS3231_SDA==1)
ack=0;
else
ack=1; //是否接到应答信号
DS3231_SCL=0;
delay(2);
}
uchar RcvByte()
{
uchar n=0;
uchar i,retc=0;
DS3231_SDA=1; //设为输入方式
for(i=0;i<8;i++)
{
delay(1);
DS3231_SCL=0; //置低,准备接收数据
delay(5);
DS3231_SCL=1; //使数据有效
delay(3);
retc<<=1;
if(DS3231_SDA==1)
retc+=1;
delay(2);
}
DS3231_SCL=0;
delay(2);
return(retc);
}
//我写的
void Ack_I2C(bit a)
{
if (a==0)
DS3231_SDA=0; //应答或非应答信号
else
DS3231_SDA=1;
delay(3);
DS3231_SCL=1;
delay(5);
DS3231_SCL=0;
delay(2);
}
uchar write1(uchar addr,uchar write_data)
{
Start_I2C();
SendByte(DS3231_Write);
if (!ack)
{
return 0;
}
delay(1);
SendByte(addr);
if (!ack)
{
return 0;
}
delay(1);
SendByte(write_data);
if (!ack)
{
return 0;
}
Stop_I2C();
delay(10);
return 1;
}
uchar read1()
{
uchar read_data;
Start_I2C();
SendByte(DS3231_Read);
if (!ack)
{
return 0;
}
delay(1);
read_data = RcvByte();
if (!ack)
{
return 0;
}
Ack_I2C(1);
Stop_I2C();
return read_data;
}
uchar read2(uchar add)
{
Start_I2C();
SendByte(DS3231_Write);
if (!ack)
{
return 0;
}
delay(1);
SendByte(add);
if (!ack)
{
return 0;
}
return(read1());
}
#endif
|