© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
R. J. SmytheAdvanced Arduino Techniques in Sciencehttps://doi.org/10.1007/978-1-4842-6784-4_4

4. The PID Process Control Algorithm

Richard J. Smythe1  
(1)
Wainfleet, ON, Canada
 

Proportional, integral, and derivative (PID) controllers are an important technological development that in the past hundred years has become an industrial commodity and an integral part of a host of manufactured laboratory equipment. However, the bulk of the literature available concerning PID control systems is heavily biased toward industrial or engineering applications and theoretical mathematical treatments. The object of this chapter is to review the simple theory of the PID algorithm and apply the robust controller to microcomputer and microprocessor small-scale experimental works.

Theory

When control of experimental or scientific investigation process variables over an extended period of time is required, the PID algorithm can be used. In processes such as maintaining the temperature within an enclosure, the intensity of illumination, the position of a robotic arm, or the speed of a rotating device such as a pump, agitator, or wavelength scanner, the PID algorithm can be used. Virtually any electro-mechanical process can be controlled with the (PID) algorithm. The PID methodology uses a feedback-loop technology that has evolved over the past century into a digital-format algorithm able to be processed in a computing machine to provide automatic or “realtime” process control on a local benchtop, manufacturing facility, or remote field location.

As noted, a full PID algorithm contains proportional, integral, and derivative mathematical operations, but proportional-only and proportional-plus-integral forms of the controller are also used to form a controller loop. Investigators implementing a control process must assess the degree of control required for the process at hand and select the appropriate form of the algorithm to use.

Each individual process that is to be controlled will have a desired “set” or operating point, an actual operating point, which can be measured, and an error value that is the difference between the set point and the actual process operating point. On startup or after a system perturbation, the set point and the actual operating point are different, and when this happens, the PID controller attempts to generate a composite output signal that will bring the process back to the desired set point. A perturbation can upset the process by causing an increase or decrease in the magnitude of the error term, thus requiring a positive or negative corrective action.

Figure 4-1 is a block flow chart for a PID-based control system.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig1_HTML.jpg
Figure 4-1

A PID-type control system

Figure 4-1 is a very simple depiction of the flow of information that can be used to control virtually any electro-mechanical system. In the cycle displayed, a computing device is operating in a continuously interactive mode with a process in a closed-loop configuration. Within the loop the process controls are continuously being manipulated by the controller to keep the monitored process status in accord with the controller’s desired set point.

A process set point may be a fixed value such as a furnace temperature or it may be a time-dependent value in a temperature program, such as those used in gas chromatography or in a heat treatment metallurgical process. The set point is a value recognized in the computing controller that is compared to the process status value as monitored by the sensor in Figure 4-1. If an error or difference is found between the set point and the sensor output, the computing controller invokes the PID mathematical algorithm to generate a signal that changes the process controls to reduce the magnitude of the calculated error.

Adaptability is a very important feature of the PID control system that is made possible by the use of five variables. To effectively control the process at hand, the process value and the desired set point are needed to determine the error signal, which is then processed by the PID algorithm in use to evaluate the proportional, proportional-plus-integral, or full PID error correction.

Figure 4-2 depicts the classical theoretical mathematical form of the full PID equation.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig2_HTML.png
Figure 4-2

The PID equation

In the time-based format of Figure 4-2, the process status is PV(t) and the desired set point is SP, so the error at time t is e(t), the difference between the set point and the process value. u(t) can be considered as the electrical signal to be sent to the process controls to bring the process value and set point closer together. זּ is a variable of integration.

The PID formula weights the proportional term by a factor of Kp, the integral term by a factor of Kp/TI, and the derivative term by a factor of Kp.TD, where Kp is the controller gain, TI is the integral time, and TD is the derivative time.

Using the notation of Kp, Ki, and Kd values in the following figures, the three empirical numerical “tuning constants” that modify the values determined by the proportional, integral, and derivative mathematical operations working on the calculated process set-point error can be defined.

The proportional term depicted in Figure 4-3 can be considered as a value that is directly proportional to the difference between the set point and the operating point. If the process is operating at its set point the proportional correction term contribution to the output is virtually zero. If the process has drifted or been pushed far from its desired set point, the proportional contribution to the output will be correspondingly larger. In experimental works such as with small, fine wire-heating elements, a power restriction must be applied to the heater circuitry to avoid heater filament destruction on system startup when initial error values are large.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig3_HTML.jpg
Figure 4-3

The proportional term

A second contribution to the algorithm’s output value that aids in bringing the operating point and set point closer together is provided by the integral term as defined in Figure 4-4.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig4_HTML.jpg
Figure 4-4

The integral term

The integral term is derived from the sums of the previous error values over a fixed time interval. If the operating and set points are far apart, a larger contribution will be generated by the error summing. If the set point and operating point are closer together, the error will get smaller and the incremental sum will increase at a slower rate. Thus, depending upon the previous trend the integral contribution will vary in accordance with the size of the calculated error. It is suggested in the general PID literature that the integral term corrects for systematic errors in which the process value and the desired set point differ by a constant value over a given period of time.

A changing error value is detected by taking the mathematical derivative of the series of numerical values constituting the error stream. The derivative term of the controller algorithm is displayed in Figure 4-5. A derivative is a measure of the rate of change of a variable. The derivative component monitors how fast the error value is changing and applies an appropriate corrective action. In a PID loop there may be random noise that may be interpreted by the controller as an error signal requiring a controller output to correct. Excessive unnecessary corrective controller output can cause premature wear and failure in the final control element (FCE) in process loops using mechanical valves as control elements. It is reported in the literature that for many fast-response industrial processes using mechanical control elements the inclusion of the derivative term in the controller algorithm does not contribute enough improvement in control performance to offset the increased equipment maintenance costs. However, for slower response processes such as temperature control loops, pH control, and other slow-response processes the derivative term should be included. The literature also notes that a two-term control algorithm is much easier to tune than the three-term entity.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig5_HTML.jpg
Figure 4-5

The derivative term

As noted, the three mathematical operations monitor the process as it runs and from the stream of error values generated produce three numerical-value contributions to an error-correction signal. The controller output based upon the three values should bring the process operating value and the set point closer together. The three K values that precede each of the mathematical operations determine how much “weight” or “influence” the individual mathematical function–created controlling values will have in the overall feedback loop. A great deal of research in the engineering community has gone into finding methods for selecting the optimum values for the tuning constants for the PID algorithm. Researchers using the PID algorithm on a unique experimental setup will probably find that best practice is to follow the Zeigler Nichols methods for estimating the required constants to optimize system performance.

Tuning and Practical Applications of the PID Controller

As noted previously, processes to be controlled can vary substantially in the rate at which they respond to disturbances, perturbations, or control inputs. To control a high-speed process, fast error generation and PID reaction times may be necessary to provide timely process adjustments. A process moving a solar panel to face the sun or keep a furnace at a constant temperature may be considered as having a very slow rate of operation, while maintaining the speed of a motor spinning a mirror in an interferometer may be considered a fast operation. It is highly unlikely that the same set of tuning constants will be applicable to all process control implementations of the algorithm.

A controlled process can operate in one of three possible states: stable, unstable, or marginally stable. A controlled stable process is one that has eventually converged to a steady state of operation and remains that way with increasing time. An unstable process is not in a state of control and oscillates around the desired steady-state point of operation, with irregular oscillation amplitude never reaching a steady-state condition. A marginally stable system will oscillate about the desired steady-state condition with a relatively constant amplitude and is considered to be the intermediate state between controlled and uncontrolled processes.

Processes that require control are usually subjected to both driving and opposing forces. The opposing entities are typically mechanical friction; electrical, gas, liquid, and magnetic resistances; thermodynamic heat flow; or gravity, and are often termed the damping force.

A very simplified division classifies process control into underdamped, overdamped, and critically damped systems. Disturbances or perturbations may cause the system to oscillate about its normal steady-state condition. An overdamped system can be said to reach or return to its steady-state condition after a disturbance or from startup without oscillation about the steady-state value. An underdamped system will return to its steady state after a series of gradually decreasing oscillations about the steady-state value. A critically damped system returns to its final steady state in the shortest time possible and without oscillation from a perturbation or system startup. In some systems there can be a fourth state in which the system oscillates at a relatively constant frequency and amplitude about the steady-state value after a disturbance; this fourth state can be considered as the situation in which the damping force is small enough to describe the system as undamped. A theoretical graphical depiction of the four states is displayed in Figure 4-6.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig6_HTML.jpg
Figure 4-6

Theoretical system response to perturbations

Figure 4-6 and the discussion on system response to disturbances have been presented as an aid in understanding adaptations of the PID controller algorithm to experimental processes. Prior to implementation of the controller algorithm, it is assumed that an investigator has assembled a system that can run safely for at least a period of time of sufficient length that the controller output and the process variable can be recorded. A documented record of process variables is required to support an experimental development program that is used to determine the values of the three controller constants that are depicted in Figures 4-3, 4-4, and 4-5 so as to get satisfactory process control.

In 1942 a pair of methods was presented to the American Society of Mechanical Engineering by J.G. Ziegler and N.B. Nichols for determining a set of PID constant values that could control a process or serve as a base from which the process operator could modify the values to obtain the desired degree of control.

Prior to examining Ziegler and Nichols’s two methods, the four terms for describing a controlled system’s response to a perturbation or disturbance will be discussed. Rise time is the initial time it takes for the process output to rise beyond 90 percent of the desired set-point level. Overshoot describes the amount above the desired set point that the controller drives the output on startup or during recovery from a disturbance. Settling time is the time required for the process to settle back to its steady-state condition after a disturbance. A steady-state error condition exists in a process if there is a difference between the steady-state value and the desired set point. As previously noted, this systematic error is usually eliminated by the integral term of the algorithm.

To implement the first of the two methods used to generate an initial set of algorithm constants, the process at hand must be running in a closed-loop configuration and be in a steady-state condition. A known sized-step perturbation or disturbance must be made to the system, and the system response should form an “S” shape as it returns to the steady-state value, as depicted in Figure 4-7.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig7_HTML.jpg
Figure 4-7

Steady-state system response to a step disturbance

Once a satisfactory curve has been recorded, the inflection point of the transition curve from disturbed state to steady-state value is located, as represented by the black dot in Figure 4-7. A line tangential to the straight portion of the transition curve at the inflection point is then drawn to intersect the zero-point disturbance value and the steady-state value. A vertical line is drawn from the point of intersection of the tangent line to the time axis to generate a pair of measured values known as the lag time L and the process time constant T.

A generally accepted application of the “S” step data response for a proportion-only controller is to set Kp equal to T/L, usually in seconds. The Kp and Ki constants for a proportional and integral controller are 0.9(T/4) and L/3, respectively. A complete set of possible constants for a full PID controller using Kp, Ki, and Kd can be calculated from 1.2(T/4), 2L, and L/2, respectively.

The second procedure described by Ziegler and Nichols sets the values of Ki and Kd to zero and increases Kp until the system under test exhibits the theoretical undamped response as seen in the green trace of Figure 4-6. In Figure 4-8, the author’s small, heated chamber’s PID temperature controller exhibits a typical in-service undamped response.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig8_HTML.jpg
Figure 4-8

Induced undamped steady-state system response

The system response depicted in Figure 4-8 was eventually obtained by setting Kp to 128. To find the 128 value, the code in the microcontroller program defining the three PID parameters was initially altered to set Kp to 1 and Ki and Kd to 0. The microcontroller code was then launched and the system response recorded for five to ten minutes. A trace consisting of recorded random noise near the system set point was deemed a failure for the Kp value in use for the present iteration of the testing cycle. After such a failure, the next iterations used binary doubling of the coefficient until a pattern in the observed random noise began to appear. The doubling process was continued until the system response was found to produce the image recorded in Figure 4-8. Increasing the value of Kp above that producing the relatively symmetrical oscillation about the nominal set point increased the distortions seen just before the halfway point between the 17:15–17:16 time stamps and just before the 17:17 time stamp. As noted, the least distorted, most symmetrical oscillating display as seen in Figure 4-8 was realized at Kp = 128.

Two values of interest are derived from the recorded system response seen in Figure 4-8. Ku, the ultimate proportional value that produces the controller response characteristic of an undamped system, and Pu, the period of these oscillations, are the two predictive values of interest. As can be seen in Figure 4-8, there are eighteen oscillations between the 17:14 and 17:15 time stamps, indicating a rate of 18/60 or 0.3 oscillations per second. (Note that the oscillations in Figure 4-8 occur about the temperature of approximately 124.8°C rather than the system set point of 125°C. The systematic error can be partially attributed to the lack of an integral term in the PID algorithm and partially to the digital hardware limitations used to implement the controller. See also the discussions for Figures 4-10 and 4-11.)

To find a reasonable proportional constant Kp for a proportional-only controller, the Ku value is divided by 2. A pair of reasonable coefficients for a proportional-plus-integral controller are 0.45Ku and 1/(1.2 Pu). For a full PID control algorithm, Kp is found by multiplying Ku by 0.6. The Ki coefficient is found by dividing the ultimate Pu by 2, and the Kd coefficient is determined by dividing Pu by 8.

There is a very large amount of literature on control engineering available to the investigator that provides many variations on the methods by which the PID coefficients can be estimated and how they can be adjusted to create a desired system performance. Only the traditional, more rudimentary process has been outlined in this chapter for use in experimental investigations.

Once the initial set of coefficients has been determined for the system at hand, the performance or dynamics of the controller can be adjusted if required in accordance with the data tabulated in Table 4-1.
Table 4-1

Effects on System Dynamics of Increased PID Constants

-../images/503606_1_En_4_Chapter/503606_1_En_4_Figa_HTML.jpg

PID for Thermal Control

If employing the circuit displayed in Figure 4-9, you would need to ensure that changing the PID coefficients would not cause damage to the process equipment being tested (i.e., heater filament destruction). Listing 4-1 was used to provide the system performance depicted in Figure 4-10, which was recorded with the DAQFactory plotting sequence shown in Listing 4-2. (All code listings provided at the end of the chapter.)
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig9_HTML.jpg
Figure 4-9

A heated chamber power control circuit

../images/503606_1_En_4_Chapter/503606_1_En_4_Fig10_HTML.jpg
Figure 4-10

The PID-controlled temperature of a heated chamber

In Chapter 9, “The Analog Front End,” the limitations of the typical microcontroller’s built-in ADCs are addressed. In essence, most microcontrollers use a 10-bit ADC to convert a 0 to 5V input signal into a 0 to 1023 digital value. Although the thermocouple signal is amplified and conditioned by the AD595 and averaged to lessen the noise, the final form of the temperature data presented to the PID controller algorithm is a digital value between 0 and 1023. The addition of random noise can toggle the ADC converter data between the next higher or lower digital value, which can interfere with the operation of the control system. Figure 4-11 illustrates one of the restrictions evident in the author’s Arduino PID temperature control system.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig11_HTML.jpg
Figure 4-11

The set point and system response for an Arduino PID-controlled temperature in a heated chamber

Careful examination of the temperature scale and system response indicates that although the microcontroller code requests a set point of 325.0°C the system responds with a median value of 324.95°C. Further examination of the black trace reveals that the system response is oscillating from 324.70°C to 325.20°C—a difference of 0.50°C. The discrepancies evident in Figure 4-11 are consistent with the results of the digital limitations imposed upon the system by the 10-bit microprocessor hardware when it is used over a large dynamic range. If these restrictions are not acceptable to the experiments being conducted, then the PID controller algorithm must be applied to a narrower range of temperature control to achieve a higher degree of resolution.

With proper heat sinking, PID control of a PWM output can manage DC heater element currents up to 33A and 100V with the FQP33N10. Higher AC voltages of up to 400V and currents of 40A can be managed with solid-state relays and the technique known as time proportioning. (See Chapter 3, “Experimental Work at High Temperatures and High Heats.”)

PID Control of Optical Brightness

Several educational institutions have made use of a microcontroller with an LED and a photoresistor optically coupled loop as a simple, inexpensive desktop demonstration of a PID controller. Figure 4-12 is a circuit diagram of an Arduino-based cadmium selenide LED optical loop to be controlled by a PID algorithm, via Listing 4-3, resident in the microcontroller. (An auxiliary supply may be used if a larger or brighter light source is desired.)
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig12_HTML.jpg
Figure 4-12

A circuit diagram for an Arduino optical PID demonstration

In Figure 4-13, the circuit of Figure 4-12 has been assembled on a 2 1/8 in. (5.5 cm) by 3 1/4 in. (8.2 cm) prototyping breadboard. The microcontroller depicted in Figure 4-13 is a Sparkfun RedBoard Arduino Uno emulator available in volume purchases for $20 (USD).
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig13_HTML.jpg
Figure 4-13

A desktop LED–LDR PID control demonstration

Item A is an Arduino-type microcontroller, and B is a small prototyping breadboard. Items C, D, and E are the LED light source, the cadmium selenide light-dependent resistor, and set-point potentiometer, respectively.

The academic institutions that used the setup described followed the previously noted industrial practice of creating a proportional, integral-only controller for both inexpensive simplicity and to accommodate a fast response process.

Figure 4-14 depicts the recorded results of interfering with the intensity of the LED emissions. Arduino’s 8-bit PWM signal is limited to values between 0 and 255, which defines the full-scale output of the controller output and consequently the set-point limits. The microcontroller ADC is a 10-bit device, and the microcontroller program must scale the LDR output accordingly.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig14_HTML.jpg
Figure 4-14

PID LED illumination control during beam-blocking perturbations

In Figure 4-14, the black trace recording the set point at approximately 200 can be seen to follow a straight line through the noise band of the input controller signal from the LDR recorded in red. The blue trace records the controller algorithm output.

A series of qualitative beam-interference perturbations were made to the system at two different set-point values and were created by altering the settings on the potentiometer, seen as item E in Figure 4-13. Prior to 7:16, the blue trace recording the controller output as generated by the PWM output on pins 5, 9, or any PWM-capable digital pin of the microcontroller remains relatively constant in the absence of a disturbance to the visible light falling upon the LDR. Shortly after 7:16 and 7:18, the first captions A mark the blockage of the overhead light by a simple hand shading. The captions at B mark an approximate quarter blockage of the LDR surface; the C captions approximate a half-surface blockage, and the D disturbances mark a full blockage of the beam. The disturbances marked by the E captions indicate the system response to turning off the overhead lights.

In Figure 4-14, the noise in the input signal is substantial, but interference with the light beam does not appear to cause any hesitation or delay in the system response. Examination of the red input trace during the output trace’s heightened power demand at caption D reveals the same apparent signal noise in the lower value of the recorded trace. During normal undisturbed operation on the bench top, the light beam can be seen to pulse and flicker at all set-point values, and hence the recorded noise level is not unexpected.
../images/503606_1_En_4_Chapter/503606_1_En_4_Fig15_HTML.jpg
Figure 4-15

PID LED illumination control scale expansion for noise examination

Using the scale-expansion capabilities of the DAQFactory software, it can be seen in Figure 4-15 that the controller output in blue is responding with sufficient speed to follow some of the apparent noise variations in the red input trace.

The system used in this demonstration or exercise does have some limitations imposed by the ambient light levels and the limited set-point values over which the system will function. Although the three suggested tuning constants published with the original descriptions of the classroom exercises of Kp = 0, Ki = 10, and Kd = 0 appear to work well with the simple system; only two functions of the PID, consisting of the proportional and integral, are determining the controller output.

Code Listings

/********************************************************
 * PID Basic Example with the chamber temperature monitored
 * by a K-type thermocouple and an AD595 in deg.C. TC output
 * averaged for noise reduction CO output is in PWM format.
 * PID controller input on A0, CO output on PWM pin 3
 ********************************************************/
#include <PID_v1.h>
#define PIN_INPUT 0
#define PIN_OUTPUT 3
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=96, Ki=1.75, Kd=0.44;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
//
double index = 0;
int avrgVlu = 0;
void setup()
{
  //initialize the variables we're linked to
  int raw = analogRead(PIN_INPUT);
  //Serial.println(raw);
  float Vout = raw*(5.0/1023.95);
  float temp = (Vout)/0.010;   // for AD595 10mV/deg C with K type thrmcpl
  Input = temp;
  Setpoint = 175;
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  // initialize the serialport
  Serial.begin(9600);
}
void loop()
{
  for (index = 1; index <= 100; index ++) {  // average added to lessen noise
    int raw = analogRead(PIN_INPUT);
    avrgVlu = avrgVlu + raw;
  }
  int raw = avrgVlu / 100;
  float Vout = raw *(5.0/1023.95);
  float temp = (Vout)/0.010;   // for AD595 10mV/deg C with K type thrmcpl
  Input = temp;
  myPID.Compute();
  analogWrite(PIN_OUTPUT, Output);
  Serial.print(Output);    // diagnostic or dual value plotting
  Serial.print(",");
  Serial.println(temp);
  raw = 0;
  avrgVlu = 0;
}
Listing 4-1

Arduino Code for PID Temperature Control

// Parse multiple values from the serial port in the order in which they are sent
// Seqnc auto polls CommPrt_N in use for streamed Ardy data in comma delimited format
// Ordering data ensures same data plotted to same trace between sessions
// Ensure null protocol has been selected in protocol window and that correct data is streaming into SP
// Data on the SP must be a carriage return/newline-separated stream of n comma-delimited values
// Create n channels to hold the data for plotting, Ardy_1, Ardy_2 etc.
// To parse out the data use a loop to find the cr/nl delimiters, convert to numbers and Parse(datain,position #,",")
// into data1, data2 etc values and then use channel.addValue(datan) to assign numerical values to the channels.
//
// clear the buffer
device.Comm11.Purge()         // clear old data lines
device.Comm11.ReadUntil(13)   // clear any partial line reads
//
while(1)
   try
      // parse the first data point for plotting
      private string datain = device.Comm11.ReadUntil(13)
      //?datain               // diagnostic
      private data1 = StrToDouble(Parse(datain,0,","))
      ardyValu_1.AddValue(data1)
      private data2 = StrToDouble(Parse(datain,1,","))
      ardyValu_2.addValue(data2)
      catch()
      delay(0.5)
      endcatch
      endwhile
Listing 4-2

DAQFactory Sequence Code for Plotting of Multiple Values from the Serial Port

 #include <PID_v1.h>
const int photores = A0;   // LDR input pin
const int pot = A1;        // Potentiometer input pin
const int led = 5;         // LED output pin
double lightLevel;         // Indirectly store the light level
// Tuning parameters
float Kp = 0;              // Proportional gain
float Ki = 10;             // Integral gain
float Kd = 0;              // Differential gain
// Record the set point as well as the controller input and output
double Setpoint, Input, Output;
// Create a controller that is linked to the specified Input, Ouput and Setpoint
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
const int sampleRate = 1;        // Time interval of the PID control
const long serialPing = 500;     // How often data is recieved from the Arduino
unsigned long now = 0;           // Store the time that has elapsed
unsigned long lastMessage = 0;   // The last time that data was recieved
void setup()
 {
 lightLevel = analogRead(photores);       // Read the set point
 // Arduino has an analogueRead() resolution of 0-1023 and an analogueWrite() resolution of 0-255
 Input = map(lightLevel, 0, 1023, 0, 255);    // Scale the input
 Setpoint = map(analogRead(pot), 0, 1023, 0, 255);  // Scale the set point
 Serial.begin(9600);                 // Initialize serial communications   at   9600   bps
 myPID.SetMode(AUTOMATIC);           // Turn on the PID control
 myPID.SetSampleTime(sampleRate);    // Assign the sample rate of the control
 //Serial.println("Begin");          // Let the user know that the set up s complete
 lastMessage = millis();             // Serial data will be received relative to this first point
 }
void loop()
 {
 Setpoint = map(analogRead(pot), 0, 1023, 0, 255);  // Continue to read and scale the set point
 lightLevel = analogRead(photores);     // Read the light level
 Input = map(lightLevel, 0, 1023, 0, 255);    // Scale the input to the PID
 myPID.Compute();                  // Calculates the PID output at a specified sample time
 analogWrite(led, Output);         // Power the LED
 now = millis();                   // Keep track of the elapsed time
 if(now - lastMessage > serialPing)      // If enough time has passed send data
 {
 //Serial.print("Setpoint = ");
 Serial.print(Setpoint);
 Serial.print(",");
 Serial.print(Input);
 Serial.print(",");
 Serial.println(Output);
 //Serial.print(" ");
 // The tuning parameters can be retrieved by the Arduino from the serial monitor: 0,0.5,0 set Ki to 0.5.
 // Commas are ignored by the Serial.parseFloat() command
 if (Serial.available() > 0)
 {
 for (int x = 0; x < 4; x++)
 {
 switch(x)
 {
 case 0:
 Kp = Serial.parseFloat();
 break;
 case 1:
 Ki = Serial.parseFloat();
 break;
 case 2:
 Kd = Serial.parseFloat();
 break;
 case 3:
 for (int y = Serial.available(); y == 0; y--)
 {
 Serial.read();
 }
 break;
 }
 }
 Serial.print(" Kp,Ki,Kd = ");  // Display the new parameters
 Serial.print(Kp);
 Serial.print(",");
 Serial.print(Ki);
 Serial.print(",");
 Serial.print(Kd);
 myPID.SetTunings(Kp, Ki, Kd);  // Set the tuning of the PID loop
 }
 lastMessage = now;             // Reference the next serial communication to this point
   }
 }
Listing 4-3

Arduino Code for PID control of LED–LDR Optical Brightness Loop

Summary

  • PID control algorithm theory, theoretical process response to perturbations, and the theoretical methods that can be used to initialize the implementation of a process-control loop are reviewed.

  • A PID heated chamber temperature control implementation shows the process working and demonstrates the limitations of microprocessor implementation of the process-control algorithm.

  • An educational, compact, inexpensive, optical desktop apparatus is assembled and connected to a strip-chart recording system to record the PID control-loop response to perturbations in a controlled light beam intensity.

  • In Chapter 5, programs able to plot streamed data as a function of time in the format traditionally known as strip-chart recording are developed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.200.77.59