Design of Three-Term Controller Using a PIC18F452 Microcontroller

Microcontrollers are used in almost any applications that come across one ’ s mind, from small control applications such as home appliances to aerospace. Microcontrol-ler-based controllers are cost-effective and flexible to modify the design to meet the requirement for any control of any industrial plant. Microcontrollers do not require external hardware interface, memories, counter/timers, and ADCs, because they are all integrated inside the chip. Those controllers could be programmed online and do not require any backup memories except for big applications. This chapter presents the implementation of the three-term PID controller using a Microchip PIC18F452 microcontroller. To read data into the controller, a 10-bit integrated ADC is used; and to read data out of the machine, an external 12-bit serial DAC is used. Before pro-gramming the PIC microcontroller, the task to be tested could be off-line using a software simulator to make sure that it is working according. When that is the case, it could be then fired into the controller on-line in a mater seconds. Not only that, if the user decides to use different algorithm, he only programs the controller again online.


Introduction
The PID (Proportional Integral Differential) algorithm is the most popular feedback controller used within the process industries. It has been successfully used for over 50 years. It is a robust easily understood algorithm that can provide excellent control performance despite the varied dynamic characteristics of process plant. It is designed to generate an output that causes some corrective effort to be applied to a process so as to drive a measurable process variable towards a desired value, known as the set point. The concept is based (as shown in Figure 1) on the re-input of the system own output according to certain laws (hence the name "feedback"). It is desired for the system output to follow the set point. All feedback controllers determine their output by observing the difference, called error, between the set point and the actual process variable measurement. The PID looks at (a) the current value of the error, (b) the integral of the error over a recent time interval, and (c) the current derivative of the error signal to determine not only how much of a correction to apply, but for how long. Each of those three quantities are multiplied by a (tuning constant) and added together. Thus the PID output is a weighted sum. Depending on the application one may want a faster convergence speed or a lower overshoot. By adjusting the weighting constants, K p , K i , and K d , the PID is set to give the most desired performance.
As a result of enormous development in microcomputer technology, analog controllers have been replaced by digital controllers either in small or large industry. It is now a common practice to implement PID controllers in its digital version, which means that they operate in discrete time domain and deal with analog signals quantized in a limited number of levels. The trend toward digital rather than analog control is mainly due to: (1) versatility where programs can be easily modified or completely changed, (2) sophistication where advanced control laws could be implemented, (3) cost effectiveness where microcontrollers are available at very low costs compared to PLCs, industrial computers, RTUs or DCS. A typical digital feedback control system is shown in Figure 2. In digital feedback systems, the controller input and output are digital (sampled) rather than continuous signals. Thus, the continuous signal from the measurement device (sensor/transmitter) is sampled and converted periodically to a digital signal by an analog-to-digital converter (ADC). A digital control algorithm is then used to calculate the controller output as a digital signal. Because most final   control elements are analog devices, the digital output signal is usually converted to a corresponding analog signal by a digital-to-analog converter (DAC).
In feedback control, the objective is to reduce the error signal to zero where where e t ð Þ = error signal, y sp t ð Þ = set point and y m t ð Þ = measured value of the controlled variable. For the PID controller, the three terms (proportional, integral, and derivative) are combined to minimize the error as much as possible. The most common combination of these three terms is in parallel as shown in Figure 3. The PID equation [1,2] is given by: where P(t) = controller output; P = bias (steady-state) value; K C = controller gain; τ I = integral time; τ D = derivative time.
A straightforward way of deriving a digital version of the parallel form of the PID controller is to replace the integral and derivative terms by finite difference approximations, where T S = the sampling time (the time between successive measurements of the controlled variable); and e k = error at the kth sampling instant for k = 1, 2, 3, … There are two alternative forms of the digital PID control equation, the position form and the velocity form. Substituting Eqs. (3) and (4) into (2) gives the position form: where P k is the controller output at the Kth sampling instant. Eq. (5) is referred to as the position form of the PID control algorithm because the actual value of the controller output is calculated [3,4].
In the velocity form, the change in controller output is calculated. The velocity form can be derived by writing the position form of Eq. (5) for the (k À 1) sampling instant: Note that the summation still begins at j = 1 because it is assumed that the process is at the desired steady state for j ≤ 0, and thus e j = 0 for j ≤ 0. Subtracting Eq. (6) from (5) gives the velocity form of the digital PID algorithm: In this study, velocity form is chosen because of the following advantages: 1. It does not need initialization. The position form requires the initial value of the controller output P, which is not normally known in practice. For example, an operator keeps the control loop in the manual mode until a desired steady state operation has been reached. At this point the error is zero and the position of the control valve would correspond to the P value. Therefore, if the operator would like to transfer the control from manual to automatic, he or she should enter in the position control algorithm the value of P which is not normally known. This difficulty can be bypassed with the velocity form of the control algorithms, which do not need initialization.
2. It is protected against integral windup. The integral mode of a controller causes its output to continue changing as long as there is a nonzero error. Often the errors cannot be eliminated quickly enough and given enough time they produce larger and larger values for the integral term, which in turn keeps increasing the control action until it is "saturated" (e.g., the valve completely opens or closes). This condition is called integral windup. Then, even if the error returns to zero, the control action will remain saturated. The position form with its continuous summation of errors will produce integral windup and special attention will be required. The velocity form, on the other hand, is protected from integral windup for the following reason: The control action changes continuously until it becomes saturated. But then as soon as the error changes sign, the control action can return within the control range in one sampling period.
3. It protects the process against computer failure. With the velocity algorithm one can send out a signal which is used to drive an integrating amplifier or a stepper motor. These devices will retain the last calculated position of the control valve (or other final control element) in case the computer fails, thus avoiding total loss of control of the process.

PIC18F452 background
As mentioned earlier, the implementation is based on a Microchip PIC18F452 microcontroller, where the controller plays the role of the brain of the control system [5]. The right choice of the microcontroller is essential, as it will be the core of the final design. The PIC18F452 from Microchip has been chosen for the following advantages: 1. Speed: with its maximum internal clock rate of 20 MHz and its 16-bit-wide instruction bus, the CPU can execute most of its instructions at a single machine cycle of four clocks which is equivalent to a 0.2 μs.
2. Math support: unlike classical microprocessors, the controller in hand has got a hardware multiplier and divider for multiple-bytes, fixed-point numbers and for floating-point numbers so multiplication is carried out in a single instruction.
3. Flexible timer resources: four independent timers modules support timing measurements and output interval control with a timing resolution as fine as 0.1 μs. Those timers could be used to produce up to three pulse width modulations which could be used for electrical motor control.
4. Free software tools: Microchip's Development Package MPLAB ® (consisting of assembler, simulator, and user interface) as well as all manuals and application notes are available at no cost from their Web site (www.microchip.com).
5. Development tool versatility: it supports in-circuit debugger which permits the loading and execution of a user program as well as the use of breakpoints, memory/ register modification, and single stepping.
6. Build-in ADCs: it has analogue-to-digital converters with 10 bits resolution.
7. Built-in serial peripheral interface: it has a variety of serial bus interfaces like USART, I 2 C & SPI.
8. C programmable: it could be programmed using C language with the use of a variety of built in C libraries developed by microchip.
The PIC18F452 microcontroller is a 40 or 44-pin depending on the package, where in the 40 pins configuration, a dual inline package is used; whereas in the 44 pins configuration, either thin quad flat package or dual flat no leads package is used. Its design is based on Harvard technology where the program and data have different buses. This type of microcontrollers is very cheap, small in size, and could be customized. It could be easily programmed on-line using either assembly language, BASIC or C language. In fact, it is ideal for small application such as the one in hand. The controller has a 24 kbytes of flash memory and 2048 bytes of SDRAM. It also has a 8 Â 10 bits analog to digital channels. It also has 5 bidirectional digital ports with 33 inputs/outputs, configured as follows: 3 Â 8 digital I/O ports (PORTB, PORTC and PORTD), one six digital I/O port (PORTA) and one three digital I/O port (PORTE). Unfortunately, one of the drawbacks of microcontrollers, it is very seldom to find one with a digital to analog converter. Luckily, they are few manufacturers around including microchip, which make serial DACs which could be programmed through Serial Port Interface (SPI) using only three wires. The PIC18F452 has four timer/counters which could be programmed either as 8 or 16 bit timers/counters. It also has two ports which could be configured either as capture, compare or pulse width modulation (PWM). It has two serial peripheral interfaces: (SPI) and an inter-integrated circuit (I 2 C). An asynchronous port (USART) is also provided. For the microcontroller to output analogue data, an MCP4921 device is used. The device is a 12-bit buffered single voltage output Digital-to-Analog Converter (DAC). The device operates from a single 2.7 V to 5.5 V supply with an SPI compatible Serial Peripheral Interface. The user can configure the full-scale range of the device to be VREF or 2*VREF by setting the gain selection option bit (gain of 1 of 2). The user can shut down the device by setting the Configuration Register bit. In Shutdown mode, most of the internal circuits are turned off for power savings, and the output amplifier is configured to present a known high resistance output load (500 kΩ, typical). The device includes double-buffered registers, allowing synchronous updates of the DAC output using the LDAC pin. The device also incorporates a Power-on Reset (POR) circuit to ensure reliable powerup. The device utilizes a resistive string architecture, with its inherent advantages of low Differential Non-Linearity (DNL) error and fast settling time. The device is specified over the extended temperature range (+125°C). It provides high accuracy and low noise performance for consumer and industrial applications where calibration or compensation of signals (such as temperature, pressure and humidity) is required. The MCP4921 device is available in the PDIP, SOIC, MSOP and DFN packages. Figure 4 shows the chip pin configuration. The MCP4921 device is designed to interface directly with the Serial Peripheral Interface (SPI) port, which is available on the PIC18F452 microcontroller and supports Mode 0,0 and Mode 1,1. Commands and data are sent to the device via the SDI pin, with data being clocked-in on the rising edge of SCK. The communication is unidirectional; this means the data cannot be read out of the MCP4921. The CS (chip select active low) pin must be held low for the duration of a write command. The write command consists of 16 bits and is used to configure the DAC's control and data latches. Register shown in Figure 5, details the write command which is loaded into the input register that is used to configure and load the DAC register [6].
The write command is initiated by driving the CS pin low, followed by clocking the four Configuration bits and the 12 data bits into the SDI pin on the rising edge of SCK. The CS pin is then raised, causing the data to be latched into the DAC's input register. The MCP4921 utilizes a double-buffered latch structure to allow the analog output to be synchronized with the LDAC pin, if desired. By bringing the LDAC pin down to a low state, the content stored in the DAC's input register is transferred into the DAC's output register (VOUT), and VOUT is updated. The write to the MCP4921 device is 16-bit words. Any clocks past the 16th clock will be ignored. The Most Significant 4 bits are Configuration bits. The remaining 12 bits are data bits. No data can be transferred into the device with CS high. This transfer will only occur if 16 clocks have been transferred into the device. If the rising edge of CS occurs prior to that, shifting of data into the input register will be aborted. The most four significant bits are defined as follows: bit 15 0 = Write to DAC register 1 = Ignore this command bit 14 BUF: VREF Input Buffer Control bit 1 = Buffered 0 = Unbuffered  : Output Shutdown Control bit 1= Active mode operation. VOUT is available. 0 = Shutdown the device. Analog output is not available. VOUT pin is connected to 500 kΩ (typical).

Liquid crystal display (LCD)
This module is designed to display the value of the temperature detected by the temperature sensor and to guide the user in changing the parameters of the controller. The LCD is a 16 Â 2 alphanumeric display with the built-in Hitachi 44780 controller and LED backlighting. It works with an 8-bit data bus, which means it will require a total of 11 data lines. Three control lines (connected to port E) plus the 8 lines for the data bus (connected to port D) [7].

System design
The system is design around a stand-alone PIC18F452 controller, where the measured variable (MV) is read through channel0 (pin 2). The MV is subtracted from the set point automatically by the controller. The error is treated by the PIC PID and produces a digital control variable. This control variable is outputted through PIC serial data output pin (SDO pin 24) together with serial clock pin (SCK pin 18) to synchronize the conversion process. For the conversion to take place, the serial DAC chip select (CS) has to be pulled low. The CS is connected to pin RC0. The positive reference voltage is connected to +5 V (pin 6) and the negative reference voltage (pin 7) is tied to zero volt. The analog output is read through pin8 (Vout). This voltage is small to drive an electric motor. This voltage is pulled up to +12 V through the non-inverting operational amplifier (LM358). The Darlington transistor 2SD1409 is used to bust the current. The motor is connected to the emitter follower so that the driving current is sufficient enough to drive the motor. Needless to say that the diode 1N4148 is used to protect the Darlington transistor against any spike due to the change of current. Figure 6 shows the schematic of the system. The LCD is used to display the measured temperature. To manipulate the setting of different parameters, six push buttons are used as follows: Six push buttons were used in the project to allow the user to change the setting and the controller parameters. Their functions are as follows: 1. Reset: To reset the microcontroller. These switches are connected to PIC PORTB to allow the user to use the internal build-in pull up resistors to prevent floating instead of using external pull-down resistors. The reset has got a separate button connected to MCLR pin. A buzzer is used as an alarm to indicate that the temperature is more than what the user specifies. Three LEDs were used to show the user the status of the microcontroller program. The three colors green, yellow, and orange were used as follows: 1. Green: means that the PID controller is working properly.
2. Yellow: means that the program is interrupted by (STOP) push button.
3. Red: means that the alarm is triggered.

Software design
To implement the control program, three major routines are used; the main routine along with the timer and external interrupts. The program starts with the main routine which contains all the configurations of the external pins whether outputs or inputs. It also contains the configurations of timer and external interrupts, so when one of these interrupts is triggered, the microcontroller will stop its current execution and perform another action. The trigger will be caused by either an overflow in timer register or a change on an external pin (RB0/INT0).
Because the time is a crucial element in digital control, the PID algorithm is controlled through a timer interrupt. This choice allows the user the ability to calculate the sampling time accurately. On the other hand, an external interrupt (INT0) is used to interrupt the program in order to allow the user a chance to modify the controller parameters. In the following we discuss in some details about the functions of each routine.

Routine function
This routine, as mentioned earlier, is dedicated to configure the direction of external pins as well as interrupt sources. It also allows the user to choose the measured variable (temperature, flow, level or others). The flow chart of this routine is shown in Figure 7.

External ports configuration
First PORTA (pin RA0) is configured as an analog input channel0 and PORTB as input digital port which is connected to the push button switches; while all other pins are configured as outputs.

LCD configuration
The configuration of the LCD was performed by separate software from Microchip called Application Maestro [8]. With the aid of this software, a configuration code was produced after modifying the module parameters. It was then incorporated into the project. Once incorporated, the LCD is configured and ready to work. One feature of using Application Maestro is its ability to use the prewritten code that this software provides to initialize or to write to the LCD.

Timer0 configuration
Timer0 can operate as a timer or as a counter. In Timer mode, the Timer0 module will increment with every instruction cycle (without prescaler). It is configured by setting a special function register called T0CON (timer0 control byte). This register is a readable and writable register that controls all the aspects of Timer0, including the prescale selection. In the design in hand, T0CON register is set to 0x85 (0b10000101) as shown below [9,10]. This value will configure the timer0 as follows:

Interrupt configuration
There are ten registers which are used to control internal and external interrupt operations to accommodate a variety of interrupts [11]. In the project in hand, only two interrupts are required INT0 and timer0 interrupt. To do so, only three control registers are required. These registers are INTCON, INTCON2, and RCON. INTCON register contains various enable bits as well as several interrupt flags. RCON is the Reset Control register which contains flag bits that allow differentiation between the sources RESET. Timer0 interrupt is enabled by setting TMR0IE bit (<5>) while external interrupt is enabled by setting INT0IE (INTCON<4>). Note that the interrupt flags are reset before enabling the interrupt in order to avoid unwanted interruptions.
To start the interrupt, the global interrupt bit GIE/GIEH (INTCON<7>) must be set. If set, it enables all unmasked interrupts, so if more than one interrupt source is used (as in our case) the Interrupt Priority Enable bit IPEN (RCON<7>) must be set and the interrupt sources should be specified either as high or low priority interrupt. The interrupt priority bit TMR0IP (INTCON2<2>) is used to specify the interrupt priority for Timer0. This bit is reset so timer0 interrupt is set to low priority. On the other hand, no need to specify the priority of the external interrupt (INT0), because it is already set to high priority by default.
After configuring the interrupts, the program will enter an infinite loop until one of the interrupt sources is triggered.

Routine function
The main purpose of this routine is to calculate the controller output and send it to the DAC serially through the synchronous SPI module [12]. Figure 8 shows the routine function.

Timer reloading
Because of the importance of time in calculating the timed controller output, timer0 is used as an accurate hardware timer. The source clock of the timer is the crystal oscillator which is fed to the clock pin of Timer0 internally. The clock used is a 20 MHz derived from a stable crystal oscillator. This frequency is automatically divided by 4 because the controller machine cycle is 4 clocks to give a 5 MHz which is fed to the timer. The timer is exactly clocked every 0.2 μs and takes 13107.2 μs (16-bit mode) to count from zero to zero again. However, by loading the timer with a suitable value, a smaller time interval could be obtained. For example, by loading the timer with the value 4095 (0xFFF), the overflow would occur after 12288.2 μs. Alternatively, the time period can be extended by using a prescaler as was done in the main routine. If a divide by 64 prescaler is selected, timer0 only overflows after 838.848 ms. This is obtained as follows:  This time period is less than one second, while a one second sampling time is required for the design in hand. To obtain a one second sampling time, the timer should count 78,125 pulses.
Because timer0 register is only 16 bit wide, it is only limited to count up to 65,535 pulses. The interruption is trigged several times to obtain one second timing, after which the controller computes the control action and sends it to the DAC. By using MPLAP simulator, it was found that 5362 cycles are required to calculate the controller output and send it to the DAC besides 51 extra cycles needed to reload the timer with time constant. If the interruption is required to repeat itself five times before calculating the controller output, one needs 5362 + 51 Â 5 = 5617 cycles (1.1234 ms). Thus, in order to get exactly one second sampling time, the timer register (TMR0) has to be reloaded with a value that interrupts the program every 998.8766 ms (1 s-1.1234 ms). The following shows how this value is obtained: No:of cycles for 1 s ¼ 5 Â 10 6 cycles Therefore no:of cycles between interrupts ¼ 5 Â 10 6 À 5617 ¼ 4, 997, 383 cycles By using a timer with 64 prescaler: However, the timer register accepts only integer numbers, thus the final value that should be added to the timer register is 49918. Because we omitted the numbers after the decimal point, our error will be AE 1 count which is equal to 64 cycles. Therefore, our error in calculating the sampling time will be: Timer error ¼ 64 Â 0:2 μs ¼ 12:8 μs This calculation is for getting 1 s sampling time. To expand the calculation in order to enable the user to change the sampling time, one defines two integer variables (repeat and cycle). The first variable repeat is to determine how many times we need to repeat the interrupt, while the second one cycle is the final value that should be added to the timer register. The following pseudo code shows the general formula used to reload the timer register.

Analog to digital converter module
The ADC module normally operates at 10-bits resolution, giving output digital values 0-1024 [13]. It needs a reference voltage to set the maximum and minimum values for the input conversion. This reference can be provided internally as V dd and V ss (supply values) or externally through V ref + and V ref À pins. To configure this module, OpenADC function from Microchip C library is used. This function performs a bitwise AND operation ("&") between its arguments which are defined in the file adc.h. The parameters of this function along with their meaning of each argument are discussed below [1] OpenADC Because the ADRES register pair (where the converted values are loaded) is 16bit wide. But the ADC is only 10bit wide. The ADC module could either be configured as right or left justified. In this project, right justified is chosen as shown in Figure 9. This sets the 6 most significant bits of register ADRES to zeros.
The supply values are chosen as the voltage references to the ADC.
• Once the A/D conversion is completed, the result is stored in an integer variable called result. After reading the analog value by the ADC module, the result will be compared with the variable alarm-trigger which was previously specified. If the result is greater than this value, the microcontroller triggers the buzzer and lights the red LED.

SPI module
To send the control variable to the final control element, the serial DAC, which is interfaced to the Serial Peripheral Interface (SPI) port, is used. The SPI is initiated using Microchip C library called OpenSPI. This function also performs a bitwise AND operation between its arguments which are defined in the file SPI.h according to the following formula.
• SPI_FOSC_16: Master mode and the clock = FOSC/16 • MODE_00: Mode 0,0 (change takes place on the rising edge) • SMPEND: Input data sample at end of data out OpenSPI(SPI_FOSC_16, MODE_00, SMPEND); After configuring the module, it is time to write a command to the DAC in order to convert it into analog signal. The write command is initiated by driving the CS pin low, followed by clocking the four configuration bits and the 12 data bits into the SDI pin on the rising edge of SCK. The CS pin is then raised, causing the data to be latched into the DAC's input registers and when the LDAC pin is pulled down through RC1, the values held in the DAC's input registers are transferred into the DAC's output registers to provide the analog signal. It is important to mention here that we wrote the write command in two steps (as shown in the following code) because the SPI module send only 8 bit at a time.

Writing on the LCD
To write characters to the LCD, required prewritten functions are provided by Application Maestro. Some of These functions are listed in following For numbers to be displayed, they are first converted into strings (characters) before being sent to the LCD, since the latter only accepts strings. To do so a C function called sprintf is called upon. This function saves the number in an array after converting it into string. The subroutine to do so is shown below [4]: sprintf (buf,"%d",temp_set); XLCDPutRamString(buf);

Routine function
The main function of this routine is to allow the user to change the controller parameters. The routine is initiated by pressing the push button (STOP) which is connected to the external interrupt pin (RB0/INT0). Once initiated, the user is able to change all the parameters of the controller (K C , τ I , τ D, sampling time, alarm trigger and sensitivity) by using three push buttons (MODE, INCREMENT and DECREMENT [11]. To determine which action the microcontroller should take if any push button is pressed, we defined two integer variables (present_button and present_mode) to be used as statuses. That is, each bit of them has specific meaning as described below: • present_button Initially, before pressing any push button, present_button variable is loaded with 0x8000 (no push button pressed), and present_mode with 0x2000 (starting mode).Then if any push button is pressed, the corresponding bit of that push button will be set, giving a specific value of present_button which indicates the push button that was pressed by the user. So by performing a bitwise OR operation between the two variables (present_button and present_mode) we will come up with a number indicates the push button pressed and the present mode and based on that number we can decide the proper action to be taken by the microcontroller. The following code shows how to perform the OR operation after checking which of the push buttons was pressed. Beside changing the controller variables, this routine has another feature, it gives the user preliminary values of the controller parameters after entering the process variables. The result is derived based on Cohen-Koon tuning method. However, this feature is impractical if the sampling time is big [14].

Testing and verification
To test the system, a first order system given by the equation below was used. To run the control action, the system was converted into a difference equation given by Eq. (10).

Conclusion
By referring to the previous graphs, it could be concluded that the response tracks the set point as expected. In addition, the increase in controller gain (K c ) does speed up the response but at the expense of the overshoot. Based on these results, it could be concluded that the three-term controller is working according to plan. Because of the flexibility of the microcontroller and its programming, any control scheme could be developed and implemented in the manner as described in this chapter. Not only that, the scheme could be transferred to several high range microcontrollers from the same company such as 16 or 32 bits with the use of the benefits those types of controllers offer.

Author details
Mostefa Ghassoul Chemical Engineering, University of Bahrain, Bahrain *Address all correspondence to: mghassoul@uob.edu.bh © 2020 The Author(s). Licensee IntechOpen. This chapter is distributed under the terms of the Creative Commons Attribution License (http://creativecommons.org/licenses/ by/3.0), which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited.