MultiTimer is a software timer extension module that allows for the expansion of timer tasks as needed, replacing the traditional flag-checking method. It offers a more elegant and convenient way to manage the timing sequences of a program.
- Configure the system time base interface and install the timer driver:
uint64_tPlatformTicksGetFunc(void)
{
/* Platform-specific implementation */
}
multiTimerInstall(PlatformTicksGetFunc);- Instantiate a timer object:
MultiTimertimer1;- Set the timing, timeout callback function, user data pointer, and start the timer:
intmultiTimerStart(MultiTimer*timer, uint64_ttiming, MultiTimerCallback_tcallback, void*userData);- Call the timer background processing function in the main loop:
intmain(intargc, char*argv[])
{
...
while (1) {
...
multiTimerYield();
}
}The clock frequency of the timer directly affects its accuracy. It is recommended to use ticks with higher precision such as 1ms, 5ms, or 10ms.
The callback function of the timer should not perform time-consuming operations, as this may occupy too much time, causing other timers to not timeout properly.
Since the timer's callback function is executed within
multiTimerYield, care should be taken not to use too much stack space to avoid stack overflow.
The test_linux.c file serves as a demo for Linux platforms, showcasing how to use MultiTimer for creating and managing multiple timers with different intervals and behaviors.
#include"MultiTimer.h"#include<stdio.h>#include<unistd.h>#include<sys/time.h>// Platform-specific function to get current ticks (milliseconds)uint64_tgetPlatformTicks() {
structtimevalnow;
gettimeofday(&now, NULL);
returnnow.tv_sec*1000LL+now.tv_usec / 1000;
}
// Callback functions for the timersvoidtimerCallback1(MultiTimer*timer, void*userData) {
printf("Timer 1 fired at %lu ms\n", getPlatformTicks());
multiTimerStart(timer, 500, timerCallback1, NULL); // Restart timer
}
voidtimerCallback2(MultiTimer*timer, void*userData) {
printf("Timer 2 fired at %lu ms\n", getPlatformTicks());
multiTimerStart(timer, 1000, timerCallback2, NULL); // Restart timer
}
voidtimerCallback3(MultiTimer*timer, void*userData) {
printf("Timer 3 (one-shot) fired at %lu ms\n", getPlatformTicks());
}
voidtimerCallback4(MultiTimer*timer, void*userData) {
printf("Timer 4 is stopping Timer 1 at %lu ms\n", getPlatformTicks());
multiTimerStop((MultiTimer*)userData);
}
intmain() {
multiTimerInstall(getPlatformTicks);
MultiTimertimer1, timer2, timer3, timer4;
multiTimerStart(&timer1, 500, timerCallback1, NULL); // 500 ms repeatingmultiTimerStart(&timer2, 1000, timerCallback2, NULL); // 1000 ms repeatingmultiTimerStart(&timer3, 2000, timerCallback3, NULL); // 2000 ms one-shotmultiTimerStart(&timer4, 3000, timerCallback4, &timer1); // 3000 ms, stops timer1// Main loop to simulate time passage and process timerswhile (1) {
multiTimerYield();
usleep(1000); // Sleep for 1 ms
}
return0;
}