Docstoc

systems and control

Document Sample
systems and control Powered By Docstoc
					       DET
Technological Studies
  Systems and Control
   (Advanced Higher)

                    7638
August 2000
                           HIGHER STILL




                            DET
              Technological Studies
                 Systems and Control

                       Advanced Higher




Support Materials
                                  
                                  
CONTENTS




Outcome 1 – control systems


Outcome 2 – microcontroller controlled mechatronic systems
 Section 1 – introduction
 Section 2 – programming in assembler control
 Section 3 – mechatronic system interfacing circuits
 Section 4 – project activities


Outcome 3 – proportional control




DET: Technological Studies: Systems and Control (Advanced Higher)   1
DET: Technological Studies: Systems and Control (Advanced Higher)   2
OUTCOME 1 – CONTROL SYSTEMS



The purpose of this unit is to introduce the operation of control systems.

When you have completed this unit you should be able to:
 recognise and identify common control systems
 describe the operation of open and closed loop control systems
 make use of systems diagrams and systems technology
 describe sequential control strategy
 compare open loop and closed loop control.

Before you start this unit you should have a basic understanding of:
 block diagrams.




DET: Technological Studies: Systems and Control (Advanced Higher)            3
Systems diagrams

Most industrial product design is solved by the systems approach. This approach
involves studying the desired function of the product, and then breaking this function
down into a series of subsystems.

When applied to control systems, a systems diagram is a useful way of visually
representing the desired function of the system. The systems diagram is a form of
block diagram that contains all the subsystems within a dashed box, called the
systems boundary. The systems boundary indicates the extent of the control system.



                           CONTROL                    OUTPUT               OUTPUT
  INPUT
                                                      DRIVER



                                          Figure 1


The ‘real world’ input and output conditions of the system are shown as arrows
entering, and leaving, the systems diagram.




DET: Technological Studies: Systems and Control (Advanced Higher)                        4
Basic control function

All systems require some controlling function to ensure that the system will carry out
the desired task. Moreover the controlling function has to ensure that the task is
carried out within the required specification for safety, accuracy, repeatability and
speed.

A control operation requires an input. The input expresses the desired outcome from
the control function. The control function will process this input and hopefully
produce the desired output. Figure 2 shows the basic concept.




                    INPUT               CONTROL
                                                                    OUTPUT
                                        FUNCTION




                                          Figure 2



Examples of input – control – output:
 a person observes the flow of traffic (input)
 checks for a safe time to cross (control)
 crosses the road (output)
 places ingredients for making a cake in a mixing bowl (input)
 mixes ingredients for a specified time (control)
 transfers mix to baking bowl (output)
 set an electric drill input for a specified speed (input)
 input processed by control section (control)
 output to motor for desired speed.

The same principles are applied to an industrial robot. The robot requires an input to
know what it has to do. It requires a control section to interpret and process this input
into the required output signal. Finally it requires the proper output devices to
respond to the output signal and produce the desired effect.




DET: Technological Studies: Systems and Control (Advanced Higher)                       5
Sequence control

Sequence control is applied to many industrial processes, including mechanical
handling and packaging.

Sequence control means carrying out a series of tasks, one after the other and in a
prescribed order. There are two forms of sequence control, ‘event-based’ and ‘time-
based’.

Event based
In an event based system each task in the sequence of tasks can only be initiated when
the previous task has indicated completion. Sensors are required in an event-based
system to indicate when a task is completed.

An example of an event-based system is shown graphically in Figure 3. It is simply
an automated system to pick up items, take them to a drill to drill a hole and then
remove the completed item to a box.



                                    Pick up item

                                              Item picked up
                                     Move item
                                     under drill

                                             Item under drill

                                  Drill hole in item

                                             Hole completed

                                  Drop item in box


                                               Item in box




                                             Figure 3


The rectangles represent tasks or actions to perform in sequence from top to bottom.
Each short horizontal line provides a sensor to indicate when the previous action has
completed. Only when the condition at the horizontal line has been satisfied can the
system proceed to the next task.




DET: Technological Studies: Systems and Control (Advanced Higher)                       6
Time based
Each task is still carried out one after the other but in a time based system each task is
sequenced to time. There are no sensors to indicate when a task has been completed.
In basic terms an action is scheduled to last for a set time. When that time has expired
the next action is initiated and it will endure for a set time and so on.

An example will best illustrate the time based system:
 a robot arm moves to picks up an item
 three seconds delay
 the robot arm moves item under drill
 three second delay
 a hole is drilled in item
 six seconds delay
 item is moved into a box
 four seconds delay
 return to pick up a new item.

Here we have repeated the identical sequence as before but substituted time delays for
sensors. In such an application the time based system may work perfectly many times
but it cannot be as accurate or reliable as the event based system. What happens if an
item is not available for pick up? The time based system will not be aware of this and
continue to operate as if an item was present. What happens if the robot slows down
because of increased friction or low voltage to its motors? The time delay to allow it
time to place the item under the drill may suddenly be too short and the system may
attempt to drill with the item still moving in under the drill.

The sensor based event system would wait until an item was available for pick up. If
no item were available the system would wait until an item became available. If the
robot arm slowed down for any reason the system would still function properly as it
would wait until an item was placed under the drill before drilling could commence.

Summary
Event based systems are more reliable than time based systems but are more
expensive due to the requirement to fit sensors for each event in the sequence.
Time based systems are less reliable as they use time delays between events rather
than perceiving that each event has occurred. In less critical applications such as
mixing sequences (mixing various ingredients for various times) time based systems
are ideal and less expensive (no sensors required).




DET: Technological Studies: Systems and Control (Advanced Higher)                       7
Open loop control

The cheapest and easiest method of control to apply to a process is open loop control
shown in Figure 4.



                          Open Loop Control Format.

                                               disturbances

            INPUT                    CONTROL                        OUTPUT
            SIGNAL                   FUNCTION                       DEVICE




                                          Figure 4


Open Loop control requires an input. The input expresses the user’s requirement
from the process under control. The control function takes the input, processes it and
produces an output effort. The output accepts the output effort and produces the
desired effect on the process. We will comment on ‘disturbances’ shortly.

Examples
Let’s look at an example of open loop control prior to examining it in greater depth.
A new conveyor is installed in a factory to carry goods from the production machines
to the warehouse. The conveyor will run at a steady speed on a particular production
run but must be capable of running at four different speeds for different production
runs. The speed will be set by an operator before the start of each run.

Solution
Assume that a DC motor has been selected to drive the conveyor. The control
function will be a device which provides a variable DC voltage output, for a variable
input, to run the motor at different speeds. Let’s assume that a control dial is provided
to vary the input to the controller.

A commissioning procedure prior to start up would entail one technician measuring
the speed of the conveyor with a hand held device and a second technician adjusting
the speed with the control dial. Once the desired speed is attained the speed position
would be marked on the dial. The same procedure would be done to mark the other
three speed positions on the dial.




DET: Technological Studies: Systems and Control (Advanced Higher)                        8
The system is now set up and can be used easily by different operators on different
shifts by merely setting the desired production speed on the controller dial.

Disturbances

Certain factors are liable to occur which may prevent the conveyor running at the
designated speeds on the dial.

The bearings and rollers on the conveyor may develop increased friction due to poor
maintenance. The DC drive motor will need to meet this increased load. To do this it
has to slow down. The same slowing down effect occurs if additional load is placed
on the conveyor (heavier items to be carried).

Limitations of open loop
These examples illustrate the main point about an open loop system. It is not a self-
monitoring system (no sensor to monitor the actual speed) and so its accuracy is
limited because external disturbances can modify the desired output.

Advantages of open loop
Open loop control is relatively cheap to apply (no sensors required) and in many
applications it may be a satisfactory solution where high accuracy of final output is
not essential. In most applications of open loop control, the response to a step input
(instant change of input signal) is a smooth change from one stable state to the next.
In the conveyor example it may be perfectly satisfactory to have a system which only
maintains speed accuracy at 10%. Open loop control gives us the capability of
running the conveyor at different speeds at a moderate cost.

Closed loop control
Closed loop control is a more accurate system of control, and at the same time more
expensive. It employs self-monitoring where a sensor is used to read the condition
being controlled.

Figure 6 shows a block diagram of a closed loop system. The process under control
could be any of a range of industrial processes involving temperature, speed, force,
pressure etc.

The value we are trying to achieve is the input value set by the users and is often
called ‘desired value’ or ‘set point’. The sensor gives the actual value of the condition
we are controlling and is often titled ‘measured value’ or ‘actual value’.




DET: Technological Studies: Systems and Control (Advanced Higher)                       9
                                       Error                  Control action


             Desired value
                             +                                      Process being
                                                Controller
                                 -                                   controlled


                                     Actual value
                                                       Feedback
                                                        Sensor


                                                    Figure 6

Closed loop control uses a comparator. It compares two values by subtracting the
actual value from the desired value. Any difference between the two produces an
error which is fed to the controller. The controller generates a control action on the
process to try and eliminate this error.

On-off control
The simplest form of closed loop control is on-off control. The system applies full
corrective action if an error is present and none if the error is zero. A simple example
is the temperature control of a water heater in a domestic situation. When the
temperature is lower than the desired value, the thermostat contact closes and full heat
is applied. When the temperature is equal to or greater than the desired value, the
thermostat opens and the heater is turned off. Figure 7 shows the temperature control
achieved with on-off control. Note the oscillating nature of the actual temperature
around the desired value. The fluctuating nature of the control is acceptable in
applications with slow response times.


                                               Actual value




                                                    Desired
                       Temperature                  value




                                                        Time




                                                    Figure 7

The unsteady nature of the measured value in on-off control is the result of the output
either being full on or full off. This causes over correction to the measured value,
especially with processes that have significant delays in their response to change.




DET: Technological Studies: Systems and Control (Advanced Higher)                        10
Assignments

1 Explain what is meant by ‘sequence control’.

2 A robot arm picks up a metal part from a conveyor. When grasped the arm is
  raised to clear obstacles. When raised the arm moves the part over a container.
  When over the container the arm lowers into the container. When in the container
  the arm releases the part. When released the arm is raised to clear the box. When
  clear the arm moves back to the conveyor.

a) Describe two ways in which these tasks could be executed. Select the best method
   for the task, giving a reason for your choice and why the alternative method may
   not be as suitable.
b) Suggest a suitable application for the alternative control method.


3 A D.C. electric motor is chosen to drive a section of a production line. Whether to
   control the motor speed by open or closed loop has not yet been decided.
   Describe how each methods works and comment on the suitability of each in
   terms of:
a) how easily they could be applied
b) the cost of each method
c) the accuracy of each technique
d) the stability.




DET: Technological Studies: Systems and Control (Advanced Higher)                 11
DET: Technological Studies: Systems and Control (Advanced Higher)   12
OUTCOME 2 – MICROCONTROLLER CONTROLLED MECHATRONIC
SYSTEMS




Section 1 – introduction

The purpose of this section is to introduce the microcontroller and it’s architecture.

When you have completed this section you should be able to:
 describe the operation and architecture of microcontrollers
 understand the terms ALU, RAM, ROM, EEPROM, bus
 understand how the microcontroller operates.

Before you start this section you should have a basic understanding of:
 no previous knowledge required.


Section 2 – programming in assembler code

When you have completed this section you should be able to:
 understand the use of flowcharts
 develop flowcharts from a brief
 understand the most common assembler commands
 write assemblers programs that involve loops, input decisions and sub-procedures.

Before you start this section you should have a basic understanding of:
 the architecture of a microcontroller
 the decimal, binary and hexadecimal number systems
 flowcharts.



Section 3 – mechatronic system interfacing circuits

The purpose of this section is to understand the need for interfacing input and output
devices when building mechatronic systems that are controlled by a microcontroller.

When you have completed this section you should be able to:
 explain why interfacing circuits are required within mechatronic systems
 select appropriate interfacing techniques for common output devices
 understand how unipolar stepper motors are controlled
 understand pulse-width modulated control of dc motors
 understand how simple servos are controlled.




DET: Technological Studies: Systems and Control (Advanced Higher)                        13
Section 4 – project activities

To complete the practical exercises in this outcome you will require:
 PIC Programmer and PIC16F84 microcontroller
 Stamp Controller fitted with ZIF socket
 Output Driver Module
 Inputs Module and Sensors
 Serial ADC Module with variable resistor
 DC Solar Motor with Propeller
 Stepper Motor
 Radio Control Servo.




DET: Technological Studies: Systems and Control (Advanced Higher)       14
Section 1 – introduction

What is a microcontroller?
A microcontroller is often described as a ‘computer-on-a-chip’. Microcontrollers
have memory, processing units, and input/output circuitry all built into a single chip.
As they are small and inexpensive they can easily be built into other devices to make
these products more intelligent and easier to use.




Microcontrollers are usually programmed to perform one specific control task – for
instance, a microwave oven may use a single microcontroller to process information
from the keypads, display user information on the seven segment display, and control
the output devices (turntable motor, light, bell and magnetron).
Microcontrollers are computers designed to control specific processes or products.
The microcontroller is programmed with a specific software program to complete the
desired task. By altering this software program the same microcontroller can be used
to complete different tasks. Therefore the same device can be used in a range of
different products by simply programming it with a different software program.




DET: Technological Studies: Systems and Control (Advanced Higher)                     15
One microcontroller can often replace a number of separate parts, or even a complete
electronic circuit. Some of the advantages of using microcontrollers in a product
design are:
 increased reliability and reduced stock inventory (as one microcontroller replaces
   several parts)
 simplified product assembly and smaller end products
 greater product flexibility and adaptability since features are programmed into the
   microcontroller and not built into the electronic hardware
 rapid product changes or development by changing the program and not the
   electronic hardware.

Applications that use microcontrollers include household appliances, alarm systems,
medical equipment, vehicle subsystems, and electronic instrumentation. Although
microprocessor systems (such as those based around the Intel Pentium™ processor)
tend to be more widely publicised (mainly via personal computer systems),
microcontroller manufacturers actually sell hundreds of microcontrollers for every
microprocessor sold.




DET: Technological Studies: Systems and Control (Advanced Higher)                  16
The Microchip PICmicro PIC16F84 microcontroller

There are many different types of microcontroller available, from a number of
different manufacturers. One of the most popular ‘brands’ is the PICmicro range,
manufactured by Microchip.




This course is based around the Microchip PIC16F84 microcontroller. The reasons
for this choice are:
 the microcontroller is fabricated using FLASH memory, which means it can be
   directly reprogrammed without the need for erasing
 the microcontroller is readily available at low cost
 the microcontroller is directly compatible with the Stamp Controller hardware.

Although the programming techniques explained within this course apply to most
microcontrollers, other brands of microcontroller may not be used on this course, as
they may not be compatible with the instruction set used. Only the official Microchip
Windows assembler (mpasmwin.exe) may be used.




DET: Technological Studies: Systems and Control (Advanced Higher)                  17
Technical note
The full technical part number of the PICmicro microcontroller used on this course is:
 microchip PIC16F84-04/P or
 microchip PIC16F84A-04/P.

The -04 indicates that the device operates up to a clock speed of 4MHz and the /P
suffix indicates a DIP plastic dual-in-line package.

Note that later die revisions of the PIC16F84 microcontroller may also be used as they
become available. Later die revisions are indicated with a revision letter after the
number, so, for instance, the PIC16F84B-04/P may also be used (if released in the
future).

This microcontroller, the PIC Programmer and all other parts used within this course
may be purchased from www.tech-supplies.co.uk

Commercial selection of microcontroller type
There are many different microcontroller devices available in the PICmicro family. In
commercial products, selection of the most appropriate microcontroller depends on a
number of factors.

Input/output pins
Different microcontrollers support different functions – the most obvious being the
number of input/output pins available. An 8 pin microcontroller may have just 6
input/output pins, whilst a 68 pin microcontroller may have as many as 50
input/output pins!

Additional features
Some microcontrollers also contain special functions built into the ‘chip’. Some
microcontrollers may have an on-board Analogue Digital Converter, which enables
analogue quantities such as light or temperature to be measured. The PIC12C671
microcontroller, as used on the Inputs Module, is an example of an 8 pin
microcontroller with on-board ADC.

Other microcontrollers may contain other special functions, such as an USART for
serial RS232 communications, a USB port for connection to the USB network from a
personal computer or an LCD driver.




DET: Technological Studies: Systems and Control (Advanced Higher)                     18
Cost
Microcontrollers vary quite considerably in cost, dependant on the functions of the
microcontroller and the quantity purchased. As volume purchasing prices are
generally more economic, many manufacturers select one or two ‘standard’
microcontrollers to use in all their products. Although this microcontroller may, on
occasions, have extra unnecessary capabilities, it may still be generally more
economic for the manufacturer to just stock the one ‘generic’ part.

Memory type
Where the microcontroller may need reprogramming in the field, it may be beneficial
to use a microcontroller with FLASH memory which can be ‘overwritten’ at any time.
However if it is not necessary to reprogram the device, a One Time Programmable
microcontroller will be more economical.

One additional feature of FLASH memory microcontrollers is their additional data
memory capability. This may be used, for instance, in a burglar alarm panel to store
the secret ‘reset’ PIN number.

Selection of common microcontroller parts

Microcontroller       Type       Mem       Pins    Special Features
PIC16F84              FLASH      1k        18      13 i/o pins, 64 byte data memory
PIC16F873             FLASH      4k        28      13 i/o pins, 128 byte data, 5 ADC
PIC12C508             OTP        0.5k      8       6 i/o pins
PIC12C671             OTP        1k        8       6 i/o pins, 4 ADC
PIC16C621             OTP        0.5k      18      13 i/o pins
PIC16C711             OTP        1k        18      13 i/o pins, 4ADC
PIC16C73              OTP        4k        28      22 i/o pins, 5 ADC, USART
PIC16C74              OTP        4k        40      33 i/o pins, 8 ADC, USART
PIC16C924             OTP        4k        64      52 i/o pins, 5 ADC, LCD driver




DET: Technological Studies: Systems and Control (Advanced Higher)                      19
Microcontroller architecture

The main features of the microcontroller are shown in the block diagram.

                               PROGRAM
                  ROM                                   RAM
                               COUNTER
                PROGRAM                                      T
                                                       REGIS ER
                 MEMORY                                  FILES
                                            DATA
                                            BUS


                                 ALU
                    PROGRAM                             I/O         “REAL”
                       BUS                             PORT S       WORLD


                                                       TIMERS
                                CLOCK


                              SIMPLIFIED PIC MICROCONTROLLER
                                       BLOCK DIAGRAM


Microcontrollers contain all these features within a single package, as opposed to the
microprocessor system where each block in the diagram above is normally a separate
integrated circuit. In general the only component that needs to be added to a
microcontroller is a clock resonator, which sets the operating speed of the
microcontroller.

Arithmetic / Logic Unit (ALU) and clock
The processing unit (full name arithmetic and logic unit (ALU)) is the ‘brain’ of the
microcontroller. It operates by reading instructions from the read only memory
ROM (permanent program memory) and then carrying out the mathematical
operations for each instruction. The speed at which these operations occur is
controlled by the clock circuit.

The clock circuit within the microcontroller ‘synchronises’ all the internal blocks
(ALU, ROM, RAM etc.) so that the system remains stable. The clock circuit is built
into the microcontroller, but an external crystal or resonator is required to set the
clock frequency. A typical clock frequency for use with a microcontroller is 4MHz,
but speeds as high as 20MHz can also be achieved. With a clock frequency of 4MHz
the microcontroller completes one million instructions a second!




DET: Technological Studies: Systems and Control (Advanced Higher)                   20
Memory


Program memory
The Program Memory (ROM) contains the operating instructions (i.e. the ‘program’)
for the microcontroller. The ROM is normally ‘programmed’ before the
microcontroller is installed in the target system, and the memory retains the
information even when the power is removed. Many microcontrollers are one-time-
programmable types, which means the ROM can only be programmed once. If you
make a mistake, and have to change the program, the chip has to be thrown away and
a new chip programmed with the revised program. To overcome this problem some
microcontrollers now use FLASH EEPROM memory instead. This type of ‘erasable-
permanent’ memory allows the ROM to be re-programmed many times. The
PIC16F84 used on this course is a FLASH memory device.

File registers (RAM)
The File Registers are temporary memory locations (RAM) used for storing
information whilst the program is running. This memory is ‘volatile’, which means
that as soon as the power is disconnected the contents of the memory is lost.




DET: Technological Studies: Systems and Control (Advanced Higher)                   21
This memory is split into two halves:

1. Special function register (SFR) files (address h’00’ to h’0b’)
   These are specially allocated registers that perform certain tasks. For instance the
   register called ‘PORTB’ controls the output conditionof the PORTB pins, and the
   STATUS register contains information about the operation of the microcontroller.

2. General purpose register files (address h’0C’ to h’4F’)
   These are the 68 general purpose file registers that can be used for temporary
   storage of numbers. It is usual to ‘rename’ each register to make them easier to use
   e.g. TEMP or COUNTER




DET: Technological Studies: Systems and Control (Advanced Higher)                    22
Unfortunately both types of file registers are split between two memory ‘pages’. The
majority of the registers are on the first page, but a few are on the second page.
Therefore it is sometimes necessary to ‘turn over’ to page 1 to read/write a register,
before ‘turning back’ to page 0 again (so that the ‘default’ page is always page 0).
This page selection is carried out by use of the RP0 flag within the STATUS register.
When the flag is clear page 0 is selected, when the flag is set page 1 is selected.

Data memory
This is an area of non-volatile FLASH memory that can be used to store numbers as
the program is running, but which is not lost when power is removed. This makes it
ideal for storing ‘combinations’ for alarm systems, as the user can select their own
PIN number which is then permanently saved in the EEPROM memory. The
PIC16F84 contains 64 bytes of data memory.

Buses
Information is carried between the various blocks of the microcontroller along
‘groups’ of wires called buses. The ‘data bus’ carries the 8-bit data between the ALU
and File Registers, and the ‘program bus’ carries the 13-bit program instructions from
the program memory.

The size of the data bus provides a description for the microcontroller. Therefore an
‘8 bit microcontroller’ has a data bus ‘8-bits’ wide. Microcontrollers with 16-bit and
32-bit data buses are also available.

Input/output circuitry
Microcontrollers communicate with the outside world via pins which are grouped
together in ‘ports’, with up to eight pins in each port. Smaller microcontrollers may
only have one port, whilst larger devices may have five or more. Generally each pin
within the port can be configured as an output or as an input, or can even be
multiplexed to change functions as the program is run! The ports of the PIC16F84 are
labelled PORTA (5 pins) and PORTB (8 pins). These notes will only make use of
PORTB, although it is important to note that all commands carried out on PORTB can
also be carried out on any other port.

The customised CMOS fabrication techniques used to build modern microcontrollers
provides a relatively high current capability (approx. 20mA) for each pin. However
further ‘interfacing’ circuits are required for most output devices.

Timers
Most microcontrollers have one or more ‘timers’ built into the system. The
‘watchdog timer’ is the most common type of timer. This is a special timer that
‘resets’ the microcontroller if it stops processing for any reason (e.g. a ‘bug’ in the
program). This ensures that the microcontroller continues working at all times –
which is essential in some applications, for instance medical monitoring equipment.




DET: Technological Studies: Systems and Control (Advanced Higher)                         23
Basic microcontroller circuit

The basic circuit for a microcontroller is shown below. A 3 pin ceramic resonator is
used to set the clock speed to 4MHz. A 4k7 resistor is used to disable the ‘reset’ pin
(MCLR – master clear). Finally the power rails are connected to pins 5 and 14.




The 18-pin PIC microcontrollers require all of the following connections to operate
correctly:
   Vdd         pin 14      power supply, must be connected to V+ (2 to 6V)
   Vss         pin 5       ground, must be connected to 0V
   OSC1        pin 15      clock, connect to one outer pin of ceramic resonator
   OSC2        pin 16      clock, connect to other outer pin of ceramic resonator
   MCLR        pin 4       master clear (reset), connect to V+ via 4.7 k resistor


Notes:


               The centre pin of the 3 pin ceramic resonator must be connected to
               ground (0V). The ceramic resonator is not polarised and so can be used
               either way around.

If a manual reset switch is required it can be connected between MCLR and ground
(0V).




DET: Technological Studies: Systems and Control (Advanced Higher)                     24
Assignments

1. List the advantages of using a microcontroller within a product design.

2. Describe the input sensors and output transducers that may be linked to a
   microcontroller in the following common household appliances:
a) microwave oven
b) washing machine
c) electronic bicycle speedometer.

3. Explain the following microcontroller terms: ALU, bus, clock.

4.   Explain the differences between the following types of memory:
a)   RAM
b)   ROM
c)   EEPROM.


5. The table below shows the microcontrollers stocked by an electronic
   manufacturing company.

Microcontroller       Type       Mem       Pins    Special Features
PIC16F84              FLASH      1k        18      13 i/o pins, 64 byte data memory
PIC16F873             FLASH      4k        28      13 i/o pins, 128 byte data, 5 ADC
PIC12C508             OTP        0.5k      8       6 i/o pins
PIC12C671             OTP        1k        8       6 i/o pins, 4 ADC
PIC16C621             OTP        0.5k      18      13 i/o pins
PIC16C711             OTP        1k        18      13 i/o pins, 4ADC
PIC16C73              OTP        4k        28      22 i/o pins, 5 ADC, USART
PIC16C74              OTP        4k        40      33 i/o pins, 8 ADC, USART
PIC16C924             OTP        4k        64      52 i/o pins, 5 ADC, LCD driver


For each of the following products, describe the most appropriate microcontroller
from the list above, giving a clear reason for your selection:
a) a four channel datalogger that has a serial RS232 link to a host computer
b) a model signal set for a model railway toy
c) a hand held medical monitor with 30 sensors and an LCD display
d) a security alarm with user programmable PIN reset code
e) a speed controller for a windscreen wiper in a motor vehicle.




DET: Technological Studies: Systems and Control (Advanced Higher)                      25
Section 2 – programming in assembler code

Microcontrollers only understand ‘numbers’, which are interpreted by the
microcontroller as sequences of ‘0’s and ‘1’s (machine code). However it is very hard
for a human programmer to write in machine code, because it is very difficult to
understand the meaning of the numbers. A typical machine code program may look
like this:
1486
0000
1086
0000
2800

Assembler code programs use text abbreviations to represent numbers. This makes it
much easier for the human programmer to understand the program. Therefore the
machine code program above can be written in assembler code as follows:

main:              bsf                 PORTB,1            ;   switch on pin 1
                   nop                                    ;   small delay
                   bcf                 PORTB,1            ;   switch off pin 1
                   nop                                    ;   small delay
                   goto                main               ;   loop back to start



Writing programs in assembler code involves four steps:
 use a text editor to write the assembler code program (saved as .asm and .inc files)
 convert the text file to a machine code number file (saved as .hex file)
 program (‘burn’) the machine code file into the microcontroller
 test the program in the target system.

Each step can involve a separate piece of computer software. First, any text editor is
used to write the assembler code. An assembler software application is then used to
convert the assembler code text into machine code. Finally a programmer and its
control software are used to actually ‘burn’ the program into the microcontroller.




DET: Technological Studies: Systems and Control (Advanced Higher)                    26
Step     Action                                 Software        Filetype   Hardware
1        Write the assembler code               Text Editor     .asm       none
         program                                                .inc
2        Convert the assembler code             MPASM           .hex       none
         program to machine code                assembler
3        Burn the machine code into the         Programmer .hex            Programmer
         microcontroller
4        Test the microcontroller               -               -          Target system
         program
         in the target system

To simplify these processes a single piece of software, called the Programmer Editor,
has been developed. This enables all three software processes to be carried out within
a single piece of software. The Programmer Editor also allows Basic Stamp PBASIC
programs to be automatically converted into assembler code.



The PICmicro programmer module

To program a PICmicro it is necessary to transfer the machine code (hex) file from the
computer into the microcontroller. This process is known as ‘burning’ the
microcontroller and can be carried out in two ways:
1. Programmer module
   The microcontroller is placed in a programmer module (usually using a Zero Insert
   Force (ZIF) socket to secure the device). The programmer then burns the
   microcontroller with a program transferred from the computer. This is the method
   generally used for ‘prototyping’ work, and is the method used within this course.
2. In-circuit programming
   With this method the microcontroller is soldered into the target system when it is
   still ‘blank’. A programming lead is then connected to the target system and the
   microcontroller is burnt remotely through the target system. This method is useful
   for equipment that rapidly develops, and may require a firmware change over the
   life of the manufacturing process. An example of this type of product could be a
   computer modem, which may need updating to faster speeds over the life of the
   product.




DET: Technological Studies: Systems and Control (Advanced Higher)                       27
Computer requirements:
 PC running Windows 95, 98, NT or 2000
 available 9 pin serial port
 programmer editor software (may be downloaded from www.rev-ed.co.uk).


Hardware requirements:
 PICmicro programmer module
 PIC16F84 microcontroller
 stamp controller module
 18 pin ZIF socket
 serial cable
 9V DC supply
 output driver module and output transducers
 inputs module and input transducers.

Modifications to stamp controller module
The Stamp Controller module is supplied fitted with a PBASIC interpreter
microcontroller fitted in a standard socket. For this course it is necessary to carefully
remove the PBASIC interpreter microcontroller and replace it with an 18 pin ZIF
socket. It is recommended that the low profile socket is removed and permanently
replaced with a ZIF socket. However, the ZIF socket may also be carefully inserted
into the low profile socket. Note that the insertion of the ZIF socket should be
regarded as a permanent installation as it distorts the low profile socket when inserted.

General information
The Stamp Controller does not connect to the computer at any point – it is purely used
as a modular board for testing programs. Therefore the serial cable can be left
permanently connected to the PICmicro Programmer module. The serial cable
supplied with the Stamp Controller may be used for the PICmicro Programmer.

The 9V power supply is required for both the Stamp Controller and the PICmicro
Programmer. Although two separate supplies may be used, it is common practice to
use one supply, moving the connector between the two modules as required.

The PIC16F84 IC may also be fitted inside an 18 pin turned pin IC socket. This helps
prevent accidental ‘bending’ of the legs of the microcontroller as it is moved from
board to board.




DET: Technological Studies: Systems and Control (Advanced Higher)                     28
Structure of an assembler code program

The format of a complete assembler code program is very strictly defined. It must
contain certain elements for the assembler software to be able to convert the
assembler code into machine code correctly. The program on the following page
shows the main elements of an assembler code program.

1. Setup PICmicro type
   This section defines the type of PICmicro that is being used. It also includes a
   standard ‘header’ include file (p16F84.inc) which includes information about the
   type of microcontroller being used. This file, for instance, tells the assembler the
   value of common labels such as PORTB and TRISB.

   Include files (.inc) are very commonly used when programming microcontrollers.
   They can be used to contain ‘standard’ definitions and sub-procedures which are
   then easily copied between different projects.

2. Setup PICmicro configuration
   This section defines the configuration ‘fuse’ settings of the PICmicro. These
   setting select the type of clock resonator used for the microcontroller, disable the
   watchdog timer etc. These settings are beyond the scope of this course, but must
   still always be included as shown.

3. File registers
   This section defines the temporary registers used within the program. It allows
   the registers to be assigned easy to remember labels, such as TEMP.

4. Reset vectors
   When the PICmicro is first powered, it jumps to address 0, which is known as the
   reset vector. Therefore this address should contain a ‘goto’ command to direct the
   program to the initialisation routine.

    If a PICmicro interrupt occurs, the program jumps to address 4, which is known as
    the interrupt vector. Use of interrupts is beyond the scope of this course, but a
    ‘return’ command must always be placed at this address.

5. Common sub-procedures
   It is very common to reuse some assembler code sub-procedures in many
   programs. For instance, you may wish to reuse a standard procedure called ‘wait’
   to create a time delay. If this procedure is saved as separate include (.inc) files it
   can be ‘linked’ to each program as shown.

6. Assembler code program
   This is where the actual initialisation and main routines are added.

7. End
   The ‘end’ keyword is required at the end of each program.




DET: Technological Studies: Systems and Control (Advanced Higher)                      29
; ************************************
; ***** (1) Setup PICmicro type. *****
; ************************************

         list             p=16F84             ; define PICmicro type
         #include         <p16F84.inc>        ; variable definitions

; **************************************
; ***** (2) Setup PICmicro config. *****
; **************************************

__CONFIG       _CP_OFF & _WDT_OFF & _PWRTE_ON & _XT_OSC

; **********************************
; ***** (3) RAM File Registers *****
; **********************************

CBLOCK h’20’
TEMP                    ; Temporary Scratchpad
COUNTER                 ; Counter for loops
          ENDC

; ********************************************
; ***** (4) Assembler code reset vectors *****
; ********************************************

; ***** Reset vector *****
        org      d’00’
        goto     Init    ; jump to init

; ***** Interrupt vector *****
        org      d’04’
        return           ; Return

; *************************************
; ***** (5) Common sub-procedures *****
; *************************************

           #include <wait.inc>           ; wait sub procedure

; ***************************************
; ***** (6) Start of assembler code *****
; ***************************************

; ***** Initialisation *****
init:       ;(initialisation goes here)

; ***** Main program *****
main:       ;(main program goes here)

; ******************************
; ***** (7) End of Program *****
; ******************************

end




DET: Technological Studies: Systems and Control (Advanced Higher)      30
Standard format for assembler code programs

As all assembler code programs for the PIC16F84 follow the same format, it is
common practice to use a template file when creating a new program. This enables
the programmer to rapidly create an assembler code program that contains all the
correct elements.

When using the Programmer Editor software, a new template can be created by
clicking the File>New Template menu option. This creates a new program with the
majority of the template already in place.

The rest of this course will only list the init and main routines that are to be added
within this template (in section 6). However it is important to remember that these
routines are just part of the overall program, and must be added into the template file
for the whole program to assemble correctly. Remember these sections must be
inserted before the keyword ‘end’ at the end of the program.

On occasions it will also be necessary to define further registers in section (3).
When using sub-procedures they should always be placed in section (5).




DET: Technological Studies: Systems and Control (Advanced Higher)                    31
Writing code

It is important to be very accurate whilst writing assembler code programs. In most
cases just being one number or letter out can cause a ‘bug’ in the program. In
industrial applications this can be very expensive – it has been known for one single
missing comma to cause a space rocket to explode!

The following program is written in PBASIC, a microcontroller orientated BASIC
language. The program switches an output pin on and off every 5 seconds.

main:         high 1                       ‘   switch on pin1
              pause 5000                   ‘   pause for 5 s
              low 1                        ‘   switch off pin1
              pause 5000                   ‘   pause for 5 s
              goto main                    ‘   loop back to start

The program can be broken down into 3 columns. The left-hand column only
contains labels. The centre column contains instructions and values, and the third
column contains comments. The <tab> key on the keyboard is used to align the
columns when the program is keyed in.

The following program is an identical program written in assembler code. Although
very similar, the assembler code program requires a much stricter structure than
PBASIC. Study just the structure of the program at this point – all the individual
instructions will be explained later.

main:       bsf                    PORTB,1        ;   switch on pin1
            movlw                  d’50’          ;   move the number 50 to W
            call                   wait           ;   call wait sub-procedure
            bcf                    PORTB,1        ;   switch off pin1
            movlw                  d’50’          ;   move the number 50 to W
            call                   wait           ;   call wait sub-procedure
            goto                   main           ;   loop back to start

The first column is again used for labels. The second column is used for the program
instructions (sometimes called mnemonics). There are over 30 different instructions
that can be used with the PIC16F84, although some of them are beyond the scope of
this course. Each program instruction is a word or abbreviation – e.g. bsf is an
abbreviation of bit set file, whilst call or goto are complete words.

The third column is used for information that is required by the program instruction.
This can be a label, number, two labels/numbers (separated by a comma) or nothing at
all.

The last column is used for adding comments. A comment starts after a semi-colon
(;) and continues to the end of the line. Although the comments are not needed to
make the program work, they are an essential part of the program as they explain in
‘plain language’ what the program is doing. You should always add a comment to
every line of your program, particularly if the program is to be studied by someone
else at a later date.

DET: Technological Studies: Systems and Control (Advanced Higher)                     32
Important microcontroller terms

Register file
Register files are temporary memory locations used to store values. Each file is a byte
long, which means it can contain a value between 0 and 255. These files ‘overflow’ if
these values are exceeded, so the sum 254 + 3 will give the answer value of 1.
(254+ 1 = 255, 255 + 1 = 0, 0 + 1 = 1)

W
W is the working register (sometimes also known as the accumulator). In most cases,
you can only perform calculations on W, so, if for instance you wanted to add 5 to a
register file, you would have to move the file to W, add 5 to W and then move the
new value in W back to the file.

Writing numbers
Programmers often use three different counting systems when programming –
decimal, binary, and hex (hexadecimal). In most cases these notes will use decimal
values, but on occasions, such as when setting the Data Direction Register, a binary
number will be used for clarity.

Each number will be preceded by the letter d, b or h to show which type of numbering
system has been used. This notation is consistent with the MPASM assembler.

d’16’                           decimal number 16                   (=16 in decimal)
b’00010000’                     binary number 00010000              (=16 in decimal)
h’10’                           hexadecimal number 10               (=16 in decimal)

On occasions it can also be useful to use the ASCII code for a printed character (e.g.
when using the serial LCD module). In this situation the prefix a is used.


a’Z’          ASCII value for the character ‘Z’




DET: Technological Studies: Systems and Control (Advanced Higher)                      33
Program instructions

Listed below are the common program instructions used within this course. It is often
easier to understand these instructions if you learn what the ‘abbreviations’ stand for.
bsf       bit set file                       set a single bit to logic level ‘1’
bcf       bit clear file                     clear a single bit to logic level ‘0’
btfsc     bit test file, skip if clear       skip next command if a single bit is clear ‘0’
btfss     bit test file, skip if set         skip next command if a single bit is set ‘1’

clrf      clear file                         clear a file to value 0
clrw      clear W                            clear W to value 0
movlw     move literal to W                  move a byte value into W
movwf     move W to file                     move the value in W into a file
movfw     move file to W **                  move the value in a file into W

addlw     add literal to W                   add byte value to W value
addwf     add W and file                     add W value to the file value
sublw     subtract W from literal            subtract W from literal
subwf     subtract W from file               subtract W from file value

iorlw     IOR literal and W                  inclusive or (logic OR) literal and W value
iorwf     IOR W and file                     inclusive or (logic OR) W and file value
xorlw     XOR literal and W                  exclusive or (logic XOR) literal and W
xorwf     XOR W and file                     exclusive or (logic XOR) W and file value
andlw     AND literal with W                 and (logic AND) literal and W value
andwf     AND W and file                     and (logic AND) W and file value
comf      complement file                    complement (logic NOT) the value in the file

rlf       rotate left file                   rotate file bitwise to left via carry
rrf       rotate right file                  rotate file bitwise to right via carry
incf      increment file                     increment (add 1) to value of file
decf      decrement file                     decrement (take 1) from value of file

incfsz    increment file, skip if zero       increment file, skip next command if equal 0
decfsz    decrement file, skip if zero       decrement file, skip next command if equal 0

goto      go to address                      jump to new address

call      call sub procedure                 call a sub-procedure
return    return from sub procedure          return from sub-procedure

nop       no operation                       create a short time delay
sleep     sleep                              enter low power sleep mode

** Note: The movfw command is officially recognised as the movf command,
although in practice most commercial programmers use the movfw pseudo-command
supported by the MPASM assembler. For the purpose of this course the movfw
command is used for clarity.

DET: Technological Studies: Systems and Control (Advanced Higher)                        34
Assignments

1. Describe the function of the following software tools in reference to assembler
   code programming:
a) text editor
b) assembler
c) programmer driver.

2.   Explain the following microcontroller terms:
a)   W
b)   registers
c)   SFR (special function registers)
d)   watchdog timer
e)   reset vector
f)   program instructions.




DET: Technological Studies: Systems and Control (Advanced Higher)                    35
Assignment 3


Activity

Step by step guide to programming and testing a microcontroller
1. Start up the Programmer Editor Software.
2. Select File>New Template File>P16F84.
3. Key in the following program within the template.

init:      bsf        STATUS,RP0               ;   move   to memory page 1
           movlw      B’00001111’              ;   make   4-7 outputs, rest inputs
           movwf      TRISB                    ;   move   W to TRISB
           bcf        STATUS,RP0               ;   move   back to page 0

main:      bsf        PORTB,7                 ;    switch on pin7
           movlw      d’50’                   ;    move the number 50 to W
           call       wait                    ;    call wait sub-procedure
           bcf        PORTB,7                 ;    switch off pin7
           movlw      d’50’                   ;    move the number 50 to W
           call       wait                    ;    call wait sub-procedure
           goto       main                    ;    loop back to start

4.   Click PICmicro>Assemble to generate a machine code file.
5.   Connect the programmer unit and ensure that a PIC16F84 is correctly inserted.
6.   Click PICmicro>Program to burn the program into the microcontroller.
7.   Remove the microcontroller from the programmer and insert into the Controller.
8.   Connect power to the Controller.

If programming has been carried out correctly, the LED on pin 7 of the Controller will
flash on and off.


Bug alert!
 The assembler software is CASE-SENSITIVE for labels and register names.
  Therefore you should always use lowercase for labels and UPPERCASE for
  register names (PORTB etc.). It is recommended that you also use lower case for
  instructions.
 Labels and register names cannot start with a digit.




DET: Technological Studies: Systems and Control (Advanced Higher)                    36
Assignment 4


Activity

Converting a PBASIC program to assembler code
For users familiar with the PBASIC language used with the Stamp Controller system,
it is also possible to automatically convert PBASIC programs into assembler code
using the Programmer Editor software. This method assists students to learn
assembler code by ‘disassembly’ of PBASIC programs.


Step by step guide:
1. Start up the Programmer Editor Software.
2. Select File>New File.
3. Key in the following program:

main:      high 7                        ‘   switch on pin7
           pause 500                     ‘   pause for 0.5 second
           low 7                         ‘   switch off pin7
           pause 500                     ‘   pause for 0.5 second
           goto main                     ‘   loop back to start

4. Click PICmicro>Convert PBASIC to Assembler to automatically generate an
   assembler code file.
5. Click PICmicro>Assemble to generate a machine code file.
6. Connect the programmer unit and ensure that a PIC16F84 is correctly inserted.
7. Click PICmicro>Program to burn the program into the microcontroller.
8. Remove the microcontroller from the programmer and insert into the Controller.
9. Connect power to the Controller.

If programming has been carried out correctly, the LED on pin 7 of the Controller will
flash on and off.

Note that this activity requires the optional Basic>Assembly plug-in module to be
installed within the Programming Editor.




DET: Technological Studies: Systems and Control (Advanced Higher)                  37
Input / output pins

The whole purpose of using a microcontroller is to control external devices, and so
these external devices must be connected to the microcontroller pins via suitable
interfacing circuits. In the case of the PIC16F84, there are 13 pins that can be used as
inputs or outputs (or both, as it is possible to change the a pin from output to input, or
vice versa, as the program is running.)
The input/output pins on the PIC16F84 are arranged in two ports. PORTA has five
pins, labelled 0 to 4. PORTB has eight pins, labelled RB0 to RB7. A pin is described
by its port followed by it’s number, so pin 3 on PORTB is known as PORTB,3. In
this course PORTA will be ignored, so that only PORTB is used.

Tell the PIC to use a pin as an output or as an input
When power is first applied to the PIC16F84, all the pins are configured as inputs.
Therefore to use a pin as an output it is necessary to alter the Data Direction Register
(also known as tristate register) (labelled as TRISB). A ‘1’ in the TRIS register
makes the pin an input, a ‘0’ in the TRIS register makes the pin an output.


input/output pin                7        6        5       4         3   2      1       0
bit of TRISB                    7        6        5       4         3   2      1       0
decimal value                  128      64       32      16         8   4      2       1

The TRIS registers are on memory page 1, so before they can be altered the memory
page bit must be set. Therefore to make pins 4 to 7 as outputs:
init:     bsf        STATUS,RP0              ;   move   to memory page 1
          movlw      b’00001111’             ;   make   4-7 outputs, rest inputs
          movwf      TRISB                   ;   move   W to TRISB
          bcf        STATUS,RP0              ;   move   back to page 0


Bug alert!
 If you are familiar with PBASIC you will note that the input/output allocation is
   reversed in assembler code. In assembler code a ‘0’ means an output, whilst in
   PBASIC a ‘0’ means an input.
 When the microcontroller is first powered, all pins are configured as inputs. To
   use a pin as an output you must setup the DDR at the start of the program.




DET: Technological Studies: Systems and Control (Advanced Higher)                       38
Switching output pins on and off

To switch a pin on, use the bsf (bit-set-file) command.
bsf         PORTB,3                     ; switch pin3 of PORTB on

To switch a pin off, use the bcf (bit-clear-file) command.
bcf         PORTB,3                     ; switch pin3 of PORTB off


It is also possible to switch all pins simultaneously by moving a number to the port.
For instance, to switch all the PORTB pins on (255) and then off (0) use the following
commands.
movlw     d’255’      ;   move the number 255 to W
movwf     PORTB       ;   move the number in W to portB
clrw                  ;   clear W (ie move the number 0 to W)
movwf     PORTB       ;   move the number in W to portB

In can also be useful to use the binary notation when switching pins on and off, to
make understanding of the condition of each pin easier.


movlw     b’10010000’                      ;   switch pin 7 and 4 on
movwf     PORTB                            ;   move the number in W to portB
movlw     b’00010000’                      ;   switch pin 7 off
movwf     PORTB                            ;   move the number in W to portB




DET: Technological Studies: Systems and Control (Advanced Higher)                     39
Creating time delays

Microcontrollers operate at very high speeds (a PIC16F84 with a 4MHz resonator
completes one million instructions per second). Therefore to create time delays it is
necessary to create a ‘loop’ sub-procedure to cause a delay of a set time period.

This course will make use of a common sub-procedure called wait, which creates a
time delay in multiples of 0.1s. The length of the delay is determined by the value in
W (1 to 255), when the wait sub-procedure is called. In the following example two
time delays, one of 1 second and one of 5 seconds, are created.




DET: Technological Studies: Systems and Control (Advanced Higher)                       40
Assignment 5


Activity

Key in the following program. Burn a PIC and then test the program
init:      bsf        STATUS,RP0             ;   move   to memory page 1
           movlw      b’00001111’            ;   make   4-7 outputs, rest inputs
           movwf      TRISB                  ;   move   W to TRISB
           bcf        STATUS,RP0             ;   move   back to page 0

main:      movlw      d’255’                 ;   move the number 255 to W
           movwf      PORTB                  ;   move the number in W to portB
           movlw      d’10’                  ;   1 second delay
           call       wait                   ;   do delay
           clrw                              ;   clear W (ie move the number 0 to W)
           movwf      PORTB                  ;   move the number in W to portB
           movlw      d’50’                  ;   5 second delay
           call       wait                   ;   do delay
           goto       main                   ;   loop back to start

To create longer delays it is necessary to put multiple wait calls together (remember
that the largest number that the microcontroller can process is 255, which is equal to
25.5 seconds). Therefore a 60 second delay can be created by placing three 20 second
delays after each other.
           movlw      d’200’                 ;   20   second delay
           call       wait                   ;   do   delay
           movlw      d’200’                 ;   20   second delay
           call       wait                   ;   do   delay
           movlw      d’200’                 ;   20   second delay
           call       wait                   ;   do   delay

On occasions this course will also use a second sub-procedure called pause. This is
identical in operation to wait, but creates a shorter length delay in milliseconds (1 ms
to 255 ms).


Bug alert!
 Do not forget to reset the value of W between each call to ‘wait’, as W is used
   during the sub-procedure and will not still be the same value after the sub!
 The largest number the microcontroller can use is 255 because it uses ‘byte’
   mathematics.




DET: Technological Studies: Systems and Control (Advanced Higher)                     41
Assignment 6



                                             T
                                            S ART



                                          WIT
                                         S CH PIN 7
                                            HIGH



                                       WAIT2 SECONDS



                                          WIT
                                         S CH PIN 6
                                            HIGH



                                       WAIT1 SECOND



                                        WIT
                                       S CH PINS 4& 5
                                            HIGH



                                       WAIT3 SECONDS



                                           WIT
                                          S CH ALL
                                             OFF


                                              T
                                             S OP




Develop an assembler code program that will carry out the instructions shown in the
flowchart above.




DET: Technological Studies: Systems and Control (Advanced Higher)                 42
Assignment 7



                                         T
                                        S ART



                                     WIT
                                    S CH PIN 7
                                       HIGH



                                   WAIT2 SECONDS



                                     WIT
                                    S CH PIN 6
                                       HIGH



                                   WAIT1 SECOND



                                    WIT
                                   S CH PINS 4& 5
                                        HIGH



                                  WAIT3 SECONDS



                                      WIT
                                     S CH ALL
                                        OFF


                                   WAIT1 SECOND




Develop an assembler code program that will carry out the instructions shown in the
flowchart above.




DET: Technological Studies: Systems and Control (Advanced Higher)                 43
Assignment

8. Describe the principle sections of an assembler code program. Clearly explain the
   purpose of each section.

9. A set of temporary traffic lights is required for a system of road works.

                            red                       10 sec
                            red and amber             2 sec
                            green                     10 sec
                            amber                     2 sec

Draw a flowchart for the lights sequence shown by one set of the traffic lights. Use
the times shown in the table for each stage.

Write an assembler code program to achieve this operation. Use the following pin
configuration – red (7), amber (6) and green (5).




DET: Technological Studies: Systems and Control (Advanced Higher)                      44
Testing input pins

When connecting input devices to the microcontroller it is often necessary to ‘jump’
to a separate part of code depending on whether the input pin is high or low.

The following code jumps to ‘nextbit’ if input 3 on PORTB is on. It uses the btfsc
(bit-test-file-skip-clear) command.
          btfsc      PORTB,0              ; test input 0
          goto       nextbit              ; do this because 0 is on
                                          ; skipped to here because 0 is off

This code jumps to ‘nextbit’ if input 3 on PORTB is off. It uses the btfss (bit-test-file-
skip-set) command.


          btfss      PORTB,0               ; test input 0
          goto       nextbit               ; do this because 0 is off
                                           ; skipped to here because 0 is on




Assignment 10

a) Key in the following program. Burn a PIC and then test the program.

init:     bsf        STATUS,RP0              ;    move   to memory page 1
          movlw      b’00001111’             ;    make   4-7 outputs, rest inputs
          movwf      TRISB                   ;    move   W to TRISB
          bcf        STATUS,RP0              ;    move   back to page 0

main:     btfss       PORTB,0                 ; test input 0
          goto        main                    ; input is off so loop

          bsf         PORTB,7                 ;   switch on output 7
          movlw       d’20’                   ;   2 second delay
          call        wait                    ;   wait
          bcf         PORTB,7                 ;   switch off output 7
          goto        main                    ;   loop back to start



b) Key in the following program. Burn a PIC and then test the program.
init:     bsf        STATUS,RP0              ;    move   to memory page 1
          movlw      b’00001111’             ;    make   4-7 outputs, rest inputs
          movwf      TRISB                   ;    move   W to TRISB
          bcf        STATUS,RP0              ;    move   back to page 0

main:     btfsc       PORTB,0                 ;   test input 0
          bsf         PORTB,7                 ;   input on so switch on 7
          btfss       PORTB,0                 ;   test input 0
          bcf         PORTB,7                 ;   input off so switch off 7
          goto        main                    ;   loop back to start




DET: Technological Studies: Systems and Control (Advanced Higher)                      45
Assignment 11
                                              T
                                             S ART



                                         GREEN LED ON




                                             SWITCH
                                            PUSHED?
                                                                NO


                                                  YES

                                         GREEN LED OFF
                                         AMBER LED ON



                                           WAIT 3 sec.



                                         AMBER LED OFF
                                          RED LED ON



                                           WAIT 4 sec.



                                         AMBER LED ON



                                           WAIT 2 sec..


                                       RED/AMBER LED OFF
                                         GREEN LED ON




DET: Technological Studies: Systems and Control (Advanced Higher)    46
Develop an assembler code program that will carry out the instructions shown in the
flowchart above. Use the following pin configuration.


Input Connection              Pin          Output Connection
                               7               Red Light
                               6              Amber Light
                               5              Green Light
                               4
                               3
                               2
                               1
   Start Switch                0




DET: Technological Studies: Systems and Control (Advanced Higher)                 47
Loops

To repeat a section of code a number of times it is necessary to use a file register as a
counter. This counter is preloaded with a value (e.g. 15 for 15 loops) and then
decremented by one on every loop. When the value reaches zero all the loops have
been completed and so the program continues.


Assignment 12


Activity

Key in the following program. Burn a PIC and then test the program.

This program flashes the outputs on and off 15 times.

init:      bsf         STATUS,RP0            ;   move   to memory page 1
           movlw       b’00000000’           ;   make   all outputs
           movwf       TRISB                 ;   move   W to TRISB
           bcf         STATUS,RP0            ;   move   back to page 0]

main:      movlw       d’15’                 ; move the number 15 to W
           movwf       COUNTER               ; store in register

loop:      movlw       d’255’          ;   move the number 255 to W
           movwf       PORTB           ;   move the number in W to portB
           movlw       d’10’           ;   1 second delay
           call        wait            ;   do delay
           clrw                        ;   clear W (ie move the number 0 to W)
           movwf       PORTB           ;   move the number in W to portB
           movlw       d’10’           ;   1 second delay
           call        wait            ;   do delay

           decfsz      COUNTER,F       ; decrement counter and test for zero
           goto        loop            ; not yet zero so loop again
           sleep                       ; now zero so sleep


Bug alert!
 Remember the largest number you can use in a byte register is 255. The number
   300 would be actually carried out as 44 (300-256).
 If you set the counter value to 0 at the start, the loop will actually be carried out
   256 times!




DET: Technological Studies: Systems and Control (Advanced Higher)                         48
Assignment 13
                                         T
                                        S ART


                                    ET
                                   S COUNTER= 5



                                     WIT
                                    S CH PIN 7
                                       HIGH



                                   WAIT1 SECOND


                                     WIT
                                    S CH PIN 7
                                        LOW



                                   WAIT1 SECOND




                                       HAVE WE             N
                                      LOOPED 5
                                        TIMES?


                                             Y

                                          T
                                         S OP




Develop an assembler code program that will carry out the instructions shown in the
flowchart above.




DET: Technological Studies: Systems and Control (Advanced Higher)                 49
Assignement 14


As part of a Christmas decoration, a lighting sequence is to be controlled by a
microcontroller. The output connections are shown below.


Input Connection              Pin          Output Connection
                               7
                               6               Yellow Light
                               5               Purple Light
                               4
                               3                Blue Light
                               2                Green Light
                               1
                               0                 Red Light


The red and green lights should come on together and stay on for 5 seconds. Then
they both go off and the yellow and blue lights should come on together for 8 seconds.
They then go off and the purple light flashes on and off 6 times (the ‘on’ and ‘off’
times being 0.5 seconds each). The sequence then repeats itself.
Draw a flowchart and write an assembler code program for this sequence.




DET: Technological Studies: Systems and Control (Advanced Higher)                  50
Assignment 15



                                         T
                                        S ART


                                       WIT
                                      S CH ALL
                                      PINS HIGH


                                   WAIT5 SECONDS




                                       WIT
                                      S CH ALL
                                       PINS LOW



                                   WAIT0.5 SECONDS



                                       WIT
                                      S CH ALL
                                      PINS HIGH



                                  WAIT0.5 SECONDS




                                    HAS T BEEN
                                         HIS                N
                                   DONE 10 T IMES?



                                              Y

                                       WIT
                                      S CH ALL
                                       PINS LOW



                                          T
                                         S OP




Develop an assembler code program that will carry out the instructions shown in the
flowchart above.




DET: Technological Studies: Systems and Control (Advanced Higher)                 51
Sub-procedures

It is often useful to be able to re-use sections of code within a program. A sub-
procedure is a small section of code that can be ‘called’ from a different part of the
program. After the sub-procedure is finished program flow moves back to the
original section of the program.

To ‘call’ a sub-procedure the call command is used. The last line of the sub-
procedure must be return, which means ‘return to the next line in the calling
procedure’.
main:    movlw      d’10’    ; move the number 10 to W
         call       wait     ; do delay


During this course you have already been using the wait sub-procedure whenever you
created a time delay. The wait sub-procedure listed below contains 3 nested loops to
create a time delay. Therefore a 20s delay is actually calculated 20 000 000 s (micro
seconds) (200 x 100 x 100 x 10). This is necessary because the largest number the
microcontroller can ever use is 255.
wait:     movwf        WC3            ; move value in W to counter 3

wait3:      movlw       d’100’        ; move 100 into WC2
            movwf       WC2           ; 100 x 1ms = 100ms loop

wait2:      movlw      d’100’         ; move 100 into WC1
            movwf      WC1            ; 100 x 10us = 1ms loop

wait1:      nop                       ;   this is a 10us delay loop
            nop                       ;   no operation
            nop                       ;   no operation
            nop                       ;   no operation
            nop                       ;   no operation
            nop                       ;   no operation
            clrwdt                    ;   clear watchdog (in case set)
            decfsz      WC1,F         ;   skip if zero
            goto        wait1         ;   inner loop 1 (10us)

            decfsz      WC2,F         ; skip if zero
            goto        wait2         ; middle loop 2 (1ms)

            decfsz       WC3,F        ; skip if zero
            goto         wait3        ; outer loop 3 (100ms)

            return       ; return to main procedure

Sub-procedures can be placed at any point in the microcontrollers memory. However
it is common practice to group them all together before the initialisation (init) section.
This ensures it is not possible to accidentally ‘drop’ into a sub-procedure by mistake.

Bug alert!
 You can only ‘nest’ sub-procedures (use one sub-procedure with another) up to 8
times (for the PIC16F84 microcontroller). This is because the microcontroller stores
the return address in a area of memory called the ‘stack’, which is only 8 levels deep.
If the stack overflows the microcontroller will get ‘lost’!


DET: Technological Studies: Systems and Control (Advanced Higher)                        52
Assignment 16


Activity

The following flowchart uses a sub-procedure called ‘flash’ to repeatedly flash output
pin number 7. The number of flashes is transferred to the sub-procedure in a register,
which has been defined as B1.


                                                      FLASH
                    T
                   S ART


                   B1 = 5                             HIGH 7


                   FLASH                            WAIT 0.1s



                   B1 = 20                            LOW 7



                   FLASH                            WAIT 0.1s



                  B1 = 10
                                                     HAS THIS
                                                    BEEN DONE
                                                     B1 TIMES?       NO
                   FLASH


                                                           YES
                     T
                    S OP
                                                     RETURN




DET: Technological Studies: Systems and Control (Advanced Higher)                   53
Key in the following program. Burn a PIC and then test the program.

flash:    movfw        B1                  ; move the number in B1 to W
          movwf        COUNTER             ; store in register

loop:     bsf          PORTB,7             ;   pin 7 on
          movlw        d’1’                ;   1 second delay
          call         wait                ;   do delay
          bcf          PORTB,7             ;   pin 7 off
          movlw        d’1’                ;   1 second delay
          call         wait                ;   do delay
          decfsz       COUNTER,F           ;   test counter
          goto         loop                ;   not all done yet so loop
          return                           ;   all done so return

init:     bsf          STATUS,RP0          ;   move   to memory page 1
          movlw        b’00001111’         ;   make   4-7 outputs, rest inputs
          movwf        TRISB               ;   move   W to TRISB
          bcf          STATUS,RP0          ;   move   back to page 0]

main:     movlw        d’5’                ;   move the number      5 to W
          movwf        B1                  ;   move the number      in W to B1
          call         flash               ;   do flashes
          movlw        d’10’               ;   1 second delay
          call         wait                ;   do wait
          movlw        d’20’               ;   move the number      20 to W
          movwf        B1                  ;   move the number      in W to B1
          call         flash               ;   do flashes
          movlw        d’10’               ;   1 second delay
          call         wait                ;   do wait
          movlw        d’10’               ;   move the number      10 to W
          movwf        B1                  ;   move the number      in W to B1
          call         flash               ;   do flashes
          sleep                            ;   end program

Bug alert!
 Do not forget to check that your program has registers called B1 and COUNTER
   defined at the start of your program!




DET: Technological Studies: Systems and Control (Advanced Higher)                54
Assignment 17


As part of a shop display, a lighting sequence is to be controlled by a microcontroller.
The output connections are shown below.

Input Connection              Pin          Output Connection
                               7               Red Light
                               6             Yellow Light
                               5              Green Light
                               4             Orange Light
                               3
                               2
      switch 2                 1
      switch 1                 0

If switch 1 is pressed, each light should flash on and off 5 times in sequence i.e.
orange then green then yellow then red (each ‘on’ and ‘off’ time should be 0.5
seconds). The system then resets for the next switch push.

If switch 2 is pressed all lights should flash simultaneously 3 times. There should
then be a 2 seconds pause, before all lights should flash simultaneously 6 times (each
‘on’ and ‘off’ time should be 0.5 seconds). The system then resets for the next switch
push.

Draw a flowchart and write an assembler code program for this sequence (use a sub-
procedure for the flash routines).




DET: Technological Studies: Systems and Control (Advanced Higher)                     55
Section 3 –- interfacing to the microcontroller

The microcontroller pins can source (‘give out’) or sink (‘take in’) up to 20mA when
configured as outputs.




To connect high current output devices (motor, bulb, buzzer etc) to the
microcontroller a conventional transistor or FET circuit may be used.
When configured as inputs, the microcontroller pins have very high impedance. This
allows switches and simple sensors to be connected in basic potential divider circuits.




DET: Technological Studies: Systems and Control (Advanced Higher)                    56
Assignments

1 Draw appropriate interfacing circuit diagrams for the following transducers.
  Clearly explain your choice of circuit in each case.
a)   LED
b)   Buzzer
c)   6V DC motor
d)   12V DC solenoid
e)   24V pneumatic solenoid valve
f)   Thermistor
g)   Reed switch.




DET: Technological Studies: Systems and Control (Advanced Higher)                57
Interfacing stepper motors




Stepper motors are very accurate motors that are commonly used in computer disk
drives, printers, XY plotters and clocks. Unlike dc motors, which spin round freely
when power is applied, stepper motors require that their power supply be continuously
pulsed in specific patterns. For each pulse, the stepper motor moves around one
‘step’, typically 7.5 degrees (giving 48 steps in a full revolution).

The stepper motor contains magnets which are fixed to the central armature. Four
electronic coils are located around the casing. When a current is passed through these
coils they generate a magnetic field, which attract/repels the permanent magnets on
the armature, and so the armature spins one ‘step’ until the magnetic fields align. The
coils are then energised in a different pattern to create a different magnetic field, and
the armature spins another step.
                                                                    + 12V


               7                1                   18
               6                2                   17
               5                3                   16
                                         ULN2803A




               4                4                   15
                                5                   14       T
                                                            S EPPER

                                6                   13
                                7                   12
                                8                   11
                                9                   10

                   0V                                                       0V



To make the armature rotate continuously the four coils must be switched on and off
in a certain order. Many microcontroller systems use four output lines to control the
stepper motor, each output line controlling the power to one of the coils.




DET: Technological Studies: Systems and Control (Advanced Higher)                      58
As the stepper motor operates at 12V, a transistor switching circuit is used to switch
each coil. As the coils create a back EMF when switched off, a suppression diode on
each coil is also required. The ULN2003 Darlington driver integrated circuit provides
a convenient device housing these transistors and coils.

The table below show the four different steps required to make the motor turn.

     Step               Coil 4              Coil 3             Coil 2       Coil 1
      1                   1                   0                  1            0
      2                   1                   0                  0            1
      3                   0                   1                  0            1
      4                   0                   1                  1            0
      1                   1                   0                  1            0

Note:
The wiring configuration of stepper motors varies from different manufacturers.
Therefore, it may be necessary to rearrange the coil connections for the above
sequence to operate correctly. An incorrect coil arrangement will result in the stepper
motor oscillating back and forth rather than rotating.




DET: Technological Studies: Systems and Control (Advanced Higher)                    59
Assignment 2


Activity

                                             12V DC
                                             SUPPLY



                   STAMP                   OUTPUT                   STEPPER
                 CONTROLLER                DRIVER                    MOTOR




Build the circuit as shown.
Key in the following program. Burn a PIC and then test the program.
The program demonstrates how to continuously spin the stepper motor. Try changing
the speed by altering the value of the wait delay.
init:      bsf       STATUS,RP0              ;    move   to memory page 1
           movlw     b’00001111’             ;    make   4-7 outputs, rest inputs
           movwf     TRISB                   ;    move   W to TRISB
           bcf       STATUS,RP0              ;    move   back to page 0

main:      movlw     b’10100000’              ;   set output pins
           movwf     PORTB                    ;   move to PORTB
           movlw     d’1’                     ;   move the number 1 to W
           call      wait                     ;   call wait sub-procedure
           movlw     b’10010000’              ;   set output pins
           movwf     PORTB                    ;   move to PORTB
           movlw     d’1’                     ;   move the number 1 to W
           call      wait                     ;   call wait sub-procedure
           movlw     b’01010000’              ;   set output pins
           movwf     PORTB                    ;   move to PORTB
           movlw     d’1’                     ;   move the number 1 to W
           call      wait                     ;   call wait sub-procedure
           movlw     b’01100000’              ;   set output pins
           movwf     PORTB                    ;   move to PORTB
           movlw     d’1’                     ;   move the number 1 to W
           call      wait                     ;   call wait sub-procedure
           goto      main                     ;   loop back to start




DET: Technological Studies: Systems and Control (Advanced Higher)                   60
Assignment 3

Describe three products which may contain stepper motors. Describe how the motor
is used in each case.


Assignment 4

A toy manufacturer is designing a new programmable robot toy. Describe the
advantages and disadvantages of using stepper motors (rather than dc motors) to
manoeuvre the robot.


Assignment 5
                                             12V DC
                                             SUPPLY



                   STAMP                   OUTPUT                   STEPPER
                 CONTROLLER                DRIVER                    MOTOR




Connect a stepper motor to the output driver module as shown.

Develop an assembler code program that will rotate the stepper motor 48 steps in one
direction, and then 48 steps in the other direction.




DET: Technological Studies: Systems and Control (Advanced Higher)                 61
Pulse Width Modulation

Pulse Width Modulation (PWM) is a digital method that can be used to vary the speed
of a DC motor. In this method the full supply voltage is applied to the motor, but it is
rapidly pulsed on and off. By varying the on and off ratio of the pulses the speed of
the motor can be varied. As the full voltage is applied to the motor during the ‘on’
pulses the torque of the motor remains high.

              V
                                                       MARK




                                                                         t
                                                P
                                               S ACE




The graph shows how the technique is applied. The ‘on’ time for the motor is called
the mark, the ‘off’ time is called the space. When the voltage is applied to the motor
it accelerates to top speed. However before the top speed is reached the motor is
switched off, thus slowing it down. By increasing the frequency of the pulses this
acceleration/deceleration becomes negligible, and the motor rotates constantly at a
slower speed.
The PWM technique does have certain limitations. It cannot be used with mechanical
relays, as the rapid switching would damage the mechanical contacts. The frequency
of the pulses must also be carefully selected – if the frequency is too slow the motor
will stall.




DET: Technological Studies: Systems and Control (Advanced Higher)                    62
Assignment 6


Activity




Connect a dc solar motor to the motor output B connection on the Output Driver
module.

Key in the following program. Burn a PIC and then test the program.
This program drives the motor at approximately half speed, as the space is twice the
length of the mark.

init:      bsf      STATUS,RP0             ;   move   to memory page 1
           movlw    b’00001111’            ;   make   4-7 outputs, rest inputs
           movwf    TRISB                  ;   move   W to TRISB
           bcf      STATUS,RP0             ;   move   back to page 0

main:      bsf      PORTB,7                ;   switch on pin7
           movlw    d’5’                   ;   set the mark to 5
           call     pause                  ;   call pause sub-procedure
           bcf      PORTB,7                ;   switch off pin7
           movlw    d’10’                  ;   set the space to 10
           call     pause                  ;   call pause sub-procedure

           goto     main                   ; loop back to start


Try out different speeds (by experiment) by altering the values of ‘mark’ and ‘space’.




DET: Technological Studies: Systems and Control (Advanced Higher)                      63
Assignment 7

Activity

Building microcontroller circuits from discrete components.




Pinout of PIC16F84 microcontroller.




Basic components required:
 PIC16F84-04/P microcontroller
 4.7k 0.25W carbon film resistor
 330R 0.25W carbon film resistor
 10k 0.25W carbon film resistor
 4MHz ceramic 3 pin resonator
 5mm red LED
 push to make switch
 prototyping breadboard and wire links
 4.5V or 5V regulated DC supply (e.g. 3xAA cells in battery box).




DET: Technological Studies: Systems and Control (Advanced Higher)    64
Using the breadboard, build the basic PIC circuit as shown below.




The 18-pin PIC microcontrollers require all of the following connections to operate
correctly:


Vdd       - pin 14         - power supply, must be connected to V+ (2 to 6V)
Vss       - pin 5          - ground, must be connected to 0V
OSC1      - pin 15         - clock, connect to one outer pin of ceramic resonator
OSC2      - pin 16         - clock, connect to other outer pin of ceramic resonator
MCLR      - pin 4           - master clear (reset), connect to V+ via 4.7 k resistor




               The centre pin of the 3 pin ceramic resonator must be connected to
               ground (0V). The ceramic resonator is not polarised and so can be used
               either way around.




DET: Technological Studies: Systems and Control (Advanced Higher)                       65
Now connect a switch (in a potential divider arrangement with a 10k resistor) to pin
PORTB,0 (IC pin 6). Also connect an LED (with 330R current limiting switch) to pin
PORTB,7 (pin 13).

Draw a flowchart, develop an assembler code program, burn the PIC and test the
program, for the following problems:
 make the LED glow only whilst the switch is pressed
 make the LED flash 15 times every time the switch is pressed
 give the switch a latching function (e.g. press once to light LED – press again to
   put LED out).

Bug alert!
 Remember that the microcontroller operates extremely quickly. You may need to
  add time delays to your program to ensure correct operation if the switch contacts
  ‘bounce’.




DET: Technological Studies: Systems and Control (Advanced Higher)                      66
Section 4 - project assignments

For the following practical project assignments students are expected to:
1. Identify the control task to be achieved.
2. Select suitable input and output transducers, explaining the reason a particular
   transducer was selected.
3. Build a model of the system, correctly connecting the transducers via the input
   and output driver modules.
4. Develop a flowchart of the control sequence.
5. Use the flowchart to develop and test an assembler code program for the control
   sequence.

Project briefs
1. A woman has a very valuable jewellery collection. Design and build an alarm
    system which will detect when a light is shone onto the jewellery box.
2. A family with several small children find that the fridge door is constantly left
    open. They require a system to warn them when the door of the fridge has been
    left open, but not when simply opened to take something out.
3. A large greenhouse needs a temperature monitoring system which includes a
    warning light to tell them when the temperature gets too high. The operator must
    lower the temperature and cancel the warning light within a short time or an alarm
    will sound.
4. Design and build a single sweep windscreen wiper. The system should start when
    the operating switch is pushed and stop it again when it returns to the parked
    position.
5. An advanced satellite television system must rotate the dish to a number of
    different positions. Design and build a system using a stepper motor that will
    move to four pre-set positions.
6. A rotary table for an automatic drilling process has to revolve clockwise for six
    seconds, stop for two seconds and then revolve anti-clockwise for six seconds. It
    carries on doing this cycle indefinitely. Design and build this system.
7. Design and build a rotary table which will revolve once, trigger a switch which
    will make the table revolve in the opposite direction until it triggers the switch
    again. The cycle should repeat indefinitely.
8. A small engineering company decide to automate their works. A system is
    required which will pick up a metal disc using an electro-magnet. It will then
    transport this disc along a line until it hits a switch, release it and return for
    another disc, thus completing the cycle. Design and build a model of this system.
9. Design and build a lift suitable for a two-story warehouse. The lift will run
    unmanned but must not be able to operate unless a safety grill has been closed
    first.
10. Car theft has become a major problem. After careful consideration, design and
    build a possible burglar alarm for cars left unattended.




DET: Technological Studies: Systems and Control (Advanced Higher)                     67
DET: Technological Studies: Systems and Control (Advanced Higher)   68
OUTCOME 3 – PROPORTIONAL CONTROL



The purpose of this outcome is to examine basic proportional control strategies, how
they operate, how they are applied and to understand important elements of their
operation.
When you have completed this outcome you should be able to:
 describe proportional control strategy
 describe the output response of proportional control
 describe the constituent elements of PID control.

Before you start this outcome you should have a basic understanding of:
 block diagrams.




DET: Technological Studies: Systems and Control (Advanced Higher)                  69
Proportional Positional Control – using model servos




A good example of a positional control device is the model servo motor commonly
found in radio-control cars and aeroplanes.




The servo contains a motor, gearbox, feedback potentiometer and electronic control
circuit on a small printed circuit board.

The feedback potentiometer is directly connected to the output shaft. Therefore, when
the motor spins, the output shaft is turned slowly by the gearbox, which in turn moves
the potentiometer. Naturally movement of the output shaft is restricted to 180º as the
potentiometer cannot spin continuously.




DET: Technological Studies: Systems and Control (Advanced Higher)                    70
The control diagram for the servo is shown below.


                                                 FEEDBACK
                                               POTENTIOMETER




  SET                               OPERATIONAL                 OUTPUT        CONSTANT
POSITION                             AMPLIFIER                  DRIVER        POSITION




Note how the feedback signal from the feedback potentiometer is fed into the negative
symbol of the error symbol on the control diagram, indicating negative feedback.

The error, e, is equal to (desired value – measured value). In this case, the operational
amplifier multiples the error by a set factor (K). This means that the further away
from the desired position, the faster the motor will spin (up to the operating
constraints of the motor). In the case of the servo the speed of the motor is often
controlled by PWM techniques.

                   Desired value
                                      e                    Ke

                                            Proportional
                            +               Controller          Process
                                -                K


                                          Measured value




                                      Servo Operation


The ‘desired position’ signal for the servo is applied as a short pulse, applied every
20ms to the signal wire (coloured white or yellow). The length of the pulse
determines the position that the servo moves to:
 a 0.75ms pulse will move the servo to one end (0 degrees)
 a 2.25ms pulse will move the servo to the other end (180 degrees)
 a 1.50ms pulse will move the servo to the central position (90 degrees)
 any other valid pulse (between 0.75-2.25) moves the servo to a corresponding
   intermediate position.

Therefore the servo continuously receives the pulse, calculates the desired position of
the output shaft, measures the error signal, and activates the motor as required.




DET: Technological Studies: Systems and Control (Advanced Higher)                        71
Assignment 1


Activity


Connect a servo to output 4 on the Output Driver module. Ensure that the black wire
aligns with the ‘B’ marked on the circuit board to ensure correct polarity.

Key in the following program. Burn a PIC and then test the program. This program
drives the servo to the central position (pulse length 1.5ms = 150 x 10us). Note the
use of the short sub-procedure to create a 10us delay.

; short sub-procedure. Creates a delay of 0.01ms x value of COUNTER
short: movwf     COUNTER      ; save loop value

shtlp:     nop                           ;   this is a 10us delay loop
           nop                           ;   no operation delay
           nop                           ;   no operation delay
           nop                           ;   no operation delay
           nop                           ;   no operation delay
           nop                           ;   no operation delay
           clrwdt                        ;   clear watchdog in case set
           decfsz      COUNTER,F         ;   test counter
           goto        shtlp             ;   not zero so loop
           return

init:      bsf         STATUS,RP0        ;   move   to memory page 1
           movlw       b’00001111’       ;   make   4-7 outputs, rest inputs
           movwf       TRISB             ;   move   W to TRISB
           bcf         STATUS,RP0        ;   move   back to page 0

main:      bsf         PORTB,4           ;   switch on pin4
           movlw       d’150’            ;   move the number 150 to W
           call        short             ;   call short sub-procedure
           bcf         PORTB,4           ;   switch off pin4

           movlw       d’20’             ; move the number 20 to W
           call        pause             ; call pause sub-procedure

           goto        main              ; loop




DET: Technological Studies: Systems and Control (Advanced Higher)                  72
Assignment 2


Activity


Connect a servo to output 4 on the Output Driver module. Ensure that the black wire
aligns with the ‘B’ marked on the circuit board to ensure correct polarity.

Key in the following program. Burn a PIC and then test the program. This program
drives the servo to the one end if switch 0 is on, and the other end if switch 0 is off.
Note the use of the short sub-procedure to create a 10us delay.


; short sub-procedure. Creates a delay of 0.01ms x value of COUNTER
short: movwf     COUNTER      ; save loop value

shtlp:     nop                           ;   this is a 10us delay loop
           nop                           ;   no operation delay
           nop                           ;   no operation delay
           nop                           ;   no operation delay
           nop                           ;   no operation delay
           nop                           ;   no operation delay
           clrwdt                        ;   clear watchdog in case set
           decfsz      COUNTER,F         ;   test counter
           goto        shtlp             ;   not zero so loop
           return

init:      bsf         STATUS,RP0            ;   move   to memory page 1
           movlw       b’00001111’           ;   make   4-7 outputs, rest inputs
           movwf       TRISB                 ;   move   W to TRISB
           bcf         STATUS,RP0            ;   move   back to page 0

main:      movlw       d’75’                 ; preload value to 75
           btfsc       PORTB,0               ; if input is on
           movlw       d’225’                ; set to 225 instead

           bsf         PORTB,4               ; switch on pin4
           call        short                 ; call short sub-procedure
           bcf         PORTB,4               ; switch off pin4

           movlw       d’20’                 ; move the number 20 to W
           call        pause                 ; call pause sub-procedure

           goto        main                  ; loop




DET: Technological Studies: Systems and Control (Advanced Higher)                          73
Assignment 3

Activity

Connect a servo to output 4 on the Output Driver module. Ensure that the black wire
aligns with the ‘B’ marked on the circuit board to ensure correct polarity.

Key in the following program. Burn a PIC and then test the program. This program
drives the servo to the two ends, and central position, every 2 seconds. Note the use
of the short sub-procedure to create a 10us delay.

; short sub-procedure. Creates a delay of 0.01ms x value of COUNTER
short: movwf     COUNTER      ; save loop value

shtlp:     nop                              ;   this is a 10us delay loop
           nop                              ;   no operation delay
           nop                              ;   no operation delay
           nop                              ;   no operation delay
           nop                              ;   no operation delay
           nop                              ;   no operation delay
           clrwdt                           ;   clear watchdog in case set
           decfsz      COUNTER,F            ;   test counter
           goto        shtlp                ;   not zero so loop
           return

; loop sub-procedure. Sends pulse (length of pulse                  in TEMP)
; out every 20ms for 2 seconds (100 loops at 20ms =                 2s)
loop:   movlw    d’100’      ; set up 100x20ms = 2s                 loop
        movwf    B1          ; move the number into                 B1

loop1:     bsf         PORTB,4          ;   switch on pin4
           movfw       TEMP             ;   move TEMP to W
           call        short            ;   call short sub-procedure
           bcf         PORTB,4          ;   switch off pin4

           movlw       d’20’            ; move the number 20 to W
           call        pause            ; call pause sub-procedure

           decfsz      B1,F             ; decrement B1
           goto        loop1            ; loop
           return                       ; all done so return

(continued on next page…)




DET: Technological Studies: Systems and Control (Advanced Higher)                   74
(continued from previous page…)


init:     bsf          STATUS,RP0       ;   move   to memory page 1
          movlw        b’00001111       ;   make   4-7 outputs, rest inputs
          movwf        TRISB            ;   move   W to TRISB
          bcf          STATUS,RP0       ;   move   back to page 0

main:     movlw        d’75’            ; first position
          movwf        TEMP             ; save in scratchpad
          call         loop             ; do two second loop

          movlw        d’150’           ; second position
          movwf        TEMP             ; save in scratchpad
          call         loop             ; do two second loop

          movlw        d’225’           ;   third position
          movwf        TEMP             ;   save in scratchpad
          call         loop             ;   do two second loop
          goto         main             ;   loop back to start




DET: Technological Studies: Systems and Control (Advanced Higher)             75
Building a mechatronic proportional control system

As seen by the operation of the radio-control servo, proportional control improves on
on-off control with a control action that is proportional to the error signal.
This means that the magnitude of the output signal changes in relation to the
magnitude of the input error signal.

This type of action should eliminate the fluctuating nature of on-off control. The
proportional controller amplifies the error by multiplying it by an adjustable gain
factor K to meet the output needs. Output = Ke.


                   Desired value
                                    e                    Ke

                                          Proportional
                            +             Controller          Process
                                -              K


                                        Measured value




This activity involves building a simple mechanical servo drive circuit with positional
feedback control. An assembler code program to provide proportional control will
then be developed.

The hardware can be constructed out of a constructional system such as Fishertechnic
or Lego, or out of discrete materials.

The principle of the system is quite straightforward – a variable resistor
(potentiometer) is connected to the output shaft of a motor/gearbox so that the
position of the output shaft can be measured.

As the PIC16F84 microcontroller does not have analogue capabilities (for the
analogue signal from the potentiometer) the ADC0831 ADC chip on the serial ADC
module must be used to connect the potentiometer to the system.

The feedback is provided by the rotary potentiometer which is connected to the output
shaft of a motor and high ratio gearbox – a slow output speed is required on the output
shaft of the gearbox. The speed of the motor is to be controller by a crude PWM
technique, where the multiplied error (value Ke) is used as the mark value (against a
pre-fixed space value). Therefore the larger the error, the larger the value of the mark,
and so the faster the motor speed.

For this activity the value of K will be initially fixed at the value 2.



DET: Technological Studies: Systems and Control (Advanced Higher)                     76
Sample apparatus (Lego)

The following pictures demonstrate a sample apparatus for this activity. Lego is used
in this instance but Fishertechnic or discrete components could also be used. The
motor is geared down by a series of gears. A long rack is moved back and forth by
the output gear to highlight the movement in the system.




DET: Technological Studies: Systems and Control (Advanced Higher)                  77
Assignment 4


This program simply demonstrates the operation of the serial ADC module to ensure
it is operating correctly. The four LEDs on the output pins 4-7 act as a simple ‘4-bit’
visual indicator of the analogue value – showing the binary patterns 0000 through to
1111 as the analogue signal increases.

Activity
Key in the following program. Burn a PIC and then test the program. Connect the
serial ADC module to the Stamp Controller, and then connect a variable resistor
(potentiometer) to the screw terminals on the serial ADC. Alter the sensor value by
twisting the potentiometer spindle.

          #include       <adcread.inc>

init:
          bsf            STATUS,RP0           ;   move to memory page 1
          movlw          b'00001100'          ;   set pins 0,1,4-7 as outputs
          movwf          TRISB                ;   move to TRISB
          bcf            STATUS,RP0           ;   back to page 0

          bsf            PORTB,0              ; disable ADC by setting CS pin

main:
          call           adcread              ;   call   sub-procedure
          andlw          b’11110000’          ;   mask   off high nibble only (4-7)
          movwf          PORTB                ;   move   to output port
          goto           main                 ;   goto   label


The sub-procedure adcread is included within the Programmer Editor software within
the include file ‘adcread.inc’.

The sub-procedure uses the pins 0, 1 and 2 to communicate with the serial ADC chip
on the serial ADC module. That is why the LEDs on these pins also flicker as the
program runs.

The sub-procedure returns the value of the analogue sensor connected to the serial
ADC module. The value (between 0 and 255) is returned in both W and the register
labelled B4. This is a standard sub-procedure which can be included within any
program by using the line #include <adcread.inc> within the sub-procedures
section of the program. There is no need to ‘learn’ the sub-procedure, although it is
listed on the next page for informational purposes.




DET: Technological Studies: Systems and Control (Advanced Higher)                     78
Full listing of file adcread.inc (included within the software)

; sub procedure to read a byte from the serial ADC module
; the data byte is returned in both register B4 and W
; first make sure the DDR (TRISB) is correct
adcread:
              bsf     STATUS,RP0   ; move to memory page 1
              bcf     TRISB,0      ; make sure ADC_CS is output
              bcf     TRISB,1      ; make sure ADC_CLK is output
              bsf     TRISB,2      ; make sure ADC_D_I is input
              bcf     STATUS,RP0   ; back to page 0

; make sure clock is low and CS is selected
              bcf     PORTB,1      ; make sure clock line is low
              nop                  ; nop to separate two bcf's
              bcf     PORTB,0      ; select ADC device

; send the initial wakeup pulse to the ADC
              bsf     PORTB,1      ; send an ADC clock pulse
              movlw   d'1'         ; of length 1ms
              call    pause
              bcf     PORTB,1

; clear the data byte         and set counter to 8 bits
              clrf            B4           ; clear data byte B4 to zero
              movlw           d'8'         ; set counter to 8 bits
              movwf           COUNTER

; shift the 8 bits of data into B4
; this is done by setting/clearing the carry bit
; depending on whether the ADC signal is high/low
; the carry bit is then rotated left into B4
adclp:        bsf     PORTB,1      ; send an ADC clock pulse
              movlw   d'1'         ; of length 1ms
              call    pause
              bcf     PORTB,1

                   bcf        STATUS,C          ;   clear carry bit
                   btfsc      PORTB,2           ;   test ADC signal
                   bsf        STATUS,C          ;   high so set carry high
                   rlf        B4,F              ;   rotate new bit into data byte

                   decfsz     COUNTER,F         ; all bits done?
                   goto       adclp             ; no so loop

; disable CS and return
              bsf     PORTB,0                   ; disable ADC
              movfw   B4                        ; put data value into W
              return                            ; return from sub




DET: Technological Studies: Systems and Control (Advanced Higher)                   79
Assignment 5

The following program will provide a basic proportional control system. It is fairly
crude in operation and may be developed further as an extension activity. The gain
factor, K, is fixed at 2 and the two desired positions are fixed at values 50 and 200,
although these values may be easily changed within the code as desired. The second
position is selected by holding down the push switch (pin3) on the serial ADC
module.

Important note
The following program introduces some more complicated programming techniques.
It is important to realise that the limited mathematical capability of the
microcontroller provides a number of problems to overcome when doing this type of
calculation in assembler code.

1. There is no multiply function within the microcontroller instruction set. However
   it is easy to duplicate a (x2) multiplication by use of the rlf (rotate left file)
   command, as this has the same result. Therefore to perform a (x4) multiplication
   you can do two consecutive rlf commands.

2. During this course we only use byte mathematics (possible value 0 to 255).
   Therefore when doing a (x2) multiplication you must not multiply any number
   that is already bigger than 128 as the result would ‘overflow’.

3. To compare two numbers you can subtract one from the other using the subwf
   instruction and see if the STATUS,C ‘carry’ bit is 1 (no overflow) or 0 (overflow).
   If the carry bit is 1 the error value (difference between the two values) is positive
   or 0.

    If the carry bit is 0 the error is negative, but the error value will also be corrupt as
    the byte will have overflowed (e.g. –7 will actually be stored as +249) due to the
    byte mathematics. Therefore before using this corrupted value you must convert it
    back to a useable number (e.g. converting –7 (249) back to +7). This is done by a
    standard assembler code process called ‘taking the two’s complement’ which is a
    comf (equivalent to a bitwise logic NOT) instruction followed by an incf
    (increment) instruction.

4. If the error value is exactly 0 it is useful to identify this fact so that the error
   correctional part of the program can be skipped. It is a common assembler code
   ‘trick’ to identify a particular value by loading this value into W and then
   performing an XORWF instruction. If the two values are the same the STATUS,Z
   bit will be set to 1, if the two values are not the same the bit will be cleared to 0.




DET: Technological Studies: Systems and Control (Advanced Higher)                        80
Activity
Key in the following program. Burn a PIC and then test the program.
Connect the serial ADC module to the Stamp Controller, and then connect the
variable resistor (potentiometer) to the screw terminals on the serial ADC.
Connect the output module to the Stamp Controller, and connect the motor to the
push-pull driver screw terminals labelled ‘A’.
As the potentiometer gets closer to the desired position the motor should slow down
and then stop. It may be useful to remove the potentiometer from the module to test
this manually. The potentiometer spindle must operate in the correct direction in
relation to the output shaft – so it may be necessary to reverse the motor contacts to
achieve this.
Also try removing the three lines that perform the k factor (x2) multiplication. See
what difference this will make to the response (unity k factor).

Also try adding two sets of these three lines, directly above each other. This will have
the result of increasing the k factor to (x4).

What other improvements can be made to the system to improve the performance?




DET: Technological Studies: Systems and Control (Advanced Higher)                      81
          #include       <adcread.inc>

init:     bsf            STATUS,RP0           ;   move to memory page 1
          movlw          b'00001100'          ;   set pins 0,1,4-7 as outputs
          movwf          TRISB                ;   move to TRISB
          bcf            STATUS,RP0           ;   back to page 0
          bsf            PORTB,0              ;   disable ADC by setting CS pin

main:     call           adcread              ; call sub-procedure
          movwf          B3                   ; save ADC value in B3

          movlw          d’50’                ; desired value when switch up
          btfsc          PORTB,3              ; test push switch
          movlw          d’200’               ; position when switch pushed

          subwf          B3,W                 ; subtract from ADC measured value
          btfss          STATUS,C             ; test carry bit for overflow
          goto           neg                  ; overflowed so negative error

pos:      movwf          TEMP                 ; save positive error into TEMP

          bcf            STATUS,C             ; multiply error in TEMP by 2
          btfss          TEMP,7               ; but only if value < 128
          rlf            TEMP,F               ; else it would overflow

          movlw          d’0’                 ;   test for error value = 0
          xorwf          TEMP,W               ;   by doing an XOR comparison
          btfsc          STATUS,Z             ;   and then testing zero bit
          goto           main                 ;   =0 so loop back immediately

          bsf            PORTB,5              ;   switch on motor backwards
          movfw          TEMP                 ;   get error as mark time
          call           pause                ;   do delay
          bcf            PORTB,5              ;   switch off motor
          movlw          d'55'                ;   short space time
          call           pause                ;   do delay
          goto           main                 ;   back to loop

neg:      movwf          TEMP                 ; save corrupt value into TEMP
          comf           TEMP,F               ; take 2’s complement
          incf           TEMP,F               ; to correct it

          bcf            STATUS,C             ; multiply error in TEMP by 2
          btfss          TEMP,7               ; but only if value < 128
          rlf            TEMP,F               ; else it would overflow

          movlw          d’0’                 ;   test for error value = 0
          xorwf          TEMP,W               ;   by doing an XOR comparison
          btfsc          STATUS,Z             ;   and then testing zero bit
          goto           main                 ;   =0 so loop back immediately

          bsf            PORTB,4              ;   switch on motor forwards
          movfw          TEMP                 ;   get error as mark time
          call           pause                ;   do delay
          bcf            PORTB,4              ;   switch off motor
          movlw          d'55'                ;   short space time
          call           pause                ;   do delay
          goto           main                 ;   back to loop




DET: Technological Studies: Systems and Control (Advanced Higher)                 82
Proportional control

Proportional control improves on on-off control with a control action that is
proportional to the error signal.

This means that the magnitude of the output signal changes in relation to the
magnitude of the input error signal.

This type of action should eliminate the fluctuating nature of on-off control. The
proportional controller amplifies the error by multiplying it by an adjustable gain
factor K to meet the output needs. Output = Ke.

                   Desired value
                                    e                    Ke

                                          Proportional
                            +             Controller          Process
                                -              K


                                        Measured value




                                           Figure 1


e is the error = Desired value – Measured value.

Figure 1 illustrates proportional action with ‘unity feedback’ where the measurement
sensor is incorporated into the process for simplicity. This is a legitimate illustrative
technique in most cases where the sensor response is fast compared with the response
of the actual process. Figure 2 shows the response of a system where the gain factor
K has been set low. Assume that the system is trying to maintain fluid at a constant
level in a tank, as set by the desired level value. A feedback sensor monitors the
actual level and an electric pump is used to control the flow into the tank. We assume
there is steady outflow from the tank as it feeds an industrial process.




DET: Technological Studies: Systems and Control (Advanced Higher)                     83
                                         Desired value
                              0
                        100

                                                                    offset



                        liquid                           Measured value
                  l     level



                                  0                 1        time        2




                                          Figure 2


Figure 2 shows that proportional action has eliminated the oscillating nature of on-off
control. At time zero, when the controller is switched on the tank is empty. The
difference between the desired and actual temperature is large, creating a large error.
This error is amplified by the controller to produce a large control action. The electric
pump is at full power. During this initial period the actual level is rising at its fastest
rate.

Response of proportional action
If we look at position 1 on the time scale the rate of rise of level is slowing
considerably. If the actual level is rising and the desired level is still the same then
the error will be reducing and consequently the control action reduces, reducing the
pump power. By position 2 the liquid level is at a steady value.

Limitations of proportional action
Figure 0, although demonstrating the smooth control that is available with
proportional action, highlights two obvious limitations. One, the response to a change
is very slow. It takes a long time to reach a steady level after the initial set point
change. Two, it appears that the actual level has reached a steady state well below the
desired value. The gap between the desired and actual valuations is commonly called
offset.

Increasing the gain of a proportional controller
The normal method of improving the response of a proportional controller is to
increase the gain factor K.

Figure 3 shows three different output responses for three different levels of gain
applied to the controller.




DET: Technological Studies: Systems and Control (Advanced Higher)                          84
                                                Desired value


                           Liquid                                    offset
                           Level
                                     Actual value




                                                     Time



                                          Figure 3 (a)




                                                     Desired value



                          Liquid
                          Level                                               offset

                                      Actual value




                                                     Time




                                         Figure 3 (b)



                                    Desired value




                           Liquid
                           Level
                                      Actual value




                                                     Time


                                          Figure 3 (c)




DET: Technological Studies: Systems and Control (Advanced Higher)                      85
The process variable under control appears to have reverted to an oscillatory
condition. Closer inspection of Figure 3 (a) and (b) shows that the output does
stabilise eventually. Figure 3 (c) illustrates an undesirable situation where the
controlled condition is reverting to on-off control as the fluctuations build up.

In figure 20 the gain applied was too low resulting in very sluggish response. Imagine
that the tank is holding at a steady level. A change is made to the desired value to set
a new level. This is called a step change. The system will attempt to control to the
new level but due to the very low gain applied by the controller, the level creeps up
very slowly eventually stabilising at a steady level well short of the new desired level.

Delays
Any device or process that has to be controlled, suffers from inherent delays. When
you wish to increase the speed of a car you put your foot down on the accelerator.
The car does not speed up immediately. A series of natural delays occur before any
response is obtained. It takes time for the increased mixture of fuel and air to get to
the engine. A further delay occurs in the time it takes for the larger explosion to occur
in the cylinder and a further delay before the increased engine power reaches the
wheels.

Robots are associated with delays in relation to electrical and mechanical aspects.
These could include the response delay of electric drives due to the inductance of the
windings and mechanical delays due to the inertia and friction of heavy mechanical
parts.

Transfer functions and time domain plots
Any industrial process is a unique combination of delays of different types. All of
these delays are taken in account when we develop a transfer function for the
process. A transfer function describes the response of a process, how it responds to
change against time. Time domain plots, as illustrated in Figures 2 and 3, illustrate
this response graphically.

In our tank level example we can increase the speed of response by increasing the
magnitude of the control effort. This is likely, depending on the level of gain applied,
to cause the measured value to overshoot the final steady value.

The best response involves a compromise where a certain degree of overshoot is
acceptable. Figure 3 (a) is an accepted response in slower processes, such as liquid
level control, to a step change where a four to one decay ratio is achieved. After the
initial step input is applied the actual level will climb to a new level and fluctuate for
about four decaying changes before settling at the new level.

In faster acting systems, such as servo-motor control, adjustment of the controller gain
would be aimed at a fast response but with minimum overshoot.




DET: Technological Studies: Systems and Control (Advanced Higher)                        86
Offset
The major limitation of a proportional only controller is its inability to match the final
actual value with the desired value. Figures 2 and 3 show this clearly. What does
become clear is that increasing the controller gain reduces the magnitude of this
offset. However if we take the gain too high the system begins to oscillate as an on-
off controller. There is a limit therefore to offset reduction using greater gain.

Why offset?
Offset exists because the proportional controller is error actuated. With no error there
would be no output. The tank level system pump is driven at various output speeds by
the output of the controller and depends on the magnitude of the error. If the error is
zero the pump stops. If liquid is being drawn from the tank the level will fall. There
has to be some liquid pumped in to meet the load demands out of the tank.

Proportional band
Manufacturers of industrial controllers usually quote proportional band instead of
gain. The actual equation for proportional band looks like this:

     fractional change in input      error      output range
PB% =                           =                            100
    fractional change in output   input range      output
 1 output range
 x              x100
 K input range


Fractional refers to the change in relation to the full range of both input and output.
The gain and proportional band are related reciprocally. Gain = output / error.
Proportional band is often quoted in %. If a controller is set to 50% proportional band
we are saying that a 50% change in the input will produce 100% change in the output.
Any further input change beyond 50% of its range will saturate the controller and
cause no further output changes. A narrow proportional band relates to a high
gain. A wide proportional band relates to a low gain. Note error / output = gain.




DET: Technological Studies: Systems and Control (Advanced Higher)                       87
Proportional,Integral and Derivative Control (PID)
There are applications where a simple proportional controller would suffice. Where
more accurate and responsive control is required we need to consider a more
sophisticated control technique.

PI Controller (Proportional + Integral)
To eliminate offset associated with proportional control we need an additional control
action which provides the required output in the steady state with zero deviation.
Integral action, which is proportional to the integral of the error over time, provides
the desired outcome.

With proportional action the output is proportional to the magnitude of the error.
When the output eventually stabilises it will still require an error to provide the
necessary output. Integral action will see this error and will continue to change the
output until the error is zero.

With integral action included, a steady state output can only be achieved when the
input error is zero. At this point the proportional action contributes nothing to the
final output. When the input step change is initially applied proportional action
provides the output but this diminishes as the error reduces.

Integral action is weighted by a constant of time Tr called ‘reset time’. The rate of
application of integral action is dependent on the reset time selected. Short ‘reset
time’ apply integral correction quickly but if too fast the system may become
unstable. Long ‘reset times’ means that the error is removed too slowly. Figure 4
shows a series of time domain responses with various degree of reset time.

                                                                          K
The mathematical version of PI control is output =Ke +
                                                                          Tr    e dt   where ‘e’is the


error, ‘K’ is the gain factor and ‘Tr’ is the integral reset time.

                100
                          Curve c        Curve b




                                            Curve a            Step change in set point


                                    Initial steady actual value equal to set point



                  0                      Time



                                                Figure 4


DET: Technological Studies: Systems and Control (Advanced Higher)                                         88
Curve ‘a’ shows the effect of a long ‘reset time’. After the step change in the desired
value, the actual value takes far too long to eliminate the offset.

Curve ‘c’, with the shortest ‘reset time’, shows a tendency to oscillate before settling
down whilst curve ‘b’ appears to offer the best response. In practise the ideal will not
normally be achievable. A compromise may have to be reached when adjusting both
‘reset time’ and ‘gain’ so that the best response obtained may be a slightly oscillatory
one like ‘c’.

The benefit of integral action is clearly seen where at the final steady state any offset
has been eliminated.




DET: Technological Studies: Systems and Control (Advanced Higher)                       89
PID Controller ( Proportional + Integral + Derivative )
Proportional action responds immediately to changes in deviation. Integral action
eliminates steady state errors which cannot be eliminated with proportional action. A
third action called ‘derivative action’ produces an output response proportional to the
rate at which the error is changing. If the error is not changing, derivative action
makes no contribution to the control effort.

Derivative action increases the speed of response and reduces the amount of
overshoot. It has no effect on steady state error. In mathematical terms it adds an
                                                                 K                de
element to the output response where controller output =Ke +
                                                                 Ti   e dt +KTd dt

Derivative action is weighted by a factor, Td, called derivative time.

Figure 5 shows two responses, one from a proportional only controller and one from a
proportional + derivative controller (PD).


                100
                       New set point
                                         Proportional action only           Offset




                                                Proportional + derivative


                                  Step change to new set point from here


                  0                    Time



                                              Figure 5


With derivative control the output settles at its final steady value sooner. Notice that
the amplitude of the oscillations is less. Derivative action has no effect on the offset.
Derivative action is avoided if the process plant has a significant amount of noise in
the measured signal. An example is flow measurement which uses orifice plates. The
turbulence created by the plates produces high frequency elements in the measured
signal. These elements result in an erratic control response with derivative action. It
would respond to these fast signals which are not part of the true measured value.




DET: Technological Studies: Systems and Control (Advanced Higher)                       90
Assignments

1. A proportional controller is applied to the temperature control of a process liquid
   in a tank. Draw three graphs of actual value against time to show the following
   control effects after a step change:
a) an optimum acceptable response
b) a slow sluggish response
c) an excessively fast response.

2.   From the previous exercise:
a)   comment on the effect of increasing the gain
b)   comment on the steady state error
c)   comment on the stability.

3. Many modern process controllers are classified as PID controllers. Describe each
   element of a PID controller in the following way:
a) give an accepted standard definition for each function
b) explain each of these definitions in terms of the practical effect.

4. Illustrate the individual effects of the elements of PID control after a step change
    as follows:
a) a response curve for proportional control only
b) a second response curve showing the effect of adding integral action to the
   proportional action
c) a third response curve showing the effect of adding derivative action to the
   proportional action
d) comment on the effects of each on the control action.




DET: Technological Studies: Systems and Control (Advanced Higher)                     91
DET: Technological Studies: Systems and Control (Advanced Higher)   92

				
DOCUMENT INFO