Use the timer of the STC single-chip microcomputer to perform a scheduled task of 1 second, 1 minute, and 1 hour.
Because I use 11.0592 crystals, the time is not very accurate. If you have precise timing requirements, use a m crystal oscillator.
The Serial Output uses the printf function.
# Include "reg51.h"
# Include "stdio. H"
# Include "intrins. H" // _ NOP _()
Unsigned int tick;
Int HH, mm, SS; // hour: minute: Second
Char putchar (unsigned char I)
{
Es = 0; // serial disconnection
Ti = 0; // clear the serial port sending complete interrupt request flag
Sbuf = I;
While (Ti = 0); // wait until the sending is completed
Ti = 0; // clear the serial port sending complete interrupt request flag
Es = 1; // allow serial port interruption
Return sbuf;
}
Void task_1s ()
{
Printf ("s = [% d: % d] \ r \ n", HH, mm, SS );
}
Void task_1m ()
{
Printf ("m = [% d: % d] \ r \ n", HH, mm, SS );
}
Void task_1h ()
{
Printf ("H = [% d: % d] \ r \ n", HH, mm, SS );
}
// 0.1 Ms = 100us
Void timer0 (void) interrupt 1 using 1 // timer 0 interrupt Principle
{
Tr0 = 0;
Th0 = (65536-2000)/256;
Tl0 = (65536-2000) % 256;
Tick ++; // Count value + 1
If (tick> 999) // Add 10 times, that is, 1 second
{
Tick = 0;
SS ++;
If (SS> 59 ){
MM ++;
Ss = 0;
If (MM> 59 ){
HH ++;
Mm = 0;
If (HH> 11 ){
HH = 0;
}
Task_1h (); // 1 hour scheduled task
}
Task_1m (); // one-minute scheduled task
}
Task_1s (); // 1 s scheduled task
}
Tr0 = 1;
}
Void main ()
{
Scon = 0x50; // 0101,0000 8-bit variable baud rate, no parity bit
Tmod = 0x21;
Th1 = TL1 =-(11059200l/12/32/9600 );
Tr1 = 1;
Tick = 0;
HH = 0;
Mm = 0;
Ss = 0;
Th0 = (65536-2000)/256;
Tl0 = (65536-2000) % 256;
Tr0 = 1;
Et0 = 1;
Es = 1; // allow serial port interruption
Ea = 1; // total disconnection
Printf ("systemstart... \ r \ n ");
While (1)
{
_ NOP _();
}
}
Result After running
Code details:
(1) Serial Port baud rate calculation
Th1 = TL1 =-(11059200l/12/32/9600 );
The 11.0592 crystal oscillator is used, so here it is 11059200l
Because the 9600 baud rate is used to communicate with the computer, the 9600
(2) Why can I use the "printf" function for Serial Output?
For example: printf ("s = [% d: % d] \ r \ n", HH, mm, SS); can easily output the desired data
The reason is that you need to implement the underlying communication code of printf by yourself, that is, add
The prototype of this function is defined in # include "stdio. H". If you are interested, you can also implement other functions. In this way, the C51 programming can be similar to the C programming on the computer.
(3) Initial timer values:
Th0 = (65536-2000)/256; 8-bit high
Tl0 = (65536-2000) % 256; 8-bit low
(4) scheduled tasks
The task is called in the timer interrupt. For details, see the timer interrupt.
Void timer0 (void) interrupt 1 using 1 // timer 0 interrupt Principle
Hope to be useful to everyone! Errors are inevitable. You can debug them yourself ....
Haha!