Skip to content

lib_pwm: PWM and servo control

Richard Hodges edited this page Oct 23, 2018 · 1 revision

Here is my 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. The header file shows which pins the channels will use.

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.

void pwm_init(char, char); /* in: mode, channels to use */

#define PWM_DUTY  1             /* duty cycle 0 to 100 percent */
#define PWM_SERVO 2             /* send servo signal every 20ms */

#define PWM_C1  1
#define PWM_C2  2
#define PWM_C3  4

/*
 *  Set new PWM duty cycle
 *  in: channel(s), percentage/2: 0 to 200
 */
void pwm_duty(char, char);

/*
 *  Set new servo position
 *  in: channel(s), position: 0 to 255 (0.5 to 2.5 mS, 125 is center: 1.5 mS)
 */
void pwm_servo(char, char);