Microcontroller

1 downloads 0 Views 2MB Size Report
Mar 2, 2006 - Z8F6401 Flash microcontroller was devised. The Encore PLCC Miniboard was used because of its versatility in accessing the on-chip ...
Laboratory Data Acquisition System Based on the Z8 Encore!TM Microcontroller

A Thesis Submitted to the ECCE Program School of Science and Engineering Ateneo de Manila University

In Partial Fulfillment of the Requirements for the Degree Bachelor of Science in Computer Engineering

by

Ian Mitchelle S. de Vera

Mentor Mr. Edward Chainani

March, 2006

i

This Computer Engineering Thesis Entitled Laboratory Data Acquisition System Based on the Z8 Encore! Microcontroller Prepared and submitted by Ian Mitchelle Sayo de Vera In partial fulfillment of the requirements for the degree of Bachelor of Science in Computer Engineering, is hereby accepted this 14th day of March, 2006

________________________ Dr. Luis G. Sison Panel Member

_________________________ Dr. Nathaniel Joseph Libatique Panel Member

_________________________ Engr. Tris Calasanz Panel Member

__________________________ Mr. Edward Chainani Thesis Adviser

Grade: A (Excellent)

ii

ABSTRACT A data acquisition system based on the Zilog Encore!TM Z8F6401 Flash microcontroller was devised. The Encore PLCC Miniboard was used because of its versatility in accessing the on-chip peripherals of the Z8F6401. The calibration of the built-in 10-bit analog-to-digital converter of the Z8F6401 gave a very linear response to voltage input from 0.1-V to voltage reference. A pH measurement system with optional auto-titration capability was designed, with an accessory glass electrode acting as pH sensor. The voltage acquired is amplified using a dual power supply LF353 op-amp, level shifted and sent to one of the 8 ADC channels. The data acquisition system allows buffer calibration, pH measurement of samples within the pH range 4.00 to 10.00 and the option to perform an automated strong-acid strong-base titration. The auto-titration feature allows reagent delivery from a reservoir to a sample vessel until the equivalence point is reached. The auto-titration is implemented via a pinch valve that controls reagent flow. The Z8F6401 controls the pinch valve using one of its output port pins, which switches an MPS2222A transistor to logic high to power a pinch valve solenoid and allow the flow of titrant. The default “off” position, which occurs when the port pin is logic low, leaves the valve pinching a silicone tubing to halt reagent delivery. The results given by the pH measurement system are comparable to that of Sartosius® PB-20 pH meter using t Test within the pH range 4.00 to 10.00. This could be attributed to the very linear response of the Z8F6401 sigma-delta ADC to changes in potential. Moreover, the auto-titration setup gave an accurate titrant volume delivery to the bromothymol blue endpoint (pH 6.2 to 7.6) in a strong acid-strong base titration.

iii

ACKNOWLEDGMENTS I would like to thank the following people and organizations: My mentor, Mr. Edward Chainani, for having an infinite patience in guiding me toward this accomplishment. Institute of Electrical and Electronics Engineers (IEEE) and Zilog Electronics Philippines for recognizing this project as a winner of the Microcontroller Applications Design Competition (MADC) open design category. Dr. Luis Sison of UP-Diliman EEE for sharing his expertise in a lecture-workshop on “Microcontrollers for Data Acquisition and Motor Control.” He also provided assistance with the Encore PLCC Miniboard. Dr. Erwin Enriquez for his wonderful insights and ideas. This research was a recipient of funding from his professorial chair. Mr. Leo Malacapo for assisting me in pH determination experiments using the Z8F6401 system and for accompanying me to MADC. Ms. Mailyn Terrado for all the encouragements when I feel down and lost and for helping me move my equipment to the thesis defense venue. Mr. Manuel Rodriguez and Jim Perez for providing me the reagents and equipments required for the experiments and for always being there to lend a helping hand. I dedicate this humble piece of work to my family. Ad majorem Dei gloriam!

iv

TABLE OF CONTENTS ABSTRACT ACKNOWLEDGMENTS 1

INTRODUCTION

1

2

STATEMENT OF THE PROBLEM 2.1 Specific Objectives / 5

3

3

REVIEW OF RELATED LITERATURE 3.1 The Z8 Encore!TM Z8F6401 microcontroller / 6 3.1.1 General description / 6 3.1.2 Description of the Peripherals / 12 3.1.2.1 GPIO / 12 3.1.2.2 ADC / 17 3.1.2.3 UART / 31 3.1.2.4 Hardware Timers / 33 3.2 The ZDS II Encore!TM software / 35 3.2.1 Creating a New Project / 35 3.2.2 Creating a New Source Code File / 40 3.3 Potentiometry and pH measurements / 41 3.3.1 Loading error in potential measurements / 41 3.3.2 Operational Amplifier voltage measurements / 42 3.3.3 Potentiometric pH measurements w/ Glass electrode / 43 3.3.4 Operational Definition of pH / 44 3.3.5 Potentiometric Titrations / 45

6

4

MATERIALS AND METHODOLOGY 4.1 Overview of the Project / 47 4.1.1 The Microcontroller Miniboard / 49 4.1.2 ADC Calibration / Testing / 52 4.1.3 Signal Conditioning Block / 54 4.1.4 The pH program and pH sensor calibration / 57 4.1.5 Auto-Titration Setup / 62

47

5

RESULTS AND DISCUSSION 5.1 Calibration of the Z8F6401 ADC / 66 5.2 Calibration and testing of the pH sensor / 76 5.3 Comparison between Sartorius® PB-20 and Z8F6401 systems / 77 5.4 Accuracy, precision, and limitations of the Z8F6401 / 82 5.5 A Laboratory Experiment: An Automated Titration / 83 5.6 Limitations of the auto-titration system. / 84

66

v

6

CONCLUSIONS AND RECOMMENDATIONS

85

BIBLIOGRAPHY

87

APPENDICES

88

vi

CHAPTER 1 INTRODUCTION Data acquisition of most modern-day laboratory equipment is digital in nature. Some of these instruments have the capability of transferring and storing data using computerized techniques. Digitization of the acquired analytical signal and equipmentcontrol are also common features of chemistry instrumentation. Hence, analog-to-digital conversion is essential for digital systems requiring interface with real-world analog signals. There are several ways to implement analog-to-digital conversion, one of which is via a microcontroller. The Z8 Encore!TM Z8F6401 is a Flash-capable microcontroller based on ZILOG’s advanced 20 MHz eZ8 8-bit microprocessor core. [3] This microcontroller has a built-in 8-channel, 10-bit analog to digital converter (ADC). This eliminates the need for an external ADC chip, which entails additional cost and complex hardware, for various applications that involve analog to digital conversion. Moreover, the capability of the Z8F6401 for Flash in-circuit programming (64K Flash memory) makes faster development time and program field changes possible.

The microcontroller’s rich

peripheral set makes it versatile for different applications, including sensors and motor control, which are essential in digital chemistry instrumentation (DCI). DCI is a reliable platform that guarantees accuracy, precision and convenience in data acquisition. The user can also save time and finish the task with less effort as the data acquisition system can gather data while simultaneously automating other tasks via a controller (e.g., sample heating, stirring and reagent addition).

The user can also

conveniently perform other laboratory activities while the data acquisition (DAQ) system

1

automatically tabulates data and performs simple data processing. Hence, we could design an ideal platform that can serve as a laboratory DAQ system for various Chemistry-related processes and experiments. Different sensors are readily available in the market (e.g., for pH, temperature, conductivity and pressure). We could simultaneously acquire several inputs into a single DAQ system via multiple 10-bit ADC channels to perform different laboratory experiments. We could also mix and match different sensors to tailor fit the needs of a lab experiment. Compared to other platforms, a microcontroller-based DAQ system interfaced to a PC is more versatile and low-cost as it could provide different variable data sets using relatively cheap and readily available materials. Moreover, the system could also be transformed into a portable PDA-interfaced system. It is like having several laboratory instruments in one package, with the same reliability as commercial equipments in terms of accuracy given the high resolution of the Z8F6401 sigma-delta ADC.

The

microcontroller-based DAQ system is relatively cheaper compared to commercial digital instruments like the ones shown in Figure 1. In addition, repair and system upgrade is easy because the design is not proprietary.

Figure 1. Sartorius® PB-20 pH meter (left) and TitroLine® commercial titrator (right)

2

CHAPTER 2 STATEMENT OF THE PROBLEM Commercial laboratory equipment are usually expensive. The lack of portability and hardware complexity of most of these digital instruments are issues that need to be addressed.

Hardware complexity is tantamount to difficult troubleshooting in case

something goes wrong with the instrument. Also, commercial equipment has proprietary hardware that precludes repair by individuals other than manufacturer-trained personnel, usually at considerable expense. This research project will test the feasibility of the Z8 Encore! TM microcontroller (Z8F6401) in portable chemical instrumentation and its suitability as a generic platform for data acquisition. A pH-meter based on the Z8F6401 microcontroller will be devised to test the linearity of 10-bit ADC response to input, which would determine if such a system is an ideal DAQ platform. Other sensors can be interfaced later, i.e., sensors that could measure temperature, pressure, light intensity, dissolved oxygen, and other parameters related to common laboratory experiments. Devising a pH meter based on the Z8F6401 microcontroller is economical, with the added versatility to change the sensor to tailor fit certain applications. A typical commercial pH meter, SartoriusTM Model PB-20 costs $ 695.00, which is approximately equivalent to PhP36,835.00 in today’s average exchange rate. [4] On the other hand, a pH sensor costs only around $74.00 or PhP3922.00. [5] The total price for the “low-cost pH meter” is approximately PhP6,197.00 (see Bill of Materials in Appendix A), including ICs, serial adapters and other minor components, 83.2% cheaper compared to its commercial counterpart.

In this project, we will evaluate the

3

performance of this low-cost pH meter in an actual laboratory set-up; that is, if it is comparable to a commercial pH meter in terms of accuracy. One way of doing this is to run a titration experiment using the Z8F6401-based DAQ and to statistically compare the results with data from a commercial Sartorius® pH meter. This low-cost pH meter was designed to follow a similar pH measurement protocol in commercial pH meters. Here, buffer calibration (e.g., employing buffers with pH 4.00, 7.00 and 10.00) is required prior to an actual pH measurement. One advantage of the microcontroller-based DAQ is the possibility of added system portability when the RS232 is interfaced to a PalmPilot® PDA instead of a PC. Moreover, with the added simplicity of the DAQ system implementation, busted hardware parts can be easily replaced. Circuit parts that could be damaged, such as the MAX232, Z8F6401 or LF353 chip, could easily be replaced as these are housed in IC or PLCC sockets.

4

2.1 Specific Objectives 2.1.1 Primary Objectives 1.

To devise a reliable data acquisition system based on the Z8 Encore!® microcontroller.

2. To test the feasibility of the Z8 Encore!® microcontroller in Chemistry instrumentation by running a titration experiment. a. Test and obtain ADC parameters such as speed, resolution and conversion accuracy. b. Determine the limitations of Z8 Encore-based system. 2.1.2

Secondary Objective

1. To interface the data acquisition system to a PDA, such as a PalmOS, for portable Chemistry instrumentation (if time permits).

5

CHAPTER 3 REVIEW OF RELATED LITERATURE 3.1 The Z8 Encore!TM Z8F6401 microcontroller 3.1.1 General Description of the Z8 Encore! Z8F6401 The following are essential features of the Z8F6401 microcontroller: [6]  20 MHz eZ8 CPU core  8 channel, 10-bit analog-to-digital converter  64 KB Flash program memory  3-channel Direct Memory Access (DMA)  4 KB register RAM  two full-duplex 9-bit UARTs  three 16-bit timers with capture, compare and PWM capability  simple-pin On-chip debugger  serial communication protocols (SPI and I2C)  24 interrupts with programmable priority  two

Infrared

Date

Association

(IrDA)-compliant

infrared

encoder/decoders integrated with the UART  31 I/O pins  Watch-Dog Timer with internal RC oscillator  Voltage Brown-out protection’  Power-on Reset

6

 0oC to +70oC standard temperature and –40oC to +105oC extended temperature ranges. Figure 2 shows a block diagram of the Z8 Encore!TM device architecture. In this project, the peripherals in focus are the following: [7] 1. General-Purpose I/O (GPIO). There are 31 port pins (Ports A[0:7] B[0:7], C[0:7] and D[0:6]). 2. 10-bit Analog-to-Digital Converter. The ADC accepts inputs from up to 8 different analog input sources. 3. UART. Full-duplex and capable of handling asynchronous data transfers. It supports 8 and 9-bit data modes and selectable parity.

Figure 2. Architecture of Z8F640x Family Devices. [7]

The latest 8-bit central processing unit of Zilog, eZ8, has the following new features worth noting: [8] 7

1. Direct register-to-register architecture allows each register to function as an accumulator, which helps increase speed and optimize program memory usage. 2. Compared to hardware stacks, software stack allows much greater depth in subroutine calls and interrupts. 3. Pipelined instruction fetch and execution. 4. More efficient code development in C due to new instructions available for higher level programming languages. The eZ8 CPU contains two major functional blocks, namely, Fetch Unit and Execution Unit. The latter is further subdivided into: 1. Instruction State Machine. The controller for the eZ8 CPU Execution Unit. It completes the instruction after initial decoding tasks of the Fetch Unit. 2. Program Counter. Contains a 16-bit counter and a 16-bit adder. 3. CPU Control Registers. Consists of 4 registers mapped into the Register File address space: stack pointer high byte, stack pointer low byte, register pointer and flags. They are located at addresses FFCH to FFFH. 4. Arithmetic Logic Unit.

Performs arithmetic (e.g. addition, subtraction,

multiplication) and logical operations (e.g. binary logic operations, bit shifting and bit rotation) on the data. The Fetch Unit on the other hand controls the memory interface, with the main function of fetching opcodes and operands from memory. It performs a partial decoding of the opcode to determine the number of bytes to fetch for the operation. The fetch unit

8

is pipelined and operates semi-independently from the rest of the eZ8 CPU.

The

sequence of Fetch Unit operation is as follows: 1. Fetch the opcode. 2. Determine the operand size (number of bytes). 3. Fetch the operands. 4. Present the opcode and operands to the Instruction State Machine. The block diagram for the eZ8 architecture is given on Figure 3 below.

Figure 3. eZ8 CPU block diagram. [8]

It is important that we understand the pin configurations unique for the 44-pin Z8F6401. Refer to Figure 4 for the signal and pin descriptions of the 44-pin Plastic Leaded Chip Carrier (PLCC) Z8F6401 microcontroller. There are four ports, namely A to D. Ports A to C are 8-bit ports, whereas Port D has only 7 bits. The acronym on the right side of the slash in Figure 4 pertains to the alternate function of that pin. Table 1 presents the signal mnemonic and its corresponding description for the different pins in the Z8F6401.

9

Table 1. Pin Descriptions for Z8F6401. [7]

10

Table 1 (cont.)

11

Figure 4. Z8F6401 44-pin PLCC Encore microcontroller. [7]

3.1.2 Description of the Peripherals From the bigger picture of the Z8F6401, we will focus our attention to the peripherals that will be used in the data acquisition system, primarily the GPIO, the ADC, the UART and the hardware timers.[7] 3.1.2.1 General-Purpose I/O (GPIO) There are 31 port pins (Ports A to D) for GPIO operations. Each port has its own control and data registers. The former is employed to determine data-direction, opendrain, output drive current, programmable pull-ups, STOP mode recovery functionality and alternate pin functions. Each port pin is individually programmable.

12

Many of the GPIO port pins can be used as both General-Purpose I/O and to provide access to on-chip peripheral functions such as the timers and serial communication devices. The port A to port D Alternate Function sub-registers configure these pins to either general-purpose I/O or alternate function operation. Table 2 lists the alternate functions associated with these port pins. The Port A-D Address registers select the GPIO Port functionality accessible through the Port A-D Control registers. The Port A-D Address and Control registers combine to provide access to all GPIO Port control (see Table 4). The Port Address selects one of the sub-registers accessible through the Port Control register. Take note that PB[7:0] can act as ADC analog inputs as an alternate function. Moreover, PA4 and PA5 can also act as receiving and transmitting end of the UART respectively. Four registers for each port provide access to GPIO control, input data and output data. Table 3 lists these port registers. It is important to note that one needs to use the ports A-D address and control registers together to provide access to subregisters for port configuration and control.

13

Table 2. Port Alternate Function Mapping for selected pins. [7]

14

Table 3. GPIO Registers and Sub-Registers [7] Port Register Mnemonic Port Register Name PxADDR Port A-D Address Register (selects sub-registers) PxCTL Port A-D Control Register (provides access to sub-registers) PxIN Port A-D Input Data Register PxOUT Port A-D Output Data Register Port Sub-Register Mnemonic Port Register Name PxDD Data Direction PxAF Alternate Function PxOC Output Control (Open-drain) PxHDE High Drive Enable PxSMRE STOP Mode Recovery Source Enable PxPUE Pull-up Enable

Table 4. Port Control sub-register accessible using Control Register. [7]

PxADDR [7:0]

Function

00H 01H 02H 03H 04H 05H 06H 07H-FFH

No function. Data Direction Alternate Function Output Control (Open-Drain) High Drive Enable STOP Mode Recovery Source Enable Pull-up Enable No function.

Subregister PxDD[7:0] controls the data direction of the associated port pin. Port Alternate function overrides the Data Direction register setting. If a bit is set to 0, the data in the Port A to D Output Data Register is driven into the port pin, else the port pin is sampled and the value is written into the Port A-D Input Data register. For instance, writing PADD = 0x33 is the same thing as: PADDR = 0x01 PACTL = 0x33

15

The Port A-D Alternate Function sub-register, PxAF[7:0], is accessed through the Port A-D control register by writing 02H to the port A-C Address register (e.g. PADDR = 0x02). One important caution is to avoid enabling alternate function for GPIO port pins which do not have an associated alternate function. This may result in unpredictable operation. The Port A-D Output Control sub-register, PxOC[7:0], can be accessed via the output control register by writing 03H to the Port A-D Address register. Setting the bits in the Port A-D Output Control sub-registers to 1 configures the specified port pins for open-drain operation; else push-pull operation is configured (default on reset). Similarly, the Port A-D High Drive Enable sub-register, PxHDE[7:0], is accessed through the Port A-D control register by writing 04H to the Port A-C Address register. Setting the bits in the Port A-D High Drive enable sub-registers to 1 configures the specified port pins for high current output drive operation (20 mA), else standard output current drive of 2mA is configured (which is the default on reset). The same operation applies to PxSMRE[7:0] and PxPUE[7:0] sub-registers. Setting the bits in the Port A-D pull-up enable sub-registers to 1 enable a weak internal resistive pull-up on the specified port pins. On the other hand, setting the bits in the Port A-D Stop Mode Recovery Source enable sub-registers to 1 configures the specified port pins as a Stop Mode Recovery source. During STOP mode, any logic transition on a port pin enabled as a Stop Mode Recovery source initiates Stop Mode Recovery. Reading from the Port A-D Input Data Registers, PxIN[7:0], returns the sampled values from the corresponding port pins. The Port A-D Input Data registers are readonly. Suppose port A is configured as inputs, in order to read the state of pins, SW =

16

PAIN (where SW is a variable). Suppose the input is 10000011, then the value will be read from the port and the value of SW will be equal to 0x83. On the other hand, the Port A-D Output Data register, PxOUT[7:0] controls the output of the pins. These bits contain the data to be driven to the port pins. The values are only driven if the corresponding pin is configured as an output and the pin is not configured for alternate function operation. Suppose Port A is configured as output, PAOUT = 0x5A, the following will be written to the port: PA[7:0] = 01011010. 3.1.2.2 Analog-to-Digital Converter (ADC) The ADC converts an analog input signal to a 10-bit binary number. There are three common parameters shared by all ADCs: conversion time, absolute accuracy and resolution. [9] Conversion time is the time it takes the ADC to convert the analog signal to the equivalent binary representation. Resolution, on the other hand, is defined as the number of bits to which the analog signal is converted.

Absolute accuracy is the

closeness of agreement between a measured result and its true value, traceable to an accepted standard. Most data acquisition vendors will provide the specification components of absolute accuracy. These components are percent of reading (or ppm reading), offset value, noise + quantization, and drift.[10]

Data acquisition instrument-error

specifications require two components: (1) Gain error, the portion of a measured value described as percent of reading. (2) Offset value, specified as a portion of full scale. In abbreviated specifications, the gain error alone may be provided even though offset error is much more critical for measurements made at the low end of an input range. Absolute accuracy can be an important consideration when choosing between 12-bit and

17

16-bit ADC instruments. Consider this example involving a 0.5-V signal measured on a 2-V bipolar range using a 12-bit ADC: Assume absolute accuracy is specified as ±(0.005% reading + 1 LSB), where 1 least significant bit (LSB) is the offset value. If we are trying to measure 0.5 V, absolute accuracy is represented as: = ±(0.5 × 0.005% + 2*1/4,096) = ±(0.5 × 0.00005 + 0.000488) = ±(0.000025 + 0.000488) = ±0.513 mV In this case, 1 LSB offset error is 2/4,096 = 0.488 mV or 0.024% of range. The offset error is larger than the gain error by almost a factor of 20, making for poor measurement integrity at the low end of full scale. With a 16-bit ADC, the same 2-V bipolar range, 0.5-V input, and specifications produce the following uncertainty: = ±(0.5 × 0.005% + 2*1/65,536) = ±(0.5 × 0.00005 + 0.000031) = ±(0.000025 + 0.000031) = ±56 µV In this case, 1 LSB offset error is 2/65,536 = 31 µV or 0.00153%. This offset error is similar to the gain error for midscale measurements. While the gain accuracy may be similar for 12-bit and 16-bit boards, factors such as noise and linearity can be more significant, especially for low-voltage signals or where readings cannot be averaged to reduce noise.

The difference between the unquantized input and the quantized output is called quantization error or noise. Quantization error is the result of the discrete steps that represent the analog input and is directly proportional to resolution. Quantization error defines a baseline noise level that effectively limits the ADC’s ability to resolve small signals in a perfect system. Higher-resolution systems have a lower baseline noise level, resulting in a greater dynamic range.

18

For example, consider figure 5 which gives the output codes and corresponding input voltages for a 2-bit ADC with a 3-V full scale value. The figure shows that input values of 0V, 1V, 2V and 3V correspond to 00, 01, 10 and 11 respectively, q is the quantization interval or LSB size. If an input of 1.75V is applied to this converter, the resulting output code is 1,0 which corresponds to a 2V input. The 0.25 V error (2V1.75V) that occurs during the quantization process is called the quantization error.[11]

Figure 5. Code example of a 2-bit ADC. [11]

The last component of absolute accuracy is drift, which is inherent in all measurement instruments. Short- and long-term drift of gain and offset (zero) can be caused by the effect of ambient temperature, humidity, and pressure as well as the aging of components in the ADC.

The features of the sigma-delta ADC of the Z8F6401 are as follows: 1. Eight analog input sources are multiplexed with GPIO ports. 2. Interrupt upon conversion complete. 3. Internal voltage reference generator. The three major functional blocks of the ADC are: 1. Converter 2. Analog Multiplexer

19

3. Voltage Reference Generator The ADC requires an input reference voltage for the conversion. The voltage reference for the conversion may be input through the external VREF pin or generated internally by the voltage reference generator (refer to figure 6 below)

2 Volts Zin = 150 kOhms

DC Offset error: -50 mV to 25 mV

Figure 6. ADC Block Diagram for the Z8F6401 [7]

If the ADC is idle for 160 consecutive clock cycles, the ADC undergoes automatic power down, after which 40 system clock cycles is required for power-up. The ADC powers up after the ADC Control register receives a conversion request. There are two types of analog-to-digital conversion: single shot conversion and continuous conversion.

When the ADC is configured for single-shot conversion, it

performs a single analog-to-digital conversion after which the ADC shuts down. The steps for ADC single shot conversion are as follows:

20

1. Enable the desired analog inputs by configuring the GPIO pins (PB[7:0]) for alternate function. 2.

Write to the ADC control register to configure the ADC and begin the

conversion. The bit fields in the ADC control register can be written simultaneously.  Write to the ANAIN[3:0] field to select one of the 8 analog input sources.  Clear CONT to 0 to select a single-shot conversion.  Write to the /VREF bit to enable or disable the internal voltage reference generator.  Set CEN to 1 to start the conversion. 3. CEN remains 1 while the conversion is in progress. a single-shot conversion requires 5129 system clock cycles to complete. If a single-shot conversion is requested from an ADC powered-down state, the ADC uses 40 additional clock cycles to power-up before beginning the 5129 clock cycles conversion.

This is equivalent to 278 us

conversion time for the Z8F6401 which has an 18.432 MHz system clock. 4.

When the conversion is complete, the ADC control logic performs the

following operations:  10-bit data result written to {ADCDH[7:0], ADCDL[7:6]}  CEN resets to 0 to indicate the conversion is complete.  An interrupt request is sent to the Interrupt Controller. 5. If the ADC remains idle for 160 system clock cycles, it is automatically powered-down. On the other hand, when configured for continuous conversion, the ADC continuously performs an analog-to-digital conversion on the selected analog input. Each

21

new data value over-writes the previous value stored in the ADC Data Registers. An interrupt is generated after each conversion.

The steps for initiating continuous

conversion are as follows: 1. Enable the desired analog inputs by configuring the GPIO pins (PB[7:0]) for alternate function. 2. Write to the ADC control register to configure the ADC for continuous conversion. The bit fields in the ADC control register may be written simultaneously.  Write to the ANAIN[3:0] field to select one of the 8 analog input sources.  Set CONT to 1 to select continuous conversion.  Write to the VREF bit to enable or disable the internal voltage reference generator.  Set CEN to 1 to start the conversion. 3. When the first conversion in continuous operation is complete (after 5129 system clock cycles, plus the 40 cycles for power-up if necessary), the ADC control logic performs the following operations:  CEN resets to 0 to indicate the first conversion is complete. CEN remains 0 for all subsequent conversions in continuous operation. 

An interrupt request is sent to the Interrupt Controller to indicate the

conversion is complete. 4.

Thereafter, the ADC writes a new 10-bit data result to {ADCDH[7:0],

ADCDL[7:6]} every 256 system clock cycles.

An interrupt request is sent to the

Interrupt Controller when each conversion is complete.

22

5. To disable continuous conversion, clear the CONT bit in the ADC Control register to 0. The ADC control register (ADCCTL[7:0]) selects the analog input channel and initiates the analog-to-digital conversion.

Table 5 describes the fields within the

ADCCTL.

Table 5. ADCCTL [7] 7

6

5

4

3

2

1

0

BITS FIELD RESET

CEN 0

Reserved 0

VREF 1

CONT 0

ANAIN[3:0] 0000

The ADC Data High Byte register contains the upper eight bits of the 10-bit ADC output. During a single-shot conversion, this value is invalid. Reading the ADC Data High Byte register latches data in the ADC Low Bits register. The ADC Low Bits register contains the lower two bits of the conversion value. The ADC of the Z8F6401 microcontroller is a sigma-delta ADC. Sigma-Delta Analog to Digital Converters offer high resolution, high integration and low cost, making them a good ADC choice for applications such as process control and precision measurement devices. The analog side of a sigma-delta converter is very simple: a 1-bit ADC. The digital side is more complex since it performs filtering and decimation. To understand how a sigma-delta ADC works, concepts such as oversampling, noise shaping, digital filtering and decimation need to be discussed. [11] According to Nyquist theory, sample frequency, Fs, must be at least twice the bandwidth of the input signal. The ADC input is a continuous signal with an infinite number of possible states. The digital output is a discrete function whose number of

23

different states is determined by the converter’s resolution. If we divide the fundamental amplitude by the RMS sum of all the frequencies representing noise, we obtain the signal-to-noise ratio, SNR. 

For an N-bit ADC, [11] SNR = 6.02N + 1.76 dB To improve SNR in a conventional ADC, number of bits should be increased (refer to Figure 7).

Figure 7. FFT diagram of a multi-bit ADC with a sampling frequency Fs. [11]

In this example, increasing the sampling frequency by the oversampling ratio k (equal to Fs/2Fo), to kFs (refer to figure 8), will result to a lower noise floor. SNR is the same as before, but the noise energy has been spread over a wider frequency range. [11]

24

Figure 8. FFT diagram of a multi-bit ADC with a sampling frequency kF S [11]

Sigma-delta converters exploit this effect by following the 1-bit ADC with a digital filter. This enables it to achieve wide dynamic range from a low-resolution ADC. Take note that SNR improvement does not come simply from oversampling and filtering. For instance, SNR for 1-bit ADC = 7.78 dB. Each factor of 4 oversampling increases SNR by 6dB, and each 6dB increase is equivalent to gaining 1 bit; 1-bit ADC with 24x oversampling achieves a resolution of 4 bits. This means that, to achieve 16-bit resolution, one needs to oversample by a factor of 415. This is not realizable! To overcome this limitation, sigma-delta converters employ noise-shaping technique. Consider the block diagram of a sigma-delta modulator of the first order below (see figure 9).

25

B

C D

W

Figure 9. Block diagram of a sigma-delta modulator [11]

This block diagram includes a difference amplifier, an integrator and a comparator with feedback loop that contains a 1-bit DAC. The DAC is simply a switch that connects the negative input of the difference amplifier to a positive or negative reference voltage. The purpose of the feedback DAC is to maintain the average output of the integrator near the comparator’s reference level. In other words, the feedback loop forces the average of the signal W to be equal to the input signal X. [12] Aside from sigma-delta ADC, there are also other analog-to-digital conversion techniques based on the Z8 microcontroller—Ramp ADC and Charge-Balancing ADC, both of which are of the Integrating ADC type. [13] [14]

A Ramp ADC, as the name

suggests, involves a ramp generator and a timer or counter. To commence conversion, a ramp generator is started and simultaneously, a counter is enabled. When the ramp voltage is the same as the input level, a comparator halts the counter. However, Ramp ADC is not suitable for high accuracy applications due to tight requirements on the stability of the capacitor and comparator. Another technique is known as the Charge-Balancing ADC, which generates digital output by timing the integration slope of an analog current signal using built-in analog comparators of the Z86 microcontroller.

Current processed after the analog

26

circuit is passed through an integrator op-amp (LM 741) circuit that generates a linear ramp for the output voltage due to the Miller effect. If the current is positive going to the integrator, the slope generated is negative, and when the current is negative going to the integrator, the output has a positive slope. [15] Sigma-Delta ADC conversion can be illustrated in the example on Table 6. For this example the input X is a DC input of 3/8. Note that the repetitive pattern develops every 16 samples and that the average of the signal W over samples 1 to 16 is 3/8, thus showing that the feedback loop forces the average of the feedback signal W to be equal to the input X. [11] Table 6. Conversion Table.

The density of “ones” at the modulator output is proportional to the input signal. For an increasing input, the comparator generates a greater number of “ones”, and viceversa for a decreasing input.

By summing the error voltage, the integrator acts as a

lowpass filter to the input signal and a highpass filter to the quantization noise.

27

Most of the quantization noise is pushed into higher frequencies through the modulator (see Figure 10). Oversampling has changed NOT the total noise power, BUT its distribution.

Figure 10. Effect of the integrator in the sigma-delta modulator [11]

If we apply a digital filter to the noise-shaped sigma-delta modulator, it removes more noise than does simple oversampling. The filter most commonly used for the backend of a sigma-delta converter is the FIR (Finite Impulse Response) filter because of its stability, ease of implementation, linear phase response and the fact that decimation can be incorporated into the filter itself. In an FIR filter, the output is dependent only on past and present values of the input.

In contrast to an IIR (Infinite Impulse Response) filter where the output is

dependent on past and present values of both the input and the output.[16] For higher orders of quantization, we can achieve noise-shaping by including more than one stage of integration and summing in the sigma-delta modulator. Figure 11 shows a 2nd order sigma-delta modulator.

28

Figure 11. Second order sigma-delta modulator. [12]

A second-order sigma-delta modulator provides a 15dB improvement in SNR in contrast to 9-dB for its first-order counterpart for every doubling of sampling rate. A smaller oversampling is necessary to achieve a desired SNR as the order to sigma-delta modulator increases. [12] The purpose of the digital-and-decimation filter is to extract information from the 1-bit data stream (at the sampling rate) at the output of the sigma-delta modulator (which can be in the MHz range), and then reduce the data rate to a more useful value (see figure 12) The digital filter’s purposes on the other hand are the following: 1. Averages the 1-bit data stream 2. Improves the ADC resolution. 3. Removes quantization noise that is outside the band of interest. The digital filter on the other hand, determines: 1. Signal bandwidth 2. Settling time 3. Stopband rejection

29

Figure 12. Digital side of sigma-delta modulator. [12]

In sigma-delta converters, a widely-used filter topology that performs the lowpass function is the Sinc3 type. The main advantage is its notch response which can reject the line frequency when set at that frequency. The notch position is directly related to the output data rate (1/data-word period). The Sinc3 filter settles in three data-word periods. Example, with a 60Hz notch (60 Hz data rate) the settling time is 3/60Hz = 50 ms. If a Sinc1 filter is used, the settling time is one-data word. (1/60Hz = 16.7 ms). Because bandwidth is reduced by the digital output filter, the output data rate can satisfy the Nyquist criterion even though its lower then the original sampling rate. [12] Decimation is used to eliminate redundant data at the output. Note that the sampling theorem tells us that the sample rate only needs to be 2 times the input signal bandwidth in order to reliably reconstruct the input signal without distortion. However, the input signal was grossly oversampled by the sigma delta modulator in order to reduce the quantization noise. Therefore, there is redundant data that can be eliminated without introducing distortion to the conversion result. The decimation ratio, M, can have any integer value, provided that the output data rate is more than twice the signal bandwidth (Figure 13). [12]

30

Figure 13. Decimation does not cause any loss of information. [12]

If the input has been sampled at Fs, the filtered output data can therefore be reduced to Fs/M without loss of information. Figure 14, demonstrates decimation in the time domain.

Figure 14. Decimation in the time domain. [12]

3.1.2.3 The UART The Universal Asynchronous Receiver/Transmitter (UART) is a full-duplex communication channel capable of handling asynchronous data transfers. The Z8F6401

31

uses two fully independent UARTs. The UART uses a single 8-bit data mode with selectable parity. Features of the UART include: [7]  8-bit asynchronous data transfer  Selectable even-and odd-parity generation and checking  Option of one or two Stop bits  Separate transmit and receive interrupts  Framing, parity, overrun and break detection  Separate transmit and receive enables  16-bit Baud Rate Generator (BRG) The UART consists of three primary functional blocks: transmitter, receiver and baud rate generator. The UART’s transmitter and receiver are independent from one another but employs the same baud rate and data format. Figure 15 shows the UART block diagram.

Figure 15. UART Architecture of the Z8F6401 microcontroller. [7]

The UART always receives and transmits in 8-bit data format, least significant bit first. An even or odd parity can be optionally added to the data stream. Each character begins with an active Low Start bit and ends with either 1 or 2 active High Stop bits.[17]

32

3.1.2.4 Hardware Timers The Z8F6401 has three 16-bit reloadable timers. That can be used for timing, event counting or generation of pulse-width modulated signals (PWM). Some of the features of timers worth mentioning are the following: [7] 

Programmable prescalers with values ranging from 1 to 128 (set as powers of 2)



PWM output generation.



Capture and compare capability.



External input pin for timer input , clock gating or capture signal.



Timer output pin.



Timer interrupts.

Figure 16 shows the timer block diagram for the Z8F6401.

Figure 16. Z8F6401 timer block diagram

There are two timer operating modes: one-shot and continuous.

In one-shot

mode, the counter counts up to the 16-bit Reload value stored in the timer Reload High and Low byte registers. The timer input is the system clock. When the reload value is reached, an interrupt is generated and the count value in the timer High and Low byte

33

registers is reset to 0x01. Then, the timer is disabled and stops counting. For the continuous mode, instead of disabling the timer after one counting, the timer resumes after resetting the value of the High and Low byte registers to zero. The following are the steps to configure the timer in continuous mode: [7] 1. Write to the timer control register to:  disable the timer  configure the timer to continuous mode  set the prescale value 2. Write to the Timer High and Low byte registers to set the starting count value (usually, 0x01). This only affects the first run in continuous mode. After the first timer reload in continuous mode, all succeeding runs will commence at the reset value 0x01. 3. Write to the Timer Reload High and Low byte registers to set the Reload value. 4. If desired, enable the timer interrupt and set the timer interrupt priority by writing to the relevant interrupt registers. 5. If using the timer output function, configure the associated GPIO port pin for the Timer Output alternate function. 6. Write to the timer control register to enable the timer and begin counting. In continuous mode, it is always the system clock that provides the timer input, which for the Z8F6401 is equal to 18.432 MHz. The timer period is given by equation 1:

(1) If an initial starting value other than 0x01 is employed, substitute (Reload Value – Starting Value) to Reload Value in equation 1.

34

3.2 The ZDS II Encore Software The Zilog Development Studio II has an integrated development environment and has a built-in C compiler, assembler, linker and project manager. A debugger allows single-stepping, viewing of variables, register files, code/data memory, ports and timers. The ZDS II connects to the uC via serial port communications.[18] When programming in the ZDS II environment, the user should know these ZDS II basics: 3.2.1 Creating a New Project To start a new project (see Figure 17) in ZDS II environment, click “File” and choose, “New Project.”

Figure 17. New Project Window Select target, CPU and Project Type as shown above. After that, select the location for the new folder and write the folder name for the new project. Finally, type the filename for the new project (see Figure 18).

35

Figure 18. New folder for new project

In the “New Project” window, click continue and wait for the “Configure New Project” window to appear (see Figure 19). Make sure that C Runtime Library and Floating Point library are selected. After that, select startup module, dynamic frames and large memory model.

36

Figure 19. Configure New Project Dialog Box

Click next, then review target memory configuration. Make sure that the settings are the same as that shown in Figure 20, then click “Finish”.

Figure 20. Configuring New Project

To check target system settings, click on “Project” then “Settings” and select the Debugger tab (see Figure 21). Make sure that the “Z8 Encore! OCD Driver” is selected. 37

Else, click on “Configure Driver” and change to the appropriate setting. Click on the “C” tab and make sure the appropriate settings are made in the “General” category, particularly “disable optimizations.” (see Figure 22)

Figure 21. “Debugger” Tab in Project Setting Dialog Box.

38

Figure 22. “C” Tab in Project Setting Dialog Box.

In the “Preprocessor” category, add __Z8F640 in the “preprocessor definitions” (see Figure 23).

Figure 23. Preprocessor Definitions.

39

3.2.2 Creating a New Source Code File To create a source code file, click “File” then select “New File” (see Figure 24). After coding in C, click “File” then select “Save As” and write the filename with a “.c” extension. Make sure that the file is saved in the folder for the project. To create source code file, choose “Project Files” then right click. Select “Add Files to Project”. Choose the “.c” file of choice (see Figure 25).

Figure 24. New Source Code File

Figure 25. “Add Files to Project”

40

Figure 26 shows some of the shortcuts worth mentioning.

Compile means

converting source code into op-codes / object code / machine code. Link, on the other hand pertains to combining all these object codes. Build is tantamount to compiling followed by linking. Syntax errors appear in the output window (as shown in Figure 27). Double-clicking on an error message takes the programmer to the offending line.

Figure 26. Shortcut Icons

Figure 27. Output Window

3.3 Potentiometry and pH measurements 3.3.1 Loading error in Potential Measurements Most cells containing a membrane electrode have very high electrical resistance (as much as 108 ohms or more). To measure potentials of such high resistance circuits accurately, it is necessary that the voltmeter have an electrical resistance that is several orders of magnitude greater than the resistance of the cell being measured. If the meter

41

resistance is too low, current is drawn from the cell, which has an effect of lowering its output potential, thus creating a negative loading error. [19] The magnitude of the loading error in potential measurements depends on the ratio of the internal resistance of the meter to the resistance of the circuit being studied. Numerous high resistance , direct-reading digital voltmeters with internal resistances of > 1011 ohms are now on the market. These meters are commonly called pH meters but could more properly be referred to as pIon meters or ion meters, since they are frequently used for the measurement of concentrations of other ions as well. Modern ion meters are digital, and some are capable of a precision on the order of 0.001 to 0.005 pH unit. Seldom is it possible to measure pH with comparable degree of accuracy. Inaccuracies of 0.02 to 0.03 pH unit are typical. [19] 3.3.2 Operational Amplifier Voltage Measurements One of the most important developments in chemical instrumentation over the past three decades has been the advent of compact, inexpensive, versatile integratedcircuit amplifiers (op-amps). These devices allow us to make potential measurements on high-resistance cells, such as those that contain a glass electrode, without drawing appreciable current. Even a small current (10-7 to 10-10 A) in a glass electrode produces a large error in the measured voltage due to loading and electrode polarization. [19] One of the most important uses for op amps is the isolation of voltage sources from their measurement circuits. The basic voltage follower, which permits this type of measurement has two important characteristics. The output voltage Vout is equal to the input voltage Vin, and the input current Iin is essentially zero (10-9 to 10-15). [16]

42

A practical application of this circuit is the measurement of cell potentials. We simply connect the cell to the op amp non-inverting input and we connect the output of the op amp to a digital voltmeter to measure the voltage. Modern op-amps are nearly ideal voltage-measurement devices and are incorporated into most ion meters and pH meters to monitor high-resistance indicator electrodes with minimal error. [19] 3.3.3 Potentiometric pH measurements with the Glass Electrode The glass electrode is undisputedly the most important indicator electrode for hydrogen ion. It is convenient to use and subject to few of the interferences that affect other pH-sensing electrodes. Errors affecting pH measurements There are some distinct limitations to the pH sensing electrodes: [20] 1. The alkaline error. The ordinary glass electrode becomes sensitive to alkali metal ions and gives low readings at pH values greater than 9. 2. The acid error. Values registered by the glass electrode tend to be somewhat high when the pH is less than 0.5. 3. Dehydration. Dehydration may cause erratic electrode performance. 4. Errors in low ionic strength solutions. It has been found that significant errors (as much as 1 or 2 pH units) may occur when the pH of samples of low ionic strengths, such as lake or stream water, is measured with a glass/calomel electrode system. [21] 5. Variation in junction potential. A fundamental source of uncertainty for which a correction cannot be applied is the junction-potential variation

43

resulting from differences in the composition of the standard and the unknown solution. 6. Error in the pH of the standard buffer. Any inaccuracies in the preparation of the buffer used for calibration or any changes in the composition during storage cause an error in subsequent pH measurements. The action of bacteria on organic buffer components is a common source of deterioration. 3.3.4 Operational Definition of pH The usefulness of pH is a measure of the acidity and alkalinity of aqueous media, the wide availability of commercial glass electrodes, and the relative recent proliferation of inexpensive solid-state pH meters have made the potentiometric measurement of pH perhaps the most common analytical technique in all of science. It is thus extremely important that pH be defined in a manner that is easily duplicated at various times and in various laboratories throughout the world. To meet this requirement, it is necessary to define pH in operational terms—that is, by the way the measurement is made. The operational definition of pH endorsed by the National Institute of Standards and Technology (NIST) and IUPAC is based on the direct calibration of the meter with carefully prescribed standard buffers followed by potentiometric determination of the pH of unknown solutions. Consider a glass/reference electrode pair. When these electrodes are immersed in a standard buffer, using the Nernst equation, we can derive: [22] pHS = (ES – K) / 0.0592

(2a)

44

where ES is the cell potential when the electrode is immersed in the buffer and K, a constant. Similarly, if the cell potential is EU when the electrodes are immersed in a solution of unknown pH, we have pHU = (EU – K) / 0.0592

(2b)

By subtracting the first equation from the second and solving for pHU, we find: pHU = pHS – [(EU-ES)/0.0592]

(3)

Equation (3) has been adopted throughout the world as the operational definition of pH.

3.3.5 Potentiometric Titrations Potetiometric titration involves measurement of a potential of a suitable electrode as a function of titrant volume. The information provided by a potentiometric titration is not the same as that obtained from a direct potentiometric measurement. For instance, the direct measurement of 0.100 M solutions of hydrochloric and acetic acids would yield two substantially different hydrogen ion concentrations because the latter is only partially dissociated. In contrast, the potentiometric titration of equal volumes of the two acids would require the same amount of standard base because both solutes have the same number of titratable protons. [23] Potentiometric titrations provide data that are more reliable than data from titrations that use chemical indicators. These titrations have been automated in a variety of different ways, and commercial titrators are available from a number of manufacturers. Manual potentiometric titrations, however, suffer from the disadvantage of being more time consuming than those involving indicators. Potentiometric titrations offer additional advantages over direct potentiometry. Because the measurement is based on the titrant volume that causes a rapid change in

45

potential near the equivalence point, potentiometric titrations are not dependent on measuring absolute values of cell potential. This makes the titration relatively free from junction potential uncertainties because the junction potential remains approximately constant during the titration. Titration results instead depend more heavily on having a titrant of accurately known concentration. The potentiometric instrument merely signals the endpoint and thus behaves in an identical fashion to a chemical indicator. [23]

46

CHAPTER 4 MATERIALS AND METHODOLOGY 4.1 Overview of the Project The framework for the project is presented as a block diagram, Figure 28, below.

Host PC or PDA

ADC

RS232

Z8F6401 uC

I/O Lines Controller (addition of reagent)

Analog Signal Conditioning

Sensor Chemical Process

Figure 28. Design Framework for the Project

In this block diagram, a sensor, which in this case is a glass electrode, is in close proximity to a chemical process to detect and measure pH. The analog signal will pass through an analog signal-conditioning block, which is subdivided into two parts: the amplifier and level-shifter sub-blocks. The analog signal will be amplified by using opamps, particularly LF353N, since the incoming voltage is too small [24]. The same signal-conditioning block will also level shift the signal to positive voltage values, since the voltage input sensed by the glass electrode is negative above pH 7.00 and positive below this pH value. For instance, a standard buffer with pH 7.00 have typical voltage values within 030 mV. On the other hand, a pH 4.00 standard buffer should give a value 169 to 186 mV more than pH 7.00. Finally, a pH 10.00 standard buffer must result

47

to a voltage equivalent, 159 to 185 mV less than pH 7.00. Whenever the potential sensed by the glass electrode deviate from these values, there is a chance that it may be broken. [25] The built-in analog-to-digital converter (ADC) will then digitize the conditioned analog signal. This data can be transferred via RS232 or serial port to a host PC or for more portability, to a personal data assistant (PDA), for instance a PalmPilot® [26]. In the current working prototype, the data was displayed by using Hyperterminal® (serial communications program). Moreover, the Z8F6401 microcontroller can also send signals to a controller by using one of its 31 I/O lines (PB1) to control the addition of reagent. In this case, the controller is a pinch valve operated by a 12 VDC power supply. This valve is a solenoid which opens when current is passed through it and closes or pinches if otherwise. The glass electrode then monitors pH change while a strong-acid strong-base titration is in progress. To test the pH measurement-auto titration system, standard buffers with pH 4.00 (0.02 20oC, 9884 Titrisol® citrate-HCl buffer), 7.00 (0.02 20oC, 1.09887 Titrisol® phosphate buffer) and 10.00 (0.05 20oC, 9890 Puffer-Titrisol®) are employed for the calibration phase. A program written in C using the Zilog Development Studio II (ZDS II) version 4.6.1, prompts the user to present the buffers to the glass electrode [18]. The ADC then digitizes the voltage sensed by the electrode. The decimal equivalent of the ADC output (with a maximum value of 3FF in hexadecimal) is converted to volts using a normalization factor [voltage reference/(210-1)]. After obtaining the voltage equivalent of each of the standard buffer solutions, the user will be asked if he or she wants a two-point

48

or a three-point calibration. For a two point buffer calibration, the user has to decide if the pH of the solution to be analyzed is within the pH range 4.00 to 7.00 or 7.00 to 10.00. The equation of the line, y = mx + b (where y is voltage and x is pH) will be generated for each case. For a three-point calibration, the equation of the best-fit line of voltage against pH for the pH range 4.00 to 10.00 is determined. After determining which calibration type and pH range to employ, the user will be prompted to present the sample. The voltage sensed by the electrode for this sample will be converted to pH using a suitable calibration curve for the pH range and calibration type selected. Finally, the user has an option to do a strong-acid strong-base titration. We can set the threshold pH to 7.00, the equivalence point for this type of titration, which can be determined by the endpoint of bromothymol blue indicator. This indicator changes from yellow to blue for the pH transition range 6.2 to 7.6 (pKa = 7.10) [19].

The program has

a feedback control loop wherein it checks the pH of the solution as the titration progresses. The pinch valve allows drop-wise delivery of reagent and stops reagent flow if the pH is equal to or greater than the threshold pH value.

4.1.1 The Microcontroller Miniboard This project employs the Encore PLCC Mini Board acquired from the University of the Philippines Diliman, Electronics and Electrical Engineering Department (EEE). The Encore PLCC Mini Board is a module that makes use of the on-chip peripherals of the 44-pin PLCC Z8F6401 Flash Microcontroller, such as the eight-channel analog-todigital converter (ADC) and the universal asynchronous receiver/transmitter (UART). A

49

9VDC adapter is employed to power the board. The I/O pins of the Z8F6401 can be conveniently accessed through pin headers. This method avoids the usual problems encountered in hardware construction, particularly erroneous and loose connections. The specification of the PLCC Mini Board is presented below: [2]  8 channel analog input (direct unbuffered)  adjustable external voltage reference (2.5 to 3.8 V)  PCB layout: single sided  RS232 interface: PCB mounted DB-9  power o LED indicator o 9V unregulated in (from adaptor) o 5V, 3.3V on-board regulation  remaining digital lines on header Figure 29 shows the Layout of the PLCC Mini Board, the schematic of which is presented in Figure 30. For a thorough discussion regarding the PLCC Mini Board, refer to the User’s Guide for the PLCC Mini Board in the Appendix B.

50

Figure 29. PLCC Mini Board [2]

In interfacing the Encore PLCC Mini Board to a PC, RS-232 or serial communication is used. A program written in C can be downloaded into the 64-K flash memory via a serial cable from COM 1 (9-pin) to Debugger UART. To output data generated by the Z8F6401, it is necessary to connect the Console UART to COM 2 (9 or 25-pin). In case COM 2 is 25-pin, a 9-to-25 serial cable should be employed. The external voltage reference is shorted to the voltage reference using a jumper. The external voltage can be adjusted by a potentiometer from 2.5-V to 3.8-V. The external voltage reference is set to 3.30-V.

51

Figure 30. Z8F6401 and its Pin Connections

4.1.2 ADC Calibration / Testing In the calibration of the Z8F6401 ADC, the incoming analog signal is varied from 0.1V to voltage reference (3.31-V) via a Bourns potentiometer potential-divider circuit. The output is displayed using Hyperterminal® and simultaneously measured using a

52

YEW® Model 2501A Precision Digital Multimeter and Hewlett-Packard® E2373A Multimeter. A program, adc.c (see Appendix J), which displays to a PC using a serial communications program (Hyperterminal®) the hexadecimal equivalent of the Z8F6401 ADC output was developed. The program is downloaded into the 64-K flash memory via a serial cable from COM 1 (9-pin) to Debugger UART. An external voltage reference which can be varied from 2.5 to 3.8 V is employed. An adjustable potential divider is used to vary the analog input signal to ANA0 with respect to an external reference voltage set to 3.31-V throughout the calibration of the ADC. The Console UART is connected to COM 2 (25-pin) via a 9-to-25 serial cable. Initially, the user will be prompted to enter any positive number. The input value will be the number of times the ADC output will be sampled in single-shot mode and value is displayed using Hyperterminal®. The hexadecimal value is converted to volts by normalizing the value by 1023—the maximum value that can be outputted by a 10-bit ADC which is equal to 3FF in hexadecimal—then multiplying the ratio by 3.31-V, the external reference voltage. The baud rate employed throughout the calibration and in succeeding experiments is 57,600 and the frequency of the Miniboard is set by the crystal oscillator at 18.432 MHz. The output of the ADC is compared to the output of YEW® Model 2501A Precision Digital Multimeter and Hewlett-Packard® E2373A Multimeter. The calibration is performed at two temperatures, 24.5oC and 28.5oC, so we can determine to what extent temperature can affect the output of the ADC.

53

4.1.3 Signal Conditioning Block The signal conditioning block is composed of the LF353N monolithic dual FET input op-amps in a single dual-in-line package (DIP) [27] [see Appendix C for the data sheet]. The op-amp employs a dual power supply, +5V and –5V. The unregulated +12V and –12V power supplies are full-wave rectifier-filter circuits, connected via phone-jacks and regulated to +5 and –5 V using LM340T and LM320T respectively (see Appendix D) [28] [29]. One op-amp amplifies the incoming analog signal from the glass electrode, which is connected to the non-inverting input of the op-amp through a BNC connector, by a factor of around 8.27.

The amplified analog input is level-shifted to positive

voltage values by the other op-amp using the output shifting voltage, Vshift , equal to 3.3 volts. The level shifted signal is sent to PB0 of the Miniboard which is set to its alternate function: ANA0 (ADC analog input 0). The circuit diagrams for the amplifier, level shifter and power-supply are shown in figures 31, 32 and 33 (also shown in full-page in Appendix E). These diagrams are generated using Qcad® electronic design system. The symbol >> pertains to off-page connectors (OPC). If two OPCs have the same name, they are connected. Two wires that cross each other perpendicularly are not connected. “Voltage plus” and “Voltage Minus” pertain to +5V and –5V regulated voltage respectively. In figure 31, the non-inverting input of op-amp A (pin 3 of LF353N) is where the input signal from the pH sensor goes. In figure 32, pin 5 or the non-inverting input for op-amp B is the buffer input for the reference voltage, which is also equal to Vshift. The other end of D1 is connected to VDD (pin 21 of miniboard), which is measured to be 3.30V. The output of the level-shifter, the node between D1 and D2, is connected to ANA0

54

of the Miniboard by using a coaxial cable—the outer braid of which is grounded to lessen noise. The output voltage (Vout) can be calculated given the voltage input (Vin) using the following formula: Vout = (Vin*8.27 + 3.30) / 2

(4)

The 0.1 uF non-polarized capacitor between the output and the inverting input of the amplifier acts as a low-pass filter with a cut-off frequency (fc) at approximately 20 Hz (since fc = 1/2RC, where R=82K, C=0.1uF). Similarly, the 10 uF capacitor parallel to the output of the level shifter is also a low-pass filter with fc=26.5 Hz (R=0.6K, C=10uF). [30]

Analog input

Figure 31. Amplifier circuit

55

Vshift VDD

VRef

Vout

Figure 32. Level Shifter

Figure 33. Power Supply.

56

The equivalent printed circuit board (PCB) design (top view) of the power supply, amplifier and level shifter is shown in Appendix F. The PCB layout, together with the circuit diagrams, is designed using Qcad® electronics design system.[31] Note that in the PCB design, the 2.2K resistor in figure 31 and the 1 uF capacitor in figure 32 do not appear on the layout. They are incorporated in the design via jumper links.

4.1.4 The pH program and pH sensor calibration For the software part, the Zilog Development Studio II (ZDS II) version 4.6.1 is used. This software is included in the Z8 Encore!® package. ZDS II Integrated Development Environment (IDE) is a complete standalone system that provides state-ofthe-art development environment. [32] ZDS II integrates a language-sensitive editor, project manager, C-compiler, assembler, linker, librarian and source-level symbolic debugger to provide a development solution specifically designed for the Z8 Encore!TM line of microcontrollers. It provides a standard user interface with intuitive, easy-to-use controls commonly found in Windows®-based environments. In ZDS II, one can access all the tools through the Z8 Encore!TM developer’s environment. The tools include the following along with the developer’s environment: [32]  Programmer’s editor  Macro Assembler  ANSI-C compiler  Linker/locator

57

 Integrated Command Processor  Automated make facility  Debug Mode  Cycle-accurate simulator  Emulator drivers A program called pHmeter.c (see Appendix G for the code) in the ZDS II project file, pH_no_tempcomp.pro prompts the user via the Zilog pH Help Menu to do buffer calibration prior to pH determination of a sample. The user needs to enter characters ‘f’, ‘s’ or ‘t’, which correspond to standard buffers 4.00, 7.00 and 10.00 respectively. The glass electrode will be immersed into the standard buffer solution selected. The voltage equivalent of the standard buffer is obtained after the user pressed ‘r’. For best results, it is observed that before pressing ‘r’, the user has to wait for 20 to 30 seconds to allow stabilization, since the electrode is still adjusting to its new environment. Unless the calibration phase is complete, the user won’t be able to proceed to pH determination. For instance, if ‘f’ is pressed, the user will be prompted to “Present buffer with pH 4 and press ‘r’ when ready.” The electrode is then immersed into the buffer with pH 4, and the voltage equivalent for that buffer is obtained. The buffer input for pH 7 and 10 is similar to this. The program can detect if one of the buffers is missing and will display “Buffer input incomplete”. The buffers will be cleared automatically after this error is detected. The user has to repeat the entire calibration. Once the user enters a character that is not in the menu, the error message, “Invalid Command” is displayed.

58

Once the voltage equivalent for the three buffers are obtained, the pH range menu will appear and the user will be prompted to input either ‘a’, ‘b’ or ‘c’, with each letter corresponding to a pH range and a calibration type (two or three-point) [refer to Figure 34]. The slope and y-intercept for the calibration curve will be calculated and displayed. The following formulas are used in calculating the slope and y-intercept of the best-fit line for the three-point calibration, where x is the pH value and y is the voltage equivalent.

m  slope 

n xy   x y n x 2  ( x ) 2

b  y  int ercept 

 y  m x n

(5a)

(5b)

For two-point calibration, the simpler formula, y/x is used to calculate the slope. The y-intercept is obtained by a simple substitution of the corresponding x and y values for a data point lying on either end of the line. After choosing the calibration type and pH range for the solution with unknown pH, the user will be asked to “Present the sample”. After which, the glass electrode is immersed into the sample. When ‘r’ is pressed, the pH of the sample is displayed. A sample Hyperterminal® display is shown in figure 34 for the pH determination of a sample with pH = 7.08 (determined using the Sartorius PB-20, employing the same glass electrode).

59

Figure 34. Sample Hyperterminal® output for pHmeter.c If a new sample needs to be analyzed, the user presses ‘n’. The pH range menu will appear again, asking the user to enter either ‘a’, ‘b’ or ‘c. The equation of the line generated depends on which letter is chosen. The suitable calibration curve is employed in calculating the pH of a sample. If ever a new calibration is desired, the user has an option to clear the buffers by pressing ‘z’ (for “zeroing”) and repeat buffer input by pressing ‘f’, ‘s’ and ‘t’ again. Alternatively, the user can simply overwrite the contents of the buffers without clearing the buffers. Also, after invoking the “Rebuild All” or “Reset” command, the buffers are automatically cleared. Finally, the user has an option to perform a strong-acid strong-base titration. Such titration has a sharp endpoint (pH 4 to 10). We can set the threshold pH to 7.00, the equivalence point for a strong acid-strong base titration. Bromothymol blue indicator is

60

chosen as the suitable indicator since it changes color from yellow to blue within the transition pH range 6.2 to 7.6—the set-point 7.00 is within this range.

The program has

a feedback control loop which constantly checks the pH of the solution as the titration progresses. The pinch valve allows “free flow” of titrant up to pH 3.00. Above pH 3.00 but less than 7.00, a hardware timer is employed to synchronize the opening and closing of the pinch valve for 0.455 s for each opening and another 0.455 s for each closing. This is implemented by setting the reload value of the timer to 65536 and the initial value to 1. The prescale value—which divides the frequency by powers of 2—is set to 128. With the XTAL frequency equal to 18.432 MHz, the delay produced using these settings is 0.455 s. This open-close action of the pinch valve results to a more controlled delivery of the titrant, so that overshooting is avoided. At pH 7.00 and above, the pinch valve closes and titrant delivery is terminated.

Note that for the auto-titration, the three-point

calibration type (pH 4.00 to 10.00) is automatically selected since we need a large pH range for this case. Figure 35 shows the program flow chart for the project.

61

Figure 35. Program flow chart.

4.1.5 Auto-Titration Setup The auto-titration setup is shown in figure 36.

The base titrant (ca 0.1 M

standardized NaOH) is delivered using a buret. The pinch valve is pinching the silicone tubing attached to the buret. In the default closed position, no reagent is coming out, but once the user decided to perform a titration, the valve opens and the titrant is delivered, first in free-flow, then to drop-wise to 25.0 mL of an acid sample (ca 0.1 M HCl) in a 500-mL beaker. Deionized water is added to the acid sample to increase the height of the

62

solution. To make sure that the NaOH titrant is distributed uniformly in the solution, and to avoid the glass electrode sensing an abrupt increase in pH because of the presence of instantaneously high pH regions (in the case when the solution is not swirled), a magnetic stirrer is placed under the beaker.

This equipment controls a stirring bar, which

constantly moves in circular motion to allow continuous mixing. The glass electrode is immersed into the acid sample and monitors pH change as the titration is in progress. For optimum performance, the glass electrode is placed in the “middle” part of the solution. This will avoid the electrode coming in contact immediately to the undistributed base, in the case when the glass electrode is on the top part of the solution. On the other hand, if the glass electrode’s position is very near the bottom, there’s a greater probability that the electrode gets hit by the stirring bar. Two drops of bromothymol blue indicator is initially added prior to the titration. Once the threshold pH is reached, the pinch valve closes and titrant delivery is stopped. The closing of the valve is expected to coincide with the yellow to blue color change of the indicator since the threshold pH is set to a value within the pH transition range of the indicator.

63

buret

Silicone tube Solenoid Pinch valve Glass electrode Variable Power Supply set to 12VDC

Magnetic stirring bar

Figure 36. The auto-titration setup

Pinch Valve Circuit The circuit for the pinch valve (see specifications in Appendix H), which controls reagent delivery is shown in figure 37. [33] The pinch valve requires a 12VDC voltage source for its operation. The current that is passing through the solenoid is measured to be 180 mA. In this figure, if PB1 of the Miniboard is logic high, current passes through the solenoid and the valve opens, allowing reagent delivery. If PB1 is logic low, we can

64

imagine the MPS2222A (see Appendix I for data sheet) transistor as an open circuit and no current passes through the solenoid. [34] Consequently, the valve closes and reagent delivery is stopped.

Figure 37. Pinch valve circuit.

65

CHAPTER 5 RESULTS AND DISCUSSION 4.1

Calibration of the Z8F6401 ADC

The output of the ADC was compared to the output of YEW® Model 2501A Precision Digital Multimeter and Hewlett-Packard® E2373A Multimeter as described in detail in the Methodology.

The output voltage for both precision meter and the

multimeter are almost the same, deviating by at most 0.01-V relative to each other. Deviation is marked at the upper end of the voltage (near 3.31-V) range. Representative points were taken from 1.00 to 3.31 V at 0.1 or 0.25-V increments. For the region of 0.1 to 1.00-V, data points were taken at 0.1-V increments. Finally, for the 0.01 to 0.1 region, 0.01-V increments are used. Data are taken by slowly increasing the analog input at desired voltage increments from 0.030-V to 3.31-V, then gradually decreasing the voltage from 3.31-V to 0.030-V, taking the hexadecimal output and equivalent voltage of the ADC output at each data point. The scanning is done in both directions to compare the response of the ADC toward increasing and decreasing voltage.

The single-shot ADC

output is sampled 10 times for each data point. More often, the output fluctuates by 1 to 2 hexadecimal units. To standardize the data gathering, the highest hexadecimal output is taken as the “correct” value. The calibration is performed at two temperatures, 24.5oC and 28.5oC, so we can determine to what extent temperature can affect the output of the ADC. Results show that there is an offset of +0.04 to +0.05 V in the output of the ADC relative to the output of the two multimeters. For instance, a 1.250-V analog input will be

66

represented as 0x174 at the ADC output, which is equivalent to 1.204-V after conversion via a normalizing factor. Moreover, based on the results, the lower limit by which the ADC output is valid and nonzero is approximately at 0.040-V analog input. Less then 0.040-V but above 0.030-V is a gray region wherein the 10-bit ADC gave anomalous outputs. For instance, for a 0.0365-V input, the ADC gave an output of 0x40 or 0.207V which is obviously erroneous. Between the range of 0.032 to 0.034V, outputs such as 0x1BF (1.446-V), 0x3F (0.204-V) and 0x3FF (3.31-V) are common. At 0.030 volts and below, the output is clearly 0x00. For simplicity in presentation, all hexadecimal numbers are represented by their respective decimal equivalents. Figure 38 shows the superimposed calibration curves for both increasing and decreasing voltage scans from 0.03-V to Vref at 24.5oC.

The

calibration curve shows a plot of the decimal equivalent of ADC output vs. analog input in volts measured via YEW® 2501A precision multimeter with Vref equal to 3.31V. The YEW® voltage output is chosen because it has inherently more significant digits (4½ digits) compared to the Hewlett-Packard® multimeter (3½ digits). Figure 39 and 40 show superimposed plots for the 0.1 to 1.0-V and 0.03 to 0.l-V range at 24.5oC. Moreover, Figure 41 gives a superimposed plot of the range 0.03 to 0.1-V and 0.1 to 0.5-V. Notice that in both figures 38 and 39, the calibration curves for the increasing and decreasing voltage scan overlap, which is tantamount to saying that the direction of the scan has no significant effect on the slope and linearity of the data points—the ADC output for a given analog input is not affected significantly by the voltage scan direction (see Appendix K for data source of the plots). Also, the linearity of the plots is very good

67

for the 0.1-V to Vref range. However, the plots do not cross the origin, with x-intercept equal to approximately 0.038-V for both plots.

Decimal Equivalent of ADC Output

Fig. 38 Calibration of Z8F6401 ADC at 24.5 oC using YEW 2501A Precision Multimeter Increasing and decreasing voltage 1075 1050 1025 1000 975 950 925 900 875 850 825 800 775 750 725 700 675 650 625 600 575 550 525 500 475 450 425 400 375 350 325 300 275 250 225 200 175 150 125 100 75 50 25 0

Increasing (pink): y = 307.66x - 11.593 R2 = 1

Decreasing (blue) : y = 307.2x - 11.742 R2 = 1

0

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2

2.2

2.4

2.6

2.8

3

3.2

3.4

YEW 2501A Output (V)

Decimal Equivalent of ADC Output

Fig. 39 Calibration of Z8F6401 ADC using YEW 2501A Precision Multimeter at 24.5 oC (0.1 to 1.0 V) for increasing and decreasing voltage

325 300 Decreasing: y = 306.55x - 11.675 275 250 R2 = 1 225 200 175 150 125 Increasing: y = 309.14x - 12.269 100 75 R2 = 1 50 25 0 0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00 YEW 2501A Output (V)

Notice that in figure 40, the value of the linearity coefficient, R2, becomes less when the analog input is in the range of 0.03 to 0.1-V compared to higher voltage ranges.

68

Consequently, we can’t gauge with confidence if the scan direction matters because of significant deviation from linearity at this voltage range. Furthermore, in the same figure, the slope of the decreasing voltage curve (blue data points) is less compared to the increasing voltage curve. Fig. 40 Calibration of Z8F6401 ADC using Yew 2501A Precision o Multimeter at 24.5 C (0.03 to 0.1 V) for increasing and decreasing voltage

Decimal Equivalent of ADC Output

20 18 16 14

Decreasing: y = 279.41x - 9.4872 R2 = 0.9947

12 10 8 6

Increasing: y = 297.57x - 11.098 R2 = 0.9976

4 2 0 0

0.02

0.04

0.06

0.08

0.1

YEW 2501A Output (V)

In figures 41 and 42, the curve for the 0.03 to 0.1-V range is slightly less steep compared to the 0.1 to 0.5-V range plot for both increasing and decreasing voltage. Figures 43 to 47 are similar to figures 38 to 42 but the calibration is done at a higher temperature, 28.5oC.

Note that an increase in temperature has no significant effect on

the results. A 4oC temperature change is probably too small to give an observable effect. Similarly, the plots at this higher temperature do not cross the origin, but instead have xintercepts within the range 0.035 to 0.037-V. The y-intercept of all the plots represents the offset of the ADC which is roughly 8 to 10% of the maximum ADC output.

69

Fig. 41 Superimposed plots for 0.03 to 0.1-V ang 0.1 to 1.0-V o (decreasing voltage) at 24.5 C.

Decimal Equivalent of ADC Output

160 140

0.03 to 0.1-V Range: y = 279.41x - 9.4872 R2 = 0.9947

120 100 80 60 40

0.1 to 0.5-V Range: y = 308.45x - 12.06 R2 = 0.9999

20 0 0.000

0.050

0.100

0.150

0.200

0.250

0.300

0.350

0.400

0.450

0.500

Yew 2501A Output (V)

0.1 to 0.5-V range Linear (0.1 to 0.5-V range )

0.03 to 1.0-V range Linear (0.03 to 1.0-V range)

Fig. 42 Superimposed plots for 0.03 to 0.1-V ang 0.1 to 1.0-V (increasing voltage) at 24.5oC.

Decimal Equivalent of ADC Output

160

y = 308.54x - 12.149 R2 = 1

140 120 100 80 60

y = 297.57x - 11.098 R2 = 0.9976

40 20 0 0.000

0.100

0.200

0.300

0.400

0.500

Yew 2501A Output (V)

0.1 to 0.5-V range Linear (0.1 to 0.5-V range )

0.03 to 0.1-V range Linear (0.03 to 0.1-V range)

70

1075 1050 1025 1000 975 950 925 900 875 850 825 800 775 750 725 700 675 650 625 600 575 550 525 500 475 450 425 400 375 350 325 300 275 250 225 200 175 150 125 100 75 50 25 0

Increasing (pink): y = 309.06x - 10.873 R2 = 1

Decreasing (blue): y = 307.51x - 11.159 R2 = 1 0

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2

2.2

2.4

2.6

2.8

3

3.2

YEW 2501A Output (V)

Fig. 44 Calibration of Z8F6401 ADC using YEW 2501A Precision Multimeter at 28.5 oC (0.1 to 1.0 V) for increasing and decreasing voltage

Decimal Equivalent of ADC Output

Decimal Equivalent of ADC Output

Fig. 43 Calibration of Z8F6401 ADC at 28.5 oC using YEW 2501A Precision Multimeter Increasing and decreasing voltage

325 300 Decreasing: y = 308.01x - 11.353 275 250 R2 = 1 225 200 175 150 125 100 Increasing: y = 309.97x - 11.386 75 R2 = 1 50 25 0 0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00 YEW 2501A Output (V)

71

3.4

Fig. 45 Calibration of Z8F6401 ADC using Yew 2501A Precision o Multimeter at 28.5 C (0.03 to 0.1 V) for increasing and decreasing voltage

Decimal Equivalent of ADC Output

25

Decreasing: y = 299.86x - 10.704 R2 = 0.9916

20 15 10

Increasing: y = 303.59x - 10.729 R2 = 0.9989

5 0 0

0.02

0.04

0.06

0.08

0.1

YEW 2501A Output (V)

Fig. 46 Superimposed plots for 0.04 to 0.1-V ang 0.1 to 1.0-V (decreasing voltage) at 28.5oC. 160

Decimal Equivalent of ADC Output

140 120

0.1 to 0.5-V range: y = 307.28x - 11.18 R2 = 1

100 80 60 40

0.04 to 0.1-V range: y = 299.86x - 10.704 R2 = 0.9916

20 0 0.000

0.050

0.100

0.150

0.200

0.250

0.300

0.350

0.400

0.450

0.500

Yew 2501A Output (V)

0.1 to 0.5-V range Linear (0.1 to 0.5-V range )

0.04 to 0.1-V range Linear (0.04 to 0.1-V range)

72

Fig. 47 Superimposed plots for 0.04 to 0.1-V ang 0.1 to 1.0-V (increasing voltage) at 28.5oC. 160

0.1 to 0.5-V range: y = 309.67x - 11.307 R2 = 1

Decimal Equivalent of ADC Output

140 120 100 80 60 40

0.04 to 1.0-V range: y = 303.59x - 10.729 R2 = 0.9989

20 0 0.000

0.050

0.100

0.150

0.200

0.250

0.300

0.350

0.400

0.450

0.500

Yew 2501A Output (V)

0.1 to 0.5-V range Linear (0.1 to 0.5-V range )

0.04 to 0.1-V range Linear (0.04 to 0.1-V range)

To improve the linearity of the calibration curves at the 0.04 to 0.1-V range, more data points are gathered for this region (0.001 to 0.003-V increments). A voltage divider is employed such that the new reference voltage is 0.125-V. Moreover, since noise is a suspect for the anomalous outputs in the low voltage range of 0.030 to 0.040-V, 0.1 uF and 1.0 uF capacitors are placed parallel to the Bourns potentiometer and Vref respectively. To connect the Bourns wiper pin to ANA0, a short coaxial cable is used with one end of its outer layer conductor grounded, instead of an ordinary wire. Results show anomalous outputs in the range of 0.040-0.045-V. For instance, a 0x40 is an ADC output for a 0.046-V input. Outputs such as 0x40, 0x41, 0x1BF, 0x17F are common in the 0.043 to 0.045-V range; 0x3FF and 0x1BF outputs are observed in the

73

0.041-0.042-V range. Below 0.040-V, the output is clearly 0x00. Anomalous outputs still persist even after filtering. Figure 48 shows superimposed plots for increasing and decreasing voltage inputs for the calibration plots in the 0.040 to 0.12-V region. Notice that the slope of the plots is now comparable to the slope of the calibration plots for higher voltage ranges. The smaller slope for plots in the 0.03 to 0.10-V region in previous figures is brought about by lack of linearity as a result of relatively large voltage increments (0.01-V). In figure 46, 0.001 to 0.003-V increments are used. Anomalous outputs are not included in the data points in this figure. Figure 48. Calibration of Z8F6401 ADC from 0.04 to 0.1 V using Yew 2501A Precision Multimeter at 24.5oC (increasing and decreasing voltage)

ADC output in Decimal

30 25

Increasing (blue) y = 312.5x - 13.907 R2 = 0.9982 Decreasing (pink) y = 308.56x - 13.699 R2 = 0.9976

20 15 10 5 0 0

0.02

0.04

0.06

0.08

0.1

0.12

0.14

Voltage input

The ADC is not sensitive to 0.001-V changes. The hexadecimal output changes by a unit, only after a 0.003-V to 0.004-V change is applied at the input. The “step size” correlates well with the calculated 3.2 millivolt (3.31 V÷1024) ADC resolution. For this reason, the value of the linearity coefficient, slope and y-intercept in previous plots are varying significantly for each calibration plot in the lower-end region. Since the voltage

74

increment (0.01-V) is relatively large in previous plots, the real behavior of the ADC is overlooked. A hexadecimal output persists within a 0.002-V or 0.003-V range, after which, an additional 0.001-V will result to a change at the ADC output by a hexadecimal unit. Thus, the hexadecimal output increases in a staircase fashion as analog input is increased by 0.001-V units (see Figure 49 below). Fig. 49 ADC Output Increases in a "Staircase" Fashion

ADC Output in Decimal

19.5 19 18.5 18 17.5 17 16.5 16 15.5 0.094

0.096

0.098

0.1

0.102

0.104

0.106

0.108

Voltage Input

Figure 50 illustrates the erratic ADC outputs in the 0.040 to 0.045-V range. To encapsulate the ADC calibration experiment, all of the plots do not cross the origin and xintercepts are near 0.040-V. The ADC has a very linear response with respect to an analog voltage input over the region 0.1-V to voltage reference (Vref). Below 0.1-V, the linearity lessens and as we approach 0.040-V, the ADC gave anomalous outputs. Temperature has negligible effects on the ADC output for a 4o temperature change.

75

Figure 50. Erratic ADC Outputs in the 0.040 to 0.045 V range

ADC Output in Decimal

1200 1000 800 600 400 200 0 0.04

0.041

0.042

0.043

0.044

0.045

0.046

Voltage Input

5.2 Calibration and Testing of the pH sensor When the ADC has been determined to be operational, the signal conditioning block was constructed and used to interface the pH sensor to the ADC input. The ph_meter.c was used for calibration of the pH electrode. In the calibration phase, the buffers with pH 4.00, 7.00 and 10.00 are presented to the electrode. Table 7 shows the decimal equivalent of the ADC output and the amplified and level-shifted voltage equivalent measured for these buffers. Figure 51 on the other hand, shows the best-fit line generated. Note the very linear response of the electrode. This result is based on one calibration. However, all calibrations performed have an r-squared value greater than 0.985. Table 7. Calibration of the glass electrode. pH of standard buffer Decimal Equivalent of ADC output 4.00 705 7.00 498 10.00 324

Voltage equivalent (V) 2.294 1.619 1.042

76

Figure 51. Three-point buffer calibration 2.4 2.2

y = -0.2087x + 3.1123 R2 = 0.998

Voltage (V)

2 1.8 1.6 1.4 1.2 1 3

4

5

6

7 pH

8

9

10

11

5.3 Comparison between the pH measurements derived from the “low-cost pH meter” and a commercial pH meter After the calibration phase, buffer samples with different pH values are presented to the electrode. These results are compared to that of the Sartorius ® PB-20 pH meter. This is done by attaching the same glass electrode employed for the Z8F6401 pH measurement system to the PB-20 pH meter, but with the Temperature Compensation probe disconnected, since the Z8F6401 pH measurement system does not have that feature. Table 8 gives the individual pH measurements for the Z8F6401-based system, the average for three runs and the calculated standard deviation for each sample. A similar data to Table 8 is presented in Table 9 for the Sartorius® PB-20 pH meter. Table 10 shows the average pH measurement using these two methods, with the calculated difference.

77

Table 8. pH measurements using the Z8F6401-based pH meter Sample Code

pH measurements 1 2 3 Average 1 7.05 7.08 7.08 7.07 2 9.08 9.09 9.12 9.10 3 9.53 9.57 9.54 9.55 4 3.35 3.32 3.34 3.34 5 10.29 10.30 10.30 10.30 6 5.74 5.76 5.74 5.75 7 6.11 6.10 6.09 6.10 8 8.16 8.12 8.13 8.14 9 4.11 4.10 4.14 4.12 10 2.39 2.38 2.41 2.39 11 10.80 10.81 10.80 10.80 Table 9. pH measurements using the Sartorius® PB-20 pH meter. Sample Code 1 7.10 9.15 9.58 3.23 10.39 5.82 6.12 8.20 4.15 2.27 10.94

1 2 3 4 5 6 7 8 9 10 11

Std. Dev 0.02 0.02 0.02 0.02 0.01 0.01 0.01 0.02 0.02 0.02 0.01

pH measurements 2 3 Average 7.09 7.12 7.10 9.16 9.17 9.16 9.61 9.60 9.60 3.24 3.20 3.22 10.36 10.38 10.38 5.80 5.79 5.80 6.16 6.17 6.15 8.18 8.18 8.19 4.14 4.15 4.15 2.24 2.22 2.24 10.96 10.94 10.95

Std. Dev. 0.02 0.01 0.02 0.02 0.02 0.02 0.03 0.01 0.01 0.03 0.01

Table 10. Comparison of pH values obtained using Z8F6401 pH measurement system and Sartorius® PB-20 Sample Code

1 2 3 4 5 6 7 8 9 10 11

Average (pH) Sartorius, Z8F6401, pHs pHz 7.10 7.07 9.16 9.10 9.60 9.55 3.22 3.34 10.38 10.30 5.80 5.75 6.15 6.10 8.19 8.14 4.15 4.12 2.24 2.39 10.95 10.80

Difference pHz-pHs -0.03 -0.06 -0.05 0.11 -0.08 -0.06 -0.05 -0.05 -0.03 0.15 -0.14

78

Note that the Z8F6401 based pH meter consistently gave pH values 0.03 to 0.06 pH units lower than the result of the Sartorius PB-20 within the pH range 4 to 10. However the difference is significant below and above this pH range. As we deviate farther from this range, the difference becomes greater. Moreover, the result for Z8F6401 pH meter is higher than that of Sartorius® at pH values lower than 4. The pH measurements of the Z8F6401 system outside the pH 4 to 10 range may deviate significantly from commercial pH meters, but pH measurements outside this range are seldom performed in common laboratory applications. The error can be attributed to the extrapolation of data, since the pH of interest is no longer within the calibration curve. Statistical analysis, particularly the t-Test was used to determine if the two methods are comparable at 99% confidence level.[35] The t-Test is a useful tool in comparing two experimental means. Often, we need to judge whether a difference in the means of two sets of analyses, translate to a big difference between the two methods or whether the discrepancy is simply a consequence of random errors in the two sets.

T-

test, shown in equation 6 would be a big help to decide:

(6)

Here, N1 and N2 pertain to the number of runs for the first and second set of analyses respectively. Data from a series of similar samples accumulated over time can often be pooled to provide an estimate of the standard deviation that is superior to the value for any

79

individual subset. To obtain a pooled estimate of the standard deviation (spooled), we will employ Equation 7. Here, the deviations from the mean for each subset are squared; the squares for the subsets are then summed and divided by an appropriate number of degrees of freedom. Note that one degree of freedom is lost for each subset. Thus, the number of degrees of freedom for the pooled s is equal to the total number of measurements minus the number of subsets.

(7)

Applying t-test to the data shows that the pH measurements of the Z8F6401-based system is comparable to that of Sartorius® PB-20 for samples 1, 2, 3, 7, 8 and 9 but not for samples 4, 5, 6, 10 and 11. The value of spooled computed for each of the samples is presented in Table 11. The value of t at 99% confidence level for 4 degrees of freedom (3 runs + 3 runs – 2) is 4.60. [35] Table 12 shows us a summary of the results for the tTest. Note that if the difference between the means of the results for the two methods is less than or equal to the value of the second column, then the results for the two methods are not significantly different, if not then otherwise.

80

Table 11. Values of spooled at 99% confidence level for 4 degrees of freedom. Sample Code

spooled

1 2 3 4 5 6 7 8 9 10 11

0.016 0.016 0.018 0.018 0.012 0.014 0.020 0.017 0.015 0.021 0.0091

Table 12. T-test results for comparison of Sartorius® PB-20 and Z8F6401-based pH meter at 99% confidence level. Sample Code 1 2 3 4 5 6 7 8 9 10 11

|xmean, PB20-xmean, Z8|

tspooled(2/3) 

Inference

0.03 0.06 0.05 0.11 0.08 0.06 0.05 0.05 0.03 0.15 0.14

0.061 0.061 0.069 0.069 0.043 0.051 0.075 0.063 0.057 0.078 0.034

not significantly different not significantly different not significantly different significantly different significantly different significantly different not significantly different not significantly different not significantly different significantly different significantly different

1/2

The results of the t-Test for samples 4, 5, 10 and 11 for the two methods are expected to be “significantly different” since the pH of these samples are outside the 4.00 to 10.00 pH range, and is therefore, outside the calibration curve. Note that the difference between the means for the two methods becomes more accentuated as we go farther from the 4.00 to 10.00 range. On the other hand, the result for sample 6 is not expected but if we look closely, it almost passed the t-Test.

81

5.4 Accuracy, Precision and Limitations of Z8F6401 pH Measurement System The system fluctuates by as much as 0.04 pH unit in the pH determination of the same sample (for 3 trials). Note that the value of the pH is related to the value of the output of the ADC in hexadecimal.

A change of 1 pH unit translates to approximately

28-mV increase in the analog input (120-mV amplified, level-shifted analog signal). This makes 0.01 pH change equivalent to around 1.20-mV change in the amplified, levelshifted input.

Since the ADC output changes by one hexadecimal unit only after

changing the input voltage by approximately 4 mV, based on the ADC calibration, then there is an expected uncertainty inherent to pH measurements by 0.033 pH unit. This explains the 0.04 pH unit fluctuations, with additional contribution of other factors such as noise and small temperature changes, since the system has no temperature compensation capability. Note that pH is directly proportional to temperature. Thus, it is highly recommended that the pH measurements be performed in an air-conditioned room with almost constant temperature conditions. Moreover, the performance of the pH measurement system is largely affected by the glass electrode. It is noticed that the glass electrode deteriorates through time after frequent use.

82

5.5 A Laboratory Experiment: An Automated Strong Acid- Strong Base Titration Solutions of HCl and NaOH, each with an approximate concentration of 0.1 M are employed in the titration. The buret is filled up to the mark with the standardized NaOH (0.09984 M). Twenty-five (25.0) mL of HCl is transferred to a 500 mL beaker using a 25-mL pipet. The beaker is then filled with deionized water to increase the height of the solution, to give enough space for the glass electrode and the stirring bar—to avoid the latter colliding with the former. A stirring bar is placed in the beaker, which is then placed on top of a magnetic stirrer. A piece of silicone tubing is firmly attached to the opening of the buret with the pinch valve in the default “pinch” position. Initially, the user is prompted to present the strong acid sample to the glass electrode. The electrode is immersed into the middle part of the acid solution. Once ready, the user invokes the auto-titration command. The pinch valve will open and the strong base is delivered drop-wise to the acid sample, which is constantly mixed by the magnetic stirrer. Two drops of bromothymol blue indicator is added previously to this solution. The program is set so that the titration will stop once the pH of the solution is equal to or greater than the threshold pH value, 7.00—which is within the transition pH range of bromothymol blue indicator. As mentioned in the Methodology, this is implemented in the program via a feedback control loop which constantly checks the pH value of the solution and displays it through a PC using a serial communications program, at approximately 0.5 s intervals as the titration progresses. The 0.5s interval is standardized using the delay( ) subroutine.

As the set-point becomes nearer, at pH = 3.00, a hardware timer

synchronizes the opening and closing of the pinch valve by toggling PB1 on (logic high)

83

and off (logic low) at 0.455 s intervals. After the pinch valve tightens, enough titrant is delivered to reach the bromothymol blue endpoint. Underestimating or overshooting the endpoint by 1 to 2 drops is typical.

5.6 Limitations of the Auto-Titration System After the titration is performed, the user should manually obtain the volume reading from the buret. The system has no means of displaying the volume of titrant delivered because the flow rate of the titrant from the buret is not constant—decreasing as the volume delivered increases.

Consequently, it is very difficult to establish a

straightforward relationship between time and volume delivered. Alternatively, we can monitor the time of the delivery of titrant at 1mL intervals in the buret and establish a calibration curve for more precise volume delivery. Also, the pH, voltage equivalent of the solution, slope and y-intercept of the calibration curve employed can be displayed only using Hyperterminal®. There is no means of saving these data yet. Finally, only strong acid-strong base titration is tested. Other titrations (weak acid-strong base, strong acid-weak base and weak acid-weak base) have not yet been tried.

84

CHAPTER 6 CONCLUSIONS AND RECOMMENDATIONS Calibration of the Z8F6401 ADC showed a very linear response of the ADC to analog input from 0.1 V to voltage reference (3.31-V). Erratic output is confirmed between 40 and 45 mV even after noise minimization. Output is clearly zero below 40 mV analog input. There is a difference between these results and Zilog’s claim that “The output from the ADC can vary widely when the input signal drops below 20 mV”(see Appendix L) [36]. Moreover, a 4o increase in temperature has no significant effect on the linearity and slope of the response of the ADC. A low-cost and reliable pH measurement system was devised using a data acquisition platform based on the Zilog Encore!TM Z8F6401 microcontroller. The system is comparable to that of Sartorius® PB-20 pH meter for pH measurements within the 4.00 to 10.00 range using a glass electrode. The difference in the results between the two methods are not comparable outside pH 4.00 to 10.00 and becomes more marked as we deviate farther from the said range. This is verified using a statistical method called tTest at 99% confidence level. An automated strong acid- strong base titration system can also be coupled to the pH measurement system at a minimal cost. This is accomplished by monitoring the pH of the solution with a glass electrode while a titration is in progress. The volume of titrant delivered is found to be accurate based on the bromothymol blue indicator—the endpoint of which coincides with the closing of the pinch valve (near pH 7.00). Since the flow rate of the titrant from the buret is not constant and varies depending on the buret

85

used and the level of the titrant in the buret, there is no means of displaying the volume of titrant delivered, to Hyperterminal® . The user therefore, has to read the volume of titrant manually using the graduations of the buret. Other sensors can be fitted to the system to perform other tasks, to suit the needs of other common chemistry laboratory experiments—pressure, temperature, light intensity, etc.—using this data acquisition system. The system can be interfaced to a PDA or LCD readout and keypad for portable chemical instrumentation. Other features can also be added to the system, such as saving of calibration data and graphing of the titration curve (pH vs. volume of titrant delivered). Moreover, it is recommended that proportional control be employed in the titration system. That is, the volume of titrant delivered should be less as the set-point is approached. The code could be modified in such a way that the difference between the set-point and the current pH reading is monitored, and increase the delay associated with the hardware timer with respect to this difference. This can be a better implementation in order to target the equivalence point more accurately.

86

BIBLIOGRAPHY [1] http://www.zilog.com/docs/z8encore/ps0176.pdf, date accessed: December 27, 2005. [2] Instrumentation, Robotics and Control Laboratory. Encore PLCC Mini Board User’s Manual. Department of Electrical and Electronics Engineering. University of the Philippines-Diliman (2005). [3] http://www.zilog.com/docs/z8encore/um0128.pdf , date accessed: December 27, 2005. [4] http://scalepeople.com/government_products.asp?subcategoryID=132, date accessed: January 4, 2006. [5] http://www.vernier.com/probes/ph-bta.html date accessed: January 4, 2006. [6] http://www.zilog.com/docs/z8encore/pb0095.pdf, accessed December 27, 2005. [7] http://www.zilog.com/docs/z8encore/ps0176.pdf, date accessed: December 27, 2005. [8] http://www.zilog.com/docs/z8encore/um0128.pdf , date accessed: December 27, 2005. [9] Diefenderfer, A.J. and B.E. Holton, Principles of Electronic Instrumentation, 3/e. USA: Brooks-Cole, p. 349. (1994) [10] http://www.evaluationengineering.com/archive/articles/0500data.htm, date accessed: January 4, 2006. [11] http://www.maxim-ic.com/appnotes.cfm/appnote_number/1870, date accessed: November 10, 2005. [12] Jarman, David. A Brief Introduction to Sigma Delta Conversion. Intersil Application Note. pp.1-2 (1995) [13] Salido, A.J., E. Oclarit and L.G. Sison, Z8 Microcontroller-Based analog to Digital Conversion Techniques, Quezon City: University of the Philippines Diliman. (2002) [14] Hoeschele, David F. Analog-to-Digital and Digital-to-Analog Conversion Techniques 2/e, New York: John Wiley and Sons, pp. 30-35. (1999) [15] Sison L, Gueta, L. Charge-balancing ADC Z8 Program. (2003) [16] Johnson, D.E., J.R. Johnson and J.L. Hilburn . Electric Circuit Analysis, 2/e, New Jersey: Prentice Hall, 1992. [17] http://francis.courtois.free.fr/jc1/serial/Basics/BitFormat.html, date accessed: November 15, 2005. [18] Sison, Luis G., and Osmonn T. Burgos. Using ZDS II Encore. Workshop on Microcontrollers for Data Acquisition and Motor Control by Luis Sison. (September 10 and 17, 2005). [19] Skoog, D.A., et.al., Fundamentals of Analytical Chemistry. 8/e, Stanford: Brooks/Cole. p. 614 (2004). [20] ibid., 621-622. [21] Davidson W and C. Woof, Anal. Chem.1985, 57, 2567 [22] Skoog, D.A., et.al., p. 615. [23] ibid.., pp. 623-624. [24] Diefenderfer and Holton , pp.183-189. [25] Sartorius® PB-20 pH meter Operation Manual, 2001. [26] http://www.onu.edu/~jhurtig/2003webpages/chembuddy/final.html, date accessed: June 22, 2005. [27] http://www.national.com/JPN/ds/LF/LF353.pdf, date accessed, January 27, 2006. [28] http://pdfl.alldatasheet.com/datasheet-pdf/view/89095/NSC/LM340T-5.0.html, date accessed: March 2, 2006. [29] http://www.rosee-hulman.edu/~herniter/Data_Sheets/LM120.pdf, date accessed: March 2, 2006. [30] Horowitz, Paul and Winfield Hill, The Art of Electronics, 2/e. New York: Cambridge University Press, pp. 37-38. (1991). [31] http:.//www.winqcad.com, date accessed: February 11, 2006. [32] http://www.zilog.com/tools/software.asp, date accessed: December 9, 2005. [33] http://www.controlandpower.com/catalog/PDFs/ASCO/Scientific/ASCO%20scientific202004.pdf. date accessed: March 3, 2006. [34] http://www.onsemi.com/pub/collateral/MPS2222-D.pdf, date accessed: January 27, 2006. [35] Skoog, Douglas A., Donald West and James Holler. Fundamentals of Analytical Chemistry, 7/e, New York: Saunders College Publishing, p. 627-629. (1996) [36] Zilog document no UP004201-0105. Errata to Z8F640x, Z8F480x, Z8F320x, Z8F240x, Z8F160x Zilog Encore! Documentation (CD).

87

APPENDIX A: Bill of Materials Article Z8F6401 MAX232 CPE pH probe Other Electronic Parts (Miniboard) Serial Cables Single-sided PCB resistors 1N4001 8-pin IC socket LF353N 10 uF 25 V DC jack 1N914 1 uF 0.1 uF 25-to-9 pin converter 3.3 uF LM 320 LM 340 MPS2222A TOTAL Solenoid valve Total cost w/ solenoid valve

Unit Price ($)

74.00 (Vernier) See parts list and costing for Miniboard

Unit Price (PhP) 762.00 (Alexan) 120.00 (Deeco) 3922.00

Quantity 1 1 1

Amount (PhP) 762.00 120.00 3922.00 857.00

100.00 85.50

2 1

200.00 85.50

0.25 1.25 2.00 26.75 1.50 24.00 1.00 1.50 2.25 100.00

11 1 1 1 1 2 2 2 2 1

2.75 1.25 2.00 26.75 1.50 48.00 2.00 3.00 4.50 100.00

2.50 18.75 20.25 15.00

2 1 1 1

5.00 18.75 20.25 15.00 6197.25 5406.00 11603.25

88

APPENDIX B. ENCORE PLCC MINI BOARD Encore PLCC Mini Board is a module that utilizes the on-chip peripherals of the Z8F6401 Flash Microcontroller, like the eight-channel Analog-to-Digital Converter (ADC) and the Universal Asynchronous Receiver/Transmitter. The board is powered using a 9VDC adapter and uses pin headers to access the input/output pins of Z8F6401.

Figure 1. Encore PLCC Front Layout The Z8F6401 Flash Microcontroller is a Flash-capable microcontroller based on Zilog's new advanced eZ8 8-bit microprocessor core. The Flash in-circuit programming capability allows for faster development time and program changes in the field. Its rich peripheral set makes it suitable for a variety of applications including motor control, security systems, home appliances, personal electronic devices, and sensors. The following are the features of the microcontroller:  eZ8 CPU, 20 MHz operations  8 channel, 10 bit analog-to-digital converter  3-channel DMA  64KB Flash memory with in -circuit programming capability  4KB register RAM  serial communication protocols (SPI/ I2C)  two full-duplex 9-bit UARTs 89

   

    

24 interrupts with programmable priority three 16-bit timers with capture, compare and PWM capability simple-pin On-Chip Debugger two Infrared Date Association (IrDA)-compliant infrared encoder/decoders integrated with the UART Watch-Dog Timer with internal RC oscillator 31 I/O pins Voltage Brown-out Protection Power-On Reset 0°C to +70°C standard temperature and -40°C to +105°C extended temperature operating ranges

Specifications  8 channel analog input (direct unbuffered)  16-pin header input (sig-gnd pairs)  adjustable external voltage reference  PCB layout: single-sided  RS232 interface: PCB mounted DB-9  power  LED indicator  9V unregulated in (from adaptor)  5V, 3.3V on-board regulation  remaining digital lines on header

90

Circuit Figure 2 shows the schematic diagram for the on-board voltage regulation. LM7805 is used to output a +5V which is the voltage supply for the MAX232 and the input voltage of LM1117 and TL431. LM1117 provides the +3.3V supply for the Encore microcontroller and the TL431 is used for the external voltage reference that may be used for Analog to Digital Conversion. The configuration and the component values used for the circuits of LM7805 and LM1117 are taken from the Z8 Encore Development Kit User Manual. The pinheaders in Figure 2 are used to access the 5V, 3.3V and ground of the on-board voltage regulation, while LED1 is a 3.3V indicator. Figure 3 shows the schematic diagram for the MAX232 that is used as an RS-232 driver/receiver. MAX232 has two internal charge-pumps that convert the +5V input to +10V (unloaded) for RS-232 driver operation. The first converter uses capacitor C11 to double the +5V to +10 on C14 at the V+ output while C12 is used by the second converter to invert +10V to -10V on C13 at the V- output. Capacitors C15 and C16 are used as bypass capacitors. In Figure 3, the word “DEBUG” is written on pin 10 of MAX232. This means that the debug pin of Z8F6401 in Figure 4 is connected to the T2IN pin of max232 and to the anode of the 2N4148 diode. This schematic for the debug pin was taken from the product specification of Z8 Microcontrollers with Flash Memory and 10 bit A/D converter. It used MAX232, a 2N4148 diode and a female DB9, which is X3 in Figure 3, as the connector to the serial port. The Vref pin in Figure 4 is connected to a two pin header that is unconnected if the voltage reference used for the A/D converter is internal. For an external voltage reference, the two pin headers are connected by a jumper link. The schematic of the external Vref consists of TL431, which is an adjustable shunt regulator that can output from 2.5V to 36V. A closer look of the external Vref circuit is shown in Figure 5. R8 and R4 limits the output voltage of TL431from 2.5V t0 3.8V. The potentiometer R4 is used to adjust the external Vref for the ADC of Z8F6401. The clock circuit connected to the XIN and XOUT pin of Z8F6401 in Figure 4 was also taken from the product specification mentioned above. R2 in the schematic limits total power dissipation by the crystal. The remaining digital pins of Z8F6401 were made accessible through pin headers. The schematic diagram is shown in Figure 6.

91

APPENDIX C: LF353 Op Amp

92

APPENDIX D: C code for pH meter //pH meter.c

#include #include #include #include

#define CHANNEL 0x00 // ANA0 #define MODE #define VREF

0x00 // Singleshot (Continuous = 0x10) 0x20 // External voltage reference (Internal = 0x00)

#define ENABLE 0x80 // CEN #define RELOAD 65535

void Init_ADC (void) { init_uart(_UART1, _DEFFREQ, _DEFBAUD); select_port(_UART1); PBAF = 0x01; // PB0 = ANA0 ACTL = (CHANNEL | MODE | VREF); }

int PollADC (void) { ACTL |= ENABLE; //Enable ADC while (ACTL & ENABLE); //Wait end of conversion or ENABLE = 0 return ((ADHR6)); }

void InitPorts(void){ PDDD &= ~0x0C; PDHDE |= 0x0C; PDOC &= ~0x0C; PDAF &= ~0x0C; PCDD &= ~0x1A; //PC1 set as output

93

PCHDE |= 0x1A; //PC1 set as high drive PCOC &= ~0x1A; // all pins push-pull PCAF &= ~0x1A; // all pins normal function PBDD &= ~0x02; //PB1 set as output (~3.3V), the rest of the pins are input. PBHDE |= 0x02; //PB1 set as high drive (20 mA), the rest of the pins are low drive (2 mA). PBOC &= ~0x02; //all pins push-pull (1 for open drain) PBAF &= ~0x02; //initially all pins are using normal function. PDOUT |= 0x0C; PCOUT |= 0x18; // PC1 logic low //PBOUT |= 0x02; //PB1 set as high, the rest of the pins are low PBOUT |= 0x00; //all pins in B port are initially low }

void InitTimer1(void) { T1CTL &= ~0x80;

// Disable timer1

T1CTL = (0x07 > 8);

// T1 reload value

T1RL = (RELOAD & 0xFF); IRQ0ENH &= ~0x40;

// disable timer1 interrupt T1I

IRQ0ENL &= ~0x40; IRQ0 &= ~0x40;

// clear timer1 interrupt flag

T1CTL |= 0x80;

// Enable timer1

}

char select_buffer (void) { char b; printf ("**************************************************************\n"); printf ("*

Zilog pH Help Menu

printf ("* COMMANDS printf ("* (case sensitive)

*\n");

FUNCTION

*\n"); *\n");

printf ("*

f

pH 4.00 buffer for calibration

*\n");

printf ("*

s

pH 7.00 buffer for calibration

*\n");

printf ("*

t

pH 10.00 buffer for calibration

*\n");

printf ("*

z

clear buffers

*\n");

94

printf ("*

n

new sample

*\n");

printf ("*

d

deliver titrant up to equiv. point *\n");

printf ("**************************************************************\n"); b = getch(); return b; }

void delay(void) { unsigned int j; for (j=0; j 5.00) { InitTimer1(); PBOUT = 0x00; while (!(IRQ0 & 0x40)) ;

// wait for T1I

to go high IRQ0 &= ~0x40;

// clear T1I

PBOUT |= 0x02; while (!(IRQ0 & 0x40)) ;

// wait for T1I

to go high IRQ0 &= ~0x40;

// clear T1I

} printf ("The pH of the solution is %4.2f \n", pH); } while (pH < 7.00); //pH at equivalence point for strong acidstrong base titration. PBOUT = 0x00; //PB1 logic low, pinch valve in CLOSED position, no titrant delivered. PCOUT |= 0x18; //PC1 logic low. } }

else if (buffer=='n') counter=0; else printf("Invalid Command \n"); } if(buffer_f==0.0) a=0; if(buffer_s==0.0) b=0; if(buffer_t==0.0) c=0; printf("Value of a is %d\n", a); printf("Value of b is %d\n", b);

99

printf("Value of c is %d\n", c); check=a*b*c; printf("Check value is %d\n", check); if (check==0) { printf("Buffer input incomplete\n"); buffer_s=buffer_t=buffer_f=0.0; check=a=b=c=1; counter=3; } else { pH_range_menu(); if (getch()=='a') { slope = (buffer_s-buffer_f)/3.0; yint = (buffer_f-(slope*4.00)); display_result (buffer_s, buffer_f, buffer_t, slope, yint); printf("Present the sample then press r when ready \n"); while (getch()=='r') { pHVAL = PollADC(); volts = display_volts(pHVAL); pH = (volts - yint) / slope; printf ("The pH of the solution is %4.2f \n", pH); counter=3; }

} else if (getch()=='b') { slope = (buffer_t-buffer_s)/3.0; yint = (buffer_t-(slope*10.00)); display_result (buffer_s, buffer_f, buffer_t, slope, yint); printf("Present the sample then press r when ready \n"); while (getch()=='r') {

100

pHVAL = PollADC(); volts = display_volts(pHVAL); pH = (volts - yint) / slope; printf ("The pH of the solution is %4.2f \n", pH); counter=3; }

} else if (getch()=='c') { slope = ((3.0*((4.0*buffer_f) + (7.0*buffer_s) + (10.0*buffer_t))) (21.0*(buffer_f + buffer_s + buffer_t))) / 54.0; yint =((buffer_f + buffer_s + buffer_t) - (slope*21.0))/3.0; display_result (buffer_s, buffer_f, buffer_t, slope, yint); printf("Present the sample then press r when ready \n"); while (getch()=='r') { pHVAL = PollADC(); volts = display_volts(pHVAL); pH = (volts - yint) / slope; printf ("The pH of the solution is %4.2f \n", pH); counter=3; } } else { printf("Invalid input, press 'a', 'b' or 'c' only \n"); }

} } }

101

APPENDIX E: C code for ADC #include #include #include

#define CHANNEL 0x00 #define MODE #define VREF

0x00 0x20

// ANA0

// Singleshot (Continuous = 0x10) // External VRef (Internal = 0x00)

#define ENABLE 0x80

// CEN

void InitADC(void) { // set PC0 high to power the potentiometer ???

PBAF = 0x01;

// PB1 = ANA0

ACTL = (CHANNEL | MODE | VREF); } int PollADC(void) { ACTL |= ENABLE; while (ACTL & ENABLE);

// Enable ADC // Wait for End of Conversion

return ((ADHR > 6)); } void main(void) { int VALUE = 0; float volts = 0.0; init_uart(_UART1, _DEFFREQ, _DEFBAUD); select_port(_UART1); printf("Press 'a' to Display ADC Value\n"); InitADC(); while(getch()=='a') { VALUE = PollADC(); volts = VALUE / 512.0;

// Convert ADC Reading to Voltage

printf("ADC: %X, %4.3f volts \n",VALUE, volts); }}

102

APPENDIX F: ADC Calibration Increasing voltage scan, 28.5 degrees C ADC Output ADC Output YEW 2501A Output (HEX) (V) (V) 2 5 8 B E 11 14 17 33 52 71 90 AF B2 B6 CE EC 10C 12B 14A 178 1C7 1E5 213 241 260 27E 2AD 2FC 349 376 394 3B4 3C2 3D1 3E2 3F0

0.006 0.016 0.026 0.036 0.045 0.055 0.065 0.074 0.165 0.265 0.366 0.466 0.566 0.576 0.589 0.667 0.764 0.867 0.967 1.068 1.217 1.472 1.569 1.718 1.867 1.967 2.064 2.216 2.472 2.721 2.867 2.964 3.067 3.113 3.161 3.216 3.261

0.042093 0.0518060 0.062101 0.07016 0.082174 0.091825 0.1008480 0.1102040 0.2021500 0.3013800 0.4017500 0.5010200 0.6004000 0.6117400 0.6244000 0.7003200 0.7994200 0.9012100 1.0006800 1.0992300 1.2505000 1.5066000 1.6011000 1.7520000 1.9020000 2.0021000 2.1004000 2.2492000 2.5050000 2.7554000 2.9026000 3.0015000 3.1083000 3.1515000 3.2012000 3.2536000 3.2872000

ADC Output (DEC)

HP E2373A Output (V)

2 5 8 11 14 17 20 23 51 82 113 144 175 178 182 206 236 268 299 330 376 455 485 531 577 608 638 685 764 841 886 916 948 962 977 994 1008

0.0420 0.0517 0.0620 0.0701 0.0821 0.0918 0.1008 0.1105 0.2022 0.3015 0.4020 0.5010 0.6000 0.6120 0.6240 0.7000 0.8000 0.9010 1.0010 1.0990 1.2510 1.5070 1.6020 1.7530 1.9030 2.0030 2.1020 2.2510 2.5070 2.7580 2.9050 3.0040 3.1110 3.1550 3.2050 3.2600 3.2900

103