pid-without-a-phd.pdf

14

Click here to load reader

Upload: giovanni-eliezer

Post on 02-Jan-2016

449 views

Category:

Documents


3 download

DESCRIPTION

PID controller

TRANSCRIPT

Page 1: pid-without-a-phd.pdf

86 OCTOBER 2000 Embedded Systems Programming

fe

at

ur

e

T I M W E S C O T T

t work, I am one of three designated “servo guys,” and theonly one who implements control loops in software. As aresult, I often have occasion to design digital control loopsfor various projects. I have found that while there certainlyare control problems that require all the expertise I canbring to bear, a great number of control problems can be

solved with simple controllers, without resorting to any control theory at all.This article will tell you how to implement and tune a simple controller

without getting into heavy mathematics and without requiring you to learnany control theory. The technique used to tune the controller is a tried andtrue method that can be applied to almost any control problem with success.

PID controlThe PID controller has been in use for over a century in various forms. Ithas enjoyed popularity as a purely mechanical device, as a pneumaticdevice, and as an electronic device. The digital PID controller using amicroprocessor has recently come into its own in industry. As you will see,it is a straightforward task to embed a PID controller into your code.

PID stands for “proportional, integral, derivative.” These three termsdescribe the basic elements of a PID controller. Each of these elements per-forms a different task and has a different effect on the functioning of a system.

In a typical PID controller these elements are driven by a combinationof the system command and the feedback signal from the object that isbeing controlled (usually referred to as the “plant”). Their outputs areadded together to form the system output.

PID Without a PhD

PID (proportional, integral, derivative) control is not as complicated as it sounds. Follow these simple implementation steps for

quick results.

A

Page 2: pid-without-a-phd.pdf

Embedded Systems Programming OCTOBER 2000 87

Figure 1 shows a block diagram ofa basic PID controller. In this case thederivative element is being drivenonly from plant feedback. The plantfeedback is subtracted from the com-mand signal to generate an error.This error signal drives the propor-tional and integral elements. Theresulting signals are added togetherand used to drive the plant. I haven’tdescribed what these elements doyet—we’ll get to that later. I’ve includ-ed an alternate placement for the pro-portional element (dotted lines)—this can be a better location for theproportional element, depending onhow you want the system to respondto commands.

Sample plantsIn order to discuss this subject withany sense of reality we need someexample systems. I’ll use three exam-ple plants throughout this article, andshow the effects of applying the vari-ous controllers to them:

• A motor driving a gear train• A precision positioning system• A thermal system

Each of these systems has differentcharacteristics and each one requiresa different control strategy to get thebest performance.

Motor and gearThe first example plant is a motordriving a gear train, with the outputposition of the gear train beingmonitored by a potentiometer orsome other position reading device.You might see this kind of mecha-nism driving a carriage on a printer,or a throttle mechanism in an auto-mobile cruise control system, oralmost any other moderately preciseposition controller. Figure 2 shows adiagram of such a system. Themotor is driven by a voltage that iscommanded by software. The motoroutput is geared down to drive theactual mechanism. The position of

this final drive is measured by thepotentiometer.

A DC motor driven by a voltagewants to go at a constant speed that isproportional to the applied voltage.Usually the motor armature has someresistance that limits its ability to accel-erate, so the motor will have somedelay between the change in input volt-age and the resulting change in speed.The gear train takes the movement ofthe motor and multiplies it by a con-stant. Finally, the potentiometer mea-sures the position of the output shaft.

Figure 3 shows the step response ofthe motor and gear combination. I’musing a time constant value of t0 = 0.2s.The step response of a system is justthe behavior of the output in responseto an input that goes from zero tosome constant value at time t = 0.Since we’re dealing with fairly genericexamples here I’ve shown the stepresponse as a fraction of full scale, so itgoes to 1. Figure 3 shows the stepinput and the motor response. The

PID stands for “proportional, integral, derivative.” These three terms

describe the basic elements of a PID controller.

HA

NN

AH

B

LA

IR

FIGURE 1 A basic PID controller

command

feedback

HardwareSoftware

error outputI

P

P

D

Integral

Proportional

Derivative

ADC

DAC &Driver

Plant∑+

+–

Page 3: pid-without-a-phd.pdf

response of the motor starts out slowlydue to the time constant, but oncethat is out of the way the motor posi-tion ramps at a constant velocity.

Precision actuatorIt is sometimes necessary to controlthe position of something very pre-cisely. A precise positioning system canbe built using a freely moving mechan-ical stage, a speaker coil (a coil andmagnet arrangement), and a non-con-tact position transducer.

You might expect to see this sort ofmechanism stabilizing an element of

an optical system, or locating someother piece of equipment or sensor.Figure 4 shows such a system. Softwarecommands the current in the coil.This current sets up a magnetic fieldthat exerts a force on the magnet. Themagnet is attached to the stage, whichmoves with an acceleration propor-tional to the coil current. Finally, thestage position is monitored by a non-contact position transducer.

With this arrangement, the forceon the magnet is independent of thestage motion. Fortunately this isolatesthe stage from external effects.

88 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 2 A voltage driven motor and gear train

Motor

Pot

– +

+

Vm

θm

θs

Vp

FIGURE 3 Motor and gear position vs. time

1

0.8

0.6

0.4

0.2

0

Posi

tion

Time

0 0.2 0.4 0.6 0.8 1

InputMotorPosition

Page 4: pid-without-a-phd.pdf

Unfortunately the resulting system isvery “slippery,” and can be a chal-lenge to control. In addition, theelectrical requirements to build agood current-output amplifier andnon-contact transducer interface canbe challenging. You can expect that ifyou are doing a project like this youare a member of a fairly talented

team (or you’re working on a short-lived project).

The equations of motion for thissystem are fairly simple. The force onthe stage is proportional to the drivecommand alone, so the accelerationof the system is exactly proportional tothe drive.

The step response of this system by

itself is a parabola, as shown in Figure5. As we will see later this makes thecontrol problem more challengingbecause of the sluggishness with whichthe stage starts moving, and its enthu-siasm to keep moving once it getsgoing.

Temperature controlThe third example plant I’ll use is aheater. Figure 6 shows a diagram of anexample system. The vessel is heatedby an electric heater, and the temper-ature of its contents is sensed by a tem-perature-sensing device.

Thermal systems tend to have verycomplex responses. I’m going toignore quite a bit of detail and give avery approximate model. Unless yourperformance requirements are severe,an accurate model isn’t necessary.

Figure 7 shows the step response ofthe system to a change in Vd. I’ve usedtime constants of t1 = 0.1s and t2 = 0.3s.The response tends to settle out to aconstant temperature for a given drive,but it can take a great deal of timedoing it. Also, without lots of insula-tion, thermal systems tend to be verysensitive to outside effects. This effectis not shown in the figure, but we’ll beinvestigating it later in the article.

ControllersThe elements of a PID controller pre-sented here either take their inputfrom the measured plant output orfrom the error signal, which is the dif-ference between the plant output andthe system command. I’m going towrite the control code using floatingpoint to keep implementation detailsout of the discussion. It’s up to you toadapt this if you are going to imple-ment your controller with integer orother fixed-point arithmetic.

I’m going to assume a function callas shown below. As the discussionevolves, you’ll see how the data struc-ture and the internals of the functionshapes up.

double UpdatePID(SPid * pid,

double error, double position)

90 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 4 A precision actuator

MagnetStage

+

Positiontransducer

ic

VpS N

Page 5: pid-without-a-phd.pdf

{

.

.

.

}

The reason I pass the error to thePID update routine instead of passingthe command is that sometimes youwant to play tricks with the error.Leaving out the error calculation inthe main code makes the applicationof the PID more universal. This func-tion will get used like this:

.

.

position = ReadPlantADC();

drive = UpdatePID(&plantPID,

plantCommand - position,

position);

DrivePlantDAC(drive);

.

.

ProportionalProportional control is the easiestfeedback control to implement, andsimple proportional control is proba-

bly the most common kind of controlloop. A proportional controller is justthe error signal multiplied by a con-stant and fed out to the drive. The pro-portional term gets calculated with thefollowing code:

double pTerm;

.

.

.

pTerm = pid->pGain * error;

.

.

.

return pTerm;

Figure 8 shows what happens whenyou add proportional feedback to themotor and gear system. For small gains(kp = 1) the motor goes to the correcttarget, but it does so quite slowly.Increasing the gain (kp = 2) speeds upthe response to a point. Beyond thatpoint (kp = 5, kp = 10) the motor startsout faster, but it overshoots the target.In the end the system doesn’t settleout any quicker than it would havewith lower gain, but there is moreovershoot. If we kept increasing thegain we would eventually reach a pointwhere the system just oscillatedaround the target and never settledout—the system would be unstable.

The motor and gear start to over-shoot with high gains because of thedelay in the motor response. If youlook back at Figure 2, you can see thatthe motor position doesn’t start ramp-ing up immediately. This delay, plushigh feedback gain, is what causes theovershoot seen in Figure 8.

Figure 9 shows the response of theprecision actuator with proportionalfeedback only. Proportional controlalone obviously doesn’t help this sys-tem. There is so much delay in theplant that no matter how low the gainis, the system will oscillate. As the gainis increased, the frequency of the out-put will increase but the system justwon’t settle.

Figure 10 shows what happenswhen you use pure proportional feed-

92 OCTOBER 2000 Embedded Systems Programming

pidFIGURE 6 A heater

+

Vt

Vd

FIGURE 5 Precision actuator position vs. time

1

0.8

0.6

0.4

0.2

0

Stag

e Po

siti

on

Time

0 0.2 0.4 0.6 0.8 1

InputStage Position

Page 6: pid-without-a-phd.pdf

back with the temperature controller.I’m showing the system response witha disturbance due to a change in ambi-ent temperature at t = 2s. Even withoutthe disturbance you can see that pro-portional control doesn’t get the tem-perature to the desired setting.Increasing the gain helps, but evenwith kp = 10 the output is still below tar-get, and you are starting to see astrong overshoot that continues totravel back and forth (this is calledringing).

As the previous examples show, aproportional controller alone can beuseful for some things, but it doesn’talways help. Plants that have too muchdelay, like the precision actuator, can’tbe stabilized with proportional con-trol. Some plants, like the tempera-ture controller, cannot be brought tothe desired set point. Plants like themotor and gear combination maywork, but they may need to be drivenfaster than is possible with proportion-al control alone. To solve these controlproblems you need to add integral ordifferential control or both.

IntegralIntegral control is used to add long-term precision to a control loop. It isalmost always used in conjunction withproportional control.

The code to implement an integra-tor is shown below. The integratorstate, iState is the sum of all the pre-ceding inputs. The parameters iMinand iMax are the minimum and maxi-mum allowable integrator state values.

double iTerm;

.

.

.

// calculate the integral state

// with appropriate limiting

pid->iState += error;

if (pid->iState > pid->iMax)

pid->iState = pid->iMax;

else if (pid->iState < pid->

iMin)

pid->iState = pid->iMin;

iTerm = pid->iGain * iState;

94 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 7 Heater temperature vs. time

1

0.8

0.6

0.4

0.2

0

Tem

pera

ture

Time

0 0.5 1 1.5 2

InputTemperature

Page 7: pid-without-a-phd.pdf

// calculate the integral term

.

.

.

Integral control by itself usuallydecreases stability, or destroys it alto-gether. Figure 11 shows the motor andgear with pure integral control (pGain= 0). The system doesn’t settle. Likethe precision actuator with propor-tional control, the motor and gear sys-tem with integral control alone willoscillate with bigger and bigger swingsuntil something hits a limit.(Hopefully the limit isn’t breakable.)

Figure 12 shows the temperaturecontrol system with pure integral con-trol. This system takes a lot longer tosettle out than the same plant withproportional control (see Figure 10),but notice that when it does settleout, it settles out to the target value—even with the disturbance added in. Ifyour problem at hand doesn’t requirefast settling, this might be a workablesystem.

Figure 12 shows why we use an inte-gral term. The integrator state“remembers” all that has gone onbefore, which is what allows the con-troller to cancel out any long termerrors in the output. This same mem-ory also contributes to instability—thecontroller is always responding toolate, after the plant has gotten upspeed. To stabilize the two previoussystems, you need a little bit of theirpresent value, which you get from aproportional term.

Figure 13 shows the motor andgear with proportional and integral(PI) control. Compare this withFigures 8 and 11. The position takeslonger to settle out than the systemwith pure proportional control, but itwill not settle to the wrong spot.

Figure 14 shows what happenswhen you use PI control on the heatersystem. The heater still settles out tothe exact target temperature, as withpure integral control (see Figure 12),but with PI control, it settles out two tothree times faster. This figure shows

operation pretty close to the limit ofthe speed attainable using PI controlwith this plant.

Before we leave the discussion ofintegrators, there are two more thingsI need to point out. First, since you areadding up the error over time, thesampling time that you are running

becomes important. Second, you needto pay attention to the range of yourintegrator to avoid windup.

The rate that the integrator statechanges is equal to the average errormultiplied by the integrator gainmultiplied by the sampling rate.Because the integrator tends to

Embedded Systems Programming OCTOBER 2000 95

pid

Page 8: pid-without-a-phd.pdf

smooth things out over the long termyou can get away with a somewhatuneven sampling rate, but it needs toaverage out to a constant value. Atworst, your sampling rate should varyby no more than ±20% over any 10-sample interval. You can even getaway with missing a few samples aslong as your average sample rate stayswithin bounds. Nonetheless, for a PIcontroller I prefer to have a systemwhere each sample falls within ±1%to ±5% of the correct sample time,and a long-term average rate that isright on the button.

If you have a controller that needsto push the plant hard, your controlleroutput will spend significant amountsof time outside the bounds of whatyour drive can actually accept. Thiscondition is called saturation. If youuse a PI controller, then all the timespent in saturation can cause the inte-grator state to grow (wind up) to verylarge values. When the plant reachesthe target, the integrator value is stillvery large, so the plant drives beyondthe target while the integratorunwinds and the process reverses. Thissituation can get so bad that the sys-tem never settles out, but just slowlyoscillates around the target position.

Figure 15 illustrates the effect ofintegrator windup. I used themotor/controller of Figure 13, andlimited the motor drive to ±0.2. Notonly is controller output much greaterthan the drive available to the motor,but the motor shows severe overshoot.The motor actually reaches its targetat around five seconds, but it doesn’treverse direction until eight seconds,and doesn’t settle out until 15 secondshave gone by.

The easiest and most direct way todeal with integrator windup is to limitthe integrator state, as I showed in myprevious code example. Figure 16shows what happens when you takethe system in Figure 15 and limit theintegrator term to the available driveoutput. The controller output is stilllarge (because of the proportionalterm), but the integrator doesn’t wind

96 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 8 Motor and gear with proportional feedback position vs. time

1

0.8

0.8

0.6

0.6

0.4

0.2

0

Posi

tion

Time

0 0.2 0.4 0.6 0.8 1 1

InputpGain = 10pGain = 5pGain = 2pGain = 1

LISTING 1 PID controller code

typedef struct

{

double dState; // Last position input

double iState; // Integrator state

double iMax, iMin; // Maximum and minimum allowable integrator state

double iGain, // integral gain

pGain, // proportional gain

dGain; // derivative gain

} SPid;

double UpdatePID(SPid * pid, double error, double position)

{

double pTerm, dTerm, iTerm;

pTerm = pid->pGain * error; // calculate the proportional term

// calculate the integral state with appropriate limiting

pid->iState += error;

if (pid->iState > pid->iMax) pid->iState = pid->iMax;

else if (pid->iState < pid->iMin) pid->iState = pid->iMin;

iTerm = pid->iGain * iState; // calculate the integral term

dTerm = pid->dGain * (pid->dState - position);

pid->dState = position;

return pTerm + dTerm + iTerm;

}

Page 9: pid-without-a-phd.pdf

up very far and the system starts set-tling out at five seconds, and finishesat around six seconds.

Note that with the code exampleabove you must scale iMin and iMaxwhenever you change the integratorgain. Usually you can just set the inte-grator minimum and maximum sothat the integrator output matches thedrive minimum and maximum. If youknow your disturbances will be smalland you want quicker settling, you canlimit the integrator further.

DifferentialI didn’t even show the precision actua-tor in the previous section. This isbecause the precision actuator cannotbe stabilized with PI control. In gener-al, if you can’t stabilize a plant withproportional control, you can’t stabi-lize it with PI control.

We know that proportional controldeals with the present behavior of theplant, and that integral control dealswith the past behavior of the plant. Ifwe had some element that predicts theplant behavior then this might be usedto stabilize the plant. A differentiatorwill do the trick.

The code below shows the differ-ential term of a PID controller. I pre-fer to use the actual plant positionrather than the error because thismakes for smoother transitions whenthe command value changes. The dif-ferential term itself is the last value ofthe position minus the current valueof the position. This gives you arough estimate of the velocity (deltaposition/sample time), which pre-dicts where the position will be in awhile.

double dTerm;

.

.

.

dTerm = pid->dGain *

(pid->dState - position);

pid->dState = position;

.

.

.

98 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 9 Precision actuator with proportional feedback vs. time

2

1.5

1

0.5

0

Stag

e Po

siti

on

Time

0 0.5 1 1.5 2 2.5 3 3.5 4

InputpGain = 1pGain = 2pGain = 5pGain = 10

Page 10: pid-without-a-phd.pdf

With differential control you canstabilize the precision actuator system.Figure 17 shows the response of theprecision actuator system with propor-tional and derivative (PD) control.This system settles in less than 1/2 of asecond, compared to multiple secondsfor the other systems.

Figure 18 shows the heating system

with PID control. You can see the per-formance improvement to be had byusing full PID control with this plant.

Differential control is very powerful,but it is also the most problematic of thecontrol types presented here. The threeproblems that you are most likely goingto experience are sampling irregularities,noise, and high frequency oscillations.

100 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 10 Temperature controller with proportional feedback. The kinkat time = 2 is from the external disturbance

1.2

1

0.8

0.6

0.4

0.2

0

Tem

pera

ture

Time

0 0.5 1 1.5 2 2.5 3 3.5 4

InputpGain = 10pGain = 5pGain = 2pGain = 1

FIGURE 11 Motor and gear with pure integral control

2.5

2

1.5

1

0.5

0

Posi

tion

Time

0 1 2 3 4 5

InputiGain = 0.01iGain = 0.005iGain = 0.002iGain = 0.001

Page 11: pid-without-a-phd.pdf

When I presented the code for adifferential element I mentioned thatthe output is proportional to the posi-tion change divided by the sampletime. If the position is changing at aconstant rate but your sample timevaries from sample to sample, you will

get noise on your differential term.Since the differential gain is usuallyhigh, this noise will be amplified agreat deal.

When you use differential controlyou need to pay close attention toeven sampling. I’d say that you want

the sampling interval to be consistentto within 1% of the total at all times—the closer the better. If you can’t setthe hardware up to enforce the sam-pling interval, design your software tosample with very high priority. Youdon’t have to actually execute the con-troller with such rigid precision—justmake sure the actual ADC conversionhappens at the right time. It may bebest to put all your sampling in an ISRor very high-priority task, then executethe control code in a more relaxedmanner.

Differential control suffers fromnoise problems because noise is usual-ly spread relatively evenly across thefrequency spectrum. Control com-mands and plant outputs, however,usually have most of their content atlower frequencies. Proportional con-trol passes noise through unmolested.Integral control averages its input sig-nal, which tends to kill noise.Differential control enhances high fre-quency signals, so it enhances noise.Look at the differential gains that I’veset on the plants above, and think ofwhat will happen if you have noise thatmakes each sample a little bit differ-ent. Multiply that little bit by a differ-ential gain of 2,000 and think of whatit means.

You can low-pass filter your differ-ential output to reduce the noise, butthis can severely affect its usefulness.The theory behind how to do this andhow to determine if it will work isbeyond the scope of this article.Probably the best that you can doabout this problem is to look at howlikely you are to see any noise, howmuch it will cost to get quiet inputs,and how badly you need the high per-formance that you get from differen-tial control. Once you’ve worked thisout, you can avoid differential con-trol altogether, talk your hardwarefolks into getting you a lower noiseinput, or look for a control systemsexpert.

The full text of the PID controllercode is shown in Listing 1 and is avail-able at www.embedded.com/code.html.

102 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 13 Motor and gear with PI control

2.5

2

1.5

1.5

1

0.5

0

Posi

tion

Time

0 1 2 3 4 5

InputpGain = 5, iGain = 0.01pGain = 2, iGain = 0.01pGain = 2, iGain = 0.005pGain = 2, iGain = 0.002

FIGURE 12 Temperature control system with integral control. The kinkat time = 2 is from the external disturbance

1.4

1.6

1.2

1

0.8

0.6

0.4

0.2

0

Posi

tion

Time

0 1 2 3 4 5 6

CommandiGain = 0.05iGain = 0.02iGain = 0.01iGain = 0.005

Page 12: pid-without-a-phd.pdf

TuningThe nice thing about tuning a PIDcontroller is that you don’t need tohave a good understanding of formalcontrol theory to do a fairly good jobof it. About 90% of the closed-loopcontroller applications in the world do

very well indeed with a controller thatis only tuned fairly well.

If you can, hook your system up tosome test equipment, or write in somedebug code to allow you to look at theappropriate variables. If your system isslow enough you can spit the appro-

priate variables out on a serial portand graph them with a spreadsheet.You want to be able to look at the driveoutput and the plant output. In addi-tion, you want to be able to apply somesort of a square-wave signal to thecommand input of your system. It isfairly easy to write some test code thatwill generate a suitable test command.

Once you get the setup ready, setall gains to zero. If you suspect thatyou will not need differential control(like the motor and gear example orthe thermal system) then skip down tothe section that discusses tuning theproportional gain. Otherwise start byadjusting your differential gain.

The way the controller is coded youcannot use differential control alone.Set your proportional gain to somesmall value (one or less). Check to seehow the system works. If it oscillates withproportional gain you should be able tocure it with differential gain. Start withabout 100 times more differential gainthan proportional gain. Watch yourdrive signal. Now start increasing thedifferential gain until you see oscilla-tion, excessive noise, or excessive (morethan 50%) overshoot on the drive orplant output. Note that the oscillationfrom too much differential gain ismuch faster than the oscillation fromnot enough. I like to push the gain upuntil the system is on the verge of oscil-lation then back the gain off by a factorof two or four. Make sure the drive sig-nal still looks good. At this point yoursystem will probably be responding verysluggishly, so it’s time to tune the pro-portional and integral gains.

If it isn’t set already, set the propor-tional gain to a starting value between1 and 100. Your system will probablyeither show terribly slow performanceor it will oscillate. If you see oscilla-tion, drop the proportional gain byfactors of eight or 10 until the oscilla-tion stops. If you don’t see oscillation,increase the proportional gain by fac-tors of eight or 10 until you start see-ing oscillation or excessive overshoot.As with the differential controller, Iusually tune right up to the point of

104 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 14 Heater with PI control. The kink at time = 2 is from the external disturbance

1.2

1

0.6

0.8

0.4

0.2

0

Tem

pera

ture

Time

0 1 2 3 4 5 6

CommandpGain = 2, iGain = 0.1pGain = 2, iGain = 0.05pGain = 2, iGain = 0.02pGain = 1, iGain = 0.02

FIGURE 15 Motor and gear with PI control and windup

1.5

1

0.5

0

-0.5

Posi

tion

Time

0 5 10 15 20

CommandPositionDriveControl

Page 13: pid-without-a-phd.pdf

too much overshoot then reduce thegain by a factor of two or four. Onceyou are close, fine tune the propor-tional gain by factors of two until youlike what you see.

Once you have your proportionalgain set, start increasing integral gain.Your starting values will probably befrom 0.0001 to 0.01. Here again, youwant to find the range of integral gainthat gives you reasonably fast perfor-mance without too much overshoot andwithout being too close to oscillation.

Other issuesUnless you are working on a projectwith very critical performance para-meters you can often get by with con-trol gains that are within a factor oftwo of the “correct” value. This meansthat you can do all your “multiplies”with shifts. This can be very handywhen you’re working with a slowprocessor.

106 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 16 Motor and gear with PI control and integrator limiting

1.5

1

0.5

0

-0.5

Posi

tion

Time

0 2 4 6 108

CommandPositionDriveControl

Page 14: pid-without-a-phd.pdf

Sampling rateSo far I’ve only talked about samplerates in terms of how consistent theyneed to be, but I haven’t told you howto decide ahead of time what the sam-ple rate needs to be. If your samplingrate is too low you may not be able toachieve the performance you want,

because of the added delay of the sam-pling. If your sampling rate is too highyou will create problems with noise inyour differentiator and overflow inyour integrator.

The rule of thumb for digital con-trol systems is that the sample timeshould be between 1/10th and

1/100th of the desired system settlingtime. System settling time is theamount of time from the moment thedrive comes out of saturation until thecontrol system has effectively settledout. If you look at Figure 16, the con-troller comes out of saturation atabout 5.2s, and has settled out ataround 6.2s. If you can live with theone second settling time you could getaway with a sampling rate as low as10Hz.

You should treat the sampling rateas a flexible quantity. Anything thatmight make the control problemmore difficult would indicate thatyou should raise the sampling rate.Factors such as having a difficultplant to control, or needing differen-tial control, or needing very precisecontrol would all indicate raising thesampling rate. If you have a very easycontrol problem you could get awaywith lowering the sampling ratesomewhat (I would hesitate tolengthen the sample time to morethan one-fifth of the desired settlingtime). If you aren’t using a differen-tiator and you are careful aboutusing enough bits in your integratoryou can get away with sampling rates1,000 times faster than the intendedsettling time.

Exert controlThis covers the basics of implement-ing and tuning PID controllers. Withthis information, you should be ableto attack the next control problemthat comes your way and get it undercontrol. esp

Tim Wescott has a master’s degree in elec-trical engineering and has been working inindustry for more than a decade. His expe-rience has included a number of controlloops closed in software using 8- to 32-bitmicroprocessors, DSPs, assembly language,C, and C++. He is currently involved incontrol systems design at FLIR Systemswhere he specifies mechanical, electrical,and software requirements and does electri-cal and software design. You can contacthim at [email protected].

108 OCTOBER 2000 Embedded Systems Programming

pid

FIGURE 17 Precision actuator with PID control

FIGURE 18 Heater with PID control

1

0.6

0.8

0.4

0.2

0

Stag

e Po

siti

on

Time

0 0.1 0.2 0.3 0.4 0.5

CommanddGain = 2000, pGain = 200dGain = 2000, pGain = 500dGain = 5000, pGain = 1000dGain = 5000, pGain = 2000

1

0.6

0.8

0.4

0.2

0

Tem

pera

ture

Time

0 0.5 1 1.5 2

CommandpGain = 20, iGain = 0.5, dGain = 100pGain = 20, iGain = 0.1, dGain = 100pGain = 10, iGain = 0.1, dGain = 50pGain = 5, iGain = 0.1, dGain = 50