Senior Design Ii Report: Control Design For Tower Copter System
Senior Design Ii Report: Control Design For Tower Copter System
I
SENIOR DESIGN II REPORT
Author: Supervisor:
Doan Minh Quang MSc. Nguyen Van Lanh
Student’s ID: K155905228031
Hoang Dinh Nghia
Student’s ID: K155520216237
Nguyen Thien Trang Anh
Student’s ID: K155905228002
II
This thesis has been approved by the
Supervisor: MSc. Nguyen Van Lanh
Signed:
Date:
Signed:
Date:
Signed:
Date:
III
Acknowledgements
In this topic, present a specific view of tower copter with PID controller. Due to
limited knowledge, our thematic issues cannot avoid shortcomings. We hope to
receive criticism and contributions from the subject teachers well as the teachers
in the Faculty so that the topic of my group completed.
We sincerely thank MSc Nguyen Van Lanh for enthusiastically guiding us in the
past time, his help and suggestions have greatly supported us to complete this
topic.
IV
Contents
Acknowledgements ........................................................................................................... iv
Contents .............................................................................................................................. 5
Abstract .............................................................................................................................. 9
2.1. Fuzzification.................................................................................................... 16
CHAPTER 3 ..................................................................................................................... 20
Page | 2
CHAPTER 4 Control design for the tower copter system........................................... 35
REFERENCES ................................................................................................................ 44
APPENDIX....................................................................................................................... 46
List of figures
Figure 1. 1. A basic control system .............................................................................. 10
Figure 1. 2. The block diagram of open loop control system ....................................... 11
Figure 1. 3 The block diagram of closed loop control system. ................................... 11
Figure 1. 4. The block diagram of PID controller........................................................12
Figure 1. 5. The block diagram of fuzzy logic controller.............................................13
List of tables
Table 2. 1. Boolean and Fuzzy logic ............................................................................ 17
List of abbreviations
CT – Continuous- time
Page | 4
DT – Discrete- time
PID – Proportional- integral- derivative
SP – Setpoint
PV – Process variable
LCD - Liquid Crystal Display
PMSM – Permanent magnet synchronous motor
ESC – Electronic Speed Control
FETs – Field effect transistors
Page | 5
Abstract
This project; presenting to the field of power electronics, describes the mechanical
design, electronic and programming of a tower copter using Fuzzy Logic controller
and the PID ( proportional- integral- derivative) controller. In addition, the operation
of the project is shown both open ( no control) and closed loop (with control) loop,
also a brief description of the different software used will be made during the project,
such as matlab, arduino, excel, etc. Also be taken into account (briefly) the machines
used for the construction of the model, such as 3D, CNC (computer numerical control)
and other.
As progress is made in the document anger exposing each of the components used for
the assembly of the tower ccopter as well as the respective show progrmacionand
tuning. It should be noted that this project was developes with the knowledge gained
during the course, mainly on topis ranging types of eletric motor, variable speed
drives, wiring, sensors, meters and other. Regarding issues related to the type of
control used, a separate investigation was made, since that issue was not included in
the curriculum of the subject. This was the great challenge of the project, learn PID
control. At the end of the document some conclusions and recommendations (or
advice) and for possible further improvement of the design and components used are
given.
Keywords: tower copter, PID, open loop, close loop, matlab, arrduino, impresora 3D,
CNC.
Page | 6
CHAPTER 1
INTRODUCTION OF CONTROL SYSTEM
Page | 7
Electrical systems operate either on continuous-time (CT) signals or
discrete-time (DT) signals.
Control systems are one of two different types, either an open loop system
or a closed loop system.
Page | 8
1.1. PID Controller
- Advantages: It only acts on the error between the desired signal and the
controlled signal. Hence, no extra measurements of the internal states are
needed, which is one of the biggest advantage in applications because more
measurements mean more sensors, more signal conditioning, more
maintenance, more cost. Apart from certain structural properties of the
plant/process, not much knowledge of the plant is required for tuning. The
tuning can be done through trial and error or a look-up table. Not much
expertise is needed for tuning, hence, few middle-skilled technicians may
easily carry out the task again cost cutting. It is efficient and robust against
some common uncertainties if properly tuned (around an operating region).
Page | 9
Easy to implement in hardware (through filters) and also easy to implement
though microcontrollers, PLC etc. No fancy codes to design… can be written
by a middle-level programmer.
Overall, the controller works well for most of the industrial/process applications
but on the contrary no really suited for advance applications for defense, robotics,
financial models,...etc.
CHAPTER 2
FUZZY LOGIC CONTROLLER
A fuzzy control system is a control system based on fuzzy logic a mathematical
system that analyzes analog input values in terms of logical variables that take on
continuous values between 0 and 1, in contrast to classical or digital logic, which
operates on discrete values of either 1 or 0 (true or false, respectively).
Fuzzy logic is a form of many-valued logic in which the truth values of variables
may be any real number between 0 and 1 inclusive. It is employed to handle the
concept of partial truth, where the truth value may range between completely true and
completely false. By contrast, in Boolean logic, the truth values of variables may only
be the integer values 0 or 1.
The term fuzzy logic was introduced with the 1965 proposal of fuzzy set theory
by Lotfi Zadeh. Fuzzy logic had however been studied since the 1920s, as infinite-
valued logic notably by Łukasiewicz and Tarski.
It is based on the observation that people make decisions based on imprecise and
non-numerical information, fuzzy models or sets are mathematical means of
representing vagueness and imprecise information, hence the term fuzzy. These
Page | 11
models have the capability of recognizing, representing, manipulating, interpreting,
and untilising data and information that are vague and lack certainty.
Fuzzy logic has been applied to many fields, from control theory to artificial
intelligence.
Fuzzy logic seems closer to the way our brains work. We aggregate data and form
a number of partial truths which we aggregate further into higher truths which in turn,
when certain thresholds are exceeded, cause certain further results such as motor
reaction.
- Defuzzification
Page | 12
2.1. Fuzzification
In this image, the meanings of the expressions cold, warm, and hot are
represented by functions mapping a temperature scale. A point on that scale has three
"truth values"—one for each of the three functions. The vertical line in the image
represents a particular temperature that the three arrows (truth values) gauge. Since
the red arrow points to zero, this temperature may be interpreted as "not hot". The
orange arrow (pointing at 0.2) may describe it as "slightly warm" and the blue arrow
(pointing at 0.8) "fairly cold".
Fuzzy sets are often defined as triangle or trapezoid-shaped curves, as each value
will have a slope where the value is increasing, a peak where the value is equal to 1
(which can have a length of 0 or greater) and a slope where the value is decreasing.
They can also be defined using a sigmoid function. One common case is the standard
logistic function defined as
1
𝑆 (𝑥 ) =
1 + 𝑒 −𝑥
which has the following symmetry property
𝑆(𝑥) + 𝑆(−𝑥) = 1
From this it follows that
(𝑆(𝑥) + 𝑆(−𝑥)) ∗ (𝑆(𝑦) + 𝑆(−𝑦)) ∗ (𝑆(𝑧) + 𝑆(−𝑧)) = 1
Page | 13
Figure 2.2: Model of Fuzzy controller
The process of transforming crisp (bivalued) input values into linguistic values is
called fuzzification
Steps of Fuzzification:
Step 1: Input values are translated into linguistic concepts, which are represented by
fuzzy set.
Step 2: Membership functions are applied to the measurements, and the degree of
membership is determined.
Boolean Fuzzy
Page | 14
AND(x,y) MIN(x,y)
OR(x,y) MAX(x,y)
NOT(x) 1–x
For TRUE/1 and FALSE/0, the fuzzy expressions produce the same result as the
Boolean expressions.
There are also other operators, more linguistic in nature, called hedges that can
be applied. These are generally adverbs such as very, or somewhat, which modify the
meaning of a set using a mathematical formula.
However, an arbitrary choice table does not always define a fuzzy logic function.
In the paper, a criterion has been formulated to recognize whether a given choice table
defines a fuzzy logic function and a simple algorithm of fuzzy logic function synthesis
has been proposed based on introduced concepts of constituents of minimum and
maximum. A fuzzy logic function represents a disjunction of constituents of
minimum, where a constituent of minimum is a conjunction of variables of the current
area greater than or equal to the function value in this area (to the right of the function
value in the inequality, including the function value).
Another set of AND/OR operators is based on multiplication
x AND y = x*y
x OR y = 1-(1-x)*(1-y) = x+y - (x*y)
1-(1 - x) * (1 - y) comes from this:
x OR y = NOT{AND[ NOT(x), NOT(y) ] }
x OR y = NOT[ AND(1-x, 1-y) ]
x OR y = NOT[(1-x)*(1-y) ]
x OR y = 1-(1-x)*(1-y)
2.4. Defuzzification
CHAPTER 3
EXPERIMENTAL SETUP
Page | 17
Figure 3.1: Real model of the product
2 4
1
Motor
Brush motor and H-bridge :
Page | 19
A brushed motor is an internally commutated electric motor designed to be run
from a direct current power source. Brushed motors were the first commercially
important application of electric power to driving mechanical energy, and DC
distribution systems were used for more than 100 years to operate motors in
commercial and industrial buildings.
Brushed DC motors can be varied in speed by changing the operating voltage or
the strength of the magnetic field. Depending on the connections of the field to the
power supply, the speed and torque characteristics of a brushed motor can be altered
to provide steady speed or speed inversely proportional to the mechanical load.
Brushed motors continue to be used for electrical propulsion, cranes, paper machines
and steel rolling mills.
Brushless motor is the core of this project because this is the Copter, brushless
Motor may be expensive but with ESC the speed and rpm are easy to maintain and
Page | 20
controlled. Because of that instead of using regular DC motor we use Brushless Motor
( shown in figure 3.6).
The advantages of a brushless motor over brushed motors are high power to
weight ratio, high speed, and electronic control. Brushless motors find applications in
such places as computer peripherals (disk drives, printers), hand-held power tools, and
vehicles ranging from model aircraft to automobiles.
Page | 21
Figure 3.7: Brushless ESC
Different types of speed controls are required for brushed DC motors and
brushless DC motors. A brushed motor can have its speed controlled by varying the
voltage on its armature (Industrially, motors with electromagnet field windings instead
of permanent magnets can also have their speed controlled by adjusting the strength of
the motor field current). A brushless motor requires a different operating principle.
The speed of the motor is varied by adjusting the timing of pulses of current delivered
to the several windings of the motor.
Page | 22
Brushless ESC systems basically create three-phase AC power, as in a
variable frequency drive , to run brushless motors. Brushless motors are popular with
radio controlled airplane hobbyists because of their efficiency, power, longevity and
light weight in comparison to traditional brushed motors. Brushless AC motor
controllers are much more complicated than brushed motor controllers.
The correct phase varies with the motor rotation, which is to be taken into account
by the ESC: Usually, back EMF from the motor is used to detect this rotation, but
variations exist that use magnetic (Hall effect) or optical detectors. Computer-
programmable speed controls generally have user-specified options which allow
setting low voltage cut-off limits, timing, acceleration, braking and direction of
rotation. Reversing the motor's direction may also be accomplished by switching any
two of the three leads from the ESC to the motor.
As we know that, an ESC controls the speed of the motors spin of an airplane. It
helps the similar purpose as the throttle servo of a glow powered airplane. It is an edge
between the radio receiver of an airplane and the power plant. An electronic speed
control will have 3- sets of wires. One wire will plug into the main battery of an
airplane. The second wire will have a typical servo wire that plugs into the receiver’s
throttle channel. And lastly, a third of wire is used for powering the motor. The main
Page | 23
features of an electronic speed control include battery eliminator circuit, low voltage
cutoff, brake, and to.
Page | 24
and is available on the Arduino website. Layout and production files for some
versions of the hardware are also available.
The word "uno" means "one" in Italian and was chosen to mark the initial release
of the Arduino Software. The Uno board is the first in a series of USB-based Arduino
boards, and it and version 1.0 of the Arduino IDE were the reference versions of
Arduino, now evolved to newer releases. The ATmega328 on the board comes
preprogrammed with a bootloader that allows uploading new code to it without the
use of an external hardware programmer.
While the Uno communicates using the original STK500 protocol, it differs from
all preceding boards in that it does not use the FTDI USB-to-serial driver chip.
Instead, it uses the Atmega16U2 (Atmega8U2 up to version R2) programmed as a
USB-to-serial converter.
- Technical Specification
Pin
Pin name Description
number
1 Vcc The Vcc pin powers the sensor, typically with +5V
2 Trigger Trigger pin is an Input pin. This pin has to be kept high
for 10us to initialize measurement by sending US wave
3 Echo Echo pin is an Output pin. This pin goes high for a
period of time which will be equal to the time taken for
Page | 26
the US wave to return back to the sensor
The HC-SR04 Ultrasonic (US) sensor is a 4 pins module, whose pin names are
Vcc, Trigger, Echo and Ground respectively. This sensor is a very popular sensor used
in many applications where measuring distance or sensing objects are required. The
module has two eyes like projects in the front which forms the Ultrasonic transmitter
and Receiver. The sensor works with the simple high school formula that
The Ultrasonic transmitter transmits an ultrasonic wave, this wave travels in air
and when it gets objected by any material it gets reflected back toward the sensor this
reflected wave is observed by the Ultrasonic receiver module as shown in the figure
3.11.
Now, to calculate the distance using the above formulae, we should know the
Speed and time. Since we are using the Ultrasonic wave we know the universal speed
of US wave at room conditions which is 330m/s. The circuitry inbuilt on the module
will calculate the time taken for the US wave to come back and turns on the echo pin
high for that same particular amount of time, this way we can also know the time
taken. Now simply calculate the distance using a microcontroller or microprocessor.
Applications
Used to avoid and detect obstacles with robots like biped robot, obstacle avoider
robot, path finding robot etc. Used to measure the distance within a wide range of 2cm
to 400cm. Can be used to map the objects surrounding the sensor by rotating it.
Page | 27
3.1.4. LCD 16x2
LCD display (shown in figure 3.12) is a device that can be used to display data
from our sensors, because we need sensors to be precise all the time displaying real
time value of sensor reading value is necessary and critical to improve and fix our
project miss or fault if it happened (It happened a lot).
For this project, we decided use a 16x2 LCD, is say, 16 columns and 2 rows.
Basically, the screen It will show two specific data, one in each row. In the primary
row will show the distance between the ultrasonic sensor and motor, and in the second
row we will show the value of the setpoint entered into through of the 4X4 keypad.
These LCD screens have a distribution of pins that are used to control it. One LCD
16X2 has 16 pins, these are: the first three (Vss, Vdd and v0) are feeding, these are
connected directly to the 5v that the arduino delivers; the pins 4, 5 and 6 (Rs, Rw,
Enable respectively) are the pins of control; pins 7, 8, 9, 10, 11, 12, 13 and 14 are the
pins that serve as communication channels between Arduino and the LCD to transmit
the desired data visualize; finally, pins 15 and 16 are used to feed the lighting of the
screen to. These pins are connect to the digital inputs / outputs of the arduino. It
should be noted that not all the aforementioned pins previously you need to connect to
Page | 28
the arduino. In this case, all the aforementioned previously minus the pins 7, 8, 9 and
10.
These pins are connected in case you need to transmit a large amount of data at
high speed, but in this case the data to be transmitted are few. It is good to note that to
vary the luminosity of the screen is used a potentiometer (connected between pins 15
and 16 of the LCD) that operates as resistance variable.
Pins Functions
Table 3. 2. Pins function of LCD16x2
Pin
Function Name
No
7 DB0
8 DB1
8-bit data pins
9 DB2
10 DB3
Page | 29
11 DB4
12 DB5
13 DB6
14 DB7
Page | 30
When you talk about “tuning” you are really referring to the calibration that must
be done to the system to be able to control it properly. This tuning is obtained when
the variables Kp, Ki and Kd have certain values that make the system reach a given
reference and stabilize in a certain time, while it is able to withstand external
disturbances. To achieve this tuning, matlab software was used.
When the engine stabilized at a height, we took all the distance data until the
moment the ultrasonic measurements stopped. This data is taken to matlab and stored
in a variable.
After doing this, the ident was called from the command window. Ident is a tool
used to identify the type of system based on the data delivered. This tool estimates
according to the data and delivers a transfer function according to the behavior of the
data. The block diagram is shown in figure 3.14
Page | 31
5
4 2
3
1
3.3. Applications
Here are some apllications of fuzzy logic controller :
CHAPTER 4
Control design for the tower copter system
Page | 32
Fuzzy logic is conceptually easy to understand. The mathematical concepts
behind fuzzy reasoning are very simple. Fuzzy logic is a more intuitive
approach without the far-reaching complexity.
Fuzzy logic is flexible. With any given system, it is easy to layer on more
functionality without starting again from scratch.
Fuzzy logic is tolerant of imprecise data. Everything is imprecise if you look
closely enough, but more than that, most things are imprecise even on careful
inspection. Fuzzy reasoning builds this understanding into the process rather
than tacking it onto the end.
Fuzzy logic can model nonlinear functions of arbitrary complexity. You can
create a fuzzy system to match any set of input-output data. This process is
made particularly easy by adaptive techniques like Adaptive Neuro-Fuzzy
Inference Systems (ANFIS), which are available in Fuzzy Logic Toolbox
software.
Fuzzy logic can be built on top of the experience of experts. In direct contrast
to neural networks, which take training data and generate opaque,
impenetrable models, fuzzy logic lets you rely on the experience of people
who already understand your system.
Fuzzy logic can be blended with conventional control techniques. Fuzzy
systems don't necessarily replace conventional control methods. In many cases
fuzzy systems augment them and simplify their implementation.
Fuzzy logic is based on natural language. The basis for fuzzy logic is the basis
for human communication. This observation underpins many of the other
statements about fuzzy logic. Because fuzzy logic is built on the structures of
qualitative description used in everyday language, fuzzy logic is easy to use.
The last statement is perhaps the most important one and deserves more
discussion. Natural language, which is used by ordinary people on a daily basis, has
been shaped by thousands of years of human history to be convenient and efficient.
Page | 33
Sentences written in ordinary language represent a triumph of efficient
communication
Page | 34
The surface view of the test which signifies like how the voltage is varying with
respect to the speed.
Page | 35
By adjusting the red line to left or right, The voltage will keep on varying to
corresponding to it.
Page | 36
The ultimate gain (Ku) is defined as 1/M, where M = the amplitude ratio, Ki= kp/Ti and
Kd= KpTd. These 3 parameters are used to establish the correction u(t) from the error
e(t) via the equation:
which has the following transfer function relationship between error and
controller output:
Experemental result :
Kp : Pink line
Kd : Blue line
Ki : Red line
Page | 37
As you can see, these values are the KP, KI and KD that make that system shown
in the graph (tower copter) be controlled. To change these variables, what was done
was to vary the behavior of the system (kp, ki, kd) so that it responded more or less
quickly as a function of time, or so that it did not have so much oscillation when
seeking stability after a disturbance. In our case, we look for values of KP, KI and KD
where the system will find the desired fast reference and counteract the overrun
(maximum peak) in about 10 seconds. Keep in mind that the system, being non-linear,
is very complicated to stabilize in a short time, since he needs a certain period to be
able to linearize.
CHAPTER 5
Conclusion and recommendation
Conclusion: For the successful development of the project, it was essential to collect
and analyze theoretical foundations related to intelligent control, in order to acquire a
clear and objective perspective of the issues, giving a correct approach to the design
and construction of an intelligent controller.
Fuzzy systems, including fuzzy logic and fuzzy set theory, provide a rich and
meaningful addtition to standard logic. The mathematics generated by these theories is
Page | 38
consistent, and fuzzy logic may be a generalization of classic logic. The applications
which may be generated from or adapted to fuzzy logic are wide-ranging, and provide
the opportunity for modeling of conditions which are inherently imprecisely defined,
despite the concernsof classical logicans. Many systems may be modeled, simulated,
and even replicated with the help of fuzzy systems, not the least of which is human
reasoning itself
As it has been seen during the development of this work, only a smart control (PID)
was implemented. This control was carried out in two stages, the first is to simulate
the process through the MATLAB platform and the other part was carried out in a
practical way through arduino iterations in order to find a good tuning of the system.
Only in the case of the practical way the answer is satisfactory, since they showed
closeness with the expected answers taken experimentally in the physical plant. As it
has been seen during the development of this work, only an intelligent control (PID)
was implemented. This control was carried out in two stages, the first is to simulate
the process through the MATLAB platform and the other part was carried out in a
practical way through arduino iterations in order to find a good tuning of the system.
Only in the case of the practical way the answer is satisfactory, since they showed
closeness with the expected answers taken experimentally in the physical plant.
At the time of testing the design of the PID controller in the real plant, it was found
unstable, to such an inconvenience, there was a need to implement an integrative
control to the design, which helps to eliminate the error between the process variable
and the Set-Point for the system to stabilize.
The brushless motor presented inconveniences when trying to rise to high altitude, due
to loss of current and potential in the connection, therefore the motor was not able to
reach the desired height or simply lost strength over time. To solve this problem, the
cables that left the source were exchanged for others of greater caliber and were
shorter to try to lose the minimum amount of current possible.
Page | 39
The design and construction of the system focused on finding in the market
components that allowed to give its own characteristics such as linearity, stiffness,
resistance, etc ... in its manufacture the design could be improved based on technical
tests that helped make the tower copter more efficient .
Closed loop control is a technique widely used in the industry because it is not
necessary to have very expensive components to exercise good control.
To achieve a successful tuning it is good to have a software such as matlab, which has
some tools such as IDENT and PID TUNER that allow you to optimize time when
finding the variables KP , KI and KD.
Recomendation:
Limitation of the current works: To perform a good control on the tower copter, it is
best to acquire components that are of a good material. for example, the rods that are
well calibrated, the bearings that are of good material and that are lubricated, thick
damping springs and of good material, a good design of the bases to grant rigidity and
stability, etc... When making Electrical connections, it is best to use good gauge
cables that allow no loss of current over time.
The ultrasonic sensor was sealed to prevent wind gusts from affecting the sensor
measurements. Cables were also welded to the pins to avoid possible noise in the
connections. In programming, an arrangement was made to save 20 readings at a
certain time and average these measurements to give the sensor greater accuracy.
The use of different software such as matlab, arduino allowed to make a very
complete design and without any additional cost, since these software can be used in
the uni versity. Similarly, the use of machines such as the 3D printer and the CNC
allowed rapid and efficient processing and construction of the components. Thanks to
all this we were able to meet the deadlines stipulated for the project.
Page | 40
Future work:
REFERENCES
1. Ziegler, J.G.; Nichols, N.B. Optimum settings for automatic controllers. Trans.
ASME 1942, 64, 759–768. [CrossRef]
Page | 41
4. Mudi, K.R.; Pal, R.N. A self-tuning fuzzy PI controller. Fuzzy Sets Syst. 2000, 115,
327–388. [CrossRef]
195. [CrossRef]
6. Chao, C.T.; Teng, C.C. A PD-like self-tuning fuzzy controller without steady-state
error. Fuzzy Sets Syst. 1997, 87, 141–154. [CrossRef].
8. Moon, B.S. Equivalence between fuzzy logic controllers and PI controllers for
single input systems. Fuzzy Sets Syst. 1995, 69, 105–113. [CrossRef]
9. Kang, C.S.; Hyun, C.H.; Kim, Y.T.; Baek, J.; Park, M. A design of equivalent PID
structure control using Fuzzy gain scheduling. In Proceedings of the 10th International
Conference on Ubiquitous Robots and Ambient Intelligence (URAI), Jeju, Korea, 30
October–2 November 2013; pp. 354–356.
10. Mann, G.K.I.; Hu, B.G.; Gosine, R.G. Analysis of direct action fuzzy PID
controller structures. IEEE Trans. Syst. Man Cybern. B 1999, 29, 371–388.
[CrossRef] [PubMed]
11. Hu, B.G.; Mann, G.K.I.; Gosine, R.G. A systematic study of fuzzy PID controller-
function-based evaluation approach. IEEE Trans. Fuzzy Syst. 2001, 9, 699–712.
Page | 42
Computational Technology (ICCICCT), Thuckalay, India, 18–19 December 2015; pp.
356–362.
13. Li, H.X.; Philip-Chen, C.L. The equivalence between fuzzy logic systems and
feedforward neural networks. IEEE Trans. Neural Netw. 2000, 11, 356–365.
[PubMed]
14. Chiou, J.S.; Tsai, S.H.; Liu, M.T. A PSO-based adaptive fuzzy PID- controllers.
Simul. Model. Pract. Theory 2012, 26, 49–59. [CrossRef]
15. Pelusi, D. PID and intelligent controllers for optimal timing performances of
industrial actuators. Int. J. Simul. Syst. Sci. Technol. 2012, 13, 65–71.
16. Pelusi, D.; Mascella, R. Optimal control algorithms for second order systems. J.
Comput. Sci. 2013, 9, 183–197. [CrossRef]
17. Ogata, K. Modern Control Engineering, 5th ed.; Prentice Hall: Upper Saddle
River, NJ, USA, 2010; p. 583.
APPENDIX
#include <Servo.h>
#include <LiquidCrystal.h>
#define trigPin 10
#define echoPin 9
#define button1 A0
#define button2 A1
Page | 43
#define button3 A2
#define button4 A3
char inChar;
int Tuning;
Servo brushless;
//----variables sensor------- //
long distance;
long duration;
int baca[nbaca];
int index = 0;
int total = 0;
int media = 0;
//-----variables PID--------- //
double timelast = 0;
double error = 0;
double errorlast = 0;
double p = 0;
double i = 0;
double d = 0;
Page | 44
double out_val;
float kp = 0.005;
float ki = 0.0003;
float kd = 0.039;
double nlast = 0;
double setpoint = 0;
double pv = 0;
int mv = 0;
double out = 0;
double input = 0;
void setup(){
Serial.begin(115200);
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("Distance=");
Page | 45
lcd.setCursor(0,1);
lcd.print("Setpoint=");
brushless.writeMicroseconds(start);
delay(1000);
void loop(){
digitalWrite(trigPin ,LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(5);
digitalWrite(trigPin, LOW);
bt1 = digitalRead(button1);
bt2 = digitalRead(button2);
bt3 = digitalRead(button3);
bt4 = digitalRead(button4);
distance = int(duration/2/29.412);
baca[index] = distance;
index = index+1;
index = 0;
Page | 46
media = total/nbaca;
pid();
brushless.writeMicroseconds(mv);
delay(10);
Serial.print(setpoint);
Serial.print("\t");
Serial.print(media);
Serial.print("\t");
Serial.print(input);
Serial.print("\t");
Serial.print(out);
Serial.print("\t");
Serial.print(error);
Serial.print("\t");
Serial.println(mv);
//--------------------------------------------
lcd.setCursor(0,0); //
lcd.print("Distance=");
lcd.setCursor(11,0);
lcd.print(media);
lcd.print(" cm");
delay(50);
Page | 47
if(bt1 == 0){
lcd.clear();
setpoint = 25;
lcd.setCursor(0,1);
lcd.print("Setpoint=");
lcd.setCursor(9,1);
lcd.print(setpoint);
lcd.print("%");
if(bt2 == 0){
lcd.clear();
setpoint = 50;
lcd.setCursor(0,1);
lcd.print("Setpoint=");
lcd.setCursor(9,1);
lcd.print(setpoint);
lcd.print("%");
if(bt3 == 0){
lcd.clear();
setpoint = 75;
lcd.setCursor(0,1);
lcd.print("Setpoint=");
lcd.setCursor(9,1);
Page | 48
lcd.print(setpoint);
lcd.print("%");
if(bt4 == 0){
lcd.clear();
setpoint = 100;
lcd.setCursor(0,1);
lcd.print("Setpoint=");
lcd.setCursor(9,1);
lcd.print(setpoint);
lcd.print("%");
void pid(){
error = setpoint-input;
p = (kp*error);
i = ki*((timelatest*errorlast)+(timelatest*((error-errorlast)/2)));
d = kd *((error-errorlast)/timelatest);
out_val = p+i+d;
out+= out_val+nlast;
if (out >90){
out=90;
if (out <0){
Page | 49
out=0;
errorlast=error;
nlast=i;
Page | 50