利用定时器产生一个0~99秒变化的秒表,并且显示在数码管上,没过一秒将这个变化的数写入板上AT24C02内部。当关闭实验板电源,并再次打开实验板电源时,单片机先从AT24C02中将原来写入的数读取出来,接着此数继续变化并显示在数码管上。
- #include
- #define uchar unsigned char
- #define uint unsigned int
- bit write = 0;
- ***it sda = P0^1;
- ***it scl = P0^0;
- ***it wp = P0^2;
- ***it dula = P3^4;
- ***it wela = P3^5;
- 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()
- {
- sda = 1;
- delay();
- scl = 1;
- delay();
- sda = 0;
- delay();
- }
- void stop()
- {
- sda = 0;
- delay();
- scl = 1;
- delay();
- sda = 1;
- delay();
- }
- void response()
- {
- uchar i;
- scl = 1;
- delay();
- while((sda == 1) && (i<250)) i++;
- scl = 0;
- delay();
- }
- void init()
- {
- sda = 1;
- delay();
- scl = 1;
- delay();
- wp = 0;
- }
- void write_byte(uchar date)
- {
- 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()
- {
- 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(0xae);
- response();
- write_byte(address);
- response();
- write_byte(date);
- response();
- stop();
- }
- uchar read_add(uchar address)
- {
- uchar date;
- start();
- write_byte(0xae);
- response();
- write_byte(address);
- response();
- start();
- write_byte(0xaf);
- response();
- date = read_byte();
- stop();
- return date;
- }
- void display(uchar bai_c, uchar sh_c)
- {
- /* dula = 1;
- P1 = table[bai_c];
- dula = 0;
- P1 = 0xff;
- wela = 1;
- P1 = 0xfe;
- wela = 0;
- delay1ms(5);
-
- P1 = 0x00;
- dula = 1;
- dula = 0;
-
- dula = 1;
- P1 = table[sh_c];
- dula = 0;
- P1 = 0xff;
- wela = 1;
- P1 = 0xfd;
- wela = 0;
- delay1ms(5);
-
- P1 = 0x00;
- dula = 1;
- dula = 0;*/
-
- P1 = 0xff;
- wela = 1;
- P1 = 0xfe;
- wela = 0;
- P1 = 0x00;
- dula = 1;
- P1 = table[bai_c];
- dula = 0;
- delay1ms(5);
-
- P1 = 0x00;
- dula = 1;
- dula = 0;
-
- P1 = 0xff;
- wela = 1;
- P1 =0xfd;
- wela = 0;
- P1 = 0x00;
- dula = 1;
- P1 = table[sh_c];
- dula = 0;
- delay1ms(5);
-
- P1 = 0x00;
- dula = 1;
- dula = 0;
- }
- void main()
- {
- init();
- sec = read_add(2);
- if(sec>100) sec = 0;
- TMOD = 0x01;
- EA = 1;
- ET0 = 1;
- TH0 = 15536/256;
- TL0 = 15536%256;
- TR0 = 1;
- while(1)
- {
- display(sec/10, sec%10);
- if(write == 1)
- {
- write = 0;
- write_add(2, sec);
- }
- }
- }
- void t0() interrupt 1
- {
- TH0 = 15536/256;
- TL0 = 15536%256;
- tcnt++;
- if(tcnt == 20)
- {
- tcnt = 0;
- sec++;
- write = 1;
- if(sec == 100) sec = 0;
- }
- }
复制代码
|