You are on page 1of 12

Esta ecuacin, genera una seal de error, en donde cada sensor de lee por el ADC en el rango de

0 a 255. Usando 16 sensores el factor es de 17, al final, nos da un rango, lineal siempre, de la
posicin de la linea respecto a los sensores, y se toma como un valor de +-127 respecto al centro
Error = (0*S0 + 17*S1 + 34*S2... + 255*S15) / (S0 + S1 + S2 +S4... + S15)

Antes que nada, checa la alimentacin de tu robot, en este caso, se usaron 2 baterias de LiPo para
tener 8.4 Volts a plena carga. Los motorcitos no son los de la caja original, sino son otros, ya que
precisamente, los originales, al no tener tanto torque, no suelen responder rapidamente a las
curvas. Saludos

1 cm entre sensores

En realidad, se usa un multiplexor analgico de 16 canales, el SN74HC4067, eso permite usar 1
solo ADC para los 16 canales, y la rutina de calculo de direccin y error, se encarga de ir
direccionando el multiplexor dentro de la rutina de interrupcin de la frecuencia de sampleo. De
todos modos, si se cambiara el PIC, por un PIC18F46K22, se tendrian 29 canales de ADC.
Saludos
http://www.robotix.in/tutorials/category/avr/pid#175

What Is PID?
PID is an acronym for Proportional Integral Derivative. As the name suggests, these
terms describe three basic mathematical functions applied to the error (error = SetVal -
SensorVal, where SetVal is the target value and SensorVal is the present input value
obtained from the sensor ). Main task of the PID controller is to minimize the error of
whatever we are controlling. It takes in input, calculates the deviation from the
intended behaviour and accordingly adjusts the output so that deviation from the
intended behaviour is minimized and greater accuracy obtained.
Why Implement PID?
Line following seems to be accurate when carried out at lower speeds. As we start
increasing the speed of the robot, it wobbles a lot and is often found getting off track.
Hence some kind of control on the robot is required that would enable us to make it
follow the line efficiently at higher speeds. This is where PID controller shines.

In order to implement line following one can basically start with just three sensors
which are so spaced on the robot that-
1. If the centre sensor detects the line the robot steers forward
2. If the left sensor detects the line the robot steers right
3. If the right sensor detects the line the robot steers left.
This algorithm would make the robot follow the line, however, we would need to
compromise with its speed to follow the line efficiently.

We can increase the efficiency of line following by increasing the number of sensors,
say 5.

Here the possible combinations represent exact position like-
00100 On the centre of the line
00001 To the left of the line
10000 To the right of the line
There will be other possible combinations such as 00110 and 00011 that can provide us
data on how far to the right is the robot from the centre of the line(same follows for left).
Further to implement better line following we need to keep track of how long is the robot
not centered on the line and how fast does it change its position from the centre.This is
exactly what we can achieve using PID control.The data obtained from the array of
sensors would then be put into utmost use and line following process would be much
more smoother, faster and efficient at greater speeds.
PID is all about improving our control on the robot.

The idea behind PID control is that we set a value that we want maintained, either
speed of a motor or reading from a sensor. We then take the present readings as input
and compare them to the setpoint. From this an error value can be calculated, i.e,
(error = setpoint - actual reading). This error value is then used to calculate how much
to alter the output by to make the actual reading closer to the setpoint.
How To Implement PID?
Terminology:

The basic terminology that one would require to understand PID are:
Error - The error is the amount at which a device isnt doing something right. For
example, suppose the robot is located at x=5 but it should be at x=7, then the error is
2.
Proportional (P) - The proportional term is directly proportional to the error at
present.
Integral (I) - The integral term depends on the cumulative error made over a period of
time (t).
Derivative (D) - The derivative term depends rate of change of error.
Constant (factor)- Each term (P, I, D) will need to be tweaked in the code. Hence,they
are included in the code by multiplying with respective constants.
o P-Factor (Kp) - A constant value used to increase or decrease the impact of
Proportional
o I-Factor (Ki) - A constant value used to increase or decrease the impact of Integral
o D-Factor (Kd) - A constant value used to increase or decrease the impact of
Derivative
Error measurement: In order to measure the error from the set position, i.e. the
centre we can use the weighted values method. Suppose we are using a 5 sensor array
to take the position input of the robot. The input obtained can be weighted depending
on the possible combinations of input. The weight values assigned would be such that
the error in position is defined both exactly and relatively.
The full range of weighted values is shown below. We assign a numerical value to each
one.
Binary Value Weighted Value
00001 4
00011 3
00010 2
00110 1
00100 0
01100 -1
01000 -2
11000 -3
10000 -4
00000 -5 or 5 (depending on the previous value)
The range of possible values for the measured position is -5 to 5. We will measure the
position of the robot over the line several times a second and use these value to
determine Proportional, Integral and Derivative values.
PID formula:

So what do we do with the error value to calculate how much the output be altered
by? We would need to simply add the error value to the output to adjust the robots
motion. And this would work, and is known as proportional control (the P in PID). It is
often necessary to scale the error value before adding it to the output by using the
constant(Kp).

Proportional:
Difference = (Target Position) - (Measured Position)
Proportional = Kp*(Difference)

This approach would work, but it is found that if we want a quick response time, by
using a large constant, or if the error is very large, the output may overshoot from the
set value. Hence the change in output may turn out to be unpredictable and
oscillating. In order to control this, derivative expression comes to limelight.

Derivative:
Derivative provides us the rate of change of error. This would help us know how quickly
does the error change from time to time and accordingly we can set the output.
Rate of Change = ((Difference) (Previous Difference))/time interval
Derivative= Kd *(Rate of Change)

The time interval can be obtained by using the timer of microcontroller.

The integral improves steady state performance, i.e. when the output is steady how far
away is it from the setpoint. By adding together all previous errors it is possible to
monitor if there are accumulating errors. For example- if the position is slightly to the
right all the time, the error will always be positive so the sum of the errors will get
bigger, the inverse is true if position is always to the left. This can be monitored and
used to further improve the accuracy of line following.

Integral:
Integral = Integral + Difference
Integral = Ki*(Integral)

Summarizing PID control-
Term Expression Effect
Proportional Kp x error
It reduces a large part of the error based on
present time error.
Integral error dt
Reduces the final error in a system. Cumulative of
a small error over time would help us further
reduce the error.
Derivative
Kd x derror
/ dt
Counteracts the Kp and Ki terms when the output
changes quickly.
Therefore, Control value used to adjust the robot's motion=
(Proportional) + (Integral) + (Derivative)

Tuning:

PID implementation would prove to be useless rather more troublesome unless the
constant values are tuned depending on the platform the robot is intended to run on.
The physical environment in which the robot is being operated vary significantly and
cannot be modelled mathematically. It includes ground friction, motor inductance,
center of mass, etc. Hence, the constants are just guessed numbers obtained by trial
and error. Their best fit value varies from robot to robot and also the circumstance in
which it is being run. The aim is to set the constants such that the settling time is
minimum and there is no overshoot.

There are some basic guidelines that will help reduce the tuning effort.

Start with Kp, Ki and Kd equalling 0 and work with Kp first. Try setting Kp to a value of
1 and observe the robot. The goal is to get the robot to follow the line even if it is very
wobbly. If the robot overshoots and loses the line, reduce the Kp value. If the robot
cannot navigate a turn or seems sluggish, increase the Kp value.
Once the robot is able to somewhat follow the line, assign a value of 1 to Kd (skip Ki
for the moment). Try increasing this value until you see lesser amount of wobbling.
Once the robot is fairly stable at following the line, assign a value of 0.5 to 1.0 to Ki. If
the Ki value is too high, the robot will jerk left and right quickly. If it is too low, you
won't see any perceivable difference. Since Integral is cumulative, the Ki value
has a significant impact. You may end up adjusting it by .01 increments.
Once the robot is following the line with good accuracy, you can increase the speed
and see if it still is able to follow the line. Speed affects the PID controller and will
require retuning as the speed changes.

Pseudo Code:Here is a simple loop that implements the PID control:
start:
error = (target_position) - (theoretical_position)
integral = integral + (error*dt)
derivative = ((error) - (previous_error))/dt
output = (Kp*error) + (Ki*integral) + (Kd*derivative)
previous_error = error
wait (dt)
goto start

Lastly, PID doesnt guarantee effective results just by simple implementation of a code,
it requires constant tweaking based on the circumstances, once correctly tweaked it
yields exceptional results. The PID implementation also involves a settling time, hence
effective results can be seen only after a certain time from the start of the run of the
robot. Also to obtain a fairly accurate output it is not always necessary to implement all
the three expressions of PID. If implementing just PI results yields a good result we can
skip the derivative part.










Qu es la PID?
"PID" es un acrnimo de Derivada Integral Proporcional. Como su nombre lo indica,
estos trminos describen tres funciones matemticas bsicas aplicadas al error (error =
setval - SensorVal, donde setval es el valor objetivo y SensorVal es el valor de entrada
actual obtenida del sensor). La tarea principal del controlador PID es minimizar el error
de lo que estamos controlando. Se necesita en la entrada, calcula la desviacin del
comportamiento previsto y en consecuencia ajusta la salida de modo que la desviacin
del comportamiento previsto se reduce al mnimo y una mayor precisin obtenida.
Por qu implementar PID?
El seguimiento de lnea parece ser precisa cuando se lleva a cabo a velocidades ms
bajas. Al comenzar el aumento de la velocidad del robot, se tambalea mucho y se
encuentra a menudo salirse del camino.
Por lo tanto se requiere algn tipo de control sobre el robot que nos permita hacerlo
seguir la lnea de manera eficiente a altas velocidades. Aqu es donde brilla controlador
PID.

Con el fin de poner en prctica la lnea siguiente, bsicamente puede comenzar con
slo tres sensores que estn tan distanciados en el robot que:
1. Si el sensor detecta la lnea de centro del robot dirige hacia adelante
2. Si el sensor izquierdo detecta el borde del robot dirige derecho
3. Si el sensor detecta la derecha de la lnea de los novillos de robots se marcharon.
Este algoritmo podra hacer que el robot siga la lnea, sin embargo, tendramos que
comprometer con su velocidad para seguir la lnea de manera eficiente.

Podemos aumentar la eficiencia de la lnea siguiente al aumentar el nmero de
sensores, por ejemplo, 5.

Aqu las posibles combinaciones representan la posicin exacta como:
00100 En el centro de la lnea
00001 A la izquierda de la lnea
10000 A la derecha de la lnea
Habr otras combinaciones posibles como 00110 y 00011 que nos puede proporcionar
datos sobre qu tan lejos a la derecha es el robot desde el centro de la lnea (el mismo
sigue por la izquierda). Adems de implementar una mejor lnea siguiente que
necesitamos para realizar un seguimiento de cunto tiempo est el robot no est centrada
en la lnea y la rapidez con qu cambia su posicin a partir del centro. Este es exactamente
lo que podemos lograr a partir de datos control. El "PID" obtenidos del conjunto de
sensores a continuacin fuera a ir a la mxima utilizacin y la lnea siguiente proceso sera
mucho ms suave, ms rpido y eficiente a mayores velocidades.
PID se trata de mejorar nuestro control sobre el robot.

La idea detrs de control PID es que hemos creado un valor que queremos mantener,
ya sea la velocidad de un motor o la lectura de un sensor. Entonces tomamos las
presentes lecturas como entrada y los comparamos con el valor de consigna. A partir
de este un valor de error se puede calcular, es decir, ( punto de ajuste de error - lectura
real). Este valor de error se utiliza entonces para calcular la cantidad de alterar la salida
por hacer la lectura real ms cerca del punto de ajuste.
Cmo implementar la EIP?
Terminologa:

La terminologa bsica que uno requerira comprender PID son:
Error - El error es el importe por el que un dispositivo no est haciendo algo bien. Por
ejemplo, supongamos que el robot est situado en x = 5 pero debe ser en x = 7,
entonces el error es 2.
Proporcional (P) - El trmino proporcional es directamente proporcional al error en la
actualidad.
Integral (I) - El trmino integral depende del error acumulativo hecho durante un
perodo de tiempo (t).
Derivada (D) - El trmino derivado depende tasa de cambio de error.
Constant (factor) - Cada trmino (P, I, D) tendr que ser ajustado en el cdigo. Por lo
tanto, se incluyen en el cdigo multiplicando con respectivas constantes.
o P-Factor (Kp) - Valor constante para aumentar o reducir el impacto de los
Proporcional
o I-Factor (Ki) - Un valor constante utilizado para aumentar o disminuir el impacto de
la integral
o Factor D (Kd) - Un valor constante utilizado para aumentar o disminuir el impacto
de derivado
Medicin de error: Con el fin de medir el error de la posicin de ajuste, es decir, el
centro se puede utilizar el mtodo de los valores ponderados. Supongamos que
estamos utilizando una matriz de 5 sensor para tomar la entrada de posicin del
robot. La entrada obtenida puede ser ponderada en funcin de las posibles
combinaciones de entrada. Los valores de peso asignados seran tales que el error en
posicin se define tanto exactamente y relativamente.
A continuacin se muestra la gama de valores ponderados. Le asignamos un valor
numrico a cada uno.
Valor binario Valor ponderado
00001 4
00011 3
00010 2
00110 1
00100 0
01100 -1
01000 -2
11000 -3
10000 -4
00000 -5 O 5 (en funcin del valor anterior)
El rango de valores posibles para la posicin medida es de -5 a 5. Vamos a medir la
posicin del robot en la lnea varias veces por segundo y usar estos valores para
determinar proporcional, integral y derivado valores.
Frmula PID:

Entonces, qu hacemos con el valor de error al calcular la cantidad de la produccin
se ve alterada por? Habra que aadir simplemente el valor de error a la salida para
ajustar el movimiento del robot. Y esto iba a funcionar, y se conoce como control
proporcional (P en PID). A menudo es necesario para escalar el valor de error antes de
aadir a la salida mediante el uso de la constante (Kp).
Proporcional:
Diferencia = (Posicin del objeto) - (posicin medida)
Proporcional = Kp * (Diferencia)

Este enfoque podra funcionar, pero se encontr que si queremos tener un tiempo de
respuesta rpido, mediante el uso de una gran constante, o si el error es muy grande,
la salida puede rebasamiento del valor establecido. Por lo tanto el cambio en la
produccin puede llegar a ser impredecible y oscilante. Para controlar esto, la
expresin derivado viene a primer plano.

Derivado:
Derivado nos proporciona la tasa de cambio de error. Esto nos ayudara a saber cmo
lo hace rpidamente el cambio de error de vez en cuando y en consecuencia podemos
establecer la salida.
Tasa de cambio = ((Diferencia) - (Diferencia anterior)) / intervalo de tiempo
Derivado = Kd * (Tasa de Cambio)

El intervalo de tiempo se puede conseguir mediante el temporizador de
microcontrolador.

La integral mejora el rendimiento de estado estable, es decir, cuando la salida es
constante a qu distancia hay desde el punto de ajuste. Sumando todos los errores
anteriores es posible monitorear si hay errores que se acumulan. Por ejemplo, si la
posicin es ligeramente a la derecha todo el tiempo, el error siempre ser positivo por
lo que la suma de los errores se hacen ms grandes, lo contrario es cierto si la posicin
es siempre hacia la izquierda. Esto se puede monitorizar y utilizar para mejorar an
ms la precisin de la lnea siguiente.
Integral:
Integral = Integral + Diferencia
Integral = Ki * (integral)

Resumiendo control "PID"
Plazo Expresin Efecto
Proporcional Kp x error
Se reduce una gran parte del error basado en
presente error de tiempo.
Integral dt error
Reduce el error final en un sistema. Acumulado de
un pequeo error en el tiempo ayudara a reducir
an ms el error.
Derivado
Kd x derror
/ dt
Contrarresta los trminos Kp y Ki cuando la salida
cambia rpidamente.
Por lo tanto, el valor de control se utiliza para ajustar el movimiento del robot =
(Proporcional) + (Integral) + (derivada)

Afinacin:

Aplicacin PID resultara ser intil bastante ms problemtico a menos que los valores
constantes se afinan dependiendo de la plataforma que el robot est diseado para
ejecutarse en. El entorno fsico en el que se est operando el robot variar
significativamente y no puede ser modelado matemticamente. Incluye friccin del
suelo, la inductancia del motor, centro de masa, etc Por lo tanto, las constantes son
slo nmeros obtenidos por ensayo y error adivinado. Su mejor valor vara en forma de
robot a robot y tambin la circunstancia en la que se est ejecutando. El objetivo es
establecer las constantes de tal manera que el tiempo de establecimiento es mnimo y
no hay sobreimpulso.

Hay algunas pautas bsicas que ayudarn a reducir el esfuerzo de sintonizacin.
Comience con Kp, Ki y Kd igual a 0 y trabajar con Kp primero. Pruebe a establecer Kp a
un valor de 1 y observar el robot. El objetivo es conseguir que el robot siga la lnea,
incluso si es muy inestable. Si el robot sobrepasa y pierde la lnea, reducir el valor de
Kp. Si el robot no puede navegar por una vez, o parece lenta, aumente el valor de Kp.
Una vez que el robot es capaz de seguir un poco la lnea, asigne un valor de 1 a Kd
(saltar Ki por el momento). Intente aumentar este valor hasta que vea en menor
cantidad de oscilacin.
Una vez que el robot es bastante estable en la lnea siguiente, asigne un valor de 0,5 a
1,0 a Ki. Si el valor Ki es demasiado alto, el robot se sacuda izquierda y derecha
rpidamente. Si es demasiado bajo, no ver ninguna diferencia perceptible. Desde
Integral es acumulativo, el valor Ki tiene un impacto significativo. Usted puede
terminar de ajustar por 0,01 incrementos.
Una vez que el robot est siguiendo la lnea con una buena precisin, se puede
aumentar la velocidad y ver si todava es capaz de seguir la lnea. La velocidad afecta el
controlador PID y requerir resintonizar como los cambios de velocidad.

Cdigo Pseudo: Aqu hay un simple bucle que implementa el control PID:
start:
error = (target_position) - (theoretical_position)
integral = integral + (error*dt)
derivative = ((error) - (previous_error))/dt
output = (Kp*error) + (Ki*integral) + (Kd*derivative)
previous_error = error
wait (dt)
goto start

comenzar:
error = (target_position) - (theoretical_position)
integral = integral + (error * dt)
derivado = ((error) - (previous_error)) / dt
salida = (Kp * error) + (Ki * integral) + (Kd * derivado)
previous_error = error
esperar (dt)
inicio Goto

Por ltimo, el PID no garantiza resultados efectivos slo por una simple aplicacin de
un cdigo, se requiere de ajustes constantes en base a las circunstancias, una vez
correctamente ajustado que produce resultados excepcionales. El PID aplicacin
tambin implica un tiempo de sedimentacin, por lo tanto resultados eficaces slo se
pueden ver despus de un cierto tiempo desde el inicio de la carrera del robot. Adems
de obtener una salida bastante precisa, no siempre es necesario aplicar todas las tres
expresiones de PID. Si la aplicacin slo resultados PI se obtiene un buen resultado
podemos omitir la parte de derivada.

You might also like