Converting Binary Numbers into Decimal
To convert a binary number into decimal, write the number as the sum of the powers of 2.
To convert a binary number into decimal, write the number as the sum of the powers of 2.
Two types of architectures are conventional in microcontrollers (see Figure 1.4). Von Neumann architecture, used by a large percentage of microcontrollers, places all memory space on the same bus; instruction and data also use the same bus.
In Harvard architecture (used by PIC microcontrollers), code and data are on separate buses, which allows them to be fetched simultaneously, resulting in an improved performance.
RISC (reduced instruction set computer) and CISC (complex instruction computer) refer to the instruction set of a microcontroller. In an 8-bit RISC microcontroller,
data is 8 bits wide but the instruction words are more than 8 bits wide (usually 12, 14, or 16 bits) and the instructions occupy one word in the program memory. Thus the instructions are fetched and executed in one cycle, which improves performance.
In a CISC microcontroller, both data and instructions are 8 bits wide. CISC microcontrollers usually have over two hundred instructions. Data and code are on the same bus and cannot be fetched simultaneously.
Microcontrollers from different manufacturers have different architectures and different capabilities. Some may suit a particular application while others may be totally
unsuitable for the same application. The hardware features common to most microcontrollers are described in this section.
Most microcontrollers operate with the standard logic voltage of þ5V. Some microcontrollers can operate at as low as þ2.7V, and some will tolerate þ6V without any problem. The manufacturer’s data sheet will have information about the allowed limits of the power supply voltage. PIC18F452 microcontrollers can operate with a power supply of þ2V to þ5.5V.
Usually, a voltage regulator circuit is used to obtain the required power supply voltage when the device is operated from a mains adapter or batteries. For example, a 5V regulator is required if the microcontroller is operated from a 5V supply using a 9V battery.
All microcontrollers require a clock (or an oscillator) to operate, usually provided by external timing devices connected to the microcontroller. In most cases, these external timing devices are a crystal plus two small capacitors. In some cases they are resonators or an external resistor-capacitor pair. Some microcontrollers have built-in timing circuits and do not require external timing components. If an application is not time- sensitive, external or internal (if available) resistor-capacitor timing components are the best option for their simplicity and low cost.
An instruction is executed by fetching it from the memory and then decoding it. This usually takes several clock cycles and is known as the instruction cycle. In PIC microcontrollers, an instruction cycle takes four clock periods. Thus the microcontroller operates at a clock rate that is one-quarter of the actual oscillator frequency. The PIC18F series of microcontrollers can operate with clock frequencies up to 40MHz.
Timers are important parts of any microcontroller. A timer is basically a counter which is driven from either an external clock pulse or the microcontroller’s internal oscillator. A timer can be 8 bits or 16 bits wide. Data can be loaded into a timer under program control, and the timer can be stopped or started by program control. Most timers can be configured to generate an interrupt when they reach a certain count (usually when they overflow). The user program can use an interrupt to carry out accurate timing-related operations inside the microcontroller. Microcontrollers in the PIC18F series have at least three timers. For example, the PIC18F452 microcontroller has three built-in timers.
Some microcontrollers offer capture and compare facilities, where a timer value can be read when an external event occurs, or the timer value can be compared to a preset value, and an interrupt is generated when this value is reached. Most PIC18F microcontrollers have at least two capture and compare modules.
Most microcontrollers have at least one watchdog facility. The watchdog is basically a timer that is refreshed by the user program. Whenever the program fails to refresh
the watchdog, a reset occurs. The watchdog timer is used to detect a system problem, such as the program being in an endless loop. This safety feature prevents runaway software and stops the microcontroller from executing meaningless and unwanted code. Watchdog facilities are commonly used in real-time systems where the successful termination of one or more activities must be checked regularly.
A reset input is used to reset a microcontroller externally. Resetting puts the microcontroller into a known state such that the program execution starts from address 0 of the program memory. An external reset action is usually achieved by connecting a push-button switch to the reset input. When the switch is pressed, the microcontroller is reset.
Interrupts are an important concept in microcontrollers. An interrupt causes the microcontroller to respond to external and internal (e.g., a timer) events very quickly. When an interrupt occurs, the microcontroller leaves its normal flow of program execution and jumps to a special part of the program known as the interrupt service routine (ISR). The program code inside the ISR is executed, and upon return from the ISR the program resumes its normal flow of execution.
The ISR starts from a fixed address of the program memory sometimes known as the interrupt vector address. Some microcontrollers with multi-interrupt features have just one interrupt vector address, while others have unique interrupt vector addresses, one for each interrupt source. Interrupts can be nested such that a new interrupt can suspend the execution of another interrupt. Another important feature of multi-interrupt capability is that different interrupt sources can be assigned different levels of priority. For example, the PIC18F series of microcontrollers has both low-priority and high- priority interrupt levels.
Brown-out detectors, which are common in many microcontrollers, reset the microcontroller if the supply voltage falls below a nominal value. These safety features can be employed to prevent unpredictable operation at low voltages, especially to protect the contents of EEPROM-type memories.
An analog-to-digital converter (A/D) is used to convert an analog signal, such as voltage, to digital form so a microcontroller can read and process it. Some microcontrollers have built-in A/D converters. External A/D converter can also be connected to any type of microcontroller. A/D converters are usually 8 to 10 bits, having 256 to 1024 quantization levels. Most PIC microcontrollers with A/D features have multiplexed A/D converters which provide more than one analog input channel. For example, the PIC18F452 microcontroller has 10-bit 8-channel A/D converters.
The A/D conversion process must be started by the user program and may take several hundred microseconds to complete. A/D converters usually generate interrupts when a conversion is complete so the user program can read the converted data quickly.
A/D converters are especially useful in control and monitoring applications, since most sensors (e.g., temperature sensors, pressure sensors, force sensors, etc.) produce analog output voltages.
Serial communication (also called RS232 communication) enables a microcontroller to be connected to another microcontroller or to a PC using a serial cable. Some
microcontrollers have built-in hardware called USART (universal synchronous- asynchronous receiver-transmitter) to implement a serial communication interface. The user program can usually select the baud rate and data format. If no serial input-output hardware is provided, it is easy to develop software to implement serial data communication using any I/O pin of a microcontroller. The PIC18F series of
microcontrollers has built-in USART modules. We shall see in Chapter 6 how to write mikroC programs to implement serial communication with and without a USART module.
Some microcontrollers (e.g., the PIC18F series) incorporate SPI (serial peripheral interface) or I2C (integrated interconnect) hardware bus interfaces. These enable a microcontroller to interface with other compatible devices easily.
EEPROM-type data memory is also very common in many microcontrollers. The advantage of an EEPROM memory is that the programmer can store nonvolatile data there and change this data whenever required. For example, in a temperature monitoring application, the maximum and minimum temperature readings can be stored in an EEPROM memory. If the power supply is removed for any reason, the values of the latest readings are available in the EEPROM memory. The PIC18F452 microcontroller has 256 bytes of EEPROM memory. Other members of the PIC18F family have more EEPROM memory (e.g., the PIC18F6680 has 1024 bytes). The mikroC language provides special instructions for reading and writing to the EEPROM memory of a PIC microcontroller.
LCD drivers enable a microcontroller to be connected to an external LCD display directly. These drivers are not common since most of the functions they provide can be implemented in software. For example, the PIC18F6490 microcontroller has a built-in LCD driver module.
Analog comparators are used where two analog voltages need to be compared. Although these circuits are implemented in most high-end PIC microcontrollers, they are not common in other microcontrollers. The PIC18F series of microcontrollers has built-in analog comparator modules.
A real-time clock enables a microcontroller to receive absolute date and time information continuously. Built-in real-time clocks are not common in most microcontrollers, since the same function can easily be implemented by either a dedicated real-time clock chip or a program written for this purpose.
Some microcontrollers (e.g., PICs) offer built-in sleep modes, where executing this instruction stops the internal oscillator and reduces power consumption to an extremely low level. The sleep mode’s main purpose is to conserve battery power when the microcontroller is not doing anything useful. The microcontroller is usually woken up from sleep mode by an external reset or a watchdog time-out.
Some microcontrollers (e.g., PICs) have built-in power-on reset circuits which keep the microcontroller in the reset state until all the internal circuitry has been initialized. This feature is very useful, as it starts the microcontroller from a known state on power-up. An external reset can also be provided, where the microcontroller is reset when an external button is pressed.
Low-power operation is especially important in portable applications where microcontroller-based equipment is operated from batteries. Some microcontrollers (e.g., PICs) can operate with less than 2mA with a 5V supply, and around 15mA at a 3V supply. Other microcontrollers, especially microprocessor-based systems with several chips, may consume several hundred milliamperes or even more.
Current sink/source capability is important if the microcontroller is to be connected to an external device that might draw a large amount of current to operate. PIC
microcontrollers can source and sink 25mA of current from each output port pin. This current is usually sufficient to drive LEDs, small lamps, buzzers, small relays, etc. The
current capability can be increased by connecting external transistor switching circuits or relays to the output port pins.
USB is currently a very popular computer interface specification used to connect various peripheral devices to computers and microcontrollers. Some PIC microcontrollers provide built-in USB modules. The PIC18F2x50, for example, has built-in USB interface capabilities.
Some PIC microcontrollers, for example the PIC18F2x31, provide motor control interface capability.
CAN bus is a very popular bus system used mainly in automation applications. Some PIC18F-series microcontrollers (e.g., the PIC18F4680) provide CAN interface capability.
Some PIC microcontrollers (e.g., the PIC18F97J60) provide Ethernet interface capabilities and thus are easily used in network-based applications.
ZigBee, an interface similar to Bluetooth, is used in low-cost wireless home automation applications. Some PIC18F-series microcontrollers provide ZigBee interface capabilities, making the design of such wireless systems very easy.
A microcontroller is a single-chip computer. Micro suggests that the device is small, and controller suggests that it is used in control applications. Another term for microcontroller is embedded controller, since most of the microcontrollers are built into (or embedded in) the devices they control.
A microprocessor differs from a microcontroller in a number of ways. The main distinction is that a microprocessor requires several other components for its operation, such as program memory and data memory, input-output devices, and an external clock circuit. A microcontroller, on the other hand, has all the support chips incorporated inside its single chip. All microcontrollers operate on a set of instructions (or the user program) stored in their memory. A microcontroller fetches the instructions from its program memory one by one, decodes these instructions, and then carries out the required operations.
Microcontrollers have traditionally been programmed using the assembly language of the target device. Although the assembly language is fast, it has several disadvantages. An assembly program consists of mnemonics, which makes learning and maintaining a program written using the assembly language difficult. Also, microcontrollers manufactured by different firms have different assembly languages, so the user must learn a new language with every new microcontroller he or she uses.
Microcontrollers can also be programmed using a high-level language, such as BASIC, PASCAL, or C. High-level languages are much easier to learn than assembly languages. They also facilitate the development of large and complex programs. In this book we shall be learning the programming of PIC microcontrollers using the popular C language known as mikroC, developed by mikroElektronika.
In theory, a single chip is sufficient to have a running microcontroller system. In practical applications, however, additional components may be required so the microcomputer can interface with its environment. With the advent of the PIC family of microcontrollers the development time of an electronic project has been reduced to several hours.
Basically, a microcomputer executes a user program which is loaded in its program memory. Under the control of this program, data is received from external devices (inputs), manipulated, and then sent to external devices (outputs). For example, in a microcontroller-based oven temperature control system the microcomputer reads the temperature using a temperature sensor and then operates a heater or a fan to keep the temperature at the required value. Figure 1.1 shows a block diagram of a simple oven temperature control system.
The system shown in Figure 1.1 is very simple. A more sophisticated system may include a keypad to set the temperature and an LCD to display it. Figure 1.2 shows a block diagram of this more sophisticated temperature control system.
We can make the design even more sophisticated (see Figure 1.3) by adding an alarm that activates if the temperature goes outside the desired range. Also, the temperature readings can be sent to a PC every second for archiving and further processing. For example, a graph of the daily temperature can be plotted on the PC. As you can see, because microcontrollers are programmable the final system can be as simple or as complicated as we like.
A microcontroller is a very powerful tool that allows a designer to create sophisticated input-output data manipulation under program control. Microcontrollers are classified by the number of bits they process. Microcontrollers with 8 bits are the most popular and are used in most microcontroller-based applications. Microcontrollers with 16 and 32 bits are much more powerful, but are usually more expensive and not required in most small- or medium-size general purpose applications that call for microcontrollers.
The simplest microcontroller architecture consists of a microprocessor, memory, and input-output. The microprocessor consists of a central processing unit (CPU) and a
control unit (CU). The CPU is the brain of the microcontroller; this is where all the arithmetic and logic operations are performed. The CU controls the internal operations of the microprocessor and sends signals to other parts of the microcontroller to carry out the required instructions.
Memory, an important part of a microcontroller system, can be classified into two types: program memory and data memory. Program memory stores the program written by the programmer and is usually nonvolatile (i.e., data is not lost after the power is turned off). Data memory stores the temporary data used in a program and is usually volatile (i.e., data is lost after the power is turned off).
There are basically six types of memories, summarized as follows:
RAM, random access memory, is a general purpose memory that usually stores the user data in a program. RAM memory is volatile in the sense that it cannot retain data in the absence of power (i.e., data is lost after the power is turned off). Most microcontrollers have some amount of internal RAM, 256 bytes being a common amount, although some microcontrollers have more, some less. The PIC18F452
microcontroller, for example, has 1536 bytes of RAM. Memory can usually be extended by adding external memory chips.
ROM, read only memory, usually holds program or fixed user data. ROM is nonvolatile. If power is removed from ROM and then reapplied, the original data will still be there. ROM memory is programmed during the manufacturing process, and the user cannot change its contents. ROM memory is only useful if you have developed a program and wish to create several thousand copies of it.
PROM, programmable read only memory, is a type of ROM that can be programmed in the field, often by the end user, using a device called a PROM programmer. Once a PROM has been programmed, its contents cannot be changed. PROMs are usually used in low production applications where only a few such memories are required.
EPROM, erasable programmable read only memory, is similar to ROM, but EPROM can be programmed using a suitable programming device. An EPROM memory has a small clear-glass window on top of the chip where the data can be erased under strong ultraviolet light. Once the memory is programmed, the window can be covered with dark tape to prevent accidental erasure of the data. An EPROM memory must be erased before it can be reprogrammed. Many developmental versions of microcontrollers are manufactured with EPROM memories where the user program can be stored. These memories are erased and reprogrammed until the user is satisfied with the program. Some versions of EPROMs, known as OTP (one time programmable), can be programmed using a suitable programmer device but cannot be erased. OTP memories cost much less than EPROMs. OTP is useful after a project has been developed completely and many copies of the program memory must be made.
EEPROM, electrically erasable programmable read only memory, is a nonvolatile memory that can be erased and reprogrammed using a suitable programming device. EEPROMs are used to save configuration information, maximum and minimum values, identification data, etc. Some microcontrollers have built-in EEPROM memories. For instance, the PIC18F452 contains a 256-byte EEPROM memory where each byte can be programmed and erased directly by applications software. EEPROM memories are usually very slow. An EEPROM chip is much costlier than an EPROM chip.
Flash EEPROM, a version of EEPROM memory, has become popular in microcontroller applications and is used to store the user program. Flash EEPROM is nonvolatile and usually very fast. The data can be erased and then reprogrammed using a suitable programming device. Some microcontrollers have only 1K flash EEPROM while others have 32K or more. The PIC18F452 microcontroller has 32K bytes of flash memory.
The term microcomputer is used to describe a system that includes at minimum a microprocessor, program memory, data memory, and an input-output (I/O) device. Some microcomputer systems include additional components such as timers, counters, and analog-to-digital converters. Thus, a microcomputer system can be anything from a large computer having hard disks, floppy disks, and printers to a single-chip embedded controller.
In this book we are going to consider only the type of microcomputers that consist of a single silicon chip. Such microcomputer systems are also called microcontrollers, and they are used in many household goods such as microwave ovens, TV remote control units, cookers, hi-fi equipment, CD players, personal computers, and refrigerators. Many different microcontrollers are available on the market. In this book we shall be looking at programming and system design for the PIC (programmable interface controller) series of microcontrollers manufactured by Microchip Technology Inc.
In general, we can make use of the block diagram shown in Figure 9.3 when designing a digital controller. In this figure, R(z) is the reference input, E (z) is the error signal, U (z) is the output of the controller, and Y (z) is the output of the system. HG(z) represents the digitized plant transfer function together with the zero-order hold.
The closed-loop transfer function of the system in Figure 9.3 can be written as
Equation (9.3) states that the required controller D(z) can be designed if we know the model of the process. The controller D(z) must be chosen so that it is stable and can be realized. One of the restrictions affecting realizability is that D(z) must not have a numerator whose order exceeds that of the numerator. Some common controllers based on (9.3) are described below.
The dead-beat controller is one in which a step input is followed by the system but delayed by one or more sampling periods, i.e. the system response is required to be equal to unity at every sampling instant after the application of a unit step input.
The required closed-loop transfer function is then
Figure 9.4 shows the system block diagram with the controller, while Figure 9.5 shows the step response of the system. The output response is unity after 3 s (third sample) and stays at this value. It is important to realize that the response is correct only at the sampling instants and the response can have an oscillatory behaviour between the sampling instants.
The control signal applied to the plant is shown in Figure 9.6. Although the dead-beat controller has provided an excellent response, the magnitude of the control signal may not be acceptable, and it may even saturate in practice.
The dead-beat controller is very sensitive to plant characteristics and a small change in the plant may lead to ringing or oscillatory response.
The Dahlin controller is a modification of the dead-beat controller and produces an exponential response which is smoother than that of the dead-beat controller.
The required response of the system in the s-plane can be shown to be
Figure 9.8 shows the step response of the system. It is clear that the response is exponential as expected.
The response of the controller is shown in Figure 9.9. Although the system response is slower, the controller signal is more acceptable.
The response of a system is determined by the positions of its closed-loop poles. Thus, by placing the poles at the required points we should be able to control the response of a system.
Pole-Placement Control – Graphical
In the previous subsection we saw how the response of a closed-loop system can be shaped by placing its poles at required points in the z-plane. In this subsection we will be looking at some examples of pole placement using the root-locus graphical approach.
When it is required to place the poles of a system at required points in the z-plane we can either modify the gain of the system or use a dynamic compensator (such as a phase lead or a phase lag). Given a first-order system, we can modify only the d.c. gain to achieve the required time constant. For a second-order system we can generally modify the d.c. gain to achieve a constant damping ratio greater than or less than a required value, and, depending on the system, we may also be able to design for a required natural frequency by simply varying the
d.c. gain. For more complex requirements, such as placing the system poles at specific points in the z-plane, we will need to use dynamic compensators, and a simple gain adjustment alone
will not be adequate. Some example pole-placement techniques are given below using the root locus approach.
The block diagram of a sampled data control system is shown in Figure 9.11. Find the value of d.c. gain K which yields a damping ratio of ζ = 0.7.
Solution
In this example, we will draw the root locus of the system as the gain K is varied, and then we will superimpose the lines of constant damping ratio on the locus. The value of K for the required damping ratio can then be read from the locus.
The root locus of the system is shown in Figure 9.12. The locus has been expanded for clarity between the real axis points (−1, 1) and the imaginary axis points (−1, 1), and the lines of constant damping ratio are shown in Figure 9.13. A vertical and a horizontal line are
drawn from the point where the damping factor is 0.7. At the required point the roots are z1,2 = 0.7191 ± j 0.2114. The value of K at this point is calculated to be K = 0.0618.
In this example, the required specification was obtained by simply modifying the d.c. gain of the system. A more complex example is given below where it is required to place the poles at specific points in the z-plane.
The block diagram of a digital control system is given in Figure 9.14. It is required to design a controller for this system such that the system poles are at the points z1,2 = 0.3 ± j 0.3.
Solution
In this example, we will draw the root locus of the system and then use a dynamic compensator to modify the shape of the locus so that it passes through the required points in the z-plane.
The root locus of the system without the compensator is shown in Figure 9.15. The point where we want the roots to be is marked with a × and clearly the locus will not pass through this point by simply modifying the d.c. gain K of the system.
The angle of G(z) at the required point is
There are many combinations of p and n which will give the required angle. For example, if we choose n = 0.5, then,
The compensator introduces a zero at z = 0.5 and a pole at z = 0.242. The root locus of the compensated system is shown in Figure 9.16. Clearly the new locus passes through the required points z1,2 = 0.3 ± j 0.3, and it will be at these points that the d.c. gain is K = 0.185. The step response of the system with the compensator is shown in Figure 9.17. It is clear from this diagram that the system has a steady-state error.
The block diagram of the controller and the system is given in Figure 9.18.
The block diagram of a system is as shown in Figure 9.19. It is required to design a controller for this system with percent overshoot (PO) less than 17 % and settling time ts ≤ 10 s. Assume that T = 0.1 s.
The root locus of the uncompensated system and the required root position is shown in Figure 9.20.
It is clear from the figure that the root locus will not pass through the marked point by simply changing the d.c. gain. We can design a compensator as in Example 9.5 such that the locus passes through the required point, i.e.
Since the sum of the angles at a point in root locus must be a multiple of −180◦, the compensator must introduce an angle of −180 − (−259) = 79◦. The required angle can be obtained using a compensator with a transfer function, and the angle introduced by the compensator is
Figure 9.21 shows the root locus of the compensated system. Clearly the locus passes through the required point. The d.c. gain at this point is K = 123.9.
The time response of the compensated system is shown in Figure 9.22.
The circuit diagram of the closed-loop system is shown in Figure 11.10. The loop is closed by connecting the output of the level sensor to the analog input AN0 of the microcontroller.
Notice that the output of the microcontroller was set to 200, which corresponds to 200× 5000/256 = 3906 mV, and this was the voltage applied to the power. We then obtain the following transfer function:
The time constant of the system is 31 s. It was shown in Section 10.6 that the sampling time should be chosen to be less than one-tenth of the system time constant, i.e. T < 3.1 s. In this case study, the sampling time is chosen to be 100 ms, i.e. T = 0.1 s.
The controller software is shown in Figure 11.13. The PI algorithm has been implemented as a parallel structure. At the beginning of the program the controller parameters are defined. The program consists of the functions Initialize AD, Initialize Timer, Read AD Input, and the interrupt service routine (ISR). The A/D converter is initialized to receive analog data from channel AN0. The Read AD Input function reads a sample from the A/D converter and stores it in variable yk . The timer is initialized to interrupt every 10 ms. At the beginning of the ISR routine, the PI algorithm is implemented after every 10th interrupt, i.e. every 100 ms. This ensures that the controller sampling time is 100 ms. The ISR routine reads the output of the level sensor and converts it to digital. Then the PI controller algorithm is implemented. Notice that in the algorithm the input of the D/A converter is limited to full scale, i.e. 255. After sending an output to D/A, the ISR routine re-enables the timer interrupts and the program waits for the occurrence of the next interrupt.
The step response of the closed-loop system is shown in Figure 11.14. Here, the reference input was set to 2280. Clearly the system response, although noisy, reaches the set-point with no steady-state error, as desired.
The system is basically a first-order system. The tank acts as a fluid capacitor where fluid enters and leaves the tank. According to mass balance,
where Qin is the flow rate of water into the tank, Q the rate of water storage in the tank, and Qout the flow rate of water out of the tank. If A is the cross-sectional area of the tank, and h the height of water inside the tank, (11.1) can be written as
The system was identified by carrying out a simple step response test. Figure 11.6 shows the hardware set-up for the step response test. The port B output of the microcontroller is connected to data inputs of the D/A converter, and the converter is controlled from pin RC0 of the microcontroller. The output of the D/A converter is connected to the LM675 power amplifier which drives the pump. The value of the step was chosen as 200, which corresponds to a D/A voltage of 5000 × 200/256 = 3.9 V. The height of the water inside the tank (output of the level
sensor) was recorded in real time using a DrDaq type data logger unit and the Picolog software. Both of these products are manufactured by PICO Technology. DrDaq is a small electronic card which is plugged into the parallel port of a PC. The card is equipped with sensors to measure physical quantities such as the intensity, sound level, voltage, humidity, and temperature. Picolog runs on a PC and can be used to record the measurements of the DrDaq card in real time. The software includes a graphical option which enables the measurements to be plotted. The microcontroller program to send a step signal to the D/A converter is shown in Figure 11.7. At the beginning of the program the input–output ports are configured and then a step signal (200) is sent to port B. The D/A converter is then enabled by clearing its WR input. After writing data to the D/A converter it is disabled so that its output does not accidentally change. The program then waits in an endless loop.
Figure 11.8 shows the step response of the system, which is the response of a typical first- order system. It will be seen that the response contains noise. Also, since the DrDaq data logger is 8-bit, its resolution is about 19.5 mV with a reference input of 5V, and this causes the step discontinuities shown in the response (the steps can be eliminated either by using a data logger with a higher resolution, or by amplifying the output of the level sensor). The figure clearly shows that in practice the response of a system is not always a perfect textbook signal.
A smooth curve is drawn through the response by taking the midpoints of the steps, as shown in Figure 11.9.
The final stage of a digital control system design is the implementation of the controller algorithm (set of difference equations) on a digital computer. In this section, we shall explore the implementation of digital controller algorithms on PIC microcontrollers. The PIC 16F877 microcontroller will be used in the examples since this microcontroller has a built-in A/D converter and a reasonable amount of program memory and data memory. There are many other microcontrollers in the PIC family with built-in A/D converters, and in general any of these can be used since the operation of microcontrollers in the PIC family with similar features is identical.
Microcontrollers have traditionally been programmed using the assembly language of the target hardware. Assembly language has several important disadvantages and is currently less popular than it used to be. One important disadvantage is that the code generated using the assembly language can only run on the specific target hardware. For example, the assembly program developed for a PIC microcontroller cannot be used, say, on an Intel 8051 micro- controller. Assembly language programs also tend to be more difficult to develop, test and maintain.
In this section, the Hi-Tech PICC language as described in Chapter 4 is used in the imple- mentation of the algorithms. As described in Section 1.6 there are several methods that can be used to implement the controller algorithm. One of the most common, which has the advantage of accurate implementation, is the use of a timer interrupt to generate the required loop delay (or the sampling interval). In this method the software consists of two parts: the main pro- gram and the interrupt service routine. As shown in Figure 10.15(a) Figure 10.15, in the main program various variables, as well as the A/D converter and the timer interrupt mechanism, are initialized. The timer is set to interrupt at an interval equivalent to the sampling interval of the required digital controller. The main program then enters a loop waiting for the timer interrupts to occur. Whenever a timer interrupt occurs the program jumps the interrupt service
routine (ISR) as shown in Figure 10.15(b), and it is within this routine that the actual controller algorithm is implemented. The error signal is obtained by calculating the difference between the reference values and measured values. The algorithm is then implemented and the output sample for the current sampling time is obtained. A preprocessing step is then performed by updating the variables for the next sample. On return from the ISR, the program waits in the main program until the next sampling interval, and the above process repeats.
In Section 10.2 we saw how a second-order module can be realized using adders, multipliers and delay elements. The second-order module is shown in Figure 10.16. The difference equations describing such a module are (10.19) and (10.20). If we let
The implementation of the second-order module is shown as a flow-chart in Figure 10.17. This figure does not show the initialization of the variables T1, T2, r1, r2, the A/D initialization,
the I/O port initialization, etc.; it only shows the interrupt service routine. A PIC microcon- troller program for the implementation of a second-order module is given in the following example.
The circuit diagram of a digital control system is shown in Figure 10.18. A PIC16F877 micro- controller is to be used as the digital controller in this system. Assume that the set-point input s is to be hard-coded to the program, and the output y is analog and connected to A/D channel AN0 (bit 0 of port A) of the microcontroller. The microcontroller is assumed to operate with a crystal frequency of 4 MHz as shown in the figure. The output (port B) of the microcontroller is interfaced to a D/A converter which acts as a zero-order-hold and generates an analog output to drive the plant.
Solution
The controller hardware is based on a PIC16F877 microcontroller. The microcontroller is operated from a 4 MHz crystal, connected to OSC1 and OSC2 inputs. With a 4 MHz crystal, the basic clock rate of the microcontroller is 1µs (the crystal frequency is divided by 4 to obtain the basic timing rate). The analog output of the plant (y) is connected to A/D converter channel AN0 of the microcontroller. Similarly, port B digital outputs of the microcontroller are connected to an AD7302 type D/A converter. The operation of this D/A converter is very simple. Digital data is applied to eight inputs D0–D7, while the write control input, WR, is at logic high. The analog data appears at the output after the WR input is lowered to logic low. The WR input of the D/A converter is controlled from port pin RC0 of the microcontroller. The D/A converter is set to operate with a full-scale reference voltage of +5 V. The resolution of the converter is 8 bits, i.e. there are 28 = 256 quantization levels. With a full-scale reference voltage of +5 V,
the resolution is 5000/256 = 19.53 mV, i.e. the digital bit pattern ‘00000001’ corresponds to 19.53 mV, the bit pattern ‘00000010’ corresponds to 2 × 19.53 = 39.06 mV and so on.
The first program attempt is shown in Figure 10.19. Comments are used to describe operation of various parts of the program. The program consists of the main program and the functions: Initialize AD, Initialize Timer, Read AD Input, and ISR.
Main program. The coefficients of the controller are defined at the beginning of the main program. Also, the A/D converter and the timer initialization functions are called here. The main program then enables global interrupts and enters an endless loop waiting for timer interrupts to occur.
ISR. This is the interrupt service routine. The program jumps to this function every 10 ms. The function reads a sample, and calculates the error term ek . The output value yk is then calculated and sent to the D/A converter. In the final part of the ISR, the variables are updated for the next sample, and the timer interrupt is re-enabled.
Initialize Timer. This function initializes the timer TMR0 so that timer interrupts can be generated at 10 ms intervals. As described in Chapter 3, the timing interval depends on the clock frequency, the pre-scaler value, and the data loaded into the TMR0 register. It can be shown that the timing interval is given by:
Initialize AD. This function initializes the A/D converter so that analog data can be received from channel AN0 of the microcontroller. As described in Chapter 3, the A/D converter is initialized by first selecting the reference voltage and the output data format using the ADCON1 register, and then selecting the A/D converter clock using the ADCON0 register. Thus, channel AN0 is configured by loading 0x8E into the ADCON1 register, and 0x41 into the ADCON0 register. Thus, the Initialize AD function is programmed as follows:
Read AD Input. This function starts the A/D converter and reads a sample at the end of the conversion. The conversion is started by setting the GO/DONE bit of ADCON0. The program should then wait until the conversion is complete, which is indicated by the GO/DONE bit becoming zero. The high 2 bits of the converted data are in ADRESH, and the low 8 bits are in register ADRESL. The 10-bit converted data is extracted and stored in variable yk .
Implementing First-Order Modules
In Section 10.2 we saw how a first-order module can be realized using adders, multipliers and delay elements. The first-order module is shown in Figure 10.21. The difference equations describing a first-order module were found to be
The implementation of the first-order module is similar to the second-order module and an example is given below.
The circuit diagram of a digital control system is shown in Figure 10.18. A PIC16F877 micro- controller is to be used as the digital controller in this system. Assume that the set-point input s is to be hard-coded to the program, and the output y is analog and connected to A/D channel AN0 (bit 0 of port A) of the microcontroller. The microcontroller is assumed to operate with a crystal frequency of 4 MHz as shown in the figure. The output (port B) of the microcontroller is interfaced to a D/A converter which acts as a zero-order-hold and generates an analog output to drive the plant.
Assume that the digital controller to be implemented is in the form of a first-order module, and write a program in C to implement this controller. The controller parameters are assumed to be:
Solution
The implementation of a first-order module is very similar to a second-order module. The program to implement a first-order controller is shown in Figure 10.22. The operation of the program is very similar to the second-order program and is not described here.
Higher-order controllers can be implemented by cascading first-order and second-order mod- ules. For example, a fourth-order controller can be implemented by cascading two second-order modules, as shown in Figure 10.23.