Software Generated PWM

27 Mar 2012

Right now I am using 4 of the PwmOut pins to drive my motors at 20khz each. The problem is that I also need to control a servo which has a frequency of 50hz and since all of the PwmOuts share the same period, I am forced to software generate the servo control pwm or do it through some other means.

Here's what I tried before but it seems to consume too much cpu time, thereby interfering with the rest of the program.

DigitalOut pwm(p15);
Ticker t;
void generatePWM(){
   if (count++ < DUTY_CYCLE)
      pwm = 1;
   else
      pwm = 0;
   if (count < 200)
      count = 0;
}
int main(){
   t.attach_us(&generatePWM, 100);
}

Basically I need to generate a pulsewidth of .4-2.4ms with a period of 20ms. Does anyone have a good way of doing this? Thanks

03 Jul 2012

Hello, I have the same problem, if I use one servo or more, I can't control the period of other PWM for the motors. Does anybody found a solution ? Thanks for the answer.

04 Jul 2012

I don't know how it will be CPU wise, but that routine will surely not work. You do count++, then compare it with DUTY_CYCLE. Count starts at zero, so meanwhile count is incremented to one, and if count is smaller than 200, count is zero again. In other words, count will never become something besides 0/1. I assume you want to check if count>200. (Then i would think that with 100us periodicy the CPU should have plenty of time).