Electronic – Generate PWM signal using GPIO

pwm

I want to generate a software PWM signal for 5 millisecond. using GPIO with 50 percent duty cycle and 100 KHz.

While(5ms)
{
 PIN = 1;
 delay_micro(10);
 PIN = 0;
 delay_micro(5);
 PIN = 1;
}

Is this correct or I want to do any thing else.

Best Answer

I'm not a big fan of the "delay" functions because they delay your whole program. I have also made this recently and to get a proper PWM I used the timer0 interrupt to toggle the outputpin every time an interrupt occurs. You can also work with a counting-loop so by example the interrupt has to occur 10 times before the output toggles.

Here is an example which worked fine for me with a PWM frequency of 1kHz. (timer0 is 8-bit timer)

 
void interrupt interrupts(void) {
    if (INTCONbits.TMR0IF == 1) {           //interrupt from timer0
        TMR0 = 0x06;                        //reload timer0
        PIN1 = !PIN1;
        if (timer0_tick_count >= speed) {     //count-loop with variable speed
            timer0_tick_count = 0;

} else { timer0_tick_count++; } INTCONbits.TMR0IF = 0; }

}