You are on page 1of 43

Proyecto Control P+I+D

Objetivo.- Basado en este proyecto construir prototipo de regulacin de velocidad de


motor empleando encoder ptico como sensor de velocidad, y realiar su calibracin de
par!metros de los modos de control "#intoniacin$.
% &rduino 'no (eeps )eader O **set
Improving t+e Beginner,s PID - #ample .ime /
Improving the Beginners PID Introduction
In conjunction 0it+ t+e release o* t+e ne0 &rduino PID 1ibrary I,ve decided to release
t+is series o* posts. .+e last library, 0+ile solid, didn,t really come 0it+ any code
e2planation. .+is time around t+e plan is to e2plain in great detail 0+y t+e code is t+e
0ay it is. I,m +oping t+is 0ill be o* use to t0o groups o* people3
People directly interested in 0+at,s going on inside t+e &rduino PID library 0ill
get a detailed e2planation.
&nyone 0riting t+eir o0n PID algorit+m can ta4e a loo4 at +o0 I did t+ings and
borro0 0+atever t+ey li4e.
It,s going to be a toug+ slog, but I t+in4 I *ound a not-too-pain*ul 0ay to e2plain my
code. I,m going to start 0it+ 0+at I call 5.+e Beginner,s PID.6 I,ll t+en improve it
step-by-step until 0e,re le*t 0it+ an e**icient, robust pid algorit+m.
The Beginners PID
)ere,s t+e PID e7uation as everyone *irst learns it3
.+is leads pretty muc+ everyone to 0rite t+e *ollo0ing PID controller3
8
9
:
;
<
=
>
?
@
8A
88
89
8:
/*working variables*/
unsigned long lastTime;
double Input, Output, Setpoint;
double errSum, lastErr;
double kp, ki, kd;
void Compute()

/*!ow long sin"e we last "al"ulated*/
unsigned long now # millis();
double timeC$ange # (double)(now % lastTime);

/*Compute all t$e working error variables*/
double error # Setpoint % Input;
errSum &# (error * timeC$ange);
double dErr # (error % lastErr) / timeC$ange;
8;
8<
8=
8>
8?
8@
9A
98
99
9:
9;
9<
9=
9>
9?
9@
:A

/*Compute 'I( Output*/
Output # kp * error & ki * errSum & kd * dErr;

/*)emember some variables *or ne+t time*/
lastErr # error;
lastTime # now;
,

void SetTunings(double -p, double -i, double -d)

kp # -p;
ki # -i;
kd # -d;
,
Compute"$ is called eit+er regularly or irregularly, and it 0or4s pretty 0ell. .+is series
isn,t about 50or4s pretty 0ell6 t+oug+. I* 0e,re going to turn t+is code into somet+ing
on par 0it+ industrial PID controllers, 0e,ll +ave to address a *e0 t+ings3
8. Sample Time - .+e PID algorit+m *unctions best i* it is evaluated at a regular
interval. I* t+e algorit+m is a0are o* t+is interval, 0e can also simpli*y some o*
t+e internal mat+.
9. Derivative Kick - Bot t+e biggest deal, but easy to get rid o*, so 0e,re going to
do just t+at.
:. On-The-Fl Tuning !hanges - & good PID algorit+m is one 0+ere tuning
parameters can be c+anged 0it+out jolting t+e internal 0or4ings.
;. "eset #indup $itigation -Ce,ll go into 0+at Deset Cindup is, and implement
a solution 0it+ side bene*its
<. On%O&& '(uto%$anual) - In most applications, t+ere is a desire to sometimes
turn o** t+e PID controller and adjust t+e output by +and, 0it+out t+e controller
inter*ering
=. Initiali*ation - C+en t+e controller *irst turns on, 0e 0ant a 5bumpless
trans*er.6 .+at is, 0e don,t 0ant t+e output to suddenly jer4 to some ne0 value
>. !ontroller Direction - .+is last one isn,t a c+ange in t+e name o* robustness per
se. it,s designed to ensure t+at t+e user enters tuning parameters 0it+ t+e correct
sign.
Once 0e,ve addressed all t+ese issues, 0e,ll +ave a solid PID algorit+m. Ce,ll also, not
coincidentally, +ave t+e code t+at,s being used in t+e lastest version o* t+e &rduino PID
1ibrary. #o 0+et+er you,re trying to 0rite your o0n algorit+m, or trying to understand
0+at,s going on inside t+e PID library, I +ope t+is +elps you out. 1et,s get started.
Be2t EE
'PD&.F3 In all t+e code e2amples I,m using doubles. On t+e &rduino, a double is t+e
same as a *loat "single precision.$ .rue double precision is C&G over4ill *or PID. I* t+e
language you,re using does true double precision, I,d recommend c+anging all doubles
to *loats.
.
http://www.arduino.cc/playground/Code/PIDLibrary
PID Library
/********************************************************
* 'I( .asi" E+ample
* )eading analog input / to "ontrol analog '01 output 2
********************************************************/
3in"lude 4'I(5v67$8
//(e*ine 9ariables we:ll be "onne"ting to
double Setpoint, Input, Output;
//Spe"i*; t$e links and initial tuning parameters
'I( m;'I((<Input, <Output, <Setpoint,=,>,6, (I)ECT);
void setup()

//initiali?e t$e variables we:re linked to


Input # analog)ead(/);
Setpoint # 6//;
//turn t$e 'I( on
m;'I(7Set1ode(@ATO1@TIC);
,
void loop()

Input # analog)ead(/);
m;'I(7Compute();
analog0rite(2,Output);
,

PID Library
/********************************************************
* 'I( @daptive Tuning E+ample
* One o* t$e bene*its o* t$e 'I( librar; is t$at ;ou "an
* "$ange t$e tuning parameters at an; time7 t$is "an be
* $elp*ul i* we want t$e "ontroller to be agressive at some
* times, and "onservative at ot$ers7 in t$e e+ample below
* we set t$e "ontroller to use Conservative Tuning 'arameters
* w$en we:re near setpoint and more agressive Tuning
* 'arameters w$en we:re *art$er awa;7
********************************************************/
3in"lude 4'I(5v67$8
//(e*ine 9ariables we:ll be "onne"ting to
double Setpoint, Input, Output;
//(e*ine t$e aggressive and "onservative Tuning 'arameters
double agg-p#B, agg-i#/7=, agg-d#6;
double "ons-p#6, "ons-i#/7/>, "ons-d#/7=>;
//Spe"i*; t$e links and initial tuning parameters
'I( m;'I((<Input, <Output, <Setpoint, "ons-p, "ons-i, "ons-d, (I)ECT);
void setup()

//initiali?e t$e variables we:re linked to


Input # analog)ead(/);
Setpoint # 6//;
//turn t$e 'I( on
m;'I(7Set1ode(@ATO1@TIC);
,
void loop()

Input # analog)ead(/);
double gap # abs(Setpoint%Input); //distan"e awa; *rom setpoint
i*(gap46/)
//we:re "lose to setpoint, use "onservative tuning parameters
m;'I(7SetTunings("ons-p, "ons-i, "ons-d);
,
else

//we:re *ar *rom setpoint, use aggressive tuning parameters
m;'I(7SetTunings(agg-p, agg-i, agg-d);
,
m;'I(7Compute();
analog0rite(2,Output);
,
Como ya sabrn la mayora de los que leen este blog a diario, el algoritmo PID
(o Proporcional Integral Derivativo), es un elemento bastante usado en
sistemas autmatas (de una manera u otra), en los cuales este algoritmo cobra
bastante importancia en las funciones de realimentacin, adems de provocar
que la curva de respuesta sea muc!o mas suave que si usamos un sistema
alternativo"
#a idea es !aceros un poco de resumen sobre el panorama de libreras ya
dise$adas que nos permitan crear un control PID sencillo (relativamente), sin
tener que programarlo desde %"
&rduino no se queda atrs'
(l PID tiene una frmula, ecuacin, e)presin, que nos permite calcular los
parmetros de salida, a partir de unos dados, bsicamente es esta*
+ a!ora, vaymonos con la lib de arduino'
ARDUINO PID LIBRARY
Cita de ,i-ipedia
"Un PID (Proporcional Integral Derivativo) es un mecanismo de control
por realimentacin que calcula la desviacin o error entre un valor medido y el
valor que se quiere obtener, para aplicar una accin correctora que ajuste el
proceso."
Funciones
PID()
Compute()
.et/ode()
.et0utput#imits()
.et1unings()
.et.ample1ime()
.etControllerDirection()
Ejemplo bsico:
view plain copy to clipboard print ?
1. /********************************************************
2. * PID Baic !"a#ple
$. * %eading analog input & to control analog P'( output $
). ********************************************************/
*.
+. ,include
-.
.. //De/ne 0ariable we1ll be connecting to
2. double 3etpoint4 Input4 5utput6
1&.
11. //3peci7y the lin8 and initial tuning para#eter
12. PID #yPID9:Input4 :5utput4 :3etpoint424*414 DI%!C;<6
1$.
1). void etup9<
1*. =
1+. //initiali>e the ?ariable we1re lin8ed to
1-. Input @ analog%ead9&<6
1.. 3etpoint @ 1&&6
12.
2&. //turn the PID on
21. #yPID.3et(ode9AB;5(A;IC<6
22. C
2$.
2). void loop9<
2*. =
2+. Input @ analog%ead9&<6
2-. #yPID.Co#pute9<6
2.. analog'rite9$45utput<6
22. C
Enlaces
Descarga la 2ltima versin
Pgina de e3emplos
Pgina oficial en bac-ground de &rduino (Con 4 e3emplos mas')
()plicacon de la librera y el PID por el autor de dic!a libreria
DDDDDDDDDDDDDDDDD
Programa e ejemplo e con!rol PID en "B#
Publicado por 0scar 5on6ale6 en Programacin el %78%484%99 (97*:%)
E!i$ue!as: programa, e3emplo, pid, vb;, quadcopter
" < comentarios
.i ests desarrollando un quadcopter pero te encuentras ya con el "problema" de la calibracin del control
PID ests de suerte" =e encontrado un interesante enlace al cdigo fuente de un peque$o programa
!ec!o en >isual ?asic ; que muestra en todo su esplendor cmo funciona un control PID"
@n PID (Proporcional Integral Derivativo) es un mecanismo de control por realimentacin que calcula la
desviacin o error entre un valor medido y el valor que se quiere obtener" (s bsicamente lo que se utili6a
para la estabili6acin de quadcopters, !e)acopters etc" Para entender cmo funciona y sobre todo cmo
reacciona cambiando sus parmetros de control, la aplicacin simula un tanque con una entrada de
lquido, una salida y un nivel de lquido que queremos mantener" (n funcin del calculo y modificacin de
las tres variables del PID (Proporcional, Integral y Derivada), podremos ver las distintas respuestas del
algoritmo y entenderemos quA !ace cada parmetro" (s interesante ver la respuesta del ciclo de
llenado8vaciado seg2n vamos modificando las variables y nos puede dar una idea de la respuesta que
queremos para nuestro ob3eto volador"
Bo os perdais el enlace y ya me contareis quA tal' C)
Enlace: Control PID >?;
"ersi%n compilaa: pidvb;"rar
Diagrama en bloques de un control PID" Cortesa de Di-ipedia
.
PID &Propor!ional'
In!egral' Deri(a!i(e) Loop
*imula!ion
Au!+or: /a) .eim
,a!egor-: /iscellaneous
.-pe: &pplications
Di//icul!-: Intermediate
"ersion
,ompa!ibili!-:
Visual Basic 5 Visual
Basic 6
0ore in/orma!ion: 1!is is a simplied PID #oop
simulator for industrial process control, in t!is
e)ample, a ,ater tan- ,it! PID #oop level control"
1!e model ,as designed for students to learn !o, industrial processes are controlled using computers"
@sers can manipulate t!e valves (manual or auto), and c!ange PID values to alter t!e control of t!e ,ater
tan-" Eor >? education, t!ere are slider controls, form grap!ics, and realtime grap!ing e)amples" I !ope
users find t!is program useful"
1!is code !as been vie,ed 12312 times"
http://www.7ree?bcode.co#/3howCode.apEID@$.&.
Proporcional integral derivativo
De 'i8ipedia4 la enciclopedia libre
3altar a: na?egaciFn4 bGHueda
'n PID "Proporcional Integral Derivativo$ es un mecanismo de control por
realimentacin 7ue calcula la desviacin o error entre un valor medido y el valor 7ue se
7uiere obtener, para aplicar una accin correctora 7ue ajuste el proceso. Fl algoritmo de
c!lculo del control PID se da en tres par!metros distintos3 el proporcional, el integral, y
el derivativo. Fl valor Proporcional determina la reaccin del error actual. Fl Integral
genera una correccin proporcional a la integral del error, esto nos asegura 7ue
aplicando un es*uero de control su*iciente, el error de seguimiento se reduce a cero. Fl
Derivativo determina la reaccin del tiempo en el 7ue el error se produce. 1a suma de
estas tres acciones es usada para ajustar al proceso vHa un elemento de control como la
posicin de una v!lvula de control o la energHa suministrada a un calentador, por
ejemplo. &justando estas tres variables en el algoritmo de control del PID, el
controlador puede proveer un control diseIado para lo 7ue re7uiera el proceso a realiar.
1a respuesta del controlador puede ser descrita en tJrminos de respuesta del control ante
un error, el grado el cual el controlador llega al Kset pointK, y el grado de oscilacin del
sistema. Btese 7ue el uso del PID para control no garantia control ptimo del sistema
o la estabilidad del mismo. &lgunas aplicaciones pueden solo re7uerir de uno o dos
modos de los 7ue provee este sistema de control. 'n controlador PID puede ser llamado
tambiJn PI, PD, P o I en la ausencia de las acciones de control respectivas. 1os
controladores PI son particularmente comunes, ya 7ue la accin derivativa es muy
sensible al ruido, y la ausencia del proceso integral puede evitar 7ue se alcance al valor
deseado debido a la accin de control.
Diagra#a en bloHue de un control PID.
!ontenido
IocultarJ
1 Kunciona#iento
o 1.1 Proporcional
o 1.2 Integral
o 1.$ Deri?ati?o
2 3igni/cado de la contante
$ Bo
) ALute de parM#etro del PID
o ).1 ALute #anual
* Li#itacione de un control
PID
+ !Le#plo prMctico
- Aplicacione / !Le#plo
. %e7erencia
2 !nlace e"terno
Funcionamiento
Para el correcto *uncionamiento de un controlador PID 7ue regule un proceso o sistema
se necesita, al menos3
1. Bn enor4 Hue deter#ine el etado del ite#a 9ter#F#etro4
caudalN#etro4#anF#etro4 etc<.
2. Bn controlador4 Hue genere la eOal Hue gobierna al actuador.
$. Bn actuador4 Hue #odi/Hue al ite#a de #anera controlada
9reitencia elPctrica4 #otor4 ?Ml?ula4 bo#ba4 etc<.
Fl sensor proporciona una seIal analgica o digital al controlador, la cual representa el
punto actual en el 7ue se encuentra el proceso o sistema. 1a seIal puede representar ese
valor en tensin elJctrica, intensidad de corriente elJctrica o *recuencia. Fn este Lltimo
caso la seIal es de corriente alterna, a di*erencia de los dos anteriores, 7ue son con
corriente continua.
Fl controlador lee una seIal e2terna 7ue representa el valor 7ue se desea alcanar. Fsta
seIal recibe el nombre de punto de consigna "o punto de re*erencia$, la cual es de la
misma naturalea y tiene el mismo rango de valores 7ue la seIal 7ue proporciona el
sensor. Para +acer posible esta compatibilidad y 7ue, a su ve, la seIal pueda ser
entendida por un +umano, +abr! 7ue establecer algLn tipo de inter*a")MI-)uman
Mac+ine Inter*ace$, son pantallas de gran valor visual y *!cil manejo 7ue se usan para
+acer m!s intuitivo el control de un proceso.
Fl controlador resta la seIal de punto actual a la seIal de punto de consigna, obteniendo
asH la seIal de error, 7ue determina en cada instante la di*erencia 7ue +ay entre el valor
deseado "consigna$ y el valor medido. 1a seIal de error es utiliada por cada uno de los
: componentes del controlador PID. 1as : seIales sumadas, componen la seIal de
salida 7ue el controlador va a utiliar para gobernar al actuador. 1a seIal resultante de la
suma de estas tres se llama varia+le manipulada y no se aplica directamente sobre el
actuador, sino 7ue debe ser trans*ormada para ser compatible con el actuador utiliado.
1as tres componentes de un controlador PID son3 parte Proporcional, accin Integral y
accin Derivativa. Fl peso de la in*luencia 7ue cada una de estas partes tiene en la suma
*inal, viene dado por la constante proporcional, el tiempo integral y el tiempo
derivativo, respectivamente. #e pretender! lograr 7ue el bucle de control corrija
e*icamente y en el mHnimo tiempo posible los e*ectos de las perturbaciones.
Proporcional
Artculo principal: Control proporcional
Proporcional.
1a parte proporcional consiste en el producto entre la seIal de error y la constante
proporcional como para 7ue +agan 7ue el error en estado estacionario sea casi nulo,
pero en la mayorHa de los casos, estos valores solo ser!n ptimos en una determinada
porcin del rango total de control, siendo distintos los valores ptimos para cada
porcin del rango. #in embargo, e2iste tambiJn un valor lHmite en la constante
proporcional a partir del cual, en algunos casos, el sistema alcana valores superiores a
los deseados. Fste *enmeno se llama sobreoscilacin y, por raones de seguridad, no
debe sobrepasar el :AN, aun7ue es conveniente 7ue la parte proporcional ni si7uiera
produca sobreoscilacin. )ay una relacin lineal continua entre el valor de la variable
controlada y la posicin del elemento *inal de control "la v!lvula se mueve al mismo
valor por unidad de desviacin$. 1a parte proporcional no considera el tiempo, por lo
tanto, la mejor manera de solucionar el error permanente y +acer 7ue el sistema
contenga alguna componente 7ue tenga en cuenta la variacin respecto al tiempo, es
incluyendo y con*igurando las acciones integral y derivativa.
1a *rmula del proporcional esta dada por3
Fl error, la banda proporcional y la posicin inicial del elemento *inal de control se
e2presan en tanto por uno. Bos indicar! la posicin 7ue pasar! a ocupar el elemento
*inal de control
Fjemplo3 Cambiar la posicin de una v!lvula "elemento *inal de control$
proporcionalmente a la desviacin de la temperatura "variable$ respecto al punto de
consigna "valor deseado$.
Integral
Artculo principal: proporcional integral
Integral.
Fl modo de control Integral tiene como propsito disminuir y eliminar el error en estado
estacionario, provocado por el modo proporcional. Fl control integral actLa cuando +ay
una desviacin entre la variable y el punto de consigna, integrando esta desviacin en el
tiempo y sum!ndola a la accin proporcional. Fl error es integrado, lo cual tiene la
*uncin de promediarlo o sumarlo por un perHodo determinadoO 1uego es multiplicado
por una constante I. Posteriormente, la respuesta integral es adicionada al modo
Proporcional para *ormar el control P + I con el propsito de obtener una respuesta
estable del sistema sin error estacionario.
Fl modo integral presenta un des*asamiento en la respuesta de @AP 7ue sumados a los
8?AP de la retroalimentacin " negativa $ acercan al proceso a tener un retraso de 9>AP,
luego entonces solo ser! necesario 7ue el tiempo muerto contribuya con @AP de retardo
para provocar la oscilacin del proceso. QQQ la ganancia total del lao de control debe
ser menor a 8, y asH inducir una atenuacin en la salida del controlador para conducir el
proceso a estabilidad del mismo. EEE #e caracteria por el tiempo de accin integral en
minutos por repeticin. Fs el tiempo en 7ue delante una seIal en escaln, el elemento
*inal de control repite el mismo movimiento correspondiente a la accin proporcional.
Fl control integral se utilia para obviar el inconveniente del o**set "desviacin
permanente de la variable con respecto al punto de consigna$ de la banda proporcional.
1a *ormula del integral esta dada por3
Fjemplo3 Mover la v!lvula "elemento *inal de control$ a una velocidad proporcional a la
desviacin respeto al punto de consigna "variable deseada$.
Derivativo
Artculo principal: proporcional derivativo
Deri?ati?o.
1a accin derivativa se mani*iesta cuando +ay un cambio en el valor absoluto del errorO
"si el error es constante, solamente actLan los modos proporcional e integral$.
Fl error es la desviacin e2istente entre el punto de medida y el valor consigna, o KSet
PointK.
1a *uncin de la accin derivativa es mantener el error al mHnimo corrigiJndolo
proporcionalmente con la misma velocidad 7ue se produceO de esta manera evita 7ue el
error se incremente.
#e deriva con respecto al tiempo y se multiplica por una constante D y luego se suma a
las seIales anteriores "P+I$. Fs importante adaptar la respuesta de control a los cambios
en el sistema ya 7ue una mayor derivativa corresponde a un cambio m!s r!pido y el
controlador puede responder acordemente.
1a *rmula del derivativo esta dada por3
Fl control derivativo se caracteria por el tiempo de accin derivada en minutos de
anticipo. 1a accin derivada es adecuada cuando +ay retraso entre el movimiento de la
v!lvula de control y su repercusin a la variable controlada.
Cuando el tiempo de accin derivada es grande, +ay inestabilidad en el proceso. Cuando
el tiempo de accin derivada es pe7ueIo la variable oscila demasiado con relacin al
punto de consigna. #uele ser poco utiliada debido a la sensibilidad al ruido 7ue
mani*iesta y a las complicaciones 7ue ello conlleva.
Fl tiempo ptimo de accin derivativa es el 7ue retorna la variable al punto de consigna
con las mHnimas oscilaciones
Fjemplo3 Corrige la posicin de la v!lvula "elemento *inal de control$
proporcionalmente a la velocidad de cambio de la variable controlada.
1a accin derivada puede ayudar a disminuir el rebasamiento de la variable durante el
arran7ue del proceso. Puede emplearse en sistemas con tiempo de retardo considerables,
por7ue permite una repercusin r!pida de la variable despuJs de presentarse una
perturbacin en el proceso.
Signi&icado de las constantes
P constante de proporcionalidad3 se puede ajustar como el valor de la ganancia del
controlador o el porcentaje de banda proporcional. Fjemplo3 Cambia la posicin de la
v!lvula proporcionalmente a la desviacin de la variable respecto al punto de consigna.
1a seIal P mueve la v!lvula siguiendo *ielmente los cambios de temperatura
multiplicados por la gan!ncia.
I constante de integracin3 indica la velocidad con la 7ue se repite la accin
proporcional.
D constante de derivacin3 +ace presente la respuesta de la accin proporcional
duplic!ndola, sin esperar a 7ue el error se dupli7ue. Fl valor indicado por la constante
de derivacin es el lapso de tiempo durante el cual se mani*estar! la accin proporcional
correspondiente a 9 veces el error y despuJs desaparecer!. Fjemplo3 Mueve la v!lvula a
una velocidad proporcional a la desviacin respeto al punto de consigna. 1a seIal I va
sumando las !reas di*erentes entre la variable y el punto de consigna repitiendo la seIal
proporcional segLn el tiempo de accin derivada "minutosRrepeticin$.
.anto la accin Integral como la accin Derivativa, a*ectan a la ganancia din!mica del
proceso. 1a accin integral sirve para reducir el error estacionario, 7ue e2istirHa siempre
si la constante (i *uera nula. Fjemplo3 Corrige la posicin de la v!lvula
proporcionalmente a la velocidad de cambio de la variable controlada. 1a seIal d es la
pendiente "tangente$ por la curva descrita por la variable.
1a salida de estos tres tJrminos, el proporcional, el integral, y el derivativo son sumados
para calcular la salida del controlador PID. De*iniendo u "t$ como la salida del
controlador, la *orma *inal del algoritmo del PID es3
,sos
Por tener una e2actitud mayor a los controladores proporcional, proporcional derivativo
y proporcional integral se utilia en aplicaciones m!s cruciales tales como control de
presin, *lujo,*uera, velocidad, en muc+as aplicaciones 7uHmica, y otras variables.
&dem!s es utiliado en reguladores de velocidad de automviles "control de crucero o
cruise control$, control de oono residual en tan7ues de contacto.
(-uste de par.metros del PID
Fl objetivo de los ajustes de los par!metros PID es lograr 7ue el bucle de control corrija
e*icamente y en el mHnimo tiempo los e*ectos de las perturbacionesO se tiene 7ue lograr
la mHnima integral de error. #i los par!metros del controlador PID "la ganancia del
proporcional, integral y derivativo$ se eligen incorrectamente, el proceso a controlar
puede ser inestable, por ejemplo, 7ue la salida de este varHe, con o sin oscilacin, y est!
limitada solo por saturacin o rotura mec!nica. &justar un lao de control signi*ica
ajustar los par!metros del sistema de control a los valores ptimos para la respuesta del
sistema de control deseada. Fl comportamiento ptimo ante un cambio del proceso o
cambio del KsetpointK varHa dependiendo de la aplicacin. Seneralmente, se re7uiere
estabilidad ante la respuesta dada por el controlador, y este no debe oscilar ante ninguna
combinacin de las condiciones del proceso y cambio de KsetpointsK. &lgunos procesos
tienen un grado de no-linealidad y algunos par!metros 7ue *uncionan bien en
condiciones de carga m!2ima no *uncionan cuando el proceso est! en estado de Ksin
cargaK. )ay varios mJtodos para ajustar un lao de PID. Fl mJtodo m!s e*ectivo
generalmente re7uiere del desarrollo de alguna *orma del modelo del proceso, luego
elegir P, I y D bas!ndose en los par!metros del modelo din!mico. 1os mJtodos de ajuste
manual pueden ser muy ine*icientes. 1a eleccin de un mJtodo depender! de si el lao
puede ser KdesconectadoK para ajustarlo, y del tiempo de respuesta del sistema. #i el
sistema puede desconectarse, el mejor mJtodo de ajuste a menudo es el de ajustar la
entrada, midiendo la salida en *uncin del tiempo, y usando esta respuesta para
determinar los par!metros de control. &+ora describimos como realiar un ajuste
manual.
(-uste manual
#i el sistema debe mantenerse online, un mJtodo de ajuste consiste en establecer
primero los valores de I y D a cero. & continuacin, incremente P +asta 7ue la salida del
lao oscile. 1uego estableca P a apro2imadamente la mitad del valor con*igurado
previamente. DespuJs incremente I +asta 7ue el proceso se ajuste en el tiempo re7uerido
"aun7ue subir muc+o I puede causar inestabilidad$. Tinalmente, incremente D, si se
necesita, +asta 7ue el lao sea lo su*icientemente r!pido para alcanar su re*erencia tras
una variacin brusca de la carga.
'n lao de PID muy r!pido alcana su setpoint de manera velo. &lgunos sistemas no
son capaces de aceptar este disparo bruscoO en estos casos se re7uiere de otro lao con
un P menor a la mitad del P del sistema de control anterior.
/imitaciones de un control PID
Mientras 7ue los controladores PID son aplicables a la mayorHa de los problemas de
control, puede ser pobres en otras aplicaciones. 1os controladores PID, cuando se usan
solos, pueden dar un desempeIo pobre cuando la ganancia del lao del PID debe ser
reducida para 7ue no se dispare u oscile sobre el valor del "setpoint". Fl desempeIo del
sistema de control puede ser mejorado combinando el lao cerrado de un control PID
con un lao abierto. Conociendo el sistema "como la aceleracin necesaria o la inercia$
puede ser avanaccionado y combinado con la salida del PID para aumentar el
desempeIo *inal del sistema. #olamente el valor de avanaccin "o Control
prealimentado$ puede proveer la mayor porcin de la salida del controlador. Fl
controlador PID puede ser usado principalmente para responder a cual7uier di*erencia o
KerrorK 7ue 7uede entre el setpoint y el valor actual del proceso. Como la salida del lao
de avanaccin no se ve a*ectada a la realimentacin del proceso, nunca puede causar
7ue el sistema oscile, aumentando el desempeIo del sistema, su respuesta y estabilidad.
Por ejemplo, en la mayorHa de los sistemas de control con movimiento, para acelerar una
carga mec!nica, se necesita de m!s *uera "o torque$ para el motor. #i se usa un lao
PID para controlar la velocidad de la carga y manejar la *uera o tor7ue necesaria para
el motor, puede ser Ltil tomar el valor de aceleracin instant!nea deseada para la carga,
y agregarla a la salida del controlador PID. Fsto signi*ica 7ue sin importar si la carga
est! siendo acelerada o desacelerada, una cantidad proporcional de fuerza est! siendo
manejada por el motor adem!s del valor de realimentacin del PID. Fl lao del PID en
esta situacin usa la in*ormacin de la realimentacin para incrementar o decrementar la
di*erencia entre el setpoint y el valor del primero. .rabajando juntos, la combinacin
avanaccin-realimentacin provee un sistema m!s con*iable y estable.
Otro problema 7ue posee el PID es 7ue es lineal. Principalmente el desempeIo de los
controladores PID en sistemas no lineales es variable. .ambiJn otro problema comLn
7ue posee el PID es, 7ue en la parte derivativa, el ruido puede a*ectar al sistema,
+aciendo 7ue esas pe7ueIas variaciones, +agan 7ue el cambio a la salida sea muy
grande. Seneralmente un Tiltro pasa bajo ayuda, ya 7ue removerHa las componentes de
alta *recuencia del ruido. #in embargo, un TPB y un control derivativo pueden +acer 7ue
se anulen entre ellos. &lternativamente, el control derivativo puede ser sacado en
algunos sistemas sin muc+a pJrdida de control. Fsto es e7uivalente a usar un
controlador PID como PI solamente.
0-emplos pr.cticos
#e desea controlar el caudal de un *lujo de entrada en un reactor 7uHmico. Fn primer
lugar se tiene 7ue poner una v!lvula de control del caudal de dic+o *lujo, y un
caudalHmetro, con la *inalidad de tener una medicin constante del valor del caudal 7ue
circule. Fl controlador ir! vigilando 7ue el caudal 7ue circule sea el establecido por
nosotrosO en el momento 7ue detecte un error, mandar! una seIal a la v!lvula de control
de modo 7ue esta se abrir! o cerrar! corrigiendo el error medido. G tendremos de ese
modo el *lujo deseado y necesario. Fl PID es un c!lculo matem!tico, lo 7ue envHa la
in*ormacin es el P1C.
#e desea mantener la temperatura interna de un reactor 7uHmico en su valor de
re*erencia. #e debe tener un dispositivo de control de la temperatura "puede ser un
calentador, una resistJncia elJctrica,...$, y un sensor "termmetro$. Fl P, PI o PID ir!
controlando la variable "en este caso la temperatura$. Fn el instante 7ue esta no sea la
correcta avisar! al dispositivo de control de manera 7ue este actLe, corrigiendo el error.
De todos modos, lo m!s correcto es poner un PIDO si +ay muc+o ruido, un PI, pero un P
no nos sirve muc+o puesto 7ue no llegarHa a corregir +asta el valor e2acto.
(plicaciones % 0-emplo
'n ejemplo muy sencillo 7ue ilustra la *uncionalidad b!sica de un PID es cuando una
persona entra a una duc+a. Inicialmente abre la llave de agua caliente para aumentar la
temperatura +asta un valor aceptable "tambiJn llamado K#etpointK$. Fl problema es 7ue
puede llegar el momento en 7ue la temperatura del agua sobrepase este valor asH 7ue la
persona tiene 7ue abrir un poco la llave de agua *rHa para contrarrestar el calor y
mantener el balance. Fl agua *rHa es ajustada +asta llegar a la temperatura deseada. Fn
este caso, el +umano es el 7ue est! ejerciendo el control sobre el lao de control, y es el
7ue toma las decisiones de abrir o cerrar alguna de las llavesO pero no serHa ideal si en
lugar de nosotros, *uera una ma7uina la 7ue tomara las decisiones y mantuviera la
temperatura 7ue deseamosU
Fsta es la ran por la cual los laos PID *ueron inventados. Para simpli*icar las labores
de los operadores y ejercer un mejor control sobre las operaciones. &lgunas de las
aplicaciones m!s comunes son3
La>o de ;e#peratura 9Aire acondicionado4 Calentadore4
%e7rigeradore4 etc.<
La>o de Qi?el 9Qi?el en tanHue de lNHuido co#o agua4 lMcteo4
#e>cla4 crudo4 etc.<
La>o de PreiFn 9para #antener una preiFn predeter#inada en
tanHue4 tubo4 recipiente4 etc.<
La>o de KluLo 9#antienen la cantidad de RuLo dentro de una lNnea o
tubo<
1

L298 DC Motor Control: Hardware
The H-Bridge
The original concept of the H-Bridge was being able to control the direction a
motor was going. Forward or backward. This was achieed by managing c!rrent flow
thro!gh circ!it elements called transistors. The formation looks like an H and that"s
where it gets the name H-Bridge. Here is what it looks like#
The pict!re aboe ill!strates the $ base cases that we can get o!t of the simple
ersion of an H-Bridge. The two cases that interest !s are when % & D are both ' and
when B & ( are both '.
)hen % & D are ' c!rrent from the battery will flow from point % thro!gh the
motor to D"s gro!nd. Howeer for the case when B & ( are both '* c!rrent will flow in
the opposite direction from B thro!gh the motor to ("s gro!nd.
LMD18245 Pinout
The L298HN Motor Drier
To the right yo!"ll see a sample of what the H-Bridge we"ll be working with looks
like with each pin labeled. For a complete description of what each pin does check o!t
the datasheet at st.com.
The adantage that the H+ offers is that all the e,tra diodes typically necessary
with a standard L298 circ!it are already internally in the chip. It saes !s as designers
an e,tra element for the motor control circ!it.
!ar"ing DC Motor #$eed
Pins - & . in the chip pino!t aboe are inp!ts ' & / respectiely. These inp!ts
take what is called a P)0 inp!t. The fre1!ency of the P)0 is dependant !pon the
motor. For o!r motor we"ll !se a ' 2H3 inp!t fre1!ency. This means the motor speed
will be !pdates ' tho!sands times a second. The d!ty cycle of the P)0 will determine
the speed & direction of the motor.
The #%he&ati%
The schematic seen below !ses all the hardware components we"e seen !p to this
point. If yo!"re following along with this t!torial be s!re to follow it e,actly as seen
below. higher.
!iew 'ull #%he&ati%
(omponents are labeled to the best of my ability. Parts hooked !p to the PI( are
minial and it sho!ld be recogni3ed that this e,periment act!ally !ses the 4lime, P-$5
Deelopment board and not a bare bones P(C layo!t as seen in the schematic. Howeer
if yo! choose to follow the schematic e,actly it will work the same as it wo!ld with the
deelopment board* proided of co!rse that the software is preprogrammed onto the
P(C.
)hat The #etu$ Loo*+ Li*e
!iew 'ull Pi%ture
Maqueta de control PID con Arduino
.
5adgets po,ered by
5oogle
.
.
Con el #oti?o de la pri#era 0irtualCa#p 9Sulio 2&11<4 el proyecto ha ido
crear una #aHueta de control didMctica con un preupueto de #eno de 1&
euro 9Arduino no incluido<. La idea 7ue hacer un proyecto en ).h durante el
/n de e#ana del 1+D1- de Sulio.
!l proceo elegido e el control de te#peratura. Para ello do reitencia de
potencia generan el calor y un ?entilador actua co#o control para la
re7rigeraciFn. Bn enor reiti?o de tipo Q;C e encarga de regitrar la
te#peratura del habitMculo.
3e ha intalado el enor de te#peratura en #edio de la reitencia de
potencia para Hue el proceo diponga de la #enor inercia poible4 y aN e
co#porte #M rMpido ante ca#bio de la entrada.
Lo participante del proyecto:
Igor %. DT CreaciFn de la #aHueta 7Nica4 o7tware Arduino y
docu#entaciFn.
Alberto Uebra DT Inter7a> grM/ca en python para la ?iuali>aciFn del
proceo. Ise ampliar este proyecto con su trabajoJ.
LeoBot 9(anuel< DT IntroducciFn al control PID y teorNa P'(.
Co#ponente neceario:
0entilador 12? uado para re7rigeraciFn de co#ponente en
ordenadore.
%eitencia de potencia 9)-oh#< DDT 2 unidade
Bn enor te#peratura reiti?o 9Q;C< V reitencia $8 pull up
;ranitor (o7et.
Diodo 1Q)1)..
Bn recipiente 9habitMculo<.
;ran7or#ador e"terno para ali#entaciFn a 12?.
Lo obLeti?o del proyecto uando Arduino han ido:
1. CreaciFn 7Nica de la #aHueta.
2. Control de un proceo uando un PID.
$. Captura de eOal analFgica.
). Con?ertir la eOal elPctrica a 7Nica #ediante una tabla guardada en
#e#oria de progra#a 9Rah< para e?itar uo de %A( del
#icrocontrolador.
*. Control carga de potencia #ediante P'(.
+. (onitori>aciFn en el PC de reultado.
0eM#o una 7oto de co#o ha Huedado la #aHueta 9e ha uado una dre#el
para #odi/car el recipiente de plMtico<:
5tra 7oto de la intalaciFn del ?entilador:
La intalaciFn elPctrica necearia e batante encilla. La pode#o di?idir
en do parte: control del ?entilador #ediante tranitor #o7et y
adHuiiciFn de la te#peratura #ediante Q;C.
A continuaciFn4 e puede ober?ar un eHue#a de la cone"iFn del
?entilador. La alida utili>ada en Arduino e el pin 2 9P'(<.
!n lo ite#a de control en la>o cerrado la alida del controlador actGa
obre el actuador 9en ete cao #otor elPctrico del ?entilador< para corregir
la #agnitud 7Nica 9te#peratura< Hue e Huiere controlar.
La tPcnica #M habitual Hue e utili>a para el control de ?elocidad de
#otore de continua4 e la #odulaciFn por anchura de pulo P'( 9Pule
'idth (odulation<. !ta tPcnica conite en una eOal periFdica cuadrada
Hue ca#bia el tie#po de u etado acti?o 9ni?el alto< en el tie#po del
perNodo de la eOal.
!l tie#po Hue la eOal periFdica etM acti?a con repecto a perNodo de la
eOal e deno#ina Ciclo de Trabajo (Duty Cycle)
D @ 9t
on
/ ;<
! decir4 el duty cycle decribe la proporciFn del tie#po a 5Q 9encendido<
obre un perNodo de tie#po /Lo.
Crear ete tipo de eOal reulta #uy encillo en un #icrocontrolador4
aunHue cabe detacar Hue la corriente generada por el #i#o e #uy
peHueOa4 por lo Hue hace neceario de una etapa de adaptaciFn de potencia
ante de unirlo al #otor. Para ello e utili>a el tranitor en con#utaciFn
9corte y aturaciFn<. 0eM#o co#o erNa nuetro circuito conectado a la
alida P'( del #icrocontrolador:
!n el circuito4 el tranitor ?a a 7uncionar en corteDaturaciFn4 acti?ando y
deacti?ando el #otor del ?entilador #ediante la eOal P'(. Co#o el #otor
e un dipoiti?o inducti?o 9por la bobina Hue tiene< e debe intalar un
diodo 9conocido co#o diodo de Rybac8 F 7reewheeling<. La bobina e
oponen al ca#bio de corriente4 por lo Hue al WcortarW la ali#entaciFn e crea
uno pico de ?oltaLe #uy alto Hue pueden daOar nuetra alida del
#icrocontrolador. Xracia a ete diodo4 la corriente dipone de un ca#ino de
decarga.
!l control de ?elocidad del #otor e conigue ?ariando la teniFn Hue paa
por el #otor y eta tarea la reali>a la eOal P'( Hue genera el
#icrocontrolador. Al ca#biar el tie#po a 5Q de la eOal P'( 9duty cycle<4
eta#o ca#biando e7ecti?a#ente el ?alor #edio 9?oltaLe< obre nuetro
#otor4 lo Hue e tralada en un incre#ento/decre#ento de la ?elocidad del
?entilador.
Por lo Hue la alida de control PID e el duty cycle de la eOal P'( aplicada
al ?entilador. 3e ha #odi/cado el regitro del ti#er 14 Hue controla la
7recuencia del pin 24 para Hue la 7recuencia ea apro"i#ada#ente $2 8Y>.
La 7recuencia de dicha eOal4 debe er lo u/ciente#ente rMpida para Hue
no a7ecte la inercia del ite#a a controlar.
0eM#o una captura real de la eOal Hue ale de nuetro control:
3e ober?a co#o el control ?a #odi/cando adecuada#ente el tie#po a 5Q
del P'( para coneguir el 3etPoint prede/nido.
Para el cao del enor Q;C:
Para e?itar reol?er operacione #ate#Mtica en el #icrocontrolador4 e ha
creado una tabla de ?alore obtenido del con?eror ADC del Arduino ?eru
te#peratura en grado centNgrado. Para ello e ha utili>ado la hoLa de
cMlculo Libre5Zce Calc. Lo dato de entrada on la %o 9reitencia a 2*[C<
y el coe/ciente beta del enor Iin7or#aciFn pro?eniente del dataheet del
7abricanteJ. Lo pao han ido crear la tabla de reitencia ?eru
te#peratura4 e ir con?irtiendo adecuada#ente para obtener una tabla en
7or#a lectura ADC ?eru te#peratura en grado.
Dicha tabla4 erM guardada en #e#oria de progra#a4 e?itando conu#ir
#e#oria %A( innecearia#ente de nuetro Arduino.
3e ober?a Hue la repueta de un enor Q;C no e lineal.
La Q;C e ha ituado entre la do reitencia calentadora. De eta 7or#a4
e conigue Hue el ite#a tenga #eno inercia y u repueta ea rMpida.
INTRODUCCIN Por LeoBot (Manuel)
La te#peratura e una #agnitud 7Nica Hue tanto en el M#bito
do#Ptico e indutrial e intereante controlar para tener un un #ayor
con7ort y e/ciencia energPtica.
!l control e puede reali>ar tanto #anual 9control en la>o abierto<
co#o auto#Mtico 9control en la>o cerrado<.
!l control en la>o abierto e un control de encendidoDapagado4 en
nuetro cao para calentar una habitaciFn4 un calentador e enciende o e
apaga. !n control en la>o cerrado e tiene un controlador Hue co#para la
?ariable 9te#peratura Hue e #ide con un enor< con la re7erencia4
te#peratura Hue e Huiere tener en la habitaciFn4 y con?ertir el error Hue
reulta en una acciFn de control para reducir el error.
a) SISTEMA EN A!" A#IE$T"
b) SISTEMA EN A!" CE$$AD"
La unidad de control puede reaccionar de di7erente #anera ante la eOal
de error y proporcionar eOale de alida para Hue actGen lo ele#ento
correctore.
;ipo de control
1.D Control de do% po%icione%: el controlador e un interruptor acti?ado por
la eOal de error y proporciona una eOal correctora tipo encendidoD
apagado.
2.D Control proporcional (&): produce una acciFn de control Hue e
proporcional al error. La eOal de correctora au#enta al au#entar la eOal
de error.
$.D Control derivativo (D): produce una eOal de control Hue e proporcional
a la rapide> con la Hue ca#bia el error. Ante un ca#bio rMpido de la eOal de
error4 el controlador produce una eOal de correcciFn de gran ?alor6 cuando
el ca#bio e progrei?o4 Flo e produce una eOal peHueOa de correcciFn.
!l control deri?ati?o e puede coniderar un control anticipati?o porHue al
#edir la rapide> con Hue ca#bia el error e anticipa a la llegada de un error
#M grande y e aplica la correcciFn ante Hue llegue. !l control deri?ati?o
no e ua olo4 ie#pre ?a en co#binaciFn con el control proporcional y/o
con el control integral.
).D Control integral (I): produce una acciFn de control Hue e proporcional a
la integral del error en el tie#po. !n conecuencia4 una eOal de error
contante producirM una eOal correctora creciente y au#entarM i el error
continua. !l control integral e puede coniderar Hue recuerda la ituaciFn
anterior4 u#a todo lo errore y reponde a lo ca#bio Hue ocurren.
*.D Co'binaci(n de tipo% de control: proporcional deri?ati?o 9PD<4
proporcional integral 9PI< y proporcional integral deri?ati?o 9PID<.

CONTROL PID
!l control Proporcional Integral Deri?ati?o 9PID< e #ecani#o de control
#ediante reali#entaciFn negati?a4 el cual aplica una acciFn correctora al
ite#a para obtener el ?alor de conigna 93etpoint<.
!"ite #ultitud de recuro en internet acerca del #i#o4 por lo Hue aHuN e
?erM dede el punto de ?ita prMctico. Por eLe#plo4 wi8ipedia dipone de una
buena introducciFn.
!l nuetro ite#a:
3etpoint DT ;e#peratura de conigna del ite#a. 3e trata de la
te#peratura deeada a la cual el proceo tiene Hue #antenere a
tra?P de la acciFn del control. !l algorit#o ocila entre do
te#peratura4 con el #oti?o de ?er co#o e co#porta ante ca#bio
de la entrada. ! decir4 e a la te#peratura Hue Huere#o Hue e
encuentre nueto recipiente.
La reali#entaciFn o in7or#aciFn de cF#o e encuentra el ite#a4 e
adHuirida por la Q;C. !l obLeti?o e Hue el ?alor #edido ea ie#pre
igual al ?alor deeado 93etpoint<.
!l actuador e el ?entilador4 el cual regula#o u ?elocidad #ediante
#odulaciFn de ancho de pulo 9P'(<.
Para la ?iuali>aciFn4 e ha utili>ado el o7tware gratuito para 'indow
3ta#p Plot Lite 9http://www.el#aware.co#/ta#pplotlite/inde".ht#<.
!#pe>are#o por reali>ar Flo un control P%5P5%CI5QAL. !l progra#a de
Arduino4 ca#bia cada 12& egundo el 3et Point entre +& y *2 grado
centNgrado.
3e puede ober?ar cF#o el control proporcional no eli#ina el error
per#anente del ite#a.
!"ite un lN#ite en el ?alor de la contante proporcional4 ya Hue nuetro
ite#a e ?uel?e ocilatorio4 ya Hue un peHueOo ca#bio en el error4 hace
Hue la alida de controlador ea #uy grande. A continuaciFn un eLe#plo:
Co#o e ha ober?ado4 la parte proporcional no tiene en cuenta el tie#po4
por lo Hue para corregir el error per#anente4 neceita#o aOadirle la parte
IQ;!X%AL.
Para poder ober?ar cF#o e co#porta4 e ha introducido un retrao a la
actuaciFn de la #i#a.
La parte integral conigue Hue nuetro ite#a alcance lo ?alore obLeti?o
93et Point de +& y *. grado<4 ya Hue corrige el error per#anente del
ite#a.
La parte D!%I0A;I0A4Flo actua i hay un ca#bio en el ?alor aboluto del
error. ! decir4 i el error e contante4 no actuarM.
!l obLeti?o /nal de un ite#a de control4 e Hue el ite#a iga lo #M
/el#ente a u entrada ante perturbacione e"terna y Hue reponda ante
ca#bio de conigna 93etPoint<. 0eM#o un ?ideo4 en el cual e altera el
ite#a 9tapando la alida de aireDcable< y co#o al ubir la te#peratura4 el
ite#a au#enta la ?elocidad del ?entilador para tratar de contrarretar la
perturbaciFn.
DESCARGA EL SKETCH DE ARDUINO AQU
http://real2electronc!"#lo$!pot"co%/2&''/&(/%a
)*eta+,e+control+p,+con+ar,*no"ht%l
http://real2electronics.blogspot.com/2011/07/maqueta-de-control-pid-con-
arduino.html
http://abigmagnet.blogspot.com/search/label/PID
I found that the neer in! "et printers often use a combination of a D# motor and an
optical encoder to ta!e the place of stepper motors for print head positioning $linear
motion% and paper feed $rotar& positioning%. 'he pieces often come out $after some
effort% as a hole( and the& seemed li!e a natural to e)periment ith.
'he motors themsel*es are prett& nice if &ou "ust ant to ma!e something mo*e and
control its speed( and in combination ith the encoder( I thought I could use them as
a -ree alternat.e to a hobb& ser*o. I !ne there had to be some information
out there about using a feedbac! loop to position a motor( and of course there as. It
turns out that the classic a& of doing this is through a PID ser*o controller
$Proportional( Integral( Deri*ati*e%. +t its simplest this method can be thought of as a
a& to use the difference beteen here the motor should be and here it is
$error%( plus the speed at hich the error is changing( plus the sum of past errors to
manage the speed and direction that the motor is turning.
,!( so I ha*e to sa& at this point( that I am not an engineer. I did ta!e an engineering
calc. class or to( but that as more then 2- &ears ago( and I ne*er much
understood it e*en then. .o all I reall& ha*e to go on is m& intuition about ho this is
or!ing( a fe good e)planations( and some e)ample code. +s ala&s ( /oogle is
&our friend. If &ou do ha*e a good understanding I ould elcome &our comments0
'he first resource I found as this e)change on the +rduino forums and then folloed
through to an article that reall& e)plained hat as going on here at
embedded.com.
+fter reading the embedded.com article a fe times I put together some simple
code( and as ama1ed to find that the thing or!ed almost perfectl& the first time.
'he !e& elements of the code loo! li!e this
int val # analog)ead(pot'in); // read t$e potentiometer value (/ %
6/=2)
int target # map(val, /, 6/=2, /, 2C//);// set t$e seek to target b;
mapping t$e potentiometer range to t$e en"oder ma+ "ount
int error # en"oder/'os % target; // *ind t$e error term # "urrent
position % target
// generali?ed 'I( *ormula
//"orre"tion # -p * error & -d * (error % prevError) & kI * (sum o*
errors)
// "al"ulate a motor speed *or t$e "urrent "onditions
int motorSpeed # -' * error;
motorSpeed &# -( * (error % lastError);
motorSpeed &# -I * (sumError);
// set t$e last and sumerrors *or ne+t loop iteration
lastError # error;
sumError &# error;
2hat is going on here is:
1. read a *alue from the potentiometer through an analog to digital input $0-1023%
2. map that *alue so that it li*es in the range from 0-3400 $the count from one full
rotation of the motor%. 2e need to scale li!e this so e can ma!e an apples to apples
comparison ith the current position reported b& the optical encoder. 'he current
position is being calculated in another function $an I.5% hene*er an interrupt is
generated b& the optical encoder $more on hat this is all about here%.
3. create an error term b& subtracting the *alue e ant to go to $target% from
here e are $encoder0Pos%
6. multipl& the error b& a constant $proportional gain% to ma!e it large enough to
effect the speed. 'his is the Proportional term( and gi*es us a simple linear speed
*alue. 7asicall& it sa&s that the further e are from here e ant to be( the faster
e need to go to get there. 'he con*erse is true( so that e ill slo don as e
approach our destination. ,f course( if e are going to fast to begin ith( e ma&
o*ershoot. 'hen the Proportional ill sitch signs $from - to 8 or *isa *ersa% and e
ill bac! up toards our target. If the speed is reall& off then e end up 1ooming
past man& times and oscillating until e $hopefull&% get to the target.
-. add the difference beteen the error 9,2 and the error from the last time
around. 'his is a a& to figure out ho fast the error is changing( and is the
Deri*ati*e term of the equation( and &ou can thin! of it a bit li!e loo!ing into the
future. If the error rate is changing fast then e are getting close to here e ant
to be :+.' and e should thin! about sloing don. 'his helps dampen the
oscillation from the position term b& tr&ing to slo us don faster if e are
approaching the target too quic!l&. +gain( e multipl& the *alue b& a constant to
amplif& it enough to matter.
4. lastl& add in the sum of all past errors multiplied b& a constant gain. 'his is the
Integral term( and is li!e loo!ing at our past performance and learning from our
mista!es. 'he further off e ere before( the bigger this *alue ill be. If e ere
going too fast then it ill tr& to slo us( if to slol&( then it speeds us up.
7. set the last;rror to the current error( and add the current error to our sum.
'he resulting motor.peed *alue ill be a signed integer. .ince the +dafruit controller
ta!es an unsigned int as its speed *alue I do a little more manipulation to figure out
the direction and get a abs$% *alue for the speed( but that part is all prett& eas&.
+s I said( it seems reall& simple for such a complicated process. It turns out that the
geared motor from the in! "ets is much easier to control that some other mechanical
s&stems. 'he ph&sics of its gears( and the performance cur*e of the simple D# motor
mean that &ou can be prett& far off on &our tuning and it ill still end up in the right
place $e*entuall&%. If e ere tr&ing to do e)tremel& precise positioning( or ma!e it
all or! reall& fast( or handle huge inertial loads( then it ould need to be a lot
more robust. I am still or!ing on <tuning < the configuration $i.e. slol& changing
the 3 constant parameters one-b&-one until it or!s best% and I ill rite more about
that later.
In the mean time here is the code. 7ear in mind that it is designed for use ith the
+dafruit controller and librar&. =ou ill also most li!el& find that it does not or!
ell ith the constants I ha*e chosen>. In that case &ou ill need to do some tuning
&ourself. .ta& tuned $hah% and I ill sho &ou ho I did it.
>discerning readers of code ill notice that the ?d constant is 0 meaning that this is
actuall& a PI controller. I found that hile the Deri*ati*e made the motor settle into
position faster( it also in"ected an enormous amount of noise and "itter. 'his is due in
part to the cheap( nois&( and non-linear potentiometer I am using. I need to do some
more e)perimenting before I can reall& call it a complete PID.
,h &eah( if &ou are ta!ing apart an in! "et &ou ma& find these ,ptical ;ncoder
datasheets to be *aluable. 'hese are specific to +gilent parts( but I ha*e found the&
all share prett& much the same pin-outs.
U!n$ a DC %otor a! a !er.o /th 0ID control
PID motor control ith an +rduino from @osh ?opel on Aimeo.
I found that the neer in! "et printers often use a combination of a D# motor and an
optical encoder to ta!e the place of stepper motors for print head positioning $linear
motion% and paper feed $rotar& positioning%. 'he pieces often come out $after some
effort% as a hole( and the& seemed li!e a natural to e)periment ith.
'he motors themsel*es are prett& nice if &ou "ust ant to ma!e something mo*e and
control its speed( and in combination ith the encoder( I thought I could use them as
a -ree alternat.e to a hobb& ser*o. I !ne there had to be some information
out there about using a feedbac! loop to position a motor( and of course there as. It
turns out that the classic a& of doing this is through a PID ser*o controller
$Proportional( Integral( Deri*ati*e%. +t its simplest this method can be thought of as a
a& to use the difference beteen here the motor should be and here it is
$error%( plus the speed at hich the error is changing( plus the sum of past errors to
manage the speed and direction that the motor is turning.
,!( so I ha*e to sa& at this point( that I am not an engineer. I did ta!e an engineering
calc. class or to( but that as more then 2- &ears ago( and I ne*er much
understood it e*en then. .o all I reall& ha*e to go on is m& intuition about ho this is
or!ing( a fe good e)planations( and some e)ample code. +s ala&s ( /oogle is
&our friend. If &ou do ha*e a good understanding I ould elcome &our comments0
'he first resource I found as this e)change on the +rduino forums and then folloed
through to an article that reall& e)plained hat as going on here at
embedded.com.
+fter reading the embedded.com article a fe times I put together some simple
code( and as ama1ed to find that the thing or!ed almost perfectl& the first time.
'he !e& elements of the code loo! li!e this
int val # analog)ead(pot'in); // read t$e potentiometer value (/ %
6/=2)
int target # map(val, /, 6/=2, /, 2C//);// set t$e seek to target b;
mapping t$e potentiometer range to t$e en"oder ma+ "ount
int error # en"oder/'os % target; // *ind t$e error term # "urrent
position % target
// generali?ed 'I( *ormula
//"orre"tion # -p * error & -d * (error % prevError) & kI * (sum o*
errors)
// "al"ulate a motor speed *or t$e "urrent "onditions
int motorSpeed # -' * error;
motorSpeed &# -( * (error % lastError);
motorSpeed &# -I * (sumError);
// set t$e last and sumerrors *or ne+t loop iteration
lastError # error;
sumError &# error;
2hat is going on here is:
1. read a *alue from the potentiometer through an analog to digital input $0-1023%
2. map that *alue so that it li*es in the range from 0-3400 $the count from one full
rotation of the motor%. 2e need to scale li!e this so e can ma!e an apples to apples
comparison ith the current position reported b& the optical encoder. 'he current
position is being calculated in another function $an I.5% hene*er an interrupt is
generated b& the optical encoder $more on hat this is all about here%.
3. create an error term b& subtracting the *alue e ant to go to $target% from
here e are $encoder0Pos%
6. multipl& the error b& a constant $proportional gain% to ma!e it large enough to
effect the speed. 'his is the Proportional term( and gi*es us a simple linear speed
*alue. 7asicall& it sa&s that the further e are from here e ant to be( the faster
e need to go to get there. 'he con*erse is true( so that e ill slo don as e
approach our destination. ,f course( if e are going to fast to begin ith( e ma&
o*ershoot. 'hen the Proportional ill sitch signs $from - to 8 or *isa *ersa% and e
ill bac! up toards our target. If the speed is reall& off then e end up 1ooming
past man& times and oscillating until e $hopefull&% get to the target.
-. add the difference beteen the error 9,2 and the error from the last time
around. 'his is a a& to figure out ho fast the error is changing( and is the
Deri*ati*e term of the equation( and &ou can thin! of it a bit li!e loo!ing into the
future. If the error rate is changing fast then e are getting close to here e ant
to be :+.' and e should thin! about sloing don. 'his helps dampen the
oscillation from the position term b& tr&ing to slo us don faster if e are
approaching the target too quic!l&. +gain( e multipl& the *alue b& a constant to
amplif& it enough to matter.
4. lastl& add in the sum of all past errors multiplied b& a constant gain. 'his is the
Integral term( and is li!e loo!ing at our past performance and learning from our
mista!es. 'he further off e ere before( the bigger this *alue ill be. If e ere
going too fast then it ill tr& to slo us( if to slol&( then it speeds us up.
7. set the last;rror to the current error( and add the current error to our sum.
'he resulting motor.peed *alue ill be a signed integer. .ince the +dafruit controller
ta!es an unsigned int as its speed *alue I do a little more manipulation to figure out
the direction and get a abs$% *alue for the speed( but that part is all prett& eas&.
+s I said( it seems reall& simple for such a complicated process. It turns out that the
geared motor from the in! "ets is much easier to control that some other mechanical
s&stems. 'he ph&sics of its gears( and the performance cur*e of the simple D# motor
mean that &ou can be prett& far off on &our tuning and it ill still end up in the right
place $e*entuall&%. If e ere tr&ing to do e)tremel& precise positioning( or ma!e it
all or! reall& fast( or handle huge inertial loads( then it ould need to be a lot
more robust. I am still or!ing on <tuning < the configuration $i.e. slol& changing
the 3 constant parameters one-b&-one until it or!s best% and I ill rite more about
that later.
In the mean time here is the code. 7ear in mind that it is designed for use ith the
+dafruit controller and librar&. =ou ill also most li!el& find that it does not or!
ell ith the constants I ha*e chosen>. In that case &ou ill need to do some tuning
&ourself. .ta& tuned $hah% and I ill sho &ou ho I did it.
>discerning readers of code ill notice that the ?d constant is 0 meaning that this is
actuall& a PI controller. I found that hile the Deri*ati*e made the motor settle into
position faster( it also in"ected an enormous amount of noise and "itter. 'his is due in
part to the cheap( nois&( and non-linear potentiometer I am using. I need to do some
more e)perimenting before I can reall& call it a complete PID.
,h &eah( if &ou are ta!ing apart an in! "et &ou ma& find these ,ptical ;ncoder
datasheets to be *aluable. 'hese are specific to +gilent parts( but I ha*e found the&
all share prett& much the same pin-outs.
http://pdf1.alldatasheet.com/datasheet-pdf/*ie/146-30/BP/B;D.-C710.html
http://pdf1.alldatasheet.com/datasheet-pdf/*ie/1430C0/BP/B;D.-C76D.html
E+7;E.: +5DFI 9, ( ;E;#'5,9I #. ( G,',5 #,9'5,E ( PI D ( .#5,F9/I 9/
PID Library
/********************************************************
* 'I( .asi" E+ample
* )eading analog input / to "ontrol analog '01 output 2
********************************************************/
3in"lude 4'I(5v67$8
//(e*ine 9ariables we:ll be "onne"ting to
double Setpoint, Input, Output;
//Spe"i*; t$e links and initial tuning parameters
'I( m;'I((<Input, <Output, <Setpoint,=,>,6, (I)ECT);
void setup()

//initiali?e t$e variables we:re linked to


Input # analog)ead(/);
Setpoint # 6//;
//turn t$e 'I( on
m;'I(7Set1ode(@ATO1@TIC);
,
void loop()

Input # analog)ead(/);
m;'I(7Compute();
analog0rite(2,Output);
,

You might also like