Saturday, February 23, 2013

Variable frequency PWM using MikroC + PIC16F887

When I was doing a project on a robot,I found out that the MikroC PWM library doesn’t support variable frequency values for the PWM frequency. I needed to use such variable values to drive servo motor according to the feedback. Hence,I tried to find some other libraries I can use (I know it’s easy to write from scratch,but why show we reinvent the wheel?)

After googling,I found this excellent PWM library for MikroC by Barton J.  Dring.You can get it from his site,Dring Engineering Services PWM page

You just have to include two functions setPWMFreq(...) & setPWMDuty(...) ,from their in your code.Then you can simply call swtPWMFreq(..) function when you need to generate a PWM signal as,

setPWMFreq(unsigned long Fpwm, unsigned long Fosc, unsigned int dutyPercent);


Here I’m going to show how to run a servo motor using PWM,







include functions setPWMFreq(...) & setPWMDuty(...)  in the beginning








void main() {


char duty=50; // Set the duty cycle


OSCCON=0x10; //Setup Internal Oscillator to 125kHz clock


TRISC = 0; //Set portC as output


setPWMFreq(9,125000,duty); //Set PWM to 9Hz,Fosc=125kHz,duty=50%


while(1){


delay_ms(100);


}


}




Configuration bits:



image



Here are some useful pages on PIC PWM



PIC16F887 Datasheet



PWM Calculator



PWM Code



Here is a video of running my servo motors using similar code Open-mouthed smile



PIC18F4550 driving MG995 Servo motors

3 comments:

  1. very nice!

    thank you :D

    ReplyDelete
  2. hello, how do I use the function,? I have copied and pasted the code from the provided link, saved it as .c, and added to the project when creating a new one, but is not working, what is the correct procedure to use this function?

    ReplyDelete