Application Constraints

While this implementation plan will produce generally reasonable results, there are some boundary conditions which must be considered.

The first is that it is possible to have a PWM duty cycle of 0%, or of 100%. These both have meaning, but they are anomalous, since the former cycle consists only of a (constant) inactive signal, and the latter only of an active signal. In neither case, there is any edge for the ICP to trigger on. To deal with these cases, the demodulator employs a heuristic, noting that for most applications the period is indeed constant (with a minimal clock drift, which typically happens slowly). The solution is a timeout mechanism, using the timer’s Output Compare Unit. At the beginning of each period, the comparator is set to the expected end of the cycle, that being the edge timestamp plus the PWM period that was most recently measured. If the Output Compare triggers, the cycle is presumed to have completed, and a sample reading of 0% or 100% as appropriate is stored.

The second issue is a race condition, which follows from the fact that the ICP sense-transition is done in software. This means a minimum latency exists between the time a pulse edge is recognized by the ICP and the time the ICP is re-armed to recognize the subsequent edge. As a consequence of this, if a pulse is either very short (close to 0% duty cycle) or very long (close to 100% duty cycle) the subsequent edge may be missed. This latency includes:
  1. 1.Completion of the current instruction, or completion of any active ISR
  2. 2.Four cycles of internal MCU interrupt processing as defined by the Data Sheet.
  3. 3.Entry code (prior to the first executable statement) for the ICP ISR.

While item (3) can be reduced, it can‘t be eliminated, and items (1)-(2) can’t be controlled at all; thus there is some minimum (and maximum) pulse width, outside of which range the pulse simply can’t be measured. Knowing these minimum and maximum measurable pulses is an important part of the overall system design. For purposes of the demodulator, the prime concern is to recognize the condition to avoid producing undefined results due to loss of synchronization with the signal.

Thus the capture ISR tests for a condition where,
  1. 1.The relevant PINx register does not reflect the level to be expected after the current edge.
  2. 2.The ICP interrupt flag is not set.
For these cases, it immediately performs the processing for the subsequent edge, effectively declaring the sample to be either 0% or 100% as appropriate.

Finally, there is the fact that decoding the PWM train takes a certain amount of processing time; this defines the minimum PWM period, which can be captured by the application. This is a significant system design consideration which depends on the number of clock cycles spent in the ISR and to calculate the duty cycle.