29
AN2749 Using PIC18F26K42's 12-bit ADC² in Low-Pass Filter Mode Introduction Author: Christopher Best, Microchip Technology Inc. Microchip offers a 12-bit Analog-to-Digital Converter with Computation (ADC 2 ) module in several PIC16 and PIC18 microcontrollers. The computation block features several useful mathematical operations, such as averaging, accumulating, and filtering. This application note will highlight the use of the Low-Pass Filter (LPF) mode while focusing on the relationship between the ADC Accumulated Calculation Right Shift Selection (CRS<2:0>) bits, total sampling time, and the LPF response. © 2018 Microchip Technology Inc. Application Note DS00002749A-page 1

Using PIC18F26K42's 12-bit ADC² in Low-Pass Filter Modeww1.microchip.com/downloads/en/AppNotes/AN2749... · until the ADC Count register (ADCNT) count value is equal to the ADRPT

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

  • AN2749 Using PIC18F26K42's 12-bit ADC² in Low-Pass Filter Mode

    Introduction

    Author: Christopher Best, Microchip Technology Inc.

    Microchip offers a 12-bit Analog-to-Digital Converter with Computation (ADC2) module in several PIC16and PIC18 microcontrollers. The computation block features several useful mathematical operations,such as averaging, accumulating, and filtering.

    This application note will highlight the use of the Low-Pass Filter (LPF) mode while focusing on therelationship between the ADC Accumulated Calculation Right Shift Selection (CRS) bits, totalsampling time, and the LPF response.

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 1

  • Table of Contents

    Introduction......................................................................................................................1

    1. ADC2 Module Overview.............................................................................................31.1. Computation Features..................................................................................................................3

    2. Low-Pass Filter..........................................................................................................42.1. Low-Pass Filter Operation............................................................................................................42.2. Filtering Noisy DC Signals............................................................................................................52.3. Filtering AC Signals......................................................................................................................9

    3. LPF Application Example........................................................................................ 133.1. Necessary Hardware..................................................................................................................133.2. Necessary Software................................................................................................................... 133.3. Application Hardware Configuration...........................................................................................133.4. Run the Application.................................................................................................................... 18

    4. Conclusion...............................................................................................................25

    The Microchip Web Site................................................................................................ 26

    Customer Change Notification Service..........................................................................26

    Customer Support......................................................................................................... 26

    Microchip Devices Code Protection Feature................................................................. 26

    Legal Notice...................................................................................................................27

    Trademarks................................................................................................................... 27

    Quality Management System Certified by DNV.............................................................28

    Worldwide Sales and Service........................................................................................29

    AN2749

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 2

  • 1. ADC2 Module OverviewThe ADC2 module consists of two main blocks: the acquisition/conversion block (ADC) and thecomputation block. The ADC block reads an analog signal and converts it into a digital number, while thecomputation block applies post-processing functions on the converted digital number.

    The computation block provides the following features:

    • Accumulate, Average, and Low-Pass Filter Functions• Reference Comparison• 2-level Threshold Comparison• Selectable Interrupts

    Please refer to "Technical Brief TB3194" for detailed information on the ADC2 as a complete module.

    1.1 Computation FeaturesThe ADC2's computation block performs post-processing functions on the ADC converted result. Oncethe ADC block completes a conversion, the result can be passed through one of the followingcomputation functions:

    • Basic – Basic mode operation resembles legacy ADC module operation (without computationfeatures). All additional computation features are disabled. Threshold tests are still performed,which may or may not set the ADC Threshold Interrupt Flag (ADTIF). Double-sampling andContinuous modes, CVD features, and the auto-conversion trigger are all still available in Basicmode.

    • Accumulate – In Accumulate mode, each new conversion result is added to the ADC Accumulatorregister trio (ADACCU:ADACCH:ADACCL). Threshold tests are performed after the conversionresult is added to the accumulator.

    • Average – Average mode operates similar to Accumulate mode in the sense that each conversionresult is added into the accumulator. In Average mode, the average of the conversion results isbased on the ADC Repeat Setting register (ADRPT). For example, when ADRPT = 4, fourconsecutive conversion results are added into the accumulator. Once all four conversion results areadded, the accumulator value is divided by four, and a threshold test is performed on the average.The averaged result can be read from the ADC Filter register pair (ADFLTRH:ADFLTRL).

    • Burst Average – Burst Average mode works like Average mode, except that instead of software re-enabling the GO bit after each completed conversion, hardware continuously retriggers the GO bituntil the ADC Count register (ADCNT) count value is equal to the ADRPT value.

    • Low-Pass Filter (LPF) – Low-Pass Filter mode functions similar to Average mode, except that afteran initial accumulation of samples based on the ADRPT setting, the module continues toaccumulate samples and perform filtering operations indefinitely.

    Computation mode selection is controlled by the ADC Operating Mode Selection (MD) bits of theADC Control Register 2 (ADCON2).

    AN2749ADC2 Module Overview

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 3

    http://ww1.microchip.com/downloads/en/AppNotes/PIC16-PIC18-ADC2-90003194A.pdf

  • 2. Low-Pass FilterThe Low-Pass Filter of ADC2 is a single-pole, unity gain digital filter. The purpose of the LPF is to removeunwanted high frequency components of an input signal. ADC2's LPF removes these components fromboth DC signals and cyclic signals.

    2.1 Low-Pass Filter OperationThe LPF can be considered as having two main processes that work in succession: an initial averagingprocess followed by a continuous filtering operation.

    The initial averaging process begins by accumulating samples until the ADC Count register (ADCNT) isequal to the ADRPT register. During this initial accumulation process, each new sample is added into theaccumulator. After each sample is added, the accumulator right-shifts (divides) its current value by thevalue of the ADC Accumulated Calculation Right Shift Selection (CRS) bits of the ADCON2 register.The new right-shifted value appears in the ADFLTR registers. When ADCNT = ADRPT, a thresholdcomparison test is performed on the ADFLTR value. During this initial averaging process, the ADRPTvalue acts as an RC time constant, allowing the computed average to reach a steady state beforeperforming a threshold comparison. This prevents threshold tests on each sample until after an averagehas been established, which helps to reduce 'false alarm' threshold violations due to random variations ofa single sample.

    Once the initial averaging process completes, the module moves into continuous filtering operation. Thefigure below explains what happens during continuous filtering operation.Figure 2-1. Continuous Filtering Operation Flowchart

    Accumulator has initial average

    ADC converts new sample

    New sample added into

    accumulator

    Previous ADFLTR value subtracted from accumulator

    Accumulator right-shifted by CRS and stored in

    ADFLTR

    Threshold test performed on

    ADFLTR; ADCNT increments (until ADCNT = 0xFF)

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 4

  • Equation 2-1 explains the ADFLTR calculation in mathematical terms. It is important to note that theaccumulator is not cleared after the initial averaging process, or after any subsequent conversion, butinstead continues to accumulate samples until software disables the module. During continuous filteringoperation, ADRPT is ignored, ADCNT continues to count until ADCNT = 0xFF (ADCNT is ignored afterreaching 0xFF), and the CRS value continues to act as the accumulator divider.

    Equation 2-1. ADFLTR Calculation in LPF Mode������ = ������2�����Where:������ = �������+ ����� − �������2�����ACCPREV – Previous accumulator result

    ADRES – Current conversion result

    2.2 Filtering Noisy DC SignalsThe LPF removes noise from a DC signal by taking a continuous running average of samples. In Figure2-2, a 1.5V DC signal has been distorted due to noise. The blue-colored trace (CH2) shows the noisysignal input to the ADC, while the yellow-colored trace (CH1) shows the filtered output signal after beingpassed through a 16-bit Digital-to-Analog Converter (DAC). In this case, the LPF keeps a runningaverage of samples. As one can see, the input waveform has many peaks and valleys, and over time theaverage will settle close to the original DC level.

    Figure 2-2. Filtered DC Signal

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 5

  • 2.2.1 Effects of CRS Values on ADFLTRFigure 2-2 shows a noisy DC input signal and the filtered output signal. What the figure does not show isthe time it took for the filtered output signal to reach a Steady-state condition. In that example, theCRS bits were set to a value of '1', but for all practical purposes, the CRS value could have beenset anywhere between one and six, resulting in a very similar filtered output signal. The figure simplyshows the steady state of the signal after time has passed.

    When filtering a DC signal, the CRS bits act as an RC time constant. As the CRS value increases, thetime it takes for the filtered output to achieve a steady state increases, but the effects of any deviationsfrom the overall average have less of an impact on the filtered output.

    Equation 2-2 explains the relationship between the CRS value and the time to achieve a Steady-stateoutput. When CRS = 1, the output reaches a steady state quickly. When CRS = 1, the ADRPT value is2CRS (ADRPT = 2). After each sample, the accumulator is updated based on Equation 2-2, and theupdated accumulator result is divided by two, resulting in a new ADFLTR value. Since the accumulator isdivided by a small value for each sample, the Steady-state condition is reached in only a few samples.

    When CRS = 6, the output reaches a Steady-state condition much slower. In this case, each time a newsample is taken, the updated accumulator is divided by 64 (26) to give a new ADFLTR value. Since theaccumulator is divided by a large number, it takes many samples to reach the Steady-state condition.

    Examples of Accumulator/ADFLTR Values Based on CRSEquation 2-2. CRS = 1��� = 1������� = 100����� = 100������ = 50 Previous value������ = �������+ ����� − �������2�����= 100 + 100 − 10021 = 150������ = ������2�����= 15021 = 75ADFLTR value increased by 25.

    Equation 2-3. CRS = 6��� = 6������� = 100����� = 100������ = 1 Previous value������ = �������+ ����� − �������2�����

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 6

  • = 100 + 100 − 10026 ≈ 198������ = ������2�����= 19826 ≈ 3ADFLTR value increased by approximately 2.

    Result: When CRS = 1, the ADFLTR value increased much more (25) than when CRS = 6 (2).Table 2-1 shows examples of the accumulator and filter values based on various CRS values. Figure 2-3graphs the ADFLTR values over time (number of samples). For this example, the ADRES value is keptconstant (ADRES = 100) for simplicity, simulating an ideal DC input without noise.

    Table 2-1. ADFLTR Output Response to Step Input

    SAMPLE # ADRESCRS = 1 CRS = 6

    Accumulator ADFLTR Accumulator ADFLTR

    0 100 100 50 100 1

    1 100 150 75 199 3

    2 100 175 87 296 4

    3 100 188 94 392 6

    4 100 194 97 486 7

    5 100 197 98 579 9

    6 100 199 99 670 10

    7 100 200 100 760 11

    8 100 200 100 849 13

    9 100 200 100 936 14

    326 100 200 100 6397 99

    327 100 200 100 6398 99

    328 100 200 100 6399 99

    329 100 200 100 6400 100

    330 100 200 100 6400 100

    331 100 200 100 6400 100

    332 100 200 100 6400 100

    333 100 200 100 6400 100

    334 100 200 100 6400 100

    335 100 200 100 6400 100

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 7

  • Figure 2-3. ADFLTR Output with an Ideal DC Input Signal

    0

    20

    40

    60

    80

    100

    120

    Sam

    ple# 9 19 29 39 49 59 69 79 89 99 10

    911

    912

    913

    914

    915

    916

    917

    918

    919

    920

    921

    922

    923

    924

    925

    926

    927

    928

    929

    930

    931

    932

    9

    ADFL

    TRO

    utpu

    t

    Sample #

    CRS1 CRS6

    As one can see from Figure 2-3, when CRS = 1, the 'rise time' only lasts a few samples before achievinga steady state. When CRS = 6, it takes close to three hundred samples before reaching steady state.As previously mentioned, Table 2-1 and Figure 2-3 show the ADFLTR results when using an ideal, noise-free DC signal. When the signal is noisy, the CRS value determines how drastically the filtered outputchanges. When the CRS value is higher (e.g. '5' or '6'), sudden changes in the input signal have less ofan influence on the output signal. Conversely, when the CRS value is lower (e.g. '1' or '2'), suddenchanges in the input signal are also observed in the output signal.

    Figure 2-4 shows the ADFLTR output when random noise is present on the DC signal. When CRS = 1,the rise time is very fast, but noise has a significant impact on the output signal. When CRS = 6, the risetime is slower than when CRS = 1, but noise has less impact on the output signal.

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 8

  • Figure 2-4. ADFLTR Output with a Noisy DC Input Signal

    0

    20

    40

    60

    80

    100

    120

    0 15 30 45 60 75 90 105

    120

    135

    150

    165

    180

    195

    210

    225

    240

    255

    270

    285

    300

    315

    330

    345

    360

    375

    390

    AD

    FLTR

    Out

    put

    Sample #

    Output with CRS = 1

    Output with CRS = 6

    2.3 Filtering AC SignalsThe LPF removes unwanted high-frequency signals from an AC input signal. The LPF hardware operatesthe same as when it filters DC signals; each new sample is added to the accumulator, averaged, anddivided by 2CRS to get the filtered output. The differentiation between the two is how the CRS value isused.

    2.3.1 CRS Effects on the -3 dB Roll-off FrequencyWhen filtering AC signals, the CRS value determines the -3 dB roll-off frequency of the single-pole filter. Equation 2-4 is used to calculate the filter gain based on time and the CRS value, and Equation 2-5 isused to calculate the gain in decibels (dB).

    Equation 2-4. LPF Gain Equation

    ���� � = 12��� × ��������− 2��� − 12���Where:���� = cos �� + �sin ���� = Π × ������ ����Equation 2-5. LPF Gain in Terms of Decibels (dB)� �� = 20 × log10 �Equation 2-6 uses both LPF gain equations to determine the -3 dB roll-off point in radians per second.

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 9

  • Equation 2-6. -3 dB Gain Calculation with CRS = 1

    Find -3 dB Roll-off in rads/secParameters: CRS = 1

    Imaginary Axis (i)

    Real Axis

    .25.75

    1. Divide the 180° 0 – π angle into 100 equal steps (T).2. Find ωT for all steps: ωT = π × T 3. Calculate the cos(ωT) for all steps4. Calculate the sin(ωT) for all steps5. Find eiωT for all steps: eiωT = cos(ωT) + isin(ωT)6. Use Equation A below to find the filter gain for all steps:

    12CRS e

    iωT

    2CRS - 12CRS

    a = ×

    eiωT -

    7. Use Equation B below to find the gain in decibels (dB) for all steps:

    a(dB) = 20 × log10(|a|)

    Equation A

    Equation B

    .23

    Steps:

    1. For this example, the 0-π angle has been divided into 100 points, but the point T = 0.23 will be used.

    2. Find ωT for T = 0.23: π × 0.23 = 0.72257

    3. Calculate cos(ωT): cos(0.72257) = 0.75011

    4. Calculate sin(ωT): sin(0.72257) = 0.66131

    5. Calculate eiωT: eiωT = cos(0.72257) + isin(0.72257) = 0.75011 + 0.66131i

    6. Using Equation A, substitute the CRS and eiωT values and solve for a:

    121 0.75011 + 0.66131i

    21 - 121

    a = ×

    0.75011 + 0.66131i -= 0.62508 – 0.33073i

    7. Using Equation B and the gain value, find gain (dB):

    a(dB) = 20 × log10(|0.62508 – 0.33073i|) = -3.009 dB

    Conclusion: With CRS = 1, gain(dB) = -3dB at ωT = 0.72 rads/sec

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 10

  • The -3 dB points for each CRS value have already been calculated and are readily available in the ADC2chapter of any device containing the ADC2 module. Table 2-2 shows the -3 dB points in terms of radiansper second for each valid CRS value.

    Table 2-2. Radians/Second at the -3 dB Roll-off

    CRS Radians @ -3 dB Roll-off

    1 0.72

    2 0.284

    3 0.134

    4 0.065

    5 0.032

    6 0.016

    Equation 2-7 is used to convert radians at the -3 dB point into frequency; however, there is onefundamental term of this equation that can cause confusion.

    Equation 2-7. Radian to Frequency Conversion��������� @ − 3�� = �������@− 3��2��Where:

    Radians @ -3 dB = the value from Table 2-2 based on the CRS value

    T = total sampling time

    The 'T' term indicates the total sampling time. The total sampling time is the time it takes to acquire asingle-filtered conversion result. The total sampling time is critical since it is has a direct effect on the roll-off frequency.

    The total sampling time should not be confused with the ADC sample rate as the sample rate is only partof the total sampling time. It is known that the ADC's sampling rate influences the ADC result. What maynot be obvious is that the number of instructions necessary to complete a single conversion can varydepending on how the filtered result is used. In other words, the total sampling time includes the ADCacquisition time, the conversion time, and the post-conversion processing (accumulation/filtering) time,and includes any time needed for interrupt servicing, and any output transmission time. Once the ADC isconfigured, the acquisition, conversion, and post-processing times are generally fixed. Interrupt servicingtimes can vary depending on the number of instructions in the servicing routine. The output transmissiontime can also vary, depending on what type of transmission is used. For example, if the filtered result is tobe logged by a PC data logger program, the Universal Asynchronous Receiver Transmitter (UART) canbe used to transmit the filtered data over USB to the PC. When the application is ready to transmit to thePC, the application software could use 'printf' statements to transmit, or could load the UART transmitbuffer with the data directly. The 'printf' statements are very easy to use, but take far more instructioncycles than directly writing to the Tx buffer. The added instruction cycles when using 'printf' adds to thetotal sampling time, which changes the roll-off point.

    When shorter total sampling times are desired, consider the following:

    • System clock (FOSC) – When the system clock is used as the ADC clock, the system clockdetermines the TAD period.

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 11

  • • ADC acquisition time – Faster acquisition times reduce the total sampling time; when low-impedance inputs to the ADC are used, acquisition times can be low.

    • Type of output transmission – Some transmission methods are faster than others; SPI transferrates are higher than I2C transfer rates.

    • Type of instructions – Using library functions, such as 'printf', can be easy to use but at theexpense of added instruction cycles.

    AN2749Low-Pass Filter

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 12

  • 3. LPF Application ExampleThe LPF application example demonstrates the effects of sampling time on the -3 dB roll-off point.

    3.1 Necessary HardwareThe following hardware items were used in this application:

    • Curiosity High Pin Count (HPC) Development Board (DM164136)• PIC18F26K42 28-lead microcontroller (PDIP package to fit Curiosity HPC)• MikroElektronika DAC2 Click Board™ (MIKROE – 1918)• MCP2200 Breakout Module (ADM00393)• Tektronix® Digital Oscilloscope (TDS2024B)• Rigol Function Generator (DG1022A)• USB, function generator, and oscilloscope cables

    The oscilloscope and function generator can be of any make and model. The oscilloscope must have aminimum of two channels for viewing input/output signals, but the use of a four-channel oscilloscope isrecommended. The function generator must have a configurable sine wave generator.

    3.2 Necessary SoftwareThe following software items were used in this application:

    • MPLAB® X IDE v.4.15• Atmel Studio 7.0 IDE• XC8 C Compiler v.1.45• Tektronix OpenChoice™ PC Communication Software• LPF APP NOTE.X Source Code

    The Atmel Studio 7.0 IDE was used to display the filtered data in the Data Visualizer plug-in. The DataVisualizer reads the ADFLTR values transmitted via UART, and reconstructs the data into a waveform,which is displayed in the Data Visualizer’s Oscilloscope window. The Data Visualizer requires aconfiguration file, which has been included in the LPF APP NOTE.X source code project folder. TheTektronix software was used to capture oscilloscope screen images and is not required for thisapplication.

    3.3 Application Hardware ConfigurationThe Curiosity HPC board is used as the base of the application (see Figure 3-1). The HPC board has twosockets for either 28-lead or 40-lead PDIP packaged microcontrollers. The HPC board also features twoMikroElektronika mikroBUS™ sockets, labeled '1' and '2'. Finally, the HPC board has an integrated PICkit™

    On-Board (PKOB) programmer/debugger that saves the need for an external programmer, such as aPICkit 4.

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 13

  • Figure 3-1. Curiosity High Pin Count (HPC) Development Board

    The DAC2 click board contains a buffered 16-bit Digital-to-Analog Converter (DAC) (see Figure 3-2). Theclick board communicates with the PIC® microcontroller (MCU) via the SPI interface with clock rates up to50 MHz, although for this application an 8 MHz clock is used. The Click Board can be configured for 3.3or 5V operation via a jumper resistor. The board came preconfigured to the 5V setting, so the jumperresistor was moved such that the board is configured for 3.3V operation. The board also has a selectableDAC reference voltage, either VCC or a 4.096V reference. The board came preconfigured for VCC, so nochanges were needed for the DAC voltage reference.

    Figure 3-2. DAC2 Click Board™

    The MCP2200 breakout module contains a USB-to-UART bridge, which was used to communicate withthe Atmel Studio 7.0 IDE (see Figure 3-3).

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 14

  • Figure 3-3. MCP2200 Breakout Module

    3.3.1 Hardware ConfigurationUse the following steps to set up the application hardware:

    1. Place the PIC18F26K42 microcontroller into the 28-lead socket of the HPC board.2. Place the DAC2 Click Board into the mikroBUS socket '1'. The board must be placed into socket '1'

    to ensure the proper connections are made.3. Place a jumper wire between the RD0 and 3.3V pin connections of mikroBUS socket '1'. This

    connects the 'clear' function of the DAC to VDD so that it is not used.4. Connect two wires to the DAC2 output screw terminals. The 'VOUT' screw terminal should be

    connected to an oscilloscope probe lead to view the DAC's output, and the 'GND' screw terminalshould be connected to the scope probe's ground connection.

    5. Connect pin 3 of the MCP2200 breakout module to a ground connection on the HPC board, andconnect pin 6 of the MCP2200 board to pin RC6 of the HPC board. The arrow on the PICkit Serialheader connection denotes pin 1 on the breakout module.

    6. Use a mini USB cable to connect the MCP2200 module to an available USB port on a PC.7. Use a micro USB cable to connect the HPC board to an available USB port on a PC for

    programming/debugging.8. Configure the HPC board for 3.3V operation by placing a jumper (supplied on board) on the 3.3V

    leads of the power selector header.9. Connect the function generator output to pin RA1 on the HPC board. In this application, the function

    generator connection cable has two connection clips, one for the output signal and one for groundreference.

    Connect a scope probe to pin RA1 to monitor the ADC input signal.

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 15

  • The application hardware is now ready to be programmed and tested. The hardware setup should looksimilar to Figure 3-4.

    Figure 3-4. Completed Hardware Configuration

    3.3.2 Software ConfigurationOnce the application hardware has been configured, the application is ready to be programmed andtested. Use the following steps to program and test the application:

    1. Download the LPF APP NOTE.X project. The project will be compressed in .zip format, so thefiles will need to be extracted. The project can be found on the MPLAB Xpress Code Examplespage at https://mplabxpress.microchip.com/mplabcloud/example.

    2. Open the LPF APP NOTE.X project in MPLAB X. The latest version can be downloaded from http://www.microchip.com/mplab/mplab-x-ide.

    3. Compile the project. Once compiled, the project is ready to be programmed into the PIC device.4. Configure the function generator so that it generates a sine wave. It is important to note that the

    ADC cannot interpret any part of a signal that falls below the negative reference. When configuringthe sine wave function, the sine wave should be offset so that no part of the signal falls below thenegative reference voltage. For this application, the waveform's high-voltage level is set to 2.5V,and the low-voltage level is set to 500 mV. This gives a 2V peak-to-peak signal offset by 1.5V fromground. The sine wave frequency should be set to 1 Hz. Once configured, enable the functiongenerator output.

    5. Open the Atmel Studio 7.0 IDE, which can be downloaded from the Atmel Studio 7 page at http://www.microchip.com/mplab/avr-support/atmel-studio-7.

    6. In Atmel Studio 7.0, open the Data Visualizer plug-in tool under the 'Tools' drop-down menu. TheData Visualizer tool can be downloaded from http://www.microchip.com/mplab/avr-support/data-visualizer.

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 16

    https://mplabxpress.microchip.com/mplabcloud/examplehttp://www.microchip.com/mplab/mplab-x-idehttp://www.microchip.com/mplab/mplab-x-idehttp://www.microchip.com/mplab/avr-support/atmel-studio-7http://www.microchip.com/mplab/avr-support/atmel-studio-7http://www.microchip.com/mplab/avr-support/data-visualizerhttp://www.microchip.com/mplab/avr-support/data-visualizer

  • 7. Configure the Data Visualizer. In the Serial Port Control Panel window, enter '115107' into the baudrate box. The Parity drop-down menu should be set to 'None', and the Stop bits drop-down menushould be set to '1 bit'. To the left of the Serial Port Control Panel window is the Configurationmenu. In the Modules box, select the Visualization drop-down menu, and select Oscilloscope.This opens the Oscilloscope window. In the same Modules box, select the Protocols drop-downmenu and select Data Streamer. This opens the Data Stream Control Panel window. The DataStream Control Panel is where the necessary configuration file is loaded so that the Visualizerinterprets the incoming data correctly. This configuration file is included in the LPF APP NOTE.Xproject folder, and is appropriately named 'Data Stream Config File'. In the Data Stream ControlPanel window, click on the '…' button and select the Data Stream Config File. Once the file isselected, click the Load button. This configures the Data Visualizer to accept a Start command, theADFLTRL and ADFLTRH values, and a Stop command for each ADC filtered sample. This alsoopens a Terminal window, which displays the incoming ADFLTR values and a time stamp as eachsample is received.

    8. Once the Data Visualizer has been configured, the incoming signals must be routed to theappropriate Control Panel window. In the Serial Port Control Panel window next to the Stop bitsdrop-down menu lies an image of a male auxiliary cable connector and a female auxiliary inputconnection. Drag the male connector down to the Data Stream Control Panel window and insert itinto the female connection point. Next, drag the male connector found in the Data Stream ControlPanel window and place it in one of the Vertical channel female connection points in theOscilloscope window, and also into the Terminal window's female connection point.

    9. When ready, press the Connect button in the Serial Port Control Panel window. At this point, therewill be no activity in the Data Visualizer since the application code is configured such that the UARTis disabled. Figure 3-5 shows the Data Visualizer window.

    At this point, both the hardware and software are ready for testing.

    Figure 3-5. Atmel Studio 7's Data Visualizer Window

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 17

  • 3.4 Run the ApplicationThe application software comes preconfigured for use with the DAC2 click, with the CRS bits set to avalue of '1', and the RPT bits set to '2'. The UART is configured, but disabled.To begin testing, program the PIC MCU with the application code. Once programmed, the ADC will readthe incoming sine wave from the function generator, convert the signal into a digital equivalent, then passthe ADFLTR data to the DAC2 click. The DAC2 reads the data and converts the digital information backto an analog signal, which is observed on the VOUT screw terminal connection. It is important to note thatthe DAC2 click accepts up to 16 bits of data, and the ADFLTR data is only 12-bits wide. Although theADC conversion result can be configured to be left justified or right justified, the ADFLTR result is alwaysright justified. The ADFLTR value was left-shifted by four in order to keep the same signal magnitude,otherwise, the filtered results would have a significant reduction in signal magnitude. Example 3-1 showsthe code snippet found in the ADCC Threshold ISR. In this example, one can observe the method used toproperly shift the ADFLTR data.

    Example 3-1. DAC2 Code Snippet

    // Method using the DAC2 click, transmit-only SPIint16_t filter = ((int16_t) ((ADFLTRH

  • Example 3-2. SPI Configuration

    // adcc.c file:

    void ADCC_ThresholdISR(void){ PIR1bits.ADTIF = 0;

    // Method using the DAC2 click, transmit-only SPI// int16_t filter = ((int16_t) ((ADFLTRH

  • // uint8_t fltrH = filter >> 8;// SPI1_Exchange24bit(fltrH, fltrL);

    // Method using UART to transmit to Studio 7's oscilloscope int16_t filter = ((int16_t) ((ADFLTRH

  • Figure 3-6. 20 Hz Sine Wave Input

    Note:  250 ms screen capture

    Figure 3-7. 7.64 kHz Sine Wave Input (at the -3 dB Roll-off)

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 21

  • Note:  500 µs screen capture

    At this point, further testing and comparison can be performed by modifying the CRS and RPT values,and changing the transmission methods and frequencies as mentioned in 3.4.1 ChangingConfigurations.

    Table below contains test data for each transmission method, CRS value, and transmission frequency. Byexamining Table 3-1, it can be observed that for each method, the total sampling time changes as thetransmission frequency changes. For example, using the SPI transmit-only method, with a SPI clockfrequency at 8 MHz and CRS = 1, the total sample time is approximately 40 µs faster than using the SPI,with the same clock speed and CRS value, in Full-Duplex mode. The reason for this difference is thatthere are more instructions needed to read the SPI receive buffer, which takes more time. This 40 µsdifference amounts to a roughly 1600 Hz difference in roll-off frequencies. The difference is greater whencomparing the UART method to the SPI transmit-only method. Figure 3-8 shows compares the roll-offfrequencies for each method (both SPI methods at 8 MHz, UART at 115,107 kbps). It is easy to see howeach method, frequency, and CRS value changes the total sampling time, which directly effects the -3 dBroll-off frequency.

    Table 3-1. Test Data for Each Transmission Method

    SPI Transmit-Only Method

    CRS RPT

    Radians@ -3dB Roll-off

    SPI @ 8 MHz SPI @ 4 MHz SPI @ 2 MHz SPI @ 1 MHz

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    1 2 0.72 15 μs 7639 17 μs 6741 21 μs 5457 29 μs 3951

    2 4 0.284 15 μs 3013 17 μs 2659 21 μs 2152 29 μs 1559

    3 8 0.134 15 μs 1422 17 μs 1255 21 μs 1016 29 μs 735

    4 16 0.065 15 μs 690 17 μs 609 21 μs 493 29 μs 357

    5 32 0.032 15 μs 340 17 μs 300 21 μs 243 29 μs 176

    6 64 0.016 15 μs 170 17 μs 150 21 μs 121 29 μs 88

    SPI Full-Duplex Method

    CRS RPT

    Radians@ -3dB Roll-off

    SPI @ 8 MHz SPI @ 4 MHz SPI @ 2 MHz SPI @ 1 MHz

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    1 2 0.72 19 μs 6031 20.5 μs 5590 26 μs 4407 38 μs 3016

    2 4 0.284 19 μs 2379 20.5 μs 2205 26 μs 1738 38 μs 1189

    3 8 0.134 19 μs 1122 20.5 μs 1040 26 μs 820 38 μs 561

    4 16 0.065 19 μs 544 20.5 μs 505 26 μs 398 38 μs 272

    5 32 0.032 19 μs 268 20.5 μs 248 26 μs 196 38 μs 134

    6 64 0.016 19 μs 134 20.5 μs 124 26 μs 98 38 μs 67

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 22

  • SPI Transmit-Only Method

    UART Transmit to Studio 7

    CRS RPT

    Radians@ -3

    dB Roll-off

    UART BR = 115,107 UART BR = 57,554 UART BR = 19,207 UART BR = 9598

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    TotalSampling

    Time

    Expected-3 dB

    Frequency

    1 2 0.72 340 μs 337 680 μs 169 2.05 ms 56 4.17 ms 27

    2 4 0.284 340 μs 133 680 μs 66 2.05 ms 22 4.17 ms 11

    3 8 0.134 340 μs 63 680 μs 31 2.05 ms 10 4.17 ms 5

    4 16 0.065 340 μs 30 680 μs 15 2.05 ms 5 4.17 ms 2

    5 32 0.032 340 μs 15 680 μs 7 2.05 ms 2 4.17 ms 1

    6 64 0.016 340 μs 7 680 μs 4 2.05 ms 1 4.17 ms 1

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 23

  • Figure 3-8. -3 dB Roll-off Comparison at each CRS Value

    0

    1000

    2000

    3000

    4000

    5000

    6000

    7000

    8000

    9000

    1 2 3 4 5 6

    Freq

    uenc

    y(H

    z)

    CRS Value

    SPI Full-Duplex Method

    UART Transmit to Studio 7

    SPI Transmit-Only Method

    AN2749LPF Application Example

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 24

  • 4. ConclusionThe Low-Pass Filter (LPF) computation function of the ADC2 is used to remove noise from DC inputsignals, and filter out high-frequency signals from AC input signals. When filtering DC signals, the CRSvalue determines how quickly the filtered output reacts to changes in the input signal. When filtering ACsignals, the CRS value and the total sampling time determine the -3 dB roll-off frequency.

    AN2749Conclusion

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 25

  • The Microchip Web Site

    Microchip provides online support via our web site at http://www.microchip.com/. This web site is used asa means to make files and information easily available to customers. Accessible by using your favoriteInternet browser, the web site contains the following information:

    • Product Support – Data sheets and errata, application notes and sample programs, designresources, user’s guides and hardware support documents, latest software releases and archivedsoftware

    • General Technical Support – Frequently Asked Questions (FAQ), technical support requests,online discussion groups, Microchip consultant program member listing

    • Business of Microchip – Product selector and ordering guides, latest Microchip press releases,listing of seminars and events, listings of Microchip sales offices, distributors and factoryrepresentatives

    Customer Change Notification Service

    Microchip’s customer notification service helps keep customers current on Microchip products.Subscribers will receive e-mail notification whenever there are changes, updates, revisions or erratarelated to a specified product family or development tool of interest.

    To register, access the Microchip web site at http://www.microchip.com/. Under “Support”, click on“Customer Change Notification” and follow the registration instructions.

    Customer Support

    Users of Microchip products can receive assistance through several channels:

    • Distributor or Representative• Local Sales Office• Field Application Engineer (FAE)• Technical Support

    Customers should contact their distributor, representative or Field Application Engineer (FAE) for support.Local sales offices are also available to help customers. A listing of sales offices and locations is includedin the back of this document.

    Technical support is available through the web site at: http://www.microchip.com/support

    Microchip Devices Code Protection Feature

    Note the following details of the code protection feature on Microchip devices:

    • Microchip products meet the specification contained in their particular Microchip Data Sheet.• Microchip believes that its family of products is one of the most secure families of its kind on the

    market today, when used in the intended manner and under normal conditions.• There are dishonest and possibly illegal methods used to breach the code protection feature. All of

    these methods, to our knowledge, require using the Microchip products in a manner outside theoperating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so isengaged in theft of intellectual property.

    • Microchip is willing to work with the customer who is concerned about the integrity of their code.

    AN2749

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 26

    http://www.microchip.com/http://www.microchip.com/http://www.microchip.com/support

  • • Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode. Code protection does not mean that we are guaranteeing the product as “unbreakable.”

    Code protection is constantly evolving. We at Microchip are committed to continuously improving thecode protection features of our products. Attempts to break Microchip’s code protection feature may be aviolation of the Digital Millennium Copyright Act. If such acts allow unauthorized access to your softwareor other copyrighted work, you may have a right to sue for relief under that Act.

    Legal Notice

    Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates. It is your responsibility to ensure that yourapplication meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORYOR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITSCONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE.Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in lifesupport and/or safety applications is entirely at the buyer’s risk, and the buyer agrees to defend,indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resultingfrom such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectualproperty rights unless otherwise stated.

    Trademarks

    The Microchip name and logo, the Microchip logo, AnyRate, AVR, AVR logo, AVR Freaks, BitCloud,chipKIT, chipKIT logo, CryptoMemory, CryptoRF, dsPIC, FlashFlex, flexPWR, Heldo, JukeBlox, KeeLoq,Kleer, LANCheck, LINK MD, maXStylus, maXTouch, MediaLB, megaAVR, MOST, MOST logo, MPLAB,OptoLyzer, PIC, picoPower, PICSTART, PIC32 logo, Prochip Designer, QTouch, SAM-BA, SpyNIC, SST,SST Logo, SuperFlash, tinyAVR, UNI/O, and XMEGA are registered trademarks of Microchip TechnologyIncorporated in the U.S.A. and other countries.

    ClockWorks, The Embedded Control Solutions Company, EtherSynch, Hyper Speed Control, HyperLightLoad, IntelliMOS, mTouch, Precision Edge, and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the U.S.A.

    Adjacent Key Suppression, AKS, Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BodyCom,CodeGuard, CryptoAuthentication, CryptoAutomotive, CryptoCompanion, CryptoController, dsPICDEM,dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial Programming,ICSP, INICnet, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, memBrain, Mindi, MiWi,motorBench, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, OmniscientCode Generation, PICDEM, PICDEM.net, PICkit, PICtail, PowerSmart, PureSilicon, QMatrix, REAL ICE,Ripple Blocker, SAM-ICE, Serial Quad I/O, SMART-I.S., SQI, SuperSwitcher, SuperSwitcher II, TotalEndurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA aretrademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

    SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.

    Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries.

    GestIC is a registered trademark of Microchip Technology Germany II GmbH & Co. KG, a subsidiary ofMicrochip Technology Inc., in other countries.

    All other trademarks mentioned herein are property of their respective companies.

    AN2749

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 27

  • © 2018, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.

    ISBN: 978-1-5224-3294-4

    Quality Management System Certified by DNV

    ISO/TS 16949Microchip received ISO/TS-16949:2009 certification for its worldwide headquarters, design and waferfabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in Californiaand India. The Company’s quality system processes and procedures are for its PIC® MCUs and dsPIC®

    DSCs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory andanalog products. In addition, Microchip’s quality system for the design and manufacture of developmentsystems is ISO 9001:2000 certified.

    AN2749

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 28

  • AMERICAS ASIA/PACIFIC ASIA/PACIFIC EUROPECorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200Fax: 480-792-7277Technical Support:http://www.microchip.com/supportWeb Address:www.microchip.comAtlantaDuluth, GATel: 678-957-9614Fax: 678-957-1455Austin, TXTel: 512-257-3370BostonWestborough, MATel: 774-760-0087Fax: 774-760-0088ChicagoItasca, ILTel: 630-285-0071Fax: 630-285-0075DallasAddison, TXTel: 972-818-7423Fax: 972-818-2924DetroitNovi, MITel: 248-848-4000Houston, TXTel: 281-894-5983IndianapolisNoblesville, INTel: 317-773-8323Fax: 317-773-5453Tel: 317-536-2380Los AngelesMission Viejo, CATel: 949-462-9523Fax: 949-462-9608Tel: 951-273-7800Raleigh, NCTel: 919-844-7510New York, NYTel: 631-435-6000San Jose, CATel: 408-735-9110Tel: 408-436-4270Canada - TorontoTel: 905-695-1980Fax: 905-695-2078

    Australia - SydneyTel: 61-2-9868-6733China - BeijingTel: 86-10-8569-7000China - ChengduTel: 86-28-8665-5511China - ChongqingTel: 86-23-8980-9588China - DongguanTel: 86-769-8702-9880China - GuangzhouTel: 86-20-8755-8029China - HangzhouTel: 86-571-8792-8115China - Hong Kong SARTel: 852-2943-5100China - NanjingTel: 86-25-8473-2460China - QingdaoTel: 86-532-8502-7355China - ShanghaiTel: 86-21-3326-8000China - ShenyangTel: 86-24-2334-2829China - ShenzhenTel: 86-755-8864-2200China - SuzhouTel: 86-186-6233-1526China - WuhanTel: 86-27-5980-5300China - XianTel: 86-29-8833-7252China - XiamenTel: 86-592-2388138China - ZhuhaiTel: 86-756-3210040

    India - BangaloreTel: 91-80-3090-4444India - New DelhiTel: 91-11-4160-8631India - PuneTel: 91-20-4121-0141Japan - OsakaTel: 81-6-6152-7160Japan - TokyoTel: 81-3-6880- 3770Korea - DaeguTel: 82-53-744-4301Korea - SeoulTel: 82-2-554-7200Malaysia - Kuala LumpurTel: 60-3-7651-7906Malaysia - PenangTel: 60-4-227-8870Philippines - ManilaTel: 63-2-634-9065SingaporeTel: 65-6334-8870Taiwan - Hsin ChuTel: 886-3-577-8366Taiwan - KaohsiungTel: 886-7-213-7830Taiwan - TaipeiTel: 886-2-2508-8600Thailand - BangkokTel: 66-2-694-1351Vietnam - Ho Chi MinhTel: 84-28-5448-2100

    Austria - WelsTel: 43-7242-2244-39Fax: 43-7242-2244-393Denmark - CopenhagenTel: 45-4450-2828Fax: 45-4485-2829Finland - EspooTel: 358-9-4520-820France - ParisTel: 33-1-69-53-63-20Fax: 33-1-69-30-90-79Germany - GarchingTel: 49-8931-9700Germany - HaanTel: 49-2129-3766400Germany - HeilbronnTel: 49-7131-67-3636Germany - KarlsruheTel: 49-721-625370Germany - MunichTel: 49-89-627-144-0Fax: 49-89-627-144-44Germany - RosenheimTel: 49-8031-354-560Israel - Ra’ananaTel: 972-9-744-7705Italy - MilanTel: 39-0331-742611Fax: 39-0331-466781Italy - PadovaTel: 39-049-7625286Netherlands - DrunenTel: 31-416-690399Fax: 31-416-690340Norway - TrondheimTel: 47-7289-7561Poland - WarsawTel: 48-22-3325737Romania - BucharestTel: 40-21-407-87-50Spain - MadridTel: 34-91-708-08-90Fax: 34-91-708-08-91Sweden - GothenbergTel: 46-31-704-60-40Sweden - StockholmTel: 46-8-5090-4654UK - WokinghamTel: 44-118-921-5800Fax: 44-118-921-5820

    Worldwide Sales and Service

    © 2018 Microchip Technology Inc. Application Note DS00002749A-page 29

    IntroductionTable of Contents1. ADC2 Module Overview1.1. Computation Features

    2. Low-Pass Filter2.1. Low-Pass Filter Operation2.2. Filtering Noisy DC Signals2.2.1. Effects of CRS Values on ADFLTR

    2.3. Filtering AC Signals2.3.1. CRS Effects on the -3 dB Roll-off Frequency

    3. LPF Application Example3.1. Necessary Hardware3.2. Necessary Software3.3. Application Hardware Configuration3.3.1. Hardware Configuration3.3.2. Software Configuration

    3.4. Run the Application3.4.1. Changing Configurations3.4.2. Test Data

    4. ConclusionThe Microchip Web SiteCustomer Change Notification ServiceCustomer SupportMicrochip Devices Code Protection FeatureLegal NoticeTrademarksQuality Management System Certified by DNVWorldwide Sales and Service