1 Design of Microprocessor Interfaces 1.1 Introduction A microprocessor is a stand alone, self contained single chip microcomputer. It must have as a minimum: • a central processing unit (CPU) • nonvolatile and program memory • input and output capabilities A structure that has these can be programmed in some convenient programming language and can interact with the outside world through the input/output ports. A microprocessor is a stand alone, self contained single chip microcomputer. It must have as a minimum: a central processing unit (CPU) nonvolatile and program memory input and output capabilities. A structure that has these can be programmed in some convenient programming language and can interact with the outside world through the input/output ports. Other important requirements are: • must be relatively simple • reasonably small • necessarily limited in most of its features memory, processing power and speed, addressing range and, of course in number of I/O devices it can interact with. • The designer must have access to all features of the microprocessor bus, memory, registers, all I/O ports There are generally TWO limitations to the performance of a microprocessor- limitations due to the microprocessor’s capabilities and limitations due to the designers imagination/capabilities (or lack thereof). 1.2 Peripheral Interface Categories Interfaces may be categorized according to the specification of the peripherals themselves, viz: 3 (i) Serial/Parallel interface (ii) Analog/digital interface (iii) Synchronized/Asynchronized interface 1.2.1 Serial Interfaces In serial communication interfaces, information is transferred one bit at a time. Ports that using serial streaming of information include: (a) Serial ports (based on RS232 technology) (b) Ethernet ports (c) USB (d) Firewire Settings Many settings are required for serial connections used for asynchronous start-stop communication, to select speed, number of data bits per character, parity, and number of stop bits per character. In modern serial ports using a UART integrated circuit, all settings are usually software-controlled; hardware from the 1980s and earlier may require setting switches or jumpers on a circuit board. One of the simplifications made in such serial bus standards as Ethernet, FireWire, and USB is that many of those parameters have fixed values so that users can not and need not change the configuration; the speed is either fixed or automatically negotiated. Often if the settings are entered incorrectly the connection will not be dropped; however, any data sent will be received on the other end as nonsense. 1.3 Interfacing I/O Devices to the Microprocessor, Memory and OS Characteristics of I/O Devices • Are interrupt driven • Shared by multiple programs 4 • Low level control is complex Function of the OS • Provision of security (for example, prevent a file created by one from being deleted by another) • Provision of abstractions for device access (e.g for collection of blocks on a disk) • Interrupt handling • Creation of ”fairness” in I/O device access • Management of I/O devices so that throughput is maximized 1.3.1 Communication between I/O Devices and the OS There are three types of communication between I/O devices and the OS: (i) OS must be able to give commands to the I/O devices. (ii) A device must be able to notify the OS when it has completed a command or when there is an error. (iii) Data must be transferred between the I/O device and memory. 1. Giving Commands to I/O Devices The CPU must be able to address the device and supply one or more commands. There are two methods of addressing the device: (a) Memory Mapped I/O: • Portions of a program’s address space are assigned to I/O devices. • Reads and Writes to these addresses are interpreted as commands to the device. • These memory addresses are not directly accessible to user programs. (b) Special I/O Instructions: • I/O instructions can specify both the device number and the command word (or the location of the command word in memory). • I/O instructions can only be executed by the OS. 2. Communicating with the Processor There are three methods: 5 (a) Continuous Dedicated Monitoring • • • • A processor is dedicated for use with the device (usually a sensor) Its output is monitored continuously The microprocessor reads the sensor’s output at a given rate Output is then used to act (b) Polling Mode • The I/O devices operate as if the microprocessor does not exist. • Their status is monitored at specified intervals by the microprocessor. • The status is used to generate action. (c) Interrupt Mode • The microprocessor is in ”sleep” mode to the I/O devices. • The device delivers an interrupt to the processor when it requires attention. • Interrupts are like exceptions, except they are not associated with any instruction. • The CPU can check before starting a new instruction if any new interrupt has been delivered. • Interrupt handling can be vectored or register-based. 3. Transferring Data Between Device and Memory There are two methods: (a) Interrupt Driven I/O • The processor is involved in data transfer. • The problem is that there is 100% overhead in case of data transfer to a hard disk. (b) Direct Memory Access (DMA) • Data is transferred directly from device to memory (and vice versa) independent of the processor through a special controller, the DMAC. • The DMA transfer consists of three steps: the initiating process, which involves identification of the device, the operation to be performed, source or destination address and volume of transfer; the transfer process itself; the DMA initiated interrupt at the end of the process. • The processor is only involved in initiating the DMA transfer and in handling the interrupt at the end of the transfer. 1.4 Interfacing the I/O to the Processor There are two methods of interfacing the I/O to the processor: Isolated I/O and Memorymapped I/O. 6 1.4.1 Isolated I/O I/O locations are isolated from the memory in a separate I/O address space. The addresses for isolated I/O devices are usually known as ports. Separate program instructions and control signals are generated to differentiate between Memory R/W operations and I/O R/W operations. The main advantage is that the memory can be expanded to its full size without using any of its space for I/O devices. A disadvantage with this method is that the amount of circuitry required increases. 1.4.2 Memory-Mapped I/O A memory mapped I/O is treated as a memory location in the memory map. No separate memory locations, separate instructions or separate control signals are required. The advantage with this method is that any memory transfer operation can be used to access an I/O device. A disadvantage is that a portion of the memory system is used as the I/O map. Parts of the PCIO map are dedicated to specific functions, for example, I/O expansion area, COM1, Floppy, CGA adapter, LPT1, Hard Disk, COM2, Timer, Interrupt Controller and DMAC. 1.5 Basic Microprocessor Input Interface An input operation is similar to a memory read cycle. 1. Microprocessor generates address and control signals to select the input device. 2. Input device generates data and loads data lines. 3. Microprocessor reads data from the data bus and places it in a register. Most microprocessors accept data from an input device through the data bus connections and therefore require some form of switch to connect this data to the bus at the appropriate time. One effective digital switch available is the three-state buffer. 7 1.5.1 Input Interfacing Requirements The following requirements must be considered in the design of the input interface: (a) Signal level (i) Basic level: 0 to Vdd . Signal must be scaled if necessary. (ii) No dual polarity signals. Signal must be translated or scaled as necessary. (iii) Direct reading or A/D? (iv) Only voltages can be read: • AC or DC? • Limitations in frequency (b) Impedance and Matching (i) Microprocessors are high input impedance devices (∼ 1 − 10M Ω), thus input currents are low (∼ 1µA). (ii) Ideal for direct connection of low impedance sensors (magnetic thermistors, thermoelectric, etc) (iii) High impedance sensors (capacitive, pyroelectric, etc) must be buffered. This can be done using Voltage followers or FET Amplifiers. (c) Response and Frequency (i) Most stand-alone sensors are slow devices, thus they can be interfaced directly without concern for response and frequency range. (ii) Sensors that are part of oscillators may operate at quite high frequencies, thus there is need to worry about proper sampling by the microprocessor. In cases where the sensor output has a frequency higher than that which can be comfortably sampled by the microprocessor, possible solutions are: • Division of the sensor’s frequency, which reduces sensitivity, and must be done externally to the microprocessor. • Use of a F-V converter, which introduces conversion errors, and must be done externally. • Use of a frequency counter at input, and then use the output of the counter as input to the microprocessor, which is an expensive option. • Use of faster microprocessors, which may also be costly. (d) Signal conditioning/Offset • Primarily for DC levels 8 • Can be offset up or down. • Usually done to remove the DC level. • Sometimes needed to remove negative polarity. • AC signals may sometimes be coupled through capacitors to eliminate DC levels. Offset may be accomplished through: (i) Use of inverting amplifiers to remove part of the DC signal, thus changing the lower level of the input range. (ii) Changing the value of the source voltage connected to the input circuit to change the range. (iii) Changing the values of biasing or protective resistors in input circuits. (iv) Rectification of unipolar ac signals (Bi-polar signals cannot be used with microprocessors). (v) Use of a bridge connection (e) Signal Scaling Signal scaling may be accomplished through the following methods: (i) By amplification -using Op-Amps (ii) By attenuation -using Op-Amps, Resistance Dividers or Transformers (for ac) • Amplifiers are preferable. • Dividers introduce errors. • Transformers are noisy and big. (f) Isolation Isolation is accomplished by two main methods: • Transformers • Optical Isolation (g) Loading • Microprocessors load the sensor. This is generally not an issue for low impedance sensors, but buffering must be provided for high impedance sensors. • The solution is to use Voltage followers with FET input stages. • An error due to loading should be taken into account. 9 1.6 Basic Microprocessor Output Interface An output operation is similar to a memory write cycle. 1. microprocessor generates address and control signals to select the output device. 2. microprocessor places data on the data bus. 3. microprocessor waits for the transfer to be successfully completed. Whenever data is sent out from the microprocessor to an external output device, it appears on the data bus for only a brief period of time. In almost all instances, the external output device uses some form of latch to grab onto and hold the data bus information. 1.6.1 Output Interfacing Requirements The following requirements must be considered in the design of output interface: (a) Signal Levels (b) Power levels (c) Isolation • Most microprocessors have output voltages of 1.8 to 6V with 20 to 25 µA per output pin. • Small loads such as LEDs and small relays can be powered directly. • Protection diodes are required on all outputs. • For large loads, circuitry must be added to boost output. Power MOSFETs are ideal for this purpose. • When inductive loads are connected, protection must be added against large spikes. • It is often necessary to isolate output. • It is very often necessary to translate voltages for output. • It is important to note that connection of output pins for sourcing and sinking of current is different. 10 1.7 Why Use Microprocessors in Mechatronic Systems • Stored Program control • Digital Processing • Speed of Operation • Design Flexibility • Integration • Cost 1.8 Embedded Real-Time Microprocessor Systems An embedded microprocessor system is one which is itself a subsystem of a much larger system which, in the case of mechatronic applications is based on a mechanical product or process. A real time application is one whose response to external events is required to meet a function of time. There are two major categories of microprocessor applications in mechatronics. Embedded real-time systems have the microprocessor built into an environment designed for typical computer applications such as a personal computer or a workstation. Data processing applications are used in mechatronic systems for centralized control. Real Time Embedded Application Memory Input/ Output Processor Data Processing Application Small amounts of both non-volatile read only memory for program storage, and read/write memory for data storage Large amounts of read/write memory which can be loaded from a data storage device, and only a small amount of nonvolatile program memory used during initialization of the system Both digital and analogue interfaces to sensors and actuators Mainly digital I/O to keyboard, visual display unit, disk drives, printers and communication with other computers. Wide range of performance to suit cost and application; fast response required to external events High performance required to improve the productivity of the user; response time is generally not critical The difference in memory requirements between embedded and computing applications is due to the fact that an embedded system typically operates with a fixed program while 11 a computer system must be capable of being reloaded with a wide range of different programs. In each case, system memory refers to the part of memory directly accessible to the microprocessor, as opposed to storage media. Non-volatile memory is that it can only be written to using a procedure that is incompatible with normal microprocessor write operations. Once information has been programmed into non-volatile memory it is considered permanent, so it is used to hold fixed programs and constant data(firmware). It is referred to as ROM. Volatile memory can be both read from and written to by the microprocessor and is normally used for data storage. It is referred to as Random Access Memory (RAM) or Read/Write Memory. Embedded systems typically contain small programs. General purpose computers, however have a system memory consisting mainly of volatile read/write memory which can be reloaded with different programs from a non-volatile storage memory device. However, the boot program is contained in non-volatile system memory. Large amounts of read/write system memory are required to accommodate the large and complex programs required for CAD and simulation. The primary input and output devices for a computer system are the keyboard and visual display unit. The main controlling influence over the system is the human operator. More user-friendly input devices have been developed to address the inefficiencies of a keyboard. An embedded microprocessor system receives input from sensors connected to the machine or device it is controlling. Output from the microprocessor is used to operate actuators which in turn control the machine or device. The primary interface for an embedded microprocessor system is therefore a machine-machine interface. Embedded real time systems may also make use of an operating system known as a realtime multitasking executive. This is an interrupt-driven system that executes special programs to service the requests that generated the interrupts. The executive may also have an interrupt scheduling mechanism to enable it to control the execution of several individual programs, thereby creating a multi-tasking system. A real-time multitasking executive thus provides a set of services onto which systems can be built from tasks which may have complex interactions with one another and with external devices. In an embedded system, the executive would reside together with the application programs in program memory whereas in a computer system it would normally be loaded from a disk. 12 1.8.1 Differences between embedded and non-embedded systems (i) Embedded systems are generally used in real-time applications. They therefore have hard real time requirements. This means that tasks must be completed within a certain amount of time or the system must react to certain external events within a certain time. Otherwise the consequences may be serious, even catastrophic. In non-embedded systems, the consequences of not meeting the real time response requirements are generally not as serious. (ii) Embedded systems have specialized architecture and resources while non-embedded systems tend to have general purpose architecture and resources. (iii) Embedded controllers and I/O interfaces are more integrated in the chip design level than general purpose computers. (iv) The physical size of the embedded system is typically required to be very small, which may be dictated by the application. (v) Embedded controllers may operate in extreme environmental conditions. (vi) Embedded controllers invariably incorporate a watchdog timer circuit to reset the system in case of failure. (vii) Embedded controllers may have a dedicated debugging circuit on the chip so that the timing of all the I/O signals can be checked and application program debugged on the target hardware. (viii) The developer must know the details of the embedded system hardware (bus architecture, memory map, register, interrupt system), because the application program development is influenced by the hardware resources available. (ix) Interrupts play a very important role in any embedded controller application, facilitating interaction between the system and external events in real time, as well as interaction within different parts of the system. (x) As the complexity increases, embedded system requires a Real Time Operating System (RTOS), also known as the Real Time Executive. 1.9 Components of Embedded Real Time Microprocessor Systems 1. input and output devices 2. CPU 3. Program and Data memory 13 4. Peripheral circuits to support communication between components 1.9.1 Input and Output Devices They provide an interface between the microprocessor and external systems. The microprocessor only handles digital information, but through the use of A/D and D/A converters, it is possible to handle analog information. The input and output devices contain registers, which may be of two types: • Control / Status Registers, which allow a program to control the mode of operation of the input/output device and indicates to the CPU the status of the device. • Read/Write Registers, which provide a data path that enables the microprocessor to read and write information from and to the outside world. A/D and D/A Converters These provide an interface between two devices which produce or are driven by analog signals, and digital systems such as microprocessors. An A/D converter takes a finite time to convert an analog signal to its digital equivalent. During the conversion time, the analog input should be maintained at a steady value so as not to cause errors in the conversion. A/D converters also contain a data register and a control register, and once conversion is completed, the converter sends an interrupt signal to the CPU. A/D converters work with multiplexers, thus may produce multiplexed outputs or signals. D/A converters provide the system with a single analog output channel, and unlike the analog inputs, it is not practical to produce multiplexed outputs from a single D/A converter, hence one D/A converter is used for each output channel required. (WHY?) The D/A converter works with one register- the data register. This holds the digital value which needs to be converted to its analog equivalent. D/A converters mainly output current signals rather than voltage signals. This is because most D/A converters work on principles based on a resistor ladder which sums up current components from each binary digit at the output of the D/A converter. The output of the D/A converter may be buffered to produce a voltage output. 1.10 The CPU The main CPU functions are: 14 • Fetching instructions • Decoding instructions • Execution of instructions in a sequential format The functions are performed depending on the program being run. Characteristics of a typical program are as follows: 1. Sequential execution of instructions, unless a specific instruction, such as a jump, transfers execution to another point in the program. 2. Frequently repeated sections are coded separately in subroutines. Calling the subroutine transfers execution to the beginning of the subroutine. Once execution of the subroutine is completed, control automatically reverts to the main program at the instruction immediately after the calling of the subroutine. Subroutines may be nested. 3. A program may contain groups of instructions whose execution is dependent on the result of previous instructions. 4. The program contains assignment and basic arithmetic functions for the manipulation of data. 1.10.1 Fetching Involves the sequential fetching of data or a set of instructions. It is normally supported by the Program Counter, the Stack Pointer, Instruction decoded control and hard wired control units. 1.10.2 Arithmetic Phase Is supported by the Arithmetic Logic Unit and the Accumulator. It is also supported by the processor’s status register and the register bank. 1.10.3 Interrupt Processing This is supported by register stacking and context switching as well as by vectored and non-vectored interrupts,multiple interrupt processing, non-maskable interrupts and CPU resets. 15 Non-vectored interrupts address a fixed location within memory. Vectored interrupts may refer to pointers or memory register locations. 1.10.4 CPU Instruction Sets These are made of OP codes and operands. The OP codes describe the operations to be performed while operands are the data to be operated on. Addressing of data involves the accessing of the data on which the OP codes are to operate. Formats of addressing include: 1. Direct addressing 2. Immediate addressing 3. Indexed addressing 4. Indirect addressing 5. Relative addressing 6. Bit addressing 7. Absolute addressing 8. Paged addressing 9. Stacked addressing 16 2 Programming for Control Using Assembly Language Assembly language is the mnemonic form of a microprocessor’s instruction set. The assembler is a program which converts an assembly language program into machine code instructions which can be executed by the microprocessor. The mnemonic itself is a simple abbreviation which indicates the action to be performed by the instruction. A typical assembly language program consists of two types of instructions. The first type are the microprocessor mnemonic instructions which cause the generation of their equivalent machine code instructions. The second type are called assembler directives and control the operation of the assembler, for instance allocating areas of read/write memory as data storage locations, defining constant values as labels which have more meaning within the context of the program, and defining the beginning and end of the program. 2.1 High Level Programming Language and Compilers The advantages of using high level language are: 1. It improves the productivity of the programmer because each line of high level source code produces several lines of machine code. 2. It makes the programmer less likely to produce errors because he no longer has to concern himself with the specific instruction set and register details of the microprocessor. 3. It allows more complex data manipulations to be more easily implemented as a high level language will support a range of data types and data structures which can be directly manipulated by high level language statements. 4. It makes the program more portable between different types of microprocessor, given that a compiler and a linker are available to generate the object code for the desired microprocessor. 5. It makes the source program more readable in that the statements in a high level language program can be based on English words and on phrases whose meanings more adequately reflect the function of the program. The disadvantages of high level languages are: 1. It generates more object code than an equivalent program written in assembly language. 17 2. Compiled object code generally runs more slowly than the assembly code program. 2.2 The Real Time Multitasking Executive An executive is a program which provides a set of services to an application program which must perform a number of concurrent functions in real time. The functions appear to be executed in parallel, though in reality they are executed sequentially by the microprocessor whose speed gives the impression of parallel execution. The application program is broken down into a number of smaller programs known as tasks. Each task performs a specific function and co-operates with other tasks to perform the overall function required of the program. The executive integrates the tasks into a single real time application program, provides co-ordination and scheduling. The services provided by the real time multitasking executive are: 1. task scheduling 2. intertask communication and synchronization 3. timing 4. memory management 2.2.1 Tasks and Task Scheduling A task is a program whose execution is controlled by the executive. A task is typically written as a continuous loop, and will have a point at which it receives input data from other tasks, or from input devices via interrupt routines, and, following any processing, will output data either to other tasks or to output devices. The task will then wait to receive further input data. As there may be several tasks that comprise the entire system, when a particular task is waiting to receive input and is therefore not performing any useful function, the executive will start to execute another task which is ready to be executed. Each task can therefore be in a blocked state waiting for input, or be in a ready state. However, because there may be more than one task in a ready state, the executive must employ a scheduling mechanism to ensure that the tasks that are ready to be executed gain access to the CPU and are executed sequentially in a particular order based upon their relative priority. A task may therefore be in one of three states: executing, ready and blocked. When a task is being executed by the CPU, it runs as would any normal programs. The task makes use of functions or subroutines, that are part of the executive to perform intertask communication, memory management or timing functions. The executive can 18 also review the status of the currently executing task and other tasks that are ready to execute or that are blocked. If a task is blocked, it is usually waiting for some condition to occur to unblock it, such s receiving data. Because the intertask communications are performed as functions within the executive, when a task receives all the necessary information required to unblock it, the executive can change the status of the task from blocked to ready. If there is more than one ready task waiting to be executed, the executive must schedule the ready tasks to reflect the importance of their execution so that the most important task is the next task to be executed. If the execution of this task is more important than the currently executing task, then the executive may also perform a task switch where the highest priority ready task starts execution and the previous executing task joins the other ready tasks. In order for the executive to perform task rescheduling and task switching functions, the executive must know some specific information about the tasks, such as the start address of the tasks and the relative priority of each ready task. Such information is placed in an area of memory known as a task control block (TCB). Each task will have a TCB which is created by the executive during its initialization and placed in a queue called the ready queue. The queue corresponds to the collection of those tasks which are ready to execute, and during rescheduling, it is reordered to place the highest priority task at the top of the queue. 2.2.2 Intertask Communications and Synchronization 1. Semaphores In computer science, a semaphore is a variable or abstract data type that provides a simple but useful abstraction for controlling access by multiple processes to a common resource in a parallel programming environment. A useful way to think of a semaphore is as a record of how many units of a particular resource are available, coupled with operations to safely (i.e. without race conditions) adjust that record as units are required or become free, and if necessary wait until a unit of the resource becomes available. Semaphores are a useful tool in the prevention of race conditions and deadlocks; however, their use is by no means a guarantee that a program is free from these problems. Semaphores which allow an arbitrary resource count are called counting semaphores, while semaphores which are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary semaphores (same functionality that mutexes have). The function set semaphore is used to set the flag on a binary semaphore when the required condition is met. The function wait semaphore causes a function to cease execution and remain in a blocked state until the required semaphore is set. 2. Mailboxes A mailbox is used to pass data between tasks. A mailbox is an area of memory under the control of the executive into which tasks can post mail messages or data, 19 and from which tasks can subsequently read the information. As in the case for semaphores, tasks which wait for data to arrive at an empty mailbox are put in a blocked state, and the action of a task that sends data to a mailbox which is being waited on by a blocked task will cause the blocked task to become ready. The commands sendmail and readmail are used to write into and read from mailboxes respectively. Mailboxes are often implemented in an executive as a queue so that the mailbox may hold more than one mail message at a time. Typically the message queue will be operated on a first in first out principle, and the maximum number of messages will be limited in order to control the size of the queue. 2.2.3 Timing Most executives use a real time clock to provide timing functions for the application tasks, and for functions which are internal to the executive. Timing functions are driven by a hardware timer within the target system which is initialized by the executive to continuously generate interrupts with a fixed period. The hardware timer will interface to the executive through an interrupt service routine, which may call a specific executive function which notifies it that a timer interrupt has occurred, and therefore that a specific period has elapsed. The executive may create a number of software timers from memory registers that it can initialize with count values, and may update each active counter when it is informed that a timer interrupt has occurred. If the executive finds that any of the active timers have timed out, it can arrange to set a semaphore associated with the timer in order to put a blocked task into the ready state. Tasks can therefore make use of several software timers under the control of the executive, each of which is synchronized to a single hardware timer. A special use of the timer by the executive is to implement a form of task scheduling called time slicing. This method is used to execute each ready task having the same priority for a fixed time. The tasks are executed one after the other in round robin fashion. 2.2.4 Memory Management An embedded microprocessor has a certain amount of read/write memory. In addition to the fixed memory requirements of each task and the executive, a task will need to use varied amounts of memory throughout the course of its execution. Because not all tasks require to use the maximum amount of memory at the same time, the executive will employ a memory manager that dynamically allocates areas of memory for use upon request by each task. The memory is a resource which must be shared by the tasks that run under the executive. 20 The organization of memory by the memory manager will vary between different executives. A common approach is to create a memory pool, where the pool is typically divided into a number of fixed size blocks in order to prevent it from becoming fragmented when variable sized blocks are allocated and subsequently returned. However, fixed size memory blocks can lead to uneconomical use of memory. To overcome this, many different memory pools may be defined, each of which can contain different fixed size blocks which correspond in general to the storage requirements of the tasks. An executive must be flexible in its use for different applications, and for different configurations of target hardware systems that have different memory maps and different hardware components such as timers and interrupt controllers. The executive typically consists of a core which implements the above features and a configuration program in which all application dependent features are defined. The configuration program is run during the initialization of the system and typically performs the following functions: • the creation and initialization of semaphores and mailboxes for the application tasks • the creation of a task control block for each task, which is then placed on the ready queue • the organization of memory pools • the creation of any software timers • the initialization of any hardware components The executive will then start to execute the highest priority task on the ready queue. 2.3 Conveyor Belt Control The functions of the controller are as follows: • Control conveyor speed • Count items conveyed The controller receives input from the keyboard and feedback from the encoder. The major task of the microprocessor system is to control the speed of the conveyor belt. The microprocessor also counts the number of items conveyed. The motor is controlled from the D/A output via a motor drive unit. The motor speed is measured with a shaft encoder on the opposite end of the conveyor belt. The encoder provides a stream of pulses whose frequency indicates the speed of the conveyor. The 21 desired speed of the conveyor is also indicated on the display. The keypad and the display are interfaced to the microprocessor via a parallel I/O port. The counting of objects on the conveyor is done using an optical encoder positioned in the middle of the conveyor belt. 2.3.1 Software The software performs a number of tasks which must co-operate in order to achieve the overall function required of the system. 1. Speed Control • measurement of encoder output • conversion of frequency to speed • calculate speed control output • display the speed To determine the speed control output, the system compares the speed of the shaft with the desired speed. The task here is to set the speed input. 2. Counting Number of items Conveyed • Count items • Display count 2.3.2 System Flowcharts Flowcharts provided on separate printout • Speed Control Is controlled by an interrupt, INT 1, from a timer. This activates the system. ISR 1 reads the counter value (from the shaft encoder output frequency). It also resets the counter and passes the counter value to the counter mailbox. TASK 1 reads the contents of the counter mailbox and converts the contents to a speed value. TASK 1 places the converted value in both the control mailbox and a display mailbox. The placing of the values into the control mailbox and the display mailbox causes a change of status value of TASK 2 and TASK 3 to a ready state. The execution of speed control is of more importance than the display of speed, so TASK 2 has a higher priority than TASK 3. 22 • Set Speed Input It is driven by the ISR response to INT 2. Though the keypad entry may be done at any point in time, the updating of the setting is not as critical as the execution of the speed control loop, thus the priority of TASK 4 is set lower than that of speed control. ISR 2 is executed each time a key is depressed. The key value is queued up in the key mailbox. The executive will not allow TASK 4 to execute until the main speed control is finished. TASK 4 reads the key value from the mailbox and stores that value in a buffer until the executive prompts the system to proceed. Task 4 converts the value stored in the buffer to a set-speed value and stores this in a memory area accessible to TASK 2. • Item Count It is initiated by INT 3, and only the occurrence of an interrupt needs to be signalled to TASK 5 in form of a pulse. ISR 3 makes use of a semaphore to trigger TASK 5 and, when executed, TASK 5 updates the software counter and TASK 6 displays the value. The system is initialized from idle, so the first action performed by each task is either to read the relevant mailbox or wait for a semaphore. As each task is executed, it is immediately placed in a blocked state, waiting for information. The speed control loop is triggered by an interrupt from the timer and the item count function is triggered by an input from the optical detector. 2.3.3 Algorithms ISR 1 (Frequency Measurement) disable timer interrupt stop timer sendmail(counter − mb, COUNT) zero counter return to ISR 1. TASK 1: (SPEED CONVERSION) COUNTER = readmail(counter-mb) convert COUNT to SPEED sendmail(control-mb, SPEED) sendmail(display-mb, SPEED) 23 Repeat TASK 2: (SPEED CONTROL) SPEED= readmail(control-mb) SETSPEED = readmail(setspeed-mb) compare SPEED and SETSPEED values calculate new CONTROL value output CONTROL to motor enable timer interrupt Repeat TASK 3: (SPEED DISPLAY) SPEED = readmail(display-mb) convert SPEED to display format display SPEED Repeat ISR 2: (READ KEY) Disable keypad interrupt read key KEY = key value sendmail(key-mb, KEY) enable interrupts Return to ISR 1 TASK 4: (ENTER SET-SPEED VALUE) KEY = readmail(key-mb) If KEY = ENTER then do convert BUFFER update SETSPEED else do display KEY 24 store KEY in BUFFER sendmail(setspeed-mb, SETSPEED) Repeat ISR 3: (Item Count) disable interrupts set semaphore(Item-sem) enable interrupts Return to ISR 1 TASK 5: (UPDATE ITEM COUNT) wait semaphore(Item-sem) increment ITEMCOUNT sendmail(itemcount-mb, ITEMCOUNT) Repeat TASK 6: (DISPLAY ITEM COUNT) VALUE = readmail(itemcount-mb) display VALUE Repeat CONFIGURATION PROGRAM) Create mailboxes: counter-mb, control-mb, display-mb, key-mb and itemcount-mb create semaphore: item-sem Create TCB: Task 1: Priority 10, Task 2: Priority 10..., Task 5: Priority 5 Initialise: CONTROL =0 Initialize: SPEED = 0 Initialize: SETSPEED = 0 Initialize: BUFFER Initialize: TIMER Output CONTROL to motor drive Display SPEED 25 Display Itemcount Enable Interrupts 26 3 COMMON ACTUATOR TYPES 3.1 3.1.1 Pneumatic Motors Pneumatic Motors: Continuous Rotation Pneumatic motors are not widely used for continuous rotation in mechatronic systems because of their intrinsically low efficiency and the difficulty in controlling their speed. Two basic types are in common use, vane and piston. Vane motors are used in pneumatic tools such as nut runners, where their high operating speed and compact format require the use of a multistage reduction gear. Piston-type pneumatic motors are used in V or in-line configuration as starter motors for diesel engine, where they do not need to be subject to any form of speed control beyond that which can be provided by a simple pressure control or flow restriction. Pneumatic motors in the radial piston configuration are used in applications where compressed air is the preferred working medium, such as in quarry rock drills, where the air can be used to clear the bit, or in driving agitators in chemical plants. Advantages 1. Intrinsically safe 2. Inherently torque limited by the available supply pressure 3. Robust against mechanical shock or jamming, especially when directly connected without reduction gears. Disadvantages 1. Very inefficient in terms of energy utilization (about 20% efficiency. 2. Require exhaust silencer 3. Speed is highly load dependent and control of speed can only be achieved by throttling. 3.1.2 Pneumatic Motors: Limited Rotation They are especially used in the generic configuration of a quarter-turn actuator. These are used to provide rotations of 90◦ or slightly more, and are often used in process plants 27 to operate fluid control valves where the movement range is between two fixed positions, typically on and off. There are two types available: vane and rack and pinion. The vane type provides slightly higher torque but at a higher cost. 3.2 Hydraulic Motors These are normally used where high torques are required and where space is limited. Applications Motor Type Low torque, low power applications Low Torque, medium power Medium Torque, medium power High Power Gear/ Vane Vane/ Axial Piston Axial Piston/ Radial Piston (Axial/ Radial Piston) Outward working Note that: • All hydraulic motors are reversible. • Hydraulic motors always work with a specified displacement, given in terms of volume/revolution (cm3 /revolution). • For proper working, there must be a close working clearance. This minimizes leakages. • All hydraulic motors are subject to leakages. This leads to the following expression for the efficiency: Nactual (1) ηH = Nideal 3.2.1 Gear Motors Are of fixed displacement, and therefore control of speed can only be exercised by controlling the oil flow rate to the motor. They are employed on low power drives. Due to internal leakage of oil across the tips of the teeth, through the mesh and across the end faces of the gears, these are the least efficient of hydraulic motors. 28 3.2.2 Vane Motors Are normally used for turning lightweight loads. Their main advantages are higher speed than gear motors, possibility of variable displacement configuration and lower tendency toward leakages since fluid is easier to contain. The motor is controlled by changing the eccentricity of the stroke ring. 3.2.3 Axial Piston Motors Are common in robotics applications. Two configurations are available: the bent axis machine and the swash plate motor. The bent axis machine has fixed displacement. The cylinders are connected to the plate using ball joints. The fluid in the individual pistons is varied such that the whole mechanism is set in rotation. The swash plate motor provides variable displacement. The pistons are used to control the movement of the swash plate, which is connected to the drive shaft in a manner that causes rotation of the drive shaft. The displacement of the drive shaft is varied by changing the slant angle of the swash plate. This configuration is used in remote control of robot arms. 3.2.4 Radial Piston Motor Rotation of the shaft is achieved by continuously varying the quantity of fluid within the pistons. The system operates with a specified amount of fluid stored in a reservoir, thus the total amount of fluid within the pistons remains constant. Advantages include the possibility of achieving higher torques since the number of pistons used can be increased. Speed may also be varied by shutting off some pistons (to increase speed) or enabling pistons. This configuration is not very common in mechatronic systems. 3.2.5 Advantages of Hydraulic Motors 1. High torque and high power achievable with low weight and bulk. 2. Hydraulic transmission systems are highly resistant to mechanical shock. 3. Acceptable in hazardous conditions, e.g. in areas with electrostatic interference. 4. The low speed varieties have low noise level. 5. Have the ability to remove, to a certain degree, heat and noise generated by the system. A heat exchanger may also be incorporated into the design. 29 3.2.6 Disadvantages 1. They require the provision of a power patch or hydraulic main. 2. The high speed varieties tend to produce a lot of noise. 3. The high torque, low speed motors have system costs that are much higher than electrical devices. 3.2.7 Control of Hydraulic Motors The majority of hydraulic transmissions employ one pump per hydraulic motor in the transmission circuit. The forces required at the pump, that is, power to drive the pump is much lower than the power that the motor imparts to the load. Characteristic At the constant torque boundary, the pump displacement is variable and the displace- Constant Torque Boundary (DP variable, DM limit) Constant Power Boundary (DP limit, DM variable) Torque Operating Region DP and DM limit Speed Torque/Speed characteristics for a combination of variable displacement pump and motor with pressure limitation ment of the motor is fixed. Along the constant power boundary, the pump displacement 30 Q Qlp Prime Mover Qlm Pump Motor Load is fixed but the motor displacement is variable. Hydraulic Transmission Nm Dp = Np Dm (2) where N is the rotational speed and D is the displacement. Dm Tm = Tp Dp (3) where T is the torque. The above represents the ideal case. Whereas the torque ratio is little affected by the small mechanical losses, apart from the case where the motor is near its minimum displacement, the speed ratio is significantly altered by the internal leakage flows QL . Thus, Nm Dm = ηhM ηhP Np Dp (4) ηhM = (Q − Qlm ) Q (5) ηhP = Q (Q + Qlp ) (6) where and The system is initialized by creating a pressure difference, e.g. by opening a valve. Hydraulic motors can be controlled using 4 strategies, based on the motor application: 31 1. Reeling and Winching: Torque is maintained constant. 2. Rapid Acceleration: Speed is varied inversely to Torque, i.e. T = is a constant for the motor in use. C , N where C 3. Hydrodynamic Machinery:Torque is made directly proportional to motor speed, i.e. T = CN 2 4. Sticky Conditions: The machine is started up using higher speeds than those required by the system. 3.3 3.3.1 Electric Motors DC Motors Motoring equation: Ea = V − Ia Ra Generating Equation: Ea = V + Ia Ra Back EMF: Ea = Kφω Torque: T = KφIa Braking methods: Regenerative, Resistive/Dynamic, Plugging/Current Reversal. Speed Control: Field Control and voltage control. DC Servo Motor : The circuit includes a tacho-generator to provide feedback. DC motors are mainly used for constant power supply. 3.3.2 Stepper Motors Are of three main types: • Variable reluctance- the rotor turns freely • Permanent magnet- the rotor locks in position • hybrid - produces a higher torque/volume ratio. Also tends to lock. Characteristic The pull in curve defines the combination of torques and stepping rates against which the motor can start or stop without losing steps. No-start regions are motor design parameters, and, for combinations of torques and stepping rates that fall within the no-start regions, the motor will NOT operate. Pull-out curve defines the maximum torque that the motor can provide once it is running without losing steps. 32 Torque Maximum starting Torque Pull-out torque curve Pull-in torque curve Stepping Rate Maximum starting rate No start regions 3.4 Maximum stepping rate Factors to Consider when Selecting Motors 1. Acceleration rate 2. Constant speed demand 3. Accurate speed control requirements 4. Probability of gearbox transmission requirements 5. Necessity to reverse the motor 6. Size and weight restrictions 7. Load inertia 8. Power demand by load (power rating of the motor) 9. Load duty cycle 10. Maximum motor speed 33 4 4.1 Measurement and Factors which Cause Errors Introduction Analysis of system response is based on the relationship between the desired output of a measurement system and the actual output. The performance of such a system involves both the static characteristics and the dynamic characteristics. Static characteristics involve constant input, or an input that varies slowly with time. Performance parameters for static characteristics include accuracy, precision, resolution, sensitivity, linearity, hysteresis, drift, overload capacity and impedance loading. Dynamic characteristics involve input that varies rapidly with time. Parameters will generally be represented by transfer functions applicable in the given situation. 4.2 Errors and Uncertainties in Performance Parameters Static performance parameters may be checked periodically by means of static calibrations. This involves imposing constant values of known inputs and observing the resulting output. In general, sensitivity of measurement may change due to certain perturbations which influence all output values, generally equally by a particular value. Such errors are caused by wear of parts, environmental effects or user settings. Equipment may not have the same output for repeated application of any particular value of input. This effect is called the scatter in output values. If scatter is within a given range, it results from random variation in the parameter of in the system of measurement. 4.3 4.3.1 Types of Errors Systematic or Cumulative Errors (System Bias) These are errors that tend to have the same magnitude and sign for a given set of conditions. Since they bear the same sign, they tend to accumulate. They alter the instrument reading by a fixed magnitude in the same direction, thus they are also referred to as system bias. Such errors are caused by: 34 1. Instrument Errors: Errors inherent in the system are mainly a result of design faults such as calibration, irregularities in internal components, etc. These can be avoided by selecting a suitable system for a given application as well as application of suitable correction after determination of amount of system error. It is also necessary to ensure calibration is done against a suitable standard. 2. Environmental Errors: These are due to variation of conditions outside the measuring device such as temperature, air pressure, humidity, magnetic or electrostatic field, wind forces, etc. 3. Loading Errors: These result from the act of measurement affecting the physical system being measured, e.g. a thermometer can change the thermal capacity of a system. Are mainly problematic in very sensitive systems. System errors can be eliminated or correlated. 4.3.2 Accidental or Random Errors These result from random variations in the parameter or system of measurement. Such errors vary in magnitude and sign, and tend to compensate each other due to varying signs. Such errors are detected by a lack of consistency in the measured value when the same input is imposed repeatedly on the measurement system. Random errors are caused by: 1. Inconsistencies associated with accurate measurement of small quantities. These are detected when very accurate/precise measurements are being made. Measurement of small variations may not be exact for systems calibrated with higher calibration values. 2. Presence of certain system defects. These include large dimensional tolerance in mating parts, resulting in backlash, and presence of friction. 3. Effect of unrestricted and randomly varying parameters. Uncontrolled disturbances may influence system output, for instance, line voltage fluctuations, vibration of instrument supports, etc. 4.3.3 Miscellaneous or Gross Errors Such errors are partly systematic and partly random. They include: 35 1. Human Errors: These are errors resulting from limitations in human senses, for instance, reading the meniscus either high or low (Systematic) or recording observed value slightly different from the actual reading (random). 2. Errors due to faulty components or adjustments: Misaligned or moving parts, electrical leakage, poor optics, etc, in the measuring system result in zero shift (system error) coupled with zero drift (random error). 3. Improper application of Instruments: Errors caused by use of instruments in conditions which do not conform to the desired design/operating conditions, e.g. temperatures, extreme vibrations, mechanical shock, electrical noise, etc all of which could introduce so much gross error as to mask the test information. 4.4 Types of Uncertainties Systematic errors are deterministic in nature, hence the effects of such errors can be eliminated by introducing suitable correction factors. Random errors represent a degree of uncertainty which can be evaluated from dispersion or scatter in data. However varied, scatter follows a Normal or Gaussian distribution, hence uncertainties can be quantified so as to increase the reliability of an experiment. 4.4.1 External Estimate of Uncertainty, UE It is assessed from the knowledge of the experiment, limitation of equipment, etc. A general rule applicable for such estimate is to take the resolution that is the smallest confidently measurable input change as the external estimate of uncertainty. 4.4.2 Internal Estimate of Uncertainty, UI This is uncertainty that is inherent in the data itself, and its quantitative assessment. 4.4.3 Propagation of Uncertainties in Compound Quantities In an experiment, the determination of a parameter (e.g. friction constant, coefficients, etc) is done using different measurements of different quantities. For instance, for the 36 formula F = m∗a, it is required to measure m and a more than once. Each measurement may constitute some uncertainties which will contribute to the overall uncertainty. Given a general equation: y = f (x1 , x2 , ..., xn ) (7) where y is a parameter dependent on variables x1 ...xn , the equation can be represented in differential form as: dy = ∂y ∂y ∂y dx1 + dx2 + . . . + dxn ∂x1 ∂x2 ∂xn (8) Taking the quantities dy, dx1 ,. . ., dxn to be uncertainties uy , ux1 ,. . . , uxn in the quantities y, x1 , . . . , xn . The equation becomes Uy = ∂y ∂y ∂y ux1 + ux2 + . . . + uxn ∂x1 ∂x2 ∂xn (9) The maximum value of uncertainty occurs when the combined uncertainties have the same sign, thus the worst possible case is: Uymax = ∂y ∂y ∂y ux1 + ux2 + . . . + uxn ∂x1 ∂x2 ∂xn (10) The probability of that occurring is very small. We therefore square the equation on both sides such that: " 2 2 2 # ∂y ∂y ∂y ∂y ∂y ∂y ∂y ux1 + ux2 + . . . + uxn (ux1 )(ux2 ) + . . . + (uxn−1 )(u Uy2 = + ∂x1 ∂x2 ∂xn ∂x1 ∂x2 ∂xn−1 ∂xn (11) Terms in the second bracket will tend to be very small quantities, and may be neglected. Thus, " # 21 2 2 ∂y ∂y Uy = ± (ux1 )2 + . . . + (uxn )2 (12) ∂x1 partialxn The overall internal estimate of uncertainty due to the combined effects of different variables can be expressed as: " (UI )overall = ± 2 n X ∂y i=1 37 ∂xi # 21 (uxi )2 (13) 5 Programmable Logic Controllers Controllers are used for various functions such as: • switching systems on or off • sequential control (for synchronizing and ordering) • feedback control (to enhance precision) • motion control (to vary rotational speeds of a system) Systems may be controlled using: • mechanical gadgets such as cams, governors, Geneva mechanism • electro-mechanical means, such as relays, timers and controllers • electronic gadgets such as electronic switches • computers, using Logic. PLCs were initially developed to replace mechanical systems. 5.1 PLC: Definition This is a digitally operating electronic gadget which uses a programmable memory for the internal storage of instructions by implementing specific functions such as logic, sequencing, timing and arithmetic to control various types of processes. A PLC is usually linked to its subject using either digital or analog links. 5.2 Components of a PLC System 1. Relay Switches: These are used to prompt the PLC, i.e. they provide the activation signal. 2. Contact Switches 3. Counters: May be either mechanical or digital. A counter has a count register, an accumulator and a relay contact. Digital counters output in the form of a relay contact when a prescribed or preassigned value is reached. 38 The count register stores the preassigned count value. The accumulator either increases or decreases the count each time an input pulse is received. When the accumulator value equals the register value, the relay contact is activated. 4. Timers: They consist of an internal clock, a count value register, an accumulator and a contact. Processes are normally synchronized by: • Event triggered synchronization, where sensors and switches are used to detect events. • Time controlled synchronization, where an event or a process is given a fixed time period to be completed. 5.3 PLC Architecture The PLC consists of 5 major parts: 1. the CPU (processor) 2. Memory (ROM, RAM, PROM, etc) 3. I/O interfaces 4. Power supply 5. Other peripherals 5.4 Ladder Diagram/Relay Logic/Contact Symbology This is a program written using symbols. It is used for control of processes and is a representation of a program that activates or deactivates events logically. A ladder diagram is composed of rungs with elements placed on each rung in series, parallel or combinations of both to represent logical inputs and outputs. In a ladder diagram, each rung must complete a circuit. The output of a rung is connected to a physical device which could be a motor, a light, a solenoid valve, etc. The output control is done by switches to form AND/OR logic. Different rungs are not connected except through the rails. In some PLC programming languages, each rung can have only one output. 39 The components in a ladder diagram consist of those used internally to construct the logic and device used to connect to physical outputs. Sometimes due to differences in operating voltages, the outputs sill not be connected physically to objects being controlled directly. 40