by Jim Sibigtroth
Motorola Microcontroller Technologies Group
Austin, Texas
his paper uses
a graphical approach to introduce fuzzy logic concepts. While fuzzy logic
is useful for a very broad range of applications, this paper concentrates
on embedded control applications using software in a microcontroller to
implement fuzzy inference algorithms. The fuzzy inference process splits
nicely into three parts called fuzzification, rule evaluation, and defuzzification.
A small general purpose fuzzy kernel
program is used to demonstrate how each of the three processes can
be implemented on an 8-bit microcontroller.
Several textbooks are now available to provide a theoretical mathematical basis for fuzzy logic. This paper attempts to build a common sense understanding of the subject to form a better basis for practical application of this new technology. As we will see, fuzzy logic uses plain language rules and knowledge directly from the application expert rather than forcing the expert to translate knowledge into a computer programming language.
n traditional
MCU based control systems, we represent inputs as precise numeric values
such as 32 RPM or an A-to-D value of $3F. We do this because that is the
kind of data we get from electronic sensors and the kind of values digital
processors use in the course of executing programs. But when people make
control decisions they use messy linguistic terms like "FAST"
and "WARM". In some traditional control systems we might assign
a name like WARM to a range of values from a temperature sensor. This helps
a little because we can now write a program that behaves in a certain way
when the temperature input is within this range of values. In mathematics
this range of values would be called a set.
In traditional Aristotelian logic, a set has sharp boundaries. In fuzzy
logic we would call this a "crisp" set. Each possible value of
the input variable either is or is not a member of the set. Fuzzy logic
gives us a more powerful way to classify data. An input value can have
a degree of membership in a fuzzy set that varies continuously from zero
(not a member) to one (absolutely a member). Where the Aristotelian set
required only the endpoints of a range to define the set, fuzzy logic requires
a describing function called a membership function to fully define the
boundaries of a fuzzy set. The fuzzy set becomes a way of assigning exact
mathematical meaning to a subjective sounding linguistic term such as WARM.
Figure 1 shows a membership function for the fuzzy set named WARM. The
x-axis shows all possible values of the input variable (temperature in
this case). The y-axis represents degree of membership (the degree to which
you would say the statement "TEMPERATURE is WARM" is true). On
the y-axis, zero represents false and one represents true. As the input
variable temperature changes from 56 to 72 , the linguistic term WARM changes
from being true (y=1) to being false (y=0). At 68 "TEMPERATURE is
WARM" is true to a degree of 25% which is closer to false than true.
Since we can assign numeric values to linguistic expressions, it follows
that we can also combine such expressions into rules and evaluate them
mathematically. A typical fuzzy logic rule might be
"If temperature is warm and pressure is low then set heat to high".
This rule has two antecedent expressions and one consequent expression.
Each antecedent expression can be replaced by a numeric value by comparing
the current input values against the membership functions for WARM and
LOW respectively. For now we are only interested in the basic idea that
a rule written in plain language can be thought of as an equivalent mathematical
expression that can be evaluated by a small microcontroller. The rest of
this paper describes a microcontroller program that implements fuzzy logic
techniques to execute a control function.
Figure 2 shows a block diagram of a software fuzzy inference system.
The right half of the figure shows the three part fuzzy inference kernel
that executes at run-time. The left half of the figure shows the data structures
that comprise the knowledge base for a specific control application. For
each of the three parts of the kernel program there is a corresponding
data structure in the knowledge base. The inputs to this system are pre-processed
values from system input sensors. The outputs are values that are suitable
for driving system components such as motors. It is likely that these output
values would need to be further processed before actually driving an output
component such as a motor. Post-processing such as converting a binary
value into a PWM signal for a motor driver circuit are well known in the
field and are not part of a fuzzy logic discussion.
The fuzzification step takes current input sensor values, compares them
against input membership functions in the knowledge base, and stores fuzzy
input values in a RAM data structure. There is one fuzzy input for each
linguistic label of each input. For a system with two inputs and seven
linguistic labels per input there would be fourteen fuzzy inputs.
The rule evaluation step processes a list of rules from the knowledge
base using current fuzzy input information from the previous fuzzification
step to produce fuzzy outputs in RAM. For a system with one output and
seven linguistic labels per output, there will be seven fuzzy outputs.
Defuzzification uses the fuzzy outputs from the rule evaluation step
and output membership function definitions from the knowledge base to produce
a single output value for each system output. An output such as HEAT is
50% may need to be post-processed into a 50% duty cycle PWM signal to drive
a system output component. This post-processing is not shown in figure
2.
The requirements of each application will determine how often the system
inputs are sampled and how often system outputs are updated. Suppose your
output must be updated every 100 milliseconds. The fuzzy
inference kernel shown in figure 2 would be executed once every 100
milliseconds. You may decide to sample system inputs at this same rate
or at a faster rate and perform some filtering or averaging algorithm as
part of the pre-processing of inputs before feeding them to the fuzzy kernel
in figure 2. You could also use historical input readings to develop derivatives
or integrals of an input parameter and use these as inputs to the fuzzy
inference system.
Looking at the fuzzy inference kernel as a whole, the goal is to provide
a specific output value (or set of output values) for every possible combination
of system input values. This is really just the definition of any control
system. If you currently use a proportional-integral-differential (PID)
control methodology you can simply replace the PID block of your program
with a fuzzy inference kernel. Fuzzy logic can be used to solve a wider
range of problems than PID because fuzzy logic does not require a linear
system or an accurate mathematical model of the system being controlled.
This has been demonstrated in a number of practical control systems where
there was no automatic control system solution before fuzzy logic. One
such system was a cement drying kiln where fuzzy logic was able to capture
the expert knowledge of human operators. Another system is a commuter train
in Sendai, Japan where the fuzzy based controller operates the train so
smoothly that riders don't need to hold onto hanging straps. This system
outperforms the human operators that it has replaced.
On the surface, the acceleration of a train seems simple but a closer
look reveals why a PID controller has so much trouble solving the problem.
The mathematical model for the train is not constant. The load weight,
track conditions, wind speed, and other factors vary over wide ranges.
An experienced human operator understands all of these factors and is able
to adapt his control strategy to compensate. The operator doesn't weigh
the train or measure track friction. He incorporates these variations into
rules which control throttle position based on speed, acceleration, and
location relative to schedule. He recognizes that certain combinations
of these inputs suggest that the train is heavily loaded or that there
must be a strong headwind. He can then incorporate this implied knowledge
into subsequent control decisions. The physical system and interrelated
factors are just too complex for a practical PID controller.
ystem inputs
enter this block as an 8-bit hexadecimal value representing the current
reading from a system sensor. For each input there can be as many as eight
linguistic labels and each one has a membership function definition in
the knowledge base. Figure 3 shows a trapezoidal input membership function
for WARM which is one label associated with the system input TEMPERATURE.
The current input corresponds to a position on the x-axis of the membership
function. A software subroutine calculates the y-intercept and returns
it as the truth value for the linguistic label. This is done for all labels
of one input. Then another input is read and the loop is repeated for each
label of that input.
This is similar to the membership function shown in figure 1 except
the axes have been re labeled with values that are more suitable for a
microcontroller based system. The input value has been scaled to fit on
a $00 to $FF scale and the y-axis now runs from $00 (false) to $FF (completely
true).
In the knowledge base, each membership function is defined by four 8-bit
values, the x position of two points and two slope values. The first point
defines the left endpoint of the base. Slope_1 defines the slope of the
left slanting side of the trapezoid. The second point defines the right
end of the top of the trapezoid and the second slope defines the slope
of the right slanting side of the trapezoid. The whole x-axis can be divided
into three segments. Segment 0 is everything to the left of the trapezoid.
Segment 1 starts at point_1 and includes any point on the left slanting
side or the top of the trapezoid. Segment 2 starts at point_2 and includes
any point on the right slanting side or to the right of the trapezoid.
There are other ways to define an input membership function but this happens
to be the way the kernels
on Motorola's FREEware BBS are defined.
Two delta values may be calculated. Delta_1 is the difference between
the current input value and point_1, and delta_2 is the difference between
the input value and point_2. In segment 0 both delta values are negative
and the truth value is zero, in segment 1 the truth value is delta_1 times
slope_1 (subject to an upper limit of $FF), and in segment 2 the truth
value is $FF minus the quantity delta_2 times slope_2 (subject to a lower
limit of zero). Listing 1 is a commented listing of the Get_Grade routine
written in M68HC11 assembly language.
**************************************************************** * GET_GRADE - Routine to project a discrete input value onto * * the associated input membership function (fuzzification). * **************************************************************** B6AB 36 [ 3] GET_GRADE PSHA ;Save input value of A B6AC 5F [ 2] CLRB ;In case grade = 0 B6AD A002 [ 4] SUBA 2,X ;Input value -- pt2 -> A B6AF 2310 [ 3] BLS NOT_SEG2 ;If input < pt2 B6B1 E603 [ 4] LDAB 3,X ;Slope 2 B6B3 271C [ 3] BEQ HAV_GRAD ;Skip if zero slope B6B5 3D [10] MUL ;(In -- pt1) * slp2 -> A:B B6B6 4D [ 2] TSTA ;Check for > $FF B6B7 2703 [ 3] BEQ NO_FIX ;If upper 8 = 0 B6B9 5F [ 2] CLRB ;Limit grade to 0 B6BA 2015 [ 3] BRA HAV_GRAD ;In limit region of seg 2 B6BC C0FF [ 2] NO_FIX SUBB #$FF ;B -- $FF B6BE 50 [ 2] NEGB ;$FF -- B B6BF 2010 [ 3] BRA HAV_GRAD ;($FF --((In -- pt2) * slp2)) B6C1 AB02 [ 4] NOT_SEG2 ADDA 2,X ;Restore input value B6C3 A000 [ 4] SUBA 0,X ;Input value -- pt1 -> A B6C5 250A [ 3] BLO HAV_GRAD ;In < pt1 so grade = 0 B6C7 E601 [ 4] LDAB 1,X ;Slope 1 B6C9 2704 [ 3] BEQ ZERO_SLP ;Skip if zero slope B6CB 3D [10] MUL ;(In -- pt1) * slp1 -> A:B B6CC 4D [ 2] TSTA ;Check for > $FF B6CD 2702 [ 3] BEQ HAV_GRAD ;Result OK in B B6CF C6FF [ 2] ZERO_SLP LDAB #$FF ;Limit region or zero slope B6D1 08 [ 3] HAV_GRAD INX ;Point at next MF spec B6D2 08 [ 3] INX B6D3 08 [ 3] INX B6D4 08 [ 3] INX B6D5 32 [ 4] PULA ;Restore A register
A relatively simple rule structure is used for small microcontroller
based fuzzy logic systems. A rule such as "If TEMPERATURE is WARM
and PRESSURE is LOW then set HEAT to HIGH", has two antecedents (if
parts) and one consequent (then part). A complete control system would
have a list of many similar rules which together describe the system control
response. The order of rules in this list does not affect the system response.
All rules are imagined to be evaluated simultaneously although in a software
based system they would actually be processed sequentially.
Each antecedent expression such as "TEMPERATURE is WARM" can
be replaced by the current value of the corresponding fuzzy input (a RAM
value that was determined during fuzzification). "If" introduces
the antecedents that are required to make the rule true and indicates the
start of a rule. "Then" separates the antecedent conditions from
the consequent actions. Antecedents are connected by the "and"
operator and there is an implied "or" operator between successive
rules. Rules can be stored in the knowledge base as pointers or offsets
to fuzzy inputs followed by pointers or offsets to fuzzy outputs. In the
code example in listing 2, one byte offsets are used and consequents are
distinguished from antecedents by setting the MSB of each consequent offset.
The end of the rule base is indicated by a $FF byte.
Min-Max rule evaluation (which works well for many embedded control
applications) is performed by initially clearing all fuzzy outputs, pointing
at the start of the rule list, and processing successive rules according
to the following algorithm. Find the smallest antecedent (min) of a rule
and store this result to each consequent of the rule unless the consequent
fuzzy output is already bigger (max). Repeat until you reach an end-of-rules
marker. The results of the rule evaluation will be a table of fuzzy output
values in RAM. You can think of the fuzzy outputs as the intermediate results
of considering all of the rules governing the system. The fuzzy outputs
will need to be processed further to get a single composite result for
each system output.
B6F1 18CEB690 [ 4] LDY #RULE_START ;Point to start of 1st rule B6F5 86FF [ 2] RULE_TOP LDAA #$FF ;Begin processing a rule * A will hold grade of smallest (min) if part B6F7 18E600 [ 5] IF_LOOP LDAB 0,Y ;Rule byte 000X XAAA; If X is A B6FA 2B0E [ 3] BMI THEN_LOOP ;If MSB=1, exit to then loop B6FC 1808 [ 4] INY ;Point at next rule byte B6FE CE0004 [ 3] LDX #FUZ_INS ;Point at fuzzy inputs B701 3A [ 3] ABX ;Point to specific fuzzy in B702 A100 [ 4] CMPA 0,X ;Is this fuzzy input lower? B704 23F1 [ 3] BLS IF_LOOP ;If not don't replace lowest B706 A600 [ 4] LDAA 0,X ;Replace lowest if B708 20ED [ 3] BRA IF_LOOP ;Do next rule byte B70A CE0024 [ 3] THEN_LOOP LDX #FUZ_OUTS ;Point at fuzzy outputs B70D C40F [ 2] ANDB #$0F ;Save 8 X out # + label # B70F 3A [ 3] ABX ;X points at fuzzy output * Grade of membership for rule is in A accumulator B710 A100 [ 4] CMPA 0,X ;Compare to fuzzy output B712 2502 [ 3] BLO NOT_HIER ;Branch if not higher B714 A700 [ 4] STAA 0,X ;Grade is higher so update B716 1808 [ 4] NOT_HIER INY ;Adv rule pntr to next byte B718 18E600 [ 5] LDAB 0,Y ;Get rule byte B71B 2AD8 [ 3] BPL RULE_TOP ;If MSB=0 its a new rule B71D C1FF [ 2] CHK_END CMPB #$FF ;Check for end of rules flag B71F 26E9 [ 3] BNE THEN_LOOP ;If not FF, it's a then part
A fuzzy associative matrix (FAM) can be helpful to be sure you are not missing any important rules in your system. Figure 4 shows a FAM for a control system with two inputs, each having three labels. Inside each box you write a label of the system output. In this system there are nine possible rules corresponding to the nine boxes in the FAM. The highlighted box corresponds to the rule "If TEMPERATURE is WARM and PRESSURE is LOW then set HEAT to HIGH".
[1] If temperature is cold and pressure is low then set heat to full
[2] If temperature is warm and pressure is low then set heat to high
[3] If temperature is hot and pressure is low then set heat to medium
[4] If temperature is cold and pressure is medium then set heat to medium
[5] If temperature is warm and pressure is medium then set heat to medium
[6] If temperature is hot and pressure is medium then set heat to low
[7] If temperature is cold and pressure is high then set heat to low
[8] If temperature is warm and pressure is high then set heat to off
[9] If temperature is hot and pressure is high then set heat to off
You can think of the FAM as a very coarse control surface (a view directly down at the control surface from above). Figure 5 shows a more detailed area map of the control surface (again viewed from above). The system in figure 5 has two inputs with only three labels per input. Trapezoidal membership functions have been drawn adjacent to the top and side of the map so you can see overlapping areas where more than one label of an input is partially true at the same time. The numbers in square brackets indicate areas where a single rule governs the output level. The number in the brackets is the rule number for reference (see figure 4). A two in a circle marks an area where two rules are partially true at the same time. A four in a circle marks an area where four rules are partially true at the same time.
In the areas where more than one rule contributes to the output level, defuzzification is used to calculate a weighted average of the contributing rules. Figure 6 shows a three dimensional control surface which defines the output control surface for the example system that was shown in figures 4 and 5. The inputs correspond to the axes that form the base of the three dimensional graph and the height of the surface is the output level for the corresponding combination of input values. Keep in mind that the fuzzy inference program only calculates one point on this surface per interval of real time. The complete surface is just an aid to help you understand how the system responds to any combination of input values.
As the control surface shows, the input to output relationship is precise
and constant. Many engineers were initially unwilling to embrace fuzzy
logic because of a misconception that the results were not repeatable and
approximate. The term fuzzy actually refers to the gradual transitions
at set boundaries from false to true.
For the program described in this paper, we use singletons to define
output membership functions. A singleton membership function is defined
by a single 8-bit value in the knowledge base (a z-axis position). The
associated fuzzy outputs provide a weight for each label of the system
output. Defuzzification uses the following formula to determine a single
z-axis position as the final system output.
Where n is the number of fuzzy outputs associated with this system
output, Fi is a weight (fuzzy output value), and Si is a
membership function singleton position. The result of this calculation
is the z-axis position of the desired output action. Fi and Si
are 8-bit values and n is typically 8 or less. This makes the
numerator a 19-bit value and the denominator an 11-bit value. Because the
numerator and denominator are not independent values, we know the result
is an 8-bit value.
The overall effect of defuzzification is to smooth the control surface
between points of known height on the control surface. Referring to figure
5, the points where a single rule is acting are known height (the singleton
position of the consequent). Listing 3 shows an assembly language routine
to perform weighted average defuzzification.
Listing 3. Weighted Average Defuzzification
B721 18CEB680 [ 4] DEFUZ LDY #SGLTN_POS ;Point at 1st output singltn B725 CE0024 [ 3] LDX #FUZ_OUTS ;Point at 1st fuzzy output B728 7F003B [ 6] CLR COGDEX ;Loop index runs from 0->1 B72B C608 [ 2] COG_LOOP LDAB #8 ;8 fuzzy outs per COG output B72D D73D [ 3] STAB SUMDEX ;Inner loop runs 8->0 B72F CC0000 [ 3] LDD #$0000 ;Used for quicker clears B732 DD36 [ 4] STD SUM_OF_FUZ ;Sum of fuzzy outputs B734 DD39 [ 4] STD SUM_OF_PROD+1 ;Low 16-bits of sum of prod B736 9738 [ 3] STAA SUM_OF_PROD ;Upper 8-bits B738 E600 [ 4] SUM_LOOP LDAB 0,X ;Get a fuzzy output B73A 4F [ 2] CLRA ;Clear upper 8-bits B73B D336 [ 5] ADDD SUM_OF_FUZ ;Add to sum of fuzzy outputs B73D DD36 [ 4] STD SUM_OF_FUZ ;Update RAM variable B73F A600 [ 4] LDAA 0,X ;Get fuzzy output again B741 18E600 [ 5] LDAB 0,Y ;Get Output singleton pos. B744 3D [10] MUL ;Position times weight B745 D339 [ 5] ADDD SUM_OF_PROD+1 ;Low 16-bits of sum of prod B747 DD39 [ 4] STD SUM_OF_PROD+1 ;Update low 16-bits B749 9638 [ 3] LDAA SUM_OF_PROD ;Upper 8-bits B74B 8900 [ 2] ADCA #0 ;Add carry from 16-bit add B74D 9738 [ 3] STAA SUM_OF_PROD ;Upper 8-bits of 24-bit sum B74F 1808 [ 4] INY ;Point at nxt singleton pos. B751 08 [ 3] INX ;Point at next fuzzy output B752 7A003D [ 6] DEC SUMDEX ;Inner loop index B755 26E1 [ 3] BNE SUM_LOOP ;For all labels this output B757 3C [ 4] PSHX ;Save index for now B758 4F [ 2] CLRA ;In case divide by zero B759 DE36 [ 4] LDX SUM_OF_FUZ ;Denominator for divide B75B 2718 [ 3] BEQ SAV_OUT ;Branch if denominator is 0 B75D 7D0038 [ 6] TST SUM_OF_PROD ;See if more than 16-bit B760 2607 [ 3] BNE NUM_BIG ;If not zero, # is > 16-bits B762 DC39 [ 4] LDD SUM_OF_PROD+1 ;Numerator for divide B764 02 [41] IDIV ;Result in low 8-bits of X B765 8F [ 3] XGDX ;Result now in B B766 17 [ 2] TBA ;Move result to A B767 200C [ 3] BRA SAV_OUT ;Go save output B769 DC38 [ 4] NUM_BIG LDD SUM_OF_PROD ;Numerator upper 16 of 24 B76B 7D003A [ 6] TST SUM_OF_PROD+2 ;Check for rounding error B76E 2A03 [ 3] BPL NO_ROUND ;If MSB clear, don't round B770 C30001 [ 4] ADDD #1 ;Round numerator up 1 B773 03 [41] NO_ROUND FDIV ;D/X -> X, use upper 8 of 16 B774 8F [ 3] XGDX ;Result now in A
Control systems must provide a proper response to all possible combinations of input values. This response can be displayed as one or more three dimensional control surfaces. For simple linear systems, the control response can be calculated in real time from the current input values. But this approach breaks down when the control system is non-linear or is too complex. There are many examples of such control systems where an expert human operator is able to control the system but attempts to develop automatic controls have failed.
Fuzzy logic provides a new way to accurately express the meaning of subjective sounding linguistic terms such as WARM. This in turn allows us to mathematically calculate control system outputs based on a set of rules provided by an application expert. A general purpose fuzzy inference kernel can be written and used for different applications by providing a different knowledge base for each application. The processing requirements for many embedded control systems based on fuzzy logic are well within the capability of a small 8-bit microcontroller.