STM8 library for PWM and Servo control

Back to STM8 code samples home page.

Here is my new library for using PWM on the inexpensive STM8S103P3 and STM8S105K4 processors. Note that servo control is a subset of PWM, but for good control, it should be handled differently. This library uses TIMER2 and gives 1, 2, or 3 output channels.

I have tested with a Futaba S3003 and Tower Pro models SG90 and MG90S. They seem to move fine using the power from the CPU board, but when I use them with a load, I will give them their separate power lines.

To use the library, include the header file "lib_pwm.h" with your other #include files and call pwm_init(mode, channels) with PWM_DUTY (for regular PWM) or PWM_SERVO (to control a servo) and which channels you want to use. These are PWM_C1, PWM_C2, and PWM_C3. The header file shows which pins the channels will use.

To change the current status of one or more channels, use the functions pwm_duty(channels, new duty cycle) or pwm_servo(channels, new position) The duty cycle is 0 to 200, one half percent per step. Zero gives solid low, 200 gives solid high. For the servo position, 0 to 250 give a pulse of 0.5 to 2.5 milliseconds, 125 is the center. The refresh is 20 milliseconds. These are easily changeable in the source code.

I have prepared a tarball with the library, Makefile, headers, and an easy test program that you can play with. Assuming you have the SDCC compiler ready, just type "make". It also has a compiled file ready to put on your STM8S103P3 with stm8flash. You can also browse the source code below.

lib_pwm.h
lib_pwm.c
test_pwm.c

Compiled test program

test_pwm.tgz: Complete source

Other notes... I always run my STM8S103 boards at 16mhz on the RC oscillator, but the STM8S105 boards I buy have an 8mhz crystal on them, so I use that. A couple of my projects call for accurate time, and the crystals are pretty good, where the RC oscillators drift a lot over the days. So that is why my code uses different divisors for setting up the timers.

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

I am currently available for software development projects.

Last page update: August 22, 2018
This web page created with vi.