# PID Control Intro with the BASIC Stamp

Andy Lindsay (Parallax)
Posts:

**1,919****PID Control Intro with the BASIC Stamp**

·

Most of us tend to enjoy the benefits of control systems without ever giving them a second though.· Consider the heaters, coolers and thermostats that maintain the comfortable temperatures in our homes and workplaces.· We just set the temperature on the thermostat, and the control system takes care of the rest.· In this case, the control system's job is to regulate temperature, and when it does it's job we hardly think about it at all.· Now, if it stops working during a heat wave or cold snap, well, that's an entirely different story.

·

More examples of control systems can be found inside our cars, where they are responsible for the smooth ride, anti-lock braking, fuel delivery and ignition just to name a few.· Factories make use of control systems to maintain fluid levels in tanks, temperatures in curing ovens, and automated placement of parts in assembly lines.· In the robotics world, control systems are used to help them maintain balance, distance from other robots or walls, and to refine navigation.· With so many projects and products using control systems, the design techniques for control systems can be a useful addition to just about any inventor's toolbox.

·

·

Closed loop control is the kind of control where information from sensors is used to determine what the actuators in the system do.· It is so named because the diagrams that describe the interaction between sensors and actuators draws a closed loop.· (See Figure 1.)· Some examples of sensors and actuators in closed loop systems include distance sensors and motors, temperature sensors and heaters/coolers, and fluid/gas level sensors and valve controls.·

·

·

The block diagram for closed loop control in Figure 1 describes a process that is repeated over and over again.· A sensor measurement is compared to the desired measurement (called the set point), resulting in an error calculation.· Some math is performed on this error value (control calculations) to determine the output that goes to the actuator.· The actuator has some effect on the system.· The sensor is again checked to find out the result of the actuators influence, and the whole loop is repeated.· Monitoring the influence of an actuator on a system and adjusting its influence on that system based on the sensor measurement is called feedback.· The closed loop in Figure 1 is often referred to as a feedback loop.

·

·

There are lots of different control calculations that can be made to determine the actuator output.· One of the most common and effective methods is called proportional-integral-derivative control, which is abbreviated PID.· In fact, many of the factory, automotive, and robotic control system examples mentioned earlier involve PID.·

·

This Chapter introduces PID control, explains how it works, and demonstrates how you can do PID calculations with the BASIC Stamp 2.· In this chapter's activities, you will provide the BASIC Stamp with sensor feedback by sending it messages from the Debug Terminal's transmit windowpane.· You will also monitor the PID controller’s output responses to get more familiar with the role of each of the three types of control.· In coming Chapters, you will use PID to smooth out the Boe-Bot’s following behavior, and improve its line following performance.····

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Andy Lindsay

Education Department

Parallax, Inc.

*Post Edited (Andy Lindsay (Parallax)) : 8/24/2010 6:42:01 PM GMT*

## Comments

1,919Activity #1: Proportional Control with PBASICThe P in PID stands for proportional.· This activity introduces closed loop control with just the proportional calculation along with a PBASIC program that performs this calculation.· This activity demonstrates how a proportional calculation can be used to have an effect on the system that is "proportional" do the difference between the measured level and the desired level.

The Proportional Control LoopProportional control is sufficient for some systems, and examples of proportional control can be found in both

Industrial ControlandRobotics with the Boe-Bot.· As circuit schematics are used to describe circuits, block diagrams are used to describe control systems.· A block diagram for proportional control is shown in Figure 2.· The circle on the left is called a summing junction, and it shows how the measured sensor value is subtracted from the desired sensor value (the set point) to calculate the error.· This is the error that needs to be corrected by the control system.· Proportional control attempts to correct this error by multiplying it by some constant value (Kp).· The resulting actuator output exerts a correcting influence on the system.· By definition, this influence is proportional to the measured error.· Since the actuator output has some effect on the system, the sensor value is checked again, and the whole process is repeated, over and over again to maintain the level(s) in the system.·

·

Let's say a robot is trying to maintain a distance between itself and a target, but something keeps moving the target.· Proportional control will detect the change in distance and apply drive to the robots wheels to make it back away from or catch up to the target.· This drive is proportional to the error in the distance measurement.· Keep in mind that "error" doesn't mean the distance measurement is wrong, it just means that the measurement is different from the desired value.· Figure 3 shows a graph of the change in some error measurements over time.· Notice how the error is 3 in the sample at time = 2.· Since Kp is 10, the output is 30.· In the second sample at time = 7, the error is -2, so the output is -20.

·

Example Program - ProportionalControl.bs2Let's look more closely at how proportional control works with ProportionalAlgorithm.bs2.· This program takes a sensor input that you enter into the Debug Terminal's transmit windowpane, performs the error and proportional calculations, and sends the drive value to the Debug Terminal's receive windowpane.· (See Figure 4.)

·

·

√······· Enter and run ProportionalAlgorthm.bs2.

√······· For each number you enter, the output value should be ten times the calculated error.

√······· Try this sequence of numbers, making sure to press the space bar once between each number to make the

DEBUGINcommand accept it.· 1 2 3 2 1 0 -1 -2 -3.How ProprotaionalControl.bs2 worksThe

DO...LOOPrepeats the operations in the proportional control block over and over again.· Figure 5 shows how each element in the block diagram is performed by a PBASIC statement.· You are the System block and the sensor input.· The program gets thesensorInputvariable from you with the commandDEBUGIN SDEC sensorInput. ·It then performs the error calculation with this statementerror(Current) = SetPoint - sensorInput.· The proportional block is executed with this statementp = Kp * error(current).· The actuator output, which is also an input to the system is determined by this command:drive = p.·

Your Turn - Adding Offset to the Actuator OutputLet's say that you expect sensor values from -10 to 10, but you need to use these values to control a servo.· Let's also say that the useful signal input range for the servo is from 1.3 ms to 1.7 ms.· That translates to

PULSOUTaugments that range from 650 to 850 for the BASIC Stamp 2.· You will need to add an offset to the output values as shown in Figure 5.· Since the input is from -10 to 10, and Kp is 100, it means the result of the proportional block (Kp) will be -100 to 100.· So, your offset value will have to be 750 to give youDurationPULSOUTarguments that range from 650 to 850.Duration·

·

To make the program accommodate the extra summing junction, you will have to modify this statement:

·

· ' Calculate output.

· drive = p

·

One simple way to do it would be like this

drive = p + 750.· However, it's a better coding practice to declare a constant at the beginning of the program and then use it in the drive statement, so try this:·

√······· Add this constant declaration to the beginning of the program

Offset CON 750.√······· Change the drive calculation to

drive = p + Offset.√······· Run the modified version of the program and verify that inputs from 10 to -10 result in outputs from 650 to 850.

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Andy Lindsay

Education Department

Parallax, Inc.

Post Edited (Andy Lindsay (Parallax)) : 8/24/2010 6:43:09 PM GMT1,919Activity #2: Integral ControlProportional is just one way to react to an error in the system.· The problem with proportional control is that it can't detect trends and adjust to them.· This is the job of integral control.

·

There is another example graph of the error in a system over time on the left of Figure 6.· Again, it might be the distance of a robot from an object, or it could be fluid level in a tank, or the temperature in a factory oven.· Perhaps the target the robot is following keeps on going away from the robot at a speed that the robot isn't catching up with.· Maybe the oven door seal is worn; maybe the fluid draw from the tank is unusually large.· Regardless of the cause, since proportional is not designed to react to trends it can't detect and correct the problem.· That's where integral control comes into the picture.·

·

Integral measures the area between the error values and the time axis.· If the error doesn't return to zero, the area of the error gets larger and larger.· The right side of figure 6 shows how the integral output can react to this kind of trend.· As the area between the error curve and the time axis increases, the output increases proportional to this area.· As a result, the output drives the actuator harder and harder to correct the error.

·

·

So what happens when the error isn't a straight line, like the curve shown in Figure 8?· That's what the calculus operation of integration determines, the area between a curve and an axis.· In the case of integral control, as more time passes with an error, the area under the curve grows, and so does the value that the integral calculation will use to drive against the system error.· If the error curve drops below the time axis, the buildup of negative area subtracts from the buildup of positive area.· When tuned correctly, integral control can help the system home in on an error of zero.

·

·

The BASIC Stamp can approximate the error under the curve with numerical integration.· Figure 9 shows how you can approximate the error under a curve by adding up the area of a bunch of little rectangles between the error curve and the time axis.· The area of each box is the error multiplied by the time between measurements.· By adding up all the box areas, you get an approximation of the area under the curve.·

·

·

So long as your measurements are evenly spaced, you can call the width of each box a value of 1.· This makes the math much simpler than trying to account for 20 ms between samples, 5 minutes between samples, or whatever your sampling rate turns out to be.· Instead of multiplying error by the time increment between samples and then adding to the next error multiplied by time, you can just multiply each error sample by a time of 1.· The result is that you can just keep a running total of error measurements for your integral calculation.· Here is an example of how to do this with PBASIC:

·

· ' Calculate integral term.

· error(Accumulator) = error(Accumulator) + error(Current)

· i = Ki * error(Accumulator)

·

The next example program performs numerical integration on the error signal and adjusts the output accordingly.· As with proportional control, there is a constant that scales the integration output to the desired value.· For simplicity's sake, we'll use 10 again for Ki.· Figure 10 shows a block diagram of the control loop. ·The term Kp ∫ edt refers Kp multiplied by the integral of the error over time.· In other words, Kp multiplied by the accumulated area between the error curve and the time axis.

·

Example Program - IntegralAlgorithm.bs2√······· Enter, save, and run IntegralAlgorithm.bs2.

√······· Enter this sequence of values into the Debug Terminal's transmit windowpane: 3 3 3 3 3 3 3 3 3.· Notice how the integral output gets larger every time the 3 is repeated.· That's integral's job, to detect trends and increase the drive to correct it as needed.

√······· Now try this sequence: 1 2 3 4 5 4 3 2 1 0 -1 -2 -3 -4 -3 -2 -1 0.· The area under this curve is 0 since the negative area is the same as the positive area.· That is also what the integral calculation will arrive at when you have finished entering the sequence.

How IntegralAlgorithm.bs2 WorksThis program is a ProportionalAlgorightm.bs2 modified to perform the integral calculation instead.· There are now two different types of errors to keep track of, so there the error variable array was expanded to two elements.· The

error(0)variable tracks the current error, anderror(1)tracks the accumulated error.· The constantsCurrent CON 0andAccumulator CON 1make the bookkeeping a little more sensible witherror(current)anderror(accumulator).·

The other change that was made is that the error is accumulated and the integral output is calculated with these two statements:

·

· ' Calculate integral term.

· error(Accumulator) = error(Accumulator) + error(Current)

· i = Ki * error(Accumulator)

·

Your Turn - Clamping the Integral OutputAs you may have gathered from repeatedly entering 3 into the Debug Terminal, the integral drive output can really start to run away.· You can use the

MINandMAXoperators to keep integral control from going overboard with the output.· Let's repeat the servo offset activity and limit the output from 650 to 850.··

√······· Change the

drive = istatement todrive = i + Offset MIN 650 MAX 850.√······· Run the program and verify that the integral output is limited to values between 650 and 850.· Try entering 2 repeatedly, then -2 repeatedly.

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Andy Lindsay

Education Department

Parallax, Inc.

Post Edited (Andy Lindsay (Parallax)) : 8/24/2010 6:44:09 PM GMT1,919Activity #3: Derivative ControlHere's a situation that neither proportional nor integral control really deal with.· It's rapid changes to the system that come from an external source.· Keeping the system steady when outside influences are making it change abruptly is the job of derivative control.· In calculus, derivative is an operation that measures the rate of change of a curve, such as the error curve shown in Figure 11.· By taking action based on the rate the error is changing, the output drive can respond rapidly to disturbances to the system.·

·

·

Like the samples in Figure 11, calculus can be used to examine any point on the curve and give you an exact slope.· Circuits that involve operational amplifiers do these continuous calculations for continuous time control systems.· When a signal is digitally sampled periodically, derivative can be an algebraic slope calculation.· The BASIC Stamp can then take the difference between two sampled points on a curve, and divide by the distance (time) between those two points.·

·

·

In the case of the error vs. time graph, derivative would be the change in error divided by the change in time.· That's ∆e/∆t.·· As with integration, numerical differentiation (calculating the derivative) can be simplified for control purposes by always considering the time between samples to be a value of 1.· Then, numerical differentiation can be accomplished by subtracting the value of the previous error measurement from the current error measurement.· In other words, derivative control can be accomplished with simple subtraction:

·

· ' Calculate derivative term.

· error(Delta) = error(Current) - error(Previous)

· d = Kd * error(delta)·

·

Although ∆t might be a small or a large value, so long as it's always the same interval, the derivative constant, Kd can be scaled to compensate for the fact that we made ∆t equal to 1.· Keep in mind that the rate that the errors are sampled also has to be faster than the error signal's tendency to change.

·

The job of derivative control is to react to changes in the system.· For example, a constant error of -3 will be dealt with by proportional and integral control, but derivative won't touch it.· Why?· Because derivative only reacts to changes.· With a series of errors of the same value, there's no change.· However, any kind of change, such as the error going from -3 to 4, will cause derivative control to resist.· Let's try an example program and observe how this works.·

·

Figure 13 shows a block diagram for the derivative control loop the next example program will emulate.· As with the other examples, Kd will be 10.· This program will measure the rate of change of the error measurement (de/dt) and multiply by Kp = 10.· This result will go to your Debug Terminal (actuator output).

·

Example Program - DerivativeAlgorithm.bs2Try entering a series of sensor inputs that don't change, like 3 3 3 3 3 3 3 -4.· Derivative will resist the first 3 because that's a change from 0 to 3, but all the rest of the threes will result in no correction from the derivative calculation.· Then, with the big change from 3 to -4, the derivative will drive hard to correct this abrupt change.

·

√······· Enter, save, and run DerivativeAlgorithm.bs2.

√······· Try 3 3 3 3 3 3 3 -4.· Verify that derivative resisted the first 3 but made no attempt to correct the others.·

√······· Also verify that the the big change from 3 to -4 resulted in a large output to correct the change in error.

How DerivativeAlgorithm.bs2 WorksThe error array variable now has four elements.· Element 0 is still the current error, element 1 is the accumulator, which is unused at present since there are not integral calculations in this program.· Element 2 is used to store the previous error measurement, and element 3 is used to store the difference between the previous and current measurements.· The constant for element 2 is

Previous, and the constant for element 3 isDelta.· That makes the derivative calculation much easier to read.·

· ' Calculate derivative term.

· error(Delta) = error(Current) - error(Previous)

· d = Kd * error(delta)

·

At the end of each pass through the loop, the current measurement has to be saved as the previous measurement.· There will be a new

error(current)the next time through the loop, and a newerror(delta)will be made with the updatederror(Previous)value.·

· ' Save current error to previous error before next iteration.

· error(Previous) = error(Current)

Your Turn - Increasing the Reaction to Abrupt Changes√······· Try changing the derivative constant (Kd) from 10 to 20.· It should react twice as strongly as before to abrupt changes in the error.

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Andy Lindsay

Education Department

Parallax, Inc.

Post Edited (Andy Lindsay (Parallax)) : 8/24/2010 6:45:10 PM GMT1,919Activity #4: All Together Now - Proportional, Integral, and DerivativeA PID control loop involves some contributions from each of the three kinds of control: proportional, integral, and derivative.· The amount of contribution that each of the controls makes can be adjusted by changing their proportionality constants, Kp, Ki, and Kd.· By making these constants larger or smaller, you can make the contribution of one of the controls more dominant or subtle in the system.· One system might need only light integral control, some proportional and strong derivative, while another system might need strong integral and proportional controls, but not much derivative, while still another system might need roughly equal measures of each.

·

Here are several important things to keep in mind when working with PID control loops:

·

•········· Error is the difference between the level you want and the level that is measured, and control loops work to correct error.

•········· Proportional control resists error by applying an opposing influence that is proportional to the error.

•········· Integral control detects and corrects trends in error over time.

•········· Derivative control detects and resists abrupt changes in the system.····

·

·

The next example program will perform this PID control loop.· To make comparisons easier, Kp, Ki, and Kd are all set to 10.

·

Example Program - PidAlgorithm.bs2Keep in mind that proportional always does some work when there's some error.· However, integral and derivative are ready to do extra work to correct the error, integral to correct trends, and derivative to correct abrupt changes.·

·

√······· Enter, save, and run PidAlgorithm.bs2.

√······· Here is a series of sensor inputs that the integral control will detect as a trend and resist much more strongly than either proportional or derivative: 1 2 3 4 5 5 5 5 5 5 5 5 5

√······· Here is a series of sensor measurements that derivative will work hard to correct while proportional and integral don't do nearly as much: 3 -3 4 -4 5 -5 6 -6 5 -5 4 -4

Your Turn - Tuning the PID Control LoopAssume that your sensor inputs will range from -10 to 10.· Adjust your constants (Kp, Ki, and Kd) so that the maximum contribution any of the controls can make to the output ranges from 650 to 850.· To get the integral control to adhere to this requirement, you will also have to use the MIN and MAX operators.·

_____________________________________________________________________________

·

The draft material in this Topic·is part of a forthcoming Stamps in Class text by Andy Lindsay.

·

(c) 2005·by Parallax Inc - all rights reserved.··

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Andy Lindsay

Education Department

Parallax, Inc.

Post Edited (Andy Lindsay (Parallax)) : 8/24/2010 6:45:44 PM GMT236657Good explanations and illustrations.

Nice job!

5Can you please look at the questions I have posted under Jo's A/D and D/A converter problem.

Thanks for your help ... I have printed off you PID explination, and it looks awsome.

Thanks again.

1,919Yes, I posted a reply to your questions on the A/D and D/A converter problem post.

Regards, Andy

26Your PID article is really excellent - clear, practical and well presented. Do you think you can do something similar for Fuzzy Logic Control ?

511,231Easy questions I like [noparse]:)[/noparse]

-Martin

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Martin HebelSouthern Illinois University Carbondale - Electronic Systems Technologies

Personal Links with plenty of BASIC Stamp info

StampPlot - Graphical Data Acquisition and Control

191,919···· drive(max) = Kp x error(max)

So,

···· Kp = drive(max) / error(max)

Let's say you want your proportional to contribute at most 70 percent of the total drive (in this case, the remainder·might be contributed by integral and/or derivative).· Then, the proportional constant would be:

···· Kp = 0.7 x (drive(max) / error(max))

There are some cases where you might want all the possible output drives to add up to more than your maximum drive.· Especially in the case of derivative, it will allow a quick decisive counterbalance to a sudden change in the system inputs.· For example,·let's say·your derivative term is also 70%.· True, this means the drive might be 140% of your maximum drive in some circumstances.· To prevent too much output drive and at the same time enjoy the benefits of extra derivative for the small fluctuations, use·PBASIC's MAX and MIN operators.· They·can prevent the sum of the proportional, derivative and integral terms from exceeding %100 percent of your maximum allowed output.

Post Edited (Andy Lindsay (Parallax)) : 7/6/2006 10:14:38 PM GMT29About a month ago I posted a question about PID control loops and the BS2 and noone responded! Bless you Andy, for solving my problems and teaching me what I want to know.

Danny22

37But I would just like to ask if it is really make sense to assume the sampling interval to be 1 sec?

As I can see from the codes, the sampling interval = 1 all the time when carrying out the numerical calculus... But it's really not the case in practice, it may be some value close to say 0.01s or even smaller...

I recall what the lecturer said in Uni. he said the sampling interval does affect the control performance....

Alright... let's say we no longer assume the sampling interval = 1sec... we insert a value of say 0.01s into the code...

A problem exists when we compute the derivative part...

Since the denominator is a very small value, 0.01s; the derivative part may become a very large value that basic stamp may not be able to handle/overflowed in some cases.

Does anyone of you try to use other more realistic sampling interval for your projects?

How's the performance?

Thank you very much for sharing!

1,919Using a constant sampling interval affects both the integral and derivative calculations. The thing you have to do is adjust Kd and Ki for your particular sampling rate. For example, if you incrase your sampling rate by 10, your new Kd might have to be ten times your old Kd. Likewise, Ki might have to be 1/10th of the previous Ki.

You also have to choose a sampling rate that gives you a measurable derivative error when you need it.

I did an academic version of PID with the Propeller Microcontroller that used the textbook PID definition, calculating delta-t along with delta-e. In that case, floating point did come in handy. I also did a constant sampling rate approximation version of the same program, and all the math fit into word variable calculations.

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Andy Lindsay

Education Department

Parallax, Inc.

Post Edited (Andy Lindsay (Parallax)) : 3/5/2007 5:04:28 AM GMT38Do you know of any PID Controllers in spin? I found PID_Routines.spin by Craig Weber but am having trouble with it. Are you familiar with it? If so, would you mind explaining it for those of us not using a Stamp? Thanks!

1,919Here's a link to a PID object and test code I wrote based on this thread:

http://forums.parallax.com/showthread.php?p=669248This PID object is a lot more powerful than the PBASIC code featured here because it takes into account the time between calculations.

Note that the test code calls the PID object's init method to set the gains for kp, ki, and kd, along with the set point and high/low clamp values. After the object's init·method has been called, just send its calculate method a measured value, and it returns an output based on the PID calculations.

For background information on how to modify the TestPID object to display the results, see pages 13-21 in the Objects lab, which is available for download from this page:

http://forums.parallax.com/showthread.php?p=617192Andy

P.S. Please keep an eye on the Objects lab. I'm going to post an updated bundle before the end of the week with terminal software so you won't have to use HyperTerminal any more.

Also, please send me a PM if you post a question about that code so that I don't miss it.· Thanks.

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Andy Lindsay

Education Department

Parallax, Inc.

Post Edited (Andy Lindsay (Parallax)) : 8/24/2010 6:46:13 PM GMT38Has anybody successfully used the IMU/KF code in conjunction with a PID. I'm getting funky results, I think due to running out of cogs, but I'm not sure.

401. Could you define Load Line - I worked with alot of PID controllers that have this Feature. I believe it is the Relationship[noparse][[/noparse] between your possible output power and your Delta between Setpoint and ambient.

2. when Using Hysteresis are the calculations still done, just not acted upon or do the calculations get initiated on traversing the hysteresis band?

3. what exactly is fuzzy logic and how is it implemented with PID?