scieee AI-readable full text Open interactive document viewer

Design and implementation of an impedance analyzer for bacteria detection

Maín Nadal, Víctor

Abstract

Aquest treball se centra en la implementaci ´o d’un analitzador d’imped `ancia per a ser utilit- zat en la detecci ´o i an `alisi de bacteris. El disseny se centra en la portabilitat i el cost, amb la finalitat de fer-lo apte per al treball de camp i poder fabricar m ´ultiples m `oduls per a ser utilitzats tamb ´e en la universitat amb finalitats de recerca. Per a aix `o, es realitza una etapa de recerca. En aquesta etapa es consideren, descriuen i discuteixen breument m ´ultiples topologies i m `etodes de diferents treballs. Es discuteixen els avantatges i desavantatges de cada document i se selecciona un per a ser implementat. La topologia seleccionada es discuteix amb m ´es detall per a mostrar les seves limitacions i es fa un treball te `oric per a extreure una aproximaci ´o matem `atica del comportament del circuit. Per a complementar l’an `alisi te `orica s’utilitzen simulacions per ordinador amb SPICE per a il·lustrar millor el comportament del circuit, aix´ı com per a verificar el treball te `oric i determinar l’efecte de les parasitancies i les no idealitats. Posteriorment, el circuit es dissenya en una placa de circuit impr `es utilitzant Kicad i es fabrica centrant-se en la simplicitat per a reduir costos. S’utilitza una Red Pitaya com ADC i DAC per a unir els dominis digital i anal `ogic i tamb ´e com a microcontrolador. La placa s’utilitza per a generar els senyals d’excitaci ´o i processar les formes d’ona generades per a extreure la informaci ´o necess `aria. La placa es programa en C i es crea una aplicaci ´o JavaScript senzilla i lleugera que serveix de front-end, utilitzant HTML i CSS per a crear una interf´ıcie gr `afica que permeti observar millor els resultats. Finalment, es prova el sistema per a comprovar la seva funcionalitat, es discuteixen els resultats i es comenten algunes propostes de millora. Finalment, aquest treball tamb ´e descriu el cost econ `omic i ecol `ogic del projecte, aix´ı com el cost en m `a d’obra.

Full text

TREBALL DE FI DE GRAU Grau en Enginyeria Electr` onica Industrial i Autom` atica Design and Implementation of an Impedance Analyzer for Bacteria Detection Autor: Victor Ma´ ın Nadal Departament: Electronica Director: Jordi Cosp Vilella Convocat ` oria: Octubre 2024 Titulo: Design and implementation of an impedance analyzer for the detection of bacteria Autor: V´ ıctor Ma´ ın Nadal Director: Jordi Cosp Vilella Fecha: 24 de septiembre de 2024 Este trabajo se centra en la implementaci´ on de un analizador de impedancia para ser utilizado en la detecci´ on de bacterias. El dise˜ no se centra en la portabilidad y el coste, con el fin de hacerlo apto para el trabajo de campo y poder fabricar m´ ultiples m´ odulos para ser utilizados tambi´ en en la universidad con fines de investigaci´ on. Para ello, se realiza una etapa de investigaci´ on. En esta etapa se consideran, describen y discuten brevemente m´ ultiples topolog´ ıas y m´ etodos de diferentes trabajos. Se discuten las ventajas y desventajas de cada documento y se selecciona uno para ser implementado. La topolog´ ıa seleccionada se discute con m´ as detalle para mostrar sus limitaciones y se realiza un trabajo te´ orico para extraer una aproximaci´ on matem´ atica del comportamiento del circuito. Para complementar el an´ alisis te´ orico se utilizan simulaciones por ordenador con SPICE para ilustrar mejor el comportamiento del circuito, as´ ı como para verificar el trabajo te´ orico y determinar los efectos par´ asitos y las no idealidades. Posteriormente, el circuito se dise˜ na en una placa de circuito impreso utilizando Kicad y se fabrica centr´ andose en la simplicidad para reducir costes. Se utiliza una Red Pitaya como ADC y DAC para unir los dominios digital y anal´ ogico y como microprocesador. La placa se utiliza para generar las se˜ nales de excitaci´ on y procesar las formas de onda generadas para extraer la informaci´ on necesaria. La placa se programa en C y se crea una aplicaci´ on JavaScript sencilla y ligera que sirve de front-end, utilizando HTML y CSS para crear una interfaz gr´ afica que permita observar mejor los resultados. Finalmente, se prueba el sistema para comprobar su funcionalidad, se discuten los resultados y se comentan algunas propuestas de mejora. Adicionalmente, este trabajo tambi´ en describe el coste econ´ omico y ecol´ ogico del proyecto, as´ ı como el coste en mano de obra. T´ıtol: Design and implementation of an impedance analyzer for the detection of bacteria Autor: V´ ıctor Ma´ ın Nadal Director: Jordi Cosp Vilella Datra: 24 de setembre de 2024 Aquest treball se centra en la implementaci´ o d’un analitzador d’imped` ancia per a ser utilitzat en la detecci´ o de bacteris. El disseny se centra en la portabilitat i el cost, amb la finalitat de fer-lo apte per al treball de camp i poder fabricar m´ ultiples m` oduls per a ser utilitzats tamb´ e en la universitat amb finalitats de recerca. Per a aix` o, es realitza una etapa de recerca. En aquesta etapa es consideren, descriuen i discuteixen breument m´ ultiples topologies i m` etodes de diferents treballs. Es discuteixen els avantatges i desavantatges de cada document i se selecciona un per a ser implementat. La topologia seleccionada es discuteix amb m´ es detall per a mostrar les seves limitacions i es fa un treball te` oric per a extreure una aproximaci´ o matem` atica del comportament del circuit. Per a complementar l’an` alisi te` orica s’utilitzen simulacions per ordinador amb SPICE per a il·lustrar millor el comportament del circuit, aix´ ı com per a verificar el treball te` oric i determinar els efectes par` asits i les no idealitats. Posteriorment, el circuit es dissenya en una placa de circuit impr` es utilitzant Kicad i es fabrica centrant-se en la simplicitat per a reduir costos. S’utilitza una Red Pitaya com ADC i DAC per a unir els dominis digital i anal` ogic i tamb´ e com a microcontrolador. La placa s’utilitza per a generar els senyals d’excitaci´ o i processar les formes d’ona generades per a extreure la informaci´ o necess` aria. La placa es programa en C i es crea una aplicaci´ o JavaScript senzilla i lleugera que serveix de front-end, utilitzant HTML i CSS per a crear una interf´ ıcie gr` afica que permeti observar millor els resultats. Finalment, es prova el sistema per a comprovar la seva funcionalitat, es discuteixen els resultats i es comenten algunes propostes de millora. Finalment, aquest treball tamb´ e descriu el cost econ` omic i ecol` ogic del projecte, aix´ ı com el cost en m` a d’obra. Title: Design and implementation of an impedance analyzer for the detection of bacteria Author: V´ ıctor Ma´ ın Nadal Director: Jordi Cosp Vilella Date: September 24, 2024 This work focuses on the implementation of an impedance analyzer to be used on the detection of bacteria. The focus of the design is on portability and cost in order to make it suitable for field work and to be able to manufacture multiple modules to be also used on the university for research purposes. For that purpose, a research stage is performed. In this stage multiple topologies and methods from different papers are considered, described and briefly discussed. The advantages and disadvantages of each paper are discussed and one is selected to be implemented. The selected topology is discussed in more detail in order to show its limitations and theoretical work is done in order to extract a mathematical approximation of the behavior of the circuit. In order to further complement the theoretical analysis computer simulations with SPICE are used to better illustrate the behavior of the circuit, as well as to verify the theoretical work and to determine the effect of parasitics and non idealities. Afterwards, the circuit is designed into a PCB using Kicad and manufactured with a focus on simplicity so as to reduce costs. A Red Pitaya is used as an ADC and DAC to bridge the digital and analog domains. The board is used to generate the excitation signals and to process the generated waveforms to extract the necessary information. The board is programmed on C and a simple and lightweight JavaScript application is created to serve as front end, using HTML and CSS to create a graphical interface to better observe the results. Finally, the system is tested to verify its functionality, the results are discussed and some proposals for improvements are commented. Finally, this work also describes the economic and ecologic cost of the project, as well as the cost in manpower. CONTENTS CHAPTER 1. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . 1 CHAPTER 2. Motivation ............................ 3 CHAPTER 3. Introduction ........................... 5 CHAPTER 4. State of the Art and previous research . . . . . . . . . 7 4.1. Working Principle ................................ 7 4.2. Real and Imaginary parts ............................ 7 4.3. Phase and Magnitude .............................. 9 4.4. Current and Voltage Measurement . . . . . . . . . . . . . . . . . . . . . . 9 4.5. Analog Front End ................................ 9 4.5.1. Current Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 4.5.2. Voltage sensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.5.3. Current Sensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4.5.4. Component values . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4.6. Commercially Available Devices . . . . . . . . . . . . . . . . . . . . . . . . 17 CHAPTER 5. Simulation ............................ 19 5.1. Voltage Measurer ................................ 19 5.2. Current Measurer ................................ 20 5.3. Current Source ................................. 21 5.4. Simulation With a pure Resistance . . . . . . . . . . . . . . . . . . . . . . 24 5.5. Simulation With a Pure Capacitance ..................... 30 5.6. Simulation With a Pure Inductance . . . . . . . . . . . . . . . . . . . . . . 31 5.7. Simulation With Mixed Impedances . . . . . . . . . . . . . . . . . . . . . . 32 CHAPTER 6. PCB Design and Assembly ................. 35 6.1. Decoupling Capacitor ............................. 35 6.2. Number of Layers: Considerations for and against a ground Plane . . . . 36 6.3. Protective Case ................................. 36 CHAPTER 7. Software ............................. 37 7.1. Connecting to the Red Pitaya ......................... 37 7.2. Front End and Back End ............................ 38 7.3. FPGA ....................................... 41 7.4. Explanation of the Designed App ....................... 41 CHAPTER 8. Assembly and Experimentation . . . . . . . . . . . . . . 45 8.1. Assembly .................................... 45 8.2. Experimentation ................................ 47 8.3. Discrepancies between the designed board and the manufactured board .47 8.4. Experimental results of the analog front end ................. 48 8.5. Red Pitaya .................................... 56 8.6. Whole system test ............................... 56 CHAPTER 9. Economic Study and Time ................. 59 9.1. Economic Study ................................ 59 9.2. Time invested .................................. 60 CHAPTER 10.Ecological Effect . . . . . . . . . . . . . . . . . . . . . . . . 61 CHAPTER 11.Further Considerations and Conclusions . . . . . . . 63 11.1.Further Considerations ............................. 63 11.2.Conclusions ................................... 64 Bibliography .................................... 65 Listings ....................................... 67 APPENDIX A. Code ............................... 69 APPENDIX B. Schematics ........................... 85 CHAPTER 2. MOTIVATION The objective of this project is to design and experimentally test a device to detect the presence of bacteria in a given sample. As bacteria grow they group themselves in large colonies. Those colonies, also called biofilm change the properties of the medium they are in. Namely, they change the impedance of the medium. Thus, by detecting a change in the impedance of the sample, it can be determined whether there is a bacteria colony growing on it. Ohmmeters are devices that calculate the DC resistance of a device. However, resistance is only the DC component of the impedance. Likewise, there is a type of device called LCR meters, which are used to calculate the inductance, capacitance and resistance of any device. This device is able to calculate the impedance of a component or sample. However, typically LCR meters only measure in one frequency, and as such only capture one value of the impedance. It is also not uncommon to see some multimeters incorporating this function, specially the measure of capacitance. There is a third type of device adequately called impedance analyzer, that is able to calculate an impedance across a range of frequencies. Although commercially available,this tools can be rather costly and can be rather bulky making them not suitable for field work. Due to their high cost it may also be complicated to justify the purchase of multiples, which may make stocking a laboratory with multiple devices and to maintain a backup stock complicated. Thus, the objective of this thesis is to attempt to build a functioning impedance analyzer. The main objective is to design a simple and cheap device at the cost of worsening the performance. A Red Pitaya will be used as the basis for the device. Furthermore, an analog front end will be designed and implemented, as well as a human interface. The main objective of this project is to obtain a compact and relatively affordable device. Although it is not expected to be possible to surpass comercial devices. The performance of the instrument must also be taken into account and the objective is to design an impedance analyzer with the best specifications possible, taking into account all of the limitations, be it technological, economical, in human resources or in know how. 3 CHAPTER 3. INTRODUCTION In the year of 1827 Georg Ohm published a book titled Die galvanische Kette, mathematish bearbeitet (The galvanic circuit investigated mathematically) (1). On his publication he studied the relation between the current and voltage across a conductor and establishing that there is a constant parameter that relates both terms following a linear relation. This constant parameter is named resistance. His work met with some difficulties, being given very little attention at first. Over time the publication started to gain some popularity.Finally his work would eventually be recognized in the 1840s and his contribution to science would be once more rewarded when in 1864 the British association for the advancement of Science adopted the ohm (initially called Ohmad until 1867 when the modern term was finally adopted) and once more on the 21st of September 1881 when the International Electrical congress adopted the ohm as its unit of resistance. It may be worth mentioning that Henry Cavendish reached the same conclusions on 1787 (2), Much earlier than Ohm. His methods are also more curious than Ohm’s since he would shock himself with Leyden Jars (a capacitor) and reporting the intensity with which he was shocked. He did not publish his reports and thus his work was unknown until James Clerk Maxwell published them in 1879. This relation, called Ohm’s law is probably one of the first equations any person is presented with when introduced to the study of electricity or electronics. V=RI (3.1) While this equation is rather powerful, and most important, extremely simple, it is also somewhat limited. Resistance is but one of the parameters that affects the flow of current. Michael Faraday measured the relative capacitance of two capacitors and he would also discover mutual and self inductance in 1831 and 1832, simultaneously and independently with Joseph Henry. Many experiments and contributions to determine the nature and measure inductance and capacitances were followed by Oliver Heaviside, who introduced the terms impedance, capacitance and inductance in 1892 and determined the mathematical notation for complex impedances. Thus, Ohm’s law was generalized to include this impedance V=ZI (3.2) Although there are some devices that do not follow this generalized Ohm’s law (such as diodes, for example) it does apply to a rather significant number of components and devices, making it useful for circuit analysis. Furthermore, the most practical method to solve circuits with non linear components consist on linearizing the devices so that Ohm’s law, and any other laws based on linear math such as Kirchhoff’s laws, can be applied. Impedance is represented as a complex number and can be expressed in any form complex numbers can be expressed. It is common at first to see impedance represented in polar or angle notation, since it eases the analysis of sinusoidal steady state circuits. Impedance is split into two two components. The resistance is the parameter that relates to the opposition of current in DC. This parameter can be safely assumed as constant, at 5 6 Design and Implementation of an Impedance Analyzer for Bacteria Detection the very least for low frequencies. At higher frequencies other phenomena, such as the skin effect, may occur. Reactance is the sum of capacitance and inductance and represents the opposition of current in AC. This parameter However does indeed change as the excitation frequency of the circuit changes. Therefore, when analyzing any circuit there is an interest in knowing how it behaves at different frequencies. The Laplace transforms, created by homonym mathematician Pierre Simon Marquis de Laplace allow the analysis of circuits using arithmetic analysis tools in what would otherwise require the analysis of differential circuits. This mathematic simplification also allows to easily determine the frequency response of any circuit. The analysis of this circuits takes place in the frequency domain. In which the independent variable is the complex operator s. Representing impedances on this domain ends up taking the form of a binomial complex number. For example, equation 3.3 shows the impedance of a resistance and capacitor on series Z(s) = R+1 Cs (3.3) This representation is enough to be able to determine the frequency response of a circuit. Determining the exact time response of a circuit is rather more complex, since the expresion must be transfered once again from the frequency domain to the time domain. Nevertheless, this step is not always needed, since a lot of information can already be glimpsed from the response on the frequency domain. Nowadays, in order to convert to and from the frequency domain either computers or tabulated values are used. This way, the most complex part of analyzing a circuit in the frequency domain can be done without much issue. Strictly speaking, the previous equation does not give the frequency response of the circuit. To determine the frequency response of a circuit the sinusoidal steady state response is determined. The demonstration can be extensively found in the literature. Nevertheless, it requires a simple variable change, substituting sfor jω. j is the imaginary operator, defined as j2=−1. In mathematics the imaginary operator is normally represented by the letter i. In engineering it is very common to use the letter j to avoid confusion with the current, which is represented with the letter i. ωis the angular frequency with units rads−1. Thus, representing the frequency response of the previously defined impedance. Z(jω) = R+1 C jω(3.4) To further ease the interpretation of the frequency response it is common to use a bode plot. This plot represents both the magnitude and phase of the complex magnitude to be studied, in this case the impedance. Furthermore, it employs a logarithmic x axis to be able to further compress the frequency response. Moreover, it is also very common to represent the magnitude in decibels in order to further compress the response. There are two conversion factors to convert from magnitude to decibel depending on whether the magnitude is voltage and or current or power. dB =20log(Mag)(3.5) dBpower =10log(Mag)(3.6) CHAPTER 4. STATE OF THE ART AND PREVIOUS RESEARCH 4.1. Working Principle Generally speaking. In order to calculate the impedance an instrument will consist on two blocks. The first one being an Analog front end, that generates and condition an analog signal to be applied to the load as well as to measure the response of the load. The second block tends to be some sort of digital logic, that helps control the measuring process as well as to calculate and store the measured impedance. Normally that digital block consists of a microprocessor of some kind, as well as some sort of storage memory, commonly RAM. In order to bridge the analog and digital world an ADC and a DAC are used to convert from one domain to the other. Impedance must be calculated using an AC signal. It is possible to measure impedance with an AC signal with a DC component. However, the DC component can pose some problems. As such it is generally a good idea to ensure that the excitation signal has no DC component or, in the case that is not possible, that it is minimized. There are multiple methods in order to measure an impedance. The most common ones being discussed below. 4.2. Real and Imaginary parts Impedance can be represented as a binomial complex number (Z=a+jb). That is to say, a number with a real and imaginary part. Thus, one way to calculate impedance is to measure both the real and imaginary part of the impedance and later calculate the magnitude and phase with the following equations |Z|=pa2+b2(4.1) φZ=arctan b a(4.2) Two main methods exist to measure an impedance in such a way. Coherent demodulation (3) and synchronous sampling (4). Generally coherent demodulation works by injecting a known voltage or current signal and a frequency carrier signal into the load. At the same time the voltage is measured at the load. The detected signal has the form of an amplitude modulate signal. Latter the signal needs to be demodulated. To do so the modulated signal is multiplied with a in phase and quadrature signal of the same frequency as the carrier. Afterwards those signals are filtered. This way the real and imaginary part of the impedance can be measured 7 8 Design and Implementation of an Impedance Analyzer for Bacteria Detection LPF LPF In Phase Signal Quadrature Signal Re Im VL Figure 4.1: Coherent Demodulation Block diagram The main drawback with coherent demodulation is the need for balanced lines. The separated channels for the in phase and quadrature signals must be matched. A slight mismatch will result on a significant phase error, specially at high frequencies. Synchronous sampling attempts to circumvent this issue by eliminating one of the signal channels. It also avoids using analog demodulators. VLHPF S/H LPF OUT Vo CLK Figure 4.2: Synchronous Sampling Block Diagram Nevertheless, both methods require a precise timing circuit in order to properly synchronize the samplers. An application of Coherent demodulation can be seen on (5) with a relatively good performance. Reaching frequencies of up to 1 MHz. However, said article covers the design of an integrated circuit analog front end. Generally speaking, integrated circuits have a better performance than implementing the same circuitry on a PCB. Furthermore, some techniques can be used on ICs that are ill advised for PCB design. Case in point, the system works with a series of switched rectifiers. Twelve in total. While switched circuits have their advantages, they are only generally viable on ICs, where they can be densely packed so as to occupy a very low area. Moreover, all of the rectifiers must be properly timed. Clock jitter, propagation delay and fanout are important aspects to take into account. Once more, attempting to implement such system on a PCB would be much more complicated. State of the Art and previous research 9 4.3. Phase and Magnitude Another method to calculate impedance is to measure the magnitude and phase of the signal directly. To calculate the magnitude a peak detector must be used. There are multiple ways to implement it. Both (6) and (7) use a rectifier to calculate the magnitude. The average value of a rectified sine wave corresponds roughly to 0.63Vpeak. To calculate the average value a low pass filter is used. In order to calculate the phase of the impedance both the excitation signal and the voltage across the load are converted into a digital wave with the use of comparators. The outputs are then connected to an XOR gate. The duty cycle of the resulting signal will be proportional to the phase diference between both signals. The main difference between both proposals is that (6) proposes a galvanostatic measurement while (7) proposes a potentiostatic measurement. That is to say, the former applies a constant current through the load while the latter ensures a constant voltage drop through the load. A constant current is preferred. The reasons behind it are twofold. Firstly, it avoids tissue damage which is important in medical applications. Secondly, it eliminates the effects of line impedance. When measuring the voltage across the impedance, if a voltage source is applied there will be some voltage drop between the voltage source and the load due to the inherent resistance of the conductor connecting both. Theoretically speaking, if a current source is introduced instead of a voltage source, the current across the load will be the same as the current generated by the power source, regardless of the impedance of the line. Therefore, it is more precise to induce a known current through the load and to measure the voltage drop at the load that it is to apply a known voltage and to measure the current through the load. 4.4. Current and Voltage Measurement Lastly, the current through the load and voltage across it can be calculated.Later, the quotient can be calculated to obtain the impedance. This can be seen on (8). The proposed analog front end is built into a PCB utilizing discrete components and comercialy available ICs. A current is injected into the load. The voltage across the load is measured as well as the current circulating through it. The measurements are then relayed to a digital stage, that converts and processes the data. Due to the manufacturing capabilities this front end appears to be the most promising for this project. 4.5. Analog Front End The analog front end discused onf (8) consists on three main blocks. A current sensing block, a voltage sensing block and a current source. 10 Design and Implementation of an Impedance Analyzer for Bacteria Detection − + − + − + − + − + − + − + − + Figure 4.3: Proposed Front end 4.5.1. Current Source The AD844 is used as a current source. The AD844 is advertised as an operational amplifier. However, the IC can also be wired to be used as a current source as seen on (9). The IC consists of three blocks. A current conveyor, a transconductance impedance and a voltage buffer. State of the Art and previous research 11 Y XZ R1 Zt io ii Vo Vi Figure 4.4: AD844 configured as a current source. The dashed line marks the IC A current conveyor is a form of electronic amplifier with unitary gain. There are three generations of current conveyors, each with different characteristics. The current conveyor on the AD844 can be considered as a second generation current conveyor, which behaves as follows •No current flows into terminal Y •The voltage at terminal Y is also applied at terminal X •The current that flows into terminal X will also flow through terminal Z whose direction will depend on the type of conveyor used –The current will flow in the same direction if the current conveyor is a CII+ –The current will flow in the opposite direction if the current conveyor is a CIIThe current flowing out of the current conveyor flows through the transconductance impedance, which causes a voltage drop. A buffer stage is used to ensure a low output impedance of the device. The impedance is formed by a 3MΩresistor and a 4.7pF capacitor in parallel. Thus, the open loop gain of the amplifier is significant. This device can be used as an operational amplifier. However, the Z terminal is also accessible from the package. therefore the device can be used as a current source. Where its current will be io=ii=vi R1 (4.3) and the output voltage, if the load is significantly lower than Zt vo=ioZl(4.4) This circuit may already work as intended. However, the proposed circuit connects a capacitor in series to the output node, making the load impedance Z′ L=1 C1s+ZL(4.5) This capacitor is intended to decouple the DC value of the system so it is safe to assume that for moderate frequencies its value can be disregarded. However, that means that the CHAPTER 5. SIMULATION The mathematical models used in the theoretical analysis are limited by necessity. In order to manually analyze a circuit and to be able to derive some insight from the study the complexity cannot be extreme. However, this limitations can lead to some inaccuracies that, if nothing else were done, would only be seen during testing. Luckily, with the actual prevalence of computers this analysis can be further complicated. With the help of a circuit simulator it is possible to analyze the behaviour of a circuit with a much more complex and accurate mathematical model that approaches more the real behaviour while all the complexities, such as the mathematical calculus or the plotting of results, which aid to understanding the predicted behaviour, are done by the computer. Computer simulation eases the analysis of circuits and allows for some analysis that would be unfeasible otherwise (such as, for example, monte carlo simulations). SPICE (Simulation Program with Integrated Circuits Emphasis) was developed on 1973 by the University of California, Bekerley and quickly became the standard for circuit simulation. After the development of SPICE3 the development was stopped. However, multiple variations of this program were quick to rise. The first commercial version was called ISPICE, although HSPICE or PSPICE are more known commercial versions used nowadays. This new versions expanded on the capabilities of the project (for example, adding the possibility to perform an FFT) or providing proprietary models for components and over the years would come to be accompanied with a fronted to ease its use. Comercial simulations are not the only alternatives. Since SPICE was an open source project once the project was discontinued some successors appeared. The most commonly used nowadays is called ngSPICE. Generally speaking the component models defined use the same syntax and are generally freely distributed by the manufacturer (although they may be obscured). This section will cover the results of the simulated circuit. The software used is LTspice. A software created by linear technologies (nowadays Analog Devices) for Spice simulation. Despite being designed with the simulation of AD devices in mind the software accepts the input of third party models. 5.1. Voltage Measurer In order to simulate the frequency response of the voltage measurer an ideal differential voltage source has been introduced between the the terminals where the load would normally be located 19 20 Design and Implementation of an Impedance Analyzer for Bacteria Detection 10 310 210 1100101102103104105106107108109 Frequency[Hz] 40 20 0 Magnitude [dB] 10 310 210 1100101102103104105106107108109 Frequency[Hz] 300 250 200 150 100 50 0 Phase [º] Figure 5.1: Transfer function of the voltage measurer It presents as expected the behaviour of a low pass function with a gain of 1 and a corner frequency situated around 100MHz 5.2. Current Measurer To simulate this behaviour an ideal current source has been placed in series with C7to simulate the current that would flow through the load. Simulation 21 10 310 210 1100101102103104105106107108109 Frequency[Hz] 40 60 Magnitude [dB] 10 310 210 1100101102103104105106107108109 Frequency[Hz] 0 25 50 75 100 125 150 175 Phase [º] Figure 5.2: Transfer function of the current measurer Similar to the previous case, the behaviour is that of a low pass filter. with a gain of 60dB and a corner frequency at around 10MHz. 5.3. Current Source To simulate the behaviour of the current source the output of the current souce is directly shorted to ground. The voltage excitation is generated with an ideal voltage supply 22 Design and Implementation of an Impedance Analyzer for Bacteria Detection 10 310 210 1100101102103104105106107108109 Frequency[Hz] 60 40 Magnitude [dB] 10 310 210 1100101102103104105106107108109 Frequency[Hz] 180 170 160 150 140 130 120 Phase [º] Figure 5.3: Transfer function of the current source The behaviour of the current source is as expected for lower frequencies. However when reaching frequencies of 20MHz the current begins to increase. This limits the upper frequencies of the device. However. Upon simulating the same current source with the capacitor C1some limitations can be observed. Simulation 23 10 310 210 1100101102103104105106107108109 Frequency[Hz] 180 160 140 120 100 80 60 40 Magnitude [dB] Z=1u Z=100u 10 310 210 1100101102103104105106107108109 Frequency[Hz] 180 160 140 120 100 80 60 40 20 Phase [º] Figure 5.4: Transfer function of the current source with the C1capacitor The capacitor behaves as a high impedance at lower frequencies. Which may lead to the saturation of the current source if the impedance is too high. What can be observed on the bode plot is the result of a current divider created between the transconductance impedace and the C1capacitor. With an excitation of 1Vthe expected current is 1mA. This current will only be observed flowing through the C1capacitor and the connected load if its impedance is small enough to disregard the effects of the transconductance impedance. Furthermore, it is also important to remember that there is a negative feedback loop designed to eliminate the low frequencies of the current. In theory, the only intention is to erase the DC component of the current wave, to avoid saturation. In practice since the filter is not a perfect brick wall there will be a range of frequencies attenuated. Increasing the C1capacitance from 1µFto 100µFwill improve the frequency response. Nevertheless, the effects of the filter will remain. The most important factor to take into account is the transfer function of the calculated impedance. Therefore some of this issues may be eliminated since the objective is to calculate the ratio. That is to say, it is not relevant if the current has an inferior magnitude, so long the measured voltage magnitude is also proportionally lower. 24 Design and Implementation of an Impedance Analyzer for Bacteria Detection 5.4. Simulation With a pure Resistance One of the simplest ways to verify the functionality of the front end is with a pure resistance. Since the bode plot of a resistance is a constant horizontal line it allows for easy detection of possible issues with the device. Furthermore, since the magnitude is constant it is also useful to detect the magnitude limitation of the device. 10 310 210 1100101102103104105106107108109 Frequency[Hz] 0 20 40 60 80 100 120 140 160 180 Magnitude [dB] Zl=1 Zl=10 Zl=100 Zl=1K Zl=10K Zl=100K Zl=1M Zl=10M Zl=100M Zl=1G 10 310 210 1100101102103104105106107108109 Frequency[Hz] 350 300 250 200 150 100 50 0 Phase [º] Figure 5.5: Impedance plot with a pure resistance Upon performing the simulation it can be observed that the performance at lower frequencies is relatively bad. This effect seen at lower frequencies is due to the C1and C7capacitors. In order to improve the response at low frequencies, those capacitors, together with C3and C4can be replaced with 100µFcapacitors. Simulation 25 10 310 210 1100101102103104105106107108109 Frequency[Hz] 0 20 40 60 80 100 120 140 160 Magnitude [dB] Zl=1 Zl=10 Zl=100 Zl=1K Zl=10K Zl=100K Zl=1M Zl=10M Zl=100M Zl=1G 10 310 210 1100101102103104105106107108109 Frequency[Hz] 400 300 200 100 0 100 200 Phase [º] Figure 5.6: Repetition of the simulation increasing the capacitance to 100µF With this simulation the limitations of the analog front end can already be seen. With respect to the lower frequencies. If the impedance is low enough the effect of the capacitors can be observed. This effect is only visible with loads of 1 and 10Ωand only at lower frequencies. Lower magnitudes will present this effect at even higher frequencies. However, with this simulations the frequency lower bound can be safely assigned at a frequency of 100mHz. When looking at higher frequencies an inductive behaviour can be observed at frequencies of around 10MΩ. The capacitive behaviour observed on lower frequencies and impedances can be explained analyzing in detail the measurements taken. 26 Design and Implementation of an Impedance Analyzer for Bacteria Detection 10 310 210 1100101102103104105106107108109 Frequency[Hz] 140 120 100 80 60 40 20 0 Magnitude [dB] V(curr_sense) V(v_sense) I(R5) 10 310 210 1100101102103104105106107108109 Frequency[Hz] 800 600 400 200 0 Phase [º] Figure 5.7: Capacitive Effect Explained As it can be seen. The voltage measurer cannot accurately follow the voltage that drops through the load ad low frequencies (which should be the same as the current circulating through the load, given that, in this case, the load impedance is 1Ω). Thus, since the voltage remains constant and the current drops the calculated impedance will increase. The inductive behaviour is not due to any parasitic inductance. It is due to the behaviour of the current and voltage measurers. as seen on the bode plots of 5.1 and 5.2 the voltage measurer has a corner frequency of about 100MHz while the corner frequency of the current measurer is found at 10MHz. This implies that the value of the measured current will start decreasing before the value of the voltage. Therefore, when calculating the ratio the impedance will begin to rise at the corner frequency of the current measurer. However, when reaching the corner frequency of the voltage measurer, the impedance will begin to decrease once again. This behaviour will continue permanently. The corner of the voltage measurer is given by the frequency responses of the IC and cannot be easily changed. The corner of the current measurer is given by the pole determined by the capacitor and resistance placed in parallel. Nevertheless, while it is possible to theoretically move the pole, it is not feasible to do so in reality. Decreasing either the capacitance or the resistance comes with significant drawbacks. Decreasing the resistance would incur on an elevated current consumption while decreasing the capacitance would make it so low that the effects of the parasitic capacitance would not be negligible. Therefore the upper bound of the frequency range can be assigned at 1MHz. Simulation 27 Yet another aspect of the bode plot can be pointed out. It can be seen that the maximum measured impedance has an impedance of approximately 150dB (on the working frequency interval). However, testing impedances of up to 1GΩthe expected magnitude should be 180dB. The explanation for this behaviour can be easily explained using ohms law. for this simulations the current generated by the current source is 1mA. With the aforementioned impedance that would imply a voltage drop of 1MV. The current source saturates. 0.0 0.2 0.4 0.6 0.8 1.0 Time[s] 1e 5 0.00100 0.00075 0.00050 0.00025 0.00000 0.00025 0.00050 0.00075 0.00100 Amplitude[A] Z=1 Z=10 Z=100 Z=1k Z=10k Z=100K Z=1M Z=10M Z=100M Z=1G Figure 5.8: Transient simulation of the current through the resistive load As seen in the previous graph. If nothing is done to adjust the current. The current source will saturate when the impedance to measure reaches a magnitude in the order of 10kΩ. In order to circumnavigate this issue the current of the current source would have to be dynamically adjusted. This will have to be implemented on the software of the Red Pitaya. However, even before implementing his dynamic adjusted a theoretical limit can be estimated. Currents in the range of nA are to small. The sources of noise will be to large to be able to disregard their effects. Therefore, assuming a minimum current of 1µAthe maximum possible load can be determined. 34 Design and Implementation of an Impedance Analyzer for Bacteria Detection 1e 03 1e 02 1e 01 1 10 100 1000 1e4 1e+05 1e+06 1e+07 1e+08 1e+09 Frequency[Hz] 20 40 60 80 100 120 140 160 Magnitude [dB] 1e 03 1e 02 1e 01 1 10 100 1000 1e4 1e+05 1e+06 1e+07 1e+08 1e+09 Frequency[Hz] 100 50 0 50 100 150 Phase [º] Figure 5.16: Magnitude calculation of 10nF capacitor and a 10mH inductance In the case of an LC series association. The impedance is represented by two assimptotes. Firstly a -20dB assimptote followed by another one with a 20dB slope. At the point where both impedances have the same magnitude, which is also the point where asimptotes meet, the impedance drops to zero. This is called the resonant frequency and in this particular case is ωr=q1 LC =100kHz. The magnitude does not drop to zero in this case due to the parasitics of the component. This also shifts the frequency. CHAPTER 6. PCB DESIGN AND ASSEMBLY Once the design has been simulated it is necessary to manufacture it. For that it is necessary to generate a schematic and a PCB design to be able to generate a series of fabrication files, instructions for the manufacturer to correctly build the board. There are multiple programs commercially available to do this. Altium, Orcad, Allegro PCB and Diptrace are just some of the offers present on the market. For this project however, Kicad has been used. Kicad is an open source EDA tool created with the purpose of offering a free and open source alternatives to the commercial programs in offer. Kicad is one of the more mature open source projects currently available. It has an extensive user base and a rather significant amount of documentation and support. Furthermore, while this may be just a curiosity, Kicad is being actively supported by CERN. In can be installed in any of the three main operating system families and comes with an extensive library of components which also makes designing a PCB board simpler. 6.1. Decoupling Capacitor Consulting the design schematics provided in the annex it can be seen that there are a number of components that do not appear on the previous schematics that do appear in the final design. Some of this components are some connectors necessary to have the inputs and outputs desired. However, most notable is the presence of a significant number of extra capacitors connected to the power supplies of the ICs. This are called decoupling capacitors. This capacitors are use to decouple different sections of a circuit. That is to say, they are used to prevent electrical energy from being transferred to or from a particular section. This capacitors can also be used in the signal path. For instance, C1,C3,C4and C7 are decoupling capacitors installed to prevent the DC signal from propagating across the device. With the same principle in mind, decoupling capacitors are installed on the power lines of the ICs to prevent or minimize the effects of noise on said lines. Generally speaking when designing a circuit it is assumed that the power supply is constant. That is not the case. Electro magnetic interference (EMI) can induce some noise of the power lines as well as other source of noise (thermal noise, coupling...). Ideally, any circuit works without being affected by any variations in its power supply. This is saddly not the case. Therefore, when utilizing an IC the manufacturer recommends the installation of said capacitors to minimize the effect. Furthermore. The power consumption of an IC is also not constant. This fluctuation is most notable when the IC is a digital circuit, although with an analog IC the effect is also present. Large and fast fluctuations of currents will cause voltage drops across the inductance of the line. With the use of decoupling capacitors this effect is minimized since the capacitor absorbs or supplies the needed current so that the variation is progressive. It is important to place the capacitor as close as possible to the IC. This minimizes the parasitic inductances of the track between capacitor and IC. The closer the better, although some ICs have more leeway than others. Normally the manufacturer will supply the necessary indications on their datasheet. This is not always the case however. Nevertheless, even if nothing is recomended on the datasheet, it is a good rule of thumb to add a decoupling capacitor of between 100nF to 1µFon the supply. 35 36 Design and Implementation of an Impedance Analyzer for Bacteria Detection 6.2. Number of Layers: Considerations for and against a ground Plane For High frequency applications it is common to add a ground plane in order to guarantee signal integrity. A ground plane is, as its name implies, a whole plane of the PCB (a whole layer) that is connected to ground. This plane is the one use for the return path of the signal and it is supposed to be continuous. Current attempts to find the easiest path to return. If there is only a ground track the current will be forced to circulate through it. In the case that one whole plane of the board is connected to ground the current will circulate through the easiest path which tends to be parallel to the signal track. Making this current loop shorter has its advantages, since the EMI that will radiate through it will be smaller. To further simplify, the loop between tracks will behave like an antenna. Creating a ground plane makes sure that the antenna is as small as possible. Furthermore, whenever possible, it is a good idea to also create a power plane. A power plane is the same principle as a ground plane, but applied to VDD. Another consideration when designing the board is to attempt to have all components on one layer of the PCB. this facilitates the layout. On anything but simple designs it will be very complicated to have all the tracks on one layer. As such it will be necessary to use multiple layers. One typical design philosophy, especially for complex designs, is to have one layer where the tracks are horizontal, and another where the tracks are vertical. This way a matrix is created and it makes it less likely that a bad initial layout may lead to a large surface being unusable and needing to restart. This is mainly because it streamlines crossings. Nevertheless, it is important to note that for each via to cross tracks between layers there are two 90 degree angle turns. This can prove an issue with really fast signals or with high power tracks. In the case of high power tracks one solution is to place multiple vias to facilitate current flow. Nevertheless, with frequencies of up to 1MHz this limitations should not be observed. For this particular case the board has only been designed with two layers in order to minimize the cost as much as possible. 6.3. Protective Case Designing a case for the board is not necessary for the project. However, it can be a useful thing to do. The casing makes the handling of the board simpler and can prevent the accumulation of dust and protect the components from accidental electrostatic discharge. Since this board does not dissipate a lot of power, it is not necessary to design any sort of ventilation into the system. However it is important to keep power dissipation in mind when designing any system to avoid problems further down the line. The case has been manufactured using PLA plastic and a 3D printer CHAPTER 7. SOFTWARE 7.1. Connecting to the Red Pitaya In order to connect to the Red Pitaya several methods can be used. In this particular case, an Ethernet connection has been used. Nevertheless, there is some configuration that needs to be done before being able to start programming the device. Also. although it is possible to directly connect the Red Pitaya to a computer for all programming and configuration the Pitaya is connected to a router. This way the board can enjoy access to the internet The red Pitaya has an associated local address for this particular device, although it will be different with another board. Once connected on the Network Settings menu the network configuration can be modified. The configuration will vary depending on the network being used. Below is the configuration used for the particular case here described Figure 7.1: Network configuration of the Red Pitaya Once this configuration has been done it is possible to connect to the red Pitaya by typing the IP address onto the search bar of any browser (Although the local address will still function). As a particular note. Since it may not be always a guarantee it is also important to know how to connect the Red Pitaya directly to a computer. Theoretically, just connecting the cable should be enough. However, the Windows operating system is not able to automatically assign IPs, so it is also necessary to manually configure the IP of the computer. On the network settings on Windows the Ethernet connection for the Red Pitaya should be available. The IP assignment must be changed from automatic to manual. Below a picture with the configuration used can be seen. 37 38 Design and Implementation of an Impedance Analyzer for Bacteria Detection Figure 7.2: Network configuration of the windows PC Now that this two connection methods have been configured using an ssh connection it is possible to directly connect to the Red Pitaya. With this connection it is possible to further configure the device. 7.2. Front End and Back End Generally speaking any developed software can be separated in two categories. The front end and the back end. The front end is the part of the software that the user will interact with. Nowadays, most of the time the front end includes a graphical user interface (GUI for short) and mostly a simple logic block to make the navigation more intuitive. For example, when using a website to fill out a form the website that the user sees is the front end of the application. As mentioned this front end can also perform certain logic functions. For example, when a form is incomplete or one of the filled fields is incorrect (such as a wrong email, or a phone number too short to be correct) normally the website flags the error so that it can be corrected. The Back end on the other hand is the part of the software that performs the heavier calculations. It is the one that ”does the job”. It is a part of the software that the normal user does not access during normal use of the app. In the example set before. Once the form is ready to be sent the front end gathers all the information and transfers it to the back end. Once received the back end is the part of the app in charge of sending the data wherever it needs and, once the form has been correctly sent, the back end relays that information to the front end, so that the user can know everything ran without issues. Therefore. most applications have two distinct parts that need to communicate with each Software 39 other and that have different functions. While it is possible to use one programming language to create the whole app it is also possible to use different programming languages for the back and front end since some languages can be optimized for specific functions. This is the case for the Red Pitaya. The front end of the Red Pitaya is formed by three ”programming languages”. Hyper Text Markup Language (or HTML for short) is, as its name implies, a markup language. A markup language is simply a way to encode or codify the information of a text. To simplify with an analogue example. When printing a manuscript it was common practice to make annotations on the margins of the paper. This annotations conveyed special information such as the font or size of a particular section of text. This way when printing a publication, the men in charge knew how the document was supposed to look like. HTML applies the same concept on the digital level. Therefore, it is possible to specify if a portion of text is supposed to be a title, or a subtitle or simply the main body of the document. HTML is designed with the intent of being rather simple to learn and use. This combined with the fact that it is also designed to ”format” text and information (since pictures can also be added) makes it ideal for the development of websites to the point where it has become the standard. Therefore, HTML is in charge of creating the GUI that the user will utilize. In principle, the GUI will be a website and as such, it seems logical that this site will have to be hosted somewhere. Fortunately, the Red Pitaya already comes with an environment pre-configured. When booting up the device the Red Pitaya creates a server where all this wesites will be hosted. They are not connected to the internet but by connecting to the Red Pitaya it is possible to access them. Now, while this proposal may, at first seem ”messy”. Using a web page as an interface may not seem at first as the best option, considering that there are other GUIs that do not require connecting to a server. Nevertheless, this sort of philosophy when designing front ends has two main advantages. The first one, as already mention is its ease. The second one is its portability. an HTML website can be opened virtually by any browser in any operating system without the need to adapt the program. This is particularly beneficial for this project since that means that connecting to and operating the Red Pitaya can be done with virtually any computer. Actually, many well known apps use this method to create an interface such as Skype, Microsoft Teams, VScode, Twitch or Dropbox among many others. They even go a step further and embed this website into a desktop application. However, HTML is not enough to design a website. HTML only takes care of the structure of the text. Front end cascading style sheets (or CSS for short) help to further define the presentation of the HTML document. While HTML is used to define the structure of the interface CSS is used to define its style. Going back to the analogy of a printing press. HTML is the annotation that specifies that one particular sentence is the title while CSS is the annotation that specifies that the title must be written in Arial 40. This style sheet language is also very simple to utilize easing its use on development. To finish this web design trifecta, JavaScript (JS for short) is the last tool used. If HTML was used to define how the website must be structured and CSS is used to define how the website must look like JS is used to define how the website must behave. JavaScript is an interpreted programming language which, despite its name, has nothing to do with Java. An interpreted language is a language that does not need to be compiled beforehand. When the program is executed an interpreter translates in real time the lines 40 Design and Implementation of an Impedance Analyzer for Bacteria Detection of code. This brings the advantage that iterating and prototyping on the program is really easy. As a downside it slows down performance. Thus it will never be as fast or efficient or resource light as other compiled languages. Nowadays the most famous programming language that is interpreted is Python. This is the first programming language in a traditional sense that is used. It is a scripting language and can be used as a general purpose language (like Python or C). The most common application however is the creation of websites front ends mainly because it is the only programming language, outside of web assembly, that is natively supported by all the main browsers in use nowadays. It can also be used for other purposes such as Server side applications (NodeJs) mobile applications (React) or desktop applications (Electron). Generally speaking, when using JS to design a website, JS is in charge of receiving the inputs of the user, maybe modifying those inputs or applying some internal logic, and finally sending the necessary data to the back end. The Bridge between the Front and Back end is done with a web server called NginX (pronounced Engine X). This tool acts as a bridge sending between both ends and is also responsible for loading the app itself. That is to say, sending the website to the requesting computer. The Back end is flexible, and Red Pitaya offers different ways to create a back end program (also called controller) Python and C/C++ are the most well known programming languages it supports however it also supports Matlab, Lab View and SciLab. For this project, the Backend in use will be a C/C++ file. This file contains 11 mandatory functions that will be called by NginX at different times (when the app is started or JS has some variable to send, for example). Furthermore, the Red Pitaya provides a number of APIs and Functions that make programming an app more easy. An API (Application Programming Interface) is any piece of software that allows for the communication between different softwares or between different components of one software. It is a very generic definition and as such the forms an API can take are varied. Generally speaking they will simplify performing some complex tasks. Technically speaking any function programmed could be considered some sort of API. However, it may be best explained when considering an example on the Red Pitaya itself Generating a sine wave is no trivial matter, neither analogically nor digitally. In order to do so it would be required to control all the signals of a DAC to correctly drive it as well as to provide the voltage value that the ADC must produce. In order to provide that value it is necessary to interpolate the point of the sine wave which needs to be sent. And already digitally calculating those points is a world of its own. Computers can only perform simple operations (summing, subtracting multiplying and dividing) so calculating this function would require some programming (such as programming the Taylor function to approximate the value). All of this work could already be a small project or, at the very least, a rather significant tangent. Nevertheless, the developers of the Red Pitaya already thought that generating a sine wave was something that the users of their board would want to do constantly and as such they created a program that does all the steps mentioned before. Therefore, when trying to generate said sine wave the only thing needed to do is to call a function and to send the relevant data: Waveform, amplitude and frequency. The API takes care of the rest. This philosophy helps greatly to create a functioning app since the most commonly used tools or capabilities of the board have already been programmed. The only thing to do is Software 41 to call those functions. Otherwise creating even the simplest of apps would be an endless task requiring to do everything from scratch. In software development it is a wise idea to reuse software that others have created, provided that this tool (API, library, code snipped) can be understood. 7.3. FPGA It may be a bit misleading to talk about an FPGA in the Software chapter.An FPGA is by no means a piece of software. Quite the opposite, it is a hardware piece. However, it is discussed here because of its relevance with respect to the software. A Field Programmable Gate Array (FPGA for short) is an integrated circuit that can be reconfigured at will. They are made of a series of logic blocs (logic gates, lookup tables, registers...) that can be connected freely to perform different tasks. The fact that it can be reprogrammed makes it very useful for prototyping or creating designs for a low cost where an ASIC design could not be justified. It is also a flexible tool. For example, if for one particular application an I2C communication protocol must be used an FPGA can be configured as such. Nevertheless, if latter, for whichever reason, the I2C module is no longer needed and a ring FIFO is required the same chip can be reconfigured and used for the new task. It makes a lot of sense to have an FPGA on a board such as this. After all the Red Pitaya is announced as a flexible tool that can change its functionally depending on the situation. The micro-controller that the Pitaya incorporates is already capable of providing a lot of the required flexibility. However, there a moments where the software is not enough. Normally on applications where speed or a deterministic behaviour is required. In those cases, it is the hardware itself that needs to be flexible and that is where an FPGA shines. The FPGA is being discussed in this chapter because it must interact at some level with the software. An impedance analyzer must generate and read analogue signals and for that it must have some interaction between the hardware and software. For this project however, the Red Pitayas default configuration has proven sufficient enough to be viable. Therefore, the FPGA has not been further programmed. In spite of the fact that it has not been modified it is necessary to acknowledge the existence of such a component and to briefly describe its functionalities and purpose. 7.4. Explanation of the Designed App Upon connecting to the Red Pitaya, an app called impedance analyzer should appear on the main menu. This is the name of the app that will be used. The main interface of the program is simple and intuitive. There are three text fields where the start frequency, end frequency and number of steps can be introduced. There are also two buttons. One to start the process, and another to update the plot. Once the data has been inputted the impedance measuring progress can start. The program will check if the data was correctly introduced. Once verified the program start iterating through the list of frequencies. An adequate sampling frequency is chosen and a sine wave is generated. Afterwards, the two output sine waves (the voltage and current measured) are stored into the ADC’s buffers. Once the buffers are completely filled the CPU obtains the magnitude of the quotient between signals. Afterwards the phase is calculated 42 Design and Implementation of an Impedance Analyzer for Bacteria Detection and both values are stored into a CSV. The process repeats until all the frequencies have been tested. At every iteration the program runs a series of checks to ensure that the board is working correctly. If at any point the sample frequency cannot be guaranteed to be, at the very least, twice the excitation frequency the process will be interrupted. Moreover, if the magnitude of the voltage sine wave has a magnitude out of range the excitation current is adjusted to attempt to avoid saturation. If this is not possible the program will also return an error and interrupt the process. The previously measured points will be saved and can be looked at without issue. The graph is generated using Plotly, a graphing library for JavaScript. The graph has an interactive zoom and can be downloaded as an image. Software 43 Start No Yes Input fields correct? Display Error to user END Calculate Frequency Range Yes No Start Button Pressed? No Range Completed? Calculate magnitude and phase No Magnitude between 0.9 and 0.5? Adjust Current Yes No Current OOR? Configure Input signal Save values on CSV Yes Yes Figure 7.3: Program Flowchart 50 Design and Implementation of an Impedance Analyzer for Bacteria Detection Figure 8.6: current signal with a 300Ωresistance and a 500kHz signal Figure 8.7: voltage signal with a 300Ωresistance and a 500kHz signal The behaviour at 500kHz is also as expected. Once the frequency reaches 1MHz the gain of the measuring stages starts decreasing. As the frequency keeps increasing, the performance worsens rapidly. Therefore, it can be ascertained that the upper limit of the frequency range is found at the 1MHz mark Assembly and Experimentation 51 Figure 8.8: current signal with a 300Ωresistance and a 1MHz signal Figure 8.9: voltage signal with a 300Ωresistance and a 1MHz signal Furthermore, as can be observed below, not only does the gain decrease but the signal becomes much more noisy and distorted. 52 Design and Implementation of an Impedance Analyzer for Bacteria Detection Figure 8.10: current signal with a 300Ωresistance and a 5MHz signal Figure 8.11: voltage signal with a 300Ωresistance and a 5MHz signal Testing with different resistances serves to determine the magnitude range of the testing load. 1 and 10 Ωloads are too small to properly measure them. The current measure is done without issue. However, the voltage drop along those loads is 1 and 10 mV respectively. This magnitudes are too small and cannot be distinguished from background noise. Assembly and Experimentation 53 Figure 8.12: voltage signal with a 1Ωresistance and a 500kHz signal Figure 8.13: voltage signal with a 10Ωresistance and a 500kHz signal While, in theory, the current could be increased in order to cause a larger voltage drop this is not a practical possibility. The input voltage at the AD844 can, at maximum be 1V. This implies that the current being generated is already the maximum possible. 100 Ω resistances present no problem. Neither do 1kΩloads. 54 Design and Implementation of an Impedance Analyzer for Bacteria Detection Figure 8.14: Current signal with a 1kΩresistance and a 500kHz signal Figure 8.15: voltage signal with a 1kΩresistance and a 500kHz signal 10kΩloads are too large for the front end and cannot be measured. Thus, the working range can be delimited between 100 and 1000 Ω. Assembly and Experimentation 55 Figure 8.16: current signal with a 10kΩresistance and a 500kHz signal Figure 8.17: In yellow input voltage to the current source. In purple output current of the current source 56 Design and Implementation of an Impedance Analyzer for Bacteria Detection Frequency Resistance (ohm) Measured Current (mA) Expected current (mA) 2000 300 1.12 1 100000 300 0.97 1 500000 300 0.95 1 1000000 300 0.88 1 5000000 300 0.296 1 Frequency relative error Measured Voltage (V) Expected Voltage (V) relative error 2000 0.12 0.294 0.3 0.02 100000 0.03 0.266 0.3 0.11 500000 0.05 0.262 0.3 0.13 1000000 0.12 0.266 0.3 0.11 5000000 0.70 0.083 0.3 0.72 Table 8.1: Performance of the AFE 8.5. Red Pitaya To test the Red Pitaya the software was compiled and external signals were generated to simulate the response of the analog board. To test the repeatability of the device the same measure was taken 200 times, and any deviation of more than 20% was considered an error. Out of this measures, only six measures returned a phase measurement outside the expected margin. That means that only 3% of the taken measures were incorrect. Thus, the repeatability of the Red Pitaya is 97%. The magnitude was always calculated correctly 8.6. Whole system test Now that the analog front end has been characterized and the Red Pitaya tested the whole system can be tested. As expected, the results of the whole system were worse than of each block individually. It firstly can be observed that the Red Pitaya has sometimes problems to start measuring the signal. Most likely, this is due to the fact that the trigger does not activate correctly. Probably due to the amount of noise. It has been observed that the position of the cables is, once again, responsible for the behaviour of the board. Figure 8.18: Result of the Measure of a 300Ωimpedance As it can be observed, the precision of the Calculated Magnitude is good, However the phase measured is very inaccurate. Probably this is due to the noise on the signal, than Assembly and Experimentation 57 can cause the trigger to activate at the wrong time. Which causes the algorithm to fail. At lower frequencies, the magnitude calculate has a slight error of 2 to 5 dB. However, as the frequency increases, the precision of the magnitude does the same. Figure 8.19: Result of the Measure of a 1000Ωimpedance Increasing the load from 300Ωto 1000Ω.The results are the same. With the magnitude being precise while the phase shows a lot of artifacts. Figure 8.20: Result of the Measure of a 110µFcapacitance Disregarding the phase measurement, the magnitude measurement corresponds with what is to be expected. At 3kHz the expected impedance is 54dB and at 10kHz 43dB. There is a slight offset on the measure (58 and 46 respectively). CHAPTER 9. ECONOMIC STUDY AND TIME All projects need a section where the cost is estimated purely to determine its viability. The simplest way to analyze the cost of the project is to analyze its monetary cost as well as the time invested on it. Strictly speaking this section is not a budget. A budget, by its very own definition is a prevision of the money that will be spend in any project. This section will cover the actual cost of the project, now that it has concluded. 9.1. Economic Study Item Description Price Qty Total 1 Operational Amplifier ANALOG DEVICES AD844ANZ 13.57 2 27.14 2 Operational Amplifier ANALOG DEVICES AD8038ARZ 2.96 1 2.96 3 Operational Amplifier ANALOG DEVICES AD8130ARZ 4.87 1 4.87 4 10kΩResistance MULTICOMP PRO MCWF08P1002FTL 0.0186 10 0.19 5 3 Pin Connector MOLEX 22-04-1031 0.684 1 0.68 6 100kΩResistance MULTICOMP PRO MCWR12X1003FTL 0.015 10 0.15 7 1kΩResistance MULTICOMP PRO MCWR12X1001FTL 0.017 10 0.17 8 BNC connector MULTICOMP PRO MP-13-53 TGN 50R 10.31 4 41.24 9 100µFCapacitor TDK C5750X5R1A107M280KC 2.89 4 11.56 10 0.1µFCapacitor MURATA GRM55DR73A104KW01L 0.906 15 13.59 11 100pF Capacitor WURTH ELEKTRONIK 885342014230 2.97 2 5.94 12 10µFCapacitor KYOCERA AVX 22201C106KAT2A 2 4 8.00 13 0.22µFCapacitor MURATA GCJ55DR72J224KXJ1L 0.791 2 1.58 14 6.8µFCapacitor KYOCERA AVX 22201C685K4T2A 2 10 20.00 15 MA connector TE CONNECTIVITY 5-1814400-2 3.95 3 11.85 16 220ΩResistance Yageo RC2512JK-07220RL 0.089 10 0.89 17 10MΩResistance TE Connectivity CRGS2512J10M 0.198 10 1.98 59 LISTINGS A.1 Impedance C++ code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 A.2 Main C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 A.3 Main Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 A.4 HTML App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 A.5 CSS formatting file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 A.6 JavaScript App file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 67 APPENDIX A. CODE Listing A.1: Impedance C++ code 1# include <stdio.h> 2# include <stdlib .h> 3# include <unistd .h> 4# include <math .h > 5# include " rp.h" 6 7uint32_t bf_siz = 16384; 8 9int calculate_magnitude ( float * buff_1 , float * buff_2 , float * mag_2 , float* mag_1 ){ 10 // Calculate Magnitude . Consider doing it via FFT perhaps 11 * mag_1 = 0; 12 * mag_2 = 0; 13 for (int i =0; i < bf_siz ;++ i ){ 14 if ( buff_1 [i]> * mag_1 ){ 15 * mag_1 = buff_1 [i ]; 16 } 17 if ( buff_2 [i]> * mag_2 ){ 18 * mag_2 = buff_2 [i ]; 19 } 20 } 21 return 0; 22 } 23 24 int calculate_phase(float * buff_1 , float * buff_2 , float* phase , float mag_1 , float mag_2 , int decimation , float freq ) { 25 * phase = 0; 26 int peak_1 = 0; 27 int peak_2 = 0; 28 29 // 0 Cross detection 30 for (int i = 1; i< bf_siz ; ++i){ 31 if ( buff_1 [i] >= 0.0 && buff_1 [i -1] <= 0.0) { 32 peak_1 = i; 33 break; 34 } 35 } 36 37 for (int i = 1; i< bf_siz ; ++i){ 38 if ( buff_2 [i] >= 0.0 && buff_2 [i -1] <= 0.0) { 39 peak_2 = i; 40 break; 69 41 } 42 } 43 * phase = ( float)( peak_1 - peak_2 )* decimation /125000000.0*360.0* freq ; 44 45 // Bound any angle between [180 , -180] degrees 46 if (* phase < -360.0) { 47 * phase = ( float)* phase +360.0* floor (* phase / -360.0) ; 48 } 49 if (* phase < -180.0) { 50 *phase = 360.0 + *phase; 51 } 52 if (* phase > 360.0) { 53 * phase = ( float)* phase - 360.0* floor (* phase /360.0) ; 54 } 55 if (* phase > 180.0) { 56 * phase = * phase -360; 57 } 58 return 0; 59 60 } 61 void gen_configure ( float freq , float amp , float offset ){ 62 rp_GenFreq ( RP_CH_1 , freq ); 63 rp_GenAmp ( RP_CH_1 , amp ); 64 rp_GenOffset ( RP_CH_1 , offset ); 65 rp_GenWaveform ( RP_CH_1 , RP_WAVEFORM_SINE ); 66 rp_GenOutEnable ( RP_CH_1 ); 67 // Just for testing remove latter 68 rp_GenFreq ( RP_CH_2 , freq ); 69 rp_GenAmp ( RP_CH_2 , amp /2) ; 70 rp_GenOffset ( RP_CH_2 , offset ); 71 rp_GenWaveform ( RP_CH_2 , RP_WAVEFORM_SINE ); 72 rp_GenPhase ( RP_CH_2 , 90) ; 73 rp_GenOutEnable ( RP_CH_2 ); 74 } 75 76 void acq_configure ( int dec , float trigger ){ 77 rp_AcqSetDecimationFactor ( dec ); 78 rp_AcqSetTriggerLevel ( RP_T_CH_1 , trigger ); 79 rp_AcqSetTriggerLevel ( RP_T_CH_2 , trigger ); 80 rp_AcqSetGain ( RP_CH_1 , RP_LOW ) ; 81 rp_AcqSetGain ( RP_CH_2 , RP_LOW ) ; 82 rp_AcqSetTriggerDelay(bf_siz/2.0); 83 84 } 85 86 int impedance(float start_freq , float end_freq , int pts ){ 87 // Create Aquisition Buffer 88 float* buff_1 = ( float *) malloc ( bf_siz * sizeof(float)) ; 89 float* buff_2 = ( float *) malloc ( bf_siz * sizeof(float)) ; 90 int decimation; // fs = 125 e6/ decimation 91 float incr; 92 float freq; 93 bool fillState = false;// State of the aquisition buffer 94 // Create CSV 95 FILE * fpt ; 96 fpt = fopen ("/ opt / redpitaya / www / apps / tfe_app / Bode . csv " , "w+"); 97 fprintf ( fpt ," Frequency , Magnitude , Phase , peak1 , peak2 \n" ); 98 99 /* Print error , if rp_Init () function failed */ 100 if ( rp_Init () != RP_OK ){ 101 fprintf ( stderr , " Rp api init failed !\ n"); 102 } 103 104 // This method creates frequencies in the interval [ start , end ) 105 // To have the end point included 106 // incr = ( end_freq - start_freq ) /( pts -1) ; 107 incr = ( end_freq - start_freq )/ pts ; 108 freq = start_freq ; 109 110 rp_GenReset () ; 111 rp_AcqReset () ; 112 113 114 for (int j =0; j < pts ; ++ j){ 115 116 // Attempt to , at the very least have fs = 4* freq 117 // If not possible guarantee fs = 2* freq 118 decimation = floor (125000000.0/(4* freq )); 119 if ( decimation == 0){ 120 decimation = floor (125000000.0/(2* freq )); 121 if ( decimation == 0){ 122 printf(" Frequencies exceed operating range \ n"); 123 return 0; 124 } 125 } 126 // Configure DAC and ADC 127 gen _conf igure ( freq ,1 ,0) ; 128 acq_configure ( decimation ,0.1) ; 129 // Start Aquisition 130 rp_GenTriggerOnly(RP_CH_1); 131 rp_GenTriggerOnly(RP_CH_2); // Just for testing delete latter 132 rp_AcqStart () ; 133 // In theory it is already added on the configuration . Only readd if there is a problem with the results 134 // sleep (1) ; // Recommended By RedPitaya 135 rp_AcqSetTriggerSrc(RP_TRIG_SRC_CHA_PE); 136 // Wait Until the buffer fills 137 rp_AcqGetBufferFillState (& fillState ); 138 while(!fillState){ 139 rp_AcqGetBufferFillState (& fillState ); 140 } 141 rp_AcqStop(); 142 // Read Buffer Data 143 rp_AcqG etOldestDataV ( RP_CH_1 , & bf_siz , buff_1 ) ; 144 rp_AcqG etOldestDataV ( RP_CH_2 , & bf_siz , buff_2 ) ; 145 float mag_1 , mag_2 , phase ; 146 calculate_magnitude ( buff_1 , buff_2 , &mag_2 , & mag_1 ) ; 147 calculate_phase ( buff_1 , buff_2 , & phase , mag_1 , mag_2 , decimation , freq ); 148 // Write data to CSV 149 fprintf ( fpt ,"%f ,%f ,%f ,%f ,% f\n", freq , 20* log10 ((1000* mag_1 / mag_2 )) , phase ,mag_1 , mag_2 ); 150 freq = freq+incr; 151 } 152 fclose ( fpt ); 153 // Important to release resources to avoid a memory leak 154 free ( buff_1 ); 155 free ( buff_2 ); 156 rp_GenReset () ; 157 rp_AcqReset () ; 158 rp_Release(); 159 return 0; 160 } Listing A.2: Main C++ 1# include <limits .h> 2# include <math .h > 3# include <stdio.h> 4# include <stdlib .h> 5# include <unistd .h> 6# include <fstream > 7# include <sys / types .h > 8# include <sys / sysinfo .h> 9# include "impedance.cpp" 10 # include " main .h" 11 12 // Parameters 13 CBooleanParameter state("LED_STATE", CBaseParameter::RW, false , 0) ; 14 CFloatParameter startFreq ("START_FREQUENCY",CBaseParameter :: RW , 0, 0, 0, 2000000) ; 15 CFloatParameter endFreq (" END_FREQUENCY ",CBaseParameter::RW, 0, 0 ,0, 2000000) ; 16 CIntParameter freq_step ("FREQ_STEP",CBaseParameter::RW, 0, 0, 0, 1000) ; 17 18 const char * rp_app_desc ( void) 19 { 20 return (const char *)" Impedance Analyzer application .\n "; 21 } 22 23 24 int rp_app_init ( void) 25 { 26 fprintf ( stderr , " Loading LED control \n"); 27 // Initialization of API 28 if ( rpApp_Init () != RP_OK ) 29 { 30 fprintf ( stderr , " Red Pitaya API init failed !\n"); 31 return EXIT_FAILURE; 32 } 33 else fprintf ( stderr , " Red Pitaya API init success !\ n"); 34 35 return 0; 36 } 37 38 39 int rp_app_exit ( void) 40 { 41 fprintf ( stderr , " Unloading LED control \n"); 42 43 rpApp_Release () ; 44 45 return 0; 46 } 47 48 49 int rp_set_params ( rp_app_params_t *p, int len ) 50 { 51 return 0; 52 } 53 54 55 int rp_get_params ( rp_app_params_t **p) 56 { 57 return 0; 58 } 59 60 61 int rp_get_signals(float ***s, int *sig_num , int *sig_len) 62 { 63 return 0; 64 } 65 66 void UpdateSignals ( void) {} 67 68 69 void UpdateParams(void){} 70 71 72 void OnNewParams ( void) 73 { 74 state . Update () ; 75 startFreq . Update () ; 76 endFreq . Update (); 77 freq_step . Update () ; 78 79 if ( state . Value () == true){ 80 std :: ofstream outFile ("/ opt / redpitaya / www / apps / tfe_app / pipe ",std :: ofstream :: trunc ); 81 outFile << ’1’; 82 outFile . close () ; 83 impedance ( startFreq . Value () , endFreq . Value () , freq_step . Value () ); 84 } 85 state . Set ( false); 86 87 std :: ofstream outFile ("/ opt / redpitaya / www / apps / tfe_app / pipe",std :: ofstream :: trunc ); 88 outFile << ’0’; 89 outFile . close () ; 90 } 91 92 93 void OnNewSignals(void){} 94 95 96 void PostUpdateSignals(void){} Listing A.3: Main Header 1#pragma once 2 3# include < DataManager .h > 4# include < CustomParameters .h > 5# include " rpApp .h" 6 7 8 9 10 #define IS_NEW (X) X. Value () != X. NewValue () 11 12 13 #ifdef __cplusplus 14 extern "C" { 15 #endif 16 17 18 /* Parameters description structure - must be the same for all RP controllers */ 19 typedef struct rp_app_params_s { 20 char * name ; 21 float value; 22 int fpga_update ; 23 int read_only; 24 float min_val ; 25 float max_val ; 26 } rp_app_params_t ; 27 28 29 30 /* module entry points */ 31 const char * rp_app_desc ( void); 32 int rp_app_init ( void); 33 int rp_app_exit ( void); 34 int rp_set_params ( rp_app_params_t *p, int len ) ; 35 int rp_get_params ( rp_app_params_t **p); 36 int rp_get_signals(float ***s, int *sig_num , int * sig_len ); 37 38 #ifdef __cplusplus 39 } 40 #endif Listing A.4: HTML App 1<! -- 2* 3* Red Pitaya Impedance Analyzer Application 4* Author : Victor Main Nadal 161 var trace2 = { 162 type: " scatter ", 163 mode: "lines", 164 name: ’Phase’, 165 x: unpack ( rows , ’Frequency’), 166 y: unpack ( rows , ’Phase’) , 167 line : { color : ’#7F7F7F’} 168 } 169 170 var data = [ trace1 , trace2 ]; 171 172 var layout = { 173 title: ’Bode Plot’, 174 xaxis: { 175 176 type: ’log ’, 177 autorange: true , 178 // range : [ ’2015 -02 -17 ’ , ’2017-02-16’], 179 rangeselector : { buttons : [ 180 { 181 count : 1, 182 label: ’1m’, 183 step: ’month’, 184 stepmode: ’backward’ 185 }, 186 { 187 count : 6, 188 label: ’6m’, 189 step: ’month’, 190 stepmode: ’backward’ 191 192 }, 193 { step : ’all ’} 194 ]} , 195 rangeslider : {} , 196 }, 197 yaxis: { 198 autorange: true , 199 range : [86.8700008333 , 138.870004167], 200 type: ’ linear ’ 201 } 202 }; 203 PLOT = document . getElementById (’chart - container’); 204 Plotly . newPlot ( PLOT , data , layout ); 205 }) 206 } 207 } 208 }) ; 209 210 211 212 } APPENDIX B. SCHEMATICS 85 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 A B C D E F A B C D E F Date: KiCad E.D.A. 8.0.4 Rev: Size: A3 Id: 1/1 Title: File: Impedance Analyzer.kicad_sch Sheet: / NC 1 -IN 2 +IN 3 -VS 4 NC 5VOUT 6+VS 7DISABLE* 8 U2 AD8038 C2 100n C8 100n R6 1k C38 100u C26 100p C16 100n 1 2 3 J1 Conn_01x03 J2 Conn_Coaxial_Small R10 220 R3 1k C3 100p 1 - 2 + 3 V4 5 6 V+ 7 8 U7 OPA656 R4 220 J5 Conn_Coaxial_Small J7 Conn_Coaxial_Small C4 100u J3 Conn_Coaxial_Small +IN 1 -VS 2 PD* 3 REF 4FB 5 OUT 6 +VS 7 -IN 8 U5 AD8130ARZ J8 Conn_Coaxial_Small R7 10MEG C10 100n 1 -2 +3 V4 5 6 V+ 7 8 U4 OPA656 R8 10MEG J4 Conn_Coaxial_Small C5 100u R5 10k R2 100k R1 1k C6 100n R9 10MEG 1 - 2 + 3 V4 5 6 V+ 7 8 U3 OPA656 C1 100u J6 Conn_Coaxial_Small NULL 1 -IN 2 +IN 3 -VS 4TZ 5 OUTPUT 6 +VS 7 NULL 8 U1 AD844 R12 1k 1 -2 +3 V4 5 6 V+ 7 8 U6 OPA656 1 -2 +3 V4 5 6 V+ 7 8 U8 OPA656 C37 10p R11 1k C7 6.8u C32 100n C27 100n C22 100n C21 6.8u C23 6.8u C25 6.8u C24 100n H4 MountingHole H3 MountingHole H2 MountingHole H1 MountingHole C9 6.8u C29 100n C35 10u C33 10u C28 10u C17 6.8u C18 100n C20 100n C19 6.8u C31 220n C36 220n C34 100n C30 10u C11 6.8u C12 100n C13 6.8u C15 6.8u C14 100n VDD VSS V_sensep GND VSS VDD Vfb VSS V+ GND VDD GND VSS GND VDD VSS GND VSSVSS V_sensep GND VSS VDD VDD V_sense GND VDD V_senseN VSSVSS GND VSS VSS VSS GND GND GND VDD GND Vout V_senseN VSS GND VDD VSS VDD VDDVDD V_guard_p VSS VDD VSS GNDGND GND I_sense VDD VSS VSS GND VSS Vin GND GND VSSVSS GND VSS GNDGND GND VDD VDD GND VDD GND VDD VDD VDD VDD VDDVDD GND V_guard_n GND VSS GND VDD Mounting Holes AD844AD8038 Decoupling Capacitors OPA656 AD8130 R11 1k C26 100p