digital pid controller 175

6
Elektor Electronics 9/99 The digital PID controller described in this article, based on a PIC microcon- troller, is on the one hand very well suited to studying how the controller operates with various parameter values, using simple con- trol loops. On the other hand, it can of course also be used for specific control tasks. A complete control loop requires an appropriate actuator and a suitable sensor, in addi- tion to the controller itself. The core of the circuit is an inexpensive PIC 16C71 microcontroller, whose built-in A/D con- verter digitizes the mea- sured value (actual value) and pro- vides the result to the controller pro- gram. The program determines the control error relative to the set value (target value) for each actual value and, based on this, calculates the control value that is output to the external D/A converter. The control parameters, which are entered by a keypad, are stored in a non-volatile memory (EEP- ROM). In order to manage with the pro- gram memory of the PIC, which is only 1 kB, the parameters are entered as hexadecimal codes. They are however displayed on the LCD as text, which is easier to understand. B ASIC THEORY Control circuits are encountered very often in electronics. For instance, a voltage regulator is present in almost every circuit. More elaborate con- trollers for dealing with other physical quantities, such as rotational speed, The term ‘PID con- troller’ normally brings to mind an analogue controller circuit with a couple of opamps. This article shows how such a controller can be implemented in digital form. In this universal controller circuit, based on a PIC and a D/A con- verter, all control para- meters can be entered via a key- board to adapt the controller to the task at hand. 14 Design By D. Kohtz digital PID controller closing the loop with a PIC Specifications: controller type: PID parameter entry: hexadecimal keypad parameter display: alphanumeric LCD adjustable parameters: - set value - initial control quantity value - upper limit - lower limit - sampling interval (100 ms to 25 s) parameter storage: EEPROM A/D and D/A conversion: 8 bit (measured value, control quantity) microcontroller: PIC 16C71 GENERAL INTEREST

Upload: andr14272

Post on 04-Apr-2015

279 views

Category:

Documents


10 download

TRANSCRIPT

Page 1: Digital Pid Controller 175

Elektor Electronics 9/99

The digital PID controller described inthis article, based on a PIC microcon-troller, is on the one hand very well

suited to studying howthe controller operateswith various parametervalues, using simple con-trol loops. On the otherhand, it can of coursealso be used for specificcontrol tasks. A completecontrol loop requires anappropriate actuator anda suitable sensor, in addi-tion to the controlleritself.

The core of the circuitis an inexpensive PIC16C71 microcontroller,whose built-in A/D con-verter digitizes the mea-

sured value (actual value) and pro-vides the result to the controller pro-

gram. The program determines thecontrol error relative to the set value(target value) for each actual value and,based on this, calculates the controlvalue that is output to the external D/Aconverter. The control parameters,which are entered by a keypad, arestored in a non-volatile memory (EEP-ROM).

In order to manage with the pro-gram memory of the PIC, which is only1 kB, the parameters are entered ashexadecimal codes. They are howeverdisplayed on the LCD as text, which iseasier to understand.

B A S I C T H E O R YControl circuits are encountered veryoften in electronics. For instance, avoltage regulator is present in almostevery circuit. More elaborate con-trollers for dealing with other physicalquantities, such as rotational speed,

The term ‘PID con-troller’ normally brings

to mind an analoguecontroller circuit witha couple of opamps.

This article showshow such a controllercan be implementedin digital form. In this

universal controllercircuit, based on a

PIC and a D/A con-verter, all control para-

meters can beentered via a key-

board to adapt thecontroller to the task

at hand.

14

Design By D. Kohtz

digital PID controllerclosing the loop with a PIC

Specifications: controller type: PID parameter entry: hexadecimal keypad parameter display: alphanumeric LCD adjustable parameters: - set value

- initial control quantity value- upper limit- lower limit

- sampling interval (100 ms to 25 s) parameter storage: EEPROM A/D and D/A conversion: 8 bit

(measured value, control quantity) microcontroller: PIC 16C71

GENERAL INTEREST

Page 2: Digital Pid Controller 175

velocity, temperature, pressure, flowand so on. Control technology dealswith finding solutions for such prob-lems. Let’s look at the basic principlesof this technology.

In control theory, the controlledactivity is referred to as the process.The job of the controller is to maintainthe value of the controlled quantity ata set-point or target value, in spite ofthe effects of external interfer-ence. In order to do this, the con-troller must measure an actual valuey, calculate the control error e by com-paring the actual value to the targetvalue w, and output a controlvalue u that depends on the value ofthe control error and which achievesthe desired effect. (Note: the officialterm for the control value is ‘manipu-lated variable’.)

A characteristic feature of everycontrol system is closed loop opera-tion, as illustrated in Figure 1. It is nec-essary that a given input signal pro-duces a specific output signal, for boththe controller and the process. In gen-eral, the relationship between theinput an output signals is time-dependent.

The step response is an essentialcharacteristic of both processes andcontrollers. It reflects how the outputsignal responds when the input signalu changes instantaneously from onelevel to another level. The waveformshown in Figure 2 illustrates a stepresponse that is typical of manyprocesses. For example, if a given DCvoltage is applied to a resistive heatingelement, the graph of its temperatureas a function of time will be similar tothis curve.

A controller is also a transfer ele-ment that produces a control value(output signal) in response to a controlerror (input signal). Depending on theway in which the controller responds, itcan be classified as a proportional, inte-gral or derivative controller. In a pro-portional controller (P controller), thetransfer element is in principle nothingmore than an amplifier. Its output sig-nal changes in proportion to its inputsignal, with the gain being anadjustable parameter. As the namessuggest, the transfer element of anintegral controller (I controller) is anintegrator, and the transfer element of aderivative controller (D controller) is adifferentiator. With the latter types ofcontrollers, both the time constant andthe gain are adjustable parameters.

A controller that combines all threetypes of response, called a PID con-troller, has proven its worth as a sort of‘universal’ controller. As shown in Fig-ure 3, the control value consists of thesum of the outputs of the three typesof controllers, which can be assignedindividual weighting factors accordingto the desired controller response.

The mathematicalrelationship betweenthe control error andthe control value is called the controlalgorithm. For a PID controller, this isa differential equation.

The primary difference between adigital controller and an analogue con-troller is that with a digital controllerthe actual value is not measured con-tinuously, but is instead periodicallysampled at some fixed interval T0. Inthe time between two successive sam-ples, the control error must be deter-mined and the control value calculatedusing the control algorithm.

The following equation can be usedas the control algorithm of a PID con-troller (see the sidebar ‘Digital PID con-troller design’ for the derivation of thisequation):

uk = u(k–1) + q0ek + q1e(k–1) + q2e(k–2)

In this equation, the index k representsthe running count of the individualmeasurements. This means that e(k–1)is the control error for the previousmeasurement. The control parametersq0 through q2 can be approximatelydetermined from the characteristicparameters of the process stepresponse using the following formulas:

q0 = [1.5TG/(KpTu)](1 + Tu/2T0)

q1 =[1.5TG/(KpTu)](T0/2Tu –Tu/T0 – 1)

q2 = 3TG/4KpT0

The step response of the process mustbe measured experimentally to obtainthese values. The parameters mustalso satisfy the following conditions:

q0 > 0q1 < 0, |q1| > q0|q0 + q1| < q2 < q0

As a guideline for the value of the sam-pling interval T0, it should chosen to bearound one tenth of the time requiredfor the process step response to reach95% of its final value.

H A R D W A R EA N D S O F T W A R EFigure 4 shows the circuit diagram ofthe controller. Its input is designed forvoltages between 0 and 5 V, which cancome from any desired type of sensor.The input voltage is passed to theinternal A/D converter of the PIC16C71 via opamp IC5a, which acts as abuffer. The low-pass filter formed byR8 and C8 at the output of the opampkeeps high-frequency interferencefrom reaching the A/D input (RA0 ofthe PIC).

The controller output provides a

15Elektor Electronics 9/99

controller process

controlvalue

u

990038 - 12

control errore

set value(target)

w

actualvalue

y

interference valuez

e = w - y

1

Figure 1. A closedloop is applied to con-trol a process.

t

y (t)

t = 0Tu

Tu = delayTG = transition periodKp = amplification

TG 990038 - 13

2Figure 2. Example of ajump reply.

Page 3: Digital Pid Controller 175

voltage that also ranges from 0 to 5 V.The output current of opamp IC5b iscertainly adequate for use with the pre-viously-mentioned circuit that simu-lates the process to be controlled. Forcontrolling a real process, you will nat-urally have to provide a suitable powerstage that can be driven by the maxi-mum load current (5 mA) of the con-troller output.

IC5b matches the voltage range ofthe D/A converter to that of the A/Dconverter of the PIC. Its gain is set to1.935 by R10 and R11.

An 8-bitDAC IC (Ana-log DevicesAD577) is

used for the D/A converter. It can beoperated from a single 5 V supply anddoes not need an external reference. Itsexternal circuitry is limited to C7,which is necessary to decouple thesupply voltage. In addition, pull-upresistors R2 and R3 are connected tothe clock and data pins of the EEP-ROM IC (24C01).

Furthermore, only a small amountof extra hardware is needed aroundthe PIC itself. In addition to the clockcircuitry with a 4 MHz crystal, there isa reset circuit which requires only afew passive components. The power-on reset is provided by R5 and C5,while a manual reset is provided by R6and S1.

The alarm LED D1 is driven directlyfrom the RA4 port output, and the D/Aconverter chip and the LCD moduleare also connected directly to the out-put port pins of the PIC. In the inputmode, the same port pins are used forscanning the contacts of the parameter-input switches. Except for S2, these arearranged as a 4×4 matrix, with fourport connections on each side. S2 isused as the SET pushbutton for con-firming input values; it connects RB0to earth when actuated.

The power supply is just as simpleas the rest of the circuit. It consists of a5 V regulator, two electrolytic capaci-tors and a reverse-polarity protectiondiode at the input connector for anexternal 9 V mains adapter.

As far as the software is con-cerned, the tables for the predefineddisplay text and the instructionsneeded to control the serial EEPROMboth take up quite a bit of storagespace. The mathematical routines forcalculating the control quantities alsotake up a certain amount of space.The actual controller program ismodest by comparison.

The program is protected by awatchdog timer, which in case of a fail-ure triggers a reset and an alarm (blink-ing LED D1) and also sets the controlquantity to zero. If this happens, thecontroller must be restarted, but it isnot necessary to re-enter the control

16 Elektor Electronics 9/99

Icontroller

Pcontroller

Dcontroller

control valueu

990038 - 15

control errore

3

Figure 3. Block dia-gram of a PID con-troller.

Figure 4. Circuit dia-gram of the PIC-baseddigital PID controller.

16C71

OSC2

IC2

OSC1

MCLR

RA4

RA0

RA1

RA2

RA3

RB0

RB1

RB2

RB3

RB4

RB5

RB6

RB7

PIC

17

18

13

12

11

10

16 15

14

1

3

9

8

7

6

2

4

5

AD557

IC3

VOUTD0

D1

D2

D3

D4

D5

D6

D7

12

11

13

16

15

14

CE

10CS

SA

SB

1

2

3

4

5

6

7

8 9

24C01

IC1 SDA

SCL

A0

A1

A0

WP

1

5

8

4

6

2

3

7

2

3

1IC5a

X14MHz

R4

27

R5

10

k

R6

10

R13

1M

C2

22p

C3

22p

C4

100n

C8

10n

C7

100n

C1

100n

R10

9k53

1%

R7

10Ω

R11

10

k0

1%

R2

10

k

R3

10

k

6

5

7IC5b

S1

RESET

C5

10µ10V

R8

1kR12

10k

S15

S11

S7

S3

S2

S16

S12

S8

S4

S17

S13

S9

S5

S18

S14

S10

S6

RB0

RB1

RB2

RB3

RB4

RB5

RB6

RB7

RB0

RB1

RB2

RB3

RB4

RB5

RB6

RB7

RB3

RB2

RB1

RB0

RB

4

RB

5

RB

6

RB

7

RB7

RB6

R1

1k

5

D1

1

2

3

4

5

6

7

8

9

10

11

12

13

K1

14

R9

10k

RB0

RB1

RB2

RB3

RB4

RB5

RB6

RB7

C6

10µ10V 10k

P1

7805

IC4

C10

10µ 10V

C9

100µ 25V

D2

1N4001

+9V +5V

+8V4 5V

5V 5V

VSS

VDD

VO

RS

R/W

E

D0

D1

D2

D3

D4

D5

D6

D7

5V

5V5V5V

5V

C D E F

8 9 A B

4 5 6 7

0 1 2 3

SET

990038 - 11

IC5

8

4

IC5 = TLC272

LM16A211

C11

100n

8V4

4

Page 4: Digital Pid Controller 175

parameters, since thevalues that were previ-ously stored in the EEP-ROM can be used again.

Since the programneeds a very large number of registers,some registers must be used for more

than one purpose. Inprinciple, this is not aproblem, since (forexample) the registersused for performing

calculations are never used duringparameter input. The only disadvan-

tage is that the registers that are usedmore than once do not have meaning-ful names.

If you want to carefully study ormodify the program, you will find thesource code on a diskette availablethrough our Readers Services.

C O N S T R U C T I O N A N DO P E R A T I O NConstructing the circuit on the printedcircuit board does not require anyunusual skills. Since the circuit board issingle-sided, a few jumpers areunavoidable. Do not overlook themwhen stuffing the board.

The keypad module specified in thelist of components must be used for theparameter input pushbuttons, due tothe internal connections. An unregu-lated 9 V mains adapter can be used forthe power supply, as long as it can sup-ply at least 200 mA.

When setting up the board, firstadjust P1 to set the contrast of the dis-play for optimum readability.

A simple circuit, shown in Figure 7,has been designed for testing the con-troller and experimenting with it. Thiscircuit simulates the process to be con-trolled. The step response of theprocess is determined by the time con-stants of three RC low-pass circuits

17Elektor Electronics 9/99

Figure 5. PCB tracklayout and componentmounting plan (boardavailable ready-made).

990038-1(C) ELEKTOR

C1

C2C3

C4 C5

C6

C7 C8

C9 C10

C11

D1

D2

H1 H2

H3H4

IC1

IC2

IC3

IC4

IC5

K1

OU

T

P1

R1

R2

R3

R4

R5

R6

R7

R8

R9

R10

R11

R12

R13

S1S2S3 S4 S5 S6

S7 S8 S9 S10

S11 S12 S13 S14

S15 S16 S17 S18

X1

T

0 1 2 3

4 5 6 7

8 9 A B

C D E F

Set Reset

T

T

0

+9V

+5V

0

990038-1

990038-1(C) ELEKTOR

5COMPONENTS LIST

Resistors:R1 = 1kΩ5R2,R3,R5,R9,R12 = 10kΩR4 = 270ΩR6 = 100ΩR7 = 10ΩR8 = 1kΩR10 = 9kΩ53 1%R11 = 10kΩ 1%R13 = 1MΩ

Capacitors:C1,C4,C7,C11 = 100nF ceramicC2,C3 = 22pF ceramicC5,C10 = 10µF radialC6 = 10µF 10VC8 = 10nF MKT (Siemens)C9 = 100µF 26V radial

Semiconductors:D1 = LED, red, high efficiencyD2 = 1N4001IC1 = 24C01IC2 = PIC16C71, order code

996504-1IC3 = AD557JN (Analog Devices)IC4 = 7805IC5 = TL272CP

Miscellaneous:X1 = 4MHz quartz crystalK1 = LM16A211 LCD module,2 x 16

characters (Sharp)S1-S18 = pushbutton, PCB mount,

ITC type D6-R-RDPCB, order code 990038-1Disk, contains PIC source code,

order code 996003-1

Page 5: Digital Pid Controller 175

connected in series. The time constantsof this ‘electronic process’ can thus beeasily changed, and interference can beeasily simulated by loading the outputwith the switchable resistor. To use thesimulation circuit, connect its input tothe output of the controller and its out-put to the input of the controller.

Control parameter values can beentered only immediately after the cir-cuit is switched on or directly follow-ing a reset. They are entered in hexa-decimal form by means of the keypad.Two characters will be displayed aftertwo keys have been pressed in turn.The SET button must be pressed forthe entered value to be accepted andstored in EEPROM. The target valueand the initial value of the controlquantity can be set between 00H andFFH, which corresponds to a voltagerange of 0 to 5 V. The upper and lowerlimit values can also be set between

00H and FFH. Thelength of thesampling interval(display indica-

tion ‘INTERVAL’) is determined bymultiplying a basic increment of 0.1 s(fixed in software) by the entered hexa-decimal value.

The parameters q0, q1 and q2, whichare important for the control algo-rithm, are entered as fixed-point num-bers, with one byte (two hex charac-ters) before the decimal point and onebyte after the decimal point. The bitsafter the decimal point are weightedaccording to 1/2n, where n representsthe bit position (MSB = 1, LSB = 8). Ahex value of 80 after the decimal pointthus corresponds to 1/2 (0.5 decimal).Since q1 is always negative, a shortexplanation of the representation ofnegative binary numbers is in order. Anegative binary number is formed bybitwise inverting a positive numberand adding one to the result. An exam-ple is:

13D = 0000 1101B = 0DHinverted: 1111 0010B = F2H+1: 1111 0011B = F3H

For 8-bit signed numbers, this results ina range of values from +127D (7FH) to–128D (80H). Negative 8-bit numberscan be recognized by the fact that theMSB is a 1.

The integer and fractional bytes ofq0 through q2 must be entered sepa-rately (for example, Q0HI and Q0LOare entered by pressing two keys foreach byte, with SET pressed betweenthe first and second pair of value-entrykeys).

If you use the simulation circuitshown in Figure 7, you can achieve sat-isfactory results with the followingparameter values:

q0 = 13.5D = 0D80Hq1 = –18.5D = ED80Hq2 = 6.5D = 0680Hsampling interval = 0.4 s (enter ‘04’)target value = 80H (approx. 2.5 V)initial control value = A0H (approx.3.1 V)

Since the electrolytic capacitors in thesimulation circuit have quite large tol-erances, it is possible that the controllerwill not operate optimally with theabove values. In this case the values ofq0 through q2 should be empiricallyadjusted.

The output signal of the controlleris set to 0 V during parameter entry.After parameter entry has been com-pleted by pressing SET, the controlvalue (CONTROL VAL) is output at alevel equal to its entered initial valueuntil the entered target value (SET-VALUE) is reached. After this, theactual control process starts up and,depending on the selected controlparameter values, more or less exactlymaintains the controlled variable at theset value, even in the presence of inter-ference. During the control process, thecurrent levels of the control value(CONTROL VAL) and the actual value(ACT.VAL) are continuously displayed.

If either the upper or lower limitvalue (UPPER LIMIT or LOWERLIMIT) is exceeded, the alarm lamp(LED D1) blinks for the duration ofout-of-limits condition. No new valuesare displayed during this interval. Thecontroller output goes to zero if theupper limit is exceeded, and to FFH(5 V) if the lower limit is exceeded.

If the controller is started anew bypressing Reset, the parameter entryprocess must be run through again bypressing SET after each parametervalue is displayed. SETVALUE appearsfirst on the display, with the last savedvalue. The values of CONTROL VAL,UPPER LIMIT, LOWER LIMIT andINTERVAL follow in turn, eachappearing after SET has been pressed.The stored values are displayed foreach parameter in turn, and can bemodified if necessary.

(990038-1)

18 Elektor Electronics 9/99

6

Figure 6. Finished pro-totype of the digitalcontroller.

Figure 7. This little cir-cuit simulates a‘process’ for testingthe controller.

1k

100µ

10

0k

4k7

100µ

10k

100µ

990038 - 14

7

Page 6: Digital Pid Controller 175

19Elektor Electronics 9/99

The easiest approach is to start with an analogue controllerdesigned according to the block diagram shown in Fig-ure 3, whose control algorithm is given by the following dif-ferential equation:

In this equation, KPR, KDR and KIR represent the(adjustable) gains of the three controllers (P, D and I con-trollers) shown in Figure 3. This equation can also be rep-resented in the frequency domain by applying the Laplacetransform, as follows:

where it is assumed that the initial conditions are all zero.The gains of the three parts of the controller (often referredto as the proportional, integral and derivative coefficientsof the controller) must be set by the designer according tothe desired control response.The next step is to find a discrete equivalent for the con-troller described by equations 1 and 2. The backwards dif-ference is defined as the discrete-time equivalent of thecontinuous-time derivative of a function. It is given by theformula

in which T is the period of the sampling signal (the sam-pling interval).The finite sum is defined as the discrete-time equivalent ofthe continuous-time integral of a function. It is given by theformula

If the relationships shown in formulas 3 and 4 are appliedto the first two equations, the result is the following equation,which is shown in the article as the control algorithm of adigital PID controller:

Once again, the index k is the running count of the indi-vidual measurements. This means that e(k-2) is the controlerror for two sample intervals prior to the present mea-surement.

u u q e q e q ek k k k k= + ⋅ + ⋅ + ⋅− − −( ) ( ) ( )1 0 1 1 2 2

f T f a T f a T f b

a

b

( ) ( ) ( ) . . . ( )τ = + + + + +[ ]∫ 2

∆f t f t f t T T( ) ( ) ( ) /= − −[ ]

u s K e s K s e s K s e sPR DR ID( ) ( ) ( ) ( / ) ( )= ⋅ + ⋅ ⋅ +

u t K e t K de t dt K e dPR DR IR

t

( ) ( ) ( )/ ( )= ⋅ + ⋅ + ⋅∫ τ τ

0

Digital PID controller design

With the passing of the years,developments and inventions inthe electrical field succeeded eachother in increasing tempo. In1876, Alexander Graham Bell(1847–1922) developed the tele-phone. The sound to be transmit-ted via the telephone line waspicked up by a funnel-shapedhorn. The horn was terminated bya thin metal diaphragm immedi-ately behind which was a smallcoil wound on a bar magnet.When sound entered the horn, thediaphragm vibrated and therebyvaried the distance between the diaphragm and the coil. This causeda voltage to be generated in the coil that alternated in rhythm withthe sound signal. When two such devices were linked by a long wire,the speaker at one end could bring the diaphragm at the other endinto vibration. The same device was thus used for speaking and lis-tening by alternately bringing it in front of the mouth and againstthe ear. This setup was improved fairly quickly and provided, amongothers, with a different kind of earpiece. Within a few years – in 1878– the first public telephone network was opened in the United States.

Within a year after the introduction of the telephone, ThomasAlva Edison (1847-1931) had devised a contraption that consistedof a wooden cylinder around which was wound a sheet of tinfoil, anarm that enabled a needle to be brought into contact with the tin-foil, and a crank to rotate the cylinder. Edison set the needle in con-tacts with the tinfoil, rotated the cylinder with the aid of the crank,and into a horn-shaped mouthpiece attached to the needle he sang (orshouted): “Mary had a little lamb …”. When he turned the cylinderagain, the horn of the instrument produced a recognizable repro-

duction of his voice. Thus was born the phonograph or, as it is bet-ter known in Europe, the gramophone.

Although the reproduction was not of very good quality, the prin-ciple had been established. Ten years later, Emile Berliner(1851–1929), another American inventor, produced an improvedversion of the phonograph, which he called ‘gramophone’. In contrastto Edison’s instrument, which used a variable-resistance transmit-ter, that of Berliner used a flat disk instead of a rotating cylinder.The flat disk is, of course, the forerunner of the modern gramo-phone record. In the Berliner system, the grooves on the disk aremodulated laterally, whereas those on the Edison cylinder areamplitude-modulated.

In 1879, in America, Edison, and in England, the British physi-cist and chemist Sir Joseph Wilson Swan (1828–1914) simultane-ously introduced the first practical incandescent lamp. It was, per-haps, not so much the improvement of the filament that made theincandescent lamp a success as the evacuation of the bulb (in whichSwan was aided by Charles Stearn, an expert in the production ofhigh vacua). Edison and his team perfected the filament: after exam-ination of thousands of alternatives, they devised the cotton-threadfilament which, when joined with the bulb patents of Swan andStearn, made the Edison lamp a commercial success.

in 1890, a young Dutch mechanical engineer, Gerard Philips(1858–1942), decided to set uphis own company to produceincandescent lamps. Thisresulted in 1891 in the PhilipsGloeilampenfabriek in Eind-hoven, which soon becamefamous all over the world and isstill an important multinationalcompany today.

[995073]

WHEN ELECTRONICS WAS YOUNG (7)

Alexander Graham Bell(1847...1922)

Antique phonograph