Shop OBEX P1 Docs P2 Docs Learn Events
PID Control Intro with the BASIC Stamp — Parallax Forums

PID Control Intro with the BASIC Stamp

edited 2008-05-21 11:57 in Learn with BlocklyProp
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.
·
attachment.php?attachmentid=73877
·
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.·
·
attachment.php?attachmentid=73878
·
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.
·
attachment.php?attachmentid=73879
·
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
499 x 198 - 15K
555 x 160 - 22K
531 x 255 - 14K
555 x 160 - 21K

Comments

  • edited 2005-03-14 18:56
    Activity #1: Proportional Control with PBASIC

    The 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 Loop

    Proportional control is sufficient for some systems, and examples of proportional control can be found in both Industrial Control and Robotics 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.
    ·
    attachment.php?attachmentid=73880
    ·
    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.
    ·
    attachment.php?attachmentid=73881

    Example Program - ProportionalControl.bs2

    Let'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.)
    ·
    attachment.php?attachmentid=73882
    ·
    ······· 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 DEBUGIN command accept it.· 1 2 3 2 1 0 -1 -2 -3.
    [color=#008000]' ProportionalAlgorithm.bs2[/color]
    [color=#008000]' Demonstrates how proportional control influences error correction[/color]
    [color=#008000]' in a feedback loop.[/color]
     
    [color=#008000]' {$STAMP BS2}[/color]
    [color=#008000]' {$PBASIC 2.5}[/color]
     
    SetPoint       CON     0                     [color=#008000]' Set point[/color]
    Kp             CON     10                    [color=#008000]' Proportionality constant[/color]
     
    Current        CON     0                     [color=#008000]' Current error[/color]
     
    sensorInput    VAR     Word                  [color=#008000]' Input[/color]
    error          VAR     Word(1)               [color=#008000]' One element error array[/color]
    p              VAR     Word                  [color=#008000]' Proportional term[/color]
    drive          VAR     Word                  [color=#008000]' Output[/color]
     
    [color=#0000ff]DO[/color]
     
      [color=#0000ff]DEBUG[/color] "[color=#ff0000]Enter sensor input value: "[/color]
      [color=#0000ff]DEBUGIN[/color] [color=#000080]SDEC[/color] sensorInput
     
    [color=#008000]  ' Calculate error.[/color]
      error(Current) = SetPoint - sensorInput
     
    [color=#008000]  ' Calculate proportional term.[/color]
      p = Kp * error(current)
     
    [color=#008000]  ' Calculate output.[/color]
      drive = p
     
    [color=#008000]  ' Display values.[/color]
      [color=#0000ff]DEBUG[/color] [color=#800080]CR[/color], [color=#800080]CR[/color], [color=#ff0000]"ERROR", [/color][color=#800080]CR[/color], 
            [color=#000080]SDEC[/color] ? SetPoint, [color=#000080]SDEC[/color] ? sensorInput, [color=#000080]SDEC[/color] ? error(Current), [color=#800080]CR[/color],
            [color=#ff0000]"PROPORTIONAL"[/color], [color=#800080]CR[/color], 
            [color=#000080]SDEC[/color] ? Kp, [color=#000080]SDEC[/color] ? error(Current), [color=#000080]SDEC[/color] ? p, [color=#800080]CR[/color],
            [color=#ff0000]"OUTPUT"[/color], [color=#800080]CR[/color],
            [color=#000080]SDEC[/color] ? drive, [color=#800080]CR[/color], [color=#800080]CR[/color]
     
    [color=#0000ff]LOOP[/color]
    
    

    How ProprotaionalControl.bs2 works

    The DO...LOOP repeats 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 the sensorInput variable from you with the command DEBUGIN SDEC sensorInput. ·It then performs the error calculation with this statement error(Current) = SetPoint - sensorInput.· The proportional block is executed with this statement p = Kp * error(current).· The actuator output, which is also an input to the system is determined by this command: drive = p.
    ·
    attachment.php?attachmentid=73883

    Your Turn - Adding Offset to the Actuator Output

    Let'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 PULSOUT Duration augments 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 you PULSOUT Duration arguments that range from 650 to 850.
    ·
    attachment.php?attachmentid=73884
    ·
    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 GMT
    499 x 198 - 13K
    488 x 466 - 36K
    490 x 464 - 97K
    527 x 444 - 30K
    531 x 239 - 12K
    543 x 507 - 23K
    543 x 521 - 30K
    567 x 501 - 21K
    543 x 292 - 15K
  • edited 2005-03-14 19:12
    Activity #2: Integral Control

    Proportional 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.
    ·
    attachment.php?attachmentid=73885
    ·
    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.
    ·
    attachment.php?attachmentid=73886
    ·
    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.·
    ·
    attachment.php?attachmentid=73887
    ·
    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.
    ·
    attachment.php?attachmentid=73888

    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.

    [color=#008000]' IntegralAlgorithm.bs2[/color]
    [color=#008000]' Demonstrates how integral control influences error correction[/color]
    [color=#008000]' in a feedback loop.[/color]
     
    [color=#008000]' {$STAMP BS2}[/color]
    [color=#008000]' {$PBASIC 2.5}[/color]
     
    SetPoint       CON     0                     [color=#008000]' Set point[/color]
    Ki             CON     10                    [color=#008000]' Integral constant[/color]
     
    Current        CON     0                     [color=#008000]' Array index for current error[/color]
    Accumulator    CON     1                     [color=#008000]' Array index for accumulated [/color]error
     
    sensorInput    VAR     Word                  [color=#008000]' Input[/color]
    error          VAR     Word(2)               [color=#008000]' Two element error array[/color]
    i              VAR     Word                  [color=#008000]' Integral term[/color]
    drive          VAR     Word                  [color=#008000]' Output[/color]
     
    [color=#0000ff]DO[/color]
     
      [color=#0000ff]DEBUG[/color] [color=#ff0000]"Enter sensor input value: "[/color]
      [color=#0000ff]DEBUGIN[/color] [color=#000080]SDEC[/color][color=#008000] sensorInput[/color]
     
    [color=#008000]  ' Calculate error.[/color]
      error(Current) = SetPoint - sensorInput
     
    [color=#008000]  ' Calculate integral term.[/color]
      error(Accumulator) = error(Accumulator) + error(Current)
      i = Ki * error(Accumulator)
     
    [color=#008000]  ' Calculate output.[/color]
      drive = i
     
    [color=#008000]  ' Display values.[/color]
      [color=#0000ff]DEBUG[/color] [color=#800080]CR[/color], [color=#800080]CR[/color], [color=#ff0000]"ERROR"[/color], [color=#800080]CR[/color],
            [color=#000080]SDEC[/color] ? SetPoint, [color=#000080]SDEC[/color] ? sensorInput, [color=#000080]SDEC[/color] ? error(Current), [color=#800080]CR[/color],
            [color=#ff0000]"INTEGRAL"[/color], [color=#800080]CR[/color], 
            [color=#000080]SDEC[/color] ? Ki, [color=#000080]SDEC[/color] ? error(accumulator), [color=#000080]SDEC[/color] ? i, [color=#800080]CR[/color][color=#008000],[/color]
            [color=#ff0000]"OUTPUT"[/color], [color=#800080]CR[/color], 
            [color=#000080]SDEC[/color] ? i, [color=#000080]SDEC[/color] ? drive, [color=#800080]CR[/color], [color=#800080]CR[/color]
     
    [color=#0000ff]LOOP[/color]
    
    

    How IntegralAlgorithm.bs2 Works

    This 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, and error(1) tracks the accumulated error.· The constants Current CON 0 and Accumulator CON 1 make the bookkeeping a little more sensible with error(current) and error(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 Output

    As 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 MIN and MAX operators 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 = i statement to drive = 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 GMT
    504 x 155 - 15K
    480 x 216 - 14K
    480 x 216 - 16K
    499 x 198 - 14K
    543 x 212 - 13K
    663 x 257 - 17K
    543 x 273 - 13K
    543 x 255 - 13K
  • edited 2005-03-14 19:20
    Activity #3: Derivative Control

    Here'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.·
    ·
    attachment.php?attachmentid=73889
    ·
    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.·
    ·
    attachment.php?attachmentid=73890
    ·
    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).
    ·
    attachment.php?attachmentid=73891

    Example Program - DerivativeAlgorithm.bs2

    Try 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.

    [color=#008000]' DerivativeAlgorightm.bs2[/color]
    [color=#008000]' Demonstrates how derivative influences error correction[/color]
    [color=#008000]' in a feedback loop.[/color]
     
    [color=#008000]' {$STAMP BS2}[/color]
    [color=#008000]' {$PBASIC 2.5}[/color]
     
    SetPoint       CON     0                     [color=#008000]' Set point[/color]
    Kd             CON     10                    [color=#008000]' Derivative constant[/color]
     
    Current        CON     0                     [color=#008000]' Current error[/color]
    Previous       CON     2                     [color=#008000]' Previous error[/color]
    Delta          CON     3                     [color=#008000]' Accumulated error[/color]
     
    sensorInput    VAR     Word                  [color=#008000]' Input[/color]
    error          VAR     Word(4)               [color=#008000]' Different types of errors[/color]
    d              VAR     Word                  [color=#008000]' Derivative term[/color]
    drive          VAR     Word                  [color=#008000]' Output[/color]
     
    [color=#0000ff]DO[/color]
     
      [color=#0000ff]DEBUG[/color] [color=#ff0000]"Enter sensor input value: "[/color]
      [color=#0000ff]DEBUGIN[/color] [color=#000080]SDEC[/color] sensorInput
     
    [color=#008000]  ' Calculate error.[/color]
      error(Current) = SetPoint - sensorInput
     
    [color=#008000]  ' Calculate derivative term.[/color]
      error(Delta) = error(Current) - error(Previous)
      d = Kd * error(delta)
     
    [color=#008000]  ' Calculate output.[/color]
      drive = d
     
    [color=#008000]  ' Display values.[/color]
      [color=#0000ff]DEBUG[/color] [color=#800080]CR[/color], [color=#800080]CR[/color], [color=#ff0000]"ERROR"[/color], [color=#800080]CR[/color],
            [color=#000080]SDEC[/color] ? SetPoint, [color=#000080]SDEC[/color] ? sensorInput, [color=#000080]SDEC[/color] ? error(Current), [color=#800080]CR[/color],
            [color=#ff0000]"DERIVATIVE"[/color], [color=#800080]CR[/color],
            [color=#000080]SDEC[/color] ? Kd, [color=#000080]SDEC[/color] ? error(Delta), [color=#000080]SDEC[/color] ? d, [color=#800080]CR[/color],
            [color=#ff0000]"OUTPUT"[/color], [color=#800080]CR[/color],
            [color=#000080]SDEC[/color] ? d, [color=#000080]SDEC[/color] ? drive, [color=#800080]CR[/color], [color=#800080]CR[/color]
     
    [color=#008000]  ' Save current error to previous error before next iteration.[/color]
      error(Previous) = error(Current)
     
    [color=#0000ff]LOOP[/color]
    
    



    How DerivativeAlgorithm.bs2 Works

    The 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 is Delta.· 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 new error(delta) will be made with the updated error(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 GMT
    499 x 198 - 14K
    543 x 209 - 9K
    543 x 225 - 11K
    543 x 255 - 13K
  • edited 2005-03-14 19:25
    Activity #4: All Together Now - Proportional, Integral, and Derivative

    A 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.····
    ·
    attachment.php?attachmentid=73892
    ·
    The next example program will perform this PID control loop.· To make comparisons easier, Kp, Ki, and Kd are all set to 10.
    ·
    attachment.php?attachmentid=73893

    Example Program - PidAlgorithm.bs2

    Keep 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

    [color=#008000]' PidMathExample.bs2[/color]
    [color=#008000]' Demonstrates how a combination of proportional, integral, and[/color]
    [color=#008000]' derivative control influence error correction in a feedback loop.[/color]
     
    [color=#008000]' {$STAMP BS2}[/color]
    [color=#008000]' {$PBASIC 2.5}[/color]
     
    SetPoint       CON     0                     [color=#008000]' Set point[/color]
    Kp             CON     10                    [color=#008000]' Proportionality constant[/color]
    Ki             CON     10                    [color=#008000]' Integral constant[/color]
    Kd             CON     10                    [color=#008000]' Derivative constant[/color]
     
    Current        CON     0                     [color=#008000]' Array index - current error[/color]
    Accumulator    CON     1                     [color=#008000]' Array index - accumulated error[/color]
    Previous       CON     2                     [color=#008000]' Array index - previous error[/color]
    Delta          CON     3                     [color=#008000]' Array index - change in error[/color]
     
    sensorInput    VAR     Word                  [color=#008000]' Sensor input variable[/color]
    error          VAR     Word(4)               [color=#008000]' Four different types of errors[/color]
    p              VAR     Word                  [color=#008000]' Proportional term[/color]
    i              VAR     Word                  [color=#008000]' Integral term[/color]
    d              VAR     Word                  [color=#008000]' Derivative term[/color]
    drive          VAR     Word                  [color=#008000]' Output[/color]
     
    [color=#0000ff]DO[/color]
     
      [color=#0000ff]DEBUG[/color] [color=#ff0000]"Enter sensor input value: "[/color]
      [color=#0000ff]DEBUGIN[/color] SDEC sensorInput
     
    [color=#008000]  ' Calculate error.[/color]
      error(Current) = SetPoint - sensorInput
     
    [color=#008000]  ' Calculate proportional term.[/color]
      p = Kp * error(current)
     
    [color=#008000]  ' Calculate integral term.[/color]
      error(Accumulator) = error(Accumulator) + error(Current)
      i = Ki * error(Accumulator)
     
    [color=#008000]  ' Calculate derivative term.[/color]
      error(Delta) = error(Current) - error(Previous)
      d = Kd * error(delta)
     
    [color=#008000]  ' Calculate output.[/color]
      drive = p + i + d
     
    [color=#008000]  ' Display values.[/color]
      [color=#0000ff]DEBUG[/color] [color=#800080]CR[/color], [color=#800080]CR[/color], [color=#ff0000]"ERROR"[/color], [color=#800080]CR,[/color]
            [color=#000080]SDEC [/color]? SetPoint, [color=#000080]SDEC[/color] ? sensorInput, [color=#000080]SDEC[/color] ? error(Current), [color=#800080]CR[/color],
            [color=#ff0000]"PROPORTIONAL"[/color], [color=#800080]CR,[/color]
            [color=#000080]SDEC [/color]? Kp, [color=#000080]SDEC[/color] ? error(Current), [color=#000080]SDEC[/color] ? p, [color=#800080]CR[/color],
            [color=#ff0000]"INTEGRAL"[/color], [color=#800080]CR[/color],
            [color=#000080]SDEC [/color]? Ki, [color=#000080]SDEC[/color] ? error(accumulator), [color=#000080]SDEC[/color] ? i, [color=#800080]CR[/color],
            [color=#ff0000]"DERIVATIVE"[/color], [color=#800080]CR[/color], 
            [color=#000080]SDEC [/color]? Kd, [color=#000080]SDEC[/color] ? error(Delta), [color=#000080]SDEC[/color] ? d, [color=#800080]CR[/color],
            [color=#ff0000]"OUTPUT"[/color], [color=#800080]CR[/color], 
            [color=#000080]SDEC [/color]? p, [color=#000080]SDEC[/color] ? i, [color=#000080]SDEC[/color] ? d, [color=#000080]SDEC[/color] ? drive, [color=#800080]CR[/color], [color=#800080]CR[/color]
     
    [color=#008000]  ' Save current error to previous error before next iteration.[/color]
      error(Previous) = error(Current)
     
    [color=#0000ff]LOOP[/color]
    
    



    Your Turn - Tuning the PID Control Loop

    Assume 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 GMT
    557 x 390 - 23K
    555 x 112 - 15K
    591 x 447 - 21K
  • OrionOrion Posts: 236
    edited 2005-03-15 23:01
    Very nice!!! Thank you!
  • KenMKenM Posts: 657
    edited 2005-03-16 02:11
    Andy,

    Good explanations and illustrations.

    Nice job!
  • vzhzjtvzhzjt Posts: 5
    edited 2005-12-19 20:40
    Andy,

    Can 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.
  • edited 2005-12-20 19:02
    Thanks vzhzjt.

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

    Regards, Andy
  • eblanckeeblancke Posts: 26
    edited 2005-12-29 20:52
    Andy,

    Your PID article is really excellent - clear, practical and well presented. Do you think you can do something similar for Fuzzy Logic Control ?
  • SterlingSterling Posts: 51
    edited 2006-04-20 17:10
    I'm curious, how does one pronounce PID? P. I. D. or pid?
  • Martin HebelMartin Hebel Posts: 1,239
    edited 2006-04-20 17:16
    P.I.D. is the normal pronounciation.

    Easy questions I like [noparse]:)[/noparse]

    -Martin

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Martin Hebel
    Southern Illinois University Carbondale - Electronic Systems Technologies

    Personal Links with plenty of BASIC Stamp info
    StampPlot - Graphical Data Acquisition and Control
  • Casey_SCUCasey_SCU Posts: 19
    edited 2006-07-06 21:53
    How do you calculate the proportionality constant, Kp?
  • edited 2006-07-06 22:02
    If the only·one of the three controls you are using is proportional, Kp has to give you the maximum allowed drive with the maximum expected error.

    ···· 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 GMT
  • Danny22Danny22 Posts: 29
    edited 2006-07-17 22:00
    Andy,
    About 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
  • koolitudekoolitude Posts: 37
    edited 2007-03-03 07:18
    Sorry for digging this post back to the top...

    But 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!
  • edited 2007-03-05 02:09
    Keep in mind that true derivative is the limit as delta-e and delta-t approach zero. However, Kd is still finite, because as delta-t gets smaller, so does your delta-e.

    Using 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 GMT
  • MCopplerMCoppler Posts: 38
    edited 2008-04-26 19:02
    Hello Andy.

    Do 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!
  • edited 2008-04-29 01:21
    Hi MCoppler,

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

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

    This 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=617192

    Andy

    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 GMT
  • MCopplerMCoppler Posts: 38
    edited 2008-05-05 23:29
    Hello again everybody.

    Has 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.
  • RickHRickH Posts: 40
    edited 2008-05-21 11:57
    Very nice, I have a few questions of paramiters I have run into in the field when I was working in the Plastics and Heat Treating Industry as a Tech.

    1. 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?
Sign In or Register to comment.