51单片机ds1302与iic结合使用的代码用c语言写
时间: 2023-11-22 07:53:24 浏览: 33
以下是51单片机DS1302与IIC结合使用的代码,使用C语言编写:
```c
#include <reg51.h> //头文件
#define uchar unsigned char
#define uint unsigned int
//定义DS1302的控制信号端口
sbit SCLK = P3^6; //时钟
sbit RST = P3^5; //复位
sbit IO = P3^4; //数据
//定义IIC总线的控制信号端口
sbit SDA = P1^1; //数据
sbit SCL = P1^0; //时钟
//DS1302读写时的地址字节
uchar code SecAdd = 0x80; //秒
uchar code MinAdd = 0x82; //分
uchar code HourAdd = 0x84; //时
uchar code DateAdd = 0x86; //日
uchar code MonthAdd = 0x88; //月
uchar code WeekAdd = 0x8A; //周
uchar code YearAdd = 0x8C; //年
void Delay(unsigned int t) //延时函数
{
unsigned int i;
while (t--)
{
for (i = 0; i < 100; i++);
}
}
void IIC_Start() //启动IIC总线
{
SDA = 1;
SCL = 1;
Delay(1);
SDA = 0;
Delay(1);
SCL = 0;
}
void IIC_Stop() //停止IIC总线
{
SDA = 0;
SCL = 1;
Delay(1);
SDA = 1;
}
void IIC_SendByte(uchar dat) //发送1字节数据
{
uchar i;
for (i = 0; i < 8; i++)
{
SDA = dat & 0x80;
dat <<= 1;
SCL = 1;
Delay(1);
SCL = 0;
Delay(1);
}
SDA = 1;
SCL = 1;
Delay(1);
SCL = 0;
}
uchar IIC_ReadByte() //读取1字节数据
{
uchar i, dat = 0;
SDA = 1;
for (i = 0; i < 8; i++)
{
SCL = 1;
Delay(1);
dat = (dat << 1) | SDA;
SCL = 0;
Delay(1);
}
return dat;
}
void DS1302_WriteByte(uchar addr, uchar dat) //向DS1302写入1字节数据
{
uchar i;
RST = 1;
SCLK = 0;
RST = 0;
IIC_Start();
IIC_SendByte(addr);
Delay(1);
for (i = 0; i < 8; i++)
{
SDA = dat & 0x01;
dat >>= 1;
SCLK = 1;
Delay(1);
SCLK = 0;
Delay(1);
}
IIC_Stop();
RST = 1;
SCLK = 1;
}
uchar DS1302_ReadByte(uchar addr) //从DS1302读取1字节数据
{
uchar i, dat = 0;
RST = 1;
SCLK = 0;
RST = 0;
IIC_Start();
IIC_SendByte(addr | 0x01);
Delay(1);
for (i = 0; i < 8; i++)
{
dat >>= 1;
if (SDA == 1)
{
dat |= 0x80;
}
SCLK = 1;
Delay(1);
SCLK = 0;
Delay(1);
}
IIC_Stop();
RST = 1;
SCLK = 1;
return dat;
}
void Init_DS1302() //DS1302初始化
{
DS1302_WriteByte(0x8e, 0x00); //禁止写保护
DS1302_WriteByte(0x80, 0x00); //秒归零
DS1302_WriteByte(0x82, 0x00); //分归零
DS1302_WriteByte(0x84, 0x12); //时设为12
DS1302_WriteByte(0x86, 0x01); //日设为1
DS1302_WriteByte(0x88, 0x01); //月设为1
DS1302_WriteByte(0x8a, 0x01); //周设为1
DS1302_WriteByte(0x8c, 0x21); //年设为21
DS1302_WriteByte(0x8e, 0x80); //开启写保护
}
void main() //主函数
{
uchar sec, min, hour, date, month, week, year; //定义时间变量
Init_DS1302(); //DS1302初始化
while (1)
{
sec = DS1302_ReadByte(SecAdd); //读取秒
min = DS1302_ReadByte(MinAdd); //读取分
hour = DS1302_ReadByte(HourAdd); //读取时
date = DS1302_ReadByte(DateAdd); //读取日
month = DS1302_ReadByte(MonthAdd); //读取月
week = DS1302_ReadByte(WeekAdd); //读取周
year = DS1302_ReadByte(YearAdd); //读取年
printf("20%d-%02d-%02d %02d:%02d:%02d\n", year, month, date, hour, min, sec); //在串口上输出时间
Delay(1000); //延时1秒
}
}
```
以上代码中,IIC_Start()、IIC_Stop()、IIC_SendByte()、IIC_ReadByte()函数是IIC总线的控制函数;DS1302_WriteByte()、DS1302_ReadByte()、Init_DS1302()函数是DS1302控制函数;main()函数中使用这些函数读取DS1302的时间,并在串口上输出。