You are on page 1of 79

Chapter One

1.1 Introduction 1.2 Need and Scope of the Project

1.1 Introduction
Perimeter Intrusion Detection System (PIDS) is a combination of multiple systems that provide warning of intrusion into a protected facility. With PIDS in place, the Central Alarm Station operator can quickly detect intrusion into the facility, assess the situation and initiate the contingency plan to neutralize the adversary. According to IAEA categorization, PIDS comes under the realm of Physical Protection System (PPS). A Physical Protection System (PPS) has four basic function: Deterrence : Discouraging intrusion attempts by employing systems for imparting painful consequences Detection: Process in a PPS that begins with sensing a potentially malicious or otherwise unauthorized act which is completed with assessment of the cause of the alarm Access Delay: To increase adversary penetration time for entry into and/or exit from the nuclear facility or transport so as to allow time for response. Response: In event of detection the response force is dispatched to counter sabotage.

Out of these, PIDS is responsible for deterrence, detection and causing access delay.

1.2 Need and Scope of Project


Perimeter Intrusion Detection system forms a critical part of the security framework for many critical installations and facilities like Nuclear Power Plants, Military Headquarter, Airports etc. It detects intrusions into the perimeter of a protected facility. This necessitates a need for its frequent and periodic performance reliability testing.

There are two modes of testing: Local Testing: Local testing requires an individual to visit the site and examine the system hardware. Remote Testing: In a remote testing paradigm, test commands are relayed to the device under test from a Central Alarm Station. These test commands simulate various test conditions and results are monitored at the Central Alarm Station. Remote testing serves as a warning system. For further troubleshooting and diagnosis, local testing is required.

Chapter Two

Basic Block Diagrams 2.1 PIDS Architecture 2.2 Remote Testing System

2.1 PIDS Architecture

Fig 2.1 Block diagram of PIDS

Figure 2.1 shows a block diagram of Perimeter Intrusion Detection System (PIDS). Basic elements forming the PIDS are: High voltage (HV) and Low voltage (LV) lines. Energizer Cabinet Central Alarm Station Communication network

High voltage pulses and low voltage pulses are sent on alternate wires at small regular intervals.Any change in voltage of consecutive high and low voltage lines indicate intrusion, which are sensed by the Energizer Cabinet. A warning signal is relayed to the Central Alarm Station through RS485 bus, where the threat location is identified. Thereafter necessary actions may be taken.

2.2 Remote Testing System for PIDS

Fig 2.2

To ensure the detection capability of the system Remote Testing System is required. Test signals from the Central Alarm Station will be relayed to the Energizer Cabinet through RS485 serial interface. The components of the Energizer Cabinet communicate with each other to simulate intrusion and fault conditions and responses are monitored at the Central Alarm Station.

Chapter Three System Description

3.1 Hardware Description 3.1.1 3.1.2 3.1.3 3.1.4 PIDS Architecture Communication Network Remote Testing: Hardware Implementation LPC 21xx Overview

3.2 Software Description 3.2.1 Keil MDK-ARM Microcontroller Development Tool Kits

3.1 Hardware Description


3.1.1 PIDS Architecture

As mentioned above the functions of PIDS may be categorised into: Deterrence Detection Access Delay

In our PIDS architecture the perimeter to be secured is divided into small zones. These zones are 250m in length. PIDS employs thick conducting wires spaced at distance of 9.5cm-15cm apart. High voltage pulses and low voltage pulses are sent on alternate wires at small regular intervals. The wires act as both intrusion detectors and deterrent respectively in the following ways:

a. Any changes in voltage of consecutive high and low voltage pulses indicate intrusion. b. These energized fencing systems deter intruders with a non- lethal, short but painful electric shock if they come in contact with the fence.

Now let us take a look at the Energizer Cabinet.

Fig 3.1 Block Schematic of Energizer Cabinet

Energizer Cabinet The Energizer Cabinet is the brain of PIDS. Each Energizer cabinet is responsible for two zones. It performs the function of Alarm Communication to the Central Alarm Station. It consists of the following:

a. High Voltage (HV) Pulse Generator b. High Voltage (HV) monitoring Card c. Low Voltage (LV) generation and monitoring Card d. Alarm Communication Card

a. HV Pulse Generator A high-voltage pulse generator is an electronic device used to produce periodic high voltage pulses. Typically the peak voltage ranges from around 8kV to 10kV.The pulse duration is kept at120microsecondsand energy of a pulse is restricted to less than 5Joules so as to keep the system nonfatal. Unlike in the case of Low Voltage (LV) Card, HV pulse generator is built as a separate unit due to the following factors: It is power electronics based board SCRs, Pulse Transformer and capacitors are used. This makes the size of HV generator circuit big and complex. High power devices are more faults prone. So in case of faults, it is replacement is easy if it is a separate entity.

b. High Voltage (HV) Card HV Card is a LPC2138 based peripheral card which receives the HV pulses. The return HV pulses before entering the HV Card are attenuated to 3V.These pulses are then converted to digital form using 10 bit on-chip ADC. Pulses are constantly monitored. Any drastic change in the voltage levels of consecutive pulses indicate open or short circuiting of the wires, thus indicating intrusion. HV card responds by switching the appropriate relays, thus alerting the Alarm Communication Card.

c. Low Voltage(LV) Card LVCard is a LPC2138 based peripheral card for receiving return LV pulses having Low Voltage pulse generator on board. It generates pulses of 12V with pulse duration in milliseconds. Similar to operation in the HV Card, LV Card converts the incoming pulses into digital form and compares consecutive

pulses. Any drastic change in the voltage levels of consecutive pulses indicate open or short circuiting of the wires, thus indicating intrusion. LV card responds by switching the appropriate relays, thus thus alerting the Alarm Communication Card.

d. Alarm Communication Card The communication card is a LPC2129 based card connected to the LV Card and HV Card only through relay contacts. As the name suggests, its responsible for Alarm Communications .Following are the functions of the Alarm Communication Card: i. ii. iii. iv. Receive responses from the relays of LV Card and HV Card and forming alarm message frame Identify each zone by providing addresses. Communication with the Central Alarm Station through serial interfaces. Monitoring cabinet door status and battery voltage level

3.1.2

Communication Network

Between Communication Card and Central Alarm Station

Fig 3.2 PIDS Communication Network

The perimeter being secured by PIDS is of the order of many kilometres and is exposed to a very noisy environment. Covering such a huge area requires the PIDS to be distributed in nature. Due to absence of Line Of Sight (LOS) path between the Energizer Cabinet and the Central Alarm Station, wired interface is used for communication. Hence the interface to be used for PIDS communication network must fulfil the following requirements: Connect several Units(Energizer Cabinets) in a network structure Ability to communicate over longer distances Ability to communicate at faster communication rates as latency might lead to delayed warning and action High Noise Immunity

Taking into account all the above needs, the RS485 serial interface is used. Following are some specifications of RS485: ATTRIBUTE Cabling Physical Media Number of devices Communications modes Maximum distance Maximum data rate Signalling Mark condition Space condition (data (data = = SPECIFICATION Multi-drop Twisted Pair 32 32 receivers half duplex 4000 feet @ 100 kbps 10 Mbps @ 50 feet Balanced 1) 1.5 V to 5 V(A is greater than B) 0) 5 V to1.5 V(B is greater than A) 250 mA transmitters

Driver output current capability

Table 3.1

Fig 3.3 Typical RS485 Two-Wire Multidrop Network

Interface between Communication Card, HV and LV Cards

HV and LV cards on detection of intrusion change the state of their respective relays. These relay contacts are connected to the ports of microcontroller of Communication Card. Thus relay contacts are the only medium of communication between Communication Card, HV and LV Cards.

3.1.3

Remote Testing: Hardware Implementation

The main essence in the hardware implementation of remote testing is establishing communication between Communication Card, HV Card and LV Card. Other hardware requirements such as communication link between Communication Card and Central Alarm Station is already available as a part of PIDS. Various options explored for communication between different cards (microcontrollers) are: 1) (Inter Integrated Circuit) I2C interface 2) Serial Peripheral Interface

1) I2C (Inter Integrated Circuit) Interface The I2C-bus is a synchronized multi-master bus. This means that more than one device capable of controlling the bus can be connected to it. The two I2C signals are serial data (SDA) and serial clock (SCL) Both SDA and SCL are bi-directional lines, connected to a positive supply voltage via a current-source or pull-up. When the bus is free, both lines are HIGH.

Fig 3.4 Example of an I2C bus configuration using two microcontrollers

Bit Transfer

Fig 3.5 Bit Transfer

When clock line SCL=1, data is accessed from SDA line. Data changes on SDA take place when SCL=0. Addressing A standard I2C device is identified with a 7-bit address. This makes the total number of devices to be 128. Data Transfer The master begins the communication by issuing the start condition (S). The master continues by sending a unique 7-bit slave device address, with the most significant bit (MSB) first. The eighth bit after the start, read/not-write (), specifies whether the slave is now to receive (0) or to transmit (1). This is followed by an ACK bit issued by the receiver, acknowledging receipt of the previous byte. Then the transmitter (slave or master, as indicated by the bit) transmits a byte of data starting with the MSB. At the end of the byte, the receiver (whether master or slave) issues a new ACK bit. This 9-bit pattern is repeated if more bytes need to be transmitted.

Fig. 3.6 Master-transmitter addressing a slave receiver with a 7-bit address

Fig. 3.7 A master reads a slave immediately after the first byte

2) Serial Peripheral Interface Bus Serial Peripheral Interface (SPI) is a hardware/firmware communication protocol .The Serial Peripheral Interface or SPI-bus is a simple 4-wire serial communications interface used by many microprocessor/microcontroller peripheral chips that enables the controllers and peripheral devices to communicate with each other. Even though it is developed primarily for the communication between host processor and peripherals, a connection of two processors via SPI is just as well possible. The SPI bus, which operates at full duplex (means, signals carrying data can go in both directions simultaneously), is a synchronous type data link setup with a Master / Slave interface and can support up to 1 Mega baud or 10Mbps of speed. Both single-master and multi-master protocols are possible in SPI. But the multi-master bus is rarely used. The SPI Bus is usually used only on the PCB. However, its possible to use the SPI Bus outside the PCB at low speeds, but this is not quite practical.

Data and control lines of the SPI and the basic connection: An SPI protocol specifies 4 signal wires. 1. Master Out Slave In (MOSI) - MOSI signal is generated by Master, recipient is the Slave. 2. Master In Slave Out (MISO) - Slaves generate MISO signals and recipient is the Master. 3. Serial Clock (SCLK or SCK) - SCLK signal is generated by the Master to synchronize data transfers between the master and the slave. 4. Slave Select (SS) from master to Chip Select (CS) of slave - SS signal is generated by Master to select individual slave/peripheral devices. The SS/CS is an active low signal. There may be other naming conventions such as Serial Data In [SDI] in place of MOSI and Serial Data Out [SDO] for MISO.

Fig 3.8 Single Master Single Slave SPI Implementation Among these four logic signals, two of them MOSI & MISO can be grouped as data lines and other two SS & SCLK as control lines. As we already know, in SPI-bus communication there can be one master with multiple slaves. In singlemaster protocol, usually one SPI device acts as the SPI Master and controls the data flow by generating the clock signal (SCLK) and activating the slave it wants to communicate with slave-select signal (SS), then receives and or transmits data via the two data lines. A master, usually the host micro controller, always provides clock signal to all devices on a bus whether it is selected or not. The usage of these each four pins may depend on the devices. For example, SDI pin may not be present if a device does not require an input (ADC for example), or SDO pin may not be present if a device does not require an output (LCD controllers for example). If a microcontroller only needs to talk to 1 SPI Peripheral or one slave, then the CS pin on that slave may be grounded. With multiple slave devices, an independent SS signal is needed from the master for each slave device. Data transfer mechanism The communication is initiated by the master all the time. The master first configures the clock, using a frequency, which is less than or equal to the maximum frequency that the slave device supports. The master then select the desired slave for communication by pulling the chip select (SS) line of that particular slave-peripheral to "low" state. If a waiting period is required (such as for analog-to-digital conversion) then the master must wait for at least that period of time before starting to issue clock cycles.

Fig 3.9 Shift Register used The slaves on the bus that has not been activated by the master using its slave select signal will disregard the input clock and MOSI signals from the master, and must not drive MISO. That means the master selects only one slave at a time. Most devices/peripherals have tri-state outputs, which goes to high impedance state (disconnected) when the device is not selected. A full duplex data transmission can occur during each clock cycle. That means the master sends a bit on the MOSI line; the slave reads it from that same line and the slave sends a bit on the MISO line; the master reads it from that same line.

Fig 3.10 Hardware Setup for communication using two shift registers

Data transfer is organized by using Shift register with some given word size such as 8- bits in both master and slave. They are connected in a ring. While master shifts register value out through MOSI line, the slave shifts data in to its shift register. Data are usually shifted out with the MSB first, while shifting a new LSB into the same register. After that register has been shifted out, the master and slave have exchanged their register values. Then each device takes that value and does the necessary operation with it (for example, writing it to memory). If there are more data to be exchanged, the shift registers are loaded with new data and the process is repeated. When there are no more data to be transmitted, the master stops its clock. Normally, it then rejects the slave. There is a "multiple byte stream mode" available with SPI bus interface. In this mode the master can shift bytes continuously. In this case, the slave select (SS) is kept low until all stream process gets finished. SPI devices sometimes use another signal line to send an interrupt signal to a host CPU. Some of the examples for these type of signals are pen-down interrupts from touch-screen sensors, thermal limit alerts from temperature sensors, alarms issued by real time clock chips, and headset jack insertions from the sound codec in a cell phone.

Bit Transfer SPI is a single-master communication protocol. This means that one central device initiates all the communications with the slaves. When the SPI master wishes to send data to a slave and/or request information from it, it selects slave by pulling the corresponding SS line low and it activates the clock signal at a clock frequency usable by the master and the slave. The master generates information onto MOSI line while it samples the MISO line.(Refer to the diagram on the next page)

Fig 3.11 A simple SPI communication: Data bits on MISO and MOSI toggle on the SCLK falling edge and are sampled on the SCLK rising edge.

SPI communication modes Four communication modes are available (MODE 0, 1, 2, 3) that basically define the SCLK edge on which the MOSI line toggles, the SCLK edge on which the master samples the MISO line and the SCLK signal steady level (that is the clock level, high or low, when the clock is not active). Each mode is formally defined with a pair of parameters called clock polarity (CPOL) and clock phase (CPHA). SPI mode 0 1 2 3 CPOL 0 0 1 1 CPHA 0 1 0 1

Fig 3.12 SPI Communication Modes If the phase of the clock is zero (i.e. CPHA = 0) data is latched at the rising edge of the clock with CPOL = 0, and at the falling edge of the clock with CPOL = 1. If CPHA = 1, the polarities are reversed. Data is latched at the falling edge of the clock with CPOL = 0, and at the rising edge with CPOL = 1. The micro-controllers allow the polarity and the phase of the clock to be adjusted. A positive polarity results in latching data at the rising edge of the clock. However data is put on the data line already at the falling edge in order to stabilize. Most peripherals, which can only be slaves, work with this configuration. If it should become necessary to use the other polarity, transitions are reversed. SPI does not define any maximum data rate, not any particular addressing scheme; it does not have a acknowledgement mechanism to confirm receipt of data and does not offer any flow control. Actually, the SPI master has no knowledge of whether a slave exists, unless something additional is done outside the SPI protocol. SPI does not care about the physical interface characteristics like the I/O voltages and standard used between the devices. Initially, most SPI implementation used a noncontinuous clock and byte-by-byte scheme. But many variants of the protocol now exist, that use a continuous clock signal and an arbitrary transfer length.

Reasons for using SPI over I2C bus: Flexibility SPI is very easy to understand and to implement and offers a great deal of flexibility for extensions and variations. SPI is considered as a good platform for building custom protocol stacks for communication between ICs. So, according to the engineers need, using SPI may need more work but offers increased data transfer performance and almost total freedom. The amount of sophistication can be controlled according to the application. Throughput / Speed:

If data must be transferred at high speed, SPI is clearly the protocol of choice, over IC because of the following reasons: i. ii. SPI is full-duplex; IC is not. SPI does not define any speed limit; implementations often go over 10 Mbps. IC is limited to 1Mbps in Fast Mode+ and to 3.4 Mbps in High Speed Mode - this last one requiring specific I/O buffers which are not always easily available. iii. Less overhead due to lack of addressing

Noise Immunity One possible disadvantage of I2C is higher noise sensitivity and along with it, lower data integrity. I2C uses a read/write bit which follows the initial 7 address bits to tell a peripheral whether data should be read or written. In addition I2C is level sensitive - in contrast to SPI, which are edge sensitive. This means that I2C samples data during the high or low phase of a bit and you can easily envision that noise could flip the read/write bit. SPI peripherals on the other hand implement read and write operations via explicit commands send over the bus, making selecting the "wrong" operation less likely. Hardware Simplicity Unlike I2C, SPI bus lines do not have open drain or open collector configurations. Hence no external pull up resistors have to be used.

LPC21xx Overview
In this section those features of LPC21xx are presented which are used in the project 1. Features of LPC21xx 16-bit/32-bit ARM7TDMI-S microcontroller in a 64 or 144 pin package. 8/16/64 kB of on-chip static RAM and 64/128/256 kB of on-chip flash program memory (except for flashless LPC2210/20/90). 128-bit wide interface/accelerator enables highspeed 60 MHz operation. Diversified Code Read Protection (CRP) enables different security levels to be implemented. InSystem/In-Application Programming (ISP/IAP) via on-chip boot loader software. Single flash sector or full chip erase in 100 ms and programming of 256 bytes in 1 ms. External 8, 16, or 32-bit bus (144 pin packages). Embedded ICE RT and Embedded Trace offer real-time debugging with the on-chip Real Monitor software and high speed tracing of instruction execution. Up to four interconnected CAN interfaces with advanced acceptance filters. 10-bit A/D converter providing four/eight analog inputs with conversion times as low as 2.44 ms per channel and dedicated result registers to minimize interrupt overhead. Two 32-bit timers/external event counters with four capture and four compare channels each, PWM unit (6 outputs), Real Time Clock (RTC), and watchdog. Multiple serial interfaces including two UARTs (16C550), a fast I2C-bus (400 kbit/s), and two SPI interfaces. Vectored interrupt controller with configurable priorities and vector addresses. Up to forty-eight 5 V tolerant fast general purpose I/O pins. Up to 12 edge or level sensitive external interrupt pins available. 60 MHz maximum CPU clock available from programmable on-chip PLL with a possible input frequency of 10 MHz to 25 MHz and a settling time of 100 ms. For flashless LPC2210/20/90 only: 60 MHz (LPC2210/90), 72 MHz (LPC2290/01), or 75 MHz (LPC2210/01 and LPC2220) maximum CPU clock available from programmable on-chip PhaseLocked Loop (PLL) with settling time of 100 s. On-chip integrated oscillator operates with an external crystal in the range from 1 MHz to 25 MHz and with an external oscillator up to 50 MHz. Two power saving modes, idle mode and Power-down mode. Peripheral clock scaling and individual enable/disable of peripheral functions for additional power optimization.

Processor wake-up from Power-down mode via external interrupt or CAN controllers. Dual power supply: CPU operating voltage range of 1.65 V to 1.95 V (1.8 V 8.3 %). I/O power supply range of 3.0 V to 3.6 V (3.3 V 10 %) with 5 V tolerant I/O pads.

Fast GPIO ports enable port pin toggling up to 3.5 times faster than the original device. They also allow for a port pin to be read at any time regardless of its function. Dedicated result registers for ADC reduce interrupt overhead. The ADC pads are 5 V tolerant when configured for digital I/O function(s). UART0/1 include fractional baud rate generator, auto-bauding capabilities, and handshake flowcontrol fully implemented in hardware. Buffered SSP serial controller supporting SPI, 4-wire SSI, and Microwire formats. SPI programmable data length and master mode enhancement. General purpose timers can operate as external event counters.

2. Pin configuration for 64-pin packages

Fig 3.13 LPC21xx Pin Configuration

Table 3.2 LPC21xx Pin description

Table 3.2 LPC21xx Pin description

Table 3.2 LPC21xx Pin description

Table 3.2 LPC21xx Pin description

3. Pin connect block The purpose of the Pin connect block is to configure the microcontroller pins to the desired functions. The pin connect block allows selected pins of the microcontroller to have more than one function. Configuration registers control the multiplexers to allow connection between the pin and the on chip peripherals. Peripherals should be connected to the appropriate pins prior to being activated, and prior to any related interrupt(s) being enabled. Activity of any enabled peripheral function that is not mapped to a related pin should be considered undefined. Selection of a single function on a port pin completely excludes all other functions otherwise available on the same pin. The only exception is the inputs to the A/D converter. Regardless of the function that is selected for the port pin that also hosts the A/D input, this A/D input can be read at any time, and variations of the voltage level on this pin will be reflected in the A/D readings. However, valid analog reading(s) can be obtained if and only if the analog input function is selected. Only then the proper interface circuit is active in between the physical pin and the A/D module. In all other cases, the logic necessary for the digital function will be active and will disrupt proper behavior of the A/D.

The PINSEL registers control the functions of device pins as shown below. Pairs of bits in these registers correspond to specific device pins.

Table 3.3 Pin function Select register bits The direction control bit in the IO0DIR/IO1DIR register is effective only when the GPIO function is selected for a pin. For other functions, direction is controlled automatically. Each derivative typically has a different pinout and therefore a different set of functions possible for each pin. Details for a specific derivative may be found in the appropriate datasheet.

Register description The Pin Control Module contains 3 registers as shown below:

Table 3.4 Pin connect block register map

Pin function Select register 0 (PINSEL0 - 0xE002 C000) The PINSEL0 register controls the functions of the pins using the settings listed below. The direction control bit in the IO0DIR register is effective only when the GPIO function is selected for a pin. For other functions, direction is controlled automatically.

Table 3.5 Pin function Select register 0

Table 3.5 Pin function Select register 0

Pin function Select register 1 (PINSEL1 - 0xE002 C004) The PINSEL1 register controls the functions of the pins using the settings listed below. The direction control bit in the IO0DIR register is effective only when the GPIO function is selected for a pin. For other functions, direction is controlled automatically.

Table 3.6 Pin function Select register 1

Table 3.6 Pin function Select register 1

Pin function Select register 2 (PINSEL2 - 0xE002 C014) The PINSEL2 register controls the functions of the pins using the settings listed below. The direction control bit in the IO1DIR register is effective only when the GPIO function is selected for a pin. For other functions direction is controlled automatically.

Table 3.7 Pin function Select register 2

Table 3.7 Pin function Select register 2

4. General Purpose I/O (GPIO) Features Every physical GPIO port can be accessed either through registers providing enhanced features and accelerated port access or through legacy registers providing backward compatibility to earlier LPC2000 devices. Accelerated Fast GPIO functions: o GPIO registers are relocated to the ARM local bus so that the fastest possible I/O timing can be achieved. o Mask registers allow treating sets of port bits as a group, leaving other bits unchanged. o All registers are byte, half-word, and word addressable. o The entire port value can be written in one instruction. Bit-level set and clear registers allow a single instruction set or clear of any number of bits in one port. Direction of each pin can be controlled individually. All I/O default to inputs after reset. Backward compatibility with other earlier devices is maintained with legacy registers appearing at the original addresses on the APB bus. Pin description

Table 3.8 GPIO Pin Description Register description LPC21xx devices have two 32-bit General Purpose I/O ports. PORT0 and PORT1 are controlled by two groups of 4 registers as shown below Legacy registers shown in Table 3.9 allow backward compatibility with earlier family devices, using existing code. The functions and relative timing of older GPIO implementations is preserved. The registers in Table 3.10 represent the enhanced Fast GPIO features available on the PORT0 and PORT1 only. All of these registers are located directly on the local bus of the CPU for the fastest possible read and write timing. An additional feature has been added that provides byte and half-word

addressability of all GPIO registers. A mask register allows treating groups of bits in a single GPIO port separately from other bits on the same port. When PORT0 and/or PORT1 are used, the user must select whether these ports will be accessed via registers that provide enhanced features or a legacy set of registers. While both of a ports fast and legacy GPIO registers are controlling the same physical pins, these two port control branches are mutually exclusive and operate independently. For example, changing a pins output through a fast register will not be observable trough the corresponding legacy register. The following text will refer to the legacy GPIO as "the slow" GPIO, while GPIO equipped with the enhanced features will be referred as "the fast" GPIO. The "slow", legacy registers are word accessible only. The fast GPIO registers are byte, half-word, and word accessible.

Table 3.9 GPIO register map (legacy APB accessible registers)

Table 3.10 GPIO register map (local bus accessible registers - enhanced GPIO features)

5. Serial Peripheral Interface LPC21xx by default has two SPI interfaces SPI0 and SPI1. Features Two complete and independent SPI controllers Compliant with Serial Peripheral Interface (SPI) specification Synchronous, serial, and full duplex communication Combined SPI master and slave Maximum data bit rate of one eighth of the input clock rate 8 bit only or 8 to 16 bit per transfer

SPI peripheral details

There are four registers that control the SPI peripheral. The SPI control register contains a number of programmable bits used to control the function of the SPI block. The settings for this register must be set up prior to a given data transfer taking place. The SPI status register contains read only bits that are used to monitor the status of the SPI interface, including normal functions, and exception conditions. The primary purpose of this register is to detect completion of a data transfer. This is indicated by the SPIF bit. The remaining bits in the register are exception condition indicators. These exceptions will be described later in this section. The SPI data register is used to provide the transmit and receive data bytes. An internal shift register in the SPI block logic is used for the actual transmission and reception of the serial data. Data is written to the SPI data register for the transmit case. There is no buffer between the data register and the internal shift register. A write to the data register goes directly into the internal shift register. Therefore, data should only be written to this register when a transmit is not currently in progress. Read data is buffered. When a transfer is complete, the receive data is transferred to a single byte data buffer, where it is later read. A read of the SPI data register returns the value of the read data buffer. The SPI clock counter register controls the clock rate when the SPI block is in master mode. This needs to be set prior to a transfer taking place, when the SPI block is a master. This register has no function when the SPI block is a slave. The I/Os for this implementation of SPI are standard CMOS I/Os. The open drain SPI option is not implemented in this design. When a device is set up to be a slave, its I/Os are only active when it is selected by the SSEL signal being active.

Master operation

The following sequence describes how to process a data transfer with the SPI block when it is set up as the master. This process assumes that any prior data transfer has already completed.

1. Set the SPI clock counter register to the desired clock rate. 2. Set the SPI control register to the desired settings. 3. Write the data to transmitted to the SPI data register. This write starts the SPI data transfer. 4. Wait for the SPIF bit in the SPI status register to be set to 1. The SPIF bit will be set after the last cycle of the SPI data transfer. 5. Read the SPI status register. 6. Read the received data from the SPI data register (optional). 7. Go to step 3 if more data is required to transmit.

Note: A read or write of the SPI data register is required in order to clear the SPIF status bit. Therefore, if the optional read of the SPI data register does not take place, a write to this register is required in order to clear the SPIF status bit.

Slave operation

The following sequence describes how to process a data transfer with the SPI block when it is set up as slave. This process assumes that any prior data transfer has already completed. It is required that the system clock driving the SPI logic be at least 8X faster than the SPI. 1) Set the SPI control register to the desired settings. 2) Write the data to transmit to the SPI data register (optional). Note that this can only be done when a slave SPI transfer is not in progress. 3) Wait for the SPIF bit in the SPI status register to be set to 1. The SPIF bit will be set after the last sampling clock edge of the SPI data transfer. 4) Read the SPI status register. 5) Read the received data from the SPI data register (optional). 6) Go to step 2 if more data is required to transmit.

Note: A read or write of the SPI data register is required in order to clear the SPIF status bit. Therefore, at least one of the optional reads or writes of the SPI data register must take place, in order to clear the SPIF status bit. Exception conditions

a) Read Overrun

A read overrun occurs when the SPI block internal read buffer contains data that has not been read by the processor, and a new transfer has completed. The read buffer containing valid data is indicated by the SPIF bit in the status register being active. When a transfer completes, the SPI block needs to move the received data to the read buffer. If the SPIF bit is active (the read buffer is full), the new receive data will be lost, and the read overrun (ROVR) bit in the status register will be activated.

b) Write Collision

As stated previously, there is no write buffer between the SPI block bus interface, and the internal shift register. As a result, data must not be written to the SPI data register when a SPI data transfer is currently in progress. The time frame where data cannot be written to the SPI data register is from when the transfer starts, until after the status register has been read when the SPIF status is active. If the SPI data register is written in this time frame, the write data will be lost, and the write collision (WCOL) bit in the status register will be activated. c) Mode Fault The SSEL signal must always be inactive when the SPI block is a master. If the SSEL signal goes active, when the SPI block is a master, this indicates another master has selected the device to be a slave. This condition is known as a mode fault. When a mode fault is detected, the mode fault (MODF) bit in the status register will be activated, the SPI signal drivers will be de-activated, and the SPI mode will be changed to be a slave.

d) Slave Abort

A slave transfer is considered to be aborted, if the SSEL signal goes inactive before the transfer is complete. In the event of a slave abort, the transmit and receive data for the transfer that was in progress are lost, and the slave abort (ABRT) bit in the status register will be activated.

Pin description

Table 3.11 SPI pin description

Register description The SPI contains 5 registers as shown below. All registers are byte, half word and word accessible.

Table 3.12 SPI register map

I.

SPI Control Register (S0SPCR - 0xE002 0000 and S1SPCR - 0xE003 0000)

The SPCR register controls the operation of the SPI as per the configuration bits setting.

Table 3.13 SPI Control Register

Table 3.13 SPI Control Register

II.

SPI Status Register (S0SPSR - 0xE002 0004 and S1SPSR - 0xE003 0004)

The SPSR register controls the operation of the SPI as per the configuration bits setting.

Table 3.14 SPI Status Register

III.

SPI Data Register (S0SPDR - 0xE002 0008, S1SPDR - 0xE003 0008)

This bi-directional data register provides transmit and receive data for the SPI. Transmit data is provided to the SPI by writing to this register. Data received by the SPI can be read from this register. When a master, a write to this register will start a SPI data transfer. Writes to this register will be blocked from when a data transfer starts to when the SPIF status bit is set, and the status register has not been read.

Table 3.15 SPI Data Register

SPI Clock Counter Register (S0SPCCR - 0xE002 000C and S1SPCCR - 0xE003 000C) This register controls the frequency of a masters SCK. The register indicates the number of SPI peripheral clock cycles that make up an SPI clock. In Master mode, this register must be an even number greater than or equal to 8. Violations of this can result in unpredictable behaviour. The SPI SCK rate may be calculated as: PCLK / SnSPCCR value. The PCLK rate is CCLK /APB divider rate as determined by the APBDIV register contents. In Slave mode, the SPI clock rate provided by the master must not exceed 1/8 of the peripheral clock. The content of the S0SPCCR register is not relevant.

Table 3.16 SPI Clock Counter Register SPI Interrupt Register (S0SPINT - 0xE002 001C and S1SPINT - 0xE003 001C) This register contains the interrupt flag for the SPI interface.

Table 3.17 SPI Interrupt Register

Architecture The block diagram of the SPI solution implemented in SPI0 and SPI1 interface is shown below.

Fig 3.14 SPI Block Diagram

3.2 Software Description


This section is going to deal with the software tools used for accomplishing the project.

3.2.1 Keil MDK-ARM Microcontroller Development Tool Kits The Keil MDK-ARM Microcontroller Development Tool Kit (MDK-ARM) generates embedded applications for many popular ARM-powered devices. The tools allow engineers to write software programs in assembly language or in a high-level language (like C or C++) and to create a complete application that can be programmed into a microcontroller or other memory device. The MDK-ARM development tools are designed for the professional software developer, but any level of programmer can use them to get the most out of the ARM7/9 and Cortex-M microcontroller. Software Development Cycle with MDK-ARM The software development cycle is roughly the same with Vision as it is with any other development tool: 1. Create a new project, select the target chip from the Device Database, and configure the tool settings. 2. Create source files and write the code in C, C++, or Assembly. 3. Build the application with the project manager. 4. Correct the errors. 5. Test the application.

The block diagram below illustrates the build process and the involved components:

Fig 3.15 Software Development Process

1. Vision4 Integrated Development Environment (IDE) The Vision4 IDE is a window-based software development platform combining a robust editor, project manager, and make facility. Vision4 supports all the Keil MDK-ARM tools including C/C++ compiler, macro assembler, linker, library manager, and object-HEX converter. Use Vision4 to create source files and organize them into a project that defines the target application. Vision4 automatically compiles, assembles, and links the application. It provides a single focal point for your development efforts. Features:

Project Manager to create and maintain projects. Device Database for selecting a device and configuring the development tools for that particular microcontroller. Make facility for assembling, compiling, and linking your embedded applications. Rich-featured Source Code Editor. Template Editor that is used to insert common text sequences or header blocks. Source Browser for rapidly exploring code objects, locating, and analyzing data in your application. Function Browser for quickly navigating between functions in your program. Function Outlining for controlling the visual scope within a source file. Built-in utilities, such as Find in Files and functions for commenting and uncommenting source code. Simulator and Target Debugger are fully integrated. Configuration Wizard providing graphical editing for microcontroller startup-code and configuration files. Interface to configure Software Version Control Systems and third-party utilities. Flash Programming Utilities dialog. Dialogs for tool settings and target configurations. Online Help that links to microcontroller data sheets and user guides.

Vision4 GUI

Fig 3.16

In Debug Mode, Vision offers the following windows and dialogs: Breakpoints Call Stack & Local Window Code Coverage : Allows defining stop conditions for program execution. : Shows objects that are currently in the call tree. : Provides statistics about code execution, including branch testing.

Command Window Disassembly window Event Viewer Execution Profiler Instruction Trace Window

: Allows entering and viewing executed commands. : Allows program testing at the level of assembly instructions. : Displays a history of task-switching events. : Displays time and call statistics on instruction level. : shows the instruction history for devices not based on a Cortex-M processor. : Displays value changes of peripherals, registers, and variables on a time graph. Displays the memory areas and their access rights. Displays and allows modifying memory content. Displays time and call statistics on module and function level. Shows and allows modifying the register content. Provides a communication interface between the application and the PC. Shows debugging status information. Shows debug symbol information of the application program. displays peripheral register information. Provides configurable buttons commands interactively. for executing debugging

Logic Analyzer

Memory Map Memory Window Performance Analyzer Registers Window Serial Window

: : : : :

Status Bar Symbols Window System Viewer Toolbox

: : : :

Trace Data Window

Shows the instruction history for Cortex-M processor-based devices. Scrolls through captured trace records. Displays and allows modifying program variable values at runtime.

Trace Navigation Watch Window

: :

2. C/C++ Compiler and Macro Assembler Source files are created with the Vision4 IDE are passed to the C/C++ compiler or macro assembler. The compiler and assembler process the source files and create relocatable object files. i.

Features of ARM C/C++ Compiler (armcc)

ARM and Thumb generation modes can be mixed in the same source file. ARM mode allows faster code execution, making it ideal for interrupt handlers. Thumb mode provides the smallest code size. Industry leading code size optimizations achieves memory cost savings by generating the smallest compiled code size. Industry leading code performance optimizations reduces power consumption by enabling increased through-put without clock speed increases. Function Attributes for Hardware Support gives access to ARM hardware features. Embedded Assembler code can be inserted into C functions. This capability is useful for fast DSP and other signal-processing algorithms. The ARM compiler supports full program optimization even when embedded assembler is used. Function Inlining to speed-up execution of frequently called functions. Such functions are expanded without the overhead associated with the function call, parameter passing, and return. Parameter Passing in CPU Registers used automatically by the ARM compiler to pass most function arguments. It can even pass and return small C structs into and from registers. Run-time Library routines are mostly reentrant and can be invoked from the main program and from interrupts. Special protection schemes for library calls are not needed. IEEE 754 Compliant Single and Double Precision Floating-point for high accuracy floating-point support.

ii.

Features of ARM Macro Assembler (armasm)

Standard Macro Processor supports assembler macros to repeat or automate assembler instruction sequences. Conditional Assembler Controls control the assembler source code to create multiple target applications from the same source file(s). Source Listing with Symbol Reference file includes an optional cross reference that provides detailed information about the assembled source file.

3. Library Manager The library manager allows creating a library from the object files created by the compiler and assembler. Libraries have a special format and are ordered collections of object modules. Libraries can be used by the linker at a later time. When the linker processes a library, it links only those object modules that are necessary to create the program. Features of ARM Library Manager (armar)

Module Management library files provide a convenient way to combine and reference a large number of modules that can be used by the linker. Library files can be built with Vision.

Variable and Function Reference; modules from libraries are extracted and added to programs only if required. Modules containing routines that are not invoked by the program are not included in the final output. Security, Speed, and Minimized Disk Space; Libraries provide a vehicle for distributing large numbers of functions and routines without distributing the original source code.

4. Linker/Locator The linker/locator creates an absolute ELF/DWARF file using the object modules extracted from libraries and those created by the compiler and assembler. An absolute object file or module contains no relocatable code or data. All code and data reside at fixed memory locations. The absolute ELF/DWARF file can be used:

To program a Flash ROM or other memory devices. With the Vision Debugger for target debugging and simulation. Features of ARM Linker (armlink)

Detailed Listing File that is easy to understand is created by the linker. It contains details like the memory configuration, input modules, memory map, symbol table, and cross reference. Global Code Listing file that shows symbolic disassembly of the generated code is created by the linker. Static Stack Analysis for stack requirements at link-time is calculated by the linker.

5. Real-Time Library The Real-Time Library (RL-ARM) is a collection of tightly-coupled libraries designed to solve the real-time and communication challenges of embedded systems based on ARM powered microcontroller devices. Features:

RTX Real-Time Kernel - Royalty-free, deterministic RTOS with source code. TCP/IP Networking Suite - Complete embedded networking suite. Flash File System - Create and modify files in memory or storage devices. CAN Interface - Drivers for common ARM-based MCU devices. USB Device Interface - for standard Windows device classes. Examples and templates - quickly begin using RL-ARM components. Integrated tool and configuration support in MDK-ARM. All RL-ARM components are supplied Royalty-Free.

While it is possible to implement an embedded program without using a real-time kernel or middleware components, a proven library like RL-ARM solves several common challenges for the embedded developer.

6. Vision4 Debugger The Vision Debugger is ideally suited for fast, reliable program debugging. The debugger includes a high-speed Simulator capable of simulating external hardware and most on-chip peripherals. The chip attributes are set automatically when selecting the device from the Device Database.

Chapter Four Software Development

4.1 Overview 4.2 Master Implementation 4.3 Slave Implementation

4.1 Overview

Fig4.1 Remote Testing System is implemented by enabling communication between Communication Card and HV, LV Cards. A test Protocol Data Unit (PDU) of 7 bytes is sent from the Central Alarm Station to the Communication Cards addressed sequentially. The PDU is as shown below: EOF CB SOF CAB TB RSB : : : HLSB Start of Frame Communication Card Address Bits Test Bits HV or LV card Selection Bits Relay Selection Bits Checksum Bits End of Frame TB CAB SOF

HLSB : RSB CB EOF : : :

All the communication cards receive the PDU. But only the one to which it is addressed accepts it. To simulate the test conditions, another PDU of 4 bytes containing the relay number is formed from the 7 bytes received. This is implemented by the update( ) in the Master program. The PDU formed is as shown below: EOF CB SOF RSB CB EOF : : : : Start of Frame Relay Selection Bits Checksum Bits End of Frame RSB SOF

Depending on the HLSB (HV or LV card Selection Bits) byte the PDU is sent to either HV or LV card. The 4 byte PDUs are sent to HV or LV by Serial Peripheral Interface (SPI), the rationale behind selection of which has been mentioned earlier in Hardware description (Section 3.1.3). The SPI bus is a synchronous type data link setup with a Master / Slave interface details of which are provided in the Hardware Description (Section 3.1.3) .The Communication Card is the Master and the HV and LV Cards the two slaves.

4.2 Master implementation

For the Master, following three states are defined to indicate different conditions: READY: Ready for transmission ERROR: Occurrence of error conditions (MODF,WCOL, ROVR) and erroneous PDU transmission DONE: Successful transmission of PDU In the Communication Card, the 7 byte PDU is received and stored in UART_RxData[]. The transmission and reception pointers are initialized. From UART_RxData[], update() forms the 4 byte PDU to be transferred to the Slave (LV Card or HV Card) and stores it in TxData[].The actual data transfer is carried out by the SPItx(). SPItx() This function first calls Initialize ().Initialize () prepares the SPI for tramsmission.It performs the following tasks: i. ii. iii. iv. v. vi. Configuring microcontroller in SPI mode. Configuring the SPI registers for Master Mode setup, Clock set up and Interrupt Enable (optional). Select the proper Slave using P0.0 & P0.1 (Other pins may be used if these arent available.) Configure the Vectored Interrupt Controller to enable SPI related interrupts.(Not used in our implementation) Set count=0 to start counting the number of bytes transferred. Set state=READY(To indicate that data transfer may be started )

Once state=READY, the byte to be transferred is placed in the SPI Data Register (S0SPDR). The transfer starts as soon as data is placed in S0SPDR.After the byte is transferred (a byte of data from Slave is also received) SPIF i.e. SPI Interrupt Flag is set. After the SPIF is set, SPIservice( ) is called to read the received byte and perform further processing. SPIservice( ) is also called in case of Mode Fault condition, where the Slave Select(SSEL) pin of Master is activated, thus making it a slave. If any error occurs during the PDU transfer, which is indicated by state=ERROR, the transmission and reception pointers are reinitialized and count is set to 0 for retransmission of the PDU. SPIservice() The Status Register (S0SPSR) is checked for Mode Fault, Write Collision, Read Overrun error conditions and state is accordingly changed to ERROR.

If no error occurs the default value of state is set to ERROR. The received bytes are checked for their expected acknowledgements. If the received acknowledgements match the correct sequence of expected values, the transmission and reception pointers are incremented and the state is changed to READY. After this, count is incremented and all the flags in S0SPSR are reset. Before returning to SPItx() the state is checked for ERROR or DONE (indicates successful transmission of 4 bytes).

main( )

Fig 4.2

SPItx( )

Fig 4.3

Initialize( )

Fig 4.4

SPIservice( )

Fig 4.5

next( )

Fig 4.6

4.3 Slave Implementation For the Slave, following three states are defined to indicate different conditions: READY: Ready for transmission ERROR: Occurrence of error conditions (ABRT, WCOL, ROVR) and erroneous PDU transmission DONE: Successful transmission of PDU The transmission and reception pointers are initialized. Pin number 31 which is the Slave Select pin is first configured as GPIO input. This pin is continuously monitored. As soon as it receives a zero logic, it changes its mode to SPI by calling Initialize(). Initialize() prepares the SPI for tramsmission.It performs the following tasks: i. ii. iii. iv. v. Configuring microcontroller in SPI mode. Configuring the SPI registers for Slave Mode setup and Interrupt Enable (optional). Configure the Vectored Interrupt Controller to enable SPI related interrupts.(Not used in our implementation) Set count=0 to start counting the number of bytes transferred. Set state=READY(To indicate that data transfer may be started )

Once state=READY, the byte to be transferred is placed in the SPI Data Register (S0SPDR). The transfer starts as soon as clock is received from the Master. After the byte is transferred (a byte of data from Master is also received) SPIF i.e. SPI Interrupt Flag is set. After the SPIF is set, SPIservice( ) is called to read the received byte and perform further processing. SPIservice( ) is also called in case of Data Abort condition, where the clock pulses issued to the Slave stops in between byte transfer. If any error occurs during the PDU transfer, which is indicated by state=ERROR, the transmission and reception pointers are reinitialized and count is set to 0 for retransmission of the PDU. SPIservice() The Status Register (S0SPSR) is checked for Data Abort, Write Collision, Read Overrun error conditions and state is accordingly changed to ERROR. If no error occurs the default value of state is set to ERROR. The received bytes are checked for their expected values. If the received bytes match the correct sequence of expected values, the transmission and reception pointers are incremented, state is changed to READY and proper acknowledge signals are sent to Master. The final acknowledgement (ACK byte) is sent after the correct reception of all the 4 bytes. The correctness is verified by matching the received checksum with the calculated one.

After this, count is incremented and all the flags in S0SPSR are reset. Before returning to main()the state is checked for ERROR or DONE (indicates successful transmission of 4 bytes)

main( )

Fig 4.7

Initialize( )

Fig 4.8

SPIservice( )

Fig 4.9

next( )

Fig 4.10

Chapter Five

Applications
The remote testing system designed here is tailor made for this specific PIDS but it may be extended to other security systems installed in critical establishments like Nuclear Power Plants, Military Headquarter, Airports, Banks and Treasuries etc. Other areas requiring a similar system include large scale sophisticated systems like factories, assembly lines, refineries and heavy machines where having such system would greatly help in problem detection and troubleshooting.

Chapter Six

Future scope
In the present project, Communication between two microcontrollers (Alarm Communication Card and monitoring Cards) has been implemented. Presently the test commands only test the healthiness of the relays. There are scope for many improvements, four of which are presented below: 1. Eliminating Relays Relays being electromechanical devices have moving parts. This may cause two problems: i. The age old problem of switch debounce. This is taken care of by extra hardware or through software in the Alarm communication Card. Moving parts in the relays are more prone to wear and tear and thus failure.

ii.

To deal with this, we can eliminate the relays entirely from the system. And the Communication Card will be notified of the intrusion through SPI bus, which is much faster and reliable because of absence of moving parts. Here the Monitoring cards will be Master and the Alarm Communication card will be the slave. 2. Implementing an RF based detection In future, if HV and LV based detection system is to be replaced by RF based detection, alarm may be notified to the Alarm Communication Cards through the established SPI link as using relays may cause a higher level of RF interference than SPI transmission. Here the Monitoring cards will be Masters and the Alarm Communication card will be the slave. 3. Implementing CCTV system in PIDS Currently there is no method to differentiate between true alarms and false alarms. In case of intrusion a person has to go to the site for inspection. In future, CCTV cameras may be installed at all Energizer Cabinet sites, which will capture images at the respective zones and send them to the Central Alarm Station turn by turn through polling. There these images will be displayed zone-wise in succession.

A fiber optic network has to be laid down for image transmission. In event of detected intrusion, commands will be sent from Monitoring Cards (HV & LV) to the Alarm Communication Card to do the following things: i. Generate commands to Communication Cards, which have not detected anything to stop their image transmission (but basic communication still continues on RS485). This would require implementing protocols for enabling communication between Communication Cards and ii. In case intrusion is detected at multiple zones, the ones which havent detected any intrusion will be told to stop image transmission .And the ones which have detected intrusion will send the images on being polled(for image transmission).For this a flexible polling mechanism has to implemented at the Central Alarm Station. Thus by installing CCTV cameras images can be captured at the respective zones and thus identification of true or false alarm can be done. 4. Scenario IV When implementing PIDS, HV Monitoring and LV monitoring may be done in following ways: i. ii. Activate the HV lines only on intrusion detection by the LV lines. This would lead to power savings. When implemented in residential environments, only LV cards can be used as high voltage electric shock from HV lines pose a health hazard. Use LV cards in the daytime, when everyone is alert to respond to theft attempts and use HV lines at night for deterrence.

iii.

Bibliography

1. UM10114-LPC21xx and LPC22xx User manual 2. UM10120-LPC2131/2/4/6/8 User manual 3. ARM System Developers Guide By Andrew Sloss, Dominic Symes & Chris Wright 4. The Insider's Guide To The Philips ARM7-Based Microcontrollers By Trevor Martin 5. http://www.keil.com/dd/chip/3648.htm 6. http://www.keil.com/support/man/docs/uv4/ 7. http://www.keil.com/support/man/docs/gsac/ 8. http://www.embeddedrelated.com/groups/lpc2000/1.php 9. http://www.ucpros.com/work%20samples/Microcontroller%20Communication%20Interfaces%20 1.htm 10. http://www.eeherald.com/section/design-guide/esmod1.html 11. http://www.eetimes.com/discussion/beginner-s-corner/4023816/Introduction-to-I2C 12. http://www.byteparadigm.com/kb/article/AA-00255/22/Introduction-to-SPI-and-IC-protocols.html 13. The I2C-Bus Specification Version 2.1 January 2000 by Philips Semiconductors (now NXP) 14. http://www.dansaks.com/articles.htm 15. http://embeddedgurus.com/barr-code/ 16. http://www.eetimes.com/EELife/BlogCollection?contentItemId=27&pageNumber=1

You might also like