Open access

PH Control Using MATLAB

Written By

Mostefa Ghassoul

Submitted: 08 December 2011 Published: 26 September 2012

DOI: 10.5772/46454

From the Edited Volume

MATLAB - A Fundamental Tool for Scientific Computing and Engineering Applications - Volume 1

Edited by Vasilios N. Katsikis

Chapter metrics overview

8,858 Chapter Downloads

View Full Metrics

1. Introduction

Wastewater neutralization plays an important part in a wastewater treatment process. It provides the optimum environment for microorganism activity between pH 6.5 and 7.5{1}, and the right water discharge to the public sewage as mandated by the Department of Environment of between pH 5 and 9 (Environmental Quality Act, 1974) {2}. Wastewater of pH below 4.5 and above 9 may greatly reduce the activity of the microorganisms which treat the water and may not support their life at all {3}.

For a number of years, Hydrogen chloride (HCL) acid was used in wastewater treatment facilities to control alkalinity. It’s a product that works, but it also has many potential problems. HCL acid can be difficult to apply and control. Correcting the pH of alkaline wastewater is usually required either for discharge to sewer, in preparation to further biological, physical/chemical treatment or direct discharge to the environment. Strong acids such as hydrochloric acid have traditionally been used to neutralize alkaline waste streams prior to discharge {4}.

On the control side, It is well known that controlling pH is very difficult, and specially neutralization in industry, due to the high non linearity of the system. In fact the pH dynamics are not only time variant, but change with each pH value and becomes oscillatory around the 7 mark as well. Even by placing the pH probe in the proximity of a mixer or in a turbulent flow could result in a big change in the pH. It has been reported in literature that researchers have been trying for ages to control the pH with a tuned classical PID controller with many additional restrictions; but experience has shown that this is not satisfactory because of the changing of dynamics hence the transfer function where when the PID is tuned for a certain characteristics, it becomes completely un-tuned for the next. To overcome this problem, we (here at the chemical engineering department University of Bahrain) have engaged in finding a solution to the problem. One of the option possible is the use of fuzzy logic. For the last fifty years, since Zadeh {5} introduces his famous paper on fuzzy logic and control, fuzzy logic control has been widely implemented successfully in many industrial applications ranging from home appliances such as washing machines to heavy industries such as loading and unloading very heavy loads in ports efficiently by minimizing the action time. Certainly its use in controlling pH is feasible.This is due two reasons:

  1. The fuzzy control does not require any transfer function, nor any tedious mathematical analysis. So there is no need to model the system continuously, with each pH space, so the change of the pH characteristic does not influence the control strategy.

  2. The membership space of the pH is restricted between zero and fourteen where pH between zero and seven is acid and between seven and fourteen is base. This space is divided into a limited number of memberships, and the control for each membership could be easily tuned separately. To apply this strategy we had to look for the best possible solution. And luckily, we find the solution in MATLAB, through SIMULINK fuzzy control blocksets. The choice of SIMULINK fuzzy control blocksets was considered very carefully for several reasons.

  3. The huge number of rule one could implement. In fact, we have currently applied more than 125 rules and still the margin is open.

  4. The simplicity of MATLAB fuzzy control, where the SIMULINK blocksets could be used directly. This saves a lot of computing time. On top of that, those blocksets are already optimized.

  5. Though MATLAB was originally designed as a simulator platform, for the last few years, several companies have developed several interfacing cards to interface online different processes to the MATLAB platform, such as HUMUSOFT MF 624 multifunction I/O card and National Instrument card NI PCI-6221 data acquisition card. Hardware interface to the process in question, real time, where this has been done with a relative ease thank’s to National Instrument NI PCI- 6221 data acquisition card.

But before discussing how SIMULINK is used, we first have to highlight the pH apparatus used. Luckily, we found an obsolete pH control apparatus made by ARMFIELD UK (PC5 PH control RIG) which was made back in the early eightees, with the following components: framework assembly complete with pump set, two storage tanks, two flow meters, with a completely irreparable pH probe, pneumatically operated valve driven with a current to pressure converter, air filter regulator, glass vessel, clamps, stirrer together with obsolete three term PID electronic controller, slide indicator and chart recorder. The control was developed around a dedicated classical PID controller where the user only sets up the PID parameters through a number of knobs. The response is either given through slide indicator or chart recorder. (see figure (1)). This procedure was no use, where advanced control is not possible. So this controller was completely isolated and replaced by a modern SIMULINK based controller built for this purpose. The process is as follows. Two tanks are used ; one filled with an acidic liquid and the other with base liquid. The acidic liquid is controlled manually and the base liquid is controlled through a 3 to 15 PSI proportional control valve. The pressure is generated by controlling a pressure gauge through a current to pressure converter. Unfortunately, the output from MATLAB to the acquisition card is only in volts, whereas the valve driving signal is in milliamperes. This has lead to the design of a 0 - 5V voltage to 4-20mA current converter to drive the valve. The control voltage is generated by SIMULINK as a result of the control strategy developed around the fuzzy control blocksets. The control signal produced by the blockset is outputted through the NI card to the hardware. The beauty of this control is that the process could be monitored through MATLAB virtual instrument online.

1.1. PH control

PH is an important variable in production fields such as chemical and petrochemical industries where tons of toxic products are pumped into environment due to contaminated chemical waste. Most of those product wastes are mainly alkaline. This will certainly harms the environment in particular sea life as well as agricultural products which in turn reflects on the human life quality. So it is essential to treat those wastes to neutralize their pH to an acceptable level, ideally around 7. So what is pH. The PH of a solution is defined as the negative of the logarithm to the base of 10 of the hydrogen ion concentration.

PH= log 10 [H+]E1

Most of the factories waste is mainly alkaline; this certainly harms the environment by poisoning life onshore or offshore, including humans either through contaminated food and water or through breathing. This is witnessed by the increased rate of cancer cases in the world. So it is a must to neutralize the industry waste by neutralizing the pH. This is quantitavely done by bringing the pH to around the magic value of seven. In industry, the pH could vary between any value between 2 and 10. Here in our lab, we are using PC5 Armfield obsolete PH control apparatus. Its PI & D diagram is shown in figure(1).

The neutralization process basically follows the following reaction:


This reaction results in salt and water which do not present any harm to nature. (The process system is shown in figure(2)). The system basically consists of two liquid circuits; one feeding the acidic substance and the other feeds the base liquid. The added liquid is controlled by a proportional control valve whereas the base liquid is manually operated.

To make the mixture homogeneous, a variable speed mixer is used. The pH is picked up with the aid of a probe placed into the mixing vessel close to the outlet. Unlike the PID controller where many restrictions are imposed, fuzzy controller only requires the probe to be out off the flow turbulence way next the outlet. The probe reading is conditioned and fed to the controller through the NI PCI-6221 card of the E series, and at the same time, fed to the pH meter for confirmation. The card has 16 analogue input channels which could be connected as differential or single ended, sixteen bit resolution and two output analogue channels. The signal conditioning is no more than an instrumentation amplifier (figure(3)) of type INA114. This type of amplifier is very precise. The output of the amplifier is then fed to NI card, to be read into SIMULINK to be analyzed using the fuzzy controller. Once the signal has been treated, the resulting control variable is outputted through the output port of the NI card to drive the control valve. Unfortunately this output is in volts, whereas the driving signal required by the control valve is in milliamperes(current). This requires the design of a voltage to current converter. It should be mentioned here that the control valve used is of proportional type where it closes linearly from fully closed to fully open by using a current to pressure converter which converters a 4-20mA to 3-15PSI pressure. The Valve controls the acid flow rate of type HCL. So by varying the valve opening, the flow rate changes so does the pH. The base flow is manually controlled. The output of the pH sensor is fed to an instrumentation amplifier as mentioned earlier, to condition it, and at the same time to the NI6221 acquisition card, through which it is read into the SIMULINK fuzzy controller. The output of the controller is applied to the voltage to current converter, which in turn drives the current to pressure converter. This action adjusts the flow rate of the HCL, thus the input to the controller is the pH reading of the waist (NAOH) which is compared against the required set point. At the same time the output obtained from the controller is used to control the valve. (1- convert the output voltage to current. 2- convert the current to pressure which drives the valve) and the valve in turn controls the percentage the valve opening to control the HCL flow rate. This output tends to maintain the pH value of the waist (NAOH) to a target value.

Figure 1.

PI & D of the PH control system

Figure 2.

The PH control system

Figure 3.

Signal amplifier of type INA114


2. Data acquisition

The National Instrument Data Acquisition Toolbox™ provides functions for connecting MATLAB® to data acquisition hardware. The toolbox supports a variety of DAQ hardware.

With it, one could configure data acquisition hardware to read data into MATLAB or SIMULINK for immediate analysis. One can also send out data over analogue or digital output channels provided by data acquisition hardware. Depending on which card is used, one can configure several channels, as input or output, digital or analogue. The card is interfaced to the process through a screw type connectors SCB-68 Quick Reference Label. Figure(4) shows the real connector board.

Figure 4.

Interfacing connecting card to PCI 6221

Data Acquisition Toolbox lets you make a variety of measurements directly to MATLAB or SIMULINK, without the need to convert the data, so one can directly read the pH from the probe through the signal conditioning circuitry. In our case, only analogue input channel0 and output channel0 are used.

2.1. Voltage to current converter "V/I" circuit

A voltage to current converter is basically a circuit which delivers a constant current with a variable voltage. The voltage changes with the change of load. The circuit used here is the XTR105 from Texas Instruments, which converts the 0 to 5 volts to a 4 to 20 milliamperes through the setting of the gain resistor RG. This is the perfect signal to drive the control valve. RG, the gain resistor is given by:

Figure 5.

Voltage to current circuit


And the load current I0 is given by:


Where VIN is the input differential voltage in volts applied between pin 13 and pin2 and RG is the gain resistor in Ohms. It could be noticed that with no input voltage, the output current is 4mA. Transistor Q1 conducts the majority of the signal dependent4-20mA loop current. Using an external transistor isolates the majority of the power dissipation from the precision input and reference circuitry of the XTR105, maintaining excellent accuracy.

The output current of the XTR105 is directly fed to current to pressure converter (I/P) which in turn controls the opening and closing of the control valve.

2.2. Control valve

The valve is opened and closed according to controlling action according to the added desirable HCL solution. The calibration of the valve opening to the input current is shown in table(1); and Its behavior is shown in figure (6). It is clear that the relationship is linear.

Figure 6.

Output current in terms of input voltage

Figure 7.

Voltage to current conversion

2.3. Software

After discussing the hardware required and the calibration of the equipment, we devote the rest of this chapter to the software development. In this project we develop the pH control strategy using SIMULINK fuzzy controller and compare it with the PID controller using different currently available tuning techniques. But before going into that, let’s see first the behaviour of the pH.

2.3.1. PH behaviour

Before the fuzzy controller is discussed, a major problem inherent into the pH is highlighted. That is the severe non linearity inherent into the pH. Though the PH changes linearly from zero to two and from nine to fourteen, but unfortunately, it oscillates between two and nine. This is known as titration curve. This renders any linear control strategy inefficient, including the three term controller. This explains the complete deficiency of the PID controller, no matter how small is the gain chosen. (See figure (7)).

Figure (8) shows online titration curve. When reagent flow first starts, the pH only changes minimally. This results in a low process gain. But, as more reagent is added, the pH suddenly changes by a large amount, resulting in a high process gain. This titration curve shows the degree of difficulty of controlling the pH. So due to this high non linearity, it is extremely difficult to use any linear technique to control the pH. This has open the door to look at other alternatives, one of them is the use of fuzzy control as it was mentioned earlier.

Figure 8.

Titration curve obtained experimentally

Figure 9.

Titration curve test online

It is also worth mentioning here that the relationship between the output voltage and the pH is linear, where a cretin voltage corresponds to a cretin pH level. This is shown in figure (9). This curve has been obtained experimentally. It shows that the output voltage varies between -0.5V and 0.5V for full pH swing. The relationship is given by:

Y=0.0126X + 7.0119E5

Figure 10.

PH vs. Voltage


MATLAB is a high-performance language for technical computing where it integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. In Addition it has easy to use drivers to interface applications through standard interfacing cards such as NI- PCI 6221 card. On top of that the MATLAB SIMULINK platform incorporates a wide range of signal processing tools. This include easy to use fuzzy control block sets.

2.5. Configuration of acquisition card NI-PCI 6221 using SIMULINK

After MATLAB is installed, together with NI DAQmax drivers, the data acquisition card is configured. This is summarized as shown in the following slides. (Refer to figures from 10.a to 10.c).

Figure 11.

a: configure Parameters, b: configure input, c: configure output

2.5.1. PID control

The three term controller (Proportional-Integral-Deriavative) is well defined as:


Where e(t) is the error signal, which represents the difference between the desired value known a set point SP and the measured variable MV. So e(t) =SP –MV. Ti is the integral time constant, Td is the derivative time constant and K is the loop gain. So basically the role of this controller is to force the output to follow the input, as fast as the parameters permit, with an acceptable overshoot and without steady state error. This requires very careful choosing of the parameters (known as tuning) with a considerable gain without driving the system into non stability. The PID controller algorithm is used for the control of almost all loops in the process industries, and is also the basis for many advanced control algorithms and strategies. In order for control loops to work properly, the PID loop must be properly tuned. Standard methods for tuning loops and criteria for judging the loop tuning have been used for many years such as Ziegler, though new ones have been reported in recent literature to be used on modern digital control systems. PID tuning

  • When one wants to find the parameters of PID control he needs first the transfer function for his process. G. Shinskey and J. Gerry (6) have described the pH tuning technique after setting up a series of restrictions summarized as follows((figure(11)):

  • Let the pH signal stabilize in the manual mode

  • Decrease the controller output by about 10%

  • Wait about 15 seconds and increase the controller output by 20% of its original value.

  • Wait another 15 seconds and decrease the controller output by 10% of its original value.

  • Let the pH signal re-stabilize. Analysis software processes the data to optimal PID tuning variables. It could be clearly noticed that this method is near to an offline more than to online technique.

This results in the smallest upset due to the fact that the net change in the amount of reagent added is zero.

From figure(11), by reducing the control valve opening by 30% (step response), the pH response could be represented by a first order system plus a time delay model (FOPTD). The following could be noticed:

For this First Order Plus Time Delay (FOPTD) model, we note the following characteristics of its step response:

  1. The response attains 63.2% of its final response at time, t = τ+θ.

  2. The line drawn tangent to the response at maximum slope (t = θ) intersects the y/KM=1 line at (t = τ + θ).

  3. The step response is essentially complete at t=5τ. In other words, the settling time is ts=5τ.

Figure 12.

PH with small disturbance on the flow rate

Figure 13.

Graphical analysis of to pbtain parameters of FOPTD

From pervious steps the transfer function is:


In the next section, we discuss different tuning methods to determine the PID parameters. ITEA technique

Integral of the time –weighted absolute error (ITEA). ITEA criterion penalizes errors that persist for long period of time.

Figure 14.








PID equation is:

PID=0.1045(1+10.876s+0.267s)E13 IMC

More comprehensive method model design is the Integral Model Control (IMC).







PID equation is:


Figure 15.

IMC using SIMULINK test

Figure 16.

IMC online test Self tuning

The SIMULINK is used to tune the PID (refer to figure(16)). The following transfer function of the self tuning PID was obtained:


From figure (13-18), it could be easily noticed that neither technique, when applied to the real system, they have all produced unsatisfactory result. In fact, the best one is the self tuning, yet it has produced an oscillatory response. This has been reflected on the valve opening. (Refer to fig(18)). This is due to the fact that there are three gains. So any small change in the input results in a large change in the output. And this explains the behaviour of the titration curve. This has lead us to look for a non linear controller to control the system. This is the fuzzy logic control which is the subject of the next part.

Figure 17.

SIMULINK for Parameters

Figure 18.

Self turning using SIMULINK simulation

Figure 19.

Self tunung online test


3. Fuzzy logic control

3.1. Introduction

In any standard book on fuzzy control, fuzzy logic control is defined to be a practical alternative for a variety of challenging control applications since it provides a convenient method for constructing non-linear controllers via the use of heuristic information. Since heuristic information may come from an operator who has acted as “a human in the loop” controller for a process. In the fuzzy control design methodology, a set of rules on how to control the process is written down and then it is incorporated into a fuzzy controller that emulates the decision making process of the human. In other cases, the heuristic information may come from a control engineer who has performed extensive mathematical modelling, analysis and development of control algorithms for a particular process. The ultimate objective of using fuzzy control is to provide a user-friendly formalism for representing and implementing the ideas we have about how to achieve high performance control. Apart from being a heavily used technology these days, fuzzy logic control is simple, effective and efficient. In this section, the structure, working and design of a fuzzy controller is discussed in detail through an in-depth analysis of the development and functioning of a fuzzy logic pH controller.

The general block diagram of a fuzzy controller is shown in figure (19). The controller is composed of four elements:

  • A Rule Base

  • An Inference Mechanism

  • A Fuzzification Interface

  • A Defuzzification Interface

Figure 20.

Fuzzy Controller


This is a set of “If ……..then…..” rules which contains a fuzzy logic quantification of the expert’s linguistic description of how to achieve good control.


This emulates the expert’s decision making in interpreting and applying knowledge about how best to control the plant.


This converts controller inputs into information that the inference mechanism can easily use to activate and apply rules.


It converts controller inputs into information that the inference mechanism converts into actual inputs for the process.


It should be made sure that the controller will have the proper information available to be able to make good decisions and have proper control inputs to be able to steer the system in the directions needed to be able to achieve high-performance operation.

The fuzzy controller is to be designed to automate how a human expert who is successful at this task would control the system. Such a fuzzy controller can be successfully developed using high-level languages like C, Fortran, etc. Packages like MATLAB® also support Fuzzy Logic.

Fuzzy Sets and Membership Function

Given a linguistic variable Ui with a linguistic value Aij and membership function μ Aij(Ui) that maps Ui to [0,1], a ‘fuzzy set is defined as

Aij= {(Ui, μ Aij (Ui)); Ui ε υi}E20

The above written concept can be clearly understood by going through the following example. Suppose we assign Ui=“PH” and linguistic value A11=“base”, then A11 is a fuzzy set whose membership function describes the degree of certainty that the numeric value of the temperature, Ui ε υi, possesses the property characterized by A11. This is made even clearer by the fig (20).

Figure 21.

Membership Function

In the above example, the membership function chosen is of triangular form. There are many other membership functions like Gaussian, Trapezoidal, Sharp peak, Skewed etc. Depending on the application and choice of the designer, one could choose the shape which suits his application. Figure(21) shows just few.

Figure 22.

Triangular, 2)Trapezoidal, 3)Skewed triangular, 4)Sharp peak

In the project in hand, the fuzzy controller has two inputs, the first one is the signal from the pH transmitter and the other one is the set point. The controller has a single output which goes through saturation, Quantizer and Weighted moving average. The saturation limiter is used to protect against over range of control valve and the Quantizer and Weighted moving average are used to hold the control valve(figure (22)).

Figure 23.

SIMULINK block diagram of the PH controller

A detailed description of the design and functioning of the fuzzy controller is given in the following section. The different sections in the fuzzy controller used in this PH controller are:

  • Fuzzification Section

  • Rule Base

  • Inference Mechanism

  • Defuzzification Section

3.2. Fuzzification section

The variables pH, set point and percentage of opening are selected for Fuzzification. In this section, the action performed is obtaining a value of the input variable and finding the numerical values of the membership function defined for that variable. As a result of Fuzzification, the situation currently sensed (input) is converted into such a form that, it can be used by the inference mechanism to trigger the rules in the rule base.

After fuzzification, the fuzzy sets obtained are labelled using the following term set, T={LAD, MAD, SAD, SP, SAL, MAL, LAL, FULLY CLOSED, 3Q, M, Q, FULLY OPEN, #N0, }

3.2.1. Input 1

  • S.acid = large acidic

  • M.acid = medium acidic

  • L.acid = small acidic

  • natural = set point PH

  • L.alk = law alkaline

  • M.alk = medium alkaline

  • S.alk = strong alkaline

3.2.2. Input 2

  • #N0(1-14 PH) = SETPOINT

3.2.3. Output

  • Fullyopen = 100% opening

  • 3Q = 75% opening

  • M = 50% opening

  • Q = 25% opening

  • Fullyclose =0% opening

The membership functions of input variables PH and output variable percentage opening shown in figures 23, 24 and 25 respectively. μi is the membership function of output. In the current work the triangular membership is chosen.

Figure 24.

membership Function of input of PH

Figure 25.

Membership Function of set point (input2)

Figure 26.

Membership Function of output pH

As a result of Fuzzification, we get the names of fuzzy sets to which the input belongs and to what extent they belong to these sets, their membership functions.

3.3. Rule base

Rule base stores the different rules that are to be fired or used according to the inputs. These rules are either gathered from experienced human operator or from careful study of existing PH systems. The base represents the control strategy employed in the PH control.

Figure 27.

Fuzzy rule

The rules used have been designed based on the expertise. Those rules are carefully chosen to make the system as accurate as possible. They have been entered through the MATLAB editor. After rigoreous testing and trial, near optimum rules have been obtained. Table above gives the set of fuzzy action rules related to the application in hand.

3.4. Inference mechanism

The inference mechanism employed in pH control is based on individual rule firing. In this scheme, contribution of each rule is evaluated and overall decision is derived.

During inference process, each rule that is fired by a crisp value of pH is summed up after giving the weightages decided by the fuzzification unit. This weightage is called degree of satisfaction (DoS). DoS is decided by the fuzzification module.

In the inference mechanism, depending on which all fuzzy sets the input belongs to, the corresponding rules are fired. This describes the functioning of the three out of four blocks in the fuzzy controller. Now comes the defuzzification section.

Figure 28.

3.5. Defuzzification

This section performs the task of converting the output of inference mechanism, the rules that are fired, and the DoS given by the fuzzification module into a signal to the control valve. For this, it uses “height defuzzification” which is computationally simple and fast.


4. Discussion and conclusions

Finally, let’s conclude this chapter by discussing a real online example where it is required to bring the pH from 3 to 7. This example was chosen to show how the fuzzy controller has successfully solved oscillation due to titration curve mentioned earlier. Using all the expertise to set the membership functions as well as the rules, plus a fine tuning process, the membership function is shown in figure (27), and the pH response is shown in figure (28). It is clear that the pH has been brought from 3 to 7 in a very smooth manner. This value has been confirmed through the pH meter reading.

As a general conclusion, due to non linearity inherent in the chemical waist, the study presented here has shown that using fuzzy logic control is probably best suited to control the pH of industrial waist, despite the expertise required to fine tune the controller as well as the time required. It has also been shown that no matter how the linear controllers are tuned especially PID, including the many restrictions, plus the delays and settling time for each disturbance, their action was not satisfactory. Finally, the study has also shown that implementing the fuzzy control technique, by careful selection of memberships and setting the right rules, it is possible to bring any waist pH to neutrality smoothly in an acceptable time, regardless if the waist is strong base nature or strong acidic or not.

Figure 29.

First membership function

Figure 30.

First test online at set point 7


  1. 1.
  2. 2.
  3. 3.
  4. 4.
  5. 5. ZadehL.Fuzzysets.InformationControl. .1965
  6. 6.
  7. 7.
  8. 8.
  9. 9. SalehiS.ShahrokhiM.AndNejati. M. “.Adaptive nonlinear control of pH neutralization process using fuzzy approximators”Control Engineering Practice20091329 EOF1337 EOF
  10. 10. DuanS.ShiP.FengH.UanD.AndZ.MaoZ. “.An on-line Adaptive Control Based on DO/pH measurements and ANN Pattern Recognition Model For Fed-Batch CultivationBiochemical Engineering Journal30200620068886

Written By

Mostefa Ghassoul

Submitted: 08 December 2011 Published: 26 September 2012