PID vs Fuzzy Control

28
Temperature control based on traditional PID versus fuzzy controllers Industrial temperature-control applications demand speed and precision. Improved temperature controllers can meet these demands by adding features not found in traditional PID controllers but increase system complexity. Fuzzy temperature controllers give you another option. By Peter Galan, Control Software Designer, Nortel Networks Common perception holds that temperature control is a mature and largely static area of technology. Some industrial applications—for example, injection-molding proc- esses—still desire not only precise temperature control but also a faster warm-up phase and a quicker response to disturbances with minimal overshoot and undershoot when the set point changes. Traditional PID (proportional-integral-derivative) control tech- niques cannot meet these extra challenges. Figure 1 shows a continuous-time (analog) PID controller, typical for most closed- loop control systems. Its output, the actuating value y(t), is a function of the regulation error e(t): ( ( ( ( = dt t de K dt t e K t e K t y D I P . The use of a standard PID controller is fully adequate for some applications. Such applications commonly feature low to moderate control-quality (timing, precision) con- straints and well-defined and stable dynamic system behavior. Precision industrial- temperature control, however, does not belong among these standard applications. For example, injection-molding processes require fast changing—readjusting of controlled temperatures with minimal overshoot. In addition, heating processes do not exhibit sta- ble dynamic behavior, because heating and cooling rates are different at each tempera- ture set point. In addition, coupling between the zones of a multizone heating system makes dynamic behavior very unpredictable. Heat-transfer-specific problems Figure 2's simplified thermal model of a typical heating system ignores heat- transport delays. Assume that when you switch on a constant power source, W, it pow- ers an electrical heating element with a heat capacity, C e . The temperature of the heat- ing element, T e (t), rises with time, t. The heat continuously propagates, by direct con- duction, to the heated system. R es represents a thermal resistance between the electrical element and the heated system, and C s represents the heated system’s thermal capac- ity. The system temperature, T s (t), also rises with time. R sa thus represents a thermal re- sistance between the heated system and surrounding environment (with ambient tem- perature T a (t)), which tends to cool the system. Ideally, without any cooling from the out- side (that is, R sa 5‘), both temperatures, T e (t) and T s (t), would rise forever. In practice, however, natural cooling prevents this occurrence. So, after a certain time period, both temperatures stabilize at certain constant values. Figure 2's model represents a second-order system with the following transfer func- tion:

Transcript of PID vs Fuzzy Control

Page 1: PID vs Fuzzy Control

Temperature control based on traditional PID versusfuzzy controllersIndustrial temperature-control applications demand speed andprecision. Improved temperature controllers can meet these demandsby adding features not found in traditional PID controllers but increasesystem complexity. Fuzzy temperature controllers give you anotheroption.

By Peter Galan, Control Software Designer, Nortel Networks

Common perception holds that temperature control is a mature and largely staticarea of technology. Some industrial applications—for example, injection-molding proc-esses—still desire not only precise temperature control but also a faster warm-up phaseand a quicker response to disturbances with minimal overshoot and undershoot whenthe set point changes. Traditional PID (proportional-integral-derivative) control tech-niques cannot meet these extra challenges.

Figure 1 shows a continuous-time (analog) PID controller, typical for most closed-loop control systems. Its output, the actuating value y(t), is a function of the regulationerror e(t):

( ) ( ) ( ) ( )∫ ++=

dttde

KdtteKteKty DIP .

The use of a standard PID controller is fully adequate for some applications. Suchapplications commonly feature low to moderate control-quality (timing, precision) con-straints and well-defined and stable dynamic system behavior. Precision industrial-temperature control, however, does not belong among these standard applications. Forexample, injection-molding processes require fast changing—readjusting of controlledtemperatures with minimal overshoot. In addition, heating processes do not exhibit sta-ble dynamic behavior, because heating and cooling rates are different at each tempera-ture set point. In addition, coupling between the zones of a multizone heating systemmakes dynamic behavior very unpredictable.

Heat-transfer-specific problemsFigure 2's simplified thermal model of a typical heating system ignores heat-

transport delays. Assume that when you switch on a constant power source, W, it pow-ers an electrical heating element with a heat capacity, Ce. The temperature of the heat-ing element, Te(t), rises with time, t. The heat continuously propagates, by direct con-duction, to the heated system. Res represents a thermal resistance between the electricalelement and the heated system, and Cs represents the heated system’s thermal capac-ity. The system temperature, Ts(t), also rises with time. Rsa thus represents a thermal re-sistance between the heated system and surrounding environment (with ambient tem-perature Ta(t)), which tends to cool the system. Ideally, without any cooling from the out-side (that is, Rsa5`), both temperatures, Te(t) and Ts(t), would rise forever. In practice,however, natural cooling prevents this occurrence. So, after a certain time period, bothtemperatures stabilize at certain constant values.

Figure 2's model represents a second-order system with the following transfer func-tion:

Page 2: PID vs Fuzzy Control

( )2

211 TssTK

sGp ++= .

The PID controller would be an ideal controller, because its transfer function with twonulls could, at least theoretically, cancel both poles of Gp.

Figure 2 demonstrates that two cascaded first-order systems can replace this sec-ond-order system. Therefore, in practice, system response to a step function will alwaysbe aperiodical, and if Res is relatively small, the output temperature will follow a simpleexponential curve when rising or falling. For such systems, even PI controllers (withoutthe derivative member) are fully adequate.

An interesting feature of a typical heated system, which represents the first difficultyfor any temperature controller, is that increasing the temperature a couple of degreesfrom the surrounding temperature takes substantially less time than does cooling downto the surrounding temperature. In contrast, increasing the temperature of the samesystem by a couple of degrees when it is close to its maximum temperature takes sub-stantially longer than does bringing the temperature back down by a couple of degrees.

At one temperature set point, the heating rate (the speed of heating up) and thecooling rate (the speed of cooling down) are equal. This set point is at the temperaturethat requires the application of exactly 50% of the maximum applicable power to theheater. What is that “balanced” temperature? Theoretically, from Figure 2's thermalmodel, the dependence between power (W) and temperature (Ts) should be linear. Thatis, the stabilized temperature corresponding to 50% of maximum power should be ex-actly in the middle between the minimum and maximum temperature. The assumptionhere is that the maximum reachable temperature requires 100% power, and the mini-mum (ambient) temperature requires you to apply 0% power to the heating element foran unlimited time.

Figure 3 shows the above-described feature for three set points: One is close to theambient temperature, one is at the balanced temperature, and one is close to the maxi-mum temperature. Temperatures are rising and decreasing exponentially with differentrates (time constants) for heating and cooling. The ratio of the rate of heating and cool-ing processes at any stage depends only on the value of the set point.

Enhancing the traditional PID controllerThe PID constants basically depend on the gain and time constant of the controlled

system. If you select them properly, they will cancel poles of the controlled system-transfer function. Different rates of the heating and cooling processes affect the optimalvalues of the PID constants, making their estimation very difficult. If you want to useautotuning, be aware that all autotuning methods provide only one set of PID constants,which will at best suit only the set points close to the balanced temperature.

A different situation exists when the temperature set point is different from the bal-anced temperature. The farther the set point is from the balanced temperature, the far-ther the PID constants will be from their optimal values. Just how far depends on how farthe set point is from the balanced temperature and whether the current temperature isbelow or above the set point.

To make the PID controller suitable for temperature control at any set point, youneed some automatic adaptation of the PID constants. Generally, all three PID con-stants, PK , IK , and DK , are inversely proportional to the rate of temperature change.Autotuning algorithms (known in control theory as the Ziegler-Nichols rules) also adhereto this rule. The rate of temperature change is not a linear function of the temperatureset point (the derivative of exponential is also exponential), but a straight line is a rea-

Page 3: PID vs Fuzzy Control

sonable approximation (Figure 4).

As Figure 4 shows, the rate (speed) of heating at the balanced temperature is 1/2τ,

where τ is a time constant of the exponential (shown previously in Figure 3). At the am-

bient temperature, 1/τ is the rate of heating. The rate of cooling at the ambient tem-perature is infinitesimally low. The opposite situation exists at the other end of the expo-nential curve, close to the maximum temperature. Here, the rate of heating is infinitesi-mally low, and the rate of cooling is very high.

To compensate for varying heating and cooling rates, the PID constants, PK , IK ,

and DK , must also vary, requiring modification of the basic PID controller. Figure 5shows the addition of two new blocks: an adapter and a heater model.

The heater model must at first determine a value of the balanced temperature. Formost applications, applying 50% of the maximum output power to the heating elementand waiting until the temperature settles down is infeasible. Therefore, the control sys-tem can first assume that the balanced temperature equals one half of the maximumtemperature (a value for which the controller has been designed). You can determine amore precise value of the balanced temperature during the control process.

The adapter block (knowing the balanced and set-point temperatures) then calcu-lates two correction coefficients for the modification of the PID constants. This calcula-tion is based on a linear dependence of the temperature-change rate as shown in Fig-ure 4. You apply the first correction coefficient, kh, (it multiplies the PID constants) duringthe heating and the other coefficient, kc, during cooling:

kh5TMAX/2(TMAX2TSP), [1]and

kc5TMAX/2TSP, [2]where TMAX is the maximum controllable and TSP is the set point temperature.

Introducing a feedforward memberOnce you have created the heater model (which is actually an inverse static char-

acteristic of the heating process), you can use its output variable power level as a feed-forward contribution to the actuating variable. Because the heating process is linear (theoutput temperature is proportional to the applied power), a simple line with the slope km

can approximate the heating model characteristic. You can then calculate an initial valueof km as:

km5MAX_POWER / MAX_TEMPERATURE.You can express the MAX_POWER value in the percentage of the output pulse

width if you use the PWM method to drive the heater elements. If you knew in advancewhat power value you’d need for the set-point temperature, you could immediately re-place the contribution of the controller's integral member with the output of the feedfor-ward member. However, at the beginning of the control process, you would not have thecorrect heater model (the correct km value). Fortunately, the integral member can providethis information to the adapter block.

So, this approach provides the adapter block with a new task. Once the temperaturestabilizes at the set-point value, the adapter block can easily calculate the required out-put power to maintain this temperature. It is a sum of the integral member and the feed-forward member outputs. Because the temperature is stabilized at the set point, theregulation error is zero, and the contributions of the proportional and derivative membersare zeros. The last step required from the adapter is to recalculate the slope km of thepower-temperature characteristic, so that the feedforward member will generate the

Page 4: PID vs Fuzzy Control

overall required output power by itself. At the same time, you must clear the content ofthe integral member to retain the current actuating variable unchanged.

Now the heater model knows the precise, necessary power value to maintain theset-point temperature; when you change the set point, the feedforward member can pre-dict and more precisely provide the required output power. It also more precisely deter-mines the balanced temperature.

Modifying the PID controller can substantially improve its control performance, es-pecially in maintaining the temperature set point. However, do not expect any miraclesduring the warm-up phase, which should bring the heated system from the ambient tem-perature to the temperature set point as quickly as possible. This phase can last a longtime (minutes or even hours), and the integral member will likely be the first one to causethe problems. During such a long warm-up period, the integrator-accumulated regulationerror will very likely hit its maximum. Therefore, you must take measures to prevent the“wind-up” of the integral member. The accumulated value of the integral member(clamped to its maximum) will continue to drive the heaters with very high power, evenafter the current temperature reaches the set point. The result will be a huge overshootusually followed by a series of temperature oscillations. Addressing this problem re-quires the introduction of some nonlinearity.

Introducing nonlinearityWith the introduction of nonlinearity, the entire range of temperature control splits

into three basic ranges with a different control mechanism acting in each one. In the firstrange, which starts at the ambient temperature and ends somewhere below the setpoint, the controller will drive on the heater elements with the full power. The PID com-pensation is disabled, and the content of the integral member stays at a zero value. Inthe middle range, the temperature controller applies the PID compensation, including thePID constants adaptation and the feedforward contribution as it is shown in Figure 5.You can call this range the LCZ (linear control zone). The range ends up somewhereabove the set-point value. The third range represents the cooling process when you ap-ply a zero power to the heating elements. Here, again, the PID compensation is dis-abled, and the integral member content is frozen. For simplicity, call the entire three-range control process an LCZ method.

From control theory, you may remember a time-optimal control or “bang-bang”control. You can describe this control as follows: The controller initially applies maximumactuating value (power) to the heating elements. If the controlled variable (temperature)and its derivative reach the so-called switching curve (in a phase diagram), the heatingprocess ends, and the cooling process starts. In unforced cooling, the power applied tothe heating element drops to 0%. In an optimally calculated switching curve, the systemeventually reaches the set-point temperature without any overshoot. At that moment, theheating element receives only the power necessary to maintain the set-point tempera-ture. The bang-bang control method yields the fastest possible system response. Itsounds simple, but applying it is not easy.

The LCZ method is an approximation of the bang-bang control, It is simple to apply,and it provides results that are almost as good as those that the bang-bang control pro-vides. The LCZ approach offers two essential differences from the bang-bang approach:First, to avoid overshoot, the LCZ band must begin at a lower temperature than wouldcorrespond to the switching curve, because a nonzero power will be applied to theheater inside the LCZ band (Figure 6). Second, because the PID control inside the LCZband takes care of reaching and maintaining the set-point temperature, precise definitionof the LCZ band is unnecessary.

Page 5: PID vs Fuzzy Control

At the beginning, the system is stable at an initial temperature (previous set-pointvalue) with the applied initial power, point 1 (Figure 6). The setting of a new set point re-sults in the application of full power to the heater (points 1 to 2), because the currenttemperature is below the beginning of LCZ. The temperature rises during application ofthe full power (points 2 to 3). When the temperature reaches the beginning of LCZ (point3), the PID compensator takes over (points 3 to 4), and the power level jumps below100%. Line P in the figure shows the contribution of the PID compensator's proportionalmember; the curve I is the contribution of the integral member. The figure omits a contri-bution of the derivative member for clarity. The actual PID output depends upon the val-ues of the PID constants and may have various shapes—such as, the bold dotted curve,C.

In an optimally tuned system, Figure 6's diagram would follow the straight bold fullline until it reached the set-point temperature and power (point 5). In real systems, how-ever, the trajectory usually follows the dotted spiral, which shows oscillation (overshootsand undershoots) around the set point. The integral member causes these oscillations.Unfortunately, the system still needs the integral member, because there is no guaran-tee that the feedforward member will provide the precise output power required for thetemperature set point. At least the integral constant, IK , can be significantly smallerthan in a PID compensation working without the feedforward member. The derivativemember contribution (not shown in Figure 6’s diagram) can help dramatically reduce theovershoot and temperature oscillations.

The implementation of an additional nonlinearity and the REL (regulation error limit)can further reduce these overshoots. The regulation error limit clamps the otherwisevarying value of the regulation error to a small constant value throughout almost the en-tire LCZ. Only when the current temperature is very close to the set-point value will theclamping fail to affect the regulation error. The regulation error clamping creates theequivalent of a tracking-control system, which tracks a moving set-point value. Becausethe set-point value is only marginally ahead of the actual temperature, even rather highvalues of the PID constants cause little danger of large overshoots.

Final design of the temperature controllerNow the temperature controller has all the possible improvements. It dynamically

adapts the PID constants according to the value of the temperature set point; it approxi-mates the optimal (bang-bang) control method using the LCZ and REL nonlinearities;and it uses a learning feedforward member capable of predicting and generating thepower output required to maintain any set-point temperature. Figure 7 shows a finalblock diagram of the enhanced PID temperature controller.

Implementation of autotuningAutotuning, referred to earlier, is useful for providing initial PID constants for a con-

trol system. Manually tuning a PID controller is a painful process, as anyone who hastried it well knows. Following a recommended tuning procedure is helpful, but using abuilt-in autotuning procedure is even more helpful.

Two widely used tuning methods for heating processes, with slight modifications,can provide reasonable initial values for not only PID coefficients but also the additionalcontrol blocks implemented in Figure 7's enhanced controller.

Relay-feedback methodThe first autotuning method is derived from the relay-feedback method for identifica-

Page 6: PID vs Fuzzy Control

tion of the dynamic behavior of a controlled process. This method applies a sequence ofpower pulses (Figure 8) to the heater, which is running in open loop. The series ofpulses forces the process variable (temperature) to oscillate around the set-point value.The set-point value acts as a switching temperature; whenever the actual temperaturecrosses it, the output (actuating value) changes from 0 to 100%, or vice versa. At theend of process, the measured values of t0, t1, t2, Tmin, Tmax, Tpeak go into calculating all thePID parameters, which include KP, KI, KD, PWMPeriod, REL, LCZ and the heater modelcharacteristic, km.

Step-response methodThe second autotuning method, called the step-response method, comes from the

step response of an open-loop system (Figure 9). At the end of the step-responseautotuning process, the measured values of t0, Tmin, ∆t, ∆T, tmax, Tmax, and Tpeak go intocalculating the same set of PID constants that the relay-feedback method calculates(except the km value).

Which autotuning method is better? Both get wide use, so each method must havecertain pros and cons. Generally, the relay-feedback method should provide more reli-able results, because it more thoroughly “exercises” the tuned system. In addition, it canfind the gain of the system, which initially helps to set up the heater model (the feedfor-ward block). On the other hand, relay-feedback autotuning is unusable in multiple-zonesystems, such as an injection-molding-machine barrel, which typically has eight heatingzones, one beside the other. The zones affect each other to such an extent that tem-perature oscillations become completely distorted. In this type of situation, only the step-response method can provide usable results.

Fuzzy logic—another approach to temperature controlEngineers have known the principles of fuzzy logic for more than 35 years. Fuzzy

logic acquired its name from the Fuzzy Set Theory developed by LA Zadeh at the Uni-versity of California—Berkeley in 1965. Practical applications started to appear later,when the world market became flooded with inexpensive microcontrollers. Fuzzy control(fuzzy logic in the role of a control system) becomes attractive, especially for the small-est microcontrollers, because it requires less computational power and demands lessoperational memory than conventional, PID compensation. Fuzzy-control applicationsare especially prevalent among consumer products such as digital cameras. However,nothing could prevent you from applying fuzzy control to industrial temperature control.

Imagine that you have to manually control the temperature of an electric oven. Yourcontrol element is only one knob, which turns in one direction to increase power and inthe opposite direction to decrease power to the heating element. Clearly, you also needto know the current value of the controlled temperature. So, you add a thermometer withan analog display to continuously measure the temperature inside the oven. Let’s saythat you are going to bring the temperature of the oven from the ambient temperature to200°C. Your task is not only to maintain the set-point value but to reach this value asquickly as possible and with minimum oscillations. How will you proceed?

From the very beginning, when the current temperature is far from the set-pointvalue, you will first try to apply full power to the heating element. The temperature willstart to rise. From the beginning, it will be rising slowly, but after a while, you will noticethat the rate of the temperature change is increasing. Will you keep the full power untilthe temperature reaches the set-point value (200°C)? Very unlikely. As the temperatureapproaches the set-point value, you will intuitively reduce the applied power to somelower level. When the temperature is even closer the set-point value, you will further re-

Page 7: PID vs Fuzzy Control

duce the power, and maybe switch it off completely.Your first attempt to manually control temperature will probably be a disaster. But

when you try it again and again, you will acquire a better sense of when and how to ma-nipulate the power level. As the input information, you will use not only the difference(deviation) of the current temperature from the set point but also the speed (rate) of thetemperature change.

Figure 10 represents a state diagram showing how the temperature deviation fromthe set-point value (a regulation error, err) and the rate of the temperature change (a de-rivative of the regulation error, derr) might change during your first attempt to control theoven temperature. FP, HP, LP, and ZP are the approximate power levels you apply tothe heating element. A dotted curve in Figure 10 represents the switching curve wellknown from the bang-bang control. If you knew the trajectory of this switching curve, youwould at first apply full power to the heating element until the trajectory of the rising tem-perature crossed the switching curve. At that moment, you would turn off the power. Thetrajectory of the regulation error and its derivative would then follow the switching curveto the set point. When it reached the set point (center of the state diagram), you wouldapply some “reasonable” power level, which would maintain the set-point value.

Terms such as “far away” and “too close” to the set point and “high” and “low powerlevel” are measures or states that fuzzy logic uses. Consider one approach to usingfuzzy logic in a role of the temperature controller.

Designing a fuzzy controllerIn reality, any implementation of fuzzy logic or fuzzy control is based on classical

numerical processing. So, the hardware design of a fuzzy temperature controller can bebased on any suitable microprocessor (microcontroller). Much more important is thesoftware design, which generally comprises three steps: fuzzification, applying the fuzzyrules, and defuzzification. Fuzzification aims to convert a single (crisp) input value intocorresponding fuzzy-set values. Applying the fuzzy rules, or second step, entails proc-essing the “fuzzy” information. The third step, defuzzification, converts the internal fuzzyresults back to a crisp output value.

In the case of a temperature controller, the input variables are the variables thatFigure 10’s state diagram uses: the regulation error, err, and its derivative, derr. Youmust calculate these two input variables on basis of the known set-point value and theperiodically measured controlled temperature. Their difference will yield the regulationerror, and the difference between two consecutive measured temperatures (or regulationerrors) will yield the derivative of the regulation error. Let’s say that you measure bothinput variables in degrees Celsius and their range is ±500 units (degrees).

The purpose of the first step, fuzzification, is to convert a crisp input value to corre-sponding fuzzy-set values. This step requires creation of the “membership” functions.The membership functions divide the entire range (±500) of the input variables into a fewsubranges represented by the fuzzy states. For example, Table 1 shows how you candefine the following five (partially overlapping) subranges and their corresponding fuzzystates.

Having defined five fuzzy states, you must define five membership functions. Themost widely used are the “lambda-type” functions, which will appear as shown in Figure11. Each membership function reaches a maximum value, MAXV, at the input valuestated above in Table 1’s second column (in bold). This maximum value can be anyvalue that is not too high and still allows a good resolution (for example, 1000). Further,you can notice that for any input value, two membership functions overlap (they havenonzero values), except at the peaks of the membership functions. At these input values

Page 8: PID vs Fuzzy Control

(2500, 2250, 0, 250 and 500), only a single membership function acquires a nonzerovalue, which is its maximum.

Before you start writing even the first fuzzy control procedure, it is always reason-able to start with data representation, variable definitions, and declarations. If you aredesigning the fuzzy controller in C, you can conveniently define the following enum type,which will be an essential definition throughout the entire process:

typedef enum { /* Input value quantificator */ LargeNegDev, MedNegDev, SmallDev, MedPosDev, LargePosDev} InputQt;

InputQt is a quantificator providing names of the fuzzy states of the input values,which are divided into five subranges. You might also find useful the following defini-tions, which are suitable for representing the membership functions:

#define MAXV 1000#define RANGE 1001#define MEMB 5

typedef struct _MFset { int Point[MEMB]; int Funct[MEMB];} MFset;

The MFset structure represents one fuzzified variable. Its first item, Point[], is an ar-ray of MEMB (5) integer values, which show at which input values the membership func-tions acquire their maximum values. As described above, these five values can be2500, 2250, 0, 250, and 500. As you will see later, this not the only possible division ofthe input range.

The second item, Funct[MEMB], is an array of MEMB (5) “weighting” coefficients,which the fuzzification procedure will periodically calculate each time the input variable ismeasured. (The following section explains fuzzification.) The two fuzzified input vari-ables, errFv and derFv, are defined as of the MFset type. You can connect their defini-tion with the initialization of the Point[] arrays:

MFset errFv5{-500, -200, 0, 200, 500};MFset derFv5{-325, -250, 0, 250, 375};

As you can see, the Point[] arrays are initialized with values other than 2500, 2250,0, 250, and 500. (The last section of this article, Relationship between control surfaceand control process, describes why.) The input variables themselves (a current regula-tion error and its derivative) are declared as simple integer variables:

int err, derr;

Now you have to deal with the definitions of the output variables of the fuzzy con-troller. The proposed fuzzy controller uses two output variables, which will later combineinto one output (actuating) variable. At the least, such an approach will simplify the entiredesign process. The first output variable is similar to the output of the feedforward mem-ber (see the section, Introducing a feedforward member). This variable, FFOut, will

Page 9: PID vs Fuzzy Control

keep the constant output power required to maintain the temperature set point once thecontrol process has stabilized. The other variable is the actual output of the fuzzy con-troller, corrOut. Its purpose is to correct the FFOut value during the warm-up phase. Inaddition, corrOut is responsible for eliminating the stabilized temperature variation due topossible disturbances.

Once the crisp input values are fuzzified, the fuzzy controller processes the fuzzyinput variables to produce the fuzzy output variable, corrVal. You can represent thisvalue with a similar set of MEMB (5) membership functions with the following states:

typedef enum{ /* Output variable quantificator */ FullNegOut, MedNegOut, SmallOut, MedPosOut, FullPosOut} CorrQt;

The next is a definition of the fuzzy output variable, CorrVal, including its initializa-tion. You use the values 2MAXV, 2MAXV/2, 0, MAXV/2 and MAXV (21000, 2500, 0,500, and 1000) for the mapping of the fuzzy output variable to the crisp output variable:

int CorrVal[MEMB] = {-MAXV, -MAXV/2, 0, MAXV/2, MAXV};

To access the individual (MEMB) values of the fuzzy output variable, use the above-defined quantificator, CorrQt.

Output of the feedforward member, FFOut, and the “crisp” correction output vari-able, corrOut, are defined as simple integer variables:

int FFOut, corrOut; /* Output of Feed-Forward & Correction blocks */

Now, that you have defined all the major data structures and variables, you cancontinue your design with the “fuzzy” procedures.

FuzzificationFuzzification aims to convert crisp input values into corresponding fuzzy set values.

As you already know, this process uses the set of membership functions. If you hadsuch a set (as shown in Figure 11) in the form of look-up tables, fuzzification would bevery simple. You would apply the input value as the offset to a look-up table and pick upa corresponding value of each membership function. Having the set of membershipfunctions ready for use in the form of look-up tables would mean sacrificing RANGE(1001) words (integers) for each of MEMB (5) arrays, representing the set. This is a lotof memory. A better approach is to generate the set of the membership functions duringthe fuzzification process itself. Actually, you need to generate only one value for each ofthe membership functions, which correspond to the current input value. These five gen-erated values are the weighting coefficients determining how strongly the input value istied to the individual membership function. This is the entire purpose of the fuzzification.

You can verify whether the fuzzification and the membership-function generation arecorrect by looking at the fuzzified variable. Table 2 shows a few selected values of theinput variable, err, and the corresponding values of errFv.Funct[MEMB] variable (forclarity, shown as Funct[x] values). The sum of weighting coefficients for any input valueis always a constant of MAXV (1000), and a maximum of two membership functions canacquire nonzero values.

Implementation of the fuzzification procedure is left to you. First, find out to whichinterval (given by the values of Point[MEMB])the input value belongs. For example, an

Page 10: PID vs Fuzzy Control

input value of 125 lies in the interval between Point[2] and Point[3]. It is immediatelyclear that only the membership function[2] and the membership function[3] will havenonzero values in this interval; all the other membership functions will have zero values.In this interval, membership function[2] has the falling edge and membership function[3]has the rising edge. Using a simple linear interpolation, you can calculate exact values ofboth functions.

Applying fuzzy rulesOnce the current values of the input variables are fuzzified, the fuzzy controller con-

tinues with the phase of “making decisions,” or deciding what actions to take to bring thetemperature to its set-point value. The criteria for this action are minimum time andminimum temperature oscillation. This process lies under the supervision of the “fuzzyrules,” therefore, it is usually called “applying the fuzzy rules.” These rules are the typicalproduction rules “, if…then ….” used in expert systems. In this case, the fuzzy ruleswill have a specific form, such as, “if err is LargePosDev and derr is MedNegDev thenset MedPosOut.”

The “if” statement evaluates the sets of the fuzzified input variables, and only if allfuzzified input variables contain nonzero weighting coefficients does the fuzzified outputvariable acquire a prescribed output level. Because there are two input variables, andeach one is decomposed into five states, 25 combinations of input states exist. There-fore, you need 25 fuzzy rules. Creating them requires the designer to have adequate“knowledge” of the control-system behavior. This knowledge is identical to the knowl-edge necessary for manual temperature control. It is based on rational feelings ratherthan on the knowledge of the time constants, gains, and other physical attributes of thecontrolled system. The fuzzy rules represent the “knowledge base” of the fuzzy controlsystem, though the fuzzification and defuzzification steps are also integral parts of thisknowledge base.

Figure 12 shows a graphical representation of a knowledge base (the fuzzy rules)suitable for the controlling of a generic heating system. FNO, MNO, SO, MPO, and FPOare the short forms of the output variable quantificator, CorrQt.

Starting from the top left corner of Figure 12 through the underlined MPO field andending at the bottom right corner, the fuzzy rules (written in a pseudo-code) are:

if err is LargeNegDev and derr is LargePosDev then set FullNegOut;if err is MedNegDev and derr is LargePosDev then set FullNegOut;if err is SmallDev and derr is LargePosDev then set FullNegOut;if err is MedPosDev and derr is LargePosDev then set MedNegOut;if err is LargePosDev and derr is LargePosDev then set SmallOut;…if err is MedPosDev and derr is ZeroDev then set MedPosOut; …if err is LargePosDev and derr is LargeNegDev then set FullPosOut.

Figures 12 and 10 are very similar. They both describe how the regulation error andits derivative depend on the output power applied to the heating elements, and viceversa. Actually, you are interested in the dependence of the output power on the regula-tion error and its derivative, because they are the input (independent) variables to thecontrol system; the output power is the dependent variable.

If the output power could acquire only one of those five levels shown in Figure 12,the control process would be very coarse. To maintain the set-point temperature, the

Page 11: PID vs Fuzzy Control

output power would have been very likely changing its levels according a following se-quence: … → MNO → SO → MPO → SO → MNO → … forever.

In addition, the fuzzy rules themselves as they are listed above, would yield am-biguous results. Either of the two fuzzified input variables will be in most cases decom-posed into two input levels (though with different weighting coefficients), so conditions ofas many as four fuzzy rules will be fulfilled at the same time. (Be aware: In the set offuzzy rules, none of the “if” statements are followed by “else” statements.) Which levelthen will be assigned to the output variable? The output level produced by each fulfilledfuzzy rule should contribute to the actuating variable. The entire process of calculatingthis multilevel contribution and converting it into a single (crisp) value is called defuzzifi-cation.

DefuzzificationDefuzzification is the opposite of fuzzification. It aims to convert a value (actually

several values) of the fuzzy output variable to a single crisp value. There are many waysto perform defuzzification, just as there are many ways to perform fuzzification. The mostcommon method is called “Min-Max” method, which selects only the maximum or mini-mum values from each fuzzy rule for further processing. Procedurally, the most conven-ient way to implement defuzzification using this method is to combine it with fuzzy rulesprocessing.

For fuzzy rules (“if” statements) comprising two or more conditions “ANDed” to-gether, you select a minimal weighting coefficient (a fuzzified input variable with theminimal value) as a combined truth value for further processing. In a fuzzy rule compris-ing two or more conditions “ORed” together, you select a maximum weighting coefficientfor further processing. These rules are consistent with the theory of sets. In this controlapplication, you use only ANDed conditions, but different applications may use ORedconditions as well. For example, if in Figure 12 an entire raw (column) used the sameoutput level, conditions would be ORed, and you would select maximum weighting coef-ficient for further processing.

The following C-code explains how the weighting coefficients and output levels areprocessed in one fuzzy rule evaluation (in Figure 12 with underlined MPO):

if(errFv.Funct[MedPosDev] && derFv.Funct[SmallDev]){

minVal = min(errFv.Funct[MedPosDev], derFv.Funct[SmallDev]); num += minVal * CorrVal[MedPosOut]; denom += minVal;}

If the expression of the “if” statement yields the truth value (both ANDed weightingcoefficients are nonzero), the minimum value of the weighting coefficients of both fuzzi-fied input variables is assigned to an auxiliary variable minVal. The minVal value isadded to the variable denom (denominator), and after multiplication with the mappingvalue corresponding to the produced output level, CorrVal[MedPosOut], the product isadded to another variable, num (numerator). You repeat these actions for each true “if”statement—in this case, for as many as four out of 25 statements. The num and denomvariables must be cleared before they enter fuzzy rules processing. After the whole setof fuzzy rules is processed, the ratio num/denom will yield a crisp value of the outputvariable, which is assigned to the corrOut variable.

You describe this process as “singleton” defuzzification. It is a simplified “centroid”

Page 12: PID vs Fuzzy Control

method, which got its name because it resembles the calculation of the center of themass of a complex object. The simplification ignores the fact that any two adjacent (out-put) membership functions overlap. The error caused by this simplification is negligibleas is shown in the following example (Figure 13). Say that the fuzzy rule processingyields two truth rules (“if” statements)—one with the minimal coefficient value of 250 andthe MedPosOut output power level and the other with the minimal coefficient value of500 and the FullPosOut output power level. Calculations based on the “centroid” methodwould find the center of the mass at the distance of 828. The “singleton” defuzzificationwould yield a value of 2833 (for clarity, negative power levels were used).

Figure 14 shows a 3-D graph of the defuzzified (crisp) output variable corrOut. Itscontent (vertical axis) changes from the MAXV value to the 2MAXV value as the inputvariables, err and derr, change from the extreme values of 500 and 2500 to the otherextreme values 2500 and 500, respectively.

The surface of the defuzzified output variable is often called the “control surface,”because it determines the value of the controlled (actuating) variable for any given inputvalues. In this case, the surface represents a nice, linear cut through a cube, led almostsymmetrically from one corner to the other. You would expect this situation, because theprocess has used for the fuzzification a set of linear and equally spaced membershipfunctions (Figure 11). The fuzzy rules exhibit no “irregularities” (Figure 12) but yieldconstant output levels diagonally placed from the lowest to the highest. The linearly ar-ranged numbers govern the mapping of the fuzzy to crisp output variable.

The shape of the control surface is extremely important. The quality of the controlprocess entirely depends on it. However, the actuating variable is a combination of thecorrOut value with a constant value, FFOut, which is an output of the feedforward mem-ber. If the value of FFOut provides the output power, which does not correspond to thetemperature set point, the temperature will settle down at a value other than the setpoint. You must correct for this deviation.

Correction of the feedforward outputSimilar to the PID control, the feedforward output is an output of the heater model

block, which is an inverse static characteristic of the heating process. The heating proc-ess is linear (the output temperature is proportional to the applied power), so a simpleline with the slope km represents the heating-model characteristic. As previously de-scribed, the initial value of km can be:

km = MAX_POWER / MAX_TEMPERATURE.(If MAX_TEMPERATURE is not at least a couple of hundreds degrees, you should sub-tract from it the ambient temperature.) The MAX_POWER value in this case should beMAXV, which represents 100% of the output pulse width, if you use the PWM method todrive the heater elements.

The feedforward output value for a particular set point temperature will be:FFOut = km * SET_POINT_TEMPERATURE.

In this case, the MAX_TEMPERATURE value is 5008C and the MAX_POWER valueis 1000. Now, if a desired set point temperature is, for example, 2008C, the FFOut valuerequired to maintain this set point value will be 400 (40% PWM). This actuating valuemight be suitable in an ideal situation when using a properly sized heater. In practice,you might prefer an oversized heater, which requires less power to maintain the sametemperature. This option is especially important when the set-point value is in the highend of the temperature range. You would not want to wait hours for the temperature toreach the set point value. In certain applications, you may encounter the opposite situa-tion, in which the heating elements are undersized. In any case, the probability that the

Page 13: PID vs Fuzzy Control

FFOut value will maintain exactly the set point temperature without any additional cor-rections is extremely low.

When FFOut is higher than is needed, the temperature will stabilize somewhereabove the set-point value. A steady nonzero (in this case, negative) regulation error willcause the corrOut value to become negative, which will reduce the overall power ap-plied to the heating element. Finally, the temperature will stabilize somewhere betweenthe set point value and the temperature corresponding to the FFOut value.

You can eliminate this control error by either adding an integral member identicalwith what the PID correction uses, or implementing the following “adaptation” routine:

if(abs(derr) < SOME_SMALL_NUMBER){

km = (FFOut + corrOut)/(currentTemperature – ambientTemperature);FFOut = km * setPoint;

}

If the current temperature settles down, the derivative of the regulation error will beclose to zero. The current temperature is maintained by the output power from the com-bined contribution of the FFOut and corrOut values. So, the calculation of a correctedcharacteristic, km, is very simple. You take the combined output power and divide it bythe current temperature decreased by the ambient temperature; km is actually a ratio of∆P/∆T, where ∆P is a difference between the powers applied to the heating element atthe current and at the ambient temperatures, ∆T. Of course, at the ambient (surround-ing) temperature, there was no power applied to the heating element. After modifying theheater-model characteristic, do not forget to calculate a new feedforward output value.And, you can go a step further in this adaptation process. If your controller can remem-ber the latest value of km, it can use it from the very beginning of the next control proc-ess.

However, this routine has one fault. The derivative of the regulation error can ac-quire a zero value even though the current temperature is far from the stabilized value.Figure 10 shows that this situation will occur every time the spiral crosses the horizontalline, even at the very beginning of the control process, when the current temperatureequals the ambient temperature. The calculation would fail even here, because of the di-vision by zero. So, you need to provide some additional mechanisms to prevent prema-ture km modifications.

Relationship between control surface and control processThe ideal (bang-bang) control surface would have only two levels: a maximum out-

put and a minimum output level. In the center of the state diagram (when both, err andderr acquire zero values), the FFOut value should be applied to the heating element tohold the desired temperature. The transition from one level to the other would be abruptand be led along the switching curve. It sounds simple in theory. The problem is deter-mining the trajectory of the switching curve. For a second-order controlled system, youcan approximate the switching curve by a parabolic curve (second-order polynomial). Ifyou do not know precisely parameters of the curve, you’ll never get to the target (thecenter of the state diagram). Therefore, you need to allow the traditional control systemto apply linear controlling in a certain band around the set-point value. PID control usesthe LCZ for exactly this reason.

The control surface in Figure 14 resembles the LCZ used in the PID control, butthey are not identical. They would be identical if the layers of the constant power were

Page 14: PID vs Fuzzy Control

laid in parallel with the vertical axis. However, they are laid under 45%, so they moreclosely follow the switching curve. The LCZ method approximates the switching curve(represented by a second-order polynomial) with a zero-order polynomial; the controlsurface from Figure 14 approximates it by a first-order polynomial, making a better ap-proximation. You can take this approximation even further, if, for the fuzzification, youuse membership functions with a nonequidistant distribution of membership functions asshown in Figure 15.

The slope of the switching curve, of course, plays a role in the controlling. If you donot know this slope (the precise parameters of the polynomial that approximates it),system-response time will be less than optimal.

You can try to modify the slope of the switching curve by further changing the divid-ing points for the membership-function distribution, but you have limited possibilities. Asimpler way is to modify the scaling of the input variables. For example, multiplying thederr variable by a constant greater than 1 will have the same effect as pressing theswitching curve toward the horizontal line. Actually, you need to multiply derr by a con-stant of 10 or even higher, because you will never get the derr values as high as 5008Cunless the sampling rate is extremely low. The rate of the temperature sampling must bereasonable, neither too high nor too low. The high sampling rate will bring a lot of noiseto the system, and the low sampling rate can cause the temperature oscillations. In ei-ther case, you should scale both input variables so that only their extreme values (themaximum regulation error and maximum change of the regulation error) would be repre-sented by values close to 500.

You do have other “freedom” degrees left in your fuzzy controller. One variable, hasso far been untouched: the fuzzy output variable, CorrVal[MEMB], which has been ini-tialized with the values 21000, 2500, 0, 500, and 1000 for the mapping of the fuzzyoutput variable to the crisp output variable. These linearly growing values cause the ver-tical cut diagonally from the bottom left corner to the top right corner through the cube inFigure 14 (a power “profile”) to be linear. Exceptions are the corners, where the power isclamped to its maximum and minimum levels, respectively. You would not want to mod-ify the extreme values 61000 and the value of 0 in the middle of the mapping function,but you can play with the values 6500. Figure 16 shows how changing those valuesaffects the power profile.

Remember that the power profiles B and C represent an extreme “distortion” of themapping function. You would get the same result if you replaced the MPO and MNOstates (in the diagonals) in Figure 12’s knowledge database with the SO and FNO (pro-file B) or the FPO and SO (profile C) states. However, by changing the mapping func-tion, you can obtain any power profile between the extreme profiles B and C, becauseyou can replace the original mapping-point values 6500 with any value from 0 to ±1000.

How can be “tweaking” the mapping function useful? Do you remember how differ-ent rates of the heating and cooling processes affected required values of the PID con-stants? The same principle applies to the power profile. The power profile A in Figure 16is suitable for the set points close to the balanced temperature. Heating and cooling ef-fects are in this area equivalent. A modified power profile approaching the B shape bestsuits the set points close to the ambient temperature. It generates only a moderate posi-tive output power for the positive regulation errors (when the current temperature is bel-low the set point value), but its negative output power changes much more dramaticallywith the changing negative regulation error (when the current temperature is above theset-point value). For the set points close to the maximum temperature, a power profileclose to C is the best choice, providing exactly the opposite heating and cooling effectsof profile B.

Page 15: PID vs Fuzzy Control

Similarly, as the PID controlling has been “enhanced” by introducing an adapterblock for the modifications of the PID constants, you can use the same idea to automati-cally modify the power profile of the fuzzy controller by modifying those distributionpoints. Your system must compare the set-point value with the balanced temperature,and a simple linear equation (Figure 4 and equations 1 and 2) can calculate the newdistribution points for the optimized power profile.

Even such a simple process as temperature control can become complex if youwant additional features, such as a fast warm-up phase. Implementing the enhanced,traditional PID controller can be a challenge, especially if you want to have autotuningcapabilities. However, the theory of PID controlling is very well known and widely used inmany other control applications. If you are a traditionalist, it might be your preferredchoice of control method.

On the other side, lesser known fuzzy control seems to accomplish the same controlquality with less complexity. Better approximation of the switching curve makes it a bet-ter candidate for time-optimal applications for temperature control. As a relatively newcontrol method, it still provides space for further improvements. If you are an innovator,you will prefer fuzzy control as a modern, elegant control method.

You can contact author Peter Galan at [email protected].

Table 1—Subranges and their corresponding fuzzy states2` 2500 2250 Large negative deviation

2500 2250 0 Medium negative deviation2250 0 1250 Small deviation

0 1250 1500 Medium positive deviation1250 1500 1` Large positive deviation

Table 2—Selected values of the input variable, err, and the corresponding valuesof errFv.Funct[MEMB] variableErr Funct[0] Funct[1] Funct[2] Funct[3] Funct[4]2500 1000 0 0 0 02499 996 4 0 0 02375 500 500 0 0 00 0 0 1000 0 0125 0 0 500 500 0490 0 0 0 40 960

Page 16: PID vs Fuzzy Control

Figure 1—A PID controller calculates an actuating value from proportional, inte-gral, and derivative components.

Figure 2—A simple heating-system model has thermal resistances and capaci-tances.

SET POINT+

-

e(t)

KDd/dt

KI ∫

KP

ACTUALVALUE

+

ACTUATINGVALUE

Res

Ce CsW

Te Ts

Ta

Rsa

Page 17: PID vs Fuzzy Control

Figure 3—Heating rates and cooling rates vary with temperature.

Figure 4—The rate of temperature change is not linear, but a straight line is a rea-sonable approximation.

MAXIMALAMBIENT BALANCED

1/τ

1/2τ

COOLING RATE

HEATING RATE

TEMPERATURECHANGE RATE

TEMPERATURE

MAXIMUM REACHABLE TEMPERATURE

AMBIENT TEMPERATURE

TEMP (T)

TIME (t)

BALANCED TEMPERATURE

HEATING

COOLING

τ

Page 18: PID vs Fuzzy Control

Figure 5—The addition of a heater model and an adapter to a PID controller pro-vides adaptive modification of PID constants and feed-forward output.

.

Set Point+

-

e

D

I

P

HEATERMODEL

ADAPTER

+ACTUATING VALUE

ACTUAL TEMPERATURE

Page 19: PID vs Fuzzy Control

Figure 6—A nonlinear control process with the LCZ (linear control zone), as seenin this diagram, approximates the bang-bang control.

100%

0%

PI

C

2 3

1

4

5

POWER (%)

SET-POINTPOWER

INITIAL (AMBIENT)TEMPERATURE

BEGINNINGOF LCZ

SET-POINTTEMPERATURE

POWER-TEMPERATURECHARACTERISTIC

INITIALPOWER

TEMPERATURE

Page 20: PID vs Fuzzy Control

Figure 7—An enhanced temperature controller incorporates PID control, adaptivePID constants, approximation of bang-bang control, and a learning feedforward mem-ber capable of predicting and generating required output power.

Set Point+

-

e

D

I

P

HEATERMODEL

ADAPTER

+ACTUATING VALUE

ACTUAL TEMPERATURE

+ REL

- REL

Linear ControlZone

Hold &Full

Power

Page 21: PID vs Fuzzy Control

Figure 8—The relay-feedback method creates power pulses that cause a processvariable (such as temperature) to oscillate around a set-point value.

Tmax

Tmin

t0 t1 t2

100% PWM

0% PWM

Set PointTemperature

Tpeak

time (t)

Page 22: PID vs Fuzzy Control

Figure 9—Step-response autotuning derives from the step-response of an open-loop system.

T [°C]

Tmax

t0

∆T

tL tmax ∆t time

Set Point Tem-perature

Tpeak

Tmin

Page 23: PID vs Fuzzy Control

Figure 10—A state diagram shows how the regulation error, err, and its derivative,derr, change upon applying different power levels.

err

derr

FP

HPLPZPZP

ZP

LP LP

LP

LPZP

ZP

LP

FP … Full PowerHP … High PowerLP … Low PowerZP … Zero Power

Switching curve

Page 24: PID vs Fuzzy Control

Figure 11—The fuzzification of the input variables uses a set of five membershipfunctions.

1000

0-500 -250 0 250 500

5-th membership function 4-th membership function 3-rd membership function 2-nd membership function1-st membership function

Page 25: PID vs Fuzzy Control

Figure 12—This graphical representation of the Fuzzy Control knowledge base issuitable for the controlling of a generic heating system.

0

-250

500-500 -250

500

250

0

250

-500

SO

SO

SO

SO

SO

MPO

MPO

MPO

MPO

FPO

FPO FPO

FPO

FPO

FPO

FNOFNOFNO

FNO

FNO

MNO

MNO

FNO

MNO

MNO

LargeNegDev MedNegDev SmallDev MedPosDev LargePosDev

err

-derr

Page 26: PID vs Fuzzy Control

Figure 13—Difference between the “centroid” and much simpler “singleton” defuz-zification is negligible.

Figure 14—A three-dimensional schematic represents the defuzzified outputvariable.

500

0 500

828

x

1000-500-1000

-833

x

SOMNOFNO MPO FPO

(SINGLETON) (CENTROID)

250

+err

-err

+derr -derr

+corrOut

-corrOut

POWER PROFILE LINE

Page 27: PID vs Fuzzy Control

Figure 15—Membership functions with a nonequidistant distribution, used for thefuzzification of the input variables, help to approximate the switching curve.

0

-250

500-500 -200

375

250

0

200

-375

err

-derr

Page 28: PID vs Fuzzy Control

Figure 16—The power “profile” depends on the mapping function of the fuzzy out-put variable to the crisp output variable.

A +corrOut

-corrOut

+1000

+500

0

-500

-1000

-err, +derr +err, -derr

(FullNegOut)

(MedPosOut)

(SmallOut)

(MedNegOut)

(FullPosOut)

B+1000

0

0

-1000

-1000

-err, +derr +err, -derr

+corrOut

-corrOut(FullNegOut)

(MedPosOut)

(SmallOut)

(MedNegOut)

(FullPosOut)

C+1000

+1000

0

0

-1000

-err, +derr +err, -derr

+corrOut

-corrOut(FullNegOut)

(MedPosOut)

(SmallOut)

(MedNegOut)

(FullPosOut)