Electrical – Count pwm pulses on pic

c18counterpicpwmtimer

I'm working on PIC18F8722 to generate PWM for 50% duty cycle. I have obtained the PWM and now I need to count the PWM pulse. As per my knowledge we can use timers to generate and count those pulses with a counter. I 'm not understanding how exactly to do it. Any advice is appreciable.

Thanks!

Best Answer

The timer being used to generate the PWM signal has an interrupt service routine (ISR). It is either triggered every time the output pin changes (Interrupt on match), or the timer is reloaded (Interrupt-on-overflow).

That interrupt service routine can increment a variable to count one more pulse every time it is called.

AFAICT, all of the PIC18F8722 timers support, at least, one of those two types of ISR.

There is no need for another hardware counter.

The pulse count will be stored in a 'global' variable and so can be read by code outside the ISR. If you are using C to program the PIC18F8722, then the pulse count variable will be defined as 'volatile'.

Ideally, the count will fit in one byte, you will only need to count up to 255. However, if the pulse count variable needs to be bigger than a byte, you'll need to be slightly careful how the code outside the ISR uses it.

A variable bigger than one byte will be read in several instructions, so it is possible for the interrupt to happen in the middle of the main code accessing its value. This can result in the main code occasionally getting confused about the actual value of the pulse count.

(Please add a bit more information to your question, so that we can understand if you need help with solving this kind of problem. If it is not an issue, it seems too much complexity to add to an answer.)