tures, namely equal clock frequency up to 16 MHz, operational voltage range between 2.7 to 5.5 V, 32 kB of flash memory (enough to store the firmware and processing code), 2 kB (ATmega328P)/2.5 kB (ATmega32U4) of static random-access memory (SRAM) (to store the main variables and acquisition samples) and an analog-to-digital unit (ADC) with 10-bit resolution, the core of the system. Both the Uno and Leonardo boards were supplied through the local-PC connection via USB interface, and the default settings were used, meaning the reference voltage (*V*REF) is the internal voltage source of 5 V. *Sensors* **2022**, *22*, x FOR PEER REVIEW 4 of 27

**Figure 1.** Equivalent circuits for the four operation modes available to configure each analog input/output (I/O) port. (**a**) mode 1, floating input. (**b**) mode 2, pull-up input. (**c**) mode 3, low output. (**d**) mode 4, high output. Each equivalent circuit is adapted from the schematics provided in the datasheets. (**e**) Block diagram of the proposed measurement system, including the serial communication and voltage source through USB interface to local PC, flash and SRAM memory, internal voltage source, and internal circuitry to program I/O ports to digital or alternate functionalities. (**f**) Equivalent circuit of two analog I/O ports bridged with a load impedance (ZLOAD). **Figure 1.** Equivalent circuits for the four operation modes available to configure each analog input/output (I/O) port. (**a**) mode 1, floating input. (**b**) mode 2, pull-up input. (**c**) mode 3, low output. (**d**) mode 4, high output. Each equivalent circuit is adapted from the schematics provided in the datasheets. (**e**) Block diagram of the proposed measurement system, including the serial communication and voltage source through USB interface to local PC, flash and SRAM memory, internal voltage source, and internal circuitry to program I/O ports to digital or alternate functionalities. (**f**) Equivalent circuit of two analog I/O ports bridged with a load impedance (*Z*LOAD).

#### *2.2. Analog I/O Operation Modes*

The AVR® micro-controller family provides access to several digital and analog ports with input and output (I/O) functionalities. Both digital and analog I/O ports share a common control unit design, often called "General Digital I/O" [26,27]. In this work, the digital I/O ports (PDN) are labeled by an alpha-numerical code, denoted by the letter "D" proceeded by the port bit number "N", while the analog I/O ports (PAN) are represented by the letter "A". The analog ports have exclusive access to the alternate functions, featuring an I/O source-measuring unit (SMU) and an analog-to-digital converter (ADC) unit. By default, *P*AN ports can be configured into four distinct operation modes: (mode 1) floating input; (mode 2) pull-up input; (mode 3) low voltage output; (mode 4) high voltage output. Each operation mode shares the same basic electrical structure, consisting of the supply voltage source (*V*S), common ground (GND), a stray capacitance (*C*pin) and location of the I/O port (*P*An) for the SMU and ADC unit. By default, vs. is equal to the reference voltage (*V*REF). Figure 1 shows the equivalent circuit that describes each analog I/O port operation mode and was adapted from references [26,27]. Operation modes 1 and 2, shown in Figure 1a,b, respectively, share the same internal circuitry components to form a highimpedance input port due to the presence of the analog input resistance (*R*AIN). *C*pin is also included in parallel with *R*AIN to account for the stray capacitance. The unique difference between operation mode 1 and 2 is the state of the internal pull-up resistance (*R*pu), which is connected to an internal bias voltage. In the case of operating mode 1, the *R*pu is inactive, leading to a floating input configuration, while in the case of operation mode 2, the *R*pu sets a SMU configuration. This aspect will be further explored to implement the RCLmeter. Operation modes 3 and 4, shown in Figure 1c,d, relate to the "General Digital I/O" functions. Operation mode 3 consists of a floating and impedance low output configuration, and the operation mode 4 consists of a voltage source (*V*S), thus forcing a high output configuration. In the absence of load impedance connected to *P*AN, the configuration of the operation mode 4 sinks current through the parallel RC network formed by the output resistance (*R*out) and *C*pin. Table 1 shows the typical values of the internal components of the I/O ports [26,27].

**Table 1.** Typical values of the operational voltage of the circuits (*V*S), the ADC unit, the internal circuitry to each I/O port and the TTL unit to each AVR® micro-controller [26,27].

The *R*pu and *C*pin values listed in Table 1 are representative values. In case of the *R*pu, both micro-controller datasheets [26,27] characterize the range of *R*pu between 20 kΩ to 50 kΩ, and solely for the purpose of the ADC unit it refers a typical reference input resistance (*R*REF) value of 32 kΩ. As for the *C*pin, the micro-controller datasheets [26,27] do not provide a typical value; only a conceptual component is shown in the equivalent circuits of the analog input circuitry representing the overall stray capacitance (also named *C*pin). Therefore, the typical stray capacitance listed in Table 1 considers all capacitive sources in the internal analog input circuitry, such as: (i) the sampling and holder capacitance (*C*S/H), approximately equal to 14 pF and (ii) the input capacitance (*C*i ) of each I/O pin, approximately equal to 10 pF. Both *C*S/H and *C*i are grounded; therefore, it is assumed that the parallel of both *C*i k *C*S/H is the minimum value of *C*pin and is approximately equal to *C*pin ∼= *C*i k *C*S/H ∼= 24 pF.

In practical terms, the operation mode of each port available on an AVR® microcontroller must be configured according to the pseudo-code described in Figure 1 through a low-level instruction set, which is not a user-friendly environment. However, Arduino®

has developed an integrated development environment (IDE) platform with support of high-level C++ functions such as pinMode() and digitalWrite(), an easy and user-friendly method to configure the ports. Figure 1 describes the C++ code required to properly configure each operation mode. In the following sections, it will be shown how the four different configurations for the ports may be used to build an RCL bridge. First, it is shown how to measure isolated resistors, capacitors and inductors, and then how to measure combinations of resistors and capacitors in series or parallel. has developed an integrated development environment (IDE) platform with support of high-level C++ functions such as pinMode() and digitalWrite(), an easy and user-friendly method to configure the ports. Figure 1 describes the C++ code required to properly configure each operation mode. In the following sections, it will be shown how the four different configurations for the ports may be used to build an RCL bridge. First, it is shown how to measure isolated resistors, capacitors and inductors, and then how to measure combinations of resistors and capacitors in series or parallel.

#### *2.3. Recording Circuit 2.3. Recording Circuit*

The recording circuit to measure resistances, capacitances and inductances, either isolated or in series and parallel is composed of the same internal components by setting two I/O ports with alternate functions, namely *P*A0 and *P*A1 ports configured for pull-up input (mode 1) and low output (mode 3), respectively, and as described in Section 2.2. Figure 1f shows the equivalent circuit resulting from the combination of the internal circuitry of each I/O port bridged by a load impedance (*Z*LOAD). In the following Sections 2.4–2.8, the equivalent circuit shown in Figure 1f is detailed by replacing *Z*LOAD with resistance, capacitance and inductance, either isolated or in series and parallel. The recording circuit to measure resistances, capacitances and inductances, either isolated or in series and parallel is composed of the same internal components by setting two I/O ports with alternate functions, namely PA0 and PA1 ports configured for pull-up input (mode 1) and low output (mode 3), respectively, and as described in Section 2.2. Figure 1f shows the equivalent circuit resulting from the combination of the internal circuitry of each I/O port bridged by a load impedance (ZLOAD). In the following sections 2.4 to 2.8, the equivalent circuit shown in Figure 1f is detailed by replacing *Z*LOAD with resistance, capacitance and inductance, either isolated or in series and parallel.

#### *2.4. Measurements of an Isolated Load Resistance (R–Meter) 2.4. Measurements of an Isolated Load Resistance (R–Meter)*

Considering that in the equivalent circuit shown in Figure 1f, *Z*LOAD is composed of an isolated load resistance (*R*LOAD), the pull-up resistor (*R*pu) at port *P*A0 drives a current source that will sink through the parallel resistance path (*R*P) formed by the analog input resistance (*R*AIN) and the sum of the load and output resistances (*R*LOAD + *R*out). Thus, for circuit analysis purposes, in Figure 2a, a reduction of the entire equivalent circuit to a voltage divider circuit is shown. In Figure 2a, the variable *N*A0 is introduced as the digital counterpart of the analog variable *V*A0, where *N*A0 = b*N*max·(*V*A0/*V*S)c. The stray capacitances (*C*pin) were neglected from the equivalent circuit, since on DC measurements, the capacitances behave as open circuit. In addition, to avoid interference of any stray capacitance, the procedure is to implement a reasonable delay time (say 1 ms) after setting the port *P*A0 to operation mode 2 (pullup input). This procedure assures that the stray capacitances are open circuit (*t τ* = *R*T*C*pin). Using *C*pin = 25 pF and *R*pu = 32 kΩ, one obtains *τ* < 1 µs. Considering that in the equivalent circuit shown in Figure 1f, ZLOAD is composed of an isolated load resistance (RLOAD), the pull-up resistor (Rpu) at port PA0 drives a current source that will sink through the parallel resistance path (RP) formed by the analog input resistance (RAIN) and the sum of the load and output resistances (*R*LOAD + *R*out). Thus, for circuit analysis purposes, in Figure 2a, a reduction of the entire equivalent circuit to a voltage divider circuit is shown. In Figure 2a, the variable *N*A0 is introduced as the digital counterpart of the analog variable *V*A0, where *N*A0 = ⌊*N*max⸱(*V*A0/*V*S)⌋. The stray capacitances (Cpin) were neglected from the equivalent circuit, since on DC measurements, the capacitances behave as open circuit. In addition, to avoid interference of any stray capacitance, the procedure is to implement a reasonable delay time (say 1 ms) after setting the port PA0 to operation mode 2 (pullup input). This procedure assures that the stray capacitances are open circuit (*t* ≫ *τ* = *R*T*C*pin). Using *C*pin = 25 pF and *R*pu = 32 kΩ, one obtains *τ* < 1 µs.

**Figure 2.** Set-up of a pure load resistance meter (R-meter). (**a**) Reduction of the equivalent circuit to a voltage divider circuit. (**b**) Pseudo-code used to implement the resistance meter mode. **Figure 2.** Set-up of a pure load resistance meter (R-meter). (**a**) Reduction of the equivalent circuit to a voltage divider circuit. (**b**) Pseudo-code used to implement the resistance meter mode.

In Figure 2a, *V*A0 is the measured voltage at port PA0 and is given by: In Figure 2a, *V*A0 is the measured voltage at port *P*A0 and is given by:

$$V\_{\rm A0} = V\_{\rm S} \frac{R\_{\rm P}}{R\_{\rm pu} + R\_{\rm P}} \tag{1}$$

(1)

where *R*P is given by *R*AIN || (*R*LOAD *+ R*out), and vs. is equal to the reference voltage source (*V*REF). Solving the voltage divider Equation (1), *R*LOAD is found as: where *R*P is given by *R*AIN || (*R*LOAD *+ R*out), and vs. is equal to the reference voltage source (*V*REF). Solving the voltage divider Equation (1), *R*LOAD is found as:

$$R\_{\rm LOAD} = \frac{R\_{\rm AIN}R\_{\rm out} - K(R\_{\rm AIN} + R\_{\rm out})}{K - R\_{\rm AIN}},\\K = R\_{\rm Pu} \frac{V\_{\rm A0}}{V\_{\rm S} - V\_{\rm A0}} \tag{2}$$

where *K* is an auxiliary variable used to shorten the length of Equation (2). All the parameters described in Equation (2) are known values, and are available on the datasheet of the micro-controller. The pseudo-code for a routine to measure *R*LOAD is described in Figure 2b. where *K* is an auxiliary variable used to shorten the length of Equation (2). All the parameters described in Equation (2) are known values, and are available on the datasheet of the micro-controller. The pseudo-code for a routine to measure *R*LOAD is described in Figure 2b.

#### *2.5. Measurements of an Isolated Load Capacitance (C–Meter) 2.5. Measurements of an Isolated Load Capacitance (C–Meter)*

Two methodologies are reported in this section: (i) fast acquisition mode, which is based on the immediate response of the *C*LOAD charging cycle, and (ii) transient acquisition mode, based on measuring the charging time until a threshold voltage is reached. It is essential that prior to initiating measurements of *C*LOAD, all capacitive components are fully discharged. A typical procedure to discharge all capacitances is achieved by configuring the operation mode of the two I/O ports in use to low output (mode 3) and waiting, for example, a period of ∆*t* ≥ 1 ms. Two methodologies are reported in this section: (i) fast acquisition mode, which is based on the immediate response of the CLOAD charging cycle, and (ii) transient acquisition mode, based on measuring the charging time until a threshold voltage is reached. It is essential that prior to initiating measurements of CLOAD, all capacitive components are fully discharged. A typical procedure to discharge all capacitances is achieved by configuring the operation mode of the two I/O ports in use to low output (mode 3) and waiting, for example, a period of Δ*t* ≥ 1 ms.

#### 2.5.1. Fast Acquisition Mode of an Isolated Load Capacitance 2.5.1. Fast Acquisition Mode of an Isolated Load Capacitance

As an exception to all other methods presented in this manuscript, the fast acquisition mode to measure an isolated load capacitance (*C*LOAD) uses a different internal circuitry. Therefore, Figure 3a shows the equivalent circuit resulting from the combination of the internal circuitry of two I/O ports, *P*A0 and *P*A1, bridged by a pure load capacitance (*C*LOAD). Essentially, the port *P*A1 is set in high output (mode 4) and links the voltage source (*V*S) to the *C*LOAD terminal behaving as an input current source (*i*S), and the port *P*A0 is set to floating input (mode 1), consisting of a measuring unit that links the input current to the ground through a high impedance resistor (*R*AIN). Both the *P*A1 and *P*A0 ports consider the leakage current path to the ground through a stray capacitance (*C*pin). However, the *C*pin located at *P*A1 can be neglected, since the characteristic time constant (*τ*A1) of *P*A1 is *τ*A1 = *R*out*C*pin ∼= 15 ns, and therefore, because the fastest clock cycle (*τ*clk) of the micro-controllers in use are approximately equal to *τ*clk ≈ 5*τ*A1, after a single clock cycle the voltage in port *P*A1 (*V*A1) is stationary. As an exception to all other methods presented in this manuscript, the fast acquisition mode to measure an isolated load capacitance (CLOAD) uses a different internal circuitry. Therefore, Figure 3a shows the equivalent circuit resulting from the combination of the internal circuitry of two I/O ports, PA0 and PA1, bridged by a pure load capacitance (CLOAD). Essentially, the port PA1 is set in high output (mode 4) and links the voltage source (VS) to the CLOAD terminal behaving as an input current source (*i*S), and the port PA0 is set to floating input (mode 1), consisting of a measuring unit that links the input current to the ground through a high impedance resistor (RAIN). Both the PA1 and PA0 ports consider the leakage current path to the ground through a stray capacitance (Cpin). However, the Cpin located at PA1 can be neglected, since the characteristic time constant (*τ*A1) of PA1 is *τ*A1 = *R*out*C*pin ≅ 15 ns, and therefore, because the fastest clock cycle (*τ*clk) of the micro-controllers in use are approximately equal to *τ*clk *≈* 5*τ*A1, after a single clock cycle the voltage in port PA1 (*V*A1) is stationary.

**Figure 3.** Set-up of a pure load capacitance meter (*C*-meter). (**a**) Equivalent circuit of two analog I/O ports bridged with a load capacitance (CLOAD). (**b**) Reduction of the equivalent circuit to an impedance divider. (**c**) Pseudo-code used to implement the fast acquisition mode. **Figure 3.** Set-up of a pure load capacitance meter (*C*-meter). (**a**) Equivalent circuit of two analog I/O ports bridged with a load capacitance (*C*LOAD). (**b**) Reduction of the equivalent circuit to an impedance divider. (**c**) Pseudo-code used to implement the fast acquisition mode.

For circuit analysis purposes, assuming all capacitances are fully discharged at the instant *t* = 0, all capacitances are shorted and all currents flow through the capacitive path. In these circumstances, the circuit analysis is simpler considering that at *t* = 0 the current For circuit analysis purposes, assuming all capacitances are fully discharged at the instant *t* = 0, all capacitances are shorted and all currents flow through the capacitive path. In these circumstances, the circuit analysis is simpler considering that at *t* = 0 the current

path flow exclusively through the capacitive path (*C*T) formed by the load (*C*LOAD) and stray (*C*pin) capacitors in series, given by *C*T = *C*LOAD*C*pin/(*C*LOAD + *C*pin). This allows the reduction of the entire equivalent circuit to a voltage divider, as shown in Figure 3b, and is only valid for measuring the impulse response. Thus, *V*A0 must be read immediately after defining *P*A0 to floating input and *P*A1 to high output.

One approach to find the load capacitance is through the analysis of the charge level (*Q*) of the circuit. Since both *C*LOAD and *C*pin are in series, the charge level must be equal in both capacitances (*Q*LOAD = *Q*pin), thus allowing the expression of *V*A0 as:

$$V\_{\rm A0} = V\_{\rm S} \frac{\mathcal{C}\_{\rm pin}}{\mathcal{C}\_{\rm pin} + \mathcal{C}\_{\rm LOAD}} \tag{3}$$

where the solution given by Equation (3) assumes *Q*LOAD = *C*LOAD (*V*S − *V*A0) and *Q*pin = *C*pin*V*A0. Rearranging (3), *C*LOAD is found as:

$$\mathcal{C}\_{\rm LOAD} = \mathcal{C}\_{\rm pin} \frac{V\_{\rm A0}}{V\_{\rm S} - V\_{\rm A0}} \tag{4}$$

The size of *C*pin is made available through the datasheet of the micro-controller, and is typically 25 pF, while vs. is equal to the reference voltage source (*V*REF), and *V*A0 is the measured voltage at port *P*A0. Thus, all parameters are known, and *C*LOAD can be determined. Lastly, the fast acquisition mode methodology is limited by the size of the *C*pin, such that, if *V*A0 → *N*max, the maximum range of (4) is an asymptote with *C*LOAD → ∞. Therefore, an approximation to determine the range of measurable *C*LOAD is:

$$\frac{\mathcal{C}\_{\text{pin}}}{N\_{\text{max}} - 1} \le \mathcal{C}\_{\text{LOAD}} \le \mathcal{C}\_{\text{pin}} (N\_{\text{max}} - 1) \tag{5}$$

where the total range is obtained for 1 ≤ *N*A0 < *N*max − 1. The pseudo-code for a routine to measure *C*LOAD through the fast acquisition mode is described in Figure 3c.

#### 2.5.2. Transient Acquisition Mode of an Isolated Load Capacitance

As pointed out before, the fast-acquisition mode methodology has limitations for large capacitances, thus requiring a different measurement strategy, namely monitoring the transient during the charging cycle of a *C*LOAD bridging the ports *P*A0 and *P*A1 in the equivalent circuit shown in Figure 1f. The stray capacitances (*C*pin) are not larger than some tens of pico-Farads (pF) and can therefore be neglected.

The remaining circuit analysis is simpler and is preferably done using the impedance analysis. Figure 4a shows the impedance representation of the equivalent circuit, where *Z*in represents the impedance due to the pull-up resistance (*R*pu) at the input port *P*A0, and *Z*out is the output impedance formed by the parallel RC network between the analog input resistance (*R*AIN) and the series RC network (*Z*LOAD + *R*out). *Z*LOAD is the impedance representation of the load capacitance (*C*LOAD). Therefore, an estimation of *C*LOAD is obtained using the step response of the impedance divider circuit shown in Figure 4b, which is given by:

$$V\_{\rm A0}(t) = V\_{\rm S} \left(1 - e^{\frac{-t}{\tau}}\right), \ \tau = R\_{\rm T} \mathbb{C}\_{\rm LOAD} \tag{6}$$

where *R*T is the total resistance path contributing for the potential difference on the capacitance terminals given by *R*T = *R*AIN || *R*pu *+ R*out. Thus, *C*LOAD can be found at any time *t* by rearranging Equation (6) to:

$$\mathcal{C}\_{\text{LOAD}} = \frac{t}{\mathcal{R}\_{\text{T}} \cdot \ln\left(\frac{V\_{\text{S}}}{V\_{\text{S}} - V\_{\text{A0}}(t)}\right)}\tag{7}$$

where *t* is the time since starting the charging of the capacitance. All parameters in Equation (7) are known except for the time (*t*). Thus, to find the *C*LOAD value, the elapsed time (∆*t*) must be determined, since *t* = 0 until a threshold voltage (*V*th) is reached. For instance, solving Equation (6) with *t* = *τ* allows the definition of *V*th = (1 − *e* −1 )*V*S and therefore solves Equation (7). The elegant procedure for testing *V*th makes use of the built-in transistor-transistor logic (TTL) unit to monitor *V*A0 by setting the TTL unit high voltage threshold (*V*IH) to the *V*th (*V*th = *V*IH), allowing not only the avoidance of the computation of the *V*th, but also the enhancement of the accuracy of the measurement. In practical terms, the elapsed time (∆*t*) since *C*LOAD initiates the charging cycle (*t* = 0) until the TTL unit changes to the logical state high '1' (*V*A1 ≥ *V*IH) must be measured, as well as proceeding to the reading of *V*A0 using the ADC unit (*N*A0). Then, *C*LOAD is found by replacing *V*A0 and *t* by the measured values of *N*A0 and ∆*t* in Equation (7). Figure 4c depicts the voltage step response of the impedance divider circuit. The highlighted region delimited between the voltage level *V*IH and vs. represents the operation region where the TTL logic unit changes of logic state low '0' to high '1'. For reference, Table 1 includes the typical values of *V*IH for the ATmega328P and ATmega32U4 micro-controllers. solving Equation (6) with *t* = *τ* allows the definition of *V*th = (1 *− e−*1)*V*S and therefore solves Equation (7). The elegant procedure for testing *V*th makes use of the built-in transistortransistor logic (TTL) unit to monitor *V*A0 by setting the TTL unit high voltage threshold (*V*IH) to the *V*th (*V*th = *V*IH), allowing not only the avoidance of the computation of the *V*th, but also the enhancement of the accuracy of the measurement. In practical terms, the elapsed time (Δ*t*) since *C*LOAD initiates the charging cycle (*t* = 0) until the TTL unit changes to the logical state high '1' (*V*A1 ≥ *V*IH) must be measured, as well as proceeding to the reading of *V*A0 using the ADC unit (*N*A0). Then, *C*LOAD is found by replacing *V*A0 and *t* by the measured values of *N*A0 and Δ*t* in Equation (7). Figure 4c depicts the voltage step response of the impedance divider circuit. The highlighted region delimited between the voltage level *V*IH and vs. represents the operation region where the TTL logic unit changes of logic state low '0' to high '1'. For reference, Table 1 includes the typical values of *V*IH for the ATmega328P and ATmega32U4 micro-controllers.

*Sensors* **2022**, *22*, x FOR PEER REVIEW 9 of 27

**Figure 4.** Set-up for recording a pure load capacitance (CLOAD) through the transient acquisition mode. (**a**) Impedance representation of the reduced equivalent circuit. (**b**) Illustration of the step response in voltage measured at the input terminal of CLOAD. *V*IH is defined in Table 1. (**c**) Pseudocode used to implement the transient acquisition mode. **Figure 4.** Set-up for recording a pure load capacitance (*C*LOAD) through the transient acquisition mode. (**a**) Impedance representation of the reduced equivalent circuit. (**b**) Illustration of the step response in voltage measured at the input terminal of *C*LOAD. *V*IH is defined in Table 1. (**c**) Pseudocode used to implement the transient acquisition mode.

Additionally, the transient acquisition mode methodology is limited by the characteristic time constant (*τ*) of the circuit, such that if *τ* → 0, the charging velocity (d*v*/d*t*) of the *C*LOAD increases to proportions where high temporal resolution is required to measure the *N*A0 accurately, since *N*A0 → *N*max just before the first reading is taken, causing the ADC unit to overflow. An approximation of the ranging limits of the transient acquisition mode is given by: Additionally, the transient acquisition mode methodology is limited by the characteristic time constant (*τ*) of the circuit, such that if *τ* → 0, the charging velocity (d*v*/d*t*) of the *C*LOAD increases to proportions where high temporal resolution is required to measure the *N*A0 accurately, since *N*A0 → *N*max just before the first reading is taken, causing the ADC unit to overflow. An approximation of the ranging limits of the transient acquisition mode is given by:

$$\frac{\Delta t}{R\_{\text{T}} \cdot \ln(N\_{\text{max}})} \le \mathcal{C}\_{\text{LOAD}}(t) \le \frac{\Delta t}{R\_{\text{T}} \cdot \ln\left(\frac{N\_{\text{max}}}{N\_{\text{max}} - 1}\right)}\tag{8}$$

than a capacitor, as it is some hundreds of farads. The pseudo-code of a routine to perform

*N*max − 1 where in Equation (8) the lower and upper resolution of the ADC unit (*N*A0) are solved assuming 1≤*N*A0 ≤*N*max *−*1. Using the typical values provided in Table 1, the detection limit of the interface assuming the fastest reading of the ADC unit could be achieved after one clock-cycle (Δ*t* = 62.5 ns). Then, the minimum range of the transient acquisition method varies between 214 fF ≤ *C*min ≤ 392 fF with 22.4 kΩ ≤ *R*pu ≤ 41.6 kΩ. Nevertheless, the impact of the stray capacitances (Cpin) was neglected, and therefore such a range is merely indicative, since *C*pin ≫ *C*min. As for the maximum range of the transient acquisition method, the maximum Δ*t* is limited by the size of the unsigned long variables given by Δ*t* = (232 − 1) × 1 µs ≅ 4295 s. Thus, the maximum range corresponds to a battery-like storage unit rather where in Equation (8) the lower and upper resolution of the ADC unit (*N*A0) are solved assuming 1 ≤ *N*A0 ≤ *N*max − 1. Using the typical values provided in Table 1, the detection limit of the interface assuming the fastest reading of the ADC unit could be achieved after one clock-cycle (∆*t* = 62.5 ns). Then, the minimum range of the transient acquisition method varies between 214 fF ≤ *C*min ≤ 392 fF with 22.4 kΩ ≤ *R*pu ≤ 41.6 kΩ. Nevertheless, the impact of the stray capacitances (*C*pin) was neglected, and therefore such a range is merely indicative, since *C*pin *C*min. As for the maximum range of the transient acquisition method, the maximum ∆*t* is limited by the size of the unsigned long variables given by ∆*t* = (232 − 1) × 1 µs ∼= 4295 s. Thus, the maximum range corresponds to a battery-like storage unit rather than a capacitor, as it is some hundreds of farads. The pseudo-code of a

routine to perform the measurement of *C*LOAD through the transient acquisition mode is described in Figure 4c.

#### *2.6. Measurements of a Serial RC Network (RC–Meter Mode)*

Considering that in the equivalent circuit shown in Figure 1f, *Z*LOAD is composed by a series RC network, the strategy to extract *C*LOAD and *R*LOAD resembles the previously described techniques to measure a pure resistor in Section 2.4 and a pure capacitor through the transient acquisition mode in Section 2.5.2. However, the TTL-based technique used to determine *C*LOAD cannot guarantee that a TTL transition will occur in the transient response of the circuit, since the voltage *V*A0 might start at a value above the TTL threshold (*V*IH). Instead, the monitoring process of the transient response must be carried out exclusively using the analog functions available on the AVR® micro-controller ports. First, the *C*LOAD must be completely discharged, which requires defining both ports *P*A0 and *P*A1 to low output configuration for a reasonable time, and then defining *P*A0 to a highimpedance SMU, while maintaining *P*A1 as low output. For the sake of simplicity, the stray capacitances (*C*pin) are neglected, which is allowed if they are not larger than some tens of pico-farads (pF).

With *C*LOAD fully discharged, after setting the port *P*A0 to a high-impedance SMU (*t* = 0), a voltage step is applied on the serial RC circuit. Since *C*LOAD is empty, it behaves as a short-circuit, which results in an equivalent circuit, as shown in Figure 2a, thus allowing the extraction of the *R*LOAD value through use of the technique described in Section 2.4 to measure a pure resistor (note that the port configuration is the same). The measured voltage (*V*A0) at the instant *t* = 0 defines an offset voltage (*V*R). For any instant *t >* 0, *C*LOAD starts to accumulate charge, and the same circuit analysis described in Section 2.5.2 applies to determine the transient dynamics of the voltage step response. For *t* → ∞, *C*LOAD is fully charged and behaves as an open circuit, thus forcing the current to flow exclusively through the analog input resistance (*R*AIN), as represented in Figure 1f by the current path '*i*R'. Thus, considering the influence of the charging current (*i*L) due to the series *R*LOAD, an estimation of *C*LOAD is obtained using the step response of the equivalent circuit shown in Figure 1f that is given by:

$$V\_{\rm A0}(t) = V\_{\rm R} + V\_{\rm REF} \left(1 - e^{\frac{-t}{\tau}}\right), \; V\_{\rm R} = \frac{V\_{\rm S}}{R\_{\rm pu}} \frac{(R\_{\rm out} + R\_{\rm LOAD}) \left(R\_{\rm AIN} \parallel R\_{\rm pu}\right)}{R\_{\rm out} + R\_{\rm LOAD} + R\_{\rm AIN} \parallel R\_{\rm pu}},\tag{9}$$

where *V*R is the offset voltage due to the series *R*LOAD, *V*REF is the new reference voltage of the circuit given by *V*REF = vs. − *V*R, *τ* is the characteristic time constant of the equivalent circuit given by the *τ* = *R*T*C*LOAD and *R*T is the total resistance path contributing to the potential difference on the capacitance terminals given by *R*T = *R*AIN || *R*pu *+ R*LOAD *+ R*out. Thus, *C*LOAD can be found at any time *t* by rearranging Equation (9) to:

$$\mathcal{C}\_{\text{LOAD}} = \frac{t}{\mathcal{R}\_{\text{T}} \ln\left(\frac{V\_{\text{REF}}}{V\_{\text{REF}} - V\_{\text{A0}}(t)}\right)} \tag{10}$$

where *t* is the time that takes charges to accumulate in the capacitance. Figure 5a illustrates the transient response to a voltage step expressed by Equation (10), where the highlighted region consists of the offset voltage (*V*R) due to the bridge of ports *P*A0 and *P*A1 with the serial RC network. As for the reading capacitance voltage level (*V*C) it is determined when *t* = *τ* = *R*T*C*LOAD, and is given by *V*C = *V*R + (1 − *e* −1 )(*V*S − *V*R). Therefore, all parameters in Equation (10) are known except for the time (*t*). To extract *C*LOAD, a routine to determine the elapsed time (∆*t*) until the measured voltage (*V*A1) is greater than or equal to *V*C (*V*A0 ≥ *V*C) must be implemented. Figure 5b depicts the pseudo-code of a routine to implement the measurement of a serial RC network. In practical terms, *C*LOAD is found by replacing in Equation (10) *V*R with the measured value of *N*A0 at *t* = 0 (*N*R), vs. with the maximum resolution of the ADC unit (*N*max) and *V*A0 and *t* with the measured value of *N*A0 and ∆*t* after *V*A0 ≥ *V*C, respectively.

(a)

## **Pseudo-code:**

```
Set port PA0 and PA1 to LOW OUTPUT
Wait 1 millisecond: delay (1)
Set port PA0 to INPUT PULLUP
Sample port PA0: VR measures VA0
Read timer: TS measures microseconds
Define stop condition:
  VTAU = VR + 0.6322 × (VS – VR)
do
  Sample port PA0: VC measures VA0
while (VC <= VTAU)
Read timer: TE measures microseconds
Determine elapsed time (Δt): T = TE – TS
RLOAD is given by Eq.(2) : Replace VA0 by VR
CLOAD is given by Eq.(10): Replace VA0 by VC
                                     t by T
                (b)
```
**Figure 5.** Set-up for recording a load impedance (*Z*LOAD) formed by a serial RC network. (**a**) Illustration of the transient response to a voltage step at the input terminal (PA0). (**b**) Pseudo-code used to implement the measurement of a serial RC network. **Figure 5.** Set-up for recording a load impedance (*Z*LOAD) formed by a serial RC network. (**a**) Illustration of the transient response to a voltage step at the input terminal (*P*A0). (**b**) Pseudo-code used to implement the measurement of a serial RC network.

#### *2.7. Measurements of a Parallel RC Network (RC–Meter Mode) 2.7. Measurements of a Parallel RC Network (RC–Meter Mode)*

Considering that in the equivalent circuit shown in Figure 1f, ZLOAD is composed of a parallel RC network (*C*LOAD║*R*LOAD), the strategy to extract *C*LOAD and *R*LOAD resembles the previously described technique in Section 2.6, although it must be noted that the change of the load capacitance (*C*LOAD) from serial mode to parallel mode causes *R*LOAD to saturate at the reference voltage (*V*F = *V*R) level when *t* → ∞ and the voltage offset is null at *t* = 0. Thus, the step response of the equivalent circuit shown in Figure 1f is given by: Considering that in the equivalent circuit shown in Figure 1f, *Z*LOAD is composed of a parallel RC network (*C*LOADk*R*LOAD), the strategy to extract *C*LOAD and *R*LOAD resembles the previously described technique in Section 2.6, although it must be noted that the change of the load capacitance (*C*LOAD) from serial mode to parallel mode causes *R*LOAD to saturate at the reference voltage (*V*F = *V*R) level when *t* → ∞ and the voltage offset is null at *t* = 0. Thus, the step response of the equivalent circuit shown in Figure 1f is given by:

$$V\_{\rm A0}(t) = V\_{\rm F} \left( 1 - e^{\frac{-t}{\tau}} \right) \tag{11}$$

where *V*F is given by the expression of *V*R that is defined in Equation (9), *τ* is the characteristic time constant of the equivalent circuit given by *τ = R*T*C*LOAD and *R*T is the total resistance path given by *R*T *=* (*R*AIN || *R*pu) || (*R*LOAD *+ R*out). Figure 6a illustrates the transient response to a voltage step expressed by Equation (11). For *t* → ∞, *C*LOAD is fully charged and behaves as an open circuit, forcing the current (*i*L) represented in the equivalent circuit shown in Figure 1f to flow exclusively through the *R*LOAD to the ground. Therefore, the extraction of *R*LOAD is analytically indeterminate, unless an approximation is made, such as, considering for any period (Δ*t*) larger than five times the characteristic time constant (*τ*) (Δ*t >* 5*τ*), Equation (11) is approximately equal to *V*A0 = *V*F(1 *− e ‒*5) ≈ *V*F, where the term (1 *− e ‒*5) ≈ 0.993 shows that the approximation has a maximum error of 0.7% when determining the *R*LOAD value. Thereby, assuming for any Δ*t >* 5*τ* the plateau *V*A0 = *V*F is reached, the *R*LOAD value is obtained using the technique described in Section 2.4 to measure a pure resistor, replacing in Equation (2) *V*A0 by *V*F, where *V*F is the measured voltage for any instant Δ*t >* 5*τ*. The next step is to determine the *C*LOAD value through the arrangement of Equation (11) with *τ* = *R*T*C*LOAD by: where *V*F is given by the expression of *V*R that is defined in Equation (9), *τ* is the characteristic time constant of the equivalent circuit given by *τ* = *R*T*C*LOAD and *R*T is the total resistance path given by *R*T = (*R*AIN || *R*pu) || (*R*LOAD + *R*out). Figure 6a illustrates the transient response to a voltage step expressed by Equation (11). For *t* → ∞, *C*LOAD is fully charged and behaves as an open circuit, forcing the current (*i*L) represented in the equivalent circuit shown in Figure 1f to flow exclusively through the *R*LOAD to the ground. Therefore, the extraction of *R*LOAD is analytically indeterminate, unless an approximation is made, such as, considering for any period (∆*t*) larger than five times the characteristic time constant (*τ*) (∆*t* > 5*τ*), Equation (11) is approximately equal to *V*A0 = *V*F(1 − *e* −5 ) ≈ *V*F, where the term (1 − *e* −5 ) ≈ 0.993 shows that the approximation has a maximum error of 0.7% when determining the *R*LOAD value. Thereby, assuming for any ∆*t* > 5*τ* the plateau *V*A0 = *V*F is reached, the *R*LOAD value is obtained using the technique described in Section 2.4 to measure a pure resistor, replacing in Equation (2) *V*A0 by *V*F, where *V*F is the measured voltage for any instant ∆*t* > 5*τ*. The next step is to determine the *C*LOAD value through the arrangement of Equation (11) with *τ* = *R*T*C*LOAD by:

$$\mathcal{C}\_{\text{LOAD}} = \frac{t}{\mathcal{R}\_{\text{T}} \cdot \ln\left(\frac{V\_{\text{F}}}{V\_{\text{F}} - V\_{\text{A0}}(t)}\right)}\tag{12}$$

where *t* is any instant of the step-response and *V*A0 the correspondent measured voltage. The determination of *V*F is critical to find both *C*LOAD and *R*LOAD values. The simplest approach to find *V*F using the transient response to a voltage step is to define the maximum characteristic time constant (*τ*max) to measure. In these circumstances all parameters are where *t* is any instant of the step-response and *V*A0 the correspondent measured voltage. The determination of *V*F is critical to find both *C*LOAD and *R*LOAD values. The simplest approach to find *V*F using the transient response to a voltage step is to define the maximum

characteristic time constant (*τ*max) to measure. In these circumstances all parameters are known, and both *C*LOAD and *R*LOAD values can be measured using Equations (2) and (10). Figure 6b depicts the pseudo-code of a routine to implement the measurement of a parallel RC network. known, and both *C*LOAD and *R*LOAD values can be measured using Equations (2) and (10). Figure 6b depicts the pseudo-code of a routine to implement the measurement of a parallel RC network.

**Pseudo-code:** Define highest time constant (*τ*) to be measured: **tau** Determine time (Δ*t*) until threshold voltage (*V*F): **T** = **5** × **tau** Set port PA0 and PA1 to LOW OUTPUT Wait 1 millisecond: **delay** (**1**) Set port PA1 to INPUT PULLUP Wait until Δ*t = τ* : **delay** (**tau**) Sample port PA1: **VC** measures *V*A1 Wait until Δ*t =* 5*τ* : **delay** (**T ‒ tau**) Sample port PA1: **VF** measures *V*A1 *R*LOAD is given by Eq.(2) : Replace *V*A0 by **VF** *C*LOAD is given by Eq.(12): Replace *V*A1 by **VC** *t* by **T** (a) (b)

**Figure 6.** Set-up for recording a load impedance (*Z*LOAD) formed by a parallel RC network. (**a**) Illustration of the transient response to a voltage step at the input terminal (PA0). (**b**) Pseudo-code used to implement the measurement of a parallel RC network. **Figure 6.** Set-up for recording a load impedance (*Z*LOAD) formed by a parallel RC network. (**a**) Illustration of the transient response to a voltage step at the input terminal (*P*A0). (**b**) Pseudo-code used to implement the measurement of a parallel RC network.

#### *2.8. Measurements of an Isolated Load Inductance (L–Meter Mode) 2.8. Measurements of an Isolated Load Inductance (L–Meter Mode)*

Considering that in the equivalent circuit shown in Figure 1f, ZLOAD is composed of an isolated load inductance (LLOAD), and that for the sake of simplicity, the stray capacitances (Cpin) are neglected, which is allowed if they are not larger than some tens of picofarads (pF), the circuit analysis is simpler than and preferable to using the impedance analysis. Figure 7a shows the impedance representation of the equivalent circuit, where *Z*in represents the impedance due to the pull-up resistance (*R*pu) at the input port PA1, and *Z*out is the output impedance formed by the parallel RC network between the analog input resistance (*R*AIN) and the series RC network (*Z*LOAD + *R*out). *Z*LOAD is the impedance representation of the load inductance (*L*LOAD), given by *Z*LOAD = *jωL*LOAD. Therefore, an estimation of *L*LOAD is obtained using the step response of the impedance divider circuit shown in Figure 7a, which is given by: Considering that in the equivalent circuit shown in Figure 1f, *Z*LOAD is composed of an isolated load inductance (*L*LOAD), and that for the sake of simplicity, the stray capacitances (*C*pin) are neglected, which is allowed if they are not larger than some tens of pico-farads (pF), the circuit analysis is simpler than and preferable to using the impedance analysis. Figure 7a shows the impedance representation of the equivalent circuit, where *Z*in represents the impedance due to the pull-up resistance (*R*pu) at the input port *P*A1, and *Z*out is the output impedance formed by the parallel RC network between the analog input resistance (*R*AIN) and the series RC network (*Z*LOAD + *R*out). *Z*LOAD is the impedance representation of the load inductance (*L*LOAD), given by *Z*LOAD = *jωL*LOAD. Therefore, an estimation of *L*LOAD is obtained using the step response of the impedance divider circuit shown in Figure 7a, which is given by:

$$V\_{\rm A0}(t) = V\_{\rm S} \left(1 - e^{\frac{-t}{\tau}}\right), \ \tau = L\_{\rm LOAD}/R\_{\rm T} \tag{13}$$

where *R*T is the total resistance path contributing to the potential difference on the inductance terminals given by *R*T = *R*AIN || *R*pu *+ R*out. Thus, *L*LOAD can be found at any time *t* by rearranging Equation (13) to: where *R*T is the total resistance path contributing to the potential difference on the inductance terminals given by *R*T = *R*AIN || *R*pu *+ R*out. Thus, *L*LOAD can be found at any time *t* by rearranging Equation (13) to:

$$L\_{\rm LOAD} = \frac{tR\_{\rm T}}{\ln\left(\frac{V\_{\rm S}}{V\_{\rm S} - V\_{\rm A0}(t)}\right)} \,\mathrm{}\,\mathrm{}\,\mathrm{L}\,\mathrm{s}\,\tag{14}$$

where *t* is the time that takes charges to accumulate in the inductance. Except for the time (*t*), all parameters in Equation (14) are known and available in Table 1. Therefore, the strategy to solve the time (*t*) of Equation (14) requires a similar approach, as previously described for the measurement of an isolated capacitance through the transient response. where *t* is the time that takes charges to accumulate in the inductance. Except for the time (*t*), all parameters in Equation (14) are known and available in Table 1. Therefore, the strategy to solve the time (*t*) of Equation (14) requires a similar approach, as previously described for the measurement of an isolated capacitance through the transient response. In this case, it must be monitored when the threshold voltage (*V*th) over *L*LOAD is approximately

equal to *V*th = *V*S·(1 − *e* −1 ). As for the isolated capacitance measurement described in Section 2.5.2, the elegant and simpler procedure for testing *V*th, involves making use of the built-in transistor-transistor logic (TTL) unit to monitor *V*A0 by setting the TTL unit low voltage threshold (*V*IL) the *V*th (*V*th = *V*IL). In practical terms, the elapsed time (∆*t*) since *L*LOAD initiates the cycle (*t* = 0) until the TTL unit changes to the logical state low '0' (*V*A0 ≤ *V*IL) must be measured, proceeding afterwards to the reading of *V*A0 using the ADC unit (*N*A0). Then, *L*LOAD is found by replacing *V*A0 and *t* with the measured values of *N*A0 and ∆*t* in Equation (14). Figure 7b depicts the voltage step response of the impedance divider circuit. The highlighted region delimited between the voltage level *V*IL and vs. represents the operation region where the TTL logic unit changes of logic state high '1' to low '0'. In this case, it must be monitored when the threshold voltage (*V*th) over *L*LOAD is approximately equal to *V*th = *V*S⸱(1 *− e‒*1). As for the isolated capacitance measurement described in Section 2.5.2, the elegant and simpler procedure for testing *V*th, involves making use of the built-in transistor-transistor logic (TTL) unit to monitor *V*A0 by setting the TTL unit low voltage threshold (*V*IL) the *V*th (*V*th = *V*IL). In practical terms, the elapsed time (Δ*t*) since *L*LOAD initiates the cycle (*t* = 0) until the TTL unit changes to the logical state low '0' (*V*A0 ≤ *V*IL) must be measured, proceeding afterwards to the reading of *V*A0 using the ADC unit (*N*A0). Then, *L*LOAD is found by replacing *V*A0 and *t* with the measured values of *N*A0 and Δ*t* in Equation (14). Figure 7b depicts the voltage step response of the impedance divider circuit. The highlighted region delimited between the voltage level *V*IL and vs. represents the operation region where the TTL logic unit changes of logic state high '1' to low '0'.

**Figure 7.** Set-up for recording an isolated load inductance (*L*LOAD) through the transient acquisition mode. (**a**) Impedance representation of the reduced equivalent circuit. (**b**) Illustration of the step response in voltage measured at the input terminal of *L*LOAD. *V*IL is defined in Table 1. (**c**) Pseudocode used to implement the inductance transient acquisition mode. **Figure 7.** Set-up for recording an isolated load inductance (*L*LOAD) through the transient acquisition mode. (**a**) Impedance representation of the reduced equivalent circuit. (**b**) Illustration of the step response in voltage measured at the input terminal of *L*LOAD. *V*IL is defined in Table 1. (**c**) Pseudocode used to implement the inductance transient acquisition mode.

The measurement range of the inductance is limited due to the ADC unit resolution, where the technique described above to monitor the transient response to a voltage step is limited by the characteristic time constant (*τ*) of the circuit, such that if *τ* → 0, the charging current velocity (d*i*/d*t*) of the *L*LOAD decreases to such proportions that accurately measuring the *N*A0 requires high temporal resolution, since *N*A0 → 0 just before the first reading is taken, causing the ADC unit to overflow. An approximation of the ranging limits of the transient acquisition mode is given by: The measurement range of the inductance is limited due to the ADC unit resolution, where the technique described above to monitor the transient response to a voltage step is limited by the characteristic time constant (*τ*) of the circuit, such that if *τ* → 0, the charging current velocity (d*i*/d*t*) of the *L*LOAD decreases to such proportions that accurately measuring the *N*A0 requires high temporal resolution, since *N*A0 → 0 just before the first reading is taken, causing the ADC unit to overflow. An approximation of the ranging limits of the transient acquisition mode is given by:

$$\frac{\Delta t \cdot R\_{\text{T}}}{\ln(N\_{\text{max}})} \le L\_{\text{LOAD}}(t) \le \frac{\Delta t \cdot R\_{\text{T}}}{\ln\left(\frac{N\_{\text{max}}}{N\_{\text{max}} - 1}\right)}\tag{15}$$

where in Equation (15) the lower and upper resolution of the ADC unit (*N*A0) are solved assuming 1 ≤ *N*A0 ≤ *N*max − 1. With the same values and assumptions used for the transient C-method, the range of measurement will vary between 0.2 mH ≤ *L*LOAD ≤ 1.5 H with *R*pu = 22.4 kΩ, and 0.4 mH ≤ *L*LOAD ≤ 2.7 H with *R*pu = 41.6 kΩ. These measurable values of *L*LOAD are not very useful in real life applications, and for that reason in this manuscript only the methodology is provided as proof of concept to perform measurements with AVR® microwhere in Equation (15) the lower and upper resolution of the ADC unit (*N*A0) are solved assuming 1 ≤ *N*A0 ≤ *N*max − 1. With the same values and assumptions used for the transient C-method, the range of measurement will vary between 0.2 mH ≤ *L*LOAD ≤ 1.5 H with *R*pu = 22.4 kΩ, and 0.4 mH ≤ *L*LOAD ≤ 2.7 H with *R*pu = 41.6 kΩ. These measurable values of *L*LOAD are not very useful in real life applications, and for that reason in this manuscript only the methodology is provided as proof of concept to perform measurements with AVR® micro-controllers of an isolated inductance. In spite of this, the pseudo-code is

provided in Figure 7c to implement the measurements of an isolated *L*LOAD through the transient acquisition mode built-in AVR® micro-controllers.

#### *2.9. Data Acquisition and Analysis*

The open-source Arduino® IDE software was used to program and upload the scripts on the AVR® micro-controllers. All routines that were programmed to perform the measurements of the RCL-meter are based on the pseudo-codes previously described in each method. The data acquisition was carried out with the serial interface made available on the Arduino® IDE software. The collected data were handled with MATLAB® to perform the data analysis. All measurements were performed at room temperature, about 25 ◦C.

#### *2.10. Noise and Uncertainty of the Measurements*

To achieve the highest measurement accuracy of the RCL parameters, the parasitic capacitances must be minimized by leaving a space of two analog pins between the measured ports, e.g., ports *P*A0 and *P*A3, and shorten the connection cables to a minimum size.

Additionally, the impact of noise sources in the measurements must be considered. This includes the thermal and 1/*f* contributions, which are not easily modelled, but are included in the global noise measurements. The measured noise of the voltage source (∆*V*n) was 6.7 mV (with the Arduino board powered through the USB interface connected to a local-PC), comparable to the digitalization uncertainty of the ADC (5 mV) described below. This value permits an enhancement of the accuracy of the ADC unit by oversampling techniques. This shows that the digitalization dominates over thermal and 1/*f* noise contributions. Thus, in this analysis we only calculate the effect of digitalization uncertainty. Using the default ADC sampling time of 100 µs, the digitalization uncertainty of a 10-bit ADC unit relative to the reference voltage (*V*REF) of 5 V, the least significant bit (LSB) voltage is 4.9 mV. To analyze the impact of this digitalization uncertainty, the relative uncertainty (*u*r) associated with the analog to digital round off was determined as:

$$\mu\_{\rm r} = \frac{f(N\_{\rm meas} + 0.5) - f(N\_{\rm meas} - 0.5)}{f(N\_{\rm meas})},\tag{16}$$

where *f*(*N*) represents one of the previous Equations (2), (4), (7), (10), (12) and (14) used to determine the *R*LOAD, *C*LOAD and *L*LOAD values. Then, the oversampling technique allow for reducing the digitalization uncertainty (*u*r) by a factor of 1/*N* but limited by other sources of uncertainty (noise).

#### *2.11. Relative Accuracy and Precision of the Measurements*

The errors associated with the accuracy and precision of the measurements were analyzed through the relative accuracy (*a*r) and the relative precision (*p*r). The relative precision (*p*r) measures the dispersion of the measured impedance values (*Z*meas) normalized to their average (*Z*meas) and was estimated by *p*r = SD(*Z*meas)/*Z*meas, where SD represents the standard deviation of the measured values. The relative accuracy (*a*r) measures the closeness of the measured *Z*meas to the true or reference value, *Z*nominal, and was estimated by *a*r = |*Z*meas − *Z*nominal|/*Z*nominal.

#### *2.12. Linearization of the ADC Unit*

Work was done to improve the linearization of the ADC unit output. By linearization is here meant the maximization of the correlation between measured and nominal values, which depends on the correct knowledge of the micro-controller's parameters. Since all methods presented previously to measure an unknown load impedance (*Z*LOAD) use the same ports configuration (except for the measurements of an isolated load capacitance using the fast acquisition mode), the simplest method to optimize the linearization of the measurements is to replace *Z*LOAD with a pure known load resistance (*R*LOAD) and use different resistor sizes to test and maximize the range and accuracy of the ADC unit. Then, Equation (2) must be used as a fitting function, where the *R*LOAD values must be

replaced by the nominal values provided by the manufacturer of the resistor, and *V*A0 and vs. by the ADC unit values. Figure 8a shows the *N*A0 values collected with through-hole resistors bridging two ports of the micro-controllers. All samples consist of an average of 100 consecutive measurements. The data were distributed in a logarithmic scale along the horizontal axis according to the nominal resistance value provided by the manufacturer. The red triangles represent the samples measured with the ATmega328P and the blue circles represent the ATmega32U4. Ordinary Least Squares (OLS) were used to fit the data shown in Figure 8a, but with a small twist, which consisted of applying the natural logarithm (ln) to the OLS objective fit function and to the measured *N*A0 values. This proved able to cope better with the large range of resistance values, encompassing several orders of magnitude. Then, to extract the optimized values of *R*AIN, *R*out and *R*pu, the user must provide a guess estimation and use a nonlinear programming solver to find the minimum values of the OLS objective function around the estimated values, taken from the manufacturer datasheets. Table 2 shows the extracted values of *R*AIN, *R*out and *R*pu for both ATmega328P and ATmega32U4 AVR® micro-controllers used in the current work. ferent resistor sizes to test and maximize the range and accuracy of the ADC unit. Then, Equation (2) must be used as a fitting function, where the *R*LOAD values must be replaced by the nominal values provided by the manufacturer of the resistor, and *V*A0 and vs. by the ADC unit values. Figure 8a shows the *N*A0 values collected with through-hole resistors bridging two ports of the micro-controllers. All samples consist of an average of 100 consecutive measurements. The data were distributed in a logarithmic scale along the horizontal axis according to the nominal resistance value provided by the manufacturer. The red triangles represent the samples measured with the ATmega328P and the blue circles represent the ATmega32U4. Ordinary Least Squares (OLS) were used to fit the data shown in Figure 8a, but with a small twist, which consisted of applying the natural logarithm (ln) to the OLS objective fit function and to the measured *N*A0 values. This proved able to cope better with the large range of resistance values, encompassing several orders of magnitude. Then, to extract the optimized values of *R*AIN, *R*out and *R*pu, the user must provide a guess estimation and use a nonlinear programming solver to find the minimum values of the OLS objective function around the estimated values, taken from the manufacturer datasheets. Table 2 shows the extracted values of *R*AIN, *R*out and *R*pu for both ATmega328P and ATmega32U4 AVR® micro-controllers used in the current work.

*Sensors* **2022**, *22*, x FOR PEER REVIEW 15 of 27

measurements is to replace *Z*LOAD with a pure known load resistance (*R*LOAD) and use dif-

**Figure 8.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to record an isolated load resistance (*R*LOAD). (**a**) Measured ADC unit discrete values at port PA0 (*N*A0). Each sample consists of an average of 100 consecutive measurements. (**b**) Measured load resistance (*R*LOAD) values according to Equation (2). The green dashed lines represent the theoretical lines. (**c**) Relative accuracy (*ar*) and (**d**) relative precision (*pr*) of the measurements in function of *R*nominal. The black dashed line represents the relative uncertainty (*ur*) of the *R*LOAD measurements according to Equation (16). The white and grey shading areas highlight the levels of *ur*, *ar* and *pr* better than 5%, 10% and 20%. A legend to describe the color scheme used in all plots of Figure 8 was included. **Figure 8.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to record an isolated load resistance (*R*LOAD). (**a**) Measured ADC unit discrete values at port *P*A0 (*N*A0). Each sample consists of an average of 100 consecutive measurements. (**b**) Measured load resistance (*R*LOAD) values according to Equation (2). The green dashed lines represent the theoretical lines. (**c**) Relative accuracy (*a*r) and (**d**) relative precision (*p*r) of the measurements in function of *R*nominal. The black dashed line represents the relative uncertainty (*u*r) of the *R*LOAD measurements according to Equation (16). The white and grey shading areas highlight the levels of *u*r, *a*r and *p*r better than 5%, 10% and 20%. A legend to describe the color scheme used in all plots of Figure 8 was included.

Figure 8a shows the ADC readings as a function of the nominal ADC values. Actual values for both ATmega328P and ATmega32U4 micro-controllers are represented by symbols, and the corresponding fitted lines from Equation (2) (overlapped) in dashed green. The figure inset provides a closer view of the measured samples between 0.5 Ω to 10 Ω. The fitted parameters allow a broad working range of about 8 orders of magnitude for

the measured resistance. Otherwise, using typical values provided by the manufacturer would result in a working range of only 2 orders of magnitude. This procedure was performed only once and the values obtained for *R*AIN, *R*out and *R*pu were used in all the subsequent measurements. AVR® micro-controllers. **ATmega328P ATmega32U4**  *R***AIN**王 (MΩ) *R***pu**王 (kΩ) *R***out**王 (Ω) *C***pin**王 (pF) *R***AIN**王 (MΩ) *R***pu**王 (kΩ) *R***out**王 (Ω) *C***pin**王 (pF)

**Table 2.** Optimized values of the *R*AIN, *R*out, *R*pu and *C*pin for both ATmega328P and ATmega32U4

3.537 36.89 565.8 23.48 5.451 36.66 542.2 25.5

formed only once and the values obtained for *R*AIN, *R*out and *R*pu were used in all the sub-

*Sensors* **2022**, *22*, x FOR PEER REVIEW 16 of 27

**Table 2.** Optimized values of the *R*AIN, *R*out, *R*pu and *C*pin for both ATmega328P and ATmega32U4 AVR® micro-controllers. Figure 8a shows the ADC readings as a function of the nominal ADC values. Actual

Likewise, the same fitting analysis previously described was used to optimize the value of *C*pin, which is required to perform measurements of an isolated load capacitance through the fast acquisition mode. In this case, through-hole capacitors of different sizes were used to bridge two I/O ports of the micro-controller, and Equation (4) was used as a fitting function for the measurements of the *N*A0 values shown in the Figure 9a. The *C*pin values extracted for each micro-controller are shown in Table 2. The MATLAB scripts written to perform the OLS fitting are available in the Supplementary Materials. sequent measurements. Likewise, the same fitting analysis previously described was used to optimize the value of *C*pin, which is required to perform measurements of an isolated load capacitance through the fast acquisition mode. In this case, through-hole capacitors of different sizes were used to bridge two I/O ports of the micro-controller, and Equation (4) was used as a fitting function for the measurements of the *N*A0 values shown in the Figure 9a. The *C*pin values extracted for each micro-controller are shown in Table 2. The MATLAB scripts written to perform the OLS fitting are available in the Supplementary Materials.

**Figure 9.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to record an isolated load capacitance (*C*LOAD) through the fast acquisition mode. (**a**) Measured ADC values at port PA0 (*N*A0). Each ADC sample consists of an average of 100 consecutive measure-**Figure 9.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to record an isolated load capacitance (*C*LOAD) through the fast acquisition mode. (**a**) Measured ADC values at port *P*A0 (*N*A0). Each ADC sample consists of an average of 100 consecutive measurements. (**b**) Measured load capacitance (*C*LOAD) given by Equation (4). The green dashed lines represent the theoretical lines. (**c**) Relative accuracy (*a*r) and (**d**) relative precision (*p*r) of the measurements in function of *C*nominal. The black dashed line represents the relative uncertainty (*u*r) of the *C*LOAD measurements according to Equation (16). The white and grey shading areas highlight the levels of *u*r, *a*r and *p*r better than 5%, 10% and 20%. A legend to describe the color scheme used in all plots of Figure 9 was included.

#### **3. Results**

Commercial through-hole resistors and capacitors in the ranges 0.5 Ω–80 MΩ and 100 Ff–4.7 mF (±5%), respectively, were used to perform measurements of either isolated or in series and parallel electrical components with the AVR® micro-controllers. The capacitances in the fF range were of SMD type (Kyocera AVX, Fountain Inn, SC, USA), and all capacitances above 1 µF were aluminum electrolyte capacitor type. The validations were made by comparing the measurements results with the components' nominal values. In all cases, each data point corresponds to the average of 100 measurements performed in a continuous loop.

#### *3.1. Characterization of Isolated Resistance Measurements*

The resistance measurements were performed with a set of resistors independent of those used to linearize the ADC. Using the methodology described in Section 2.4, the voltages at port *P*A0 (*V*A0) were recorded with the ADC unit (*N*A0), and the measurements were inserted in Equation (2), to obtain the *R*LOAD values shown in Figure 8b. This figure also includes the same resistances measurements recorded with a commercial instrument, the Fluke 8840A multimeter (Fluke Corporation, Everett, WA, USA), for reference and validation. These are excellent results for a low-cost technique. However, it is important to keep in mind that each individual point is the average of 100 consecutive measurements, performed in a loop. Table 3 provides numeric detail on the data shown in Figure 8b.

**Table 3.** Comparison of the ATmega328P, ATmega32U4 and Fluke 8840A measured load resistance (*R*LOAD) values ± standard deviation (SD).

Figure 8c shows the relative accuracy (*a*r) of the measurements as a function of the nominal resistance, as defined in Section 2.11. Figure 8d shows their relative precision, *p*r, also defined in Section 2.11 (data points), and the estimated upper limit for the relative uncertainty caused by the digitalization round-off error, *u*r, defined in Equation (16) and represented by the dashed line. Note that the standard deviations are calculated on samples that are already averages of 100 points, which means that *u*r should be divided by 10, for a correct comparison with *p*r. Both plots include white and grey shading regions to highlight the levels of *a*r and *p*r better than 5%, 10% and 20%. The two plots show better

performance of the method in the intermediate resistance range and its degradation in the regime of very low or very high resistances. This is because the lower and upper limits for *R*LOAD correspond to *N*A0 tending to the higher (*N*max) and lower (≈0) values of the digital output, respectively, where the roundoff errors introduced by digitalization become more important, affecting both precision and accuracy.

Most of the data points lay below the *u*r curve. This is because *u*r is merely an upper limit for the digitalization noise, which is actually lower. In any case, the plot indicates that the main uncertainty source in the determination of resistance is the digitalization roundoff.

In terms of performance, the ATmega32U4 delivers better results. The range defined by *p*r < 5% is approximately 10 Ω–10 MΩ for the ATmega328P and 10 Ω–80 MΩ for the ATmega32U4, while the range defined by *a*r < 5% is 100 Ω–100 kΩ for the ATmega328P and 100 Ω–10 MΩ for the ATmega32U4.

The sensitivity of the R-meter (minimum detectable increment in resistance) was assessed at a representative value of 1 kΩ, as well at increments of 0.5, 1 and 4.7 Ω. 50 measurements were acquired at each resistance value. The average of the 50 ADC counts were plotted against the resistance values and a local slope ADC counts/Ω was determined. The standard deviations of the 4 measurements were also calculated and averaged to get a typical value. A conservative estimative of the sensitivity was then performed by calculating the increase in resistance needed to shift the ADC count by two standard deviations, which was about 1.2 Ω or 0.1% of the nominal value. Additionally, a student *t*-test analysis was performed by comparing all the 4 datasets of 50 measurements against each other to conclude that they were all different (*p* < 0.05). This suggested that even an increment of 0.5 Ω is enough to change the output of the R-meter, which is about 2 times less than the previous conservative estimate.

#### *3.2. Characterization of Isolated Capacitance Measurements: Fast Acquisition Method*

Using the methodology described in Section 2.5.1 with different commercial capacitors varying from 100 fF to 100 nF, measurements of the voltage at port *P*A0 (*V*A0) were recorded with the ADC unit (*N*A0) and shown in Figure 9a. Figure 9a also includes a green dashed line that represents the theoretical lines for the two micro-controllers (overlapped), obtained from Equation (3) with the fitted *C*pin values shown in Table 2. The measured *N*A0 and fitted *C*pin values were replaced in Equation (4) to determine the load capacitance (*C*LOAD), shown in Figure 9b. At the end of Section 3.2, Table 4 was included, providing numeric detail on the data shown in Figure 9b. For reference and validation, this plot also includes the measurements recorded with two commercial instruments, the BK Precision 890C capacitance meter (B&K Precision Corporation, Yorba Linda, CA, USA) and the Fluke PM6304 impedance meter (Fluke Corporation, Everett, WA, USA) at the lowest frequency available (*f* = 50 Hz). The green dashed line is *C*LOAD = *C*nominal, showing that the *C*LOAD values determined by both micro-controllers match the target values within the range 100 Ff–10 nF, thus achieving a range of about 5 orders of magnitude.

Figure 9c,d allow a more detailed view of the quality of this match and display *a*r, *p*r and *u*r (in the same way as in Figure 8c,d). The accuracy *a*r drops significantly above 10 nF because the voltage drop at the load capacitance tends towards the circuit voltage source (*N*A0 → *N*max), as predicted by Equation (5), inducing large errors in the determination of *C*LOAD.

This is evidenced in the *u*r curve represented (black dashed line in Figure 9d), showing the same V-shaped distribution *u*r, as described in Figure 8d, for the resistance measurement. The overlap between *u*r and *p*r means that the main source of variability is the digitalization noise, to which the fast C-meter adds almost no contribution.

**Table 4.** Comparison of the ATmega328P, ATmega32U4 and Fluke 8840A measured load capacitance (*C*LOAD) values ± standard deviation (SD) through the fast acquisition mode.

The sensitivity estimates were performed according to the same lines described in Section 3.1, this time for the representative values of 18 pF and 22 pF, with small increments of 1, 1.2 and 1.5 pF. The sensitivity was estimated to be about 10–20 fF in both cases. The student *t*-test analysis also concluded that all the capacitance measurement datasets were different from each other (*p* < 0.05).

#### *3.3. Characterization of Isolated Capacitance Measurements: Transient Acquisition Method*

The capacitance meter in the transient mode was tested according to the methodology described in Section 2.5.2 with different commercial capacitors ranging from 100 pF to 4.7 mF. The transient acquisition mode requires waiting until the TTL logic unit returns '1' and the elapsed time (∆*t*) until that transition. The measurements of port *P*A0 (*N*A0), taken at the transition and the corresponding elapsed time (∆*t*) are shown in Figure 10a.

The upper graph shows *N*A0 as symbols. Note that by definition these *N*A0 readings correspond to TTL parameter *V*IH—High-Level Input Voltage (because they are acquired at the transition). The same graph shows that the lower the capacitance, the higher the *V*IH of the TTL unit. This aspect is consistent with the expected operation mode of the TTL unit. In fact, the TTL unit uses the output high-level current (*i*HL) as a test condition, thence, as *C*LOAD → *C*pin, the more leakage current flows through *C*LOAD, leading to a non-constant *V*IH. It should be remarked that the inconstancy of the threshold does not represent a problem for the application of Equation (7), since it only requires a given time and the associated reading *V*A0.

*V*IH stabilizes above 22 nF because in that range *i*HL remains essentially undisturbed. This allows the estimation of the "basal" *V*IH (∆*N*A0) averaging the values of *N*A0 at the transition for all samples above 22 nF, specifically ∆*N*A0 ∼= 536 for the ATmega328P and ∆*N*A0 ∼= 331 for the ATmega32U4, which are represented by the green dashed lines. The measured values of ∆*N*A0 are consistent with the typical values described in Table 1.

**Figure 10.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to record an isolated load capacitance (*C*LOAD) through the transient acquisition mode. (**a**) Measured ADC value and time (Δ*t*) until the TTL unit changes to digital state high, logic '1' at port PA0 (*N*A0). Each ADC and Δ*t* sample consist of an average of 100 consecutive measurements. (**b**) Measured load capacitance (*C*LOAD) given by Equation (7). The green dashed lines represent the theoretical lines. (**c**) Relative accuracy (*ar*) and (**d**) relative precision (*pr*) of the measurements in function of *C*nominal. The black dashed line represents the relative uncertainty (*ur*) of the *C*LOAD measurements according to Equation (16). The white and grey shading areas highlight the levels of *ur*, *ar* and *pr* better than 5%, 10% and 20%. A legend to describe the color scheme used in all plots of Figure 10 was included. **Figure 10.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to record an isolated load capacitance (*C*LOAD) through the transient acquisition mode. (**a**) Measured ADC value and time (∆*t*) until the TTL unit changes to digital state high, logic '1' at port *P*A0 (*N*A0). Each ADC and ∆*t* sample consist of an average of 100 consecutive measurements. (**b**) Measured load capacitance (*C*LOAD) given by Equation (7). The green dashed lines represent the theoretical lines. (**c**) Relative accuracy (*a*r) and (**d**) relative precision (*p*r) of the measurements in function of *C*nominal. The black dashed line represents the relative uncertainty (*u*r) of the *C*LOAD measurements according to Equation (16). The white and grey shading areas highlight the levels of *u*r, *a*r and *p*r better than 5%, 10% and 20%. A legend to describe the color scheme used in all plots of Figure 10 was included.

The upper graph shows *N*A0 as symbols. Note that by definition these *N*A0 readings correspond to TTL parameter *V*IH—High-Level Input Voltage (because they are acquired at the transition). The same graph shows that the lower the capacitance, the higher the *V*IH of the TTL unit. This aspect is consistent with the expected operation mode of the TTL unit. In fact, the TTL unit uses the output high-level current (*i*HL) as a test condition, thence, as *C*LOAD → *C*pin, the more leakage current flows through *C*LOAD, leading to a non-constant *V*IH. It should be remarked that the inconstancy of the threshold does not represent a problem for the application of Equation (7), since it only requires a given time and the associ-The measured elapsed time (∆*t*) shown in the bottom graph of Figure 10a closely matches the green dashed line, which represents the characteristic time constant *τ* = *R*T*C*LOAD, where *R*T = *R*AIN || *R*pu + *R*out. The linearity still holds in spite of a non-constant *V*IH due to the role of *i*HL, since the leakage current is also determined by the RC constant of the circuit. The RT values differ only slightly for the two micro-controllers (*R*T ∼= 35 kΩ for ATmega328P and *R*T ∼= 37 kΩ for ATmega32U4), causing overlap of the corresponding time constant lines.

ated reading *V*A0. *V*IH stabilizes above 22 nF because in that range *i*HL remains essentially undisturbed. This allows the estimation of the "basal" *V*IH (Δ*N*A0) averaging the values of *N*A0 at the transition for all samples above 22 nF, specifically Δ*N*A0 ≅ 536 for the ATmega328P and Δ*N*A0 ≅ 331 for the ATmega32U4, which are represented by the green dashed lines. The measured values of Δ*N*A0 are consistent with the typical values described in Table 1. For the smallest capacitances (*C*LOAD < 1 nF), ∆t tends toward a plateau (∆*t*min) given by 12.5 µs for both micro-controllers, because *C*LOAD → *C*pin. Thus, the *C*LOAD values determined with Equation (7), and shown in Figure 10b, are affected by larger errors in the low capacitance range. This is not very apparent in this figure, where the data points seem very close to the green dashed line (*C*LOAD = *C*nominal) because of the logarithmic scale. Still, at the end of Section 3.3, Table 5 provides numeric detail on the data shown in Figure 10b.

The measured elapsed time (Δ*t*) shown in the bottom graph of Figure 10a closely matches the green dashed line, which represents the characteristic time constant *τ* = *R*T*C*LOAD, where *R*T = *R*AIN || *R*pu + *R*out. The linearity still holds in spite of a non-constant *V*IH due to the role of *i*HL, since the leakage current is also determined by the RC constant

**Table 5.** Comparison of the ATmega328P, ATmega32U4 and Fluke 8840A measured load capacitance (*C*LOAD) values ± standard deviation (SD) through the transient acquisition mode.

The plots of *a*r in Figure 10c illustrate better the difficulties in the low capacitance ranges. The relative accuracy drops significantly (worse than 5%) below 70 nF for the ATmega32U4 and below 10 nF for the ATmega328P. However, both remain, at least, on a 5% accuracy level above those critical values, representing a linear response of the instrument across 6 decades.

Figure 10d shows *p*r (points) and *u*r (dashed lines). Contrary to the fast C-meter case, here the *u*r and *p*r lines are clearly above *u*r, which means that the method introduces sources of noise other than digitalization. This is probably because variations of some ADC units in the threshold level impact much more the measurement than one ADC unit only, related to the digitalization error. These variations may be caused by the internal noise of the micro-processors. The performance degradation in the low capacitance regime is also evident from this figure.

The sensitivity estimates were performed according to the same lines described in Section 3.1, for the representative value of 1 µF, with small increments of 1.8, 2.2, 2.7, 3.3, 3.9 and 4.7 nF. The sensitivity was estimated to be about 10–20 fF in both cases. The student *t*-test analysis also concluded that all the capacitance measurement datasets were different from each other (*p* < 0.05).

#### *3.4. Characterization of Measurements for Serial RC Networks*

Using different sets of commercial resistors varying in factors of 10, from 10 Ω to 10 MΩ, and capacitors with 2 samples per order of magnitude, from 100 pF to 4.7 mF, seven trials were made to test the methodology described in Section 2.6. Each trial consisted of keeping the *R*LOAD constant and varying the *C*LOAD. Figure 11 compiles a total of 14 trials carried out with the two micro-controllers. The white points with red edges represent the data measured with the ATmega328P, and the blue points represent the ATmega32U4. They are mostly overlapped.

duces the same type of distortion in Figure 11b, top.

**Figure 11.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to measure a serial RC network. (**a**) Measured ADC value at *t =* 0. (**b**) Measured ADC value and time (Δ*t*) until *V*A1 ≥ *V*C. (**c**,**d**) Obtained *R*LOAD and *C*LOAD values according to Equations (2) and (10), respectively. A legend to describe the color scheme used in all plots of Figure 11 was included. The black dashed lines always represent the theoretical lines. **Figure 11.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to measure a serial RC network. (**a**) Measured ADC value at *t =* 0. (**b**) Measured ADC value and time (∆*t*) until *V*A1 ≥ *V*C. (**c**,**d**) Obtained *R*LOAD and *C*LOAD values according to Equations (2) and (10), respectively. A legend to describe the color scheme used in all plots of Figure 11 was included. The black dashed lines always represent the theoretical lines.

The method implies measurement of the port *P*A0 voltage level (*V*A0) at *t* = 0 to find the offset voltage (*V*R) and at *t* = Δ*t* ≥ *τ*, to find the voltage level *V*C (defined in Section 2.6). Figure 11a,b show the measured discrete values (*N*A0) at the instants *t* = 0 and *t* ≥ *τ*, respectively, with both micro-controllers. Figure 11b also includes in the bottom graph the measured elapsed time (Δ*t*) until *V*A1 ≥ *V*C, together with the theoretical time constants, *τ* = *R*T*C*LOAD. Note that, from Equation (9), *N*A0(*t* = 0) = *V*R, which is independent of *C*LOAD. This means that all the curves in Figure 11a should be horizontal lines. However, the minimum available acquisition time (ca. 3 µs) is insufficient to capture the initial curve values for *C*LOAD < 1 µF. Thus, the captured *N*A0 values at *t* = 0 tend to *N*max in the limit of very small capacitances. This explains why the (ideal) straight lines become distorted in Figure 11a, especially for lower *R*LOAD. Likewise, the plateau *N*A0 (*t* ≥ *τ*) = *V*C is reached for any *C*LOAD > 100 nF, which hampers the measurements of *N*A0 after *t* ≥ *τ* in this range and in-

*R*LOAD and *C*LOAD were determined through the use of Equations (2) and (10), with the results shown in Figure 11c,d, respectively. The horizontal lines in Figure 11c represent The method implies measurement of the port *P*A0 voltage level (*V*A0) at *t* = 0 to find the offset voltage (*V*R) and at *t* = ∆*t* ≥ *τ*, to find the voltage level *V*C (defined in Section 2.6).

the ideal result, *R*measured = *R*LOAD. The measured *R*LOAD values are unreliable within a domain in the R-C plane approximately defined by *R*nominal *C*nominal < 10−4 s. As discussed above, the system loses accuracy for smaller values of *R*LOAD. In fact, when *R*LOAD ≪ (*R*AIN || *R*pu) + *R*out, then *R*T = (*R*AIN || *R*pu) + *R*LOAD + *R*out ≈ *R*pu + *R*out, and the Figure 11a,b show the measured discrete values (*N*A0) at the instants *t* = 0 and *t* ≥ *τ*, respectively, with both micro-controllers. Figure 11b also includes in the bottom graph the measured elapsed time (∆*t*) until *V*A1 ≥ *V*C, together with the theoretical time constants, *τ* = *R*T*C*LOAD. Note that, from Equation (9), *N*A0(*t* = 0) = *V*R, which is independent of *C*LOAD. This means that all the curves in Figure 11a should be horizontal lines. However, the minimum available acquisition time (ca. 3 µs) is insufficient to capture the initial curve values for *C*LOAD < 1 µF. Thus, the captured *N*A0 values at *t* = 0 tend to *N*max in the limit of very small capacitances. This explains why the (ideal) straight lines become distorted in Figure 11a, especially for lower *R*LOAD. Likewise, the plateau *N*A0 (*t* ≥ *τ*) = *V*C is reached for any *C*LOAD > 100 nF, which hampers the measurements of *N*A0 after *t* ≥ *τ* in this range and induces the same type of distortion in Figure 11b, top.

*R*LOAD and *C*LOAD were determined through the use of Equations (2) and (10), with the results shown in Figure 11c,d, respectively. The horizontal lines in Figure 11c represent the ideal result, *R*measured = *R*LOAD. The measured *R*LOAD values are unreliable within a domain in the R-C plane approximately defined by *R*nominal *C*nominal < 10−4 s.

As discussed above, the system loses accuracy for smaller values of *R*LOAD. In fact, when *R*LOAD (*R*AIN || *R*pu) + *R*out, then *R*T = (*R*AIN || *R*pu) + *R*LOAD + *R*out ≈ *R*pu + *R*out, and the information about *R*LOAD is lost. For this reason, the higher the *R*LOAD, the better the accuracy. This observation is valid for both micro-controllers, except for the trials performed with a *R*LOAD of 10 MΩ since *N*A0 → *N*max at *t* = 0.

The measurements of the elapsed time (∆*t*), after *V*A0 ≥ *V*C, shown in the bottom graph of Figure 11b, exhibit a relative shift in the vertical axis due to the different *R*LOAD values. Deviations from the straight line are consequence of the excess digitalization uncertainty. This aspect is evidenced after determination of the *C*LOAD values using Equation (10) and shown in Figure 11d, where the deviations from the black dashed line (*C*LOAD = *C*nominal) relate to the excess digitalization uncertainty.

Overall, there is a trade-off between the *R*LOAD and *C*LOAD ranges for best accuracy. There are three extreme regimes: (case 1) *R*LOAD is large (>1 MΩ), irrespective of the *C*LOAD value: the accuracy of the measurements is good for the resistance and poor for the capacitance; (case 2) small *R*LOAD (<100 kΩ) and large *C*LOAD (>1 nF): measurements with poor accuracy for the resistance, good for the capacitance; (case 3) small *R*LOAD (<100 kΩ) and small *C*LOAD (<0.1 nF): measurements with very poor accuracy for the resistance, poor for the capacitance. Outside these extreme regimes, the accuracy is at least acceptable for *R*LOAD and *C*LOAD simultaneously.

#### *3.5. Characterization of Measurements for Parallel RC Networks*

The experimental procedures to perform the characterization of measurements for parallel RC networks were the same as those of the previous section.

For the parallel RC, the saturation voltage (*V*F) lies below *V*S, and it is necessary to determine both *V*F and *τ* from the data. There are simple and computationally light algorithms allowing the identification of a stationary plateau, such as that occurring at *V*F. These have been tested and verified, but including here the description of such methods would increase the length of this report. Thus, the subsequent analysis assumes that *τ* is already known. No generality is lost with this assumption.

Therefore, to each combination of a parallel RC network (*R*LOAD || *C*LOAD) that was measured, the time constant *τ* was directly assumed as *R*T*C*LOAD. The total acquisition time was set to 10*τ*, *V*F was read from *V*A0 at *t* = 5*τ* and *V*C was read from *V*A0 at *t* = *τ*.

Figure 12 aligns the results in two columns. The left column [(a) and (c)] refers to the measurements of *R*LOAD values and the right one [(b) and (d)] refers to the measurements of *C*LOAD values. The *N*A0 values at the instants *t* = 5*τ* and *t* = *τ* are shown in Figure 12a,b, respectively. Figure 12c,d show the *R*LOAD and *C*LOAD values, which were obtained from Equations (2) and (12), respectively.

The *R*LOAD values are generally in line with the measurements carried on with isolated resistors shown in Figure 8b, but with few deviations to linearity (at 10 Ω and any *C*LOAD, for the ATmega328P; at 1 MΩ and *C*LOAD > 1 µF, for both micro-controllers).

As discussed before, in Section 3.4, a too large minimal acquisition time and/or the excess of digitalization noise are the reason the collected samples deviate from the theoretical lines represented by the horizontal black dashed lines. Similarly, the *C*LOAD values are in line with the measurements carried on with isolated capacitors shown in Figure 9b. However, the accuracy of the measurements is variable, for the same reasons mentioned above.

Overall, there is a trade-off between the *R*LOAD and *C*LOAD ranges for best accuracy. There are two extreme regimes: (case 1) *C*LOAD is small (<1 µF), and *R*LOAD is large (<1 kΩ): the accuracy of the measurements is good for the resistance and poor for the capacitance; (case 2) large *R*LOAD (>1 MΩ) and small *C*LOAD (<1 µF): measurements with very poor accuracy for the capacitance, and poor for the resistance. Outside these extreme regimes, the accuracy is at least acceptable for *R*LOAD and *C*LOAD simultaneously.

**Figure 12.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to measure a parallel RC network. (**a**) Measured ADC value at *t =* 5*τ*. (**b**) Measured ADC value at *t = τ*. (**c**,**d**) Obtained *R*LOAD and *C*LOAD values according to Equations (2) and (12), respectively. A legend to describe the color scheme used in all plots of Figure 12 was included. The black dashed lines always represent the theoretical lines. **Figure 12.** Comparison between the ATmega328P and ATmega32U4 AVR® micro-controllers configured to measure a parallel RC network. (**a**) Measured ADC value at *t =* 5*τ*. (**b**) Measured ADC value at *t = τ*. (**c**,**d**) Obtained *R*LOAD and *C*LOAD values according to Equations (2) and (12), respectively. A legend to describe the color scheme used in all plots of Figure 12 was included. The black dashed lines always represent the theoretical lines.

#### The *R*LOAD values are generally in line with the measurements carried on with isolated **4. Discussion and Conclusions**

resistors shown in Figure 8b, but with few deviations to linearity (at 10 Ω and any *C*LOAD, for the ATmega328P; at 1 MΩ and *C*LOAD > 1 µF, for both micro-controllers). As discussed before, in Section 3.4, a too large minimal acquisition time and/or the excess of digitalization noise are the reason the collected samples deviate from the theoretical lines represented by the horizontal black dashed lines. Similarly, the *C*LOAD values are in line with the measurements carried on with isolated capacitors shown in Figure 9b. This work described and characterized methods to accurately measure impedance using Arduino® boards with built-in AVR® micro-controllers. This is highly remarkable considering the ultra-low cost of the hardware. The measurement method allows the extraction of the resistance (R) and capacitance (C) values of either isolated or series and parallel configuration. Furthermore, inductance (L) measurements can be also performed, yet the range of measurable values is not very useful.

However, the accuracy of the measurements is variable, for the same reasons mentioned above. Overall, there is a trade-off between the *R*LOAD and *C*LOAD ranges for best accuracy. There are two extreme regimes: (case 1) *C*LOAD is small (<1 µF), and *R*LOAD is large (<1 kΩ): To check the cross-platform applicability of our proposed RCL-meter, two different AVR® micro-controllers assembled on Arduino® boards were selected, namely the ATmega328P assembled on an Arduino® Uno and the ATmega32U4 assembled on an Arduino® Leonardo. A benchmark was made to test the performance of micro-processors.

the accuracy of the measurements is good for the resistance and poor for the capacitance; (case 2) large *R*LOAD (>1 MΩ) and small *C*LOAD (<1 µF): measurements with very poor accuracy for the capacitance, and poor for the resistance. Outside these extreme regimes, the accuracy is at least acceptable for *R*LOAD and *C*LOAD simultaneously. **4. Discussion and Conclusions**  This work described and characterized methods to accurately measure impedance using Arduino® boards with built-in AVR® micro-controllers. This is highly remarkable As for the measurements of isolated resistances and capacitances, the ATmega32U4 outperforms the ATmega328P, and some specific differences were identified. For instance, the ATmega32U4 was revealed to be more efficient in terms of acquisition time, providing a significant improvement when recording long-term transients. In the worst-case scenario, when recording an isolated capacitance (*C*LOAD = 4.7 mF) through the transient acquisition mode, the ATmega32U4 performs two times faster than the ATmega328P. In addition, when measuring both *C*LOAD and *R*LOAD values of in-series or parallel RC networks, the ATmega32U4 takes a slight advantage over the ATmega328P for larger values of *R*LOAD, while, conversely, the ATmega32U4 performs better for larger values of *C*LOAD.

The noise profiles of the direct measurements (R-meter and fast C-meter) are essentially defined by the digitalization noise, while the transient C-meter brings an important extra noise source from the variability in the determination of instants of time required to perform the calculations.

The fast and transient C-meter methods complement each other, since the fast method is best for low capacitances and the transient method best for high capacitances. Operated together, they are able to deliver a relative accuracy equal to or better than 20% in the range 100 fF–10 mF, that is, across 11 orders of magnitude. Furthermore, the accuracy is equal to or better than 5% in the ranges 100 fF–100 pF and 100 nF–10 mF. The series and parallel RC combinations are also able to deliver good measurements of R and C in specific domains of the R-C plane.

Additional investigations were made to analyze the performance of both Arduino® boards supplied via a large power bank (Litionite Tanker 90 W/50,000 mAh) and using a data logger shield (RobotDynTM, Zhuhai, China) to store the measurements in a local micro-SD card. This work led to the conclusion that no substantial improvements are achieved by using a low-noise and low-uncertainty voltage supply, and therefore all presented data considers the typical noise and uncertainty from a common USB interface voltage supply source. However, the voltage supply unit determines the overall measurement quality in regions close to the ADC unit threshold values (*N*) for *N* < 20 or *N* > 1000.

Additionally, measurements of the same *R*LOAD and *C*LOAD values were made with commercial instruments and presented in the manuscript to provide insight on the overall performance of the ATmega328P and ATmega32U4 micro-controllers as a low-cost alternative to more expensive and sophisticated instruments.

Moreover, the concept proposed in this work, based on AVR® micro-controllers, may possibly be extended to other microcontrollers such as the STM32 family based on ARM architecture. The latter have more or improved integrated hardware features relative to the former, such as more flash memory, higher resolution ADC drive and faster clocks. On the other hand, using more sophisticated microcontrollers brings the disadvantage of idle but power-consuming internal hardware, for example, the digital-to-analog unit (DAC), which is not required in the present work. In any case, the inherent specificities of each architecture imply different implementations, difficult to cover in a single report.

The work carried out in the investigation of an ultra-low-cost RCL meter was mainly targeted towards impedimetric biosensor measurements, in order to facilitate the integration of the sensing and processing layers to the IoT. Its simplicity opens new possibilities for the improvement of ongoing and future projects in the field of smart sensing. The long-term goal of this work is to integrate the control of the sensing and processing layers into the Web of Things (WoT), which is an upper layer of interaction between devices that may be managed by artificial intelligence.

**Supplementary Materials:** The following supporting information can be downloaded at: https: //www.mdpi.com/article/10.3390/s22062227/s1, C++ code A.1: High-level routine to measure isolated resistances; C++ code A.2: High-level routine to measure isolated capacitances through the fast acquisition mode; C++ code A.3: High-level routine to measure isolated capacitances through the transient acquisition mode; C++ code A.4: High-level routine to measure a series RC-network; C++ code A.5: High-level routine to measure a parallel RC-network; C++ code A.6: High-level routine to measure an isolated inductance; MATLAB code B.1: High-level routine for fitting the Ordinary Least Squares (OLS) function to the resistance values; MATLAB code B.2: High-level routine for fitting the Ordinary Least Squares (OLS) function to the capacitance values.

**Author Contributions:** Conceptualization, P.M.C.I. and P.S.; methodology, P.M.C.I. and P.S.; software, P.M.C.I.; validation, P.M.C.I.; formal analysis, P.M.C.I.; investigation, P.M.C.I. and R.G.; resources, R.G.; data curation, P.M.C.I.; writing—original draft preparation, P.M.C.I.; writing—review and editing, R.G. and P.S.; supervision, P.S.; project administration, R.G.; funding acquisition, R.G. All authors have read and agreed to the published version of the manuscript.

**Funding:** This research was funded by the FCT—Fundação para a Ciência e a Tecnologia, Portugal, through the CEOT project UIDB/00631/2020 CEOT BASE and UIDP/00631/2020 CEOT PROGRAMATICO. This work was also developed under the FEDER/Portugal2020 project NIBAP (ALG-01-0247-FEDER-037303).

**Institutional Review Board Statement:** Not applicable.

**Informed Consent Statement:** Not applicable.

**Data Availability Statement:** Not applicable.

**Conflicts of Interest:** The authors declare no conflict of interest.

#### **References**

## *Article* **Blockchain Based Authentication and Cluster Head Selection Using DDR-LEACH in Internet of Sensor Things**

**Sana Amjad 1 , Shahid Abbas 1 , Zain Abubaker 1 , Mohammed H. Alsharif 2 , Abu Jahid 3 , Nadeem Javaid 1,4,\***

**Abstract:** This paper proposes a blockchain-based node authentication model for the Internet of sensor things (IoST). The nodes in the network are authenticated based on their credentials to make the network free from malicious nodes. In IoST, sensor nodes gather the information from the environment and send it to the cluster heads (CHs) for additional processing. CHs aggregate the sensed information. Therefore, their energy rapidly depletes due to extra workload. To solve this issue, we proposed distance, degree, and residual energy-based low-energy adaptive clustering hierarchy (DDR-LEACH) protocol. DDR-LEACH is used to replace CHs with the ordinary nodes based on maximum residual energy, degree, and minimum distance from BS. Furthermore, storing a huge amount of data in the blockchain is very costly. To tackle this issue, an external data storage, named as interplanetary file system (IPFS), is used. Furthermore, for ensuring data security in IPFS, AES 128-bit is used, which performs better than the existing encryption schemes. Moreover, a huge computational cost is required using a proof of work consensus mechanism to validate transactions. To solve this issue, proof of authority (PoA) consensus mechanism is used in the proposed model. The simulation results are carried out, which show the efficiency and effectiveness of the proposed system model. The DDR-LEACH is compared with LEACH and the simulation results show that DDR-LEACH outperforms LEACH in terms of energy consumption, throughput, and improvement in network lifetime with CH selection mechanism. Moreover, transaction cost is computed, which is reduced by PoA during data storage on IPFS and service provisioning. Furthermore, the time is calculated in the comparison of AES 128-bit scheme with existing scheme. The formal security analysis is performed to check the effectiveness of smart contract against attacks. Additionally, two different attacks, MITM and Sybil, are induced in our system to show our system model's resilience against cyber attacks.

**Keywords:** blockchain; clustering; authentication; malicious node detection; LEACH protocol; service provisioning; interplanetary file system; security

## **1. Introduction**

The wireless sensors networks (WSNs) play an important part in the Internet of sensors things (IoST) [1]. IoST is useful in sensing data from the environment and is used in the field of energy trading, surveillance, smart grids, etc., [2,3]. It connects with the Internet and automates the monitoring system without any involvement from a third party. The IoST network consists of sensor nodes that perform environmental monitoring [4]. However, the sensor nodes in the WSNs face the issue of non-repudiation, limited resources, presence of malicious nodes, etc., [5–7]. Many studies are proposed to solve these aforementioned issues [8–10]. However, these studies have issues of single point of failure (SPOF) and performance bottlenecks due to their centralized architecture.

**Citation:** Amjad, S.; Abbas, S.; Abubaker, Z.; Alsharif, M.H.; Jahid, A.; Javaid, N. Blockchain Based Authentication and Cluster Head Selection Using DDR-LEACH in Internet of Sensor Things. *Sensors* **2022**, *22*, 1972. https://doi.org/ 10.3390/s22051972

Academic Editor: Alexandru Lavric

Received: 25 December 2021 Accepted: 22 February 2022 Published: 2 March 2022

**Publisher's Note:** MDPI stays neutral with regard to jurisdictional claims in published maps and institutional affiliations.

**Copyright:** © 2022 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license (https:// creativecommons.org/licenses/by/ 4.0/).

To overcome these aforementioned issues, many researchers provide different mechanisms to remove third parties by introducing blockchain in the WSNs. Blockchain is a secure and decentralized protocol that solves many issues such as SPOF, a third party involvement, etc., [11]. Moreover, the distributed and tamper-proof ledger in blockchain solves trust issues between unknown entities. The transactions that are performed by entities in the network are confirmed by the miners. These transactions are validated by the miners using various consensus mechanisms, such as proof of work (PoW) [12], proof of authority (PoA), proof of stake, etc., [13]. In the PoW mechanism, all the nodes participate in solving the mathematical puzzle. The node that solves it first validates the transactions. The blockchain is created by validating and storing the transactions. Moreover, a smart contract is used in blockchain in which all the terms and conditions are finalized. Additionally, it eliminates the third party. Moreover, blockchain provides security in the network by malicious nodes' detection through Merkle tree [14,15] and also through different techniques, such as trust evaluation of nodes, etc., [16–18].

Many blockchain-based schemes are proposed to solve the issues of single point of failure, huge monetary cost, and performance bottlenecks [19–22]. However, the data of all these networks are stored on blockchain, which is very costly. When 1MB of data are stored on blockchain, it costs USD 14151.68 [23]. Moreover, PoW consensus algorithm is used in [21,22], which is not suitable for resource constrained environment.

In IoST networks, routing is an important aspect in which nodes communicate and transmit data from source to the destination. The transmitted data are controlled by different nodes in IoST that are sensor nodes, CHs and base stations (BSs). In [19], the data are processed by CHs and are forwarded to the BSs. However, authentication of network nodes is not performed. Therefore, any node can enter the network and behave maliciously. Moreover, in [19], no cost-effective data storage mechanism is proposed, which leads to expensive data storage in blockchain. As data are permanently stored on blockchain then the issues of limited storage arises. Additionally, in an IoST network, CHs fail due to high energy depletion, which affects the whole network's performance. In [21], no mechanism is proposed for the selection of new CHs. Furthermore, in PoW, the miners solve the puzzle for validating the transactions and adding the blocks into the blockchain [17,22]. This mining process takes considerable time due to puzzle's complexity, which ultimately increases network's computational cost. This paper is the extension of [24] and the contributions in the proposed work are as follows:

The rest of the paper is organized as follows. The related work is discussed in Section 2 and Table 1. The proposed system model is presented in Section 3. The simulation results and the validation of system model are discussed in Section 4. The formal security analysis is discussed in Section 5. Section 6 contains the conclusion of the proposed work and future work.

#### **Table 1.** Related work.

#### **2. Related Work**

The studies related to the blockchain integrated with WSNs are discussed in this section. The studies are categorized based on the limitations they have addressed.

#### *2.1. Nodes' Authentication*

The sensor nodes perform an important role in performing many tasks in IoT networks and nodes' identities authentication is one of them. The nodes in the IoT network work together and provide the services to the buyers. However, the nodes' identities authentication is not performed in [13,21], which leads to malicious nodes becoming the part of the network and affecting its performance.

Authentication is required to restrict unauthenticated nodes from entering the network. The unauthenticated nodes behave maliciously by tampering data during routing, as well as refusing to forward data packets toward the destination. Therefore, in [20], the authors propose a lightweight authentication mechanism for WSNs. The sensor nodes use unique sequence numbers during data transmission based on the concept of a Merkle tree. Secure hashing algorithm 1 (SHA-1) is used to authenticate the nodes. Although in [25], the network nodes are authenticated using routing protocol. However, due to centralized authority, a trust issue is created. In [26], the wireless body area network is comprised of sensor nodes, which collect the information of human body parts and publicly forward it to the local node. Health is a very critical and sensitive matter, and the malicious nodes can enter in the network and misuse the data. However, these nodes are not authenticated in the network.

#### *2.2. Lack of Data Storage*

The authors in [27] propose an incentive based data storage mechanism. Each node stores data in the blockchain; however, computational cost increases due to the usage of PoW consensus mechanism. Although, in [29], mining is performed using PoW. The PoW increases the computational cost. Therefore, a lightweight blockchain network is proposed to reduce blockchain storage and computational requirements in IoST environment. The blockchain is merged with IoTs in [30] to aggregate the blocks' header information and transmit it to the IoT nodes. However, keeping a copy of data in a resource constrained network is not appropriate.

#### *2.3. Lack of Data Privacy*

In [19], no technique is proposed to prevent the network data from being stolen by malicious nodes. Additionally, in [31], the products are controlled and monitored by workers in the industry. However, the issue of data transparency is created. The important information of the products may be stolen by the workers. In addition, the misuse of important products' record is also possible. Additionally, in the WSNs, the security of data and its privacy is compromised [13]. In [32], the authors state that collecting the information from crowdsensing is essential for the network nodes. However, privacy protection of the data is not considered.

Whereas, in [33], the data-driven network is converged with WSN and the reserving information is copied for sharing it in the network. However, the security of data is being compromised by the malicious nodes. Moreover, in [22], the growth of IoT in the smart city creates data latency, scalability, and huge bandwidth issues. Therefore, hybrid blockchain network is proposed and SDN controllers are used as an interface between the IoT. Additionally, digital signatures are used for the data security in the network. The sensor nodes transmit the data to IoT nodes in [37]; however, no mechanism for data security is proposed, which causes data security issue.

#### *2.4. Lack of Resources*

In [27], the chances of malicious nodes' existence are high in the network, which do not allow the legitimate nodes to participate in the network. Additionally, blockchain technology is used for different purposes, such as content caching in [28]. Moreover, in [27,28], the authors use PoW consensus mechanism, in which high computational power is required. The blockchain is integrated with IoT for secure routing in [30]. However, the nodes in the network have very low storage capability and these resource constrained

nodes cannot keep the copied records in them. Whereas, in [38], PoW is replaced with Tangle based technology to provide fast and secure information. However, the frequency of transaction is very low. Moreover, the IoT sensor nodes' energy depletes very fast due to the high computational overhead. Low computational power of IoT nodes hinders the validation of transactions.

#### *2.5. Malicious Nodes' Existence*

Obtaining the exact location of sensor nodes in the network is an emerging domain nowadays. However, malicious behavior of sensor nodes lead to the broadcast of wrong location information. Due to this, the security of the network is compromised [34]. Additionally, in [17], no mechanism is proposed to detect the malicious nodes in the network. Different fields, such as manufacturing products and healthcare use IoT [35]. However, still some challenges are faced by provisioning process, such as provision of malicious services. Furthermore, the client can behave maliciously by repudiating on behalf of services. In [36], the sensor nodes find the shortest path for communication. However, there is no mechanism to secure the data and to find the malicious nodes.

#### *2.6. Single Point of Failure Issue*

The network performance is affected when the identity authentication of nodes is compromised. In [21], the nodes' identity depends on central authority servers that become the reason for SPOF. Whereas, in [39], the authors integrate the software-defined networking and blockchain to detect attacks without any involvement of a third party. The data are sent directly to the centralized cloud. However, bandwidth and latency issues arise. The smart contracts in the blockchain system share the trained classifiers with the cloud layer for fusion. However, SPOF issue arises due to central authority. In [25], a centralized authority is used to authenticate the routing nodes. Due to the central authority used in the system, SPOF issue arises. In [40], the data are stored in the network by a centralized system, which leads to SPOF issue.

Table 2 presents problems identified in existing literature, their proposed solutions and their validations. An authentication scheme is proposed to prevent from the unauthenticated nodes, so that only authenticated nodes are allowed to perform an action. In DDR-LEACH protocol, motivated from [41], the highest degree node is selected, which solves the node battery issue. Moreover, IPFS is used to solve the costly data storage issue of the blockchain. IPFS stores the data cost-effectively and distributively. Additionally, the issue of high computational cost is resolved using PoA consensus mechanism.

**Table 2.** Mapping between limitations, solutions, and validations.

#### **3. Proposed System Model**

In this section, the assumptions, components and work flow of the proposed system model are discussed.

### *3.1. Assumptions*

The system model is based on following assumptions:

#### *3.2. System Components*

In this section, the components of the proposed system model are discussed as depicted in Figure 1. The components include IoST, buyers, IPFS, and blockchain.

**Figure 1.** Blockchain based nodes' authentication and CHs' selection in IoST.

*Internet of sensor things:* The IoST is an emerging technology, which consists of sensor nodes deployed for collecting the environmental data [32]. The sensor nodes sense the surrounding information such as the data of humidity, pressure, and temperature, etc., [42]. In the proposed system model, the IoST consists of sensor nodes, CHs, and BSs. Their working is described in Section 3.3.

*Buyers:* To prevent the network from malicious activities, the buyes are registered and authenticated in the blockchain network. For that purpose, registration and authentication schemes are used, motivated from [21].

*Interplanetary file system:* It is a distributed platform where data are stored in the form of chunks. Whenever the data are stored on IPFS, a hash is generated. IPFS generates the 32-bit hash in result of data storage, which is stored on the blockchain as a record.

#### *3.3. Workflow of the System Model*

The system model is discussed in the steps given below.

*Step 1. Initialization*: The blockchain technology introduces a smart contract, which is a digital agreement that works without the involvement of any third party. It is deployed on BSs that handle the network transactions. The blockchain is used for registering sensor nodes in the network by storing their credentials for authentication. Credentials are sent in the form of a message shown in following equation.

$$(ID\_{Node} \, MACAddr\_{Node} \, Reputation\_{Node})\_{Packet} = Message \, \tag{1}$$

In the registration and authentication process, MAC address, ID, and Reputation of nodes are used as credentials. *ReputationNode* is the reputation value given to a specific node on the basis of its previous history of interaction with the network. If the node provides accurate data to the network, its reputation increases; otherwise, it decreases. The credentials are stored in the blockchain using a asymmetric scheme. The blockchain also keeps their addresses to prevent the network free from malicious activities. Therefore, during authentication process, the credentials are matched with already stored data. If the credentials are not matched with already stored data, then the node is considered as a malicious node.

*Step 2. CH selection*: The IoST network consists of sensor nodes, CHs, and BSs. The sensor nodes collect the data from the environment and send it to CHs for performing computation. CHs receive data from sensor nodes, process the data, and send it to BSs. BS requests IPFS for storing data; IPFS calculates hash value of the data and sends it to BS. In processing and storing the data, the energy of CHs depletes rapidly. To solve this issue, our proposed model provides a mechanism that selects CHs from ordinary nodes using DDR-LEACH. The CHs are selected based on three parameters: residual energy, minimum distance from BSs, and maximum degree of a node. If a node satisfies the criteria mentioned earlier, then it is selected as CH. CH aggregates the data packet and transmits it to the destination, as given in Algorithm 1. If more than one nodes meet the criteria, then CH is randomly selected.

**Algorithm 1:** CH selection.

*Step 3. Nodes*0 *authentication*: In this step, sensor nodes are authenticated in the blockchain. The sensor nodes' authentication is important to revoke malicious nodes from the network and provide the secure services. The messages are exchanged between the WSN nodes and the distributed ledger, i.e., blockchain, after being encrypted using asymmetric encryption. The encryption is performed over the registration data for providing more security. The node encrypts the data with the public key of the BS (known to everyone in the network) and then BS decrypts the encrypted data with its private key (known to BS only) and stores data in the blockchain. Moreover, the solution for providing the

keys for encryption and decryption remains the same because the keys can neither be invalidated nor can be changed. Additionally, whenever any node performs any activity in the network, its credentials are verified by the BS. Therefore, this solution is sufficient to provide the security to the overall network. There are many papers that are based on nodes' authentication, i.e., [43,44]. As in [43], the nodes' identity authentication is performed using an encryption scheme. However, due to centralized authority, the SPOF and performance bottleneck issues arise. Although, in [44], a lightweight authentication scheme is used. However, due to centralized authority, the SPOF issue occurs. Few authentication-based papers are mentioned in the related work, i.e., [20,21]. As in [20], authentication of nodes is performed by their acknowledgment to the sink node. The nodes acknowledge the sink node based on their provided sequence numbers. However, during nodes' authentication, the PoW consensus mechanism is used, which incurs high computational cost. Although, in [21], hybrid blockchain-based nodes' authentication is performed. However, PoA is used, which incurs high computational cost. Moreover, data storage in blockchain is very costly. In our proposed system model, we have used nodes' identity authentication using a PoA consensus mechanism, which reduces computational cost. We do not claim that this authentication model is the novel work. We have embedded this authentication model with an efficient CH selection and secure storage of sensors' data. This integration of authentication model is a novel combination, as authentication mechanism is used in different scenarios [20,21,44]. Moreover, a distributed IPFS data storage mechanism is used to reduce overall monetary cost of the network. The authentication is performed by matching the credentials of nodes that are already stored in the blockchain.

When a node is taken over by a malicious node, then malicious node can transmit these data in the network to perform malicious activities. As we know, all legitimate nodes are registered with BSs and their credentials are already stored in the blockchain. When any malicious node transmits the data, it can be easily detected in authentication process because its credentials are not stored in the blockchain. In this way, the malicious node cannot perform malicious activities in our network by taking over any node. Moreover, when a malicious node is removed from the network, it is revoked from transmitting any kind of data in the network. The malicious node is removed and revoked by BSs because blockchain is deployed on them and they are responsible for validating the transactions. In the proposed model, PoA is used as the consensus mechanism for mining the transactions. It incurs less computational cost as compared to the traditional PoW consensus mechanism. Additionally, the miners are pre-selected nodes in PoA. The registered nodes are authenticated after the authentication request. The request contains *IDNode*, *MACAddrNode*, and *ReputationNode*, which are already stored on the blockchain. Blockchain checks whether the credentials provided by nodes are matched with the credentials already stored or not in the blockchain. If the credentials match the provided information, the nodes become authentic and are broadcasted as legitimate nodes. Otherwise, they are broadcasted as malicious or unauthentic nodes. The step-wise process is according to Algorithm 2.

*Step 4. Data storage*: Storing the large amount of data on the blockchain is not suitable because the storage cost is high on the blockchain. The cost of storing 1 MB data on the blockchain is approximately USD 14151.68 [23]. Therefore, BSs send data to IPFS and keep its hash values and the credential of registered nodes in the blockchain. In the blockchain, the transaction of each entity is stored in a ledger. This ledger is distributed to all entities of the network. All entities act as a foundation of the network. When any transaction is performed, the ledgers of all entities are updated simultaneously. When malicious node tries to manipulate the transaction record in a ledger of any entity, then it can easily be detected because this ledger is not matched with already stored ledger. The data are stored on IPFS in the form of chunks. IPFS does not store the data for long time. Therefore, we propose a payment method for long time data storage of IPFS. The IPFS is incentivized in order to motivate the peer nodes for storing the data. The hashes are stored on the blockchain. Only authenticated nodes obtain data using the provided hash. However, the

data storage on IPFS is temporary. Therefore, we propose an incentive method for IPFS to store a huge amount of data for a long time.

```
11 end
```
*Step 5. Service provisioning*: We use a private blockchain, deployed on BSs, to register and authenticate the nodes. In the beginning, the blockchain receives the registration request from the buyers. Then, the nodes are checked by the blockchain whether they are already registered or not. If a buyer is already registered, it discards the request. Otherwise, it allows the node for registration. Algorithm 2 shows how the authentication process works.

The already stored credentials in the blockchain are used to authenticate the buyers. A buyer must first provide its credentials for verification in the blockchain. The blockchain checks the credentials to confirm whether the node's credentials exist in the blockchain or not. If the provided credentials match with the stored one, it is considered as an authentic user; otherwise, it is considered a malicious node, which is immediately removed from the network. Afterward, if the buyer is authenticated, then the ethers are checked according to the threshold. If ethers are enough to buy the data, the hash of the requested data is sent to the buyer; otherwise, request will be rejected. After the authentication process, the buyer receives services from the network. Whenever a buyer requests the service, BS encrypts the service with buyer's secret key and sends the cypher text to the buyer.

The buyer receives the encrypted data and then decrypts it with the private Figure 2.

**Figure 2.** Interaction of buyers with IPFS.

We use AES 128-bit encryption for ensuring data security in the network. Moreover, SHA-256 is used with AES encryption to ensure data integrity. Initially, the BS calculates the hash by the SHA-256 hashing algorithm and then uploads this hash on the blockchain. After this, the BS encrypts the data with a secret key and sends these encrypted data to a client. The buyer receives the data and decrypts it with the secret key provided by the sender. After decryption of data, the buyer calculates the hash by itself using SHA-256 algorithm and compares this hash with the hash already stored in blockchain. In this way, the SHA-256 hashing technique together with the AES encryption technique ensures data security and data integrity. Moreover, we have used the AES 128-bit encryption technique in our scenario because our primary goal is to provide real time data to buyers and AES 128-bit encryption consumes a very small amount of time in encryption and decryption of

data. Furthermore, the efficiency of the AES 128-bit encryption scheme in terms of time is shown in Figure 10 in the simulation section.

In the proposed system model, 5% of the buying amount is given to IPFS as an incentive. The service provisioning mechanism is shown in Algorithm 3.

In Table 2, the mapping between limitations, proposed solutions and their validations is provided. The limitations L1 and L2 represent the unauthenticated and the malicious activities of nodes in the network, which are solved by S1. The parameter that is used to validate the nodes' authentication is message size, which is evaluated by transaction cost. The message size indicates that how many bytes it takes to authenticate a node while the transaction cost means the cost required for nodes' authentication. The third limitation L3 is the inefficient energy consumption of CHs. In S2, CHs are selected based on nodes' residual energy, minimum distance from BS and degree. If these conditions are satisfied for a node, then it becomes a CH. The network lifetime, packet delivery ratio and energy consumption are used as validation parameters. L4 indicates the high computational cost when using PoW consensus mechanism. In S3, PoA consensus mechanism is used to solve this issue, which consumes less computational resources as compared to PoW. The cost incurred when using PoA is depicted by the average transaction cost. The limitation L5 shows that the data storage on the blockchain is very costly. Therefore, a large amount of data are stored in the IPFS in S4. The average transaction cost and encryption time are taken as validation parameters. The average transaction cost shows the cost used to store data on

IPFS. At the same time, encryption time shows the time, which is used in encryption and decryption of data during service provisioning.

#### **4. Simulation Results and Discussion**

In this section, the performance evaluation of the proposed model is described. The specifications for the simulation setup include an Intel(R) Core (TM) i5-2520M CPU @ 2.50 GHz processor, 64-bit operating system, x64-based processor, and 8 GB RAM. Remix IDE is used to develop a smart contract, whereas, Ganache is used to manage the transactions. Although MetaMask is used for providing virtual currency to perform transactions. Moreover, for simulating our WSN, MATLAB is used. The use of a cryptographic scheme is simulated in Visual Studio using Python.

In the network, three types of nodes are considered for the simulations: 100 sensor nodes, 4 CHs, and 2 BSs in the network area of 100 × 100 m2 . Moreover, there are three input data in our system model: sensed data, data index, and buyer's address. The data are sensed by sensor nodes in the network. They send the sensed data to CHs for processing. The CHs after processing the data send it to BSs for further processing. The BS stores the data with data index. The sensed data with data index are provided by BSs. Furthermore, the buyer's address is the Ethereum address that is provided to each buyer when it joins the network. Initially, the nodes are registered and authenticated to provide malicious nodes free network. The simulation parameters are mentioned in Table 3.

**Table 3.** Simulation parameters.

Figure 3 illustrates the message size of network nodes. During the registration phase, unknown nodes request to become a part of the network. For the registration process, a new node first registered in the blockchain network before its participation. The nodes send their credentials to the blockchain. BS stores its credentials, and perform authentication process. The message size is large during the registration phase as compared to authentication phase because in registration phases, more resources are required to store the data on the blockchain. Whereas, in authentication phase, BS only matches the nodes' credentials with the already stored credentials, which incurs less resources.

**Figure 3.** Message size.

Figure 4 shows the transaction cost incurred during registration and authentication phases. When smart contracts are deployed, then transaction cost is incurred. The results show that the transaction cost increases with the increase in the number of packets. Similar behavior is observed for authentication and registration phases in Figure 4 as that of Figure 3. The transaction cost increases with the increased number of nodes. The authentication process takes less transaction cost because already stored registration information has to be verified.

**Figure 4.** Transaction cost during registration and authentication of nodes.

Figure 5 shows the energy consumption against the number of rounds. The comparison of LEACH protocol with DDR-LEACH is performed in terms of energy consumption. In the DDR-LEACH, energy is consumed by the nodes till 1400 rounds. Whereas, in the LEACH, the energy is consumed by the nodes till 1000 rounds. The energy consumption is high in LEACH because random CHs' selection is performed. The sensor nodes near to the BS may not participate in the network and may not be selected as CHs. Therefore, maximum energy is utilized by any of the nodes to send the data packets from source to destination. As compared to LEACH, the maximum energy is consumed by the nodes till 1400 rounds. The DDR-LEACH considers the three parameters that are maximum degree, minimum distance, and minimum energy consumption to select the CHs. The energy usage is efficient in the starting rounds because CHs are alive and working. CHs aggregate data and send it to BS. Therefore, energy consumption is decreased, as shown in Figure 5.

**Figure 5.** Energy consumption.

Figure 6 depicts that the network throughput of both schemes is zero at the start. The reason is that no data packet is sent at initials rounds. It continues to increasing with the number of rounds because large amount of packets are sent at these rounds. In DDR-LEACH, the amount of data sent from ordinary nodes to BSs is increased gradually because all the nodes are participating in the network. It gradually decreases at 1500th round, trend becomes constant. The throughput is maximum because CHs are selected using DDR-LEACH and maximum nodes are alive to send the data packets. The data packets are increased with the decrease in the number of rounds. Whereas, in LEACH, the

nodes are randomly selected and if the CHs are selected that are away from BSs, then nodes have to utilize more energy. Additionally, in DDR-LEACH, the selection of CHs is based on three parameters. Whereas, in LEACH, the randomly selected CHs die because these parameters are not considered in the CHs' selection process. Therefore, nodes inefficiently perform operations in the network and minimum data packets are sent from source to destination.

**Figure 6.** Network throughput.