我做一个软件时钟,要的结果是当板子断电时吧时钟存入EEProm 里,当上电时要读取EEprom的数据,继续断电前的时钟。
我的时钟程序做好,没有问题测试正常,我又写了一个IIC的驱动,我测试后也没有问题,EEPROM的数据可以正常读写, 但是我把iic程序加入时钟里面,程序运行就达不到我要的效果。
下面是iic 程序
#include
#include "delay.h"
#define uchar unsigned char
#define uint unsigned int
sbit scl=P2^1 ;
sbit sda=P2^0 ;
uchar shu,dat;
void start()
{
sda=1;
delay(5);
scl=1;
delay(5);
sda=0;
delay(5);
}
void stop()
{
sda=0;
delay(5);
scl=1;
delay(5);
sda=1;
delay(5);
}
void ask()
{
unsigned char i;
scl=1;
delay(5);
if(sda==1&&i<200) i++;
scl=0;
//delay(5)
}
void write_i2c(uchar date1)
{
uchar temp, x;
temp=date1;
for(x=0;x<8;x++)
{
scl=0;
temp=temp<<1;
sda=CY;
scl=1;
delay(5);
}
scl=0;
delay(5);
sda=1;
delay(5);
}
uchar read_i2c()
{
uchar m,dat;
scl=0;
delay(5);
sda=1;
delay(5);
for(m=0;m<8;m++)
{
scl=1;
delay(5);
dat=(dat<<1)|sda;
scl=0;
delay(5);
}
return dat;
}
void write_datei2c(unsigned char address,unsigned char date)
{
start();
write_i2c(0xa0);
ask();
write_i2c(address);
ask();
write_i2c(date);
ask();
stop();
}
uchar read_datei2c(uchar address)
{
start();
write_i2c(0xa0);
ask();
write_i2c(address);
ask();
start();
write_i2c(0xa1);
ask();
read_i2c();
stop();
shu=dat;
return shu;
}
下面是时钟程序的调用
void main()
{
init();
// write_sfm(5,30,20);
// delay(20);
shi=23;
fen=59;
miao=50;
shi=read_datei2c(0x20);
//fen=read_datei2c(0x21);
//miao=read_datei2c(0x22);
while(1)
{
delay(5);
if(t==20)
{
t=0;
miao++;
if(miao==60)
{
miao=0;
fen++;
if(fen==60)
{
fen=0;
shi++;
if(shi==24)
{
shi=0;
}
write_sfm(shi,fen,miao);
}
write_sfm(shi,fen, miao);
}
write_sfm(shi,fen,miao);
}
keyscan();
write_datei2c(0x20,shi);
// write_datei2c(0x21,fen);
// write_datei2c(0x22,miao);
naoling();
guannaozhong();
}
}
|