MICROCONTROLLER – BASED MULTIPORT COMMUNICATION
SYSTEM FOR DIGITAL ELECTRICITY METERS
A THESIS SUBMITTED TO
THE GRADUATE SCHOOL OF NATURAL AND APPLIED SCIENCES
OF
MIDDLE EAST TECHNICAL UNIVERSITY
BY
FIRAT BEŞTEPE
IN PARTIAL FULFILLMENT OF THE REQUIREMENTS
FOR THE DEGREE OF MASTER OF SCIENCE
IN
ELECTRICAL AND ELECTRONICS ENGINEERING
DECEMBER 2004
Approval of the Graduate School of Natural and Applied Sciences.
Prof. Dr. Canan ÖZGEN
Director
I certify that this thesis satisfies all the requirements as a thesis for the
degree of Master of Science.
Prof. Dr. İsmet ERKMEN
Head of Department
This is to certify that we have read this thesis and that in our opinion it is
fully adequate, in scope and quality, as a thesis for the degree of Master of
Science
Prof. Dr. Hasan GÜRAN
Supervisor
Examining Committee Members Prof. Dr. Osman SEVAIOĞLU (METU,EE)
Prof. Dr. Hasan GÜRAN (METU,EE)
Assoc. Prof Dr. Gözde BOZDAĞI (METU,EE)
Asst. Prof. Dr. Cüneyt BAZLAMAÇCI (METU,EE)
Graduate Engineer Turgay ŞENDUR (KOSGEB)
iii
I hereby declare that all information in this document has been obtained and presented in accordance with academic rules and ethical conduct. I also declare that, as required by these rules and conduct, I have fully cited and referenced all material and results that are not original to this work. Name, Last name : Fırat BEŞTEPE
Signature :
iv
ABSTRACT
MICROCONTROLLER-BASED MULTIPORT COMMUNICATION
SYSTEM FOR DIGITAL ELECTRICITY METERS
BEŞTEPE, Fırat
Ms., Department of Electrical and Electronics Engineering
Supervisor : Prof. Dr. Hasan GÜRAN
December 2004, 116 pages
This thesis explains the design of a microcontroller-based device, which
provides an efficient and practical alternative for the remote reading of digital
electricity meters over Public Switch Telephone Network (PSTN). As an
alternative application, a system is constructed providing file transfer capability to
the PC connected to the port of implemented device in addition to remote reading
of digital electricity meters. This thesis also provides detailed explanations about
the basics of serial asynchronous communication over modem for PICs
(peripheral interface controllers) together with description of each component
included by the constructed system, which can be used in energy metering sector
commonly.
Keywords: PIC, Microcontroller, Serial Communication
v
ÖZ
ELEKTRONİK ELEKTRİK SAYAÇLARI İÇİN MİKRODENETLEYİCİ
TEMELLİ ÇOKLU PORT HABERLEŞME SİSTEMİ
BEŞTEPE, Fırat
Yüksek Lisans, Elektrik-Elektronik Mühendisliği Bölümü
Tez Yöneticisi : Prof. Dr. Hasan GÜRAN
Aralık 2004, 116 sayfa
Bu tez elektronik elektrik sayaçlarının, Genel Telefon Ağı (PSTN)
üzerinden uzaktan okunması amacına yönelik etkili ve kullanışlı bir alternatif
sunan, mikrodenetleyici temelli bir cihazın dizaynını açıklamaktadır. Alternatif bir
uygulama olarak da, elektronik elektrik sayaçlarının uzaktan okunmasının
yanısıra, dizayn edilen cihazın portlarından birine bağlanan PC ile dosya
transferinin de yapılabildiği bir sistem oluşturulmuştur. Ayrıca enerji ölçüm
sektöründe yaygın olarak kullanılabilecek bu sistemin tüm temel unsurlarının
izahı ile birlikte, çevresel arayüz denetleyicileri (PICs) için modem üzerinden seri
ve eşzamanlı olmayan haberleşme temelleri konusunda ayrıntılı bilgi vermektedir.
Anahtar Kelimeler: PIC, Mikrodenetleyici, Seri Haberleşme
vi
ACKNOWLEDGEMENTS
The author wishes to express his deepest gratitude to his supervisor Prof.
Dr. Hasan GÜRAN for his guidance, advices, criticism, and encouragements and
insight throughout the study.
The technical assistances of Tuncay KANDEMİR, Ali Erkan ERKOL and
Kadir ERDOĞAN are gratefully acknowledged.
This study was supported by Aktif Enerji Ltd. Şti., ANKARA.
vii
TABLE OF CONTENTS
PLAGIARISM……………………………………………………………. iii ABSTRACT……………………………………………………………….. iv ÖZ………………………………………………………………………….. v ACKNOWLEDGEMENTS……………………………………………….vi TABLE OF CONTENTS………………………………………………… vii LIST OF TABLES………………………………………………………... x LIST OF FIGURES………………………………………………………. xi CHAPTER 1)- GENERAL DESCRIPTION OF THE SYSTEM 1.1 Introduction………………………………………………………….... 1 1.2 Common Remote Reading Infrastructure…...……………………… 2 1.3 Developed Remote Reading Infrastructure…...…………………….. 3 1.4 Alternative Application of Multi-port Device…..……………...…… 6 1.5 Objective of This Thesis………………………………..…………….. 8 CHAPTER 2)- DATA COMMUNICATION INTERFACE 2.1 Introduction………………………………………………………....… 10 2.2 EIA232 Standard…………………………………………………...… 11 2.3 EIA232 Signal Functions…………………………………………...… 11
2.3.1 Signal Ground and Shield………………………………….… 16 2.3.2 Primary Communications Channel……………………….….. 16 2.3.3 Secondary Communications Channel…………………….….. 17 2.3.4 Modem Status and Control Signals……………………….…. 18 2.3.5 Transmitter and Receiver Timing Signals…………………… 19 2.3.6 Channel Test Signals…………………………………….…… 20
2.4 Electrical Standards…………………………………………...……....21 CHAPTER 3)- PIC 16F877 MICROCONTROLLER 3.1 General Overview to Microcontrollers…………………………...…. 23
3.1.1 Program Counter and Program Memory EPROM……...……. 25 3.1.2 Data RAM…………………………………………….……… 26 3.1.3 Arithmetic Logic Unit………………………………..………. 26 3.1.4 I/O ports……………………………………………..……….. 27
3.1.4.1 PORTA and the TRISA Register………...………… 28 3.1.4.2 PORTB and the TRISB Register………………...… 28 3.1.4.3 PORTC and the TRISC Register……………...…… 29 3.1.4.4 PORTD and TRISD Registers…………………...… 29 3.1.4.5 PORTE and TRISE Register……………………….. 29
3.1.5 Peripherals……………………………………………….……30 3.2 Microcontroller Programming Procedure……..………………...…. 32
viii
CHAPTER 4)- SERIAL COMMUNICATION WITH MICROCONTROLLERS 4.1 Introduction…………..……………………………………………….. 34 4.2 USART Module……………...………………………………………... 34
4.2.1 Signal Level Conversion……………………………………... 35 4.2.2 The USART Module Asynchronous Mode………………..….38
4.2.2.1 USART Asynchronous Transmitter……………..…. 39 4.2.2.2 USART Asynchronous Receiver………………..…. 41
4.3 Inverted Logic……………………………………………..…… 43 4.4 Comments on Serial Communication with Microcontrollers….. 45
CHAPTER 5)- DESCRIPTION OF IMPLEMENTED SYSTEM 5.1 Remote Access Software…………………………………………...…. 46
5.1.1 Running of Full Version Remote Access Software………….. 47 5.1.2 Running of Lite Version Remote Access Software………….. 49 5.1.3 Flow Diagram of Reading Software…………………………..51
5.2 Modem……………………………………………………………….... 55 5.2.1 Communication Protocol…………………………………….. 55
5.3 The Implemented Multi-port Device…………………………………57 5.3.1 General Description………………………………………….. 57 5.3.2 Voltage Regulator……………………………………………. 57 5.3.3 LCD Module…………………………………………………. 58 5.3.4 Microcontroller Module……………………………………… 61
5.3.4.1 Reset Process………………………………………. 61 5.3.4.2 Oscillator…………………………………………… 61 5.3.4.3 Serial Communication with USART………………. 61 5.3.4.4 Serial Communication with Inverted Logic……….. 63
5.3.5 Operational Principles of Multi-port Device………………….63 5.3.6 Flow Diagram of Microcontroller Code………………………66 5.3.7 Circuit Diagram……………………………………………… 69
5.4 The Digital Electricity Meter………………………………………… 72 5.4.1 General Description………………………………………….. 72 5.4.2 EDIS (Energy Data Identification System)…………………... 73 5.4.3 Combi Meter / 4-Quadrant Meter……………………………. 74
5.4.3.1 Combi Meter……………………………………….. 74 5.4.3.2 Four-Quadrant Meter………………………………. 75
5.4.4 Modules……………………………………………………… 76 5.4.4.1 Power Unit………………………………….……… 77 5.4.4.2 Suppressor Circuits………………………………… 77 5.4.4.3 Modular Construction……………………………… 78
5.4.5 Digital Measuring Mechanism……………………….………. 78 5.4.5.1 Measurement principle…………………….……….. 78 5.4.5.2 Voltage measurement……………………...………..78 5.4.5.3 Current measurement………………………………. 79 5.4.5.4 Digitization…………………………...……………. 79
ix
5.4.5.5 Integral values……………………………………… 79 5.4.5.6 Measurement values…………………………...…… 79 5.4.5.7 Calibration…………………………………….……. 80
5.4.6 Tariff Mechanism…………………………………….………. 80 5.4.7 Data Interface………………………………………………… 80
CHAPTER 6)- CONCLUSION…...……………………………………... 81 REFERENCES………………………………………………………….… 83
APPENDIX A – READING SOFTWARE SOURCE CODE…………….. 85 APPENDIX B – SOURCE CODE IN PICBASIC………………………... 96 APPENDIX C – MULTIPORT DEVICE USER MANUAL……………... 105 APPENDIX D – XMODEM FILE TRANSFER PROTOCOL…………… 112 APPENDIX E – COMPLETE LIST OF SERIN2/SEROUT2 MODES….. 115
x
LIST OF FIGURES Figure – 1.1 Remote Reading Infrastructure used in metering solutions….. 2 Figure – 1.2 More feasible remote reading solution with Implemented Multi-port Device………….…………………………………. 3 Figure – 1.3 Meter-Device connection….………………………………… 4 Figure – 1.4 Modem-Device connection…..………………………………. 5 Figure – 1.5 Alternative Application of Implemented Multi-port Device… 6 Figure – 1.6 Remote PC-Device connection…………….………………… 7 Figure – 2.1 DTE and DCE……………………………………………….. 11 Figure – 2.2 DB25 Male DTE device connector…………………………. 12 Figure – 2.3 DB9 Male DTE device connector…………………………… 12 Figure – 2.4 DB25 Female DCE device connector…..……………………. 13 Figure – 2.5 DB9 Female DCE device connector…….…………………… 13 Figure – 2.6 Conventional usage of signal names………...………………. 15 Figure – 2.7 Non-Return to Zero format………………………………….. 21 Figure – 3.1 PIC 16F877 Block Diagram…………………………………. 23 Figure – 3.2 Two situations of loading PC…………….………………….. 25 Figure – 3.3 PDIP package…………………………….………………….. 27 Figure – 4.1 TT/CMOS Serial Logic Waveform…….……………………. 36 Figure – 4.2 RS-232 Logic Waveform………………..…………………… 36 Figure – 4.3 Logical Regions of signal……………………………………. 36 Figure – 4.4 MAX232 pin diagram………………….…………………….. 37 Figure – 4.5 MAX232 circuit diagram……………….……………………. 37 Figure – 4.6 USART Transmit Block Diagram……………………...……. 40 Figure – 4.7 USART Receive Block Diagram………………………..…… 43 Figure – 4.8 Inverted logic connections………………………………….... 44 Figure – 5.1 Main screen of Reading Software on main PC……….....…… 47 Figure – 5.2 Main screen of Reading Software on remote PC…...……..… 49 Figure – 5.3 Reading software flow diagram (I)………….……………….. 51 Figure – 5.3 Reading software flow diagram (II)…………………………. 52 Figure – 5.4 Asynchronous transmission packets…………………………. 57 Figure – 5.5 Voltage regulation circuit……………………………………. 58 Figure – 5.6 General LCD connection diagram……………...……………. 59 Figure – 5.7 Microcontroller code flow diagram (I)………………………. 66 Figure – 5.7 Microcontroller code flow diagram (II)……………………… 67 Figure – 5.8 Multi-port device PCB diagram……………………...……… 70 Figure – 5.9 Multi-port device circuit diagram............................................. 71 Figure – 5.10 General EDIS code system…………….…………………… 74 Figure – 5.11 EDIS coding for Combi-meter……….…………………….. 75 Figure – 5.12 EDIS coding for Four-quadrant meter……………………… 76
xi
LIST OF TABLES Table – 3.1 Basic features of PIC 16F877……………………………...…. 24 Table – 5.1 Summary of the most commonly used protocols………...…… 56
1
CHAPTER 1
GENERAL DESCRIPTION OF THE SYSTEM
1.1 Introduction
Electricity meters functioned according to electromechanical principles
until 1980’s. Therefore, desired measures in accuracy, reliability, lifetime and
price of metering solutions could not be attained. Since that time, electronics has
made a remarkable development. Today electricity meters are mass-produced
using the most modern microelectronics. This digital processing technology is not
only providing better solutions than the classical measurement technology but also
is able to operate with auxiliary devices (e.g. modem). Also these high technology
meters enable the consumers to construct very feasible remote reading
infrastructures via their advanced communication facilities.
Within this scope, in this thesis, an implemented device will be presented
and elucidated as a solution for simplifying the remote reading infrastructures of
digital electricity meters by means of reducing the number of components used in
the system.
1.2 Common Remote Reading Infrastructure
Figure – 1.1 shows the brief model of a system, which is used very
commonly in the metering sector. The system mainly consists of a PC including
software for remote reading purpose, a modem at PC side, a telephone line
dedicated to the PC side modem, modems for each meter at remote side and
dedicated telephone lines for each modem. This kind of infrastructure has been
widely used in metering systems, especially in high power plants, multi lined
power plants and auto-producers. The main difficulty in this kind of systems is
the necessity of modem and telephone line for each meter. Using a small but
sufficient telephone exchange instead of using one dedicated line for each meter
can eliminate this hardship a bit. But using a modem for each meter is an
unavoidable necessity for these kinds of systems.
2
Figure – 1.1 Remote Reading Infrastructure used in metering solutions
1.3 Developed Remote Reading Infrastructure
3
Figure – 1.2 More feasible remote reading solution with Implemented Multi-port
Device
4
Considering the previous mentioned issues, Figure – 1.2 shows the same
which is the subject of this thesis. As in Figure – 1.2, there is
o need to have modems and telephone lines for each meter any more. One
nnector at the other end for the serial
port of
system in Figure – 1.1 but materialized by the implemented multi-port device,
it can be seen clearly
n
telephone line and one modem connected to the multi-port device is now enough
to communicate with more than one meter.
In a system shown in Figure – 1.2, the PC establishes the communication
with the multi-port device over PSTN. The direct connection between PC and
modem is done by original modem cable, which has 25-pin female connector for
the end of modem side, and 9-pin female co
PC. In addition to that, two different types connection cables are also
needed in the system; one of which is to be used for connection between remote
modem and the multi-port device, and the other of which to be used for
connection between multi-port device and each meter. The pin specifications of
these cables are shown in Figure – 1.3 and 1.4.
Meter Side RJ-12 Male Socket - Device
E: empty, not used
Figure – 1.3 Meter-Device connection
5
Modem Side (25-pin Male) RJ-12 Male Socket - Device
E: empty, not used
Figure – 1.4 Modem-Device connection
Using the software running on the PC, which will be described in Chapter
5, the user enters the telephone number of the remote modem for dialing. After the
communication is established b user chooses only the port of
the implemented multi-port device to which the meter is connected. Right after
the reception of the lti-port device, the
microcontroller in the device sends the string to the specified port according to the
Flag p
the reception process, an indication message demonstrating a
continuing data reception appears on the LCD. After data reception is completed,
etween two ends, the
port number of the meter by the mu
rotocol, which arranges the communication rules of the meter with the
peripherals. If the meter is password protected, it will reply with a specific string
that indicates a password requirement or if there is no meter connected to this
port, time-out occurs and the multi-port device sends a related message to the user
station. A similar message is also sent to LCD on the device for local recognition
by the users.
If there is a meter connected to a specified port and the meter is not
password protected, it will reply in 20 msec after receiving a request according to
the protocol. If the request is standard readout request of the meter, the meter will
send all the standard readout data character by character to the multi-port device
and the multi-port device sends all the characters to the PC as soon as it receives
them. During
6
the mu
Figure – 1.5 Alternative Application of Implemented Multi-port Device
lti-port device sends another message indicating the completed readout
process to both LCD and user station and then starts to wait for the next request.
1.4 Alternative Application of Multi-port Device
7
As shown in Figure – 1.5, the implemented multi-port device has 4 ports
(expandable to 8) apart from the port providing the connection to the remote
modem. Four digital electricity meters can be connected to these ports as well as
one PC and three digital electricity meters. As shown in Figure – 1.5 the device
connected to the port 1 may be a PC or a digital electricity meter according to the
application. The application with a PC connected to port 1 provides the users to
carry out two-way file transfer between the main PC and the remote PC. This two-
way file transfer process is performed according to Xmodem file transfer protocol.
The details of Xmodem protocol are explained in Appendix D. The pin
specifications of the connection cable between the multi-port device and remote
PC is as shown in Figure – 1.6.
Remote PC Side DB9 Female RJ-12 Male Socket – Device
E: empty, not used
Figure – 1.6 Remote PC-Device connection
1.5 Objective of This Thesis
This thesis aims to reduce the number of components used in the remote
reading infrastructures of digital electricity meters and thus simplify the system
together with a cost reduction.
The topic of meter remote reading has become very popular in last decade
in the world and almost all producers have integrated communication interfaces to
their meters, which provide the capability of remote access. Correspondingly,
8
rofessional remote reading infrastructure, several
ompanies with different proficiencies should work together. For example, The
W in
Australia and their meter remote reading infrastructure has been constructed based
on GSM technology by a group being composed of CallDirect
Telecommunications, Nokia and a software development company. Another
example is Clark Public Utilities, which is a customer-owned utility providing
electricity, water and wastewater service in Clark County, Washington and they
have more 164.000 electricity customer and 26.000 water customer. The meters of
customers are connected to the remote reading system by radio transmitter or
telephone line according to met ess.
The remote 1.1 and 1.2 may
sometimes need many more meters as m ntioned previous examples, which will
also mean more modems and more inter-phone lines or dedicated lines. At most of
the sites where a lot o er with inter-phone or
edicated lines, various problems might be come across. For instance, enough
aller space a system requires, the more adaptable
ber of ports of implemented multi-port device
several companies, such as CallDirect Telecommunications [Ref. 19], Adaptive
Networks [Ref. 20], Enermet [Ref. 21], PERAX Remote Automated Management
Systems [Ref. 22], started to carry on business related with constructing remote
reading infrastructures for meters.
In order to construct a p
c
Integral Energy is the second largest state-owned energy corporation in NS
er type and feasiblen
reading infrastructures illustrated in Figure –
e
f modems will be installed togeth
d
space for modems could not be found on the panel where the meters will be put.
Additionally, operating and maintaining too many devices is not very simple.
It is obvious that the sm
the system is. Therefore reducing the number of devices used in a system is an
engineering matter, which provides several advantages including maintenance
ease.
As an example, when we consider a remote reading infrastructure having
32 meters, an implemented 4-port multi-port device will be able to decrease the
number of modems and phone lines to 8. This type of a reduction in the system
will be more remarkable if the num
is expanded to 8.
9
ances this two-way file
that
the PIC
explained in details in Chapter 4. Finally, the developed remote access
softwar
hich is written by using PicBasic Pro, is presented in Appendix
Moreover, if the implemented multi-port device is connected to a PC
together with digital electricity meters as shown in Figure – 1.5, this application
will provide two-way file transfer between the main PC and the remote PC. The
readout data of a meter contains all the information that the meter has, such as all
energy registers according to tariff measurements and their old values, all mean
power values, instantaneous date and time, meter serial number, error code giving
the current situation of the meter, etc. With regard to that, the readout data of the
meters or some evaluation reports of this readout data may be necessary to be
shared between the remote ends. Under the circumst
transfer opportunity can simplify this process fairly.
The system constructed in the scope of this thesis will be explained in next
chapters by giving the details about operating principles of used components and
devices, designing of multi-port device and code implementation.
First of all, the basics of serial communication and RS 232 standard, which
constitute the base of interface between multi-port device and peripherals such as
digital electricity meters and computers, will be explained in Chapter 2. After
16F877, which is the microcontroller used in the multi-port device, will
be explained in Chapter 3. Then the fundamentals of serial communication with
the microcontrollers, which is the main issue performed by the multi-port device,
will be
e, modems, implemented multi-port device and digital electricity meters,
which are the main parts of the system, will be described in Chapter 5.
The source code of developed remote access software written by using
Delphi 7.0 is presented in Appendix A and the code of PIC 16F877
microcontroller, w
B. In Appendix C the user manual of multi-port device is given. The Appendix D
includes the details of Xmodem, which is the protocol used for the file transfer
between main PC and remote PC. The final appendix gives the serial
communication modes in PicBasic Pro, which is explained in Chapter 4.
10
ly between
different
anufacturers. From these ideas, the RS232 standard, which is the short of
ecommended Standard-232, was born. It specified signal voltages, signal timing,
ignal function, a protocol for information exchange, and mechanical connectors.
Over the 40 years since this s dard was developed, the Electronic
Industries Association published ons, the most recent being the
EIA232E standard introduced in 1991 [Ref. 12]. Besides changing the name from
RS232 to EIA232, some signal lines were
defined, inclu
CHAPTER 2
DATA COMMUNICATION INTERFACE
2.1 Introduction
SCI is an abbreviation for Serial Communication Interface, as a special
subsystem, and it exists on most microcontrollers. In the early 1960s, a standards
committee, today known as the Electronic Industries Association, developed a
common interface standard for data communications equipment. At that time, data
communications was thought to mean digital data exchange between a centrally
located mainframe computer and a remote computer terminal, or possib
two terminals without a computer involved. These devices were linked by
telephone voice lines, and consequently required a modem at each end for signal
translation. While simple in concept, the chances for data errors that could occur
when transmitting data through an analog channel are considerably high and
therefore transmission over phone lines require a relatively complex design. It was
thought that a standard was needed first to ensure reliable communication, and
second to enable the interconnection of equipment produced by
m
R
s
tan
three modificati
renamed and various new ones were
ding a shield conductor.
11
2.2 EIA232 Standard
If the full EIA232 standard is implemented, the equipment at the far end of
the connection, which is named as DTE device (Data Terminal Equipment,
usually a computer or terminal), has a male DB25 connector, and utilizes 22 of the
25 available pins for signals or ground. Equipment at the near end of the
connection (the telephone line interface), which is named as DCE device (Data
Circuit-terminating Equipment, usually a modem), has a female DB25 connector,
and utilizes the same 22 available pins for signals and ground. The cable linking
DTE and DCE devices is a parallel straight-through cable. If all devices exactly
followed this standard, all cables would be identical, and there would be no
chance that an incorrectly wired cable could be used. Figure – 2.1 shows the
orientation and connector types for DTE and DCE devices:
Figure – 2.1 DTE and DCE
Figure – 2.1 also shows EIA232 communication function and connector
types for a personal computer and modem. DCE devices are sometimes called
“Data Communications Equipment” instead of Data Circuit-terminating
Equipment [Ref. 3].
Figure – 2.2 DB25 Male DTE device connector
Figure – 2.3 DB9 Male DTE device connector
Figure – 2.2 and Figure – 2.3 is the full EIA232 signal definition for the
DTE device (usually the PC). The most commonly used signals are shown in
bold. 12
13
Figure – 2.4 DB25 Female DCE device connector
Figure – 2.5 DB9 Female DCE device connector
the DCE device (usually the m
Figure – 2.4 and Figure – 2.5 show the full EIA232 signal definition for
odem). The most commonly used signals are
shown in bold.
14
Many of the 22 signal lines in the EIA232 standard pertain to connections
where the DCE device is a modem, and then are used only when the software
protocol employs them. For any DCE device that is not a modem, or when two
DTE devices are directly linked, fewer signal lines are necessary.
It can be noticed that in the pin-out drawings there is a secondary channel,
which includes a duplicate set of flow-control signals. This secondary channel
provides the management of the remote modem, enables retransmission when a
parity error is detected and also provides other control functions. Furthermore, it
enables baud rates to be changed during the flow. This secondary channel, when
used, is typically set to operate at a very low baud rate in comparison with the
primary channel to ensure reliability in the control path. In addition, it may
operate as either a simplex, half-duplex, or full-duplex channel, depending on the
capabilities of the modem [Ref. 3].
Transmitter and receiver timing signals (pins 15, 17, and 24) are used only
for a synchronous transmission protocol. For the standard asynchronous 8-bit
protocol, external timing signals are unnecessary.
Signal names that imply a direction, such as Transmit Data and Receive
Data, are name d were strictly
followed, these signals would have the same name for the same pin number on the
DCE side as well. Unfortunately, most engineers do not do this in practice,
probably because no one pays attention to which side is DTE and which is DCE.
As a result, direction-sensitive signal names are changed at the DCE side to reflect
their drive direction at DCE. Figure – 2.6 gives the conventional usage of signal
names:
d according to DTE device. If the EIA232 standar
Figure – 2.6 Conventional usage of signal names
ctions
3 - Secondary communications channel: If implemented, this is
sed for control of the remote modem, requests for retransmission when errors
occur.
4 - Modem status and control signals: These signals indicate
modem status and provide intermediate checkpoints as the telephone voice
channel is established.
5 - Transmitter and receiver timing signals: If a synchronous
protocol is used, these signals provide timing information for the transmitter and
receiver, which may operate at different baud rates.
2.3 EIA232 Signal Fun
Signal functions in the EIA232 standard can be divided into six
subcategories. These categories are summarized as below. After that each signal
category is described more comprehensively.
1 - Signal ground and shield.
2 - Primary communications channel: This is used for data
interchange and includes flow control signals.
u
15
16
6 - Channel test signals: Before data is interchanged, the channel
may be tested for its integrity, and the baud rate automatically adjusted to the
maximum rate that the channel could support.
2.3.1 Signal Ground and Shield
Pin 7, pin 1, and the shell are included in this category. Cables provide
separate paths for each, but internal wiring often connects pin 1 and the cable
shell/shield to signal ground on pin 7.
Pin 7 – Ground: All signals are referenced to a common ground, as defined by the
voltage on pin 7. This conductor may or may not be connected to protective
ground inside th otential within
the cable makes the EIA232 standard different from a balanced differential
voltage standard, such as EIA530, which provides far greater noise immunity.
2.3.2 Primary Communications Channel
Pin 2 -
e DCE device. The existence of a defined ground p
Transmitted Data (TxD): This signal is active when data is transmitted
from the DTE device to the DCE device. When no data is transmitted, the signal
is held in the mark condition (logic 1, negative voltage).
It s DCE device is commonly labeled
“Received
t to be destined for a remote DTE
device.
Received Data (RxD):
hould be noted that pin 2 on the
Data”, although by the EIA232 standard it should still be called
“Transmitted Data” because the data is though
Pin 3 - This signal is active when the DTE device receives
data from
ted that pin 3 on the DCE device is commonly labeled
“Transmitt
the DCE device. When no data is transmitted, the signal is held in the
mark condition (logic 1, negative voltage).
It should be no
ed Data”, although by the EIA232 standard it should still be called
“Received Data” because the data is thought to arrive from a remote DTE device.
17
Pin 4 - Request to Send (RTS): This signal is changed to space condition (logic 0,
positive voltage) to prepare the DCE device for accepting transmitted data from
the DTE device. Such preparation might include enabling the receive circuits, or
in half-duplex applications. When the DCE is
ady, it acknowledges by changing Clear To Send to positive voltage.
tined for a remote DTE device.
setting up the channel direction
re
It should be noted that pin 4 on the DCE device is commonly labeled Clear
to Send, although by the EIA232 standard it should still be called Request to Send
because the request is thought to be des
Pin 5 - Clear to Send (CTS): This signal is changed to space condition (logic 0,
positive voltage) by the DCE device to inform the DTE device that transmission
may begin. RTS and CTS are commonly used as handshaking signals to moderate
the flow of data into the DCE device.
It should be noted that pin 5 on the DCE device is commonly labeled
“Request to Send”, although by the EIA232 standard it should still be called Clear
inate from a remote DTE device.
Pin 13 - Secondary Clear to Send (SCTS)
to Send because the signal is thought to orig
2.3.3 Secondary Communications Channel
Pin 14 - Secondary Transmitted Data (STxD)
Pin 16 - Secondary Received Data (SRxD) Pin 19 - Secondary Request to Send (SRTS)
These signals are equivalent to the corresponding signals in the primary
communications channel. The baud rate, however, is typically much slower in the
secondary channel for increased reliability.
18
.3.4 Modem Status and Control Signals 2
Pin 6 - DCE Ready (DSR): When originating from a modem, this signal is
changed to space condition (logic 0, positive voltage) when the following three
conditions are all satisfied:
1 - The modem is connected to an active telephone line that is “off-hook”,
If the line goes “off-hook”, a fault condition is detected or a voice
e that the device is turned on and ready to
functio
TE
evice may be programmed to ignore this signal.
2 - The modem is in data mode, not voice or dialing mode,
3 - The modem has completed dialing or call setup functions and it is
generating an answer tone.
connection is established, the DCE Ready signal is changed to mark condition
(logic 1, negative voltage).
If DCE Ready originates from a device other than a modem, it may be
changed to space condition to indicat
n, or it may not be used at all. If unused, DCE Ready should be
permanently held in space condition (logic 0, positive voltage) within the DCE
device or by use of a self-connect jumper in the cable. Alternatively, the D
d
Pin 20 - DTE Ready (DTR): This signal is changed to space condition (logic 0,
ositive voltage) by the DTE device when it wishes to open a communication
annel ondition
e circuit, and once connected,
aintai ged to mark condition (logic
, negative voltage), the modem is switched to "on-hook" to terminate the
xample, a printer) is not responding,
onfirm that DTE Ready is changed to space condition.
in 8 - Received Line Signal Detector (CD):
p
ch . If the DCE device is a modem, changing DTE Ready to space c
prepares the modem to be connected to the telephon
m ns the connection. When DTE Ready is chan
1
connection.
If the DCE device is not a modem, it may require DTE Ready to be
changed to space condition before the device can be used, or it may ignore DTE
Ready altogether. If the DCE device (for e
c
P It is also called carrier detect. This
signal is relevant when the DCE device is a modem. It is changed to space
19
e modem when the telephone line is
off-hook”, a connection has been established, and an answer tone is being
quirements (perhaps due to a noisy channel).
Pin 12
condition (logic 0, positive voltage) by th
“
received from the remote modem. The signal is changed to mark condition when
no answer tone is being received, or when the answer tone is of inadequate quality
to meet the local modem's re
- Secondary Received Line Signal Detector (SCD): This signal is
equival
ent to the Received Line Signal Detector (pin 8), but refers to the
secondary channel.
Pin 22 - Ring Indicator (RI): This signal is relevant when the DCE device is a
modem, and is changed to space condition (logic 0, positive voltage) when a
ringing signal is being received from the telephone line. The time of holding in
space condition for this signal will approximately equal the duration of the ring
signal, and it will be held in mark condition between rings or when no ringing is
present.
Pin 23 - Data Signal Rate Selector: This signal may originate either in the DTE or
CE devices (but not both), and is used to select one of two prearranged baud D
rates. The space condition (logic 0, positive voltage) selects the higher baud rate.
2.3.5 Transmitter and Receiver Timing Signals
Pin 15 - Transmitter Signal Element Timing (TC): It is also called Transmitter
Clock. This signal is relevant only when the DCE device is a modem and is
operating with a synchronous protocol. The modem generates this clock signal to
control
l
ontinuously, except when it is performing internal diagnostic functions.
exactly the rate at which data is sent on Transmitted Data (pin 2) from the
DTE device to the DCE device. The logic 1 to logic 0 (negative voltage to
positive voltage) transition on this line causes a corresponding transition to the
next data element on the Transmitted Data line. The modem generates this signa
c
20
Pin 17 - Receiver Signal Element Timing (RC): It is also called Receiver Clock.
This signal is similar to TC described above, except that it provides timing
information for the DTE receiver.
Pin 24 - Transmitter Signal Element Timing (ETC): It is also called External
nsition (negative voltage to positive voltage) indicates the
e-center of the data element. Timing signals will be provided whenever the
Transmitter Clock. Timing signals are provided by the DTE device for use by a
modem. This signal is used only when TC and RC (pins 15 and 17) are not in use.
The logic 1 to logic 0 tra
tim
DTE is turned on, regardless of other signal conditions.
2.3.6 Channel Test Signals
Pin 18 - Local Loopback (LL): This signal is generated by the DTE device and is
used to place the modem into a test state. When local loopback is changed to
space condition (logic 0, positive voltage), the modem redirects its modulated
in 21 - Remote Loopback (RL):
output signal, which is normally fed into the telephone line, back into its receive
circuitry. This enables data generated by the DTE to be echoed back through the
local modem to check the condition of the modem circuitry. The modem changes
its Test Mode signal on Pin 25 to space condition in order to acknowledge that it
has been placed in local loopback condition.
P
is used to place the remote modem into a test state. When remote loopback is
changed to space condition (logic 0, positive voltage), the remote modem
redirects its received data back to its transmitted data input, thereby re-modulating
the received data and returning it to its source. When the DTE initiates such a test,
transmitted data is passed through the local modem, the telephone line, the remote
modem, and back, to exercise the channel and confirm its integrity. The remote
modem signals the local modem to change pin 25 to space condition when the
remote loopback test is in progress.
This signal is generated by the DTE device and
21
in 25 - Test Mode (TM):P This signal is relevant only when the DCE device is a
lso cause Test Mode to be changed to space
condition.
standard used in 1950s
teletype machines in which a flowing current (and hence a low voltage) represents
gative logic assignment of EIA232 is the reverse of
ost modern digital circuit designs.
modem. When changed to space condition (logic 0, positive voltage), it indicates
that the modem is in a local loopback or remote loopback condition. Other
internal self-test conditions may a
2.4 Electrical Standards The EIA232 standard uses negative, bipolar logic in which a negative
voltage signal represents logic 1, and positive voltage represents logic 0. This
probably originated with the pre-RS232 current loop
logic 1. Be aware that the ne
that found in m
The EIA232 standard includes a common ground reference on Pin 7, and
is frequently joined to Pin 1 and a circular shield that surrounds all 25-cable
conductors. Data, timing, and control signal voltages are measured with respect to
this common ground. EIA232 cannot be used in applications where the equipment
on opposite ends of the connection must be electrically isolated. Optical isolators
may be used to achieve ground isolation, however, this option is not mentioned or
included in the EIA232 specification [Ref. 3].
Figure –2.7 Non-Return to Zero format
Standard NRZ (Non Return to Zero) format is also known as 8 (9)-N-1 (8
or 9 data bits, with/without parity bit and with one stop bit). Free line is defined as
22
s is when the data line is held in a logic 0 state for a time long enough
to send an entire word. Therefore if the line is not put back into an idle state, then
the receiving end will inte
the status of logic 1. Start of transmission - Start Bit, has the status of logic 0. The
data bits follow the start bit (the first bit is the low significant bit-LSB), and after
the bits we place the Stop Bit as logic 1. If there is no more data coming then the
receive line will stay in idle state (logic 1). There is another signal called as Break
Signal. Thi
rpret this as a break signal.
The duration of the stop bit “T” depends on the transmission rate and is
adjusted according to the needs of the transmission. For the transmission speed of
9600 baud, T is 104 µS.
23
ntrollers
CHAPTER 3
PIC 16F877 MICROCONTROLLER
3.1 General Overview to Microco
Figure – 3.1 PIC 16F877 Block Diagram [Ref. 8]
24
Microcontroller is a single integrated ircuit containing specialized circuits
and functions that are applicable to ontrol based systems. The
microcontrollers are low-cost and high performance devices and mostly use
Reduced Instruction Set Computer (RISC) architecture. The core blocks of a
microcontroller are s
between microprocessor and microcontroller is that microcontrollers also
incorporate on torage), and
peripherals, which would be externally icroprocessor system.
This arrangement simplifies the design of microcontroller systems. On the other
hand, the peripherals are generally simpler than external device and the amount of
available memory would be much smaller [Ref. 2].
Figure – 3.1 shows the layout of architecture of the PIC 16F877
microcontroller [Ref. 8], which is manufactured by Microchip Technology. The
key features of the PIC 16F877 microcontroller are shown in the Table – 3.1
below.
Table – 3.1 Basic features of PIC 16F877
Key Features PIC 16F877
c
intelligent and c
imilar to those of a microprocessor. The main difference
board RAM, EPROM (for program and data s
interfaced on a m
Operating Frequency DC - 20 MHz Resets (and Delays) POR, BOR (PWRT, OST)
FLASH Program Memory 8K x 14bit Data Memory 368 bytes
EEPROM Data Memory 256 bytes
Interrupts 14
I/O Ports Ports A,B,C,D,E
Timers 3
Serial Communication MSSP, USART
Capture/Compare/PWM Modules 2
Parallel Communications PSP
10-bit Analog-to-Digital Module 8 input channels
Instruction Set 35 instructions
25
3.1.1 P
y space. That means that the
PIC 16
es from the PCL register, which is a readable and writable register. The
upper 4 bits are not readable, but are indirectly writable through the PCLATH
register. On any RE eared. Figure – 3.2
hows the two situations for the loading of the PC. The upper example in the
figure shows how ed on a write to lower example in
the figure shows how the PC is loaded during a CALL or GOTO instruction.
rogram Counter and Program Memory EPROM
The program counter is used to fetch each instruction in order.
Modifications to the program counter by JUMP instructions affect program flow.
Program memory is addressed word-wise, rather than byte-wise, so the first
instruction is located at 0x000, the second at 0x001, etc. Program memory is
organized into pages. Memory pages can be selected using the PCLATH register.
There are three memory blocks in each of the PIC16F877 microcontrollers. The
Program Memory and Data Memory have separated buses so that concurrent
access can occur. The PIC16F877 microcontrollers have a 13-bit program counter
capable of addressing an 8K x 14 program memor
F877 microcontrollers have 8K x 14 words of FLASH program memory
[Ref. 8].
As mentioned before, the program counter (PC) is 13-bits wide. The low
byte com
SET, the upper 5 bits of the PC will be cl
s
the PC is load PCL and the
Two situations of loading PC
Figure – 3.2
26
deep and 13-bit wide
ardware stack, which operates as a circular buffer. The stack space is not a part
variable storage, or user settings. The data memory of the PIC 16F877
icroc
and
peripheral.
3.1.3 Arithmetic Logic Unit
Actual arithmetic instructions (add, subtract, shift, AND, OR, etc.) are
carried out here. The results of arithmetic instructions are generally stored in the
working (W) register, although some instructions allow a file register to be
operated on directly. The contents of the W register can be transferred to the I/O
ports, or used as an indirect address to access program or data memory.
The PIC 16F877 microcontrollers have an 8-level
h
of neither program space nor data space and the stack pointer is not readable or
writable. The PC is pushed onto the stack when a CALL instruction is executed,
or an interrupt causes a branch. The stack is popped in the event of a RETURN, a
RETLW or a RETFIE instruction execution. PCLATH is not affected by a PUSH
or POP operation.
3.1.2 Data RAM
Data RAM is organized as file registers (usually 8 bit) which are both
readable and writable. Data RAM can be used to hold data for calculations,
temporary
m ontroller is partitioned into multiple banks each of which has 128 bytes
long. A specific bank can be selected by setting special bits (RP0 and RP1) of the
STATUS register. All implemented banks contain Special Function Registers,
which may be mirrored in another bank for code reduction and quicker access.
Special Function Registers are registers used by CPU and peripheral modules for
controlling the desired operation of the device. These registers, which are
implemented as static RAM, can be classified into two groups: core (CPU)
27
3.1.4 I/
xternal reset is used, the pin should be tied to Vdd. The PIC
6F877 microcontroller has A (6 pins), B (8 pins), C (8 pins), D (8 pins) and E (3
33 pins.
O ports
The PIC 16F877 microcontroller is 40-pin device as shown in Figure – 3.3
[Ref. 8]. Vdd and Vss pins provide power and ground references, respectively.
There are two ports for external oscillator connection. The Master Clear/Reset pin
(MCLR) is used to reset the PIC device externally. This could be tied to a system-
reset circuit. If no e
1
pins) ports, totally
Figure – 3.3 PDIP package
n for the
eripheral features on the device. The function of the pin (input, output, or
eripheral) is determined by internal control registers. In general, when a
eripheral is enabled, that pin may not be used as a general purpose I/O pin.
The generic I/O ports are bidirectional pins that can be set up for input (the
microcontroller reads the data on the pins) or output (the microcontroller sets the
value on the pins) by the code. For output, each pin has an internal latch to drive
the output. Some I/O ports are multiplexed with the onboard peripherals. Some
pins for these I/O ports are multiplexed with an alternate functio
p
p
p
28
.1.4.1 PORTA and the TRISA Register
gister reads the status of the pins, whereas writing to
it will write to the port latch. All write operations are read-modify-write
operations. Pin RA4 is multiplexed with the Timer0 module clock input. This pin
is a Schmitt Trigger input and an open drain output. All other PORTA pins have
TTL input levels and full CMOS output drivers. Other PORTA pins are
multiplexed with analog inputs and analog VREF input. The operation of each pin
is selected by clearing or setting the control bits in the ADCON1 register (A/D
Control Register1). It should be noted that on a Power-on Reset (POR), these pins
are configured as analog inputs and read as '0'. The TRISA register controls the
direction of the RA pins, when they are being used as analog inputs.
3.1.4.2 PORTB and the TRISB Register
PORTB is an 8-bit wide, bi-directional port and the corresponding data
direction register is TRISB multiplexed with the Low
Voltage Programming function. Each of the PORTB pins has a weak internal pull-
up. A s
e the
3
PORTA is a 6-bit wide, bi-directional port and the corresponding data
direction register is TRISA. Setting a TRISA bit (one) will make the
corresponding PORTA pin an input (i.e., put the corresponding output driver in a
Hi-Impedance mode). Clearing a TRISA bit (zero) will make the corresponding
PORTA pin an output (i.e., put the contents of the output latch on the selected
pin). Reading the PORTA re
. Three pins of PORTB are
ingle control bit can turn on all the pull-ups. This is performed by clearing
bit RBPU (bit 7 of OPTION_REG register). The weak pull-up is automatically
turned off when the port pin is configured as an output. The pull-ups are disabled
on a Power-on Reset.
Four of the PORTB pins (RB4, RB5, RB6 and RB7) have an interrupt-on-
change feature. Only pins configured as inputs can cause this interrupt to occur.
These input pins are compared with the old value latched on the last read of
PORTB. The mismatched outputs of these pins are OR’ed together to generat
29
RB Port Change Interrupt with flag bit RBIF (bit 0 of INTCON register). This
. In the Interrupt Service Routine the
terrupt can be cleared in the following manner:
e TRISC bit
verride is in effect while the peripheral is enabled, read-modify-write
ISC as destination, should be avoided.
.1.4.4
3.1.4.5
the I/O control inputs for the microprocessor port when bit PSPMODE is set. In
interrupt can wake the device from SLEEP
in
a) Any read from or write to PORTB.
b) Clear flag bit RBIF.
This interrupt-on-mismatch feature, together with software configurable
pull-ups on these four pins, allow easy interface to a keypad and make it possible
for wake-up on key depression. RB0 is an external interrupt input pin and is
configured using the INTEDG bit (bit 6 of OPTION_REG register).
3.1.4.3 PORTC and the TRISC Register
PORTC is an 8-bit wide, bi-directional port and the corresponding data
direction register is TRISC. PORTC is multiplexed with several peripheral
functions, and PORTC pins have Schmitt Trigger input buffers. When enabling
peripheral functions, care should be taken in defining TRIS bits for each PORTC
pin. Some peripherals override the TRISC bit to make a pin an output, while other
peripherals override the TRISC bit to make a pin an input. Since th
o
instructions (BSF, BCF, XORWF) with TR
3 PORTD and TRISD Registers
PORTD is an 8-bit port with Schmitt Trigger input buffers. Each pin is
individually configurable as an input or output. PORTD can be configured as an
8-bit wide microprocessor port (parallel slave port) by setting control bit
PSPMODE (bit 4 of TRISE register). In this mode, the input buffers are TTL.
PORTE and TRISE Register
PORTE has three pins, which are individually configurable as inputs or
outputs. These pins have Schmitt Trigger input buffers. The PORTE pins become
30
egister also controls the parallel
slave p iplexed with analog inputs. When
selected for analog input, these pins will read as ’0’s. The user must make sure to
keep th
ybe included on the chip. The various
pes included by the PIC 16F877 microcontroller are summarized below:
enerates a digital result of this analog level via successive approximation. The
l results in a corresponding 10-bit digital
umber. The A/D module has high and low voltage reference input that is
softwar
The A/D module has four registers. These registers are:
ESH)
• A/D Result Low Register (ADRESL)
•
this mode, the user must make certain that the bit 0, bit 1 and bit 2 of TRISE are
set, and that these pins are made digital inputs by configuring ADCON1 register.
In this mode, the input buffers are TTL. TRISE r
ort operation. PORTE pins are mult
e pins configured as inputs when using them as analog inputs. On a Power-
on Reset, these pins are configured as analog inputs, and read as ‘0’.
3.1.5 Peripherals
There are many peripherals that ma
ty
Analog to Digital Converters: Analog inputs on some pins are converted to a
digital value, which can then be processed by the microcontroller. This is useful
for obtaining data from external devices like thermistors, accelerometers, and
other sensors. The PIC 16F877 microcontroller has 10-bit ADC module with 8
input channels.
The analog input charges a sample and hold capacitor. The output of the
sample and hold capacitor is the input into the converter. The converter then
g
A/D conversion of the analog input signa
n
e selectable to some combination of VDD, VSS, RA2, or RA3.
The A/D converter has a unique feature of being able to operate while the
device is in SLEEP mode. To operate in SLEEP, the A/D clock must be derived
from the A/D’s internal RC oscillator.
• A/D Result High Register (ADR
A/D Control Register0 (ADCON0)
• A/D Control Register1 (ADCON1)
31
ler USART
odule will be explained comprehensively in Chapter 4.
Master Synchronous Serial Port (MSSP): This module provides a mode in
which
r or a
peripheral, which may be a serial EEPROM, shift register, display drivers, A/D
•
•
o 8-bit registers (TMR1H, TMR1L)
The ADCON0 register controls the operation of the A/D module. The
ADCON1 register configures the functions of the port pins.
Universal Synchronous/Asynchronous Receiver/Transmitter (USART):
This device allows the microcontroller to interface serially with other devices
through protocols such as RS232. The PIC 16F877 microcontrol
m
Data bus, RD, WR, and Chip Select are all made available. This allows the
microcontroller to be interfaced to a microprocessor, a microcontrolle
converters, etc. The MSSP module can operate in one of two modes, such as
Serial Peripheral Interface (SPI) and Inter-Integrated Circuit (I2C). The I2C bus is
a proprietary serial bus developed by Microchip Technology. Not all
microcontrollers have both I2C Master function and I2C Slave function, but
16F877 has.
Timers: Timers can be used to time events. Timers have an advantage over
merely using wait loops in that other processing can take place while the timer is
running. 16F877 has three independent timers.
Timer 0 has the following features:
• 8-bit timer/counter
Readable and writable
• Software programmable prescaler
• Internal or external clock select
Interrupt on overflow from FFh to 00h
• Edge select for external clock
Timer 1 has the following features:
• 16-bit timer/counter consisting of tw
32
le
Interrupt on overflow from FFFFh to 0000h
• Software programmable prescaler and postscaler
Capture register
• 16-bit Compare register
identical in operation, with the
excep al event trigger.
gramming Procedure
dio programming environment was
used it to the microcontroller. MicroCode Studio
is a powerful, visual Integrated Development Environment (IDE) with In Circuit
Debugging (ICD) capability with PicBasic PRO compiler [Ref. 9]. The code
explo s,
• Readable and writab
• Software programmable prescaler
• Internal or external clock select
•
Timer 2 has the following features:
• 8-bit timer/counter
• Readable and writable
• Interrupt on overflow from FFh to 00h
Capture/Compare/PWM (CCP): This module allows the microcontroller to
watch an input until it reaches a certain value, then take some action. It is
especially useful for implementing Pulse Width Modulation (PWM) schemes. The
PIC 16F877 microcontroller has two CCP module, each contains 16-bit register
which can operate as a:
• 16-bit
• PWM Master/Slave Duty Cycle register
Both the CCP1 and CCP2 modules are
tion being the operation of the speci
3.2 Microcontroller Pro
During this thesis study MicroCode Stu
to compose the code and to load
rer allows the user to automatically jump to include files, defines, constant
33
varia s, symbols and labels that are contained within the
sourc set up the compiler, assembler and
progr t MicroCode Studio do it for him with its
built embler errors can easily be
identified and corrected using the error results window. MicroCode Studio even
provi .
ugger (ICD) enables the user to execute a PicBasic
Progr ontroller and view variable values, Special Function
Regis is executing. The user
can to h the PicBasic code line by line.
PicBasic programming language, which can be defined as compiler in
nique.co.uk/code-studio/
icBasic code in MicroCode Studio, hex code is
create code is sent to microcontroller via ICProg PIC
progr grammer in MicroCode Studio
ptionally. ICProg allows the user to program all types of serial programmable
Integra
VR, 80C51 etc. using
indows 95/98/NT/2000/ME/XP. ICProg or other equivalent PIC programmers
an be obtained from Internet easily.
bles, aliases and modifier
e code. It is easy for a user to
ammer options or the user can le
in auto-search feature. Compilation and ass
des a serial communications window
The In Circuit Deb
am on a host PIC microc
ters (SFR), memory and EEPROM as the program
ggle multiple breakpoints and step throug
MicroCode Studio, has nearly 100 different and powerful commands. These
commands were determined according to the microcontroller needs, so PicBasic
helps the user to write powerful codes much simpler than assembly. MicroCode
Studio can be obtained from the following web page [Ref. 16]:
http://www.meca
After compiling the P
d automatically. This hex
ammer, which can be defined as pro
o
ted Circuits as 12Cxx, 16Cxxx, 16Fxx, 16F87x, 18Fxxx, 16F7x, 24Cxx,
93Cxx, 90Sxxx, 59Cxx, 89Cx051, 89S53, 250x0, PIC, A
W
c
34
s
ented multi-port
device. ctioned for communicating with
other m crocontroller devices and peripherals, such as serial EEPROMs, shift
register
logic level technology. Hereafter the details
f the USART module and inverted logic level technology will be explained.
4.2 USART Module
The Universal Synchronous Asynchronous Receiver Transmitter
(USART) module is one of the two serial I/O modules embedded in PIC 16F877
microcontrollers. The USART, which is also known as a Serial Communications
CHAPTER 4
SERIAL COMMUNICATION WITH MICROCONTROLLERS
4.1 Introduction
There are two modules embedded in the PIC 16F877 microcontrollers for
serial communication purpose. These are USART (Universal Synchronou
Asynchronous Receive Transmit) module and MSSP (Master Synchronous Serial
Port) module. The USART module is mainly used in order to interface the
microcontroller with a peripheral device with RS 232. That is why the USART
module is in the scope of this thesis and it is implemented in order to perform the
serial communication between the main PC and the implem
Whereas the MSSP module is mainly fun
i
s, display drivers, A/D converters, etc. So the MSSP module is not covered
in this thesis.
In addition to these two serial communication modules, the ordinary I/O
pins can be used for serial communication purpose thanks to the advanced I/O
features of the PIC 16F877 microcontroller. This technique is named as inverted
logic level method. The serial communication between the implemented multi-
port device and the digital electricity meters and the remote PC is performed over
the 8 RB pins by using this inverted
o
35
Interface or SCI, can be configured as a full duplex asynchronous system that can
communicate with peripheral devices such as CRT terminals and personal
computers, or it can be configured as a half duplex synchronous system that can
communicate with peripheral devices such as A/D or D/A integrated circuits,
s
The USART module can be confi ured in the following modes:
- Asynchronous
- Synchronous - Master (half duplex)
cess.
the
icrocontroller is +5 V for logic one, and 0 V for logic zero, we need an
intermediary stage that will e are some chips specially
for this task. These chips receive signals from -10 to +10 V and convert
them into 0 and 5 V [Re
erial EEPROMs etc.
g
(full duplex)
- Synchronous - Slave (half duplex)
Bit 7 of RCSTA register and bit 7 and bit 6 of TRISC registers have to be
set in order to configure pins RC6 and RC7 as the Universal Synchronous
Asynchronous Receiver Transmitter.
As mentioned previously, because of the mismatch between the
TTL/CMOS signal level and RS 232 signal level, the serial data communication
between a microcontroller and a peripheral device with RS 232 interface, via
USART module must be fulfilled over a level converter device. So before giving
the details of USART module, it should be better to explain signal level
conversion pro
4.2.1 Signal Level Conversion
In order to connect a microcontroller to the serial port of a peripheral
device (EIA 232 or RS 232) properly, we need to adjust the level of the signal.
The signal level on the serial port of a PC is –10 V for logic zero, and +10 V for
logic one as shown in Figure – 4.1 and 4.2. Since the signal level on
m
convert the levels. Ther
designed
f. 1].
Figure – 4.1 TT/CMOS Serial Logic Waveform
Figure – 4.2 RS-232 Logic Waveform
Figure – 4.3 Logical Regions of signal
ch package contains 4 inverters, but only one type,
either Drivers or Receivers. The driver requires two supply rails, +7.5 to +15 V
and -7.5 to –15 V. As it could be understood this may be a problem in many
Voltages of –3 V to –25 V with respect to signal ground pin are considered
logic 1 (the marking condition), whereas voltages of +3 V to +25 V are
considered as logic 0 (the spacing condition) as shown in Figure – 4.3. The range
of voltages between –3 V and +3 V is considered a transition region for which a
signal state is not assigned.
Two common RS-232 Level Converters are the 1488 RS-232 Driver and
the 1489 RS-232 Receiver. Ea
36
37
instances where only a single supply of +5 V is present. However the advantages
of these I.C.’s are their cheapness [Ref. 3].
Another device is the MAX 232, which is used in the implemented multi-
port device. It includes a charge pump, which generates +10 V and –10 V from a
single 5 V supply. M smitters in
the same package [Ref. 1]. This is handy in many cases when you only want to
use the Transmit and Receive data lines. And also there is no need to use two
chips, one for the receive line and one for the transmit line.
AX 232 also includes two receivers and two tran
Figure – 4.4 MAX232 pin diagram
Figure – 4.5 MAX232 circuit diagram
The large valued capacitors, which are used with level converters, are not
only bulky, but also expensive. Therefore some level converter devices are
available which use smaller capacitors and even some with inbuilt capacitors.
However the MAX-232 is the most common one.
38
ode
scillator it should be
necessary to look at the PIC 16F877 data sheet [Ref. 8].
The USART module transmits and receives the LSB first. The transmitter
and receiver are functionally independent, but use the same data format and baud
rate. Parity is not supported by the hardware, but can be implemented in the
software (and stored as the ninth data bit). Asynchronous mode, which is activated
by clearing bit SYNC (bit 4 of TXSTA register), is stopped during SLEEP.
The USART Asynchronous m ing important
elements:
• Baud Rate Generator
• Sampling Circuit
• Asynchronous Transmitter
• Asynchronous Receiver
In PicBasic Pro, the parameters of USART module, which affects both
USART receiver and transmitter, must be declared at the beginning of the
program with “Define” commands as below [Ref. 5 and 6]:
Define HSER_EVEN 1 'If even parity desired
Define HSER_ODD 1 'If odd parity desired
Define baud rate
Define HSER_CLROERR 1 'Clear USART overrun error
in PicBasic Pro module are as
4.2.2 The USART Module Asynchronous M
In this mode, the USART module uses standard non-return-to zero (NRZ)
format with one START bit, eight or nine data bits, and one STOP bit. The most
common data format is 8-bit. An on-chip, dedicated, 8-bit baud rate generator can
be used to derive standard baud rate frequencies from the oscillator. In order to
define appropriate baud rate according to the employed o
odule consists of the follow
HSER_BAUD 4800 'USART
After these declarations, the transmit and receive processes in the code
with commands Hserout and Hserin respectively will be fulfilled according
defined parameters. The default settings of USART
39
data bits, none parity, 1 stop bit. Please refer to the PicBasic Pro code in
4.2.2.1
oaded until the STOP bit
has be
nable
bit TXI
it TXIE and cannot be cleared in software. It will reset only when new
data is loaded . While flag bit TXIF indicates the status of
the TXREG register, another bit TRMT (bit 1 of TXSTA register) shows the
status of the TSR register. Status bit TRMT is a read only bit, which is set when
the TSR regist ogic is tied to this bit, so the user has to
ll thi bit in order to determine if the TSR register is empty. It should be noted
ransm setti ena actual
w egis ith data
d the aud r a nsmission
XEN. Normally, when transmission is first started, the TSR register is empty. At
8
Appendix B.
USART Asynchronous Transmitter
The USART transmitter block diagram is shown in Figure – 4.6. The heart
of the transmitter is the transmit (serial) shift register (TSR). The shift register
obtains its data from the read/write transmit buffer, TXREG. The TXREG register
is loaded with data in software. The TSR register is not l
en transmitted from the previous load. As soon as the STOP bit is
transmitted, the TSR is loaded with new data from the TXREG register (if
available). Once the TXREG register transfers the data to the TSR register (occurs
in one TCY), the TXREG register becomes empty and flag bit TXIF (bit 4 of PIR1
register) is set. This interrupt can be enabled/disabled by setting/clearing e
E (bit 4 of PIE1 register). Flag bit TXIF will be set, regardless of the state
of enable b
into the TXREG register
er is empty. No interrupt l
po s
that the TSR register is not mapped in data memory, so it is not available to the
user and flag bit TXIF is set when enable bit TXEN (bit 5 of TXSTA register) is
set, TXIF is cleared by loading TXREG.
T ission is enabled by ng ble bit TXEN. The
transmission ill not occur until the TXREG r ter has been loaded w
an b ate generator (BRG) has produced shift clock. The tra
can also be started by first loading the TXREG register and then setting enable bit
T
that point, transfer to the TXREG register will result in an immediate transfer to
TSR, resulting in an empty TXREG. A consecutive transfer is thus possible.
Clearing enable bit TXEN during a transmission will cause the transmission to be
aborted and will reset the transmitter. As a result, the RC6 pin will revert to hi-
impedance.
40
Figure – 4.6 USART Transmit Block Diagram
When setting up an Asynchronous Transmission, the following steps are
executed [Ref. 8]:
1 - Initialize the SPBRG register for the appropriate baud rate. If a high-
speed baud rate is desired, set bit BRGH.
2 - Enable the asynchronous serial port by clearing bit SYNC and setting
bit SPEN.
3 - If interrupts are desired, then set enable bit TXIE.
4 - If 9-bit transmission is desired, then set transmit bit TX9.
5 - Enable the transmission by setting bit TXEN, which will also set bit
TXIF.
6 - If 9-bit transmission is selected, the ninth bit should be loaded in bit
TX9D.
7 - Load data to the TXREG register (starts transmission).
8 - If using interrupts, ensure that GIE bit and PEIE bit (bits 7 and 6 of the
INTCON register) are set.
41
vided by PicBasic Pro, sending data over USART module becomes
fairly practical. At the beginning of the code, the initiation of transmit over
USART module must be also defined as below:
Define HSER_TXSTA 20h 'USART transmit status init
4.2.2.2 USART Asynchronous Receiver
The receiver block diagram is shown in Figure – 4.7. Once Asynchronous
mode is selected, reception is enabled by setting bit CREN (bit 4 of RCSTA
register). The data is received on the RC7 pin and is passed to the data recovery
block. The data r operating at x16
times the baud rate. Whereas, the main receive serial shifter (RSR) operates at the
baud rate or at FOSC.
r (if it is empty). If the transfer is complete, flag bit RCIF (bit 5
of PIR
g bit RCIF is a read
only bi
ad and is empty. The RCREG is a double-buffered register (that is, it is
a two to be received and
transfe to the RSR
register
ull, the overrun error bit OERR (bit 1 of RCSTA register) will be set. The
word in
bytes in the FIFO. Overrun bit OERR has to be cleared in software. This
is done et). If bit OERR
is set, t
d. It is therefore, essential to clear error bit OERR if it
is set. Framing error bit FERR (bit 2 of RCSTA register) is set if a STOP bit is
detected as clear. Bit FERR and the 9th receive bit (RX9D, bit 0 of RCSTA
It seems that these steps are troublesome a bit. But owing to the “Hserout”
command pro
ecovery block is actually a high-speed shifter,
After sampling the STOP bit, the received data in the RSR is transferred to
the RCREG registe
1 register) is set. The actual interrupt can be enabled/disabled by
setting/clearing enable bit RCIE (bit 5 of PIE1 register). Fla
t, which is cleared by the hardware. It is cleared when the RCREG register
has been re
deep FIFO). It is possible for two bytes of data
rred to the RCREG FIFO and a third byte to begin shifting
. On the detection of the STOP bit of the third byte, if the RCREG register
is still f
the RSR will be lost. The RCREG register can be read twice to retrieve
the two
by resetting the receive logic (CREN is cleared and then s
ransfers from the RSR register to the RCREG register are inhibited, and no
further data will be receive
42
register) are buffered the same way as the receive data. Reading the RCREG will
load bits RX9D and FERR with new values, therefore, it is essential for the user
to read the RCSTA register before reading the RCREG register in order not to
lose the old FERR and RX9D information.
Figure – 4.7 USART Receive Block Diagram
When setting up an Asynchronous Reception, the following steps are
executed [Ref. 8]:
1 - Initialize the SPBRG register for the appropriate baud rate. If a high-
speed baud rate is desired, set bit BRGH.
2 - Enable the asynchronous serial port by clearing bit SYNC and setting
bit SPEN.
3 - If interrupts are desired, then set enable bit RCIE.
4 - If 9-bit reception is desired, then set bit RX9.
5 - Enable the reception by setting bit CREN.
6 - Flag bit RCIF will be set when reception is complete and an interrupt
will be generated if enable bit RCIE is set.
7 - Read the RCSTA register to get the ninth bit (if enabled) and determine
if any error occurred during reception.
43
Similar to the USART transmit process, the USART receive process can
be fulfilled very practically by using “Hserin” command provided by PicBasic
Pro. At the beginning of the code, the initiation of transmit over USART module
must be also defined as below:
Define HSER_TXSTA 90h 'USART receive status init
4.3 Inverted Logic
As mentioned previously normal I/O pins can be utilized as serial
communication interface thanks to plementation and the
excellent I/O specifications of the PI
I/O pins as serial interface is a necessity for this thesis, because the
ulti-port device needs at least 5 serial communication interfaces, but the PIC
6F877
ed for serial interface to digital
electricity m
ponent for level conversion other than
resistors between RB pins of the m
munication still has voltage level conflict. Under these circumstances
the PIC 16F877 m
I/O pin can be inverted for serial
requirem rent. The pins of the
microcontro
as Tx are connected to Rx
of othe
8 - Read the 8-bit received data by reading the RCREG register.
9 - If any error occurred, clear the error by clearing enable bit CREN.
10 - If using interrupts, ensure that GIE and PEIE (bits 7 and 6) of the
INTCON register are set.
current RS-232 im
C 16F877. As a matter of fact, utilizing
ordinary
m
1 has only one USART module.
8 RB pins of PIC 16F877 are allocat
eters and remote PC. As it can be seen from the circuit diagram in
Figure – 5.9, there are not any extra com
icrocontroller and the ports for the peripherals,
so the com
icrocontroller provides an effective solution. Voltage level of an
communication purpose by the code. Only
ent is using resistors in order to limit the cur
ller used as Rx are connected to Tx pins of other peripherals over 22
KΩ resistors, similarly the pins of microcontroller used
r peripherals over 1 KΩ resistors as shown in Figure – 4.8 [Ref. 9].
Figure – 4.8 Inverted logic connections
ic according to application and hardware.
, which
efines the specifications of receiving such as baud rate, parity enabling, inverted
There are several commands used in PicBasic Pro in order to transmit or
receive character serially. Serin2 and Serout2 are two of them, which can be
utilized as inverted logic or normal log
Only the number of data-bits and odd parity enabling (if parity is enabled, even
parity is default) of Serout2 and Serin2 commands must be declared at the
beginning of the program as below:
Define SER2_BITS 8 'Set number of data bits
Define SER2_ODD 1 'Use odd parity instead of even parity
The usage of Serin2 command in the code is as following [Ref. 5 and 6]:
Serin2 PortB.2,16572,65000,receivernotready,[char]
The above code performs the required procedure in order to receive the
char character over PortB.2. The parameter 16572 is the mode of receiving
d
44
45
logic or normal logic. The complete table of Serin2 and Serout2 modes is
presented in Appendix E. The number of 65000 is the timeout value (65000
milisec = 65 sec) to receive a character. Please refer to PicBasic code to see the
different usages of Serout2 and Serin2 commands. For the detailed information
about the PicBasic Pro, please look at http://picbasic.com [Ref. 9].
4.4 Comments on Serial Comm nication with Microcontrollers
According to given explanation, the remarks listed below should be taken
into consideration for properly performing serial communication with
microcontrollers:
- Firstly a stable oscillator should be equipped in the circuit. If 4
MHz Crystal or Resonator oscillator is equipped, that would be enough for prope
data communication type oscillator is
sed, it would be unlikely to get stable communication above 1200 baud rate [Ref
0].
Throughout designing level, operating the system starting with
lower b
ards a PC is realized, it should be better to
terminate the > a se Carriage
Return and Li r ate the data buffer string at the PC and
start a new string with the next data packet.
u
r
at 4800 baud rate. But if internal or RC
u
1
-
aud rates would be a good designing method. After success, the baud rate
should be increased step by step.
- The signal level conversion between TTL/CMOS logic and RS 232
should be fulfilled properly, otherwise nothing can be transmitted or received
between a microcontroller and a peripheral device.
- If a transmission tow
data packets with a <CR nd <LF> characters. The
ne Feed characters te min
46
,
a developed remote access software running on the main PC, one modem
connec
icity meters. The device connected to the port 1 may be a PC or
a digita lectr
5.1 Remote Access Software
ous Professional) Libraries to perform serial
commu catio
programs easily together with
advanced term
e has two versions, one of them is for
ain PC, and the other one is for remote PC. The version operating on remote PC
an be stated as lite version, because it does not have many functions such as
eter remote reading options. This lite version is specified for the Xmodem file
ansfer. So the program execution procedure will be explained separately for full
ersion and lite version.
CHAPTER 5
DESCRIPTION OF IMPLEMENTED SYSTEM
As mentioned briefly in Chapter 1, the overall system contains a main PC
ted to main PC, the multi-port device, another modem connected to the
multi-port device, one remote PC and three digital electricity meters or no remote
PC and four electr
l e icity meter according to the application. Hereafter the main parts of
the system and their operating principles will be explained one by one.
The remote access software used in the system was developed with Delphi
7.0 by using APRO (Asynchron
ni n [Ref. 11]. With APRO, the implemented programs can send
alphanumeric characters to anywhere in the world, even across the Internet. The
user can add Dial-Up networking capabilities to the
inal control, automated scripting for complex communication tasks,
and even multi-user fax server solutions. The software developed in this thesis
mainly uses the Dial-Up networking features of APRO Libraries.
The developed remote access softwar
m
c
m
tr
v
47
5.1.1 Running of Full Version Remote Access Software
Figure – 5.1 Main screen of Reading Software on main PC
When the program, which is developed by Delphi 7.0 programming
languag
x at left side of
Dial bu
lished and the program starts to send communication
indication string to the multi-port device. After the handshake process between the
e and loaded to main PC, is started, the program window shown in Figure
– 5.1 should appear on the screen.
The execution steps of software are described below:
1)- First of all, the serial port of main PC, which will be used for serial
communication, should be selected. The active serial ports are listed in the left
upper box.
2)- Then the phone number, which will be dialed to establish the
communication with the remote side, should be specified in the bo
tton.
3)- Next, the timeout values for main PC to modem connection and main
PC to multi-port device should be entered to right upper box. After that, Dial
button can be clicked, thus the “ATDT + Phone Number” command is sent to
modem. Then, if the remote modem and telephone lines are available, the
communication is estab
48
will receive the port
status o rt device, such as which device is connected to which port. If
the handshake process between main PC and multi-port device, which can
continue 60 seconds at most, fails anyhow, the connection will be closed
automatically by the program. The related indication messages appear on the left
log window.
4)- After the communication is established successfully, the request may
be to perform a remote reading of a meter or to perform a file transfer to the
remote PC.
5)- If the request is to perform a remote reading of a meter, the desired
meter should be selected from the box and then Read Device button should be
clicked. If the meter is not password protected and also connected to the port
properly, the readout data will be listed in reading window on the left. The readou
data can be written to a text file by clicking right button of mouse over the
window.
6)- This meter readout procedure can be executed for each meter in the
same m
m a file transfer to the remote PC, the request
must b ter that the file to be
sent sh
cedure will wait for 30 seconds for preparation of remote PC to
receive
a file transfer request is initiated from remote PC, the multi-port
device
multi-port device and main PC is completed, the program
f the multi-po
t
anner. The readout window on the left can be cleared anytime by clicking
Clear Text button.
7)- If the request is to perfor
e initiated by clicking to the Initiate FTP button and af
ould be selected by clicking File Open icon at the bottom of the program
window at same line with Send button. After clicking to the Send button, the file
transfer pro
a file. Within 30 seconds, when the remote PC passes to receiving file
mode, the file transfer process will start according to Xmodem protocol.
8)- If
informs the main PC to be in receiving mode within 30 seconds. When the
main PC enters to receiving file mode, the file transfer process will start according
to Xmodem protocol.
9)- The connection between main PC and multi-port device can be closed
anytime by the user of main PC by clicking Close Port button.
49
are
Note: The buttons below the reading window indicates the status of serial
communication performed by using APRO Libraries [Ref. 11]. They will be red
or green according to the status of process while the program is running. Clear
Text button clears the reading window to be prepared for next reading. Clear Text
button can be used anytime.
The source code of the reading software is presented in Appendix A.
5.1.2 Running of Lite Version Remote Access Softw
Figure – 5.2 Main screen of Reading Software on remote PC
When the program is started on remote PC and Slave Computer box at the
right b
e serial port to be used for the communication with multi-
port de
ice sends the port
status detection string to all ports. As soon as the remote PC receives this string, it
ottom of window is checked, the program window shown in Figure – 5.2
should appear on the screen of remote PC.
The execution steps of software are described below:
1)- First of all, th
vice should be specified and opened.
2)- During the start up procedure, the multi-port dev
50
immed
0 seconds. Within 30 seconds, when the remote PC
asses to receiving file mode, the file transfer starts immediately.
ialize
TP button at the right bottom of the program window. If the remote PC receives
e started. When Send
utton is clicked, the file transfer procedure will wait for 30 seconds for
preparation of main PC to receive a file. Within 30 seconds, when the main PC
passes to receiving file mode, the file transfer process starts according to Xmodem
protocol.
5)- After the file transfer from remote PC to main PC is completed, the
program execution turns back step 2. Throughout running of lite version remote
access software, the specified serial port must be opened and the Slave Computer
button must be checked.
Note: The buttons below the reading window indicates the status of serial
communication performed by using APRO Libraries. They will be red or green
according to the status of process while the program is running. The Clear Text
utton clears the reading window to be prepared the window for next reading.
Clear Tex
iately replies with a specified string that indicates remote PC is connected
and ready.
3)- Then the remote PC starts to wait for a file transfer procedure
initialization message. When this message is received, the program should be in
receiving file mode within 3
p
4)- The remote PC can initiate a file transfer anytime by clicking Init
F
“Ready for file transfer” message, the file transfer can b
b
b
t button can be used anytime.
5.1.3 Flow Diagram of Reading Software
51
Figure 5.3 Reading software flow diagram (I)
52
re flow diagram (II) Figure 5.3 Reading softwa
53
It should be useful to describe the program code by following the flow
diagram in order to give the theory.
When the program is started, first of all the Slave PC check box must be
checked or not according to operating user station. If the program is running on
remote PC, the box must be checked, and after that some options peculiar to main
PC and meter readout process will be off by calling the TForm1.ChkboxClick()
procedure.
If we assume that the operating user station is main PC, the next step will
be establishing communication with remote side. In order to that, first of all the
serial port to be used should be specified. When the upper left ComboBox is
clicked, the available and properly working serial ports are listed. The Comfind()
procedure in the program performs this port detection process. Then the timeout
values for the establishment of communication between main PC and remote
modem and main PC and the implemented multi-port device should be defined.
The usage of timeout values in these EditBoxes by the program will be explained.
Finally, the phone number, which will be dialed, should be defined before
clicking Dial button.
When the Dial button is clicked, the program calls the TForm1.DialClick()
procedure. In this procedure, the program branches to SingOn() procedure and
then the selected serial port is assigned to the TApdComPort component of APRO
(Asynchronous Professional) serial communication library. After that, the number
is dialed by sending the ‘ATDT’ + Edit2.Text to the modem. At the same time,
the timers controlling the periods for communication establishment are set by
using previously mentioned timeout values defined in EditBoxes. If the remote
modem or multi-port device does not respond with specified strings before the
timers are expired, the program calls ComEnd() procedure and closes the serial
port assigned to TApdComPort. If communication is established properly
between main PC and multi-port device, the program will receive the port status
information, which is sent by multi-port device. The reception of characters by
sing TApdCom p2TriggerAvail()
procedure. Please look at APRO manual for more detailed information [Ref. 11].
u Port component is performed by TForm1.c
54
After acq ram is ready to
perform meter readout or file transfer. For remote reading of a meter, after the
e required string is sent to the multi-port
ox. The readout data on the reading window can be saved to a text
g <ACK> character by sender. After the file transfer is
mple
uiring the knowledge of port status, the prog
device is selected from the ComboBox, the Read Device button should be clicked.
By clicking Read Device button, th
device by TForm1.RdeviceClick() procedure. If there is a problem about the
specified meter, the multi-port device informs the user of main PC by sending a
message. If everything is OK, the readout data sent by the meters is received by
TForm1.cp2TriggerAvail() procedure and screened on the reading window, which
is a MemoB
file, if it is required.
When a file transfer is wanted to be performed, first of all the Initiate FTP
button must be clicked in order to inform the multi-port device. After that, an
acknowledgement message should be waited to start file transfer. If the message is
received and the file, which will be sent, is selected, the Send button can be
clicked. By clicking Send button, the XmodemCRC file transfer protocol is
initiated by TForm1.FsendClick () procedure. As soon as the handshake character,
which is sent by the receiver (i.e. remote PC), is received, the XmodemCRC file
transfer process starts and continues until sending <EOT> character and
subsequently receivin
co ted, the TForm1.Prt1ProtocolFinish() procedure is called.
If a message indicating the initiation of file transfer by remote PC is
received, the file name should be specified by clicking the folder icon. After that
by clicking Receive button, the file transfer process, which is initiated by remote
PC, starts. During file reception process according to XmodemCRC protocol,
TForm1.FreceiveClick() procedure is executed. After the file transfer is
completed, the TForm1.Prt1ProtocolFinish() procedure is called.
The file transfer process performed by the remote PC follows the same
steps and executes the same procedures as it can be seen clearly from the flow
diagram. As the remote PC is not allowed to perform meter readout, all the related
options are disabled under the condition of checked Slave Computer box.
55
s refers to connecting a device to a network via a modem
5.2 Modem
Modem term is the acronym for modulator-demodulator. A modem is a
device or a program that enables a computer to transmit digital data in the form of
analog waves over telephone lines.
There is a standard interface for connecting external modems to computers
which is called as RS-232. By using this interface, any external modem can be
attached to any computer that has an RS-232 port, which almost all personal
computers have. RS-232 standard is explained comprehensively in Chapter 2.
There are also onboard or internal modems as an expansion board that you can
insert into a vacant expansion slot.
Dial-up Acces
and a public telephone network. Dial-up access is really just like a phone
connection, except that two ends are the computers (or the devices having at least
an RS-232 port) rather than people. Because dial-up access uses normal telephone
lines, the quality of the connection is not always good and data rates are limited.
In the past, the maximum data rate with dial-up access was 56 Kbps (56,000 bits
per second), but new technologies such as ISDN provide faster rates [Ref. 4].
An alternative way to connect two devices is through a leased line, which
provides a permanent connection between two devices. Leased lines provide faster
throughput and better quality connections, but they are also more expensive.
5.2.1 Communication Protocol
All communications between devices require that the devices agree on the
format of the data. The set of rules defining a format is called as protocol. At
least, a communication protocol must define the followings:
• Rate of transmission (in baud or bps).
• Whether transmission is to be synchronous or asynchronous.
• Whether data is to be transmitted in half-duplex or full-duplex mode.
56
In addition, protocols can include sophisticated techniques for detecting
and recovering from transmission errors and for encoding and decoding data.
Table – 5.1 summarize only used protocols for
communication via modems [Ref. 13]. These protocols are almost always
plemented in the hardware; that is, they ar ilt into modems.
ost commonly used protocols
s the most comm
im e bu
Table – 5.1 Summary of the m
Protocol
Maximum Transmission
Rate
Duplex Mode
Bell 103 300 bps Full CCITT V.21 300 bps Full Bell 212A 1,200 bps Full ITU V.22 1,200 bps Half ITU V.22bis 2,400 bps Full ITU V.29 9,600 bps Half ITU V.32 9,600 bps Full ITU V.32bis 14,400 bps Full ITU V.34 36,600 bps Full ITU V.90 56,000 bps Full
In addition to the standard protocols listed in the table, there are numerous
rotocols that complement these standards by adding extra functions such as error
ompression, etc. Some of these protocols are
Xmodem, Kermit, MNP, and CCITT V.42 [Ref. 17]. These protocols can be
plem
packets. Once these
are rec e les them into a form computer
can use
p
detection, error recovery, data c
im ented either in hardware or software.
Typical modems are known as asynchronous devices. This means that
these devices transmit data in an intermittent stream of small
eiv d, the receiving system then reassemb
.
57
Sto
p 1 bit
Data 8 bits
Start 1 bit
Stop 1 bit
Data 8 bits
Start 1 bit
Packet Packet 10 bits 10 bits
Figure – 5.4 Asynchronous transmission packets
Figure – 5.4 represents the packet format in an asynchronous transmission
over a ph bits) is
ansferred within 1 packet, which is equivalent to one character. However for the
computer to receive this information each packet must contain a Start and a Stop
bit therefore the complete packet b basics of serial
communication is des compreh ly in C .
5 plem lti-port ce 5.3.1 General De
The imple port signed b n the PIC 16F877,
which is a micro produce chip Co and explained in
Chapter 3. The m vice ca ed in th in parts as voltage
regulator module, LCD module, and mic ocontroller module. These modules will
e described in this section.
voltage adaptors between 12-24 V
range c
one line. In an asynchronous communication, 1 byte (8
tr
would be 10
ensive
its. The
hapter 2cribed more
.3 The Im ented Mu Devi
scription
mented multi- device is de ased o
controller d by Micro mpany
ulti-port de n be examin ree ma
r
b
5.3.2 Voltage Regulator
The multi-port device includes an internal voltage regulation circuit.
Owing to this voltage regulation circuit, any
an be used as a power supply for the multi-port device. Voltage regulation
circuit diagram is shown in Figure – 5.5 [Ref. 15].
Figure – 5.5 Voltage regulation circuit
Although a voltage adaptor acquired from the market has its own
regulation circuit, this extra regulation circuit is used because the microcontrollers
require very pure and stabilized voltage level in order to operate properly. The
required stabilized +5V is achieved by using the power stabilizer LM-7805. If the
utput voltage goes down, the LM-7805 regulator will draw more current, forcing
e output voltage back to 5V. Thus, the LM-7805 regulator controls the output
voltage and keep
Because the microcontrollers require very clear voltage, a capacitor
the MCU is also used in order to filter the distortion
om the circuit itself.
D’s are inexpensive and easy to use. Hitachi LCDs
ave a standard ASCII set of characters along with Japanese, Greek and
The LCD module can be wired for a 4-bit or an 8-bit mode. In PicBasic
Pro, th
es D4-D7 default, but it can be
changed to D0-D3 by code, if required [Ref. 9 and 15]. Four-bit mode is a good
o
th
s it at 5V.
between Vdd and Vss pins of
fr
5.3.3 LCD Module
The LCD used in the multi-port device has 16-pin Hitachi LCD with
HD44780 module. These LC
h
mathematical symbols.
e LCD mode (4-bit or 8-bit) must be defined at the beginning of the
program via “DEFINE LCD_BITS” instruction, please refer to microcontroller code
in Appendix B. In 4-bit mode shown in Figure – 5.6, a byte is sent by
microcontroller as two successive 4-bit over the lin
58
59
way to save control lines. The entire LCD module can normally be controlled
from 6 control lines. The initialization commands are constructed in such a way
that you can instruct the LCD module which interface is to be used just after reset.
Figure – 5.6 General LCD connection diagram
only requires the supply lines plus 7 I/O lines. When the
CD display is not enabled, data lines are tri-state which means that they are in a
ence (as though they are disconnected) and this also means
at they do not interfere with the operation of the microcontroller when the
display
For an 8-bit data bus, the display requires a +5V supply plus 11 I/O lines.
For a 4-bit data bus it
L
state of high impend
th
is not being addressed.
The LCD requires mainly 3 control lines from the microcontroller:
Read/Write (R/W): This line determines the direction of data between the LCD
d mian crocontroller. When it is low, data is written to the LCD. When it is high,
data is read from the LCD.
Register Select (RS): With the help of this line, the LCD interprets the type of
data on data lines. When it is low, an instruction is being written to the LCD, and
when it is high, a character is being written to the LCD.
60
Enable (E): This line allows access to the display through R/W and RS lines.
When this line is low, the LCD is disabled and ignores signals from R/W and RS.
When (E) line is high, the LCD checks the state of the two control lines and
responds accordingly.
Logic status on control lines:
E 0 Access to LCD disabled
1 Access to LCD enabled
R/W 0 Writing data to LCD
1 Reading data from LCD
RS 0 Instruction
1 Character
Writing data to the LCD is done in several steps:
- Set R/W bit to low
- Set RS bit to logic 0
- Set data to data lines
ontrol ports must be declared at the
PORTE 'LCD register select port
Define LCD_RSBIT 0 'LCD register select bit
or 1 (instruction or character)
- Set E line to high
- Set E line to low
The “LCDOUT” command, which performs the above explained steps, is
used for writing data to the LCD in PicBasic Pro.
The definition of LCD data ports and c
beginning of the program by “Define” command in PicBasic Pro code as shown
below:
Define LCD_DREG PORTD 'LCD data port
Define LCD_DBIT 0 'LCD data starting bit 0
Define LCD_RSREG
Define LCD_EREG PORTE 'LCD enable port
Define LCD_EBIT 1 'LCD enable bit
61
PIC 16F877, which is produced by Microchip Company.
hoose PIC 16F877 for this study. First of all
e PIC 16F877 is a low-cost and high performance device with RISC CPU
chite ure. O o m memory it provides designing
practical interfacing options with
this study. Also owing to large
mber of I/O pins and their inverted logic feature, which is explained in Chapter
n cessity of 8 more (4 of them are in use) serial communication interfaces
ld satisfied very practically. It is very obvious that the PIC 16F877
microc ause of its powerful and
actic interf
ntroller in the
plem scribed in this section. The PIC 16F877 is
scrib com ter 3.
3.4.1 eset Process
er nto a known condition. That
practic
at is all registers would be placed in a starting position. Reset is not only
used w esir e used to get
a microcontroller ready when loading a program.
MCL s,
which the
microc ese e-low pin,
has to der gical zero to
5.3.4 Microcontroller Module
As mentioned previously the microcontroller used in the implemented
multi-port device is the
There are several reasons to c
th
ar ct wing t electrically erasable progra
ease. Also it has very powerful I/O features and
peripherals. Especially the USART module is a very feasible peripheral option for
serial communication, which is the main issue of
nu
4, the e
cou be
ontroller is really a good choice for this study bec
pr al acing features.
The auxiliary processes and components used with microco
im ented multi-port device are de
de ed prehensively in Chap
5. R
Reset is used for putting the microcontroll i
ally means that microcontroller can behave inaccurately under certain
undesirable conditions. In order to continue its proper functioning it has to be
reset, th
hen microcontroller does not behave as d ed, but also can b
The PIC 16F877 microcontroller has R pin for resetting proces
is logic one during normal operation of microcontroller. When
ontroller is required to be r t, the MCLR pin, which is an activ
be made logic zero. In or to prevent from bringing a lo
62
CLR pin accidentally it has to be connected via resistor to the positive supply
en 5K and 10K. This kind of resistor, whose
nction is to keep a certain line on a logical one as a preventive, is called as pull
ng together with two 33 pF capacitors. The crystal
re the most common source of time and
ls. The crystal is sometimes called as timing crystal. They can be
circuits.
5.3.4.3
l conversion process between
microc
M
pole. Resistor should be betwe
fu
up. If MCLR pin will not be used, it has to be connected to positive supply pole
(i.e. to +5V) [Ref. 8].
During a reset, RAM memory locations are not being reset. They are
unknown during a power up and are not changed at any reset. On the other hand,
special function registers are reset to a starting position initial state. One of the
most important effects of a reset is setting the program counter (PC) to zero
(0000h), which enables the program to start executing from the first written
instruction.
5.3.4.2 Oscillator
The microcontroller included by implemented multi-port device has the 4
MHz crystal oscillator operati
oscillator is a good choice for a reliable triggering required by the
microcontrollers. The crystal is usually made of quartz, but can also be made of
rubidium or ceramic. Crystal oscillators a
frequency signa
embedded in integrated
Serial Communication with USART
The communication between the implemented multi-port device and
modem is fulfilled over MAX 232 level converter device by using the RC6 and
RC7 pins of the microcontroller. RC6 and RC7 pins are the Rx and Tx pins of
USART module respectively. The voltage leve
ontroller and modem is realized by MAX 232. PicBasic Pro supports the
USART module with very powerful and practical commands, such as HSERIN
and HSEROUT (mean that “Hardware Serial Input” and “Hardware Serial Output,
respectively, please refer to PicBasic Pro code presented in Appendix B). The
63
ocontroller has only one USART module, these asynchronous serial
ommunications must be fulfilled by some other ordinary I/O pins. Naturally there
ces between these connections and the USART module
onnection. Inverted logic serial communication can be used very practically via
PicBas
ulti-port device is powered on, it will take less
an one second to be ready for the operation. Then the device starts to wait for a
ason the device listens
e Rx pin of USART module (RC7 pin of the PIC 16F877). The communication
betwee
detailed description of serial communication with USART module is presented in
Chapter 4.
5.3.4.4 Serial Communication with Inverted Logic
In this thesis, the microcontroller has 5 serial interfaces (may increase to
9) with peripheral devices. As mentioned previously one of them is used for
asynchronous serial communication with an external modem, which provides the
connection to the main PC via USART module. Other 4 ports are specified for the
connections to the digital electricity meters and the remote PC. As the PIC
16F877 micr
c
are some differen
c
ic Pro, please refer to PicBasic code in Appendix B and check the
“Serout2” and “Serin2” commands in the code. The detailed description of serial
communication with inverted logic is presented in Chapter 4.
5.3.5 Operational Principles of Multi-port Device
When the implemented m
th
communication initialization from the main PC. For that re
th
n main PC and multi-port device is performed with 4800-baud rate and
8N1 (1 start bit, 8 data bits, none parity and 1 stop bit). As soon as the multi-port
device receives the communication initialization string from main PC, it triggers a
port detection process by sending a specified string to all ports (8 RB pins of the
PIC 16F877 utilized as serial port). If a meter is connected to a port, the meter will
respond with its serial number. If a PC is connected to the port 1, it will respond
by a specified string. If there is not a PC or a meter connected to a port, time-out
will occur. After this process the multi-port device could detect the connected
64
Then the multi-port device starts to wait for the instruction from the main
ll be evaluated immediately
nd the code loaded to the microcontroller will branch to the related part of the
program
ack to the point of
waiting instruction.
quest sent by main PC, the
essages giving the instruction to start the file transfer process are sent to main
PC and
peripherals and informs the user of main PC as which device is connected to
which port.
PC and remote PC. If an instruction is received, it wi
a
according to the received instruction.
If the received instruction is the indication string of closing port process
sent by main PC, the execution turns back to starting point and waits for the
communication initialization again.
If the received instruction is the meter readout request, the serial
communication with 4800-baud rate and 7E1 (1 start bit, 7 data bits, even parity
and 1 stop bit) will be established between the multi-port device and the meter on
the specified port. Then readout request string is sent to the meter. As soon as the
meter receives readout request, it starts to transmit all standard readout data, if the
meter is not password protected. All received characters by the multi-port device
will be transmitted to the main PC over Tx pin of USART module (RC6 of PIC
16F877). After the readout is completed, the execution turns b
If the received instruction is the file transfer re
m
remote PC. As mentioned previously the file transfer process is fulfilled
according to Xmodem protocol with 4800-baud rate and 8N1 (which is a
requirement for Xmodem protocol [Ref. 17]). In file transfer mode, firstly, remote
PC sends handshake character, which is <C> for CRC error checks, to the main
PC, and waits 10 seconds for the transmitter to send a block of data. The main PC
starts to send the blocks as soon as it receives handshake character. The remote
PC responds with <ACK> character to each successfully received block. The file
transfer will end after receiving <EOT> character by the remote PC. The details of
Xmodem protocol is given in Appendix D.
If the received instruction is the file transfer request sent by remote PC, the
above explained steps will be repeated as the remote PC is sender and the main
65
PC and remote PC.
ocontroller, which is written in
PicBas
PC is receiver. After file transfer is completed, the multi-port device starts to
listen to main
During the whole operation, all required messages giving the information
about the current situation of the process for local recognition appears on the
LCD.
The source code loaded to the micr
ic Pro language is presented in Appendix B. Figure – 5.7 shows the flow
diagram of the source code.
5.3.6 Flow Diagram of Microcontroller Code
66
Figure – 5.7 Microcontroller code flow diagram (I)
67
Figure – 5.7 Microcontroller code flow diagram (II)
It should be useful to describe the PicBasic code with the help of sample
code fragments by following the flow diagram in order to give the theory of code.
After the implemented multi-port device is powered on, it will start to wait
a communication initiation from main PC by means of the PicBasic code:
Hserin[wait("m"),b] .
Hserin command is used for receiving character by utilizing USART
ned at the beginning module. The parameters of this serial communication are defi
68
of the program such as 4800 baud rate, 8 data bits, no parity bit and 1 stop bit by
means of the code such as:
Define HSER_………………
If the expected string for communication initiation is received, the port
status detection process is triggered by multi-port device. During this operation,
the device sends a specific string to each port by means of the code line:
Serout2 PortB.1,24764,[13,10,21,47,63,33,13,10]
then waits for the response by means of the code line:
Serin2 PortB.0,24764,2000,meterdetect1,[str a1\16]
These Serin2 and Serout2 commands can use the inverted logic property
of PIC 16F877 I/O pins, which is defined by the mode 24764 in the code [Ref. 6
and 9]. This mode number also defines the parameters of this serial
communication, such as 4800 baud rate, 7 data bits, Even parity and 1 stop bit.
Please look at Appendix E for Serin2 and Serout2 mode definitions.
The devices connected to each port of implemented multi-port device are
determined according to the received responses.
Then the multi-port device starts to wait for operation request, which can
be sent by main PC or remote PC. The device performs this process by listening
Rx pins of USART module and Port1 in a loop. The program branches from this
point to the related part of the code according to what the request is and which PC
ends it.
If the r the specified
eter is connected to, is utilized and the data transfer between the multi-port
the r e transfer between main PC and remote PC,
ram branches to the code part related with Xmodem protocol. The file
s
equest is remote reading of a meter, the port, which
m
device and meter is performed over this port according to Flag protocol. The
received characters are sent to the main PC over the USART module. After the
process is completed, the multi-port device turns back to wait for operation
request.
If equest is to perform a fil
the prog
69
<ACK> or <NACK> from receiver, transmitting to
ure:
Hserout [13,10,"Ready for file transfer",13,10]
]
Hserout [nak]
Hserin 500,ftpcompleted,[char2]
k]
urns back to the point of waiting for communication initiation.
spectively. The PCB diagram was created by ARES tool in Proteus
transfer process can be performed from main PC to remote PC or from remote PC
to main PC. There is only one difference, that is the direction of transfer, but the
idea is same; receiving the Xmodem data blocks from sender, transmitting to
receiver, and receiving the
sender. The below code performs this proced
pause 1000
Serout2 PortB.1,16572,[13,10,"Be ready for receiving file",13,10]
pause 1000
Serin2 PortB.0,16572,30000,receivernotready,[nak
loop1:
Hserin 5000,nofiletransfer,[char1]
Hserin 1000,problem,[char3]
Hserin 1000,problem,[str char\65]
Hserin 1000,problem,[str a\65]
Serout2 PortB.1,16572,[char1,char2,char3,str char\65,str a\65]
Serin2 PortB.0,16572,11000,noreplyfromreceiver,[na
Hserout [nak]
goto loop1
After the file transfer is completed or failed anyhow, the program turns
back to wait for operation request. The file transfer, which is failed, can be
initiated again at this point. If the communication is terminated by main PC, the
program t
5.3.7 Circuit Diagram
The PCB (Printed Circuit Board) and the circuit diagram, which are
designed and built in the scope of this thesis, are shown in Figure – 5.8 and Figure
– 5.9 re
70
trollers and a set of animated
ypads, an RS232
a and m re. It is possible to simulate complete microcontroller systems and
s to evelo
q ently roteus 6.0 allows professional engineers to set up a
s and finally
t the P t.
Professional 6.0 after circuit diagram was drawn by ISIS tool again in Proteus
Professional 6.0 [Ref. 18].
Proteus Professional 6.0 is a software package, which combines a mixed
mode circuit simulator with animated component models. And it provides an
architecture in which additional animated models may be created by users. Indeed,
many types of animated model can be produced without coding. Proteus also
provides simulator models for popular microcon
models for related peripheral devices such as LED, LCD, ke
termin l o
thu d p the software for them without access to a physical prototype.
Conse u P Professional
circuit of real designs, run the circuit as interactive simulation
construc CB of the circui
Figure – 5.8 Multi-port device PCB diagram
Figu
re –
5.9
Mul
ti-po
rt de
vice
circ
uit d
iagr
am
72
5.4 The Digital Electricity Meter 5.4.1 General Description
The electricity meters that operate according to electromechanical
plete, high performance tariff system. The interfaces of the past have been
extended by an optical fibre interface in this meter generation. The information
important for the d from the main
eter with this interface and fed into an isolating relay box. The relay model can
e chosen by the customer.
This concept allows that the relays, which were previously in the meter,
an be removed to external boxes. This guarantees the maximum possible
sulation from outward interference and also reduces the need for additional
olating relays in the meter cabinet. Before electronics arrived in the meters of
e electricity providers, a classical measuring set for special contract customers
sually looked like as following: For the measurement set there was a maximum
principles could not satisfy some requirements such as accuracy, reliability,
lifetime and compatibility with electronic solutions. After electronics has made a
remarkable development, electricity meters have been mass-produced using the
most modern microelectronics in order to satisfy the requirements of present age.
Upon closer view, EMH meters, which are used with implemented multi-
port device in this thesis, will be examined briefly. EMH is a digital electricity
meter producer in Germany. EMH developed digital electricity meters, which are
self-contained functioning tariff systems. These have little resemblance to the old
meter technology.
The term ‘digital meter’ requires a brief explanation. The digital principle
means that voltages and currents in individual phases are measured
simultaneously. They are measured at a high sample and hold rate, and trans-
formed into digital words. This information is then fed into a signal processor,
which calculates all the desired values.
The control elements used, such as the real time clock with calendar and a
universal ripple control receiver, which were previously external, are already
integrated into the meter. The result is that a simple meter is transformed into a
com
final customer of this system can be separate
m
b
c
in
is
th
u
73
and a power distribu according to tariffs,
n external ripple control receiver or tariff time switch was added. And also the
e meter were separated by additional relays in the
with this newest technology w
urers such as EMH, ACTARIS
(Schlum
ean power, last recorded mean power, maximum
demand and energy. Maxim
tion meter. In order to control the device
a
transmission contacts for th
measuring set cabinet.
With the introduction of the combi-meter with integrated ripple control
receiver, integrated real time clock and optical fibre interface, the costs can be
reduced remarkably.
There is no doubt that introduction and equipping of a measurement point
ill lead to an increase in reliability and a reduction
of error sources in the system.
5.4.2 EDIS (Energy Data Identification System)
The EDIS code system was created on the basis of the future-oriented
efforts by the German Electrical Engineering Commission of the DIN and VDE
(DKE) [Ref. 14]. The purpose of the EDIS is to provide unambiguous
identification of data for display and processing originating from devices, which
are produced by different manufact
berger), SIEMENS, ABB etc.
Some examples shown in Figure – 5.10 illustrate the structure of EDIS
code system. As seen from the examples, the first digit, which can be any number
between 1 and 8, defines the measurement, as 1 for active imported, 2 for active
exported, 3 for reactive imported, 4 for reactive exported, 5 for reactive-inductive
imported, 6 for reactive-capacitive imported, 7 for reactive-inductive exported and
8 for reactive-capacitive exported. The second digit defines which quantity is
measured. It may indicate m
um demand is one of the most important values for
plants and factories. If the consumer has a demand agreement with the energy
provider, the consumer will be limited for importing power with this undertaken
maximum demand value. If the limit is exceeded, the consumer will have to pay
fine. So maximum demand value should be measured and controlled very
carefully. The third digit is related with the tariff indication. The last two digits
show the historical values of measurement.
Figure – 5.10 General EDIS code system
induction-type meters, an active use meter (which is coded as 1.x.x in EDIS code
5.4.3 Combi Meter / 4-Quadrant Meter
EMH combi meter and 4-quadrant meters are identical in appearance and
belong to the same family of devices. The combi meter has become widely used.
The 4-quadrant meter is more complex than combi-meter and is state of the art in
hardware and software [Ref.14].
5.4.3.1 Combi Meter
The EMH combi meter replaces measurement sets, which consisted of two
74
75
active use measurement separately in
). The
ombi meter is capable of depicting the measurements according to the EDIS code
system which is illustrated in Figure – 5.11 [Ref. 14].
system) and a reactive use meter (which is coded as 3.x.x in EDIS code system).
In addition, the combi meter can perform re
quadrants 1 and 4 (which are coded as 5.x.x and 8.x.x in EDIS code system
c
ing for Combi-meter
5.4.3.2
mption meter for imported and exported energy.
he 4-quadrant meter is able to display the measurements, the codes of which are
from the EDIS code system.
Figure – 5.11 EDIS cod
Four-Quadrant Meter
The EMH 4-quadrant meter replaces the classical 4 induction-type meters
each comprising an active consu
T
shown in Figure – 5.12
Figure – 5.12 EDIS coding for Four-quadrant meter
5.4.4 Modules
The meter consists of two essential elements as digital measuring
mechanism and tariff mechanism.
The measuring mechanism is critical for the accuracy of the meter. It
s, then transforms them into digital information
nd transmits them to the tariff mechanism for calculation and processing. EMH
meters
technology has been used to
obtain this high degree of meter accuracy. Both the measuring and the tariff
mechanisms are charged with a common power unit.
realizes the basic measurement
a
with LZ prefix belong to accuracy class 0.5S while with PZ prefix are
class 0.2S (precision meters). Class 0.5S and 0.2S mean that in normal operation
conditions the maximum probable measurement error will not exceed 0.5 % and
0.2 % respectively. The experience in meter testing
76
77
5.4.4.1 Power Unit
This is a primary switched-mode power unit with a high degree of
effectiveness. Even in case of a module defects it is secure against overload or
short-circuiting. Potential damage remains limited and consequential damage is
avoided.
For EMH meters with LZ prefix with a single-phase connected meter,
error-free operation until Unom - 20% is guaranteed. EMH meters with PZ prefix
(precision meters) have a wide area power unit that is supplied from external
auxiliary power terminals, independent of the measurement path. This prevents
unnecessary load on the measurement path and that the meter's measurement path
remains functional and ready to measure even in the event of power failure.
While the meter is operating, the current measurements are stored in the
working me in a non-volatile
memory. The m
below nomi
event of a pow ectronics will
ontinue to function normally for the next 500 ms. It is powered by the energy in
acitor. If it is only a short outage of less than 500 ms, then the
eter will continue to operate quasi-non-stop. Only in case of longer interruptions
will the
be started when the meter is reactivated. Data
remain
eans that fast, energy-rich
mory (RAM). Every 24 hours, this data is stored
eter also performs this storage operation when there is a 20% drop
nal voltage or a total power interruption (loss of 50 Hz signal). In the
er outage or drop below the minimum voltage, the el
c
the charger-cap
m
measuring period be interrupted and the device completely shut down so
that a new measuring period can
s stored in the non-volatile memory for at least ten years. No buffer battery
is needed to preserve the data. The data received is retained alone through the
qualities of the storage medium (EEPROM).
5.4.4.2 Suppressor Circuits
The suppressor circuit behind the voltage terminals consists of a
combination of surge-proof power resistors and varistors, which dilute the surge
energy in the event of an overvoltage. This m
78
which can be caused by turning off reactive loads, are
revented effectively thanks to the microelectronics.
e entire measuring and tariff mechanism including the options, such as
clock m
gram
code a
urrent values are then digitized. The
digitized current and voltage values are then transmitted individually to a digital
multiplexer.
5.4.5.2
levels. These are fed into the input channels of the ADC.
disturbance pulses,
p
5.4.4.3 Modular Construction
Th
odule, tariff time switch, ripple control receiver and electrical interface,
control inputs and outputs. They are all included on a single circuit board. The
modular structure of the entire meter means that the meter can be assembled to
perform functions in accordance with the customer’s desired meter properties. The
display is plugged onto the circuit board and can be easily replaced.
The meters have a memory (EPROM or FLASH) containing the pro
nd an additional memory (EPROM) for storing the relevant billing data,
parametering, settings and correction factors for the measuring mechanism which
operate independent of any battery.
EMH meters with LZ prefix with optical fibre interface or load profiles
have an additional circuit board. On this circuit board is a FLASH containing the
program code. Depending on the meter version, there may be a further FLASH for
the load profile.
5.4.5 Digital Measuring Mechanism
5.4.5.1 Measurement principle
Measurement is performed by taking voltage and current measurements at
very short intervals. The analog voltage and c
signal processor by means of a
Voltage measurement
The terminal voltages generate network-proportional internal voltage
79
n ferrite cores that generate current-proportional
oltages. These are fed into the two ADC inputs via an instrument amplifier.
idual integral of i2, u2, u * i and u90o * i for
each p
g to the tariff structures configured.
The following measurement values can be seen on the display and read out
using th
line voltages,
• Number of active phases, network frequency and power factor
idual phases.
5.4.5.3 Current measurement
The current paths contai
v
5.4.5.4 Digitization
The analog current and voltage proportional instantaneous values are
digitized in the ADCs and fed into the digital signal processor (DSP) input
through a multiplexer with a high sampling rate.
5.4.5.5 Integral values
The DSP calculates the indiv
hase. These integral values and other information are transmitted to the
tariff mechanism and in particular to the tariff controller CPU. Here the P, Q and
S for each phase are calculated and assigned to the respective energy and power
registers accordin
5.4.5.6 Measurement values
e data interfaces:
• Instantaneous active, reactive, apparent power for each phase
and the combined value,
• Individual line current and
as well as power factor for indiv
80
.4.5.7 Calibration
EMH's combi meter and 4-quadrant meter are fully static and digital
meters.
s are
o matched to each other that a partial calibration between manufacturing steps is
e devices can be produced rationally in identical series.
At the end of the production process, the meters are subjected to a final
calibra
easurement with its own precise
measurement and sends measurement correction factors back to the various points
of measurement constants. These are then stored in the
on-volatile memory elements of the meter. This allows the error curve to be
improv
riff mechanism calculates
lectricity consumed or supplied as well as electrical power. It then assigns it to
r register according to the tariff control and meter
onfiguration provided.
e between meters and read out devices is performed by
means of the h is located on the
meter’s auxilia
(1 stop bit, 7 data bits, even parity
it and 1 stop bit).
5
In practice, this means that there are no mechanical moving parts in the
measuring device. This also means that the electronic components’ tolerance
s
unnecessary. Thus th
tion. The meters are submitted to precise normal load on the test stand.
Each meter measures this load and transmits its measurement to the test stand via
an optical interface. This compares the meter's m
in the meter in the form
n
ed by offset corrections [Ref. 14].
5.4.6 Tariff Mechanism
Using digitized measurement values, the ta
e
the respective energy or powe
c
5.4.7 Data Interface
The data exchang
electrical interface (RS-232, RS-485), whic
ry terminal below the sealable terminal cover. The transmission is
fixed between 300 – 4800 baud rate and 7E1
b
81
CHAPTER 6
and
implem
transfer between two remote computers, was described.
his software was developed in Delphi 7.0 by using APRO (Asynchronous
Profess
plained comprehensively. Also the file transfer process
etween two computers performed over the multi-port device according to
escribed.
The PIC 16F877 microcontroller, which is used in the design, was
describ
work, the multi-port device can be improved by providing
eter readout capability to remote PC with only the help of code modification.
esides, more advanced file transfer protocols with the aspect of speed and error
CONCLUSION
In the scope of this thesis, a general overview of a remote reading
infrastructure for digital electricity meters was given. Then, the design
entation of a multi-port device, which can reduce the cost of this
infrastructure and also simplify it effectively by reducing the number of device
used in the system, were described. And also an alternative application of
implemented multi-port device, which provides interfacing with a PC together
with digital electricity meters, was described.
The operating principles of auxiliary devices used in the system such as
modems and digital electricity meters were explained along with implemented
multi-port device.
A remote access software, which performs remote reading of digital
electricity meters and file
T
ional) Libraries.
As the serial communication was the main issue of the design of this
multi-port device, the fundamental principles of serial communication with
microcontrollers were ex
b
Xmodem protocol is d
ed in detail. Additionally, the LCD usage, which is one of the popular
applications realized with microcontrollers, is also mentioned. The source code of
microcontroller written in PicBasic Pro including the procedures of serial
communication and LCD application is also presented.
As a future
m
B
82
cate with more than one device
ossessing a serial communication port at the same time. Owing to this feature,
the multi-port device can be u lications by making required
odifications in the code.
tolerance, such as Zmodem can be implemented with multi-port device. In fact the
multi-port device can be used in order to communi
p
tilized in lots of app
m
REFERENCES [1] Peatman, J.B. 2003, Embedded Design with the PIC 18F452
Microcontroller, Prentice Hall.
83
Hintz, K. , Tabak, D. 1992, Microcontrollers : Architecture, Implementation & Programming, McGraw Hill.
] Kheir, Michael 1997, The M68HC11 Microcontroller: Applications in control, instrumentation and communication, Prentice Hall.
] Anderson, D., Dawson, P., Tribble, M., The Modem Technical Guide
] Doğan , İbrahim, PIC BASIC : Programlama ve Projeler, İstanbul Bileşim Yayınları
] Altınbaşak, Orhan 2002, PicBasic Pro ile PIC Programlama, Altaş Basım Yayın.
] Altınbaşak, Orhan 2003, Microdenetleyiciler ve PIC Programlama, Altaş Basım Yayın.
] http://www.microchip.com/
]
0] http://www.picbasic.co.uk/forum/
1] http://www.turbopower.com
2] http://www16.boulder.ibm.com/pseries/en_US/aixasync/asycomgd/ mastertoc.htm#mtoc
3] http://readthetruth.com/modems.htm
4] http://www.emh-meter.de
5] http://www.microelektronika.co.yu
6] http://www.mecanique.co.uk/code-studio/
7] http://www.totse.com/en/technology/telecommunications/wxmodem.html
8] http://labcenter.co.uk
[2]
[3
[4 [5 [6
[7 [8 [9 http://picbasic.com [1 [1 [1
[1 [1 [1 [1 [1 [1
84
9] http://www.calldirect.at [20] http://www.adaptivenet
1] http://www.enermet.com
[1
works.com [2 [22] http://www.perax.fr
85
PPENDI
nit mdmshare;
terface
ses WinTypes, WinProcs, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AdPort, OoMisc, AdStatLt, Buttons, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxImageComboBox, Mask, sCustomComboEdit, sTooledit, AdProtcl, AdPStat, sButtonControl, sCustomButton,Registry, ComCtrls, Menus;
pe TForm1 = class(TForm) Memo1: TMemo; cp2: TApdComPort; lc1: TApdSLController; ApdStatusLight1: TApdStatusLight; ApdStatusLight2: TApdStatusLight; ApdStatusLight3: TApdStatusLight; ApdStatusLight4: TApdStatusLight; ApdStatusLight5: TApdStatusLight; ApdStatusLight6: TApdStatusLight; ApdStatusLight7: TApdStatusLight; ApdStatusLight8: TApdStatusLight; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Edit2: TEdit; Dial: TBitBtn; Rdevice: TBitBtn; Pclose: TBitBtn; Panel1: TPanel; cbIslem: TcxImageComboBox; Clstxt: TButton; Panel2: TPanel; Fedit1: TsFilenameEdit; Fsend: TsBitBtn; Freceive: TsBitBtn; Fedit2: TsFilenameEdit; Prt1: TApdProtocol;
A X A – READING SOFTWARE SOURCE CODE u in u ty
86
PrtSt: TApdProtocolStatus;
Memo2: TMemo; ssBar;
PMenu1: TPopupMenu; xt1: TMenuItem;
ClearTxt1: TMenuItem; lg: TSaveDialog;
Label10: TLabel; t3: TEdit;
pen(Sender: TObject); Avail(CP: TObject; Count: Word);
ender: TObject); ct); ject); t; var Action: TCloseAction); ct); ct); ject);
ct); ject);
eClick(Sender: TObject); tocolFinish(CP: TObject; ErrorCode: Integer); findDropDown(Sender: TObject);
ick(Sender: TObject); ggerData(CP : TObject; TriggerHandle : Word); ggerTimer(CP: TObject; TriggerHandle: Word); s:longint); xt1Click(Sender: TObject);
etoTxt1Click(Sender: TObject); oxClick(Sender: TObject);
lick(Sender: TObject); lick(Sender: TObject);
4Click(Sender: TObject);
ions n;
d;
CbComfind: TComboBox; PBar: TProgre SavetoT SD Chkbox: TCheckBox; Btnopen: TButton; Btnftp: TButton; Edit1: TEdit; Label9: TLabel; Edi Button4: TButton; procedure cp2PortO procedure cp2Trigger procedure RdeviceClick(S procedure PcloseClick(Sender: TObje procedure cp2PortClose(Sender: TOb procedure FormClose(Sender: TObjec procedure FormCreate(Sender: TObje procedure ClstxtClick(Sender: TObje procedure Fedit1Change(Sender: TOb procedure FsendClick(Sender: TObje procedure Fedit2Change(Sender: TOb procedure Freceiv procedure Prt1Pro procedure CbCom procedure DialCl procedure cp2Tri procedure cp2Tri procedure Tmr(m procedure ClearT procedure Sav procedure Chkb procedure BtnopenC procedure BtnftpC procedure Button private Private declarat procedure SignO procedure Comfind; procedure ComEn public Public declarations
87
ord;
#22;
ESC = #27; #28;
end; var Form1: TForm1; S: String = ''; TF:Boolean = False; MCnttrg : Word; DCnttrg : Word; Timeout : Word; TCnttrg : Word; TDCnttrg : W PCnttrg : Word; RCnttrg :Word; const bos = #0; SOH = #1; STX = #2; ETX = #3; EOT = #4; ENQ = #5; ACK = #6; BEL = #7; BS = #8; TAB = #9; LF = #10; VT = #11; FF = #12; CR = #13; SO = #14; SI = #15; DLE = #16; DC1 = #17; DC2 = #18; DC3 = #19; DC4 = #20; NAK = #21; SYN = ETB = #23; CAN = #24; EM = #25; SUB = #26; FS = GS = #29;
88
= #30; US = #31;
= #32;
p2PortOpen(Sender: TObject); n
lc1.ComPort:=cp2; lc1.Monitoring:=True;
el1.Color:=clGreen;
rm1.cp2TriggerAvail(CP: TObject; Count: Word);
ount do
har;
s.Text:=memo1.Lines.Text+S;
1.RdeviceClick(Sender: TObject);
erties.Items[cbIslem.ItemIndex].Tag=1 then 'm1'
perties.Items[cbIslem.ItemIndex].Tag=2 then 'm2'
roperties.Items[cbIslem.ItemIndex].Tag=3 then = 'm3'
RS SP implementation uses Windows; $R *.DFM procedure TForm1.cbegi Panend; procedure TFovar I : Word; C : Char; S : String; begin S := ''; for I := 1 to C begin C :=cp2.GetC S := S+C; end; memo1.Line end; procedure TFormbegin if cbIslem.Prop cp2.OutPut := else begin if cbIslem.Pro cp2.OutPut := else begin if cbIslem.P cp2.OutPut :
89
= 'm4'; ;
end; nd;
1.PcloseClick(Sender: TObject); egin
'm9'; Tmr(100); ComEnd; nd;
ure TForm1.cp2PortClose(Sender: TObject);
rocedure TForm1.FormCreate(Sender: TObject);
slem.ItemIndex :=0; isible :=False; ible :=False;
re TForm1.ClstxtClick(Sender: TObject);
t:= ''; xt:='';
rocedure TForm1.Fedit1Change(Sender: TObject);
ileMask := Fedit1.FileName;
ure TForm1.FsendClick(Sender: TObject);
rotocolType := ptXmodemCRC ; tTransmit;
else cp2.Output : end e procedure TFormb cp2.Output:= e procedbegin Panel1.Color:=clRed; end; pbegin cbI Btnopen.V Btnftp.Vis end; procedubegin memo1.Tex memo2.Te Pbar.Position:=0; end; pbegin Prt1.Fend; procedbegin PrtSt.Visible:=True; Tmr(200); Prt1.P Prt1.Star S:=''; Memo1.Text:='';
90
.Visible:=False; ;
dure TForm1.Fedit2Change(Sender: TObject); egin rt1.FileName:= Fedit2.FileName;
receiveClick(Sender: TObject);
.ProtocolType := ptXmodemCRC; memo1.Visible:=False;
tartReceive;
nd;
ure TForm1.Prt1ProtocolFinish(CP: TObject; ErrorCode: Integer);
emo1.Visible:=True; Close.Enabled:=True;
ssMessages; = omfind.Text,4,Length(CbComfind.Text)-3));
; cp2.Open:=True;
trg := cp2.AddDataTrigger('CONNECT 4800', False); T', False);
PCnttrg := cp2.AddDataTrigger('/?!',True); ',True);
erTrigger; merTrigger;
cp2.AddTimerTrigger;
Memo1 Pclose.Enabled:=Falseend; proceb Pend; procedure TForm1.Fbegin S:=''; Prt1 Pclose.Enabled:=False; Prt1.S e procedbegin PrtSt.Visible:=False; Memo1.Text:=''; MPend; procedure TForm1.SignOn; begin Application.Proce cp2.ComNumber:StrToInt(Copy(CbC S:='' cp2.OutPut := 'ATDT'+ Edit2.Text+CR; MCnt DCnttrg := cp2.AddDataTrigger('CN RCnttrg := cp2.AddDataTrigger('FTP Completed TimeOut:= cp2.AddTim TCnttrg:= cp2.AddTi TDCnttrg:= Pbar.Position:=0; end;
91
findDropDown(Sender: TObject);
ind; nd;
ure TForm1.Comfind;
TRegistry; ts,PL : TStrings;
LOCAL_MACHINE; devicemap\serialcomm',false);
eate; PL := TStringList.Create; reg.GetValueNames(ts);
:= 0 to ts.Count -1 do begin
osition
ar Action: TCloseAction); egin
rocedure TForm1.DialClick(Sender: TObject);
egin
procedure TForm1.CbCombegin Comfe procedvar reg : i : integer; begin reg := TRegistry.Create; reg.RootKey := HKEY_ reg.OpenKey('hardware\ ts := TStringList.Cr for i PL.Add( reg.ReadString(ts.Strings[i]) ); end; ts.Free; reg.CloseKey; reg.free; CbComfind.Items:=PL; end; procedure TForm1.ComEnd;begin cp2.Open:=False; Dial.Enabled:=True; Pbar.P :=0; end; procedure TForm1.FormClose(Sender: TObject; vb cp2.Open:=False; Application.Terminate; end; pvar i:integer; b
92
toint(Edit1.Text); led:=False;
On; cp2.SetTimerTrigger(Timeout, i, True);
orm1.cp2TriggerData(CP : TObject; TriggerHandle : Word); nteger;
egin
ttrg then
etTimerTrigger(Timeout, 36, False);
True; F = True do
.Output:='m9'; Tmr(2000);
r(2000); cp2.Output:='m0';
F:=False; ComEnd; Memo2.Lines.Add('Not Connected to Device '+ DateTimeToStr(Now));
DCnttrg then in
TF:= False; Cp2.SetTimerTrigger(TDCnttrg,t,True);
else if TriggerHandle = PCnttrg then n
s:=''; i:= str Dial.Enab Sign end; procedure TFvar i,t:ib PBar.Min:=1; PBar.Max:=12; i:=0; t:= StrToInt(Edit3.Text); if TriggerHandle = MCn begin cp2.S Pclose.Enabled:=False; TF:= While T begin i:=i+1; Pbar.Position:= i; cp2 cp2.Output:='m9'; Tm Tmr(5000) ; if i=12 then begin T end end end else if TriggerHandle = beg end begi
93
utput:='Comp';
= RCnttrg then
Memo1.Lines.Add('FTP Completed'); ;
end;
ount -t)< ms do essMessages;
TForm1.cp2TriggerTimer(CP: TObject; TriggerHandle: Word);
ut then
odem Time Out.. '+ DateTimeToStr(Now)); ;
= TDCnttrg then
Add('Connected to device '+ DateTimeToStr(Now)); e;
=0;
m1.ClearTxt1Click(Sender: TObject);
ext:='';
der: TObject);
then ;
cp2.o end else if TriggerHandle begin PrtSt.Visible:=False; end procedure TForm1.Tmr ; var t : longint; begin t:= GetTickCount; while (GetTickC Application.Proc end; procedurebegin if TriggerHandle = Timeo begin Memo2.Lines.Add('M ComEnd end else if TriggerHandle begin Memo2.Lines. Pclose.Enabled:=Tru Pbar.Position: end; end; procedure TForbegin Memo1.Tend; procedure TForm1.SavetoTxt1Click(Senbegin if SDlg.Execute Memo1.Lines.SaveToFile(SDlg.FileName)end;
94
oxClick(Sender: TObject);
.Checked =True then
isible:=False; .Visible:=False;
device.Visible:=False;
True; .Visible:=False;
lse;
4.Visible:=False; Chkbox.Checked =False then egin
isible:=True;
.Visible:=True;
le:=True; .Visible:=True;
isible:=False;
dit3.Visible:=True; 4.Visible:=True;
nd
= StrToInt(Copy(CbComfind.Text,4,Length(CbComfind.Text)-
p2.Open:=True; alse);
ct);
cp2.Open = False then egin emo2.Lines.Add('The Port Is Not Opened '+ DateTimeToStr(Now));
procedure TForm1.Chkbbegin If ChkboxEdit2.Visible:=False; Dial.Visible:=False; Clstxt.VcbIslemRBtnopen.Visible:=True; Btnftp.Visible:=Label9Label10.Visible:=FaEdit1.Visible:=False; Edit3.Visible:=False; ButtonifbEdit2.Visible:=True; Dial.VClstxt.Visible:=True; cbIslemRdevice.Visible:=True; memo1.Visibmemo2Btnopen.Visible:=False; Btnftp.VLabel9.Visible:=True; Label10.Visible:=True; Edit1.Visible:=True; EButtoneend; procedure TForm1.BtnopenClick(Sender: TObject); begin cp2.ComNumber:3)); cPCnttrg := cp2.AddDataTrigger('CRLFNAK/?!CRLF',Fend; procedure TForm1.BtnftpClick(Sender: TObjebeginIfbM
95
cp2.Open = True then p2.Output:='m6';
tton4Click(Sender: TObject);
end else if cend; procedure TForm1.Bubegin cp2.Output:='m5'; end; end.
96
ODE IN PICBASIC
e "modedefs.bas"
OSC 4 SED 1
efine LCD_BITS 4 ‘LCD bus size 4 or 8’ efine LCD_DREG PORTD ‘LCD data port’
e LCD_DBIT 0 ‘LCD data starting bit 0’ efine LCD_RSREG PORTE ‘LCD register select port’ efine LCD_RSBIT 0 ‘LCD register select bit’ efine LCD_EREG PORTE ‘LCD enable port’ efine LCD_EBIT 1 ‘LCD enable bit’
efine HSER_RCSTA 90h ‘Hser receive status init’ efine HSER_TXSTA 20h ‘Hser transmit status init’ efine HSER_BAUD 4800 ‘Hser baud rate’ efine HSER_CLROERR 1 ‘Hser CLEAR overrun error’
efine SER2_BITS 8 ‘Set number of data bits for Serin2’ ‘and Serout2’
1 var byte[16] har0 var byte
har var byte[65] var byte[65] var byte
har1 var byte har2 var byte har3 var byte
ak var byte
ADCON1 = 7 ‘Set PORTA and PORTE to digital, otherwise portA ADC’ Low PORTE.2 ‘LCD R/W line low (W)’ Pause 500 ‘Wait for LCD to startup’
Lcdout $fe, 1, " Waiting for" Lcdout $fe, $C0, "initialization!"
APPENDIX B – SOURCE C Includ DefineDefine LOADER_U DDDefinDDDD DDDD D
ac cab ccc n
97
g Tx port of USART’
serin 6000,notinitialized,[wait ("m"), b]
] m nication "
Lcdout $fe, $C0, " initialized! "
erin2 PortB.0,24764,20
erin2 PortB.2,24764,2000,meterdetect2,[str a1\16]
etect3:
13,10,21,47,63,33,13,10] 4,2000,meterdetect3,[str a1\16]
serout [13,10,"Port 3 = Meter",13,10]
64,[13,10,21,47,63,33,13,10] erin2 PortB.6,24764,2000,meterdetect4,[str a1\16]
4 = Meter",13,10]
Lcdout $fe, 1, "Status of Ports " , " detected! "
Hserout [13,10,"Multi-port device is waiting for request!",13,10]
etting the operation request by listenning the USART serial port and’
inverted logic serial port in a loop’
‘Waiting for communication initialization by listenin start: H Hserout ["CNT"
Lcdout $fe, 1, " Co mu
pause 1000 ‘Port status detection procedure’ Serout2 PortB.1,24764,[13,10,21,47,63,33,13,10] S 00,meterdetect1,[str a1\16] Hserout [13,10,"Port 1 = Meter",13,10] detect2: Serout2 PortB.3,24764,[13,10,21,47,63,33,13,10] SHserout [13,10,"Port 2 = Meter",13,10]
dSerout2 PortB.5,24764,[Serin2 PortB.4,2476H detect4: Serout2 PortB.7,247SHserout [13,10,"Port loop: Lcdout $fe, $C0 pause 2000 Lcdout $fe, 1, " Waiting for" Lcdout $fe, $C0, " request!!! " ‘G‘
98
2000,listennext,[wait ("m"),char0]
Serin2 PortB.0,24764,2000,listenstart,[wait ("m"),char0] goto lis
sten:
Case "1"
d the readout string to meter’
rwise branch to noconnection’ Serin2 PortB.0,24764,3010,noconnection,[str a1\16]
rout [str a1\16]
‘Data receiving after getting Meter id from meter, if ended goto datason’
cdout $fe, 1, " Data Receiving "
$C0, " from 2 "
,13,10]
erin2 PortB.2,24764,3000,noconnection,[str a1\16] Hserout [str a1\16] pause 10
listenstart: Hseringoto listen listennext:
ten li Select Case char0 Lcdout $fe, 1, " Data Receiving " Lcdout $fe, $C0, " from 1 " ‘Sen Serout2 PortB.1,24764,[47,63,33,13,10] ‘Start to receive data(meter id), othe Hse pause 10 Don1: Serin2 PortB.0,24764,3010,datason,[char0] Hserout [char0] Goto Don1 Case "2" L Lcdout $fe, Serout2 PortB.3,24764,[47,63,33 S
99
on2: PortB.2,24764,3000,datason,[char0]
Hserout [char0]
Lcdout $fe, 1, " Data Receiving " Lcdout $fe, $C0, " from 3 "
Serout2 PortB.5,24764,[47,63,33,13,10]
erin2 PortB.4,24764,3000,noconnection,[str a1\16]
erin2 PortB.4,24764,3000,datason,[char0]
Case "4"
dout $fe, 1, " Data Receiving "
B.7,24764,[47,63,33,13,10] pause 10
Serin2 PortB.6,24764,3000,noconnection,[str a1\16] t [str a1\16]
ause 10
4: 0]
serout [char0]
"5"
D Serin2 Goto Don2 Case "3" pause 10 S Hserout [str a1\16] pause 10 Don3: S Hserout [char0] Goto Don3 Lc Lcdout $fe, $C0, " from 4 " Serout2 Port Hserou p Don Serin2 PortB.6,24764,3000,datason,[char H Goto Don4 Case
100
nsfer procedure is initiated from main PC’
TP initiated " 0, " by main PC"
Hserout [13,10,"Ready for file transfer",13,10] pause 1000
erout2 PortB.1,16572,[13,10,"Be ready for receiving file",13,10]
Serin2 PortB.0,16572,30000,receivernotready,[nak]
op1:
leted,[char2] 00,problem,[char3]
Hserin 1000,problem,[str char\65] erin 1000,problem,[str a\65]
6572,[char1,char2,char3,str char\65,str a\65]
Serin2 PortB.0,16572,11000,noreplyfromreceiver,[nak] Hserout [nak]
ase "6"
Lcdout $fe, 1, " FTP initiated "
ortB.1,16572, [13,10,"Ready for file transfer",13,10] 1000
erout [13,10,"Be ready for receiving file",13,10]
0,receivernotready1,[nak] Serout2 PortB.1,16572,[nak]
‘File tra Lcdout $fe, 1, " F Lcdout $fe, $C S pause 1000 Hserout [nak] lo Hserin 5000,nofiletransfer,[char1] Hserin 500,ftpcomp Hserin 10 Hs Serout2 PortB.1,1 goto loop1 C‘File transfer procedure is initiated from remote PC’ Lcdout $fe, $C0, " by remote PC" Serout2 P pause Hs pause 1000 Hserin 3000 loop12:
101
ar1] erin2 PortB.0,16572,500,ftpcompleted1,[char2]
lem1,[char3]
Serin2 PortB.0,16572,1000,problem1,[str char\65]
Hserout [char1,char2,char3,str char\65,str a\65]
,noreplyfromreceiver1,[nak] Serout2 PortB.1,16572,[nak]
out2 PortB.1,16572,["Modem connection is closed by remote end!!"]
Lcdout $fe, $C0, "initialization!"
oto start
Case Else
Lcdout $fe, 1, "FALSE REQUEST!"
oto loop
otinitialized:
t 1 = Computer",13,10] 2 PortB.1,16572,[13,10,"The main PC is online now!!!",13,10]
eterdetect2: rout [13,10,"Port 2 = No connection",13,10]
ct3
Serin2 PortB.0,16572,5000,nofiletransfer1,[ch S Serin2 PortB.0,16572,1000,prob Serin2 PortB.0,16572,1000,problem1,[str a\65] Hserin 11000 goto loop12 Case "9" Ser Lcdout $fe, 1, " Waiting for" g End Select g ngoto start meterdetect1: Hserout [13,10,"PorSeroutgoto detect2 mHsegoto dete
102
o detect4
rout [13,10,"Port 4 = No connection",13,10]
fter Data reading is completed’
Lcdout $fe, 1, " Data Received " Hserout [13,10,"Data receiving is completed!",13,10]
000 goto loop
’
Lcdout $fe, 1, " No connection!" [13,10,"No meter connected to this port!",13,10]
pause 1000 goto loop
low program parts are related with ftp process’
tp process from main PC to remote PC is not started’ ransfer:
Lcdout $fe, 1, "No data received" ut ["No data received"]
Serout2 PortB.1,16572,["No data received from sender"] pause 1000
f ftp process from main PC to remote PC is completed’ pcompleted:
t2 PortB.1,16572,[4] Hserout [6]
00
t2 PortB.1,16572,[13,10," FTP Completed",13,10]
meterdetect3: Hserout [13,10,"Port 3 = No connection",13,10] got meterdetect4: Hsegoto loop ‘Adatason: pause 3 ‘If no access to meter at related portnoconnection: Hserout ‘Be ‘If fnofilet Hsero goto loop ‘Ift Lcdout $fe, 1, "FTP completed!" pause 2000 Serou pause 1 Hserout [13,10," FTP Completed",13,10] Serou
103
goto loop
main PC to remote PC’
24]
ut $fe, 1, "problem" pause 2000 goto loop
e char’ ady:
f receiver does not respond with ACK or NACK to last received block’ yfromreceiver:
noreplyfromrcvr" t reply with ACK or NACK for last
m sender"]
rom remote PC to main PC is completed’ pcompleted1:
, "FTP completed!"
B.1,16572,[6]
‘If a problem is occured during file transfer from problem: Hserout [ Serout2 PortB.1,16572,[24,24,24] Lcdo ‘If receiver does not send handshakreceivernotre Lcdout $fe, 1, " Receiver" Lcdout $fe, $C0, " not ready!! " goto loop ‘Inorepl Lcdout $fe, 1, " Serout2 PortB.1,16572,["You did noblock"] goto loop ‘If ftp process from remote PC to main PC is not started’ nofiletransfer1: Lcdout $fe, 1, "No data received" Hserout ["No data received fro Serout2 PortB.1,16572,["Data could not be received!!"] pause 1000 goto loop ‘If ftp process fft Lcdout $fe, 1 pause 2000 Serout2 Port Hserout [4] pause 100 Hserout [13,10," FTP Completed",13,10]
104
rtB.1,16572,[13,10," FTP Completed",13,10] goto loop
em is occured during file transfer from remote PC to main PC’ roblem1:
,24,24] , "problem"
goto loop
t send handshake char’ ernotready1:
e in receving file mode!"] oto loop
spond with ACK or NACK to last received block’ yfromreceiver1:
rout ["You did not reply with ACK or NACK for last block"]
nd
Serout2 Po ‘If a problp Hserout [24] Serout2 PortB.1,16572,[24 Lcdout $fe, 1 pause 1000 ‘If receiver does noreceiv Lcdout $fe, 1, "notready" Hserout ["B g ‘If receiver does not renorepl Lcdout $fe, 1, "noreplyfromrcvr" Hse goto loop E
105
MULTIPORT DEVICE USER MANUAL
sions of the Device
shows the dimensions of the multi-port device. As it can be e can be located easily thanks to its
APPENDIX C – 1)- Dimen Figure – 1 seen from the figure multi-port devicreasonable dimensions.
Figure – 1 Dimensions of the device
)- Connection Specifications
onnection point in the system:
2 C The multi-port is connected between the remote
odem and digital electricity meters as shown in Figure – 2: m
Figure – 2 The multi-port device and digital electricity meters
Figure – 3 The multi-port device, remote PC and digital electricity meters Port Specifications: The connection points of modem, PC and electricity m
n in Figure – 4. The connections are realized by RJ12 connectors asspecified in Figure 5 and 6.
eters are as show
Figure – 4 Connections to the ports
106
107
Meter Side RJ-12 Male Socket - Device
Modem Side
Figure – 5 Meter-Device Connection
(25-pin Male) RJ-12 Male Socket - Device
Figure – 6 Modem-Device Connection
Remote PC Side DB9 Female RJ-12 Male Socket – Device
Figure – 7 Modem-Device Connection
E: empty, not used
108
Power Supply: The multi-port device can be operated by using a standard voltage daptor. The voltage of the adaptor can be changed between 12 V –24 V. The
recomm an adaptor. 3)- Minimum Requirements for the Main Parts of the System PC:
aended voltage is 12 V DC from
The PC might be a standard personal computer, which has Windows 2000 or XP operating system. For other Windows or Linux, Unix some settings about the operating system might be needed. The main and easy requirement for the PC is a properly working serial com. Port. PC Side Modem : It ter producers
at the modem should be Hayes compatible, under this circumstances the modem ight be internal or external. The recommended and tested as properly working
and sets are as following:
AT &F1 AT+MS=9,0,4800,0,0,4800 AT&M0 AT%C0 ATX3 ATE0 AT&W0 AT&W1 AT&Y0
But it should be noted that these settings are not the only way for solution and might be changed according to user and system preferences.
emote Side Modem :
is recommended by the Digital Electricity Methmmodem settings with AT comm
R It is recommended by the Digital Electricity Meter and
sted as properly working modem settings with AT command sets are as following:
AT &F1 AT+MS=9,0,4800,4800,0,0,4800 ATS0=1 AT&M0 AT%C0 ATE0 AT&D0 AT&W0 AT&W1 AT&Y0
producers that the modem should be Hayes compatible. The recommendedte
109
But it should be noted that these settings are not the only way for solution nd might be changed according to user and system preferences. a
Meters : The meters which can be read properly in this system must have at least ne RS232 communication port and very importao ntly they must communicate ith the peripherals according to the FLAG protocol. FLAG protocol is created
wby FLAG Association as guide to IEC Meter Communications Specifications. 4)- Reading Software
Figure – 8 Main Screen of Reading Software on Main PC
tion, should be selected. The active ports are listed in the left upper ox.
2)- h will be dialed to establish the communic specified in the box at left side of Dial button
3)- Next, the timeout values for main PC to modem connection and main PC to mul vice should be entered to right upper box. After that, Dial button should be clicked, and thus the “ATDT + Phone Number” command is sent to modem. Then connection is established and the program starts to send connection indication string to the multi-port device. After the handshake process between th rt device and main PC is completed, the program will receive the por st e multi-port device, such as which device is connected to
When the program is started on the main PC, the program window shown
in Figure – 2.1 should appear on the main PC screen. The execution steps of software are described below: 1)- First of all, the port of main PC, which will be used for serial
ommunicacb
Then the phone number, whice remote side, should beation to th
.
ti-port de
e multi-poatus of tht
110
which nnection will be
losed automatically by the program. The related indication messages appear on e left log window.
esired meter should be selected from the box and then Read Device button hould be clicked. If the meter is not password protected and also connected to the
ata will be listed in reading window on the left. The ut data can be written to a text file by clicking right button of mouse over the
window. 6)- This meter readout procedure can be executed for each meter in the
same manner. The readout window on the left can be cleared at anytime by clicking Clear Text button.
7)- If the request is to perform a file transfer to the remote PC, the request must be initiated by clicking to the Initiate FTP button and after that the file to be sent should be selected by clicking File Open icon at the bottom of the program window at same line with Send button. After clicking to the Send button, the file transfer procedure will wait for 30 seconds for preparation of remote PC to receive a file. Within 30 seconds, when the remote PC passes to receiving file mode, the file transfer process will start according to Xmodem protocol.
8)- If a file transfer request is received from remote PC, the multi-port device informs the main PC to be in receiving mode within 30 seconds. When the main PC enters to receiving file mode, the file transfer process will start according to Xmodem protocol.
9)- The connection between main PC and multi-port device can be closed at anytime by the user of main PC by clicking Close Port button.
Note s of serial
ommunicat or green accordi
. Clear Text button can be used at
port. If the handshake process between main PC and multi-port device, which can continue 60 seconds at most, fails anyhow, the cocth
4)- After the connection is established successfully, the request may be to perform a remote reading procedure of a meter or to perform a file transfer to the remote PC.
5)- If the request is to perform a remote reading procedure of a meter, the dsport properly, the readout dreado
: The buttons below the reading window indicates the statuion performed by using APRO Libraries. They will be redc
ng to the status of process while the program is running. Clear Text button clears the reading window to prepare for next reading
anytime.
111
Figure – 9 Main Screen of Reading Software on Remote PC
When the program is started on the remote PC, the program window shown in Figure – 2.2 should appear on the remote PC screen.
The execution steps of software are described below: 1)- First of all, the Slave Computer box must be checked in order to turn
the lite version on. As soon as the program is started, the serial port to be used for the communication with multi-port device should be specified and opened.
2)- While the start up procedure of the multi-port device, the multi-port device sends the port status detection messages to all ports. As soon as the remote PC receives this message, it immediately replies with a specified string that indicates remote PC is connected and ready.
3)- Then the remote PC starts to wait for a file transfer procedure initialization message. When this message is received, the program should be in receiving file mode within 30 seconds. After a few seconds, the file transfer starts.
4)- The remote PC can initiate a file transfer anytime by clicking Initialize FTP button at the right bottom of the program window. If the remote PC receives Ready for file “ transfer” message, the file transfer can be started. When Send utton is clicked, the file transfer procedure will wait for 30 seconds for reparation of main PC to receive a file. Within 30 seconds, when the main PC asses to receiving file mode, the file transfer process will start according to
Xmodem protocol. 5)- After the file transfer from remote PC to main PC is completed, the
program execution turns back step 2. Throughout running of lite version remote access software, the specified serial port must be opened and the Slave Computer button must be checked.
bpp
112
APPENDIX D – XMODEM FILE TRANSFER PROTOCOL
Xmodem
Xmodem, which is one of the oldest, simplest and slowest file transfer
t
a
an is req
protocols, was developed and first implemented by Ward Chrlstensen in 1977 and
placed in the public domain. Since then, it has become an extremely popular
protocol and continues in use today (although at a diminished frequency).
Xmodem uses blocks of only 128 bytes and requires an acknowledgmen
of each block. It uses only a simple checksum for data integrity.What follows is
simplified description of the Xmodem protocol, although it describes far more
th uired to actually use the protocol.
Figure – 1 Xmodem block structure
The <SOH> character marks the start of the block. Next comes a one byte
block number followed by a ones complement of the block number. The block
number starts at one and goes up to 255 where it rolls over to zero and starts the
cycle again. Following the block numbers are L28 bytes of data and a one-byte
checksum. The checksum is calculated by adding together all the data bytes and
ignoring any carries that result. Below table describes a typical Xmodem protocol
transfer.
113
itter to send a block of
data. If it does not get a block within 10 seconds, it sends another <NAK>. This
continues for 10 retries, after which the receiver gives up.
If the receiver does get a block, it compares the checksum. It calculates to
the received checksum. If the checksums differ, the receiver sends a <NAK> and
the transmitter resends the block. If the checksums match, the receiver accepts the
block by sending an <ACK>. This continues until the complete file is transmitted.
The transmitter sign which the receiver
cknowledges with an <ACK>.
of value BlockFillChar, whose default is ^Z.
Xmodem often exhibits a start-up delay. The transmitter always waits for a
<NAK> from the receiver as its start signal If the receiving program was started
first, the transmitter probably missed the first <NAK> and must wait for the
receiver to time out and send another <NAK>.
Figure – 2 Xmodem protocol transfer steps
The receiver always starts the protocol by issuing a <NAK>, also called
the handshake character. It waits 10 seconds for the transm
ifies this by sending an <EOT>,
a
From this description several things become clear. First, this protocol does
not transfer any information about the file being transmitted. Hence, the receiver
must assign a name to the incoming file.
The receiver also does not know the exact size of the file, even after it is
completely received. The received file size is always a multiple of the block size.
This Xmodem implementation fills the last partial block of a transfer with
characters
114
Xmodem has been tweaked and improved through the years. Some of
which substitutes
16 bit CRC (cyclic redundancy check) for the original checksum. This offers a
the transmitter doesn't
ck starts with an <STX> character instead of an
it for an acknowledgment. However, it
The only merit of the basic Xmodem protocol is that it is so widespread
that it is probably supported by any microcomputer communications program you
can find, thus providing a lowest common denominator between systems.
Xmodem Extensions
these variations have become standards of their own.
The first of these improvements is called Xmodem CRC,
a
much higher level of data integrity. When given the opportunity, you should
always choose Xmodem CRC over plain Xmodem.
The receiver indicates that it wants to use Xmodem CRC by sending the
character ‘C’ instead of <NAK> to start the protocol. If
respond to the ‘C’ within three attempts, the receiver assumes the transmitter is
not capable of using Xmodem CRC. The receiver automatically drops back to
using checksums by sending a <NAK>.
Another popular extension is called Xmodem 1K. This derivative builds
on Xmodem CRC by using 1024 byte blocks instead of 128 byte blocks. When
Xmodem 1K is active, each blo
<SOH>. Xmodem 1K also uses a 16 bit CRC as the block check.
A larger block size can greatly speed up the protocol because it reduces the
number of times the transmitter must wa
can actually reduce throughput over noisy lines because more data must be
retransmitted when errors are encountered.
115
APPENDIX E – COMPLETE LIST OF SERIN2/SEROUT2 MODES
Baud Rate Bit 15 (Output)
Bit 14 (Conversion)
Bit 13 (Parity) Mode Number
300 Driven True None 3313 300 Driven True Even* 11505 300 Driven Inverted None 19697 300 Driven Inverted Even* 27889 300 Open True None 36081 300 Open True Even* 44273 300 Open Inverted None 52465 300 Open Inverted Even* 60657
600 Driven True None 1646 600 Driven True Even* 9838 600 Driven Inverted None 18030 600 Driven Inverted Even* 26222 600 Open True None 34414 600 Open True Even* 42606 600 Open Inverted None 50798 600 Open Inverted Even* 58990
1200 Driven True None 813 1200 Driven True Even* 9005 1200 Driven Inverted None 17197 1200 Driven Inverted Even* 25389 1200 Open True None 33581 1200 Open True Even* 41773 1200 Open Inverted None 49965 1200 Open Inverted Even* 58157
2400 Driven True None 396 2400 Driven True Even* 8588 2400 Driven Inverted None 16780 2400 Driven Inverted Even* 24972 2400 Open True None 33164 2400 Open True Even* 41356 2400 Open Inverted None 49548 2400 Open Inverted Even* 57740
4800 Driven True None 188 4800 Driven True Even* 8380 4800 Driven Inverted None 16572 4800 Driven Inverted Even* 24764 4800 Open True None 32956 4800 Open True Even* 41148 4800 Open Inverted None 49340 4800 Open Inverted Even* 57532
9600 baud may be unreliable with 4MHz clock 9600 Driven True None 84 9600 Driven True Even* 8276 9600 Driven Inverted None 16468
116
9600 Driven Inverted Even* 24660 9600 Open True None 32852 9600 Open True Even* 41044 9600 Open Inverted None 49236 9600 Open Inverted Even* 57428
baud rates Hz c terbelow require 8M lock or fas 14400 Driven True None 49 14400 Driven True Even* 8241 14400 Driven I nverted None 16433 14400 Driven Inverted Even* 24625 14400 Open True None 32817 14400 Open True Even* 41009 14400 Open I nverted None 49201 14400 Open Inverted Even* 57393
baud rates belo z c aster w require 10MH lock or f19200 Driven True None 32 1920 Driven Tru Even 82240 e * 1920 0 Driven I nverted None 16416 1 I920 0 Driven nverted Even* 24608 1920 0 Open True None 32800 1920 0 Open True Even* 40992 1920 0 Open I nverted None 49184 1 I920 0 Open nverted Even* 57376
baud rates belo z c aster w require 16MH lock or f28800 Driven True None 15 28800 Driven True Even* 8207 28800 Driven I nverted None 16399 28800 Driven I nverted Even* 24591 28800 Open True None 32783 28800 Open True Even* 40975 28800 Open Inverted None 49167 28800 Open I nverted Even 57359
33600 Driven True None 10 33600 Driven True Even* 8202 33600 Driven Invert ed None 16394 33600 Driven I 2nverted Even* 4586 33600 Open True None 32778 33600 Open True Even* 40970 33600 Open Inverte d None 49162 33600 Open I nverted Even 57354
baud rates below z c aster require 20MH lock o fr 38400 Driven True None 6 38400 Driven True Even* 8198 38400 Driven Inverted None 16390 38400 Driven I 2nverted Even* 4582 38400 Open True None 32774 38400 Open True Even* 40966 38400 Open Inverted None 49158 38400 Open Inverted Even 57350
ty when E SER D 1 is u
]
*Pari is odd DEFIN 2_OD sed. [Ref. 9