本帖最后由 yf15966844335 于 2018-11-11 00:02 编辑
- #include<reg52.h>
- #define uint unsigned int
- #define uchar unsigned char
- bit write=0;
- sbit sda=P2^0;
- sbit scl=P2^1;
- sbit dula=P2^6;
- sbit wela=P2^7;
- uchar sec,tcnt;
- uchar code table[]={
- 0x3f,0x06,0x5b,0x4f,0x66,0x6d,
- 0x7d,0x07,0x7f,0x6f,0x77,0x7c,
- 0x39,0x5e,0x79,0x71
- };
- void delay()
- {
- ;;
- }
- void delay1ms(uint z)
- {
- uint x,y;
- for(x=z;x>0;x--)
- for(y=110;y>0;y--);
- }
- void start()//kaishi
- {
- sda=1;
- delay();
- scl=1;
- delay();
- sda=0;
- delay();
- }
- void stop()//tingzhi
- {
- sda=0;
- delay();
- scl=0;
- delay();
- sda=1;
- delay();
- }
- void respons()//yingda
- {
- uchar i;
- scl=1;
- delay();
- while((sda==1)&&(i<250))i++;
- scl=0;
- delay();
- }
- void init()//chushihua
- {
- sda=1;
- delay();
- scl=1;
- delay();
- }
- void write_byte(uchar date)//xiezijie
- {
- uchar i,temp;
- temp=date;
- for(i=0;i<8;i++)
- {
- temp=temp<<1;
- scl=0;
- delay();
- sda=CY;
- delay();
- scl=1;
- delay();
- }
- scl=0;
- delay();
- sda=1;
- delay();
- }
- uchar read_byte()//duzijie
- {
- uchar i,k;
- scl=0;
- delay();
- sda=1;
- delay();
- for(i=0;i<8;i++)
- {
- scl=1;
- delay();
- k=(k<<1)|sda;
- scl=0;
- delay();
- }
- return k;
- }
- void write_add(uchar address,uchar date)
- {
- start();
- write_byte(0xa0);
- respons();
- write_byte(address);
- respons();
- write_byte(date);
- respons();
- stop();
- }
- uchar read_add(uchar address)
- {
- uchar date;
- start();
- write_byte(0xa0);
- respons();
- write_byte(address);
- respons();
- start();
- write_byte(0xa1);
- respons();
- date=read_byte();
- stop();
- return date;
- }
- void display(uchar bai_c,uchar sh_c)
- {
- dula=0;
- P0=table[bai_c];
- dula=1;
- dula=0;
- wela=0;
- P0=0xfe;
- wela=1;
- wela=0;
- delay1ms(5);
- dula=0;
- P0=table[sh_c];
- dula=1;
- dula=0;
- wela=0;
- P0=0xfd;
- wela=1;
- wela=0;
- delay1ms(5);
- }
- void main()
- {
- init();
- sec=read_add(2);
- if(sec>100)
- sec=0;
- TMOD=0x01;
- ET0=1;
- EA=1;
- TH0=(65536-50000)/256;
- TH1=(65536-50000)%256;
- TR0=1;
- while(1)
- {
- display(sec/10,sec%10);
- if(write==1)
- {
- write=0;
- write_add(2,sec);
- }
- }
- }
- void T0_time()interrupt 1
- {
- TH0=(65536-50000)/256;
- TH1=(65536-50000)%256;
- tcnt++;
- if(tcnt==20)
- {
- tcnt=0;
- sec++;
- write=1;
- if(sec==100)
- sec=0;
- }
- }
复制代码 以上就是AT24c02的读写小程序,要求是:利用定时器产生一个0~99秒变化的秒表,并且在数码管上显示,每过一秒将这个变化的数写入AT24c02内部。当关闭电源时,并再次打开电源,单片机先从AT24c02中读出原先显示数值,接着运行秒表。 代码写入后,1、数码管每次开机都显示“10”,一直运行到“99”,再从“0”,运行;且不能在断电时恢复数据;求解!!
2、uchar read_add(uchar address)中write_byte(address);作用是什么,为什么后面跟着开始?
求大神帮帮忙,小弟刚刚学习不久,最近对I2c比较感兴趣,再次谢谢了!
|