Anda di halaman 1dari 67

Design and Realization of Modbus Protocol

CHAPTER 1 INTRODUCTION
With the rapid development of the embedded computer technology, the new generation of industrial automation data acquisition and monitoring system, which takes the high performance of embedded microprocessor as its core, adapts well to the application system. It meets the strict requests of the function, reliability, cost, size and power consumption, etc. In the industrial automation application system, the Modbus communication protocol is widespread industrial standard and is used in massive industrial equipments, including DCS, PLC, RTU and the intelligent instrument, etc. Modbus is a serial communications protocol used with programmable logic controllers (PLCs). It is the de facto standard communications protocols in the industry, and it is amongst the most commonly available means of connecting industrial electronic devices.

1.1 LITERATURE SURVEY


MODBUS is an application layer messaging protocol, positioned at level 7 of the OSI model that provides client/server communication between devices connected on different types of buses or networks. The industrys serial de facto standard since 1979, MODBUS continues to enable millions of automation devices to communicate. Today, support for the simple and elegant structure of MODBUS continues to grow. The Internet community can access MODBUS at a reserved system port 502 on the TCP/IP stack. MODBUS is a request/reply protocol and offers services specified by function codes. MODBUS function codes are elements of MODBUS request/reply PDUs. The objective of this document is to describe the function codes used within the framework of MODBUS transactions. MODBUS is an application layer messaging protocol for client/server communication between devices connected on different types of buses or networks. It is currently implemented using: TCP/IP over Ethernet. See MODBUS Messaging Implementation Guide V1.0a. Asynchronous serial transmission over a variety of media (wire : EIA/TIA-232-E, EIA422, EIA/TIA-485-A; fiber, radio, etc.) MODBUS PLUS, a high speed token passing network.

Department of ECE | CMRIT

Design and Realization of Modbus Protocol

1.2 PROJECT OBJECTIVE


The aim of the project is to reach the demand of the embedded data acquisition monitoring system of the industrial automation application, an embedded data acquisition monitoring platform based on Modbus protocol is designed in this paper. The serial port Modbus master protocol is realized, which includes two kinds of communication mode: ASCII and RTU. As a result, communicating with various serial Modbus salve protocol equipments can be satisfied. The Modbus master realized by this embedded platform is stable and reliable. It has excellent prospect in the embedded data acquisition monitoring system of new automation applications. The Modbus master is implemented with ARM7 processor and the slaves are implemented with the 8051 microcontrollers. The physical media used between the Master and slaves is RS485.

1.3 EXISTING SYSTEM


The current communication system offer a unicast type of communication between the devices connected on the network. And the number of devices connected to the network is also restricted to a small number. The current communication system does not offers the master and slave communication due to which the effective reception of data is not guaranteed. The implementation is also complex which makes it difficult to understand.

1.4 PROPOSED SYSTEM


MODBUS Protocol is a messaging structure developed by Modicon in 1979, used to establish master-slave/client-server communication between intelligent devices. It is a de factostandard, truly open and the most widely used network protocol in the industrial manufacturing environment. The MODBUS protocol provides an industry standard method that MODBUS devices use for parsing messages. Modbus is a serial communications protocol published by Modicon and generally used with PLCs (programmable logic controllers). It has now become a factory standard for communications protocols in industry, and is the most commonly used means of communicating industrial devices. The main reasons for the extensive use of Modbus over other communications protocols are:

It is open source protocol and its free. It is simple to understand, easy to implement.

Department of ECE | CMRIT

Design and Realization of Modbus Protocol

It moves raw bits or words without placing many restrictions on vendors Modbus allows for serial communication between many third party devices connected to

the same network, for e.g. a system that measures temperature and humidity and communicates the results to a computer or number of VFDs communicating to PLC over a single Modbus serial line. Each device intended to communicate using Modbus is given a unique address. Maximum of 247 stations can be connected on a Modbus network. Maximum length of wire is limited to 1200mtr. Generally Master/slave configuration used for Modbus.

1.5 BLOCK DIAGRAM


The basic block diagram of our project is given by figure 1.1 which includes the basic modules used in the project and also describes the flow of information between these modules

Fig 1.1 Block diagram

Department of ECE | CMRIT

Design and Realization of Modbus Protocol

CHAPTER 2 LPC 2148 MICROCONTROLLER


2.1 INTRODUCTION
ARM7 family includes the ARM7TDMI, ARM7TDMI-S, ARM720T, and ARM7EJ-S processors. The ARM7TDMI core is the industrys most widely used 32-bit embedded RISC microprocessor solution. Optimized for cost and power-sensitive applications, the ARM7TDMI solution provides the low power consumption, small size, and high performance needed in portable, embedded applications. The ARM7TDMI-S core is the synthesizable version of the ARM7TDMI core, available in both VERILOG and VHDL, ready for compilation into processes supported by in-house or commercially available synthesis libraries. The ARM720T hard macro cell contains the ARM7TDMI core, 8kb unified cache, and a Memory Management Unit (MMU) that allows the use of protected execution spaces and virtual memory. This macro cell is compatible with leading operating systems including Windows CE, Linux, palm OS, and SYMBIAN OS.

2.2 ARM 7 FAMILY


The ARM7EJ-S processor is a synthesizable core that provides all the benefits of the ARM7TDMI low power consumption, small size, and the thumb instruction set while also incorporating ARMs latest DSP extensions and Jazelle technology, enabling acceleration of javabased applications. Compatible with the ARM9, ARM9E, and ARM10 families, and Strong-Arm architecture software written for the ARM7TDMI processor is 100% binarycompatible with other members of the ARM7 family and forwards-compatible with the ARM9, ARM9E, and ARM10 families, as well as products in Intels Strong ARM and xscale architectures. This gives designers a choice of software-compatible processors with strong price-performance points. Support for the ARM architecture today includes: Operating systems such as Windows CE, Linux, palm OS and SYMBIAN OS. More than 40 real-time operating systems, including qnx, Wind Rivers vxworks and mentor graphics vrtx.

Department of ECE | CMRIT

Design and Realization of Modbus Protocol

Fig 2.1 ARM7TDMI Core Diagram

Figure 2.1 shows the ARM7TDMI Core Diagram. The ARM7TDMI core is based on the Non Neumann architecture with a 32-bit data bus that carries both instructions and data. Load, store, and swap instructions can access data from memory. Data can be 8-bit, 16-bit, and 32-bit.

Department of ECE | CMRIT

Design and Realization of Modbus Protocol

2.3 ARM7TDMI PROCESSOR CORE


The ARM7TDMI processor core implements the ARMv4T Instruction Set Architecture (ISA).This is a superset of the ARMv4 ISA which adds support for the 16-bit Thumb instruction set. Software using the Thumb instruction set is compatible with all members of the ARM Thumb family, including ARM9, ARM9E, and ARM10families 2.3.1 REGISTERS The ARM7TDMI core consists of a 32-bit data path and associated control logic. This data path contains 31 general-purpose 32-bit registers, 7 dedicated 32-bit registers coupled to a barrel-shifter, Arithmetic Logic Unit, and multiplier. 2.3.2 MODES AND EXCEPTIONS The ARM7TDMI supports seven modes of operation: User mode Fast Interrupt (FIQ) Interrupt (IRQ) Supervisor mode Abort mode Undefined mode and System mode.

All modes other than User are privileged modes. These are used to service hardware interrupts, exceptions, and software interrupts. Each privileged mode has an associated Saved Program Status Register (SPSR). This register is use to save the state of the Current Program Status Register (CPSR) of the task immediately before the exception occurs. In these privileged modes, mode-specific banked registers are available. These are automatically restored to their original values on return to the previous mode and the saved CPSR restored from the SPSR. System mode does not have any banked registers. It uses the User mode registers. System mode runs tasks that require a privileged processor mode and allows them to invoke all classes of exception. 2.3.3 PROCESSOR STATES The ARM7TDMI processor can be in one of two states: ARM state

Department of ECE | CMRIT

Design and Realization of Modbus Protocol In ARM state, 16 general registers and one or two status registers are accessible at any one time. The ARM state register set contains 16 directly accessible registers: R0 to R15. All of these except R15 are general-purpose, and may be used to hold either data or address value the registers available to the programmer in each mode, in ARM state, are illustrated in fig 2.2.

Fig 2.2 Register Organization in ARM state

Department of ECE | CMRIT

Design and Realization of Modbus Protocol

Fig 2.3 Register Organization in THUMB state

Department of ECE | CMRIT

Design and Realization of Modbus Protocol In figure 2.3 the thumb state registers are shown. The THUMB state register set is a subset of the ARM state set. The programmer has direct access to eight general registers, R0-R7, as well as the Program Counter (PC), a stack pointer register (SP), a link register (LR), and the CPSR. There are banked Stack Pointers, Link Registers and Saved Process Status Registers (SPSRs) for each privileged mode. The registers available to the programmer in each mode, in THUMB state, are illustrated in Figure.3.3 Register Organization in THUMB state. 2.3.4 AMBA BUS ARCHITECTURE The ARM7 Thumb family processors are designed for use with the Advanced Microcontroller Bus Architecture (AMBA) multi-master on-chip bus architecture. AMBA is an open standard that describes a strategy for the interconnection and management of functional blocks that makes up a System-on-Chip (SoC). The AMBA specification defines three buses: Advanced System Bus (ASB) Advanced High-performance Bus (AHB) Advanced Peripheral Bus (APB).

ASB and AHB are used to connect high-performance system modules. APB offers a simpler interface for low-performance peripherals. 2.3.5 ADVANTAGES Small Dice Lower Power Consumption Simple decoding Higher performance Easy to implement an effective pipelined structure Performance depends on compiler Poor code density RISC has a fixed size of instruction format Small number of instructions

2.3.6 DISADVANTAGES

2.3.7 APPLICATIONS Using the ARMv7 architecture, ARM can strengthen its position as a low-

Department of ECE | CMRIT

Design and Realization of Modbus Protocol power/performance leader while conquering new markets to carry its cores up in high performance and down in the low-cost high-volume domain of the microcontroller ARM designs the technology that lies at the heart of advanced digital products, from wireless, networking and consumer entertainment solutions to imaging, automotive, security and storage devices. ARM's comprehensive product offering includes 16/32-bit RISC microprocessors, data engines, 3D processors, digital libraries, embedded memories, peripherals, software and development tools, as well as analog functions and high-speed connectivity products

2.4 LPC2148 MICROCONTROLLER


LPC2148 microcontroller board based on a 16-bit/32-bit ARM7TDMI-S CPU with realtime emulation and embedded trace support, that combine microcontrollers with embedded highspeed flash memory ranging from 32 kB to 512 kB. A 128-bit wide memory interface and unique accelerator architecture enable 32-bit code execution at the maximum clock rate. For critical code size applications, the alternative 16-bit Thumb mode reduces code by more than 30% with minimal performance penalty. The meaning of LPC is Low Power Low Cost microcontroller. This is 32 bit microcontroller manufactured by Philips semiconductors (NXP).Due to their tiny size and low power consumption, LPC2148 is ideal for applications where miniaturization is a key requirement, such as access control and point-of-sale. The Thumb sets 16-bit instruction length allows it to approach twice the density of standard ARM code while retaining most of the ARMs performance advantage over a traditional 16-bit processor using 16-bit registers. This is possible because Thumb code operates on the same 32-bit register set as ARM code. Thumb code is able to provide up to 65 % of the code size of ARM, and 160 % of the performance of an equivalent ARM processor connected to a 16-bit memory system. 2.4.1 FEATURES OF LPC2148 MICROCONTROLLER 16-bit/32-bit ARM7TDMI-S microcontroller in a tiny LQFP64 package. 8 kB to 40 kB of on-chip static RAM and 32 kB to 512 kB of on-chip flash memory; 128-bit wide interface/accelerator enables high-speed 60 MHz operation. In-System Programming/In-Application Programming (ISP/IAP) via on-chip boot loader software, single flash sector or full chip erase in 400 ms and programming of 256 B in 1 ms Embedded ICE RT and Embedded Trace interfaces offer real-time debugging with the on-chip Real Monitor software and high-speed tracing of

Department of ECE | CMRIT

10

Design and Realization of Modbus Protocol instruction execution. USB 2.0 Full-speed compliant device controller with 2 kB of endpoint RAM. In addition, the LPC2148 provides 8 kB of on-chip RAM accessible to USB by DMA. One or two (LPC2141/42 Vs, LPC2144/46/48) 10-bit ADCs provide a total of 6/14 analog inputs, with conversion times as low as 2.44 ms per channel. Single 10-bit DAC provides variable analog output (LPC2148 only) Two 32-bit timers/external event counters (with four capture and four compare channels each), PWM unit (six outputs) and watchdog. Low power Real-Time Clock (RTC) with independent power and 32 kHz clock input Multiple serial interfaces including two UARTs (16C550), two Fast I2C-bus (400 kbit/s), SPI and SSP with buffering and variable data length capabilities. Up to 45 of 5 V tolerant fast general purpose I/O pins in a tiny LQFP64 Package. Up to 21 external interrupt pins available. PLL with settling time of 100 ms. On-chip integrated oscillator operates with an external crystal from 1 MHz to 25 MHz and Power saving modes include Idle and Power-down Individual enable/disable of peripheral functions as well as peripheral clock scaling for additional power optimization. Processor wake-up from Power-down mode via external interrupt or BOD. CPU operating voltage range of 3.0 V to 3.6 V (3.3 V 10 %) with 5 V tolerant I/O. 60 MHz maximum CPU clock available from programmable on-chip

Department of ECE | CMRIT

11

Design and Realization of Modbus Protocol

2.4.2 LPC2148 Microcontroller ARCHITECTURE In the following figure 2.4, the architecture of the LPC2148 microcontroller is shown.

Fig 2.4 LPC2148 Microcontroller Architecture

Department of ECE | CMRIT

12

Design and Realization of Modbus Protocol 2.4.3 PIN DIAGRAM The pin diagram of the LPC2148 microcontroller is show in the below figure 2.5. The LPC2148 microcontroller has 2 ports and each port comprises of 32 pins. So in total the microcontroller has 64 pins.

Fig 2.5 LPC2148 Microcontroller Pin Diagram

Department of ECE | CMRIT

13

Design and Realization of Modbus Protocol 2.4.4 ARCHITECTURAL OVERVIEW The ARM7TDMI-S is a general purpose 32-bit microprocessor, which offers high performance and very low power consumption. The ARM architecture is based on Reduced Instruction Set Computer (RISC) principles, and the instruction set and related decode mechanism are much simpler than those of micro programmed Complex Instruction Set Computers (CISC). This simplicity results in a high instruction throughput and impressive real-time interrupt response from a small and cost-effective processor core. Pipeline techniques are employed so that all parts of the processing and memory systems can operate continuously. Typically, while one instruction is being executed, its successor is being decoded, and a third instruction is being fetched from memory. The ARM7TDMI-S processor also employs a unique architectural strategy known as Thumb, which makes it ideally suited to highvolume applications with memory restrictions, or applications where code density is an issue. The key idea behind Thumb is that of a super-reduced instruction set. Essentially, the ARM7TDMI-S processor has two instruction sets: The standard 32-bit ARM set. A 16-bit Thumb set. The Thumb sets 16-bit instruction length allows it to approach twice the density of standard ARM code while retaining most of the ARMs performance advantage over a traditional 16-bit processor using 16-bit registers. This is possible because Thumb code operates on the same 32-bit register set as ARM code. Thumb code is able to provide up to 65 % of the code size of ARM, and 160 % of the performance of an equivalent ARM processor connected to a 16-bit memory system. The particular flash implementation in the LPC2141/42/44/46/48 allows for full speed execution also in ARM mode. It is recommended to program performance critical and short code sections (such as interrupt service routines and DSP algorithms) in ARM mode. The impact on the overall code size will be minimal but the speed can be increased by 30% over Thumb mode.

2.4.5 ON-CHIP FLASH PROGRAM MEMORY

Department of ECE | CMRIT

14

Design and Realization of Modbus Protocol The LPC2141/42/44/46/48 incorporates a 32kB, 64kB, 128kB, 256kB and 512kB flash memory system respectively. This memory may be used for both code and data storage. Programming of the flash memory may be accomplished in several ways. It may be programmed In System via the serial port. The application program may also erase and/or program the flash while the application is running, allowing a great degree of flexibility for data storage field firmware upgrades, etc. Due to the architectural solution chosen for an on-chip boot loader, flash memory available for users code on LPC2141/42/44/46/48 is 32 kB, 64 kB, 128 kB, 256 kB and 500 kB respectively. The LPC2141/42/44/46/48 flash memory provides a minimum of 100,000 erase/write cycles and 20 years of data-retention. 2.4.6 ON-CHIP STATIC RAM On-chip static RAM may be used for code and/or data storage. The SRAM may be accessed as 8-bit, 16-bit, and 32-bit. The LPC2141, LPC2142/44 and LPC2146/48 provide 8 kB, 16 kB and 32 kB of static RAM respectively. In case of LPC2146/48 only, an 8 kB SRAM block intended to be utilized mainly by the USB can also be used as a general purpose RAM for data storage and code storage and execution. 2.4.7 MEMORY MAP The LPC2141/42/44/46/48 memory map incorporates several distinct regions, as shown in Fig 4.4 Memory map. In addition, the CPU interrupt vectors may be remapped to allow them to reside in either flash memory (the default) or on-chip static RAM. 2.4.8 INTERRUPT CONTROLLER The Vectored Interrupt Controller (VIC) accepts all of the interrupt request inputs and categorizes them as Fast Interrupt Request (FIQ), vectored Interrupt Request (IRQ), and nonvectored IRQ as defined by programmable settings. The programmable assignment scheme means that priorities of interrupts from the various peripherals can be dynamically assigned and adjusted. Fast interrupt request (FIQ) has the highest priority. If more than one request is assigned to FIQ, the VIC combines the requests to produce the FIQ signal to the ARM processor. The fastest possible FIQ latency is achieved when only one request is classified as FIQ, because then the FIQ service routine does not need to branch into the interrupt service routine but can run from the interrupt vector location. If more than one request is assigned to the FIQ class, the FIQ service

Department of ECE | CMRIT

15

Design and Realization of Modbus Protocol routine will read a word from the VIC that identifies which FIQ source(s) is (are) requesting an interrupt. Vectored IRQs have the middle priority. Sixteen of the interrupt requests can be assigned to this category. Any of the interrupt requests can be assigned to any of the 16 vectored IRQ slots, among which slot 0 has the highest priority and slot 15 has the lowest. Non-vectored IRQs have the lowest priority. The VIC combines the requests from all the vectored and non-vectored IRQs to produce the IRQ signal to the ARM processor. The IRQ service routine can start by reading a register from the VIC and jumping there. If any of the vectored IRQs are pending, the VIC provides the address of the highest-priority requesting IRQs service routine, otherwise it provides the address of a default routine that is shared by all the non-vectored IRQs. The default routine can read another VIC register to see what IRQs are active. Each peripheral device has one interrupt line connected to the Vectored Interrupt Controller, but may have several internal interrupt flags. Individual interrupt flags may also represent more than one interrupt source. 2.4.9 PIN CONNECT BLOCK 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. The Pin Control Module with its pin select registers defines the functionality of the microcontroller in a given hardware environment. After reset all pins of Port 0 and 1 are configured as input with the following exceptions: If debug is enabled, the JTAG pins will assume their JTAG functionality; if trace is enabled, the Trace pins will assume their trace functionality. The pins associated with the I2C0 and I2C1 interface are open drain. 2.4.10 FAST GENERAL PURPOSE PARALLEL I/O (GPIO) Device pins that are not connected to a specific peripheral function are controlled by the GPIO registers. Pins may be dynamically configured as inputs or outputs. Separate registers allow setting or clearing any number of outputs simultaneously. The value of the output register may be read back, as well as the current state of the port pins.

Department of ECE | CMRIT

16

Design and Realization of Modbus Protocol LPC2141/42/44/46/48 introduces accelerated GPIO functions over prior LPC2000 devices: GPIO registers are relocated to the ARM local bus for the fastest possible I/O timing. Mask registers allow treating sets of port bits as a group, leaving other bits unchanged. All GPIO registers are byte addressable. 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 control of individual bits. Separate control of output set and clear. All I/O default to inputs after reset. 2.4.11 UARTs The LPC2141/42/44/46/48 each contains two UARTs. In addition to standard transmit and receive data lines, the LPC2144/46/48 UART1 also provide a full modem control handshake interface. Compared to previous LPC2000 microcontrollers, UARTs in LPC2141/42/44/46/48 introduce a fractional baud rate generator for both UARTs, enabling these microcontrollers to achieve standard baud rate such as 115200 with any crystal frequency above 2 MHz. In addition, auto-CTS/RTS flow-control functions are fully implemented in hardware (UART1 in LPC2144/46/48 only). 16 byte Receive and Transmit FIFO. Register locations conform to 550 industry standard. Receiver FIFO triggers points at 1, 4, 8, and 14 bytes Built-in fractional baud rate generator covering wide range of baud rates without a need for external crystals of particular values. Transmission FIFO control enables implementation of software (XON/XOFF) Flow control on both UARTs. LPC2144/46/48 UART1 equipped with standard modem interface signals. This Module also provides full support for hardware flow control (auto-CTS/RTS).

Department of ECE | CMRIT

17

Design and Realization of Modbus Protocol 2.4.12 I2C-BUS SERIAL I/O CONTROLLER The LPC2141/42/44/46/48 each contains two I2C-bus controllers. The I2C-bus is bidirectional, for inter-IC control using only two wires: a serial clock line (SCL), and a serial data line (SDA). Each device is recognized by a unique address and can operate as either a receiver-only device (e.g., an LCD driver or a transmitter with the capability to both receive and send information (such as memory)). Transmitters and/or receivers can operate in either master or slave mode, depending on whether the chip has to initiate a data transfer or is only addressed. The I2C-bus is a multi-master bus; it can be controlled by more than one bus master connected to it. The I2C-bus implemented in LPC2141/42/44/46/48 supports bit rates up to 400 k bit/s (Fast I2C-bus) Compliant with standard I2C-bus interface. Easy to configure as master, slave, or master/slave. Programmable clocks allow versatile rate control. Bidirectional data transfer between masters and slaves Multi-master bus (no central master). Arbitration between simultaneously transmitting masters without corruption of serial data on the bus. Serial clock synchronization allows devices with different bit rates to communicate via one serial bus. Serial clock synchronization can be used as a handshake mechanism to suspend and resume serial transfer. The I2C-bus can be used for test and diagnostic purposes. 2.4.13 SPI serial I/O controller The LPC2141/42/44/46/48 each contains one SPI controller. The SPI is a full duplex serial interface, designed to handle multiple masters and slaves connected to a given bus. Only a single master and a single slave can communicate on the interface during a given data transfer. During a data transfer the master always sends a byte of data to the slave, and the slave always sends a byte of data to the master. Compliant with Serial Peripheral Interface (SPI) specification.

Department of ECE | CMRIT

18

Design and Realization of Modbus Protocol Synchronous, Serial, Full Duplex, Communication. Combined SPI master and slave. Maximum data bit rate of one eighth of the input clock rate. 2.4.14 SSP SERIAL I/O CONTROLLERs The LPC2141/42/44/46/48 each contains one SSP. The SSP controller is capable of operation on a SPI, 4-wire SSI, or Micro wire bus. It can interact with multiple masters and slaves on the bus. However, only a single master and a single slave can communicate on the bus during a given data transfer. The SSP supports full duplex transfers, with data frames of 4 bits to 16 bits of data flowing from the master to the slave and from the slave to the master. Often only one of these data flows carries meaningful data. Compatible with Motorolas SPI, TIs 4-wire SSI and National Semiconductors Micro wire buses. Synchronous serial communication. Master or slave operation. 8-frame FIFOs for both transmit and receive. Four bits to 16 bits per frame. 2.4.15 GENERAL PURPOSE TIMERS/EXTERNAL EVENT COUNTERS The Timer/Counter is designed to count cycles of the peripheral clock (PCLK) or an externally supplied clock and optionally generate interrupts or perform other actions at specified timer values, based on four match registers. It also includes four capture inputs to trap the timer value when an input signals transitions, optionally generating an interrupt. Multiple pins can be selected to perform a single capture or match function, providing an application with or and and, as well as broadcast functions among them. The LPC2141/42/44/46/48 can count external events on one of the capture inputs if the minimum external pulse is equal or longer than a period of the PCLK. In this configuration, unused capture lines can be selected as regular timer capture inputs, or used as external interrupts. A 32-bit timer/counter with a programmable 32-bit prescaler. External event counter or timer operation. Four 32-bit capture channels per timer/counter that can take a snapshot of the

Department of ECE | CMRIT

19

Design and Realization of Modbus Protocol timer value when an input signals transitions. A capture event may also optionally generate an interrupt.

CHAPTER 3 AT89C51MICROCONTROLLER
3.1 Description
AT89C51RD2/ED2 is high performance CMOS Flash version of the 80C51 CMOS single chip 8-bit microcontroller. It contains a 64-Kbyte Flash memory block for code and for data. The 64-Kbytes Flash memory can be programmed either in parallel mode or in serial mode with the ISP capability or with software. The programming voltage is internally generated from the standard VCC pin. The AT89C51RD2/ED2 retains all of the features of the Atmel 80C52 with 256 bytes of internal RAM, a 9-source 4-level interrupt controller and three timer/counters. The AT89C51ED2 provides 2048 bytes of EEPROM for nonvolatile data storage. In addition, the AT89C51RD2/ED2 has a Programmable Counter Array, an XRAM of 1792bytes, a Hardware Watchdog Timer, SPI interface, Keyboard, a more versatile serial channel that facilitates multiprocessor communication (EUART) and a speed improvement mechanism(X2 Mode). The fully static design of the AT89C51RD2/ED2 allows reducing system power consumption by bringing the clock frequency down to any value, including DC, without loss of data. The AT89C51RD2/ED2 has 2 software-selectable modes of reduced activity and an 8-bit clock prescaler for further reduction in power consumption. In the Idle mode the CPU is frozen while the peripherals and the interrupt system are still operating. In the Power-down mode the RAM is saved and all other functions are inoperative. The added features of the AT89C51RD2/ED2 make it more powerful for applications that need pulse width modulation, high speed I/O and counting capabilities such as alarms, motor control, corded phones, and smart card readers.
Table 3.1 Memory Size and I/O Pins

Department of ECE | CMRIT

20

Design and Realization of Modbus Protocol

3.2 Features

80C52 Compatible 8051 Instruction Compatible Six 8-bit I/O Ports (64 Pins or 68 Pins Versions) Four 8-bit I/O Ports (44 Pins Version) Three 16-bit Timer/Counters 256 Bytes Scratch Pad RAM 9 Interrupt Sources with 4 Priority Levels Integrated Power Monitor (POR/PFD) to Supervise Internal Power Supply ISP (In-System Programming) Using Standard VCC Power Supply 2048 Bytes Boot ROM Contains Low Level Flash Programming Routines and a Default Serial Loader. High-speed Architecture In Standard Mode: o 40 MHz (Vcc 2.7V to 5.5V, both Internal and external code execution) o 60 MHz (Vcc 4.5V to 5.5V and Internal Code execution only)

In X2 mode (6 Clocks/machine cycle) o 20 MHz (Vcc 2.7V to 5.5V, both Internal and external code execution) o 30 MHz (Vcc 4.5V to 5.5V and Internal Code execution only) 64K Bytes On-chip Flash Program/Data Memory o Byte and Page (128 Bytes) Erase and Write o 100k Write Cycles On-chip 1792 bytes Expanded RAM (XRAM) o Software Selectable Size (0, 256, 512, 768, 1024, 1792 Bytes)

Department of ECE | CMRIT

21

Design and Realization of Modbus Protocol o 768 Bytes Selected at Reset for T89C51RD2 Compatibility On-chip 2048 Bytes EEPROM Block for Data Storage (AT89C51ED2 Only) 100K Write Cycles Dual Data Pointer Variable Length MOVX for Slow RAM/Peripherals

Improved X2 Mode with Independent Selection for CPU and Each Peripheral Keyboard Interrupt Interface on Port 1 SPI Interface (Master/Slave Mode) 8-bit Clock Prescaler 16-bit Programmable Counter Array High Speed Output Compare/Capture Pulse Width Modulator Watchdog Timer Capabilities Asynchronous Port Reset Full-duplex Enhanced UART with Dedicated Internal Baud Rate Generator Low EMI (Inhibit ALE) Hardware Watchdog Timer (One-time Enabled with Reset-Out), Power-off Flag Power Control Modes: Idle Mode, Power-down Mode Single Range Power Supply: 2.7V to 5.5V
Industrial Temperature Range (-40 to +85C)

Packages: PLCC44, VQFP44, PLCC68, VQF

Department of ECE | CMRIT

22

Design and Realization of Modbus Protocol

3.3 Block Diagram

Fig 3.1 Block diagram

3.4 SFR Mapping


The Special Function Registers (SFRs) of the AT89C51RD2/ED2 fall into the following categories:

C51 core registers: ACC, B, DPH, DPL, PSW, SP I/O port registers: P0, P1, P2, P3, PI2 Timer registers: T2CON, T2MOD, TCON, TH0, TH1, TH2, TMOD, TL0, TL1, TL2, RCAP2L, RCAP2H Serial I/O port registers: SADDR, SADEN, SBUF, SCON PCA (Programmable Counter Array) registers: CCON, CCAPMx, CL, CH, CCAPxH, CCAPxL (x: 0 to 4) Power and clock control registers: PCON Hardware Watchdog Timer registers: WDTRST, WDTPRG

Department of ECE | CMRIT

23

Design and Realization of Modbus Protocol Interrupt system registers: IE0, IPL0, IPH0, IE1, IPL1, IPH1 Keyboard Interface registers: KBE, KBF, KBLS SPI registers: SPCON, SPSTR, SPDAT BRG (Baud Rate Generator) registers: BRL, BDRCON Clock Prescaler register: CKRL Others: AUXR, AUXR1, CKCON0, CKCON1

3.5 Pin Configuration

Department of ECE | CMRIT

24

Design and Realization of Modbus Protocol

Fig 3.2 Pin Configuration of AT89C51RD2/ED2

Fig 3.3 Pin Configuration of AT89C51RD2/ED2

3.6 PORT TYPES


Department of ECE | CMRIT 25

Design and Realization of Modbus Protocol AT89C51RD2/ED2 I/O ports (P1, P2, P3, P4, P5) implement the quasi-bidirectional output that is common on the 80C51 and most of its derivatives. This output type can be used as both an input and output without the need to reconfigure the port. This is possible because when the port outputs logic high; it is weakly driven, allowing an external device to pull the pin low. When the pin is pulled low, it is driven strongly and able to sink a fairly large current. These features are somewhat similar to an open drain output except that there are three pull-up transistors in the quasi-bidirectional output that serve different purposes. One of these pull-ups, called the "weak" pull-up, is turned on whenever the port latch for the pin contains a logic 1. The weak pull-up sources a very small current that will pull the pin high if it is left floating. A second pull-up, called the "medium" pull-up, is turned on when the port latch for the pin contains a logic 1 and the pin itself is also at a logic 1 level. This pull-up provides the primary source current for a quasibidirectional pin that is outputting a 1. If a pin that has a logic 1 on it is pulled low by an external device, the medium pull-up turns off, and only the weak pull-up remains on. In order to pull the pin low under these conditions, the external device has to sink enough current to overpower the medium pull-up and take the voltage on the port pin below its input threshold. The third pull-up is referred to as the "strong" pull-up. This pull-up is used to speed up low-to high transitions on a quasi-bidirectional port pin when the port latch changes from a logic 0 to a logic 1. When this occurs, the strong pull-up turns on for a brief time, two CPU clocks, in order to pull the port pin high quickly. Then it turns off again. The DPU bit (bit 7 in AUXR register) allows disabling the permanent weak pull up of all ports when latch data is logical 0.

3.7 REGISTERS
Table 3.2 CKRL Register

Table 3.3 PCON Register

Department of ECE | CMRIT

26

Design and Realization of Modbus Protocol

3.8 Enhanced Features


In comparison to the original 80C52, the AT89C51RD2/ED2 implements some new features, they are:

X2 option; Dual Data Pointer Extended RAM; Programmable Counter Array (PCA) Hardware Watchdog; SPI interface 4-level interrupt priority system; Power-off flag ONCE mode; ALE disabling

CHAPTER 4
Department of ECE | CMRIT 27

Design and Realization of Modbus Protocol

SERIAL COMMUNICATION
4.1 RS232 (serial port) RS-232 (Recommended Standard - 232) is a telecommunications standard for binary serial communications between devices. It supplies the roadmap for the way devices speak to each other using serial ports. The devices are commonly referred to as a DTE (data terminal equipment) and DCE (data communications equipment); for example, a computer and modem, respectively.RS232 is the most known serial port used in transmitting the data in communication and interface. Even though serial port is harder to program than the parallel port, this is the most effective method in which the data transmission requires less wires that yields to the less cost. The RS232 is the communication line which enables the data transmission by only using three wire links. The three links provides transmit, receive and common ground. The transmit and receive line on this connecter send and receive data between the computers. As the name indicates, the data is transmitted serially. The two pins are TXD & RXD. There are other lines on this port as RTS, CTS, DSR, DTR, and RTS, RI. The 1 and 0 are the data which defines a voltage level of 3V to 25V and -3V to -25V respectively. 4.1.1 TTL Logic Levels When communicating with various micro processors one needs to convert the RS232 levels down to lower levels, typically 3.3 or 5.0 Volts. Here is a cheap and simple way to do that. Serial RS-232 (V.24) communication works with voltages -15V to +15V for high and low. On the other hand, TTL logic operates between 0V and +5V. Modern low power consumption logic operates in the range of 0V and +3.3V or even lower.
Table 4.1 TTL Logic Levels

RS-232

TTL

Logic

-15V -3V +2V +5V High +3V +15V 0V +0.8V Low

Department of ECE | CMRIT

28

Design and Realization of Modbus Protocol Thus the RS-232 signal levels are far too high TTL electronics, and the negative RS-232 voltage for high cant be handled at all by computer logic. To receive serial data from an RS-232 interface the voltage has to be reduced. Also the low and high voltage level has to be inverted. This level converter uses a Max232 and five capacitors. The MAX232 from Maxim was the first IC which in one package contains the necessary drivers and receivers to adapt the RS-232 signal voltage levels to TTL logic. 4.1.2 RS232 INTERFACED TO MAX 232
Fig 4.2 RS232 232
J 9 8 7 6 2 5 4 3 2 1 16 U T 1 O U T T 5 V 1 8 3 R R 2 1 1 1 2 2 + 3 C 1 1 u f IR N 1 IR N 2 1 2 1 O9 O 2 U U T T P 3R . X0 D O U

Interfaced to MAX

1 2

VCC

Rs232 is 9 pin pins of this are used i.e. RS232 is connected to 4.1.3 Max232

C 0

GND

0 . 1 . 1 u f C

1 0 X P D 3 1. 1 1 T T 4 1 3 C 0C . 5 1 u 4 f C 5 C C C u2 f 6 V V 7 0 . 1 M

I TN I TN + + -

1 4 O 7 U O U

T 1 T T

db connector, only three 2, 3, 5 the transmit pin of rx pin of microcontroller interfaced to

microcontroller

A X u f 15

Fig 4.3 Max232 interfaced to microcontroller

4.2 MAX 485 The MAX485 is low-power transceivers for RS-485 and RS-422 communication. The IC contains one driver and one receiver. The driver slew rates of the MAX485 is not limited, allowing them to transmit up to 2.5Mbps. These transceivers draw between 120A and 500A of supply current when unloaded or fully loaded with disabled drivers. All parts operate from a single 5V supply.

Department of ECE | CMRIT

29

Design and Realization of Modbus Protocol Drivers are short-circuit current limited and are protected against excessive power dissipation by thermal shutdown circuitry that places the driver outputs into a high-impedance state. The receiver input has a fail-safe feature that guarantees a logic-high output if the input is open circuit. The MAX485 is designed for half-duplex applications.

Low Quiescent Current: 300A -7V to +12V Common-Mode Input Voltage Range Three-State Outputs 30ns Propagation Delays, 5ns Skew Operate from a Single 5V Supply Allows up to 32 Transceivers on the Bus Data rate: 2.5 Mbps Current-Limiting and Thermal Shutdown for Driver Overload Protection The transmitter outputs and receiver inputs are protected to 15kV Air ESD

CHAPTER 5 HARDWARE DESCRIPTION


5.1 INTRODUCTION
In this chapter we will discuss about the hardware used in this project. All the components will be discussed in detail like LCD, Analog to Digital convertor, LDR (Light Dependent Resistor), and

Department of ECE | CMRIT

30

Design and Realization of Modbus Protocol LM35 Temperature Sensor.

5.2 Liquid Crystal Display


Liquid crystal display is a type of display which used in digital watches and many portable computers. LCD displays utilize two sheets of polarizing material with a liquid crystal solution between them. An electric current passed through the liquid causes the crystals to align so that light cannot pass through them. Each crystal, therefore, is like a shutter, either allowing light to pass through or blocking the light. The liquid crystals can be manipulated through an applied electric voltage so that light is allowed to pass or is blocked. By carefully controlling where and what wavelength (color) of light is allowed to pass, the LCD monitor is able to display images. A back light provides LCD monitors brightness. Other advances have allowed LCDs to greatly reduce liquid crystal cell response times. Response time is basically the amount of time it takes for a pixel to change colors. In reality response time is the amount of time it takes a liquid crystal cell to go from being active to inactive. They make complicated equipment easier to operate. LCDs come in many shapes and sizes but the most common is the 16 character x 4 line (16x4) display with no backlight. It requires only 11 connections eight bits for data (which can be reduced to four if necessary) and three control lines (we have only used two here). It runs off a 5V DC supply and only needs about 1mA of current. The display contrast can be varied by changing the voltage into pin 3 of the display.

5.2.1 PIN DESCRIPTIONS While VCC and VSS provide +5V and ground respectively, VEE is used for controlling LCD contrast. Description of other pins is given in the table 3.2
Table 5.1 Pin Description of LCD

PIN 1

SYMBOL VSS

I/O --

DESCRIPTION Ground

Department of ECE | CMRIT

31

Design and Realization of Modbus Protocol

2 3

VCC VEE

---

+5V power supply Power supply to

control contrast 4 RS I RS=0 to select

command register RS=1 to select data register 5 R/W I R/W=0 for write R/W=1 for read 6 7 8 9 10 11 12 13 14 EN DB0 DB1 DB2 DB3 DB4 DB5 DB6 DB7 I/O I/O I/O I/O I/O I/O I/O I/O I/O Enable The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus

The three control lines are referred to as EN, RS, and RW. The EN line is called "Enable". This control line is used to tell the LCD that you are sending it data. To send data to the LCD, your program should first set this line high (1) and then set the other two control lines and/or put data on the data bus. When the other lines are completely ready, bring EN low (0) again. The 1-0 transition tells the 44780 to take the data currently found on the other control lines and on the data bus and to treat it as a command.

Department of ECE | CMRIT

32

Design and Realization of Modbus Protocol The RS line is the "Register Select" line. When RS is low (0), the data is to be treated as a command or special instruction (such as clear screen, position cursor, etc.). When RS is high (1), the data that is sent is a text data which should be displayed on the screen. For example, to display the letter "T" on the screen you would set RS high. The RW line is the "Read/Write" control line. When RW is low (0), the information on the data bus is being written to the LCD. When RW is high (1), the program is effectively querying (or reading) the LCD. Only one instruction ("Get LCD status") is a read command. All others are write commands, so RW will almost be low. Finally, the data bus consists of 4 or 8 lines (depending on the mode of operation selected by the user). In the case of an 8-bit data bus, the lines are referred to as DB0, DB1, DB2, DB3, DB4, DB5, DB6, and DB7. The ASCII code to be displayed is eight bits long and is sent to the LCD either four or eight bits at a time. If four bit mode is used, two "nibbles" of data (Sent high four bits and then low four bits with an "E" Clock pulse with each nibble) are sent to make up a full eight bit transfer. The "E" Clock is used to initiate the data transfer within the LCD. Deciding how to send the data to the LCD is most critical decision to be made for an LCD interface application. Eight-bit mode is best used when speed is required in an application and at least ten I/O pins are available. The "R/S" bit is used to select whether data or an instruction is being transferred between the microcontroller and the LCD. If the Bit is set, then the byte at the current LCD "Cursor" Position can be written. When the Bit is reset, either an instruction is being sent to the LCD or the execution status of the last instruction is read back. 5.2.2 ADVANTAGES LCD interfacing with 8051 is a real-world application. In recent years the LCD is finding widespread use replacing LEDs (seven segment LEDs or other multi segment LEDs). This is due to following reasons: The declining prices of LCDs.

Department of ECE | CMRIT

33

Design and Realization of Modbus Protocol The ability to display numbers, characters and graphics. This is in contrast to LEDs, which are limited to numbers and a few characters. An intelligent LCD displays two lines, 20 characters per line, which is interfaced to the 8051. Incorporation of a refreshing controller into the LCD, thereby relieving the CPU to keep displaying the data. Ease of programming for characters and graphics. For a LCD module to be used effectively in any piece of equipment, a microprocessor or a micro controller is usually required to drive it. However, before attempting to wire the two together some initial experiments can be performed by connecting a series of switches to the pins of the module. This can be a quite beneficial step, if even you are thoroughly conversant with the workings of microprocessors. 5.2.4 BASIC COMMANDS OF LCD When LCD is powered up the display should show a series of dark squares, possibly only on part of display. These characters are actually in their off state, so the contrast control should be adjusted anti-clockwise until the squares are just visible. The display module resets itself to an initial state when power is applied, which curiously the display has blanked off so that even if characters are entered, they cannot be seen. It is therefore necessary to issue a command at this point, to switch the display on which can be explained by table 3.3 which consist of some basic LCD command codes
Table 5.2 LCD Command Codes

5.2.3 PROTOTYPE CIRCUIT

Code (Hex) 1 2 4 6 5
Department of ECE | CMRIT

Command to LCD Instruction Register Clear display screen Return home Decrement cursor (shift cursor to left) Increment cursor (shift cursor to right Shift display right
34

Design and Realization of Modbus Protocol

7 8 A C E F 10 14 18 1C 80 C0 38

Shift display left Display off, cursor off Display off, cursor on Display on, cursor off Display off, cursor blinking Display on, cursor blinking Shift cursor position to left Shift cursor position to right Shift the entire display to the left Shift the entire display to the right Force cursor to beginning of 1st line Force cursor to beginning of 2nd line 2 lines and 5X7 matrix

5.2.5 CIRCUIT DESCRIPTION OF LCD EXPERIMENT The circuit can be wired up on a plug-in-style prototyping board, using dual-in-line switches for the data lines (S1-S8). A toggle switch for the RS input (S10) and a momentary action switch (or macro switch) for usage. Most of the LCD modules conform to a standard interface specification. A 14pin access is provided having eight data lines, three control lines and three power lines. The connections are laid out in one of the two common configurations, either two rows of seven pins, or a single row of 14 pins. One of the, pins are numbered on the LCDs print circuit board (PCB), but if not, it is quite easy to locate pin1. Since this pin is connected to ground, it often has a thicker PCB track, connected to it, and it is generally connected to metalwork at same point. 5.2.6 SPECIFICATIONS

Department of ECE | CMRIT

35

Design and Realization of Modbus Protocol Resolution: The horizontal and vertical size expressed in pixels (e.g., 1024x768). Unlike CRT monitors, LCD monitors have a native-supported resolution for best display effect. Dot pitch: The distance between the centers of two adjacent pixels. The smaller the dot pitch size, the less granularity is present, resulting in a sharper image. Dot pitch may be the same both vertically and horizontally, or different (less common). Viewable size: The size of an LCD panel measured on the diagonal (more specifically known as active display area). Response time: The minimum time necessary to change a pixel's color or brightness. Response time is also divided into rise and fall time. Matrix type: Active or Passive. Viewing angle: (coll., more specifically known as viewing direction). Color support: How many types of colors are supported (coll., more specifically known as color gamut). Brightness: The amount of light emitted from the display (coll., more specifically known as luminance). Contrast ratio: The ratio of the intensity of the brightest bright to the darkest dark. 5.2.7 INTERFACING LCD TO MICROCONTROLLER

Department of ECE | CMRIT

36

Design and Realization of Modbus Protocol Interfacing LCD to a microcontroller requires some particular steps to be followed. The below figure 5.7 describes how the interfacing between LCD and a microcontroller is done

Microcontroller
E R/W R S DB7DB0

LPC 2148

LCD control

Fig 5.1 Interfacing LCD to microcontroller

5.3 Analog to Digital converter


Analog-to-Digital Converters (ADCs) transform an analog voltage to a binary number (a series of 1s and 0s), and then eventually to a digital number (base 10) for reading on a meter, monitor, or chart. The number of binary digits (bits) that represents the digital number determines the ADC resolution. However, the digital number is only an approximation of the true value of the analog voltage at a particular instant because the voltage can only be represented (digitally) in discrete steps. How closely the digital number approximates the analog value also depends on the ADC resolution. A mathematical relationship conveniently shows how the number of bits an ADC handles determines its specific theoretical resolution: An n-bit ADC has a resolution of one part in 2n. For example, a 12-bit ADC has a resolution of one part in 4,096, where 212 = 4,096. Thus, a 12-bit ADC with a maximum input of 10 VDC can resolve the measurement into 10 VDC/4096

Department of ECE | CMRIT

37

Design and Realization of Modbus Protocol = 0.00244 VDC = 2.44 mV. Similarly, for the same 0 to 10 VDC range, a 16-bit ADC resolution is 10/216 = 10/65,536 = 0.153 mV. The resolution is usually specified with respect to the full-range reading of the ADC, not with respect to the measured value at any particular instant.

5.3.1 Successive-Approximation ADCs


A successive-approximation converter is composed of a digital-to-analog converter (DAC), a single comparator, and some control logic and registers. When the analog voltage to be measured is present at the input to the comparator, the system control logic initially sets all bits to zero. Then the DACs most significant bit (MSB) is set to 1, which forces the DAC output to 1/2 of full scale (in the case of a 10-V full-scale system, the DAC outputs 5.0 V). The comparator then compares the analog output of the DAC to the input signal, and if the DAC output is lower than the input signal, (the signal is greater than 1/2 full scale), the MSB remains set at 1. If the DAC output is higher than the input signal, the MSB resets to zero. Next, the second MSB with a weight of 1/4 of full scale turns on (sets to 1) and forces the output of the DAC to either 3/4 full scale (if the MSB remained at 1) or 1/4 full scale (if the MSB reset to zero). The comparator once more compares the DAC output to the input signal and the second bit either remains on (sets to 1) if the DAC output is lower than the input signal, or resets to zero if the DAC output is higher than the input signal. The third MSB is then compared the same way and the process continues in order of descending bit weight until the LSB is compared. At the end of the process, the output register contains the digital code representing the analog input signal. Successive approximation ADCs are relatively slow because the comparisons run serially, and the ADC must pause at each step to set the DAC and wait for its output to settle. However, conversion rates easily can reach over 1 MHz. Also, 12 and 16-bit successiveapproximation ADCs are relatively inexpensive, which accounts for their wide use in many PCbased data acquisition systems.

Department of ECE | CMRIT

38

Design and Realization of Modbus Protocol

Fig 5.2 Successive-Approximation ADC 5.3.2 8-Bit, Microprocessor-Compatible, A/D Converters The ADC080X family is CMOS 8-Bit, successive approximation A/D converters which use a modified potentiometric ladder and are designed to operate with the 8080A control bus via threestate outputs. These converters appear to the processor as memory locations or I/O ports, and hence no interfacing logic is required. The differential analog voltage input has good common mode- rejection and permits offsetting the analog zero-input voltage value. In addition, the voltage reference input can be adjusted to allow encoding any smaller analog voltage span to the full 8 bits of resolution.

Department of ECE | CMRIT

39

Design and Realization of Modbus Protocol 5.3.3 Typical Application Schematic

Fig 5.3 Typical Application Schematic

80C48 and 80C80/85 Bus Compatible - No Interfacing Logic Required Conversion Time . . . . . . . . . . . . . . . . . . . . . . . . . . <100s Easy Interface to Most Microprocessors Will Operate in a Stand Alone Mode Differential Analog Voltage Inputs Works with Bandgap Voltage References TTL Compatible Inputs and Outputs On-Chip Clock Generator Analog Voltage Input Range (Single + 5V Supply) . . . . . . . . . . . . . . . . . . . . . . 0V to 5V No Zero-Adjust Required

Department of ECE | CMRIT

40

Design and Realization of Modbus Protocol 80C48 and 80C80/85 Bus Compatible - No Interfacing Logic Required

5.4 Light Dependent Resistor


An LDR is a Light Dependent Resistor i.e. its resistance varies with the amount of light falling on it. Resistance becomes lower as the light falling on the LDR increases. A simple circuit would be a voltage divider circuit with an LED connected in parallel with the LDR. When the amount of light decreases the resistance of the LDR increases causing the bulb to light up. A Light Sensor generates an output signal indicating the intensity of light by measuring the radiant energy that exists in a very narrow range of frequencies basically called "light", and which ranges in frequency from "Infrared" to "Visible" up to "Ultraviolet" light spectrum. The light sensor is a passive devices that convert this "light energy" whether visible or in the infrared parts of the spectrum into an electrical signal output. Light sensors are more commonly known as "Photoelectric Devices" or "Photo Sensors" because the convert light energy (photons) into electricity (electrons). Photoelectric devices can be grouped into two main categories, those which generate electricity when illuminated, such as Photo-voltaics or Photo-emissives etc, and those which change their electrical properties in some way such as Photo-resistors or Photo-conductors. This leads to the following classification of devices.

Photo-emissive Cells - These are photodevices which release free electrons from a light sensitive material such as cesium when struck by a photon of sufficient energy. The amount of energy the photons have depends on the frequency of the light and the higher the frequency, the more energy the photons have converting light energy into electrical energy.

Photo-conductive Cells - These photo devices vary their electrical resistance when subjected to light. Photoconductivity results from light hitting a semiconductor material which controls the current flow through it. Thus, more light increase the current for a given applied voltage. The most common photoconductive material is Cadmium Sulphide used in LDR photocells.

Photo-voltaic Cells - These photo devices generate an EMF in proportion to the radiant light energy received and is similar in effect to photoconductivity. Light energy falls on to two semiconductor materials sandwiched together creating a voltage of approximately 0.5V. The most common photovoltaic material is Selenium used in solar cells.

Department of ECE | CMRIT

41

Design and Realization of Modbus Protocol

Photo-junction Devices - These photo devices are mainly true semiconductor devices such as the photodiode or phototransistor which use light to control the flow of electrons and holes across their PN-junction. Photo junction devices are specifically designed for detector application and light penetration with their spectral response tuned to the wavelength of incident light. A Photoconductive light sensor does not produce electricity but simply changes its

physical properties when subjected to light energy. The most common type of photoconductive device is the Photoresistor which changes its electrical resistance in response to changes in the light intensity. Photoresistors are Semiconductor devices that use light energy to control the flow of electrons, and hence the current flowing through them. The commonly used Photoconductive Cell is called the Light Dependent Resistor or LDR. The Light Dependent Resistor

Fig 5.4 Typical LDR As its name implies, the Light Dependent Resistor (LDR) is made from a piece of exposed semiconductor material such as cadmium sulphide that changes its electrical resistance from several thousand Ohms in the dark to only a few hundred Ohms when light falls upon it by creating hole-electron pairs in the material. The net effect is an improvement in its conductivity with a decrease in resistance for an increase in illumination. Also, photo resistive cells have a long response time requiring many seconds to respond to a change in the light intensity. Materials used as the semiconductor substrate include, lead sulphide (PbS), lead selenide (PbSe), indium antimonide (InSb) which detect light in the infra-red range with the most commonly used

Department of ECE | CMRIT

42

Design and Realization of Modbus Protocol of all photoresistive light sensors being Cadmium Sulphide (Cds). Cadmium sulphide is used in the manufacture of photoconductive cells because its spectral response curve closely matches that of the human eye and can even be controlled using a simple torch as a light source. Typically then, it has a peak sensitivity wavelength (p) of about 560nm to 600nm in the visible spectral range. The Light Dependent Resistor Cell

Fig 5.5 Light Dependent Resistor Cell The most commonly used photo resistive light sensor is the ORP12 Cadmium Sulphide photoconductive cell. This light dependent resistor has a spectral response of about 610nm in the yellow to orange region of light. The resistance of the cell when unilluminated (dark resistance) is very high at about 10M's which falls to about 100's when fully illuminated (lit resistance). To increase the dark resistance and therefore reduce the dark current, the resistive path forms a zigzag pattern across the ceramic substrate. The CdS photocell is a very low cost device often used in auto dimming, darkness or twilight detection for turning the street lights "ON" and "OFF", and for photographic exposure meter type applications.

Department of ECE | CMRIT

43

Design and Realization of Modbus Protocol One simple use of a Light Dependent Resistor, is as a light sensitive switch as shown below.

Fig 5.6 LDR Switch This basic light sensor circuit is of a relay output light activated switch. A potential divider circuit is formed between the photoresistor, LDR and the resistor R1. When no light is present ie in darkness, the resistance of the LDR is very high in the Megaohms range so zero base bias is applied to the transistor TR1 and the relay is de-energised or "OFF". As the light level increases the resistance of the LDR starts to decrease causing the base bias voltage at V1 to rise. At some point determined by the potential divider network formed with resistor R1, the base bias voltage is high enough to turn the transistor TR1 "ON" and thus activate the relay which inturn is used to control some external circuitry. As the light level falls back to darkness again the resistance of the LDR increases causing the base voltage of the transistor to decrease, turning the transistor and relay "OFF" at a fixed light level determined again by the potential divider network. By replacing the fixed resistor R1 with a potentiometer VR1, the point at which the relay turns "ON" or "OFF" can be pre-set to a particular light level. This type of simple circuit shown above has a fairly low sensitivity and its switching point may not be consistent due to variations in either temperature or the supply voltage.

5.5 LM35 Temperature Sensor


The LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature. The LM35 thus has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large

Department of ECE | CMRIT

44

Design and Realization of Modbus Protocol constant voltage from its output to obtain convenient Centigrade scaling. The LM35 does not require any external calibration or trimming to provide typical accuracies of 14C at room temperature and 34C over a full 55 to +150C temperature range. Low cost is assured by trimming and calibration at the wafer level. The LM35s low output impedance, linear output, and precise inherent calibration make interfacing to readout or control circuitry especially easy. It can be used with single power supplies, or with plus and minus supplies. As it draws only 60 A from its supply, it has very low self-heating, less than 0.1C in still air. The LM35 is rated to operate over a 55 to +150C temperature range, while the LM35C is rated for a 40 to +110C range (10 with improved accuracy). The LM35 series is available packaged in hermetic TO-46 transistor packages, while the LM35C, LM35CA, and LM35D are also available in the plastic TO92 transistor package. The LM35D is also available in an 8-lead surface mount small outline package and a plastic TO-220 package.

5.5.1 Features

Calibrated directly in Celsius (Centigrade) Linear + 10.0 mV/C scale factor 0.5C accuracy guarantee able (at +25C) Rated for full 55 to +150C range Suitable for remote applications Low cost due to wafer-level trimming Operates from 4 to 30 volts Less than 60 A current drain Low self-heating, 0.08C in still air Nonlinearity only 14C typical

Department of ECE | CMRIT

45

Design and Realization of Modbus Protocol

Low impedance output, 0.1 W for 1 mA load

5.5.2 Typical Application

Fig.5.7 Basic Centigrade Temperature Sensor (+2C to +150C)

Fig 5.8. Full-Range Centigrade Temperature Sensor

Department of ECE | CMRIT

46

Design and Realization of Modbus Protocol

CHAPTER 6 SOFTWARE TOOLS


6.1 INTRODUCTION
Here we explain about keil compiler and flash magic. Keil compiler is used for writing the code for the project and flash magic software is required to dump the code in the microcontroller.

6.2 KEIL MICROVISION 4


It is possible to create the source files in a text editor such as Notepad, run the Compiler on each C source file, specifying a list of controls, run the Assembler on each Assembler source file, specifying another list of controls, run either the Library Manager or Linker (again specifying a list of controls) and finally running the Object-HEX Converter to convert the Linker output file to an Intel Hex File. Once that has been completed the Hex File can be downloaded to the target hardware and debugged. Alternatively KEIL can be used to create source files; automatically compile, link and covert using options set with an easy to use user interface and finally simulate or perform debugging on the hardware with access to C variables and memory. Unless you have to use the tolls on the command line, the choice is clear. KEIL Greatly simplifies the process of creating and testing an embedded application. 6.2.1 PROJECT The user of KEIL centers on projects. A project is a list of all the source files required to build a single application, all the tool options which specify exactly how to build the application, and if required how the application should be simulated. A project contains enough information to take a set of source files and generate exactly the binary code required for the application. Because of the high degree of flexibility required from the tools, there are many options that can be set to configure the tools to operate in a specific manner. It would be tedious to have to set these options up every time the application is being built; therefore they are stored in a project file. Loading the project file into KEIL informs KEIL which source files are required, where they are, and how to configure the tools in the correct way. KEIL can then execute each tool with the correct options. It is also possible to create new projects in KEIL. Source files are added to the project and

Department of ECE | CMRIT

47

Design and Realization of Modbus Protocol the tool options are set as required. The project can then be saved to preserve the settings. The project is reloaded and the simulator or debugger started, all the desired windows are opened. KEIL project files have the extension. The figure 4.1 is the screen shot of our project window

Fig 6.1 Screenshot of Project window

6.2.2 SIMULATOR/DEBUGGER The simulator/ debugger in KEIL can perform a very detailed simulation of a micro controller along with external signals. It is possible to view the precise execution time of a single assembly instruction, or a single line of C code, all the way up to the entire application, simply by

Department of ECE | CMRIT

48

Design and Realization of Modbus Protocol entering the crystal frequency. A window can be opened for each peripheral on the device, showing the state of the peripheral. This enables quick trouble shooting of mis-configured peripherals. Breakpoints may be set on either assembly instructions or lines of C code, and execution may be stepped through one instruction or C line at a time. The contents of all the memory areas may be viewed along with ability to find specific variables. In addition the registers may be viewed allowing a detailed view of what the microcontroller is doing at any point in time. The below figure 4.2 is the screen shot of simulator window

Fig 6.2 Screenshot of simulator window

6.3 Flash Magic


Flash Magic is a PC tool for programming flash based microcontrollers from NXP using a serial or Ethernet protocol while in the target hardware. Flash Magic works on Windows 2000, XP, Vista and 7. 10Mb of disk space is required. The below figure is the Screenshot of Flash Magic Window.

Department of ECE | CMRIT

49

Design and Realization of Modbus Protocol

Fig 6.3 Screenshot of Flash Magic Window The method to dump Hex File into Flash Memory of MCU in Board is to use Program Flash Magic that is connected with MCU through Serial Port of computer PC. Procedure to dump Hex File into MCU: 1. Interface RS232 Cable between RS232 Serial Port of PC and Board UART-0 (CN3). 2. Supply power into board; in this case, we can see red LED1 is in status ON. 3. Set jumper BR4 (INT1) in ON state. 4. Run Program Flash Magic, it will display result as shown in Figure 1.1

5. Start setting the initial values into program as desired, so we configure values into program as follows:

Department of ECE | CMRIT

50

Design and Realization of Modbus Protocol


Select COM port corresponding with (in this example, it is COM1) Set the baud rate to 9600 Set Device to be LPC2148 Set Interface to be None ISP Set Crystal Oscillator with MHz corresponding with the value internal Board. In this case, it is 12.000MHz, so we must set to be 12. Press ISP LOAD Switch (S1) and RESET Switch (S2) on Board ARM7 LPC2148 Development Board to reset MCU to run in Boot Loader following the processes; Press ISP LOAD Switch (S1) and hold Press RESET Switch (S2) while ISP LOAD Switch (S1) is being held. Remove RESET Switch (S2) but ISP LOAD Switch (S1) is being held. Lastly, remove ISP LOAD Switch (S1).

6. Select format of erasing data to be Erase all Flash + Code Rd Prot. 7. Set Option to be Verify after programming. 8. Click Browse to select HEX File for downloading. 9. Click Start, Program FlashMagic will start downloading data into MCU instantly. In this case, we can see the status operation at Status Bar and we must wait for the operation until it is completed. 10. When the operation of program is complete, press RESET Switch (S2) on Board and MCU will start running follow the downloaded program instantly.

CHAPTER 7
Department of ECE | CMRIT 51

Design and Realization of Modbus Protocol

PROJECT DESCRIPTION
7.1 INTRODUCTION
In this chapter we will discuss about the various components used to design the project. This includes selection and designing of various components such as power supply section, microcontroller.

7.2 DESIGNING
The main intension of this project is to design an effective communication system with high accuracy; the following steps have to be carried out in order to fulfill this application. The steps are as follows: 1) Designing the power supply for the entire circuitry. 2) Selection of microcontroller that suits our application.
3) Selection of the proper modbus master.

4) Selection of LCD.
5) Selection of the Slave Module.

Complete studies of all the above points are useful to develop this project. 7.2.1 POWER SUPPLY SECTION In-order to work with any components basic requirement is power supply. In this section there is a requirement of two different voltage levels. Those are
1) 5V DC power supply for Modbus Master. 2) 5V DC power supply for Modbus Slaves.

Now the aim is to design the power supply section which converts 230V AC in to 5V DC and 3.3V DC. Since 230V AC is too high to reduce it to directly 5V DC, therefore we need a step-down transformer that reduces the line voltage to certain voltage that will help us to convert it in to a 5V DC. Considering the efficiency factor of the bridge rectifier, we came to a conclusion to choose a transformer, whose secondary voltage is 3 to 4 V higher than the required voltage i.e. 5V. For this application 0-9V transformers is used, since it is easily available in the market.

Department of ECE | CMRIT

52

Design and Realization of Modbus Protocol The output of the transformer is 9V AC; it feed to rectifier that converts AC to pulsating DC. As we all know that there are 3 kind of rectifiers that is 1) Half wave rectifier 2) Full wave rectifier 3) Bridge rectifier Here we have short listed to use Bridge rectifier, because half wave rectifier has less in efficiency. Even though the efficiency of full wave and bridge rectifier are the same, since there is no requirement for any negative voltage for our application, we have chosen bridge rectifier. Since the output voltage of the rectifier is pulsating DC, in order to convert it into pure DC we use a high value (1000UF/1500UF) of capacitor in parallel that acts as a filter. The most easy way to regulate this voltage is by using a 7805 voltage regulator, whose output voltage is constant 5V DC irrespective of any fluctuation in line voltage. 7.2.2 SELECTION OF MICROCONTROLLER As we know that there are so many types of microcontroller families that are available in the market. Those are 1) 8051 Family 2) AVR microcontroller Family 3) PIC microcontroller Family 4) ARM Family Basic 8051 family is enough for our application, but for our project we select ARM family as all the components are inbuilt in it. ARM is a 32-bit reduced instruction set computer (RISC) instruction set architecture (ISA) developed by ARM Holdings. It was named the Advanced RISC Machine and, before that, the Acorn RISC Machine. The ARM architecture is the most widely used 32-bit instruction set architecture in numbers produced. Originally conceived by Acorn Computers for use in its personal computers, the first ARM-based products were the Acorn Archimedes range introduced in 1987. The system is built using ARM7 as the processing module. The Philips ARM7 Microcontroller LPC2148 series is a high-performance, low-cost embedded processor. It includes several useful modules, like I2C, RTC, PWM, UART etc. It is quite convenient for embedded system designer to use it as an all-in-one solution. The

Department of ECE | CMRIT

53

Design and Realization of Modbus Protocol software for the proposed embedded system is developed using source code is written in Embedded C. 7.2.3. Selection of the proper Modbus Master In the modbus communication system, there is suppose to be a master for controlling and triggering the communication between the 256 slaves simultaneously and to start the communication as well as end the communication. So this master can be a single PC or can be microcontroller based system. In this project a microcontroller based master has been chosen to communicate to the slaves. 7.2.4 Selection of LCD Here in this project we require a LCD to display the data from the respective slaves and in the master. So in this project we have taken three 16 2 LCD, one for master and two for the respective slaves, as this is enough to display the data. It has two rows and can display 16 characters in each row. 7.2.5. Selection of the proper Modbus Slave In the modbus communication system, the 256 slaves communicate with the master. So a proper selection of the slave is supposed to be done. In the underlying project the two selected slaves are 1. LDR 2. LM35 Temperature Sensor The LDR stands for Light Dependent Resistor is a resistor whose resistance decreases with increasing incident light intensity; in other words, it exhibits photoconductivity. And the LM35 Temperature Sensor is used to show the current temperature of the particular location. KEIL Vision IDE and the

7.2.6. CONNECTIONS TO MICROCONTROLLER


LPC2148 microcontroller has 2 ports. Each port has 32 pins. All the external components are connected to these ports only. The transmission line used for entire communication between the Modbus master and slaves is connected to port P0.8 and P0.9 and the LCD is connected to port P0.11 to P0.13 and P1.16 to P1.23.

Department of ECE | CMRIT

54

Design and Realization of Modbus Protocol

7.3 CIRCUIT OPERATION


Whenever power is given to the circuit, the modbus masters LCD displays the title as MODEBUS and the respective slaves LCD shows the LDR and Temperature Sensor readings. Now when the switch for slave 1 is pressed the modbus master sends a request to read the data from the slave 1, then on receiving the request from master the slave transmits the data to master on the transmission line. During that time the slave will send the null values that are unacceptable by modbus master. As soon as the slave 2 switch is pressed it will receive the request from the master and will be ready to transmit the data on the transmission lines to the master, at that moment the slave 1 will be sending null values. Slave 1 is an LDR (Light dependent resistor), as its name suggests, offers resistance in response to the ambient light. The resistance decreases as the intensity of incident light increases, and vice versa. In the absence of light, LDR exhibits a resistance of the order of mega-ohms which decreases to few hundred ohms in the presence of light. It can act as a sensor, since a varying voltage drop can be obtained in accordance with the varying light. It is made up of cadmium sulphide (CdS). An LDR has a zigzag cadmium sulphide track. It is a bilateral device, i.e., conducts in both directions in same fashion. Slave 2 is an LM35 Temperature sensor, are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature. The LM35 thus has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large constant voltage from its output to obtain convenient Centigrade scaling.

Department of ECE | CMRIT

55

Design and Realization of Modbus Protocol

7.4 SCHEMATICS
7.4.1. MODBUS MASTER

Fig 7.1 Schematic of the Modbus Master

The figure 7.1 represents the schematics of the project which clearly indicates how the connections are given between each and every components of Modbus master in our project.

Department of ECE | CMRIT

56

Design and Realization of Modbus Protocol 7.4.2. MODBUS SLAVE 1(LDR)

Fig 7.2 Schematic of the Modbus Slaves The figure 7.2 represents the schematics of the project which clearly indicates how the connections are given between each and every components of Modbus slave in our project.

Department of ECE | CMRIT

57

Design and Realization of Modbus Protocol 7.4.3. MODBUS SLAVE 2(LM35 Temperature Sensor)

Fig 7.3 Schematic of the Modbus Slaves The figure 7.3 represents the schematics of the project which clearly indicates how the connections are given between each and every components of Modbus slave in our project.

Department of ECE | CMRIT

58

Design and Realization of Modbus Protocol

7.5 SCREENSHOTS

Fig 7.4 Screenshot of the Project The above figures 7.4 is the screenshot of our project

Department of ECE | CMRIT

59

Design and Realization of Modbus Protocol

MODBUS MASTER

Fig. 7.5 Screenshot of Modbus Master MODBUS SLAVE

Fig. 7.6 Screenshot of Modbus Slave


The above figures 7.4 and 7.6 are the screenshots of our project

Department of ECE | CMRIT

60

Design and Realization of Modbus Protocol

CHAPTER 8 RESULTS AND CONCLUSION RESULTS


The Modbus communication system consists of two sections. One is Master And second is Slave. All are connected to each other through serial communication lines. As soon as it receives the power it displays MODE BUS on the masters LCD.

Fig 8.1 Modbus The Slaves LCD displays the corresponding LDR and temperature sensor values.

Department of ECE | CMRIT

61

Design and Realization of Modbus Protocol

Fig 8.2 Modbus Slaves displaying respective data When LDR slave switch is pressed, it receives the request from master and then it transmits the LDR value to the master

Department of ECE | CMRIT

62

Design and Realization of Modbus Protocol

Fig 8.3.1 Modbus master requesting Modbus Slaves for data When Temperature slave switch is pressed, it receives the request from master and then it transmits the temperature value to the master

Department of ECE | CMRIT

63

Design and Realization of Modbus Protocol

Fig 8.3.2 Modbus master requesting Modbus Slaves for data The data from both the slaves is stored in the Master

Department of ECE | CMRIT

64

Design and Realization of Modbus Protocol

Fig 8.4 Modbus Master receiving data from both the slaves simultaneously

Department of ECE | CMRIT

65

Design and Realization of Modbus Protocol

CONCLUSION
MODBUS PROTOCOL is the enhancement of the local communication protocols. Unlike in the common communication protocols the transmission and reception takes so long, MODBUS provides a efficient signal communication network. In the current scenario we are reducing the manly efforts in the field of technology; therefore MODBUS Protocol is fulfilling the purpose and communication can be done by the MODBUS Master without any Physical requirement. In MODBUS Protocol we are implementing the communication using advance communication devices which can reduce the time delay and also the distance of communication is more as compared to the old communication protocols. Also we can communicate between more than 247 slaves which overall reduce the system complexity and also reduce the system cost. The bandwidth i.e. the number of slaves can be increased such that the functionality area of MODBUS PROTOCOL will increase and also efficient control can be implemented. Zigbee model can be implemented in the same module which can reduce the cost of the project by reducing the usage of the hardware. The distance of communication can be increased by improving the communication protocol and the area of operation can be increased.

Department of ECE | CMRIT

66

Design and Realization of Modbus Protocol

REFERENCES

The 8051 Microcontroller-Architecture, Programming & Applications-Kenneth J .Ayala Second Edition ; Penram International. The 8051 Microcontroller ATMEL, Designers data sheets. Ramesh. S. Goankar; Microcontroller Architecture Programming and Applications with the 8051; 4th Ed.; Penram International Publishers. Arm architecture and system, data sheet by Dave Jaggar, 1997. Arm 7 processor family, www.arm.com. ARM7 TDMI, Technical reference manual by ARM Limited 2001-2004. NXP LPC2148, www.keil.com. LPC2148, Preliminary datasheet by Philips (NXP). Keil microvision 4, www.keil.com/microvision. RS 485 communication protocol by Jan Axelsons Lakeview.

Department of ECE | CMRIT

67

Anda mungkin juga menyukai