Saturday, September 22, 2018

STM8S time base using SDCC

The standart "hello world" program is usually blinking LEDs. The straightforward way to do this is to use a loop which wastes CPU time. This is simple but imprecise! What to do if we want to blink a LED at, say, 1Hz?

The solution is to use a hardware timer. We set a hardware timer to count from the system clock. If we know the clock rate, then we can calculate the number of counts required. When the timer overflows, we know the predefined time has passed.

We can either keep checking and wait for the timer to overflow, or set an interrupt service routine (ISR) so that it notifies the program of the overflow. Here I demonstrate the latter. A blocking timer function "Delayms" is given. Its argument is the number of milliseconds that the function will block. Non blocking timing is also demonstrated. It uses the signal set by TIM1 overflow ISR.

The above is general knowledge, but my intention here is to show you the details of how the timer (TIM1) is set up for overflow interrupts, how the blocking and non blocking delay can be implemented and how external variables are declared and used (a variable that is set and used by functions in different files).

I also show how multiple-file projects can be implemented in SDCC, with several Makefiles. This project is made up of several files. Some reside in a local directory "libs', others reside in the STM8 provided peripheral libraries. All of the "other" files are first compiled into respective object files (.rel extension), and then stored in a local library built specifically for this project. In this project, the library file is "libs/projectlib.lib". The Makefiles check if "projectlib.lib" is up-to-date and if not, also generate it.

For the source code, see my Github site:
https://github.com/ahmetonat/STM8S-time-base-using-SDCC

To build and flash, type:
$ make flash

For an introduction to STM8 programming in SDCC, see another post of mine.

After building and flashing, you should see the LED blink rapidly for 10 pulses first; this uses the blocking delay function. Then it should settle into a double blink pattern, using the non-blocking metod.