Silicon ChipBuild A Low-Frequency Distortion Analyser - April 2015 SILICON CHIP
  1. Outer Front Cover
  2. Contents
  3. Publisher's Letter: We live in a time of plenty and we should all be optimistic
  4. Feature: Airborne Weather Radar: Keeping Aircraft Safe by Dr David Maddison
  5. Review: National Instruments VirtualBench by Nicholas Vinen
  6. Project: Appliance Insulation Tester by John Clarke
  7. Project: A Really Bright 12/24V LED Oyster Light by Ross Tester
  8. Project: Build A Low-Frequency Distortion Analyser by Nicholas Vinen
  9. Product Showcase
  10. Project: WeatherDuino Pro2 Wireless Weather Station, Pt.2 by Armindo Caneira & Trevor Robinson
  11. Vintage Radio: The AWA 897P: Australia’s first transistor radio by Ian Batty
  12. Review: Keysight MSO-X 3104T Oscilloscope by Nicholas Vinen
  13. Market Centre
  14. Notes & Errata
  15. Advertising Index
  16. Outer Back Cover

This is only a preview of the April 2015 issue of Silicon Chip.

You can view 34 of the 96 pages in the full issue, including the advertisments.

For full access, purchase the issue for $10.00 or subscribe for access to the latest issues.

Items relevant to "Appliance Insulation Tester":
  • Appliance Insulation Tester PCB [04103151] (AUD $10.00)
  • Hard-to-get parts for the Appliance Insulation Tester (Component, AUD $15.00)
  • Appliance Insulation Tester front panel [04103152] (PCB, AUD $10.00)
  • Appliance Insulation Tester PCB pattern (PDF download) [04103151] (Free)
  • Appliance Insulation Tester panel artwork (PDF download) (Free)
Items relevant to "Build A Low-Frequency Distortion Analyser":
  • Bad Vibes Infrasound Snooper / Low Frequency Distortion Analyser PCB [04104151] (AUD $5.00)
  • PIC32MX170F256B-I/SP programmed for the Low Frequency Distortion Analyser [0410415B.HEX] (Programmed Microcontroller, AUD $15.00)
  • Firmware (HEX) file and C source code for the Low Frequency Distortion Analyser [0410415B.HEX] (Software, Free)
  • Low Frequency Distortion Analyser / Infrasonic Snooper PCB pattern (PDF download) [04104151] (Free)
  • Low Frequency Distortion Analyser panel artwork (PDF download) (Free)
Articles in this series:
  • WeatherDuino Pro2 Wireless Weather Station, Pt.1 (March 2015)
  • WeatherDuino Pro2 Wireless Weather Station, Pt.1 (March 2015)
  • WeatherDuino Pro2 Wireless Weather Station, Pt.2 (April 2015)
  • WeatherDuino Pro2 Wireless Weather Station, Pt.2 (April 2015)
  • WeatherDuino Pro2 Wireless Weather Station, Pt.3 (May 2015)
  • WeatherDuino Pro2 Wireless Weather Station, Pt.3 (May 2015)
  • WeatherDuino Pro2 Wireless Weather Station, Pt.4 (June 2015)
  • WeatherDuino Pro2 Wireless Weather Station, Pt.4 (June 2015)

Purchase a printed copy of this issue for $10.00.

By NICHOLAS VINEN Low Frequency Distortion Analyser Are you concerned about the quality of your 50Hz 230VAC supply? Would you like to measure the harmonic distortion of your loudspeaker system? This unit will measure the distortion of a 50Hz or 60Hz mains waveform (via a low-voltage isolating transformer) or the distortion of any 3-20VAC sinewave signal in the range of 20Hz10kHz, eg, the output of a midrange or bass loudspeaker. W E TEND TO think of the 50Hz AC mains supply as a 230V RMS sinewave but if you have a look at it on an oscilloscope (see Fig.1), it is often quite distorted. A large proportion of mains loads are not resistive but reactive and since they draw current out-of-phase or in a non-sinusoidal manner, they generate a voltage across the finite impedance of the mains supply network and distort the signal. Typical “waveform distorters” are fluorescent and gas discharge lights and devices with transformer/rectifier-based linear power supplies or non-PFC (Power Factor Correction) switchmode power supplies. These all tend to draw current only at the voltage peaks, leading to the pronounced 58  Silicon Chip “flat-topping” you can see in Fig.1. Does this matter? Well, most equipment will not be affected by even quite severe levels of mains distortion but some sensitive devices could be upset. As an extreme example, there are plenty of devices which will not operate correctly from square-wave inverters and some devices won’t operate from modified sinewave inverters either. Having said that, the distortion levels of such inverters are well above the maximum allowable figure for the mains supply which is normally quoted as 5%. In our experience, a typical harmonic distortion figure is around 3% but it varies quite a bit depending on location. Interestingly, different power points in our office gave quite different readings, from 2.43.2%, suggesting that they are wired to different mains phases. And yes, this analyser can be used to (indirectly) check the distortion of portable 230VAC generators and inverters. It’s safe to use because a small 3-20VAC plugpack is used as an isolation transformer (ie, the plugpack is plugged into the generator or the mains and the plugpack’s low-voltage AC output is fed into the signal input of the analyser). So how would you know whether your mains supply is badly distorted? Well, this simple device will tell you. It can measure harmonic distortion from below 0.1% to around 33% with a bandwidth of a few kilohertz and siliconchip.com.au it’s very simple to build and operate. Some devices which may be sensitive to mains distortion include certain types of (mainly older) test equipment and medical devices. Devices with motors will still run with highly distorted mains but some may get hotter than normal. Severe harmonics, such as those present when mains tone control signals are being broadcast, can also cause transformers, motors and fluorescent light ballasts to hum or buzz audibly. Some hifi enthusiasts also believe that AC mains waveform distortion and noise can also affect the sound quality of amplifiers and other equipment. In our experience, while control tones and some mains-borne interference may become audible, that tends to be more likely in valve amplifiers. Otherwise, typical distortion of the 50Hz (or 60Hz) mains waveform is not likely to have any effect on audio performance. However, there is one exception. If the mains waveform is severely “flat topped” that means that its peak-topeak value will be significantly reduced with respect to an undistorted sinewave. That in turn means that the resulting supply voltages in the amplifier can be less than they should be and that can definitely affect performance, particularly if the amplifier being driven hard. For more information see this link: http://www.mantenimientomundial. com/sites/mm/notas/Harmonics.pdf If you want to measure loudspeaker distortion you will need a microphone and preamplifier. The easy solution is to use the PreChamp featured in our article on “How To Do Your Own Loudspeaker Measurements” in the December 2011 issue. Fig.1: a typical mains waveform, as measured at our office (yellow, top) with its distortion residual (green, bottom). Not only are the peaks badly flattened but there are visible bumps along the rising and falling edges too, especially around the zero crossing points. It isn’t obvious from the residual but the distortion is almost all odd-order harmonics (ie, 3rd, 5th, etc) due to the flat-topping. This is very similar to the distortion in an audio amplifier when the output is clipping. How it works Traditional audio analysers use a tunable notch filter. The filter removes the fundamental frequency (eg, 50Hz or 60Hz for a mains supply) and the remaining harmonics and noise are measured and related to the input voltage to obtain a percentage reading. This project idea was initially suggested to us as a series of passive notch filters driven by a low-voltage transformer. The notches would be tuned to the local mains frequency (ie, 50Hz), thus removing the fundamental. The residual signal (ie, distortion components) could then be measured siliconchip.com.au Fig.2: at top is the same distorted mains waveform as in Fig.1 with a low-pass filter applied to remove noise; below is the spectrum calculated by the scope from this data using a Fast Fourier Transform. It is configured to use the same Flat Top window as the microcontroller in this project. You can see that the third, fifth, seventh and ninth harmonics are dominant at around -39dB with a second harmonic at about -48dB. The number of harmonics shown is about the same as the micro uses to calculate total distortion. April 2015  59 Parts List 1 double-sided PCB, coded 04104151, 104 x 60.5mm 1 UB3 jiffy box (optional) 1 5kΩ mini horizontal trimpot (VR1) 1 28-pin DIL IC socket (for IC1) 1 9V battery snap 1 9V battery 1 piece non-conductive foam, approximately 65 x 40 x 8mm 1 PCB-mount DC socket (optional) (CON1) 1 2-way terminal block, 5.08mm spacing (CON2) 1 5-pin right-angle header (CON3) (for programming IC1) 1 2-pole 6-position rotary switch (S1) 1 knob to suit S1 2 PCB stakes 2 chassis-mount binding posts (optional, for use with case) Semiconductors 1 PIC32MX170F256B-I/SP programmed with 0410415A. HEX (IC1) 1 78L05 100mA regulator (REG1) 2 MCP1700-3.3/TO 3.3V lowdropout regulator (REG2) 1 yellow or orange 3mm LED (LED1) 1 red 3mm LED (LED2) 1 1N4004 1A diode (D1) 1 1N5819 1A Schottky diode (D2) Capacitors 1 220µF 25V electrolytic 3 100µF 16V electrolytic 1 10µF+ 6V tantalum or SMD ceramic 1 1µF multi-layer ceramic 3 100nF multi-layer ceramic Resistors (0.25W, 1%) 3 100kΩ 2 470Ω 1 33kΩ 1 22Ω 3 10kΩ 1 10Ω 1 1kΩ with a DMM and divided by the raw transformer output voltage in order to calculate the THD+N figure as a percentage. We investigated this concept but concluded that passive filters are too fiddly to tune and too lossy for this purpose. Tuning is a tricky issue because such filters inevitably involve 60  Silicon Chip capacitors which are not normally sold in tolerances better than 5%. So each notch stage would need at least one trimpot and they would all need to be tuned very close to 50Hz to get a deep enough notch for sufficient fundamental rejection. However, the real show-stopper for the passive filter idea is its inherent signal loss and its lack of notch depth; you need a really steep notch to remove the fundamental but have no effect on the harmonics. A simulation of the required filter with ideal components showed that the first few harmonics (ie, 100Hz, 150Hz, 200Hz etc) were severely attenuated by the shoulders of the notch, making the resulting reading likely to severely underestimate the actual level of distortion. The third harmonic at 150Hz is normally the largest component of mains distortion and a twin-T passive notch filter tuned for 50Hz is still 10dB down at this frequency. If multiple such filters were used (and it seems likely this would be required), the attenuation would be 20dB or more and this is clearly unacceptable. We did consider using active notch filter(s) but to get the required notch depth with sufficiently little attenuation for the second harmonic at 100Hz would require a complex circuit. The alternative is to use digital signal processing with a microcontroller. DSP software to the rescue The DSP concept is relatively simple, even if the software is not. The output of a 9VAC or 12VAC plugpack is attenuated to give a signal of about 3.3V peak-to-peak. This is fed to the analog-to-digital converter (ADC) input of a 32-bit microcontroller. The micro digitises the signal, does some filtering to make up for its relatively low-performance internal ADC, then does a spectral analysis and determines the THD from the result. The output from the microcontroller is a pulse width modulated (PWM) signal which is filtered to obtain a DC voltage that can be read with a multimeter or panel meter. So the circuit is really quite simple even though the software is anything but. In fact, we use a Fast Fourier Transform (FFT) to produce a spectrum analysis of the input signal. This tells us the amplitudes of fundamental frequency and all the harmonics up to the 20th. The tallest peak will be the 50Hz fundamental and the micro can easily search for the highest peak, so frequency accuracy is not important. The distortion components (ie, the harmonics) will be at equally spaced frequencies above this peak. These calculations are performed in the frequency domain. As hinted at earlier, the formula for computing THD (in the time domain) is to divide the RMS average of the residual signal (ie, signal minus 50Hz fundamental sinewave) by the RMS average of the fundamental sinewave itself, then take the square root of the result. It isn’t hard to do this in the frequency domain, as the spectral peaks correspond to the RMS voltages of each individual sinewave component. In theory, the answer is the same although the time-domain method inevitably includes any noise within the measurement bandwidth of the instrument while the spectral version gives the possibility of ignoring noise and only considering the harmonics themselves, thus giving a THD (only) measurement rather than THD+N. In this case, it’s necessary because the micro’s 10-bit ADC has a lot of aliasing noise and this would cause a THD+N reading to be much too high. Also, if mains noise is going to cause any problems, it’s most likely to be due to RF emissions. This would not normally contribute much to a THD+N reading, partly because the absolute power is low and partly due to the typically limited bandwidth of the measurement. Other uses The aforementioned distortion measurement method is sufficiently generic that it could be used for other purposes. Because the unit searches for the fundamental, the THD of any signal in the range of 20Hz-10kHz can be measured. However given that the output starts to become less accurate at lower readings (<0.1%) and the lowest reading you’re likely to get is around 0.03%, it isn’t suitable for measuring hifi audio amplifiers. Having said that, it certainly should be suitable for measuring the kind of distortion that’s typical for . . . ahem . . . a valve amplifier. The lowest readings the device can give are more or less in line with the best performance expected from a valve amplifier. And with solid-state amplifiers, it’s good siliconchip.com.au CON1 22Ω 6-12V DC POWER D1 1N400 4 1 ON/OFF 2 3 S1b K A K A 5 6 9V BATTERY OUT IN GND +3.3V GND 100 µF 220 µF 100k REG2 MCP1700-3.3/TO +5V OUT IN 4 D2 1N 5819 + REG1 78L05 100 µF 100nF 16V 25V 16V 33k +3.3V 10Ω 470Ω CON2 SIGNAL + INPUT (20VAC MAX.) MMC MMC 10k ADJUST VR1 SENSITIVITY 5k 13 1 µF 470Ω 3 2 VDD 1 SELECT 2 3 4 S1a 6 5 K AVDD RA1/AN1/VREF– SOSCO/RA4 RA0 /AN 0 /VREF+ PGED1/AN2/RB 0 AN9/RB15 11 10 9 6 AN 10 /RB1 4 SOSCI/RB4 AN11/RB13 RA3/CLKO AN12/RB12 RA2/CLKI PGEC2/RB11 IC1 PIC32MX170PIC3 2 MX170F256B RB2/AN4 +3.3V PGED2/RB10 TD0/RB9 TCK/RB8 CON3 ICSP TDI/RB7 10k 1 1 2 14 3 15 4 AN5/RB3 MCLR A λ LED1 28 MODE 100k A 100nF 100nF 100k 1k PGEC1/AN3/RB1 12 LOW BATTERY/ OPERATE λ LED2 CLIP K 4 26 25 10k 24 TP1 23 22 21 OUTPUT VOLTAGE 100mV/% 100 µF 18 16V 17 16 7 TP2 5 LEDS PGED3/RB5 PGEC3/RB6 5 VCAP K A 20 10 µF AVSS 27 VSS 19 78L05 6.3V TANT. OR SMD CERAMIC VSS 8 GND IN OUT MC P1700 SC  20 1 5 LOW FREQUENCY DISTORTION ANALYSER D1, D2 A K IN OUT GND Fig.2: the distortion analyser circuit. There isn’t much to it since most of the work is done in IC1’s software. The signal is attenuated by VR1 and then biased to half-supply (1.65V) before being applied to analog input RA0. A PWM signal from pin 24 (RB13) passes through a low-pass RC filter with the reading available between TP1 and TP2. Power comes from a 9V battery or DC plugpack while rotary switch S1 provides both on/off switching and mode selection. enough to at least check that an amplifier is operating correctly and so it might be useful for servicing work. In order to provide relatively accurate readings at higher frequencies, the unit automatically increases its sampling rate (by reducing the amount of averaging done) when it detects that the fundamental is at a higher frequency. Circuit description The full circuit is shown in Fig.2. It would normally be powered from a siliconchip.com.au 9V battery via Schottky reverse polarity protection diode D2 but it could be powered from a DC plugpack via diode D1. It cannot be powered from the same 9-12VAC plugpack which is used to couple the 50Hz mains AC signal into the analyser. If a plugpack is used to power the Low Frequency Analyser, the 9V battery is disconnected by the socket switch, CON1. D1 provides separate reverse-polarity protection for the plugpack. The DC supply is connected to the circuit via one pole of 6-position 2-pole rotary switch S1. Two 3-terminal regulators are connected in series to provide a 3.3V supply for the microcontroller. The first is REG1, 78L05 5V regulator which acts as a pre-regulator for 3.3V regulator REG2 which can only handle a maximum input voltage of 6V. In practice, this two-regulator combination provides a regulated 3.3V rail (important for accuracy of the output voltage) for input voltages down to about 5V, which would mean the 9V battery was well and truly flat. April 2015  61 10Ω 10k +10 µF – ICSP + % + TP1 5819 Batt 1 TP2 Clip 100 µF 470Ω 1k LED1 LED2 A 100nF 100nF 100 µF CON3 PIC32MX170F256B IC1 9V 0V 100k 470Ω 22Ω REG2 + REG1 A D1 Power/Mode 100nF 100 µF 10k D2 220 µF + S1 + 9V BATTERY Distortion Analyser CON1 33k CON2 100k 100k AC in 4004 VR1 5k C 2015 1 µF 10k 04104151 (GREY OUTLINES REPRESENT COMPONENTS NOT USED IN THIS PROJECT) Fig.3: follow this PCB overlay diagram and the photo at right to build the Distortion Analyser. Note that many of the components are left off as this PCB was designed to be used for multiple purposes. It snaps into the side rails on a UB3 jiffy box or can be housed in a larger enclosure if a panel meter is to be fitted, to display THD readings. So that you know if the battery has gone flat, a 100kΩ/33kΩ resistive divider allows PIC32MX17F256B microcontroller IC1 to monitor the battery voltage at its AN1 analog input (pin 3). The 3.3V rail is used as a reference and if the battery voltage drops below about 5.6V, LED1 is illuminated. The input signal is fed in via CON2 and has a 15kΩ fixed resistive load. This minimal loading means that a 9VAC or 12VAC transformer’s output closely tracks the mains waveform, ie, the transformer itself causes minimal extra distortion. The signal is then coupled via a 1µF capacitor and DCbiased to 1.65V (half the 3.3V supply) by a pair of 100kΩ resistors. The signal then goes to analog input AN0 (pin 2) of IC1 via a 470Ω protection resistor. The chip uses its internal RC (resistor/capacitor) oscillator and PLL (phase locked loop) to run at 24MHz, so that its FFT calculations on the sampled data at AN0 complete fairly quickly. The ADC requires 13 clocks per sample (1 for sampling, 12 for conversion) and is run at ¼ the main clock rate, giving a sampling rate of 24MHz ÷ 13 ÷ 4 = 460kHz. Between 1 and 16 samples are averaged, giving an effective sampling rate of between 28.75kHz and 460kHz. For a 50Hz signal (eg, mains) at 28.75kHz and a window size of 8192 samples, this means 8192 / 28750 = 285ms worth of data or just over 14 full cycles is processed at a time. Having done the THD calculation, the micro then uses one of its internal PWM peripherals to generate a signal at output RB13 (pin 24). The associated timer period is set to 3300 so that for each increment in the PWM duty cycle value, the average output voltage increases by 1mV. This assumes an ac- Features & Specifications Input signal voltage: 3-20V RMS Input signal frequency: 20Hz-10kHz THD measurement range: 0.03-33% THD measurement accuracy: typical error less than 0.1% (absolute) Modes: total distortion %, second harmonic %, third harmonic %, even harmonic % and odd harmonic % Power supply: 9V battery or 6-15V DC plugpack Operating current drain: ~15mA Low battery indicator: LED, ~5.5V threshold 62  Silicon Chip curate 3.3V rail; the MCP1700 has an output voltage tolerance of ±0.4% at 25°C so it should be well within ±1% at normal room temperatures. This PWM signal passes through a 10kΩ/100µF RC low-pass filter with a time constant of around one second. This gives a DC voltage to make the meter’s job easier and also to smooth out any jitter in the measurement due to noise and so on. It can then be measured between TP1 and TP2. Each time the output voltage is updated, LED1 is flashed briefly. This indicates that the unit is operating. As mentioned earlier, IC1 monitors the battery level via its AN1 input and should the battery voltage drop to a low level (before output accuracy suffers), the state of LED1 is inverted. That is, LED1 is switched on all the time, except briefly when the output voltage is updated when it flickers off. Thus, if LED1 is on most of the time, the battery is flat and should be changed. LED2 is used to indicate ADC overload on input AN0. For optimum performance, VR1 is adjusted to just below the level where LED2 lights. Having said that, the exact setting is not critical as long as LED2 remains off during operation; if VR1 is set a little low, it doesn’t appear to affect the readings much. Rotary switch S1a connects either pin 6 or one of pins 9-11 of IC1 to ground. With S1 in position 1, power siliconchip.com.au the circuit are the two supply bypass capacitors for IC1’s VDD and AVDD rails, a 10Ω resistor to help filter its analog supply and a 10µF capacitor at pin 20 (VCAP) which is used by its internal core regulator. This 10µF capacitor must be a low-ESR type (below 1Ω) which means either tantalum or ceramic. Construction is disconnected so the unit is off. IC1 can determine which of the other five positions the switch is in by enabling its weak internal pull-up current sources on these pins. If S1 is in position 2, none of these pins (6 or 9-11) is pulled low whereas positions 3-6 each pull a different pin low. IC1 checks the state of S1 immediately after it updates its output and performs a slightly different measurement at the next update, depending on its state. In position 2, the normal THD calculation is made. In position 3, only the THD contribution from the second harmonic is read out. Similarly, position 4 reads the third harmonic only, position 5 gives the THD contribution of all even harmonics (2nd, 4th, 6th, etc) and position 6 reads only odd harmonics. CON3, the ICSP header, is used to program IC1 and is not required if you are using a pre-programmed chip. The only remaining components in Building this unit is straightforward with most of the parts mounted on a PCB coded 04104151. Note that there are a number of blank component locations, as this PCB was designed for other uses as well. Fig.3 shows the parts layout on the PCB. Start by checking the resistor values with a DMM and fit them where shown. Follow with diodes D1 and D2; these are different types and are both orientated with their cathode stripes facing the bottom edge of the PCB. Next, fit the IC socket with its notched end towards the top of the board. Check that it’s sitting flat after soldering two diagonally opposite pins, then make the rest of the joints. Follow with the ceramic capacitors, trimpot VR1 and then the two regulators. Don’t get the latter mixed up and note that you will probably need to crank their leads out with small pliers before mounting them so that they fit the pads. If fitting the DC socket, do so now. Similarly, you can install pin header CON3 but note that it isn’t required if you have a pre-programmed chip. Now fit the two PCB stakes at lower right, followed by the tantalum and electrolytic capacitors. These capacitors are all polarised, with the longer (positive) leads all going towards the top of the board. If fitting CON3, lay the adjacent 100μF electrolytic capacitor over, otherwise you will have trouble plugging the PICkit programmer in. CON2 can now go in, making sure Table 1: Resistor Colour Codes o o o o o o o o siliconchip.com.au No.   3   1   3   1   2   1   1 Value 100kΩ 33kΩ 10kΩ 1kΩ 470Ω 22Ω 10Ω 4-Band Code (1%) brown black yellow brown orange orange orange brown brown black orange brown brown black red brown yellow violet brown brown red red black brown brown black black brown its wire entry holes go towards the nearest edge of the board. That done, trim about 10mm from the end of switch S1’s shaft, leaving it 30mm long as measured from the top of switch body. File off any burrs and check that the knob still fits, then mount S1 on the PCB. Be careful with S1’s orientation as there are two possible ways it can go in. The plastic locating spigot must go towards IC1 as shown in Fig.3 Once the switch is in, feed the battery snap leads through the two strain relief holes and solder them in place. Note that if you haven’t fitted CON1, you will also need to solder a wire link between its pad nearest the edge of the board and the vertical pad immediately to its left and slightly below. This replaces CON1’s internal switch. Without this, the circuit won’t get any power from the battery. The two LEDs are fitted at almost full lead length, with the base of their lenses 25mm above the top of the PCB (use a cardboard spacer). This allows them to just poke through the lid of the jiffy box. If you aren’t using a jiffy box, you could just push them all the way down onto the board. Either way, both anodes (the longer leads) go towards the left. We used a red LED for the clipping indicator (LED2, at left) and yellow for the operation/low battery indicator (LED1, at right) but you can change the colours if you want. You may need to adjust the current-limiting resistors to suit though. You can now plug microcontroller IC1 into its socket, ensuring it has the correct orientation, ie, pin 1 towards upper left. If your chip is blank, use Table 2: Capacitor Codes Value µF Value IEC Code EIA Code 1µF 1µF   1u0 105 100nF 0.1µF 100n 104 5-Band Code (1%) brown black black orange brown orange orange black red brown brown black black red brown brown black black brown brown yellow violet black black brown red red black gold brown brown black black gold brown April 2015  63 Total harmonic distortion is defined as the ratio of the RMS voltage of a signal’s harmonics to the RMS voltage of the signal itself (the signal normally being a sinewave). The traditional method for measuring the THD of a sinewave is to align a deep, adjustable notch filter with the fundamental frequency, measure the RMS voltage of the residual, then divide this by the RMS voltage of the signal. However, this calculation can also be done based on a spectral analysis of the signal. Spectral analysis breaks the signal down into a series of sinewaves with various frequencies, amplitudes and phases. When these sinewave components are summed, the original signal is reconstructed. We can find the fundamental by looking for the sinewave component with the largest amplitude and we can then find its harmonics at integer multiples of the fundamental frequency. The ratio of the sum of harmonic amplitudes to the fundamental amplitude then gives us the THD figure. Note that this is not THD+N since we’re only looking at the harmonic amplitudes and not the wideband noise (which would also be at frequencies below the fundamental and between the fundamental and harmonics). That all sounds relatively easy but there are quite a few tricks to it. First, we need to discuss the use of the Fast Fourier Transform method which is used to convert the sampled time-domain data to frequency-domain (ie, spectral data). The input to a Fourier Transform is typically a buffer with a power-of-two number of sample values, encoded as complex numbers. Normally the complex numbers would initially have a zero imaginary portion, ie, they are real numbers nominally in the range of -1 to 1 (we’re using some tricks here to get extra performance but we’ll explain them later; for now, assume that’s true). The Fourier Transform converts these complex numbers into another set of numbers of identical size, the magnitude of which indicate the amplitude of the component sinewaves at a set of evenly spaced frequencies. For example, say we have a 4096-entry buffer (212) and the sampling rate is 8192Hz. The magnitude of the resulting complex number at index #1 indicates the amplitude of the sinewave component at 1Hz, index #2 at 2Hz and so on, up to 2047Hz (ie, half the Nyquist limit). The complex “angle” of these values indicates the relative phase of the constituent sinewaves but we aren’t really interested in that. So you might expect that if you performed an FFT transformation on a pure sinewave at say 100Hz, you would be able to read out its amplitude at index #100 and all the other values would be zero, indicating the lack of any other frequencies in the signal. However, with the naive implementation of the FFT, as well as getting a positive magnitude at index #100, you also get lesser values at index #101, index #102, etc with decreasing values. The result is similar at lower indexes, ie, #99, #98, etc. In fact, you will get a non-zero value in every single “bin”. That’s because of the fact that in the 4096-sample window, the signal abruptly starts at sample #0 and ends at sample #4095. These sudden start and end transitions cause this “blurring” of the data. This problem is mitigated to a large extent by the practice known as “windowing” the data. This is akin to a piece of music which fades in at the start and fades out at the end – you lose the abrupt transitions at these points. There are infinitely different ways to do this (which vary by the rates of “fade-in” and “fadeout”) and depending on which windowing method you use, the result has different properties. Basically, different methods provide different compromises as to how much the “blurring” is reduced versus how much the magnitudes are altered. Popular windowing methods include Hann (also known as Hanning), Hamming, Blackman-Harris and Flat Top. If no such function is applied, this is known as a “Rectangular Window”. These is an excellent description of these methods at the following URL: http://en.wikipedia. org/wiki/Window_function The behaviour of some common windows is shown here, in images taken from that article. In each case, the left panel shows the function by which the input time-domain samples are multiplied. On the right is the sample output of an FFT for a pure sinewave with this windowing function applied. Note how slowly the function falls off from the peak with a rectangular window compared to the others. For the task at hand, we decided to use Flat Top because this makes measuring the exact amplitude at a given frequency easy. Basically, it guarantees that even for frequencies which fall between two “bins”, one of the bins will contain the correct value. The other will contain a similar or lesser value. This means we don’t have to do any complex summing to determine fundamental or harmonic amplitudes. For an explanation, see: http://www.dsprelated.com/ showarticle/155.php Flat Top has worse frequency resolution than most other windowing methods however since the harmonics are spaced apart nicely (by the fundamental frequency in fact), it isn’t really an issue. But there is another, more subtle (and less discussed) issue with windowing and this is that it also causes the resulting amplitudes to fall off at higher frequencies. Failure to compensate for this will cause under-estimation of distortion an in-circuit programmer to flash it now, via CON3. You can power the chip from the programmer if it has that capability (the PICkit3 does) – if not, apply DC power to CON1 or the battery snap. First, turn trimpot VR1 fully anticlockwise and apply the triangle-wave to CON2 with a peak-to-peak voltage close to 5V if possible. That done, apply power, switch S1 to position 2 and turn VR1 clockwise until either LED2 lights or you reach the end-stop. If LED2 lights, turn VR1 anti-clockwise until it just turns off. Now measure between TP1 and TP2. It may take a little while to settle but it should give a reading close to 1.2V (representing 12% distortion) and stay there. However, it may be slightly higher if your triangle-wave source is badly distorted. LED1 should flash at a few hertz, depending on the signal frequency (anywhere in the range of 20Hz-10kHz should be OK). If you don’t have a suitable signal Calculating Distortion Using A Fourier Transform Testing If you have a triangle-wave generator, you can test the unit quite easily. 64  Silicon Chip Windowing siliconchip.com.au due to apparently reduced harmonic amplitudes. Our simple solution to this problem was to run a Flat Top-windowed FFT on a series of sinewaves of equal amplitude, each of which was at a frequency centred on a bin, measure the resulting peak value and store its inverse in a correction table. By then multiplying the output of the FFT by this correction table, we cancel out the frequency-dependent windowing attenuation. Having sampled the data, applied the windowing function, performed the FFT and determined the fundamental frequency, we then look for the second harmonic at twice the fundamental frequency. We handle cases where the fundamental falls between bins using an estimation function. Normally, there will be a small but definite second harmonic spike and we then look at a 50% higher frequency for the third harmonic and so on. Each harmonic spike that is found improves the accuracy of the guess for the location of the next harmonic. It’s then just a matter of summing the squares of the resulting amplitudes, then dividing this by the amplitude of the fundamental and performing a square root to give the THD result. generator, you can use the same procedure with the signal fed in from a 9-12VAC plugpack instead. Expect a reading of around 300mV, ie 3%. If LED1 doesn’t flicker or the reading seems wrong, switch off and check for circuit faults. Assuming it’s all OK, you can optionally do a further test if you have a sinewave generator. Apply its signal to CON2 using the same procedure as above and you should get a low voltage reading at TP1 of around 30-100mV, representing the lower limit of the distortion measurement – 0.03-0.1%, depending on how pure the sinewave is. Note that if the unit can’t find a signal at all, the output voltage goes to 0V. This will be the case if the input signal amplitude is too low, given the siliconchip.com.au Improving efficiency We said above that the input to an FFT is normally a set of complex numbers with zero imaginary components. Our FFT algorithm is a 32-bit fixed-point inplace calculation with a 4096 window size. This means the input is 4096 x 32 x 2 bits (two 32-bit numbers for the real and imaginary part of each complex number), for a total of 32KB storage required. Our micro has 64KB RAM, leaving half for other stuff. Here the advantage of the in-place FFT becomes apparent; because the same buffer is used as the input and output and no temporary storage is required, we can have a larger window size than would otherwise be possible. But it’s actually possible to double the effective window size to 8192 samples without using any extra RAM. How you ask? Well, have a look at this explanation from Texas Instruments: http://processors.wiki.ti.com/index.php/Efficient_ FFT_Computation_of_Real_Input To start off, what you do is you take your 8192 samples and create 4096 complex numbers where the real and imaginary part of each consists of alternating sample values. Thus, the imaginary portions aren’t “wasted” by being filled with zeros. You then perform a normal FFT computation. Normally, half of the FFT output is “wasted” as the second half is identical to the first half (but reversed in order). With this method, the extra data is no longer duplicated and by convolving it with some sinewave coefficients, using the formulae provided by TI, we recover the full set of result vectors that we would have gotten with a twice-as-large window with a regular FFT. Don’t worry too much about understanding the mathematics behind this – it certainly works! setting of VR1. If a signal is detected but it is grossly distorted (eg, a square wave), then the output will peg at 3.3V. Putting it in a box If you’re planning on building the unit into the recommended UB3 jiffy box, it will snap into the integral ribs. All that’s required is three holes in the lid for S1 and the two LEDs, plus some April 2015  65 This is the view inside the completed instrument. The PCB snaps into integral plastic ribs inside the case, while the battery is sandwiched between a piece of foam and the case lid as shown. holes in the base for the signal input and output. For the lid, copy the front-panel label shown in Fig.4 and use this as a drilling template. You can then download the label in PDF format from the SILICON CHIP website, print it out, laminate it and glue it to the lid. The holes can be cut out using a sharp hobby knife. For the signal input, we drilled a hole adjacent to the location of CON2 and fitted a small rubber grommet. We then cut away a section of the grommet on the inside of the case so that the PCB would still fit properly (you probably don’t need a grommet; we just wanted to make sure the leads don’t fray from rubbing on the edges of the hole). For the output, we drilled two holes 19mm (0.75-inch) apart at the right- Using it There isn’t much to it, simply connect a 3-20VAC signal source (eg, an SILICON CHIP Sensitivity Signal Input: 20VAC Max. hand end of the box (centred on that end). We then fitted binding posts and soldered two strands of ribbon cable to the binding post lugs. The other ends of these leads were then soldered to TP1 & TP2. After passing the signal cable through the grommet and screwing it firmly into CON2, we dropped the board in the box, placing some nonconductive foam next to S1 (either side will do), connected the 9V battery and sat the battery on top of the foam. The lid was then attached which holds the battery in place and the knob the secured to S1’s shaft. 3rd Harmonic 2 Harmonic Even Harmonics nd Odd Harmonics THD Off Clip 66  Silicon Chip AC plugpack) to the signal input leads and turn S1 to its first stop, for the full THD measurement. Use a small flat-bladed screwdriver to readjust the sensitivity control if necessary, then connect the outputs to a DMM and calculate the distortion by dividing the voltage reading by 10 to get the percent figure. For example, a reading of 0.28V indicates 2.8% distortion. If you want to use the device for measuring audio signals, you may wish to reduce the 10kΩ resistor value at the top of VR1 however it should not go below 470Ω (higher if you will be probing signals above 20V peak). This is to protect IC1 from excessive current flow. In this case, you may wish to connect some sort of probe or SC clip leads to CON2. Fig.4: top lid label for the UB3 jiffy box. To make a reading, connect the signal up and simply rotate the knob to the required position. The output voltage will stabilise after a few seconds, once the unit has adjusted for the signal frequency and the output filter capacitor has finished charging. Operate/Low Battery siliconchip.com.au