STM8 library for system clock and timing

Back to STM8 libraries home page.

Here is my library for maintaining a system clock. It uses TIMER4 and provides millisecond and 1/10 second callbacks. The millisecond callback is very handy for polling keypads and the 1/10 second callback is useful for keeping various timer variables. The callbacks happen in interrupt context, so your callbacks should be as brief as possible. There won't be any race conditions with other interrupts, but you still need to consider races with user space, such as loading or updating variables. Using a MUTEX flag and an "unposted update" variable might avoid races.

clock_init(call_ms, call_tenth): Initialize the clock, give pointers to your callback functions.
clock_string(buffer): Get clock as string. Formats like "22:00:00" (8 chars + zero).
clock_set(string): Get clock as string. Format like "22:00:00" (8 chars + zero).
clock_bin_get(string): Get binary values for day, hour, minute, second (4 bytes).
clock_bin_set(string): Set binary values for day, hour, minute, second (4 bytes).
clock_trim(large, small): Set clock trim. large +/- (0.4%), fine +/- (0.1%)

The clock_trim(large, small) function can help you get the system clock more accurate. The large adjustment changes the TIMER4 counter and the small (fine) adjustment adds or subtracts milliseconds once every second. The RC oscillator is pretty good, but the hourly or daily drift can be very large.

lib_clock.h
lib_clock.c

Typical usage:

#include "lib_clock.h"
void timer_ms(void);	/* millisecond timer call */
void timer_10(void);	/* 1/10 second timer call */

char time_tenths;	/* tenth second counter */

int main()
{
	/* do board setup first */
	clock_init(timer_ms, timer_10);
	/* rest of main() code */
}

/*  Millisecond timer callback */

void timer_ms(void)
{
	/* do polling or whatever */
}

/*  1/10 second timer callback */

void timer_10(void)
{
	time_tenths++;
}

Other notes:

The millisecond callback will be called whether you need the function or not. It is very fast to call an empty function (call + return), where testing for a non-NULL function pointer would waste CPU cycles.

Questions or comments? Feel free to contact me:
richard@hodges.org

I am currently available for software development projects.

Last page update: October 12, 2018
This web page created with vi.