// test4.c // 写一个从999999开始倒计时的秒表。并且改用定时器T1的中断来完成 // make a stopwatch that counts down from 999999. and use interrupt to finish it. #include "homework5.h" unsigned char LedBuff[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // buffer to store the seg chars. volatile unsigned char i = 0; // to current digit. volatile unsigned long display_time = 999999; // to store the time to display. unsigned int cnt = 0; // to count interrupt. // init timer void initTimer(void) { TMOD &= 0x0F; // clear TMOD. TMOD |= 0x10; // set TMOD to mode 1. TH1 = 0xFC; // 1ms timer. TL1 = 0x18; ET1 = 1; // enable timer 1 interrupt. EA = 1; // enable global interrupt. TR1 = 1; // start timer 1. } // timer1 interrupt service routine. void timer1ISR(void) interrupt 3 { TH1 = 0xFC; // reset timer. TL1 = 0x18; // display the number. set38Transistors(i); P2 = LedBuff[i]; i = (i + 1) % 6; // to switch to the next digit. // 1s timer. if (++cnt >= 1000) { // if reached 1s. cnt = 0; if (display_time > 0) { display_time--; // decrease the time. } } } void test4() { initTimer(); while (1) { // split the time into 6 digits. unsigned char first_digit = display_time / 100000; // to get the first digit. unsigned char second_digit = (display_time % 100000) / 10000; // to get the second digit. unsigned char third_digit = (display_time % 10000) / 1000; // to get the third digit. unsigned char fourth_digit = (display_time % 1000) / 100; // to get the fourth digit. unsigned char fifth_digit = (display_time % 100) / 10; // to get the fifth digit. unsigned char sixth_digit = display_time % 10; // to get the sixth digit. // load the number in the buffer. // 5 is high digit. // 0 is low digit. LedBuff[5] = LedChar[first_digit]; // to display the first digit. LedBuff[4] = LedChar[second_digit]; // to display the second digit. LedBuff[3] = LedChar[third_digit]; // to display the third digit. LedBuff[2] = LedChar[fourth_digit]; // to display the fourth digit. LedBuff[1] = LedChar[fifth_digit]; // to display the fifth digit. LedBuff[0] = LedChar[sixth_digit]; // to display the sixth digit. } } void main() { test4(); }