An Embedded Sensor Node for the Surveillance of Power Quality

: The energy supply of o ﬃ ce buildings and smart homes is a key issue in the global energy system. The growing use of microelectronics-based technology achieves new devices for a more comfortable life and wider use of electronic o ﬃ ce equipment. On the one hand, these applications incorporate more and more sensitive electronic devices which are potentially a ﬀ ected by any external electrical transient. On the other hand, the existing electrical loads, which generally use electronic power systems (such as di ﬀ erent types of battery chargers, ballasts, inverters, switching power supplies, etc.), generate di ﬀ erent kinds of transients in their own electrical internal network. Moreover, improvements in the information of the state of the mains alternating current (AC) power line allows risk evaluation of any disturbance caused to permanently connected electronic equipment, such as computers, appliances, home security systems, phones, TVs, etc. For this reason, it is nowadays more important to introduce monitoring solutions into the electrical network to measure the level of power quality so that it can protect itself when necessary. This article describes a small and compact detector using a low-cost microcontroller and a very simple direct acquiring circuit. In addition; it analyzes di ﬀ erent methods to implement various power quality (PQ) surveillance algorithms that can be implemented in this proposed minimum hardware platform. Hence; it is possible to achieve cheap and low-power monitoring devices that can become nodes of a wireless sensor network (WSN). The work shows that using a small computational e ﬀ ort; reasonable execution speed; and acceptable reliability; this solution can be used to detect a variety of large disturbance phenomena and spread the respective failure report through a 433 MHz or 2.4 GHz radio transmitter. Therefore, this work can easily be extended to the Internet of Things (IoT) paradigm. Simultaneously, a software application ( PulsAC ) has been developed to monitor the microcontroller’s real-time progress and detection capability. Moreover, this high-level code (C ++ language), allows us to test and debug the di ﬀ erent utilized algorithms that will be later run by the microcontroller unit. These tests have been performed with real signals introduced by a function generator and superimposed on the true AC sine wave


Introduction
It is well known that the increasing introduction of electronic loads (e.g., ballasts, electric vehicle chargers, switching power supplies, etc.) in a worldwide scenario where the distributed energy resources are gaining greater presence is provoking a major concern in power quality (PQ) degradation.
Although an IoT sensor network allows a global data spread, the access delay to the Internet due to TCP-IP protocol could be slow in risk situations by electrical transients. This could be a disadvantage with respect to the wireless sensor network, where every node implements a radio-transmitter. A sensor-to-sensor connection via radio achieves more efficient coordination through the network.
Our main goal is to produce a simple estimator device which can report any basic information about the line state or alert when a dangerous disturbance occurred. The proposed module is oriented to detect the fundamental parameters related to the external electrical disturbances, as the transients which are generated in the consumer's own line. In this sense, the surveillance and protection of the state of the power line may be accomplished by a cooperative interaction among different nodes, which can be protection elements (e.g., a special circuit breaker node remotely operated) or simply measurement elements. Another possible application is to incorporate the sensor module inside the electrical appliances themselves, for self-protection and protection of adjacent equipment connected to the electrical network.
Considering the conclusions of the previous works our interest is in the design of devices that are as simple as possible. For this case, reduced use of electronics components is supposed, but it requires taking full advantage of the microcontroller resources. Considering the limited internal resources of this microcontroller, the algorithms must be implemented through coding in assembly language. In this first version, the proposed circuit measures only the voltage. Our purpose is to measure voltage transients in the electrical installation. Optionally, a current Hall sensor could be incorporated, but that was not the initial objective. However, the internal resources of this microcontroller cannot execute real-time routines, sampling voltage, current, and computing its respective results.
Therefore, the circuit proposed is a microcontroller-based voltage meter, directly connected to the LV power line, and running dedicated algorithms (low-level programming implemented).
Following this line, this article introduces, first, the sensor-node architecture and second, analyzes several algorithms to detect a lot of typical electrical transients. This proposal is the base of development of a low-cost node solution, conceived to implement an IoT node or a wireless sensor network. It is structured as follows. Section 2 shows a brief review of the detector circuit, the electrical parameters measurement, several processing techniques and the description of the electronic circuit to accomplish these actions. In Section 3, the physical system implementation is described. In Section 4, the results are detailed. Finally, the conclusions are presented in Section 5.

Sensor Node Architecture
The solution was conceived to facilitate the network installation and it consists of a sensor module connected to AC power sockets ( Figure 1a). Likewise, it could be installed inside the appliances, actuating as a self-protection mechanism, disconnecting when a dangerous transient is detected. The sensor node block diagram is depicted in Figure 1b. Each node is used as a real-time failure data logger. In this case, it is compulsory to include an independent real-time clock and to provide enough memory to implement an efficient data-logger for failure reporting. Moreover, wireless data communication is required for a couple of reasons. Firstly, the complexity and the installation cost are strongly reduced. Secondly, users and processing equipment must be electrically isolated from the sensor node.
Due to the widespread use of open hardware prototyping platforms such as Beagle-Bone, Raspberry-Pi or Arduino, we adopted the ATmega328 microcontroller [29] that is also the core of the various development boards in the market. Thus, the results can run on an Arduino or an equivalent platform (assembly language directly) or on other similar processors of the same Atmel manufacturer series. It is also possible the immediate transfer to other analogous micro-controllers from other manufacturers. In addition, many sensor node platforms have also integrated ATmega devices (Waspmote, Arduino-BT, WiSmote, Tnode, NanoQplus, PanStamp, Mica, Mica2Dot, BTnode, AVRaven, Cricket, Iris, etc.) [25]. Due to the widespread use of open hardware prototyping platforms such as Beagle-Bone, Raspberry-Pi or Arduino, we adopted the ATmega328 microcontroller [29] that is also the core of the various development boards in the market. Thus, the results can run on an Arduino or an equivalent platform (assembly language directly) or on other similar processors of the same Atmel manufacturer series. It is also possible the immediate transfer to other analogous micro-controllers from other manufacturers. In addition, many sensor node platforms have also integrated ATmega devices (Waspmote, Arduino-BT, WiSmote, Tnode, NanoQplus, PanStamp, Mica, Mica2Dot, BTnode, AVRaven, Cricket, Iris, etc.) [25].

Acquiring and Conditioning of Electrical Parameters
The sensor node involves the microcontroller and its internal resources (analog-digital converter (ADC), memory, timers, interruption mechanisms and comparators). Each node is situated at one concrete point of the installation and monitors local voltage transients.

Alternating Current (AC) Power Line Adapter
As depicted in Figure 2, the analog-to-digital conversion (ADC) is realized from an attenuator and rectifier adaptor (adding overvoltage protection, as Transil TM or TransZorb TM devices). Thus, the voltage at ADC input is a scaled value, smaller with respect to the no-rectified voltage present on the AC power line. The AC voltage divider introduces an attenuation factor of 57.5. In this way, a 230 V AC is represented in the ADC by 4 V DC. Regarding the IEC 61557-12 standard, referring to root mean square (RMS) and swell and dip measurement, the '120% Un' limit is equivalent to 276 V RMS. The maximum value measurable with this attenuator is 287 V RMS (ADC full scale). However, concerning IEEE STD 1159-2009, the maximum RMS voltage (swell cases) is higher than 400 V. To increase the range, a solution could be to use an additional attenuator, with a factor divider higher than 57.5 and connected to other ADC input available (e.g., a factor of around 100).
Processing from rectified voltage is proposed because the dynamic range of the ADC converter is doubled. In this sense, all the programming codes of the microcontroller will take into account the absolute value of the sinusoidal voltage, abs[V(t)], but it is necessary to know the original sign of every rectified half-wave. This function is achieved by utilizing an analog-comparator.

Acquiring and Conditioning of Electrical Parameters
The sensor node involves the microcontroller and its internal resources (analog-digital converter (ADC), memory, timers, interruption mechanisms and comparators). Each node is situated at one concrete point of the installation and monitors local voltage transients.

Alternating Current (AC) Power Line Adapter
As depicted in Figure 2, the analog-to-digital conversion (ADC) is realized from an attenuator and rectifier adaptor (adding overvoltage protection, as Transil TM or TransZorb TM devices). Thus, the voltage at ADC input is a scaled value, smaller with respect to the no-rectified voltage present on the AC power line. The AC voltage divider introduces an attenuation factor of 57.5. In this way, a 230 V AC is represented in the ADC by 4 V DC. Regarding the IEC 61557-12 standard, referring to root mean square (RMS) and swell and dip measurement, the '120% Un' limit is equivalent to 276 V RMS. The maximum value measurable with this attenuator is 287 V RMS (ADC full scale). However, concerning IEEE STD 1159-2009, the maximum RMS voltage (swell cases) is higher than 400 V. To increase the range, a solution could be to use an additional attenuator, with a factor divider higher than 57.5 and connected to other ADC input available (e.g., a factor of around 100).  Processing from rectified voltage is proposed because the dynamic range of the ADC converter is doubled. In this sense, all the programming codes of the microcontroller will take into account the absolute value of the sinusoidal voltage, abs[V(t)], but it is necessary to know the original sign of every rectified half-wave. This function is achieved by utilizing an analog-comparator. Considering a sine-wave input, if it is applied an averaging algorithm, we can obtain the RMS value using the V RMS and the average voltage, V avg , ratio given by V RMS /V avg = π/ 2 √ 2 = 1.111 ( Figure 3a).

Figure 2.
Alternating current (AC) power line attenuator and high-frequency equalization proposed for interfacing. A full-wave rectifying of a sine-wave permits an easy Vpeak, VRMS and Vavg interrelation.

Average Voltage Measurement
Considering a sine-wave input, if it is applied an averaging algorithm, we can obtain the RMS value using the VRMS and the average voltage, Vavg, ratio given by ( ) To get the arithmetic average value only a simple summation processing applied during the preceeding complete cycle is required, which for 50 Hz or 60 Hz is needed to just analyze one frame of 20 ms (50 Hz) or 16.7 ms (60 Hz). To simplify, it is not necessary to divide by N, the samples number: the final sum is just proportional with regard to N to the average amplitude. Any deformation of the signal shape will affect equally this final result and could be a failure indicator. However, to speed up the computation, it is possible to get the VRMS and Vavg taken as the result of the peak value measurement. This value can be acquired sequentially from a second ADC (Figure 3b). We assume that the input voltage is sinusoidal, without anomalies most of the time, except during transient events. Table 1 shows a list of classified phenomena according to IEEE-1159 recommendations. In the IEC 61557-12 are established test methods to assess them [4]. In general, a lot of these disturbances can be detected using time-domain methods instead of the frequency domain. On the other hand, high-frequency disturbances or oscillations require implementation of the Fourier transform or complex digital filtering, resulting in a high computational cost when we are using reduced feature processors. The evaluation of the peak and average voltage allows quick detection of some common electrical supply failures such as sag, swell and interruptions.

Signal Processing Techniques
Our goal is to achieve a compact sensor node employing minimal hard ware equipment. For this reason, the use of C++ language or machine code would allow accelerating the algorithms to To get the arithmetic average value only a simple summation processing applied during the preceeding complete cycle is required, which for 50 Hz or 60 Hz is needed to just analyze one frame of 20 ms (50 Hz) or 16.7 ms (60 Hz). To simplify, it is not necessary to divide by N, the samples number: the final sum is just proportional with regard to N to the average amplitude. Any deformation of the signal shape will affect equally this final result and could be a failure indicator. However, to speed up the computation, it is possible to get the V RMS and V avg taken as the result of the peak value measurement. This value can be acquired sequentially from a second ADC (Figure 3b). We assume that the input voltage is sinusoidal, without anomalies most of the time, except during transient events. Table 1 shows a list of classified phenomena according to IEEE-1159 recommendations. In the IEC 61557-12 are established test methods to assess them [4]. In general, a lot of these disturbances can be detected using time-domain methods instead of the frequency domain. On the other hand, high-frequency disturbances or oscillations require implementation of the Fourier transform or complex digital filtering, resulting in a high computational cost when we are using reduced feature processors. The evaluation of the peak and average voltage allows quick detection of some common electrical supply failures such as sag, swell and interruptions.

Signal Processing Techniques
Our goal is to achieve a compact sensor node employing minimal hard ware equipment. For this reason, the use of C++ language or machine code would allow accelerating the algorithms to real-time detection. We will focus on analyzing only easily implementable algorithms on a microcontroller-based platform. Mainly, the statistical techniques are easy to implement. Unquestionably, it is very difficult to obtain real-time FFT computed in a microcontroller with limited resources. For this reason, the selection of the algorithms must be the main purpose.

Statistical Processing Techniques
Frequently, statistical variables from first-order moments (such as variance and the mean) are used. This does not exclude the possibility to apply higher-order statistics (HOS) and Kurtosis procedures. However, the HOS evaluation is more oriented to harmonic analysis (spectral kurtosis) [5][6][7]. Basically, the arithmetic average value per cycle and the previous average calculated during many cycles provide information about the voltage waveform integrity and the supply continuity (interruptions). Therefore, it is possible to apply this detection method to some of the phenomena listed in Table 1a.
The application of statistical analysis requires then calculating moments over a whole period. As N (samples number) is a constant value and the sampling is synchronized every period, the variance of the rectified signal is given by: The knowledge of the arithmetic average value reveals indirectly the effective total surface value of the waveform previous cycle and, thus, large voltage variations as well as micro-interruptions. It would not be applied to detect sudden transients that momentarily affect to the sinusoidal waveform. Although the algorithm is very simple, the HOS computational effort is really notable.

Detection Algorithm Using Kalman Filter
A Kalman filter [30] behaves as a predictive element to develop the effective comparison of the regular signal, with a momentary perturbed sine wave. This algorithm attempts to minimize the covariance error between every captured input sample and the corresponding expected output value with respect to a previous wave form.
For the prediction of the sine wave voltage given V(t) = U sin(ωt) (representing an AC voltage with U = √ 2 · V RMS the peak value, without disturbances), can be established as an equation in the state space considering the amplitude U(t) as the main parameter to be estimated and, secondly, the frequency variations of this waveform. In order to form a system of at least two matrix equations, we compose the orthogonal state equations according to the signal itself (sine) and 90 degrees out of phase (cosine) obtaining both equations: where ω = 2πf is the sine wave frequency, U is the estimated voltage value and x 1 (k) and x 2 (k), state functions at time k. In order to simplify, it can be considered an initial null delay (θ = 0). The next state (k + 1) can be established using the differential ∆t, after of t k time. By making use of the incremental time t k+1 = t k + ∆t, x 1 (k + 1) and x 2 (k + 1) will be the next states. Employing trigonometric relationships for sums of sine and cosine, the Equation (2) can be simplified as follows: (3) and finally, we have: Since the output variable of interest is precisely the state x 1 (k), the equation indicating the measured value output, z(k), is exactly the state x 1 (k) itself and the superimposed noise υ(k): where υ(k) is white noise with null mean value. When a transient is superimposed, then this disturbance υ(k) is now not Gaussian, which causes discrepancy with respect to the previously estimated voltage. The Kalman filter allows a sufficient prediction of sinusoidal voltage from the previously sampled data. By comparing a recently sampled period with abnormalities (disturbances) with a previously predicted sine wave without apparent irregularities, it will generate a differential value when detecting any mismatch between the two periods (with and without transient pulses).

Detection Algorithm Using the Helmholtz Equation
Given that function V(t) = Usin(ωt) representative of the AC power line is an n-times differentiable function, it is possible to set it into an one-variable ordinary differential equation, as the one-dimensional Helmholtz mathematical expression, and this can by written as: Annulment of F in Equation (6) is a method to find variations of f (t) when this function is a periodic signal such as the analyzed sine wave. The proof is obvious in the linear version case of F: given f (t) = Usin(ωt), we only need to derive the sinusoidal function consecutively to reach the conclusion that K = ω; under normal conditions, the contrasting of the sine function with its second derivative yields a null value. Once a value of K has been found for the undistorted sinusoidal function, any shape deviation with respect to the original (due to some disturbance) will affect to the function f (t) which will not be now a perfect sine wave, and consequently, Equation (6) is not verified.
When a discrimination threshold appropriate is exceeded, an alarm signal is notified announcing the disturbances presence. For the discrete case, utilizing the discrete-time variable (t→∆t) and where is now applied the voltage V(n·∆t) = Usin(ω·n·∆t), with peak value U = √ 2 ·V RMS , without disturbances, for every instant n = 0,1,2, . . . . the derivative function is given by: and the second derivative function: which can be simplified in the following expression: Applying the equality expressed in Equation (6), we have: If we consider K = −1, the function is canceled when the two terms are equal, or expressed otherwise, the function g(t) given by: that is, equal to sin(ω· t), which is equivalent to the initially sine wave function. Therefore, when the original f (t) slightly differs from an ideal sin(ω·t) function, the homologous, g(t), will not verify the sinusoidal relationship. Since sin(w·t) represents a previous cycle sampled from the next sin(ω·(t + ∆t)), we can express the function g(t) as an equation in differences, G(n), with a sampling interval (n·∆t) of the acquired power sequence V(n·∆t) that can be rewritten as: where ∆t = 1 / F S is a very small number. Using the Z −2 operator, the definitive equation to be algorithmically implemented is:

Detection Algorithm by Contrasting with Successive Previous Integrations
If during a long time interval, the acquired sinusoidal input is integrated (each sample with its respective previous one of similar phase), the V acc [n] array of the resulting waveform should contain a filtered AC power sine wave without any transient.
Now, if the power line is unexpectedly affected (transients, disturbances, etc.) different instantaneous input samples, V i (t), will differ with respect to the previous arithmetic averages, V acc (t), for those same array indexes. These differences can detect any anomaly when implementing this comparison algorithm:

Hardware Platform
Our contribution is a low-cost and compact sensor circuit. Therefore, it is required to use the smallest number of components. The prototype has a small size (two cards, staked, 80 × 60 mm) that can be inserted into a plastic box and directly connected to the electrical socket. This purpose suggests designing an optimized hardware platform, capable of detecting disturbances in real time and avoiding the inclusion of specific integrated circuits. This sensor node is mainly oriented to measure the voltage of the power line directly using a balanced AC voltage divider. The circuit is auto-powered by the same power line where it performs the monitoring work ( Figure 4b) and optionally, it can integrate supercapacitors to provide autonomy in long interruption failures.
The processor ATmega328 from Atmel (up to 20 millions of instructions per second (MIPS) is adequately fast for that price range) has been selected. This integrated circuit is the core component of the Arduino prototyping platforms. This choice allows us to translate the validated conclusions from our prototype toward others similar open hardware platforms. A real time clock (Maxim DS1307 powered by a back-up battery) drives the timing for the failure data-logger. The prototype also includes a buzzer and two light-emitting diodes (LEDs) to show the current state of the node and to alert of any recent failure.
A wireless communication emitter (AM modulation at 433 MHz) is added to transmit the results. Optionally, a BlueTooth or WiFi module can be connected. This communication method allows the formation of the network and the galvanic isolation since the modules work directly with the AC line voltage. Additionally, an infra-red communication receiver has been included only for purposes of wireless configuration from a computer. A second circuit board contains the attenuators, edge detector (synchronism), rectifier and equalizer for the direct measurement of the main power voltage. Both cards are connected in a sandwich mode (stacked) to reduce the overall size of the equipment and achieve greater galvanic isolation from the AC power card.  The processor ATmega328 from Atmel (up to 20 millions of instructions per second (MIPS) is adequately fast for that price range) has been selected. This integrated circuit is the core component of the Arduino prototyping platforms. This choice allows us to translate the validated conclusions from our prototype toward others similar open hardware platforms. A real time clock (Maxim DS1307 powered by a back-up battery) drives the timing for the failure data-logger. The prototype also includes a buzzer and two light-emitting diodes (LEDs) to show the current state of the node and to alert of any recent failure.
A wireless communication emitter (AM modulation at 433 MHz) is added to transmit the results. Optionally, a BlueTooth or WiFi module can be connected. This communication method allows the formation of the network and the galvanic isolation since the modules work directly with the AC line voltage. Additionally, an infra-red communication receiver has been included only for purposes of wireless configuration from a computer. A second circuit board contains the attenuators, edge detector (synchronism), rectifier and equalizer for the direct measurement of the main power voltage. Both cards are connected in a sandwich mode (stacked) to reduce the overall size of the equipment and achieve greater galvanic isolation from the AC power card.
In order to avoid electric risk during the preliminary debug and tests, a transformer has been inserted to isolate the main power voltage and it allows direct connection from the prototype to the computer, through the universal serial bus (USB) port.

Measurement Setup
The sensor node must be connected directly to main power line. The attenuator adapts the AC power voltage to the microcontroller ADC converter. Figure 4a shows an oscilloscope image of the rectified sine wave (yellow) at the ADC input. This ADC voltage is scaled over 4 V peak when a 230 V RMS nominal voltage is present in the power line. It can also be seen the sync pulses (green, every zero crossing) and the peak value, Vpeak, using hardware method (rectifier and RC-filter). In order to avoid electric risk during the preliminary debug and tests, a transformer has been inserted to isolate the main power voltage and it allows direct connection from the prototype to the computer, through the universal serial bus (USB) port.

Measurement Setup
The sensor node must be connected directly to main power line. The attenuator adapts the AC power voltage to the microcontroller ADC converter. Figure 4a shows an oscilloscope image of the rectified sine wave (yellow) at the ADC input. This ADC voltage is scaled over 4 V peak when a 230 V RMS nominal voltage is present in the power line. It can also be seen the sync pulses (green, every zero crossing) and the peak value, V peak , using hardware method (rectifier and RC-filter).

Dynamic Range
Dynamic range is optimized for the ADC full-range (10 bits and 5 V DC input max) to represent the rectified full-wave. It is planned that this maximum ADC range, 5 V, represents a 25% higher input than the service voltage (230 V AC previously scaled by the input attenuator, see Figure 2) and 287 V RMS (ADC full scale).
With this factor, we have 4 V DC (equivalent 230 V AC) into the ADC converter. Regarding the IEC 61557-12 standard, the '120% Un' limit referred to is equivalent to 276 V RMS. For specified cases in IEEE-1159 (Table 1) as swell and over-voltage, this recommendation considers a maximum amplitude of 1.8 p.u., that regarding 230 V power line, can estimate shall rise around 414 V RMS (or 585 V peak). This will develop a peak value into the AD converter of 7.2 V (the maximum permissible ADC input level is 5 V). Therefore, a Zener protection circuit must limit it to a maximum voltage of 5.1 V. Voltage peaks above the 1.25 p.u. will not be evaluated quantitatively by our detector (only qualitatively). In Section 2.1.1, an optional measurement range increase is proposed.

Synchronous Conversion and Sampling Rate
The conversion synchronized every zero crossing of the input voltage avoids the requirement of windowing techniques and leads to simple comparisons of 256 samples per block, sequentially captured every period. Thus, similar samples successively occupy the same phase locations in a conversion data array (a solution already proposed by Artioli et al. [16]). The crossing detection is very easy using an analog-comparator or an opto-coupler. This provides constantly an array size of N = 2 8 = 256 numbers in all applied algorithms. Therefore, the conversion speed is set to 256 samples per period of the input voltage (50 or 60 Hz). This quantity is a compromise between resolution and memory size, and affects both data arrays of samples and of intermediate results. For a power line of 50 Hz, this supposes a sampling rate F S = 256 × 50 Hz = 12.8 kHz. This frequency allows an accurate representation of the full-wave rectified sine wave of 50 Hz, but limits the bandwidth of transients at about 6.4 kHz according to Nyquist limit.

The Absence of the Anti-Aliasing Filter
For simplicity, the essential anti-aliasing filter was not included in the data acquisition sequence. Since the monitor mission is to detect disturbances qualitatively, we expect to capture easily high-frequency transients outside the Nyquist range. We take advantage of the overlapping phenomenon (a consequence of Shannon's theorem itself) considering the mirrored copies of the higher spectral components, to the low side, with respect to the sampling frequency point, F S .
Thus, any high-frequency transient that exceeds the requirements of band-pass framed below Nyquist frequency, F S (e.g., some perturbation frequencies above of F S /2 = 12800 Hz / 2 = 6400 Hz) should generate errors in the conversion process and shall appear as spectral components into the sampling frequency band due to overlap effect (lower sideband in a heterodyning phenomenon, Figure 5). Consequently, this mirrored component, below than F S frequency, can also reveal the disturbances.

Application Software for Essays of Algorithms and Test-Bench
An application called 'puls.AC' was developed to verify the algorithm implementations and the prototype electronic board ( Figure 6). This software tool has been programmed in C++ language employing the LabWindows/CVI environment from National Instrument TM . If the procedures are written using exclusively an integer-numbers based programming code, the detection algorithms can be directly translated and tested in assembler language for ATmega328 processor (Atmel™ company also provides a C free compiler for the developer community using its own microcontrollers). By Shannon's theorem (graphically expressed in Figure 5), generally if aliasing exists, the transient component located above F S /2 is now reflected in the Nyquist sampling area, within the spectrum band conversion between 0 Hz and F S (overlap). Under these circumstances, some disturbance components will be qualitatively processed and the algorithms can indicate the presence of anomalies. However, although this simplification allows detection of transient pulses above the sampling frequency, cannot correctly determine the event frequency: it is only possible to determinate that this disturbance had occurred.

Application Software for Essays of Algorithms and Test-Bench
An application called 'puls.AC' was developed to verify the algorithm implementations and the prototype electronic board ( Figure 6). This software tool has been programmed in C++ language Energies 2019, 12, 1561 12 of 20 employing the LabWindows/CVI environment from National Instrument TM . If the procedures are written using exclusively an integer-numbers based programming code, the detection algorithms can be directly translated and tested in assembler language for ATmega328 processor (Atmel™ company also provides a C free compiler for the developer community using its own microcontrollers).
qualitatively identified into the below zone from the Nyquist frequency. (Simulated by Octave TM (GNU) to N = 256 points/period, FS = 12.8 kHz and 50 Hz equivalent FFT spectral resolution).

Application Software for Essays of Algorithms and Test-Bench
An application called 'puls.AC' was developed to verify the algorithm implementations and the prototype electronic board ( Figure 6). This software tool has been programmed in C++ language employing the LabWindows/CVI environment from National Instrument TM . If the procedures are written using exclusively an integer-numbers based programming code, the detection algorithms can be directly translated and tested in assembler language for ATmega328 processor (Atmel™ company also provides a C free compiler for the developer community using its own microcontrollers). Figure 6. LabWINDOWS™ /CVI-C ++ test bench application that shows real-time acquired data from the hardware prototype.

Data Acquisition State Machine
To maximize the processing speed, a fast state machine was implemented using the incorporated features into the microcontroller, mainly the internal interrupting architecture. The acquiring process starts every detected zero crossing. An internal clock counter is configured to Figure 6. LabWINDOWS™ /CVI-C ++ test bench application that shows real-time acquired data from the hardware prototype.

Data Acquisition State Machine
To maximize the processing speed, a fast state machine was implemented using the incorporated features into the microcontroller, mainly the internal interrupting architecture. The acquiring process starts every detected zero crossing. An internal clock counter is configured to generate software interruptions during an equivalent time to the sampling period. This interruption routine forces the system to acquire an input voltage sample and save it. A counter variable allows for the conversion of a frame of up to 256 sampled data. The available free time between adjacent-acquisitions permits the processor to run the required detection algorithms (Figure 7). When the synchronism is different to 20 ms (50 Hz), the internal counter generates a count overflow. This event marks an anomaly situation. generate software interruptions during an equivalent time to the sampling period. This interruption routine forces the system to acquire an input voltage sample and save it. A counter variable allows for the conversion of a frame of up to 256 sampled data. The available free time between adjacent-acquisitions permits the processor to run the required detection algorithms (Figure 7). When the synchronism is different to 20 ms (50 Hz), the internal counter generates a count overflow. This event marks an anomaly situation.

Algorithms' Implementation Codes
Three computational strategies have been considered: 3.2.1. Detection Algorithm Based on the Helmholtz Equation

Algorithms' Implementation Codes
Three computational strategies have been considered:

Detection Algorithm Based on the Helmholtz Equation
In this case, it was implemented the comparison algorithm of the second derivative of the input sine wave sampled. For a given sampling rate of ∆t = 78.12 µs, is ∆t 2 ≈ 0. The method was previously exposed and here is implemented (pseudocode) according to the conclusion given by Equation (13)

Algorithms' Implementation Codes
Three computational strategies have been considered:

Detection Algorithm Based on the Helmholtz Equation
In this case, it was implemented the comparison algorithm of the second derivative of the input sine wave sampled. For a given sampling rate of Δt = 78.12 μs, is Δt 2 ≈ 0. The method was previously exposed and here is implemented (pseudocode) according to the conclusion given by Equation (13)

Kalman Filter Implementation
As discussed in Section 2.2.1., the minimized Kalman filter to estimate simply amplitude A of the sinusoid A sin(ω•t), leads to the implementation of Equations (4) and (5), implementing the following pseudocode sequence:

Kalman Filter Implementation
As discussed in Section 2.2.1., the minimized Kalman filter to estimate simply amplitude A of the sinusoid Asin(ω·t), leads to the implementation of Equations (4) and (5), implementing the following pseudocode sequence:

Algorithms' Implementation Codes
Three computational strategies have been considered:

Detection Algorithm Based on the Helmholtz Equation
In this case, it was implemented the comparison algorithm of the second derivative of the input sine wave sampled. For a given sampling rate of Δt = 78.12 μs, is Δt 2 ≈ 0. The method was previously exposed and here is implemented (pseudocode) according to the conclusion given by Equation (13)

Kalman Filter Implementation
As discussed in Section 2.2.1., the minimized Kalman filter to estimate simply amplitude A of the sinusoid A sin(ω•t), leads to the implementation of Equations (4) and (5), implementing the following pseudocode sequence: Three arrays are required: one to contain the instantaneous samples input voltage (256 words) and two more to the consecutive previous periods (512 words); two fixed-point multiplications are required too.

Detection Algorithm by Contrasting with Successive Previous Integrations
This method was previously shown and requires the successive integration of the input sine-wave captured. In fact, an averaging algorithm successively and repeatedly applied to a sinusoidal voltage with transients leads towards a pure waveform without disturbances. Every voltage sample newly acquired is compared continuously with the accumulative previous average value, with an identical phase, by making use of the expression: sinusoidal voltage with transients leads towards a pure waveform without disturbances. Every voltage sample newly acquired is compared continuously with the accumulative previous average value, with an identical phase, by making use of the expression: (16) where

Results
To verify the sensor-node prototype performance and to check the different detection algorithms, three routines only were implemented. Therefore, a basic set of different transient pulses and oscillations has been applied according to some conditions included in the IEEE-1159 recommendation (Table 1). Specifically, the Helmholtz equation method, the Kalman predictor, and the successive integration (LPF) and comparison method have been compared. These three techniques have shown that they are easily implementable and give an efficient response to the failure detection.
To generate real transients, we used a standard analog function generator Tektronix CFG250 and an ad-hoc circuit board with manual switches (Figure 8) that allow us to enter the following scaled disturbances: • VRMS decreased by approximately half of the nominal 230 V AC (−54.7%) (0.6 p.u. momentary sag). • Half-cycle missing or a sag in an amount bigger than 10 % (instantaneous sag, 0.5 cycles > 0.1 p.u.). • Swelled peak voltage at 13.35% over the 311 V nominal peak (1.13 p.u. momentary swell).
• Permanent or intermittent disturbance signals, as sine or square waves, with different amplitude levels and frequencies, from the function generator. • To emulate impulsive transients of different duration, square pulses of low, medium and high frequency (10 Hz, 1 kHz, 10 kHz and 100 kHz) and amplitude up to 10% of Vpeak (corresponding to 0.1 p.u., with respect to the rectified voltage and using a voltage divider) were injected. To emulate harmonic distortion a 200 Hz sine low-amplitude component can also be superimposed. Different sinusoidal functions (10 Hz to 10 kHz), approximately 10% (0.1 p.u.) amplitude with respect to the rectified voltage peak value were used for oscillations simulation.

Results
To verify the sensor-node prototype performance and to check the different detection algorithms, three routines only were implemented. Therefore, a basic set of different transient pulses and oscillations has been applied according to some conditions included in the IEEE-1159 recommendation (Table 1). Specifically, the Helmholtz equation method, the Kalman predictor, and the successive integration (LPF) and comparison method have been compared. These three techniques have shown that they are easily implementable and give an efficient response to the failure detection.
To generate real transients, we used a standard analog function generator Tektronix CFG250 and an ad-hoc circuit board with manual switches (Figure 8) that allow us to enter the following scaled disturbances: The adjustable 'threshold' level permits us to modify the failure detection sensitivity. To achieve the maximum, sensitivity should be taken to the lowest level possible, but avoiding the occurrence of false alarms.

Helmholtz-Based Method
1. Voltage fluctuations testing: the slow voltage variation generates small differences values in the derivative algorithm given by Equation (13). This method is insensitive for phenomena such as The adjustable 'threshold' level permits us to modify the failure detection sensitivity. To achieve the maximum, sensitivity should be taken to the lowest level possible, but avoiding the occurrence of false alarms.

1.
Voltage fluctuations testing: the slow voltage variation generates small differences values in the derivative algorithm given by Equation (13). This method is insensitive for phenomena such as sag or swell voltage.

2.
The process is not sensitive to brief changes such as micro-interruption or sudden half-cycle missing failures (Figure 9a) because the algorithm requires a full period to compute completely the array of the sampled input voltage.
1. Voltage fluctuations testing: the slow voltage variation generates small differences values in the derivative algorithm given by Equation (13). This method is insensitive for phenomena such as sag or swell voltage. 2. The process is not sensitive to brief changes such as micro-interruption or sudden half-cycle missing failures (Figure 9a) because the algorithm requires a full period to compute completely the array of the sampled input voltage. 3. When a square voltage (1 kHz or 100 Hz) is superimposed ( Figure 9b) the algorithm presents a good detection response (relative threshold = 5% adjustable from 0 up to 30%). It also works correctly for high frequencies (10 kHz and 100 kHz, even greater than FS (Subsection 4.4) To detect up to 1 kHz order sinusoidal oscillation injected, it is necessary to decrease the detection threshold up to 2%. This causes any false alarms even when the AC voltage is normal (undistorted). In this situation, it is impossible to detect the 4th harmonic distortion using this method. However, it works properly for higher frequencies (as 10 kHz and 100 kHz > FS) (Figure 9c).

3.
When a square voltage (1 kHz or 100 Hz) is superimposed ( Figure 9b) the algorithm presents a good detection response (relative threshold = 5% adjustable from 0 up to 30%). It also works correctly for high frequencies (10 kHz and 100 kHz, even greater than F S (Section 4.4) To detect up to 1 kHz order sinusoidal oscillation injected, it is necessary to decrease the detection threshold up to 2%. This causes any false alarms even when the AC voltage is normal (undistorted). In this situation, it is impossible to detect the 4th harmonic distortion using this method. However, it works properly for higher frequencies (as 10 kHz and 100 kHz > F S ) (Figure 9c).

1.
Voltage fluctuations testing: Figure 10a shows a half-cycle sudden failure (blue). Thus, the filter predicts the half-cycle missing (magenta) and consequently detects the failure (the green line show the error value; the red one is the computed comparator result). Likewise, it also detects slow disturbances with a presence for a longer time than the period of the signal.

2.
Since detection is a strategy based on prediction, the code correctly detects the square transients (Figure 10b). When a square wave voltage is superimposed (frequencies of 10 Hz to 1 kHz), the algorithm presents a good differentiation (up to a relative threshold level of 6%, adjustable).

3.
Injecting a sine wave disturbance higher than 10 Hz, the system shows a good response, for different threshold values ( Figure 10). In this case, it is possible to detect the harmonic distortion (4th-harmonic of the 50 Hz sine wave).
2. Since detection is a strategy based on prediction, the code correctly detects the square transients (Figure 10b). When a square wave voltage is superimposed (frequencies of 10 Hz to 1 kHz), the algorithm presents a good differentiation (up to a relative threshold level of 6%, adjustable). 3. Injecting a sine wave disturbance higher than 10 Hz, the system shows a good response, for different threshold values (Figure 10.). In this case, it is possible to detect the harmonic distortion (4 th -harmonic of the 50 Hz sine wave).

Method of Successive Integrations (LPF) and Comparison
1. Voltage fluctuations testing: since the algorithm obtains an arithmetic average of each similar phase sample (during previous periods), this process is slow with respect to any very fast event that may occur in the immediate preceding half-cycle. In these situations, sometimes the algorithm can produce an erroneous result. However, since the final average is obtained from the immediately previous samples, it works quite accurately when sudden events occur, lasting longer than a half-cycle. In this case, a swell voltage variation is detected perfectly. 2. This method works properly when a square disturbance is injected (Figure 11b). For square wave voltage superimposing tests (10 Hz and 1 kHz), the algorithm presents a good differentiation and detection (using a threshold level of 6%). If the phenomenon is persistent, the transient will gradually dissolve in the averaged waveform array (due to the filter effect). 3. For low-frequency sinusoidal oscillation (hundreds of Hz), the procedure has an equally good detection response because it compares the current signal samples with the previous averaged sine wave and without transients (Figure 11c). It could also detect the harmonic distortion (presence of the 4th harmonic).

1.
Voltage fluctuations testing: since the algorithm obtains an arithmetic average of each similar phase sample (during previous periods), this process is slow with respect to any very fast event that may occur in the immediate preceding half-cycle. In these situations, sometimes the algorithm can produce an erroneous result. However, since the final average is obtained from the immediately previous samples, it works quite accurately when sudden events occur, lasting longer than a half-cycle. In this case, a swell voltage variation is detected perfectly.

2.
This method works properly when a square disturbance is injected (Figure 11b). For square wave voltage superimposing tests (10 Hz and 1 kHz), the algorithm presents a good differentiation and detection (using a threshold level of 6%). If the phenomenon is persistent, the transient will gradually dissolve in the averaged waveform array (due to the filter effect).

3.
For low-frequency sinusoidal oscillation (hundreds of Hz), the procedure has an equally good detection response because it compares the current signal samples with the previous averaged sine wave and without transients (Figure 11c). It could also detect the harmonic distortion (presence of the 4th harmonic).

Performance in High Frequency
To verify the effectiveness of the ADC and sampling bypassing the antialiasing filter, we compare results of the three previous algorithms, considering an oscillation injected of 10 kHz, near to sampling frequency ( Figure 12). The response was also good for the highest frequencies (up to 100 kHz).

Performance in High Frequency
To verify the effectiveness of the ADC and sampling bypassing the antialiasing filter, we compare results of the three previous algorithms, considering an oscillation injected of 10 kHz, near to sampling frequency ( Figure 12). The response was also good for the highest frequencies (up to 100 kHz). Figure 11. Integrator (LPF) and comparator method (Blue line: sampled input voltage; magenta: accumulative previous-integration (average); gray line: difference; Red line: error). (a) Swell: only detect half-cycle to full-cycle correcting cases. Detected disturbances: 118 D./cycle. (b) Square wave superimp., 10% of Vpeak, 100 Hz, relative threshold 5%, 111 detections/cycle. (c) Oscillation, sine, 100 Hz, 10% of Vpeak, and threshold level to 5%, up to 88 detections/cycle.

Performance in High Frequency
To verify the effectiveness of the ADC and sampling bypassing the antialiasing filter, we compare results of the three previous algorithms, considering an oscillation injected of 10 kHz, near to sampling frequency ( Figure 12). The response was also good for the highest frequencies (up to 100 kHz).  Table 2 summarizes the different results for each method discussed in this paper. Attending to the results, the Kalman algorithm has a better transient detections response. However, it represents a slight implementation complexity compared to other implemented algorithms.
The integration (LPF) and comparison method requires several previous integrations cycles to a precise detection. For this reason, it works incorrectly in half-cycle disruption failures. For this case, it is easy to implement an additional algorithm based on peak value measurement.
Similarly, the Helmholtz-based method does not detect voltage variations cases. Any additional algorithm can be used to mathematically analyze the peak voltage variations.

Conclusions
This work presents a low-cost sensor-node supported on a microcontroller platform. It is aimed to be integrated into a cooperative wireless sensor network. In order to simplify, an attenuator-rectifier adapter was proposed to connect the analog-to-digital converter to the power line. The rectifier process improves the dynamic range of the ADC, but introduces a low-intensity spectral content in 200 Hz and with lower intensity, in 400 Hz.  Table 2 summarizes the different results for each method discussed in this paper. Attending to the results, the Kalman algorithm has a better transient detections response. However, it represents a slight implementation complexity compared to other implemented algorithms. The integration (LPF) and comparison method requires several previous integrations cycles to a precise detection. For this reason, it works incorrectly in half-cycle disruption failures. For this case, it is easy to implement an additional algorithm based on peak value measurement.
Similarly, the Helmholtz-based method does not detect voltage variations cases. Any additional algorithm can be used to mathematically analyze the peak voltage variations.

Conclusions
This work presents a low-cost sensor-node supported on a microcontroller platform. It is aimed to be integrated into a cooperative wireless sensor network. In order to simplify, an attenuator-rectifier adapter was proposed to connect the analog-to-digital converter to the power line. The rectifier process improves the dynamic range of the ADC, but introduces a low-intensity spectral content in 200 Hz and with lower intensity, in 400 Hz.
Several simple processing algorithms were also analyzed, implemented and tested to assess the transient detection capability and specific oscillation failures (PQ). In order to accelerate the computational work, it was essential to execute integer mathematical algorithms. The search and selection of implementable algorithms and real-time achievement is an additional difficulty. Therefore, these small integrated systems could act correctly as very low-cost and low-power instruments to become sensor nodes. Frequency, RMS voltage and transient voltage measurements are feasible. The ADC (10 bits) resolution could comply with some standards as a lot of IEC-61557-12 specific paragraphs.
As the hall sensor was not included, it is not achievable at current or power measurements. However, the feature of simplicity makes them ideal parts of a PQ wireless sensor network.
In addition, a physical prototype based on an ATmega-328 microcontroller was built to verify the ideas and machine codes previously considered. It can also affirm that the use of embedded resources in simple microcontroller devices (ADC, interrupt vectors, counters, etc.) improves real-time execution performance. This prototype allows us to verify numerous detector algorithms and if necessary, we could replace the microcontroller architecture (e.g., replace ATmega by an ARM processor).
A software application (C++, LabWindows TM ) was developed and employed as an algorithms test-bench. Thus, it was possible to test the different detection methods described in this paper and to check the efficiency of each algorithm.
With this help, and as evidenced in Table 2, it can be considered that: • In order to achieve a high penetration of sensor nodes, low-cost platforms are essential.

•
For this reason, a special design is required, choosing low-energy and inexpensive hardware ad-hoc platforms and implementing specific algorithms to maximize the device performance.

•
The 2nd-derivative Helmholtz method is quite sensitive to high-frequency interferences (brief oscillations) or pulses, while it is very insensitive to slow changes (harmonic distortion, sag or swell voltage).

•
The Kalman filter option is the most effective and is able to show all kinds of anomalies that have been tested. The disadvantage is that it demands more memory and requires much more code implementation complexity.

•
The 'integration (LPF) and comparison' method detects correctly for slow voltage variation or high-frequency disturbances (swell, sag, oscillations or short pulses, etc.). However, it is not capable of detecting short voltage variations with a shorter duration of a half cycle due to the integration time.
Future works may be conducted to complete the sensor network, increasing the number of nodes, to exploit the individual measurements acquired. It would also be interesting to design a breaker-node (remotely controlled) that disconnects a local section when an excessive phenomenon occurs and is detected by a remote sensor-node. In this way, this node could disconnect the power when another sensor node detects an anomaly (via radio 433 MHz).
Moreover, specific pattern recognition techniques may be considered for increasing nodes measurement capability and prediction. Thus, the node could allow predicting some anomalies.