Source Code Fuzzy Logic Arduino

A Fuzzy Logic Control Library in C++

By: Juan Rada-Vilela, Ph.D.

Released: 20/March/2017

Table of Contents

License
Introduction
Features
Example
Compile, Link, and Execute
Bulding from Source
Binaries
What's new
What's next

Nov 19, 2016 C Fuzzy Logic Programming Library - For problem solving in the fuzzy logic domain. It has an object oriented API well suited to C syntax for direct inclusion in source code. Portable to platforms that support the C STL. Code is written with pieces that are considered as bad code smells. Presence of any bad code smell can disturb normal code maintainability. It is important to recognize the concept of bad smells as a particular compromise between the vague programming aesthetics and the precise source code metrics. 3 Application of Fuzzy Logic to Code.

License

fuzzylite 6.0 is licensed under the GNU General Public License (GPL) 3.0. You are strongly encouraged to support the development of the FuzzyLite Libraries by purchasing a license of QtFuzzyLite 6.

QtFuzzyLite 6 is the new and (very likely) the best graphical user interface available to easily design and directly operate fuzzy logic controllers in real time. Available for Windows, Mac, and Linux, its goal is to significantly speed up the design of your fuzzy logic controllers, while providing a very useful, functional and beautiful user interface. Please, download it and check it out for free at www.fuzzylite.com/downloads/.

The platform is also open source, modular and can easily integrate any other type of sensor. 4.2 Implementation of the Fuzzy Logic Algorithm on the Arduino. Fuzzy mamdani Arduino is a decision making program based on fuzzy logic or fuzzy logic controller, Arduino as a microcontroller that processes fuzzy logic programs. In this article, we will discuss thoroughly about making design of fuzzy logic mamdani with Arduino and its application. Fuzzy logic is a branch of mathematics.

Introduction

fuzzylite is a free and open-source fuzzy logic control library programmed in C++ for multiple platforms (e.g., Windows, Linux, Mac, iOS). jfuzzylite is the equivalent library for Java and Android platforms. Together, they are the FuzzyLite Libraries for Fuzzy Logic Control.

The goal of the FuzzyLite Libraries is to easily design and efficiently operate fuzzy logic controllers following an object-oriented programming model without relying on external libraries.

Reference

If you are using the FuzzyLite Libraries, please cite the following reference in your article:

Juan Rada-Vilela. fuzzylite: a fuzzy logic control library, 2017. URL http://www.fuzzylite.com/.

author={Juan Rada-Vilela},
url={http://www.fuzzylite.com/},

Documentation

Source

The documentation for the fuzzylite library is available at: www.fuzzylite.com/documentation/.

Features

**(6) Controllers**: Mamdani, Takagi-Sugeno, Larsen, Tsukamoto, Inverse Tsukamoto, Hybrids

**(21) Linguistic terms**: (4) Basic: triangle, trapezoid, rectangle, discrete. (9) Extended: bell, cosine, gaussian, gaussian product, pi-shape, sigmoid difference, sigmoid product, spike. (5) Edges: binary, concave, ramp, sigmoid, s-shape, z-shape. (3) Functions: constant, linear, function.

**(7) Activation methods**: general, proportional, threshold, first, last, lowest, highest.

**(8) Conjunction and Implication (T-Norms)**: minimum, algebraic product, bounded difference, drastic product, einstein product, hamacher product, nilpotent minimum, function.

**(10) Disjunction and Aggregation (S-Norms)**: maximum, algebraic sum, bounded sum, drastic sum, einstein sum, hamacher sum, nilpotent maximum, normalized sum, unbounded sum, function.

**(7) Defuzzifiers**: (5) Integral: centroid, bisector, smallest of maximum, largest of maximum, mean of maximum. (2) Weighted: weighted average, weighted sum.

**(7) Hedges**: any, not, extremely, seldom, somewhat, very, function.

**(3) Importers**: FuzzyLite Language fll, Fuzzy Inference System fis, Fuzzy Control Language fcl.

**(7) Exporters**: C++, Java, FuzzyLite Language fll, FuzzyLite Dataset fld, R script, Fuzzy Inference System fis, Fuzzy Control Language fcl.

**(30+) Examples** of Mamdani, Takagi-Sugeno, Tsukamoto, and Hybrid controllers from fuzzylite, Octave, and Matlab, each included in the following formats: C++, Java, fll, fld, R, fis, and fcl.

Example

#### FuzzyLite Language

Engine: ObstacleAvoidance
enabled: true
lock-range: false
Source Code Fuzzy Logic Arduino
term: right Ramp 0.000 1.000
enabled: true
lock-range: false
defuzzifier: Centroid 100
lock-previous: false
term: right Ramp 0.000 1.000
enabled: true
disjunction: none
activation: General
rule: if obstacle is right then mSteer is left
#include 'fl/Headers.h'
int main(int argc, char* argv[]){
Engine* engine = FllImporter().fromFile('ObstacleAvoidance.fll');
std::string status;
throwException('[engine error] engine is not ready:n' + status, FL_AT);
InputVariable* obstacle = engine->getInputVariable('obstacle');
OutputVariable* steer = engine->getOutputVariable('mSteer');
for (int i = 0; i <= 50; ++i){
scalar location = obstacle->getMinimum() + i * (obstacle->range() / 50);
engine->process();
FL_LOG('obstacle.input = ' << Op::str(location) <<
' => ' << 'steer.output = ' << Op::str(steer->getValue()));
}

#### C++

#include 'fl/Headers.h'
int main(int argc, char* argv[]){
//Code automatically generated with fuzzylite 6.0.
using namespace fl;
Engine* engine = newEngine;
engine->setDescription(');
InputVariable* obstacle = newInputVariable;
obstacle->setDescription(');
obstacle->setRange(0.000, 1.000);
obstacle->addTerm(newRamp('left', 1.000, 0.000));
obstacle->addTerm(newRamp('right', 0.000, 1.000));
mSteer->setName('mSteer');
mSteer->setEnabled(true);
mSteer->setLockValueInRange(false);
mSteer->setDefuzzifier(newCentroid(100));
mSteer->setLockPreviousValue(false);
mSteer->addTerm(newRamp('right', 0.000, 1.000));
mamdani->setName('mamdani');
mamdani->setEnabled(true);
mamdani->setDisjunction(fl::null);
mamdani->setActivation(newGeneral);
mamdani->addRule(Rule::parse('if obstacle is left then mSteer is right', engine));
mamdani->addRule(Rule::parse('if obstacle is right then mSteer is left', engine));
if (not engine->isReady(&status))
throwException('[engine error] engine is not ready:n' + status, FL_AT);

Fuzzy Logic Technology

for (int i = 0; i <= 50; ++i){
scalar location = obstacle->getMinimum() + i * (obstacle->range() / 50);
engine->process();
FL_LOG('obstacle.input = ' << Op::str(location) <<
' => ' << 'steer.output = ' << Op::str(steer->getValue()));
}

Compile, Link, and Execute

Once you have an engine written in C++, you can compile it to create an executable file which links to the fuzzylite library. The linking can be either static or dynamic. Basically, the differences between static and dynamic linking are the following. Static linking includes the fuzzylite library into your executable file, hence increasing its size, but the executable no longer needs to have access to the fuzzylite library files. Dynamic linking does not include the fuzzylite library into your executable file, hence reducing its size, but the executable needs to have access to the fuzzylite shared library file. When using dynamic linking, make sure that the shared library files are either in the same directory as the executable, or are reachable via environmental variables:

set PATH='pathtofuzzylitereleasebin;%PATH%'
export LD_LIBRARY_PATH='/path/to/fuzzylite/release/bin/:$LD_LIBRARY_PATH'

Windows

The commands to compile your engine in Windows are the following:

C++11 (default)

cl.exe ObstacleAvoidance.cpp fuzzylite-static.lib /Ipath/to/fuzzylite /EHsc /MD
cl.exe ObstacleAvoidance.cpp fuzzylite.lib /Ipath/to/fuzzylite /DFL_IMPORT_LIBRARY /EHsc /MD

C++98

cl.exe ObstacleAvoidance.cpp fuzzylite-static.lib /Ipath/to/fuzzylite /DFL_CPP98=ON /EHsc /MD
cl.exe ObstacleAvoidance.cpp fuzzylite.lib /Ipath/to/fuzzylite /DFL_IMPORT_LIBRARY /DFL_CPP98=ON /EHsc /MD

Unix

The commands to compile your engine in Unix are the following:

C++11 (default)

g++ ObstacleAvoidance.cpp -o ObstacleAvoidance -I/path/to/fuzzylite -L/path/to/fuzzylite/release/bin -lfuzzylite-static --std=c++11
g++ ObstacleAvoidance.cpp -o ObstacleAvoidance -I/path/to/fuzzylite -L/path/to/fuzzylite/release/bin -lfuzzylite -Wno-non-literal-null-conversion

C++98

g++ ObstacleAvoidance.cpp -o ObstacleAvoidance -I/path/to/fuzzylite -L/path/to/fuzzylite/release/bin -lfuzzylite-static -DFL_CPP98=ON
g++ ObstacleAvoidance.cpp -o ObstacleAvoidance -I/path/to/fuzzylite -L/path/to/fuzzylite/release/bin -lfuzzylite -DFL_CPP98=ON -Wno-non-literal-null-conversion

CMake

Alternatively, you can use CMake to build your project linking to fuzzylite. Please, refer to the example application available at examples/application.

Building from Source

You can build the fuzzylite library from source using CMake(cmake.org).

The files fuzzylite/build.bat and fuzzylite/build.sh are build scripts for the Windows and Unix platforms, respectively. After building from source, the resulting binaries will be located in the sub-folders fuzzylite/release/bin and fuzzylite/debug/bin. The usage of these scripts is presented as follows.

#### Windows

Usage: build.bat [options]
all builds fuzzylite in debug and release mode (default)
release builds fuzzylite in release mode
help shows this information

#### Unix

Usage: [bash] ./build.sh [options]
all builds fuzzylite in debug and release mode (default)
release builds fuzzylite in release mode
help shows this information

Building Options

For advanced building options, please check the contents of fuzzylite/build.bat or fuzzylite/build.sh, and the contents of fuzzylite/CMakeLists.txt.

The following building options available:

  • -DFL_USE_FLOAT=ON builds the binaries utilizing the fl::scalar data type as a float represented in 4 bytes. By default, the binaries are built utilizing -DFL_USE_FLOAT=OFF to utilize fl::scalar as a double represented in 8 bytes and hence providing better accuracy. If fuzzylite is built with -DFL_USE_FLOAT=ON, then the applications linking to fuzzylite also need to specify this compilation flag.
  • -DFL_CPP98=ON builds binaries utilizing C++98 features. By default, fuzzylite is built with -DFL_CPP98=OFF to utilize C++11 features. If compiling for C++98, be aware that you will not be able to benchmark the performance of your engine using the Benchmark class.
  • -DFL_BACKTRACE=OFF disables the backtrace information in case of errors (default is ON). In Windows, the backtrace information requires the external library dbghelp, which is generally available in your system.
  • -DCMAKE_BUILD_TYPE=[Debug|Release] sets the mode of your build. You can only build one mode at a time with a single CMake script.

Documentation

The source code of fuzzylite is very well documented using doxygen formatting, and the documentation is available at fuzzylite.com/documentation. If you want to generate the documentation locally, you can produce the html documentation from the file Doxyfile using the command line: doxygen Doxyfile. The documentation will be created in the documentation folder.

Binaries

After building from source, the following are the relevant binaries that will be created in Release mode. In Debug mode, the file names end with -debug (e.g., fuzzylite-debug.exe).

Windows

  • console application: fuzzylite.exe
  • shared library: fuzzylite.dll, fuzzylite.lib
  • static library: fuzzylite-static.lib

Linux

  • console application: fuzzylite
  • shared library: libfuzzylite.so
  • static library: libfuzzylite-static.a

Mac

  • console application: fuzzylite
  • shared library: libfuzzylite.dylib
  • static library: libfuzzylite-static.a

Console

Fuzzy logic downers grove

The console application of fuzzylite allows you to import and export your engines. Its usage can be obtained executing the console binary. In addition, the console can be set in interactive mode. The FuzzyLite Interactive Console allows you to evaluate a given controller by manually providing the input values. The interactive console is triggered by specifying an input file and an output format. For example, to interact with the ObstacleAvoidance controller, the interactive console is launched as follows:

What's New?

  • The FuzzyLite Libraries, namely fuzzylite and jfuzzylite, both in version 6.0, are dual licensed under the GNU General Public License version 3 and the Apache License version 2.
  • By default, fuzzylite builds using C++11 instead of C++98.
  • Important performance improvements.
  • Refactored the following names for the operation of engines: from activation operator to implication operator, from accumulation operator to aggregation operator.
  • Renamed the term Accumulated to Aggregated.
  • New activation methods decouple the activation of rules from the rule block and provide different methods for activating rules (see Activation Methods).
  • New class ActivationFactory provides a factory of activation methods.
  • New class Benchmark to evaluate the performance and accuracy of engines.
  • New class Complexity to estimate the computational complexity of an engine.
  • New class RScriptExporter to export the surfaces of an engine using the ggplot2 library.
  • New class Binary term for binary edges.
  • New UnboundedSum S-Norm in SNormFactory.
  • New classes SNormFunction and TNormFunction to create custom functions on any two values using the Function class.
  • Added description strings to Engine, Variable and RuleBlock
  • Privatized previously protected members of classes and subclasses of Term, Variable, Rule, Defuzzifier, [Cloning|Construction]Factory, Importer, Exporter, amongst others.
  • Improved portability by replacing int for std::size_t where necessary, thereby additionally removing warnings in Windows 64bit
  • Deleted Operation.cpp and inlined its methods into Operation.h
  • Updated .travis.yml to use Docker, and build using g++ (versions 6, 5, 4.9, 4.8, 4.7) and clang (versions 3.8, 3.7, 3.6, and 3.5).
  • Added appveyor.yml to use continuous integration in Windows under Visual Studio 2013 and 2015.
  • Added some unit tests and support for future unit tests.
  • Bug fixes.
  • New example of hybrid engines.
  • New example on obstacle avoidance for Mamdani, Takagi-Sugeno, and Hybrid engines.
  • New R scripts for each example and its respective surfaces in pdf formats.

Source Code Fuzzy Logic Arduino Code

Bug fixes

  • Fixed bug in CloningFactory::deregisterObject(). Bug: Object was deleted before removing it from the map, leaving an invalid object in the map which would cause a segmentation fault. Solution: Remove the object from the map before deleting it.
  • Fixed bug causing segmentation fault when malformed term in FuzzyLite Language
  • Fixed bug computing the NormalizedSum S-Norm.
  • Fixed bug in RuleBlock to reset and clone the implication operator. Bug: implication operator is not copied and reset. Fix: copy and reset implication operator when cloning the RuleBlock.
  • Fixed bug in Function term. Bug: given a formula = 'tan(y)' and a map['y'] = 1.0, and executing Function::load(formula), then the map of variables is reset because load() calls unload() first, causing the deregistration of variable y. Solution: Removed method unload() from load(), thereby causing future load() not to reset variables.
  • Fixed bug in Function when enclosing variable in double parenthesis.

What's Next?

  • Optimization of Fuzzy Logic Controllers
  • Type-2 Fuzzy Logic Controllers
  • Adaptive Neuro-Fuzzy Inference System (ANFIS)
  • Fuzzy C-means data clustering

fuzzylite® is a registered trademark of FuzzyLite Limited.
jfuzzylite™ is a trademark of FuzzyLite Limited.
QtFuzzyLite™ is a trademark of FuzzyLite Limited.

Copyright &#xa9; 2010-2017 FuzzyLite Limited. All rights reserved.

You can generate code for evaluating a fuzzy inference system using MATLAB® Coder™. For more information on generating code, see Code Generation (MATLAB Coder).

To generate code for evaluating fuzzy systems, you must first create a fuzzy inference system (FIS). For more information, see Build Fuzzy Systems at the Command Line and Build Fuzzy Systems Using Fuzzy Logic Designer.

While this example generates code for a type-1 Mamdani fuzzy inference system, the workflow also applies to Sugeno and type-2 fuzzy systems.

Source Code Fuzzy Logic Arduino Programming

Generating code using MATLAB Coder does not support fuzzy FIS objects (mamfis, sugfis, mamfistype2, sugfistype2). To generate code for evaluating fuzzy systems, you must convert your fuzzy inference system objects into homogeneous structures using the getFISCodeGenerationData function.

Embed FIS Data in Generated Code

You can embed the data for your fuzzy inference system within the generated code. Use this option if you do not want to change the FIS data after compilation.

Code

First, create a fuzzy system, or load a fuzzy system from a .fis file. For this example, load the fuzzy system from tipper.fis.

To use this FIS for code generation, convert it to a homogeneous structure.

By default, getFISCodeGenerationData assumes that the FIS object is a type-1 system. To generate code for a type-2 system, you must indicate the system type using getFISCodeGenerationData(fisObject,'type2').

Create a function for evaluating the fuzzy system fis for a given input vector x. Within this function, you can specify options for the evalfis function using evalfisOptions.

Generate code for evaluatefis1, specifying that the fis input argument is constant. You can specify different targets for your build, such as a static library, an executable, or a MEX file. For this example, generate a MEX file.

To verify the execution of the MEX file:

  1. Evaluate the MEX file for one or more input values. When you call the MEX file, specify the same FIS structure that you used at compile time.

  2. Evaluate the original FIS for the same input values using evalfis. When evaluating using evalfis, use the same homogeneous FIS structure.

  3. Compare the evaluation results.

The MEX file output matches the evalfis output.

Alternatively, you can embed the FIS data in the generated code by reading the FIS data from a file at code generation time. Specify a function for evaluating a fuzzy system for given input vector x. Within this function, read the FIS data from the file tipper.fis.

Generate code for evaluatefis2.

Verify the execution of the MEX file using the same input values for x. In this case, you do not have to specify the original FIS structure used at compile time.

Source Code Fuzzy Logic Arduino Tutorial

Generate Code for Loading FIS Data at Run Time

You can generate code for evaluating a FIS that is read from a .fis file specified at run time. In this case, the FIS data is not embedded in the generated code. Specify a function for evaluating the fuzzy system defined in the specified file fileName for a given input vector x.

Define input data types for this function.

Generate code for evaluatefis3.

Verify the execution of the MEX file using the same input values for x. In this case, you specify the name of the .fis file.

Each time you run evaluatefis3, it reloads the fuzzy system from the file. For computational efficiency, you can create a function that only loads the FIS when a new file name is specified.

Generate code evaluatefis4. The input data types for this function are the same as for evaluatefis3.

Verify the execution of the MEX file using the same input values file name.

Generate Code for Single-Precision Data

The preceding examples generated code for double-precision data. To generate code for single-precision data, specify the data type of the input values as single. For example, generate code for evaluatefis2 using single-precision data.

Fuzzy logic downers grove

Verify the MEX file execution, passing in single-precision input values.

See Also

evalfis | getFISCodeGenerationData

Fuzzy Logic Example

Related Topics