5 Analog Signal Pulse Duration/Frequency Measurements

The tinyAVR® 0- and 1-series, megaAVR® 0-series and AVR® Dx devices feature Event System (EVSYS), a simple but powerful system that allows autonomous control of peripherals without any use of interrupts, CPU, or DMA resources. It allows a change in one peripheral (the event generator) to trigger actions in other peripherals (the event users) through event channels. It provides short and predictable response times between peripherals and can reduce the complexity, size, and execution time of the software, to save power.

Figure 5-1. Analog Signal Duration/Frequency Measurement Block Diagram

The application example in this chapter shows an implementation of duration/frequency measurement for an analog input signal, with minimal usage of microcontroller power. It uses the Event System to route the signals from the AC output through an event channel to Timer Counter B (TCB) event input. Configure the Event System properly to do this.

The first step in the Event System configuration is to set the AC output as event generator for channel 0:

Figure 5-2. EVSYS.CHANNEL - Set AC Output as Event Generator for Channel 0

For EVSYS channel 0, the channel generator selection register must be loaded with 0x20 to enable analog comparator as event generator:

EVSYS.CHANNEL0 = EVSYS_GENERATOR_AC0_OUT_gc;

To trigger events on TCB input, the TCB event user must be connected to channel 0:

EVSYS.USERTCB0 = EVSYS_CHANNEL_CHANNEL0_gc;

To enable pulse and period measurements, the TCB is configured in Pulse-Width Measurement mode, having the Event System as input. The Event System is used to route AC output through event channel 0 to TCB event input.

In Pulse-Width Measurement mode, the TCB will start counting when a positive edge is detected on the event input signal. On the next falling edge, the count value is captured. The counter stops when the second rising edge of the event input signal is detected, and this will set the Interrupt flag. Reading the capture will clear the Interrupt flag. When the Capture register is read, or the Interrupt flag cleared, the TCB becomes ready for a new capture sequence. Therefore, it is recommended to read the Counter register before the Capture register since it is reset to zero at the next positive edge:

Figure 5-3. TCB - Input Capture Frequency and Pulse-Width Measurement

The following code provides basic initialization for TCB in Pulse-Width Measurement mode with Event System as input:

int8_t TIMER0_init()
{

    TCB0.CTRLB = TCB_CNTMODE_FRQPW_gc;		
    TCB0.EVCTRL = TCB_CAPTEI_bm;			

    TCB0.INTCTRL = TCB_CAPT_bm;			
    TCB0.CTRLA = TCB_CLKSEL_CLKDIV2_gc		
               | TCB_ENABLE_bm			
               | TCB_RUNSTDBY_bm;			

}
Tip: The full code example is also available in the Appendix section.

An MCC generated code example for AVR128DA48 with the same functionality as the one described in this section can be found here: