SlideShare a Scribd company logo
1 of 61
Download to read offline
i
The Robert Gordon University, Aberdeen
School of Engineering
BSc(Eng) in Electronics & Electrical Engineering
Remote Serially Addressable Actuator
G S Mackay 0708738
April 2009
ii
Remote Serially Addressable Actuator
Gerard Steven Mackay
April 2009
This report is submitted in partial fulfilment of the requirements for the degree of
BSc(Eng) in Electronics and Electrical Engineering at The Robert Gordon
University, Aberdeen
iii
I declare that this report, except where otherwise stated, is based on my own
work. To the best of my knowledge and belief, this report contains no material
previously published or written by another person, except where due reference
has been made.
Signed:……………………………………….. Date:……………………………
iv
Abstract
The project of developing a Serially Addressable Actuator for operation over a
long-haul two-wire transmission-line (10K-25K Ft) is being pursued to investigate
the feasibility of direct communication with sensors and actuators in remote
locations, from a local computer, without the need for an intermediary ‘smart-hub’.
A ‘smart-hub’ can be a relatively complex device incorporating CPU-based
telemetry systems and its complexity may become the ‘weak-link’ with respect to
reliability in hostile environments that are exposed to temperature and vibration
extremes.
The Actuating-Device is to be developed on minimal hardware for maximum
reliability and compactness of design (minimum cost being an associated benefit).
The PICKit1 Flash Programmer Starter Kit forms the hardware basis of the project.
The project involves development of suitable line-code and firmware to operate the
communication link over a simulated transmission-line and to test and assess
functionality by transferring data between a transmission and reception device.
Progress has been documented by photographic screen-capture of scope-signals.
Initial progress has been encouraging, having established a prototype that has
demonstrated functional 9600 bps communication over a simulated 10K – 20Kft
line.
There are some clear and specific limitations in the design, but they have been
given due consideration, are well understood, and specific remedial work and a
more thorough testing regime have been proposed.
i
Acknowledgements
I would like to thank my Project Supervisor, Mr. Graeme Dunbar in the
School of Engineering for his guidance, advice and consideration.
ii
Table Of Contents
Page Number
1.0 Introduction 1
1.1 Background 1
1.2 Objectives 1
2.0 Technical analysis and Formulation of Solution 3
2.1 Basic Elements of the System 3
2.2 Consideration of Control-Station Signal-Source 3
2.3 Consideration of Transmission Medium and Signal 4
2.4 Consideration of Line-Signal Encoder/Transmitter 5
2.5 Consideration of Line-Signal Receiver/Decoder 6
2.6 Selection of Development Hardware 7
3.0 Design & Working Solution 8
3.1 Speed Limitation of the Receiving Hardware 8
3.2 Generating Line-Code in a Continuous Loop 10
3.3 Implementation of Line-Code Generator 13
3.4 Hardware Reconfiguration to Develop Receiver Code 15
3.5 Developing Receiver Code- Analysing Sync Detection 17
iii
3.6 Developing Receiver Code- Sync Recovery 19
4.0 Testing and Evaluation 26
4.1 Reviewing Results- Data-Recovery and Addressability 26
4.2 Project Appraisal 29
5.0 Future Development 31
5.1 Performance Enhancement of Existing Hardware via Firmware 31
5.2 Performance Enhancement through Hardware 31
5.3 Further Testing 32
6.0 A Brief Note in Conclusion 33
7.0 References 34
8.0 Bibliography 35
Appendix-1 TX-PIC Program Listing 36
Appendix-2 Short, Medium and Long Line Scope Signals 43
Appendix-3 RX-PIC Program Listing 46
iv
List of Figures
Page Number
Figure-1 Opto-Coupler 4
Figure-2 Line-Code 6
Figure-3 Hardware 14
Figure-4 TXER Test Schematic 14
Figure-5 Line-Code Scope Capture 16
Figure-6 RXER PIC Hardware Reconfiguration 17
Figure-7 Short-Line Sync Detection Pulses 20
Figure-8 Medium-Line Sync Detection Pulses 21
Figure-9 Long-Line Sync Detection Pulses 21
Figure-10 Idealised Line-Code Diagram 22
Figure-11 Data Recovery Routine 24
Figure-12 Recovered Serial Data 26
Figure-13 Short Line Data Recovery 27
Figure-14 Long Line Data Recovery 27
1
1.0 Introduction
1.1 Background
Control of actuators (electrical, electro-hydraulic or electro-mechanical) in remote
sub-sea completions or down-hole equipment is often achieved by communicating
with a ‘smart’ hub (usually a CPU based device located in the remote location, like
Kvaerner’s Sub-sea Distribution Unit, for example) over a dedicated telemetry link
or MODEM.
CPU based devices tend to be realized on relatively complex PCB’s, the reliability
of which can be severely compromised by the adverse conditions (temperature
and vibration extremes) often associated with sub-sea well-head and down-hole
operating environments.
Communicating directly with the simpler (‘dumber’) devices normally connected
below the ‘smart hub’ could offer greater reliability-
 minimal component count with fewer inter-connections translates into
physically more rugged and compact (and relatively inexpensive) hard-ware
 simple, rugged, compact and relatively inexpensive hard-ware units can be
easily ganged together (in duplicate) to build redundancy into a specific
function
1.2Objectives
Investigate the feasibility of direct-communication with simple working-end
devices, such as actuators, over an extended transmission-line utilising minimal
peripheral/additional hardware. The investigation will be conducted as follows-
1 Implementation of a simple electronic actuator to be located remotely from its
control station and operated over a two-wire electrical connection
2 To make the actuator addressable to enable multiple identical devices to be
operated (for redundancy and/or multiple alternate actuations) over a single
two-wire communication link.
2
3 To implement a suitable serial line-code for transmission of the device-address
in a format that produces an easily recoverable signal at the remote-end of a
simulated transmission-line (using a commercial line-simulator).
4 To use an oscilloscope to document and assess signal-quality at the remote
end and to determine a broadly suitable line-termination resistance and assess
its effect on signal-quality.
5 To implement the design on minimal hardware to minimise cost and maximise
physical reliability and compactness.
6 To appraise the results of the project objectively, highlighting limitations,
assessing practical viability and identifying areas for further investigation and
development going forward.
3
2.0 Technical analysis and Formulation of Solution
2.1 Basic Elements of the System
There are four basic hardware elements to the proposed system-
 Control-Station/Signal-Source
 Local encoder/transmitter
 Transmission medium
 Remote receiver/decoder
There is one basic hardware element to the project in general- selection of
appropriate transmission and reception hardware to meet the following criteria-
 Minimal component count to maximise compactness and reliability (as
stated in the project objectives)
 Versatility of hardware configuration for ease of reconfiguration as
development progresses
 Hardware complexity suited to the experience-level of the developer
2.2 Consideration of Control-Station Signal-Source
Personal Computers (PC’s) are widely available in the modern workplace and are
an obvious and practical choice as a work-station for generating control signals.
The RS232 9-Pin Serial-Port is a simple computer I/O-Interface, available as part
of the standard PC hard-ware or as an ‘add-on’ through a USB-RS232 Dongle.
The port can be operated as a two-wire (one-way) or three-wire (two-way)
connection and is accessible to the user through terminal-emulators such as
AccessPort-1.8 (which can be down-loaded from the internet, free of charge).
Digital logic-states in RS232 are represented serially in dual-polarity voltage-
windows within successive fixed-period time-slots, or ‘bit-periods’,
(*Tompkins&Webster 6.5 p175, 6.3 p165) and are easily converted to single-
ended 5v logic as per figure-1 below (*pin-out from OPI1264 Data-Sheet).
4
The RS232-port can be configured from the AccessPort tool-bar.
To simplify the initial development process the Parity-bit will not be used and only
one stop-bit will be used (though this effectively ‘legalises’ any number of actual
stop-bits). The required number of data-bits per character and baud-rate will
become clear after consideration of the performance limits of the transmission and
reception hardware.
2.3 Consideration of Transmission Medium and Signal
The transmission-medium being utilized ultimately determines the nature of the
transmission signals and terminating-hardware appropriate for the system.
An electrical-wire medium can be adversely affected by localised sources of
electrical noise and interference, but it offers the following advantages over RF
and optical-fibre-
 Mechanically rugged- umbilical connections may be load-bearing
 Ease of connection to, and termination of, the medium at either end
 Suitable for subterranean or submarine applications
 Steady-State Power can be carried on transient-signal lines
The electrically reactive properties of a wire transmission-line become increasingly
significant with length and signal-frequency (*Tompkins&Webster section 6.5).
For a given line-length, signal attenuation will increase with frequency. Raw
RS232 serial-data contains a range of frequency components at the bit-level, from
consecutive logic ‘ones’ or ‘zeros’ at the high-end, to alternating logic ‘ones’ and
‘zeros’ at the low-end. A range of signal frequencies translates into a range of
signal attenuations, producing inconsistent signal amplitudes and compounding
5
threshold-based data recovery. Furthermore, frequency-attenuation at edge-
transitions manifest as slewing that obscures bit-boundary definition and hence,
compounds bit-level recovery within the correct time-frame.
This project proceeds using a commercial line-simulator (from General Electric
Energy Systems Ltd) which simulates short, medium and long (switch-selectable)
lines of ~0.25” armoured mono-conductor cable- broadly representing line-lengths
up to 15KFt, 20KFt and 25KFt respectively.
2.4 Consideration of Line-Signal Encoder/Transmitter
As outlined above, signal-level based communication becomes increasingly
impractical for transmission of serial-data over an extended wire-connection as bit-
rate increases. A low-speed system may well suffice for a limited number of
remote addressable actuators- but a higher speed system with higher bandwidth
could be more versatile, supporting an extended array of actuators to a finer
degree of timing-precision and potentially handling more complex transfers, such
as sending adjustment parameters to variable-output actuators and receiving
responses like acknowledgements, alarms or even sensor-data. In short, the more
versatile the system, the more practically viable it becomes- but this requires
greater bandwidth and this translates into higher bit-rate.
Self-Clocking line-encoding techniques use edge-transition polarity to preserve the
logic-state and time-frame integrity of a digital-signal, even when the edge-
transitions are slewed. In this system, the direction of the edge-transition in the
middle of a bit-period (rising/slope-up or falling/slope-down) corresponds to a
distinct bit-state (eg. logic-1 or logic-0). This requires a digital level-transition
within every bit-period and produces a line-signal frequency which is at least
double that of the RS232 equivalent. This higher frequency signal will suffer
greater attenuation over a given transmission-line, but the critical point here is that
its logic-state and time-frame information are preserved.
Converting an RS232 bit-level to an edge-transition is straight-forward- the bit-
level can be ‘flipped-over’ half-way through the bit-period.
6
However, in a series of consecutive ‘ones’ or ‘zeros’ edge-transitions are produced
on the boundary between the end of the previous bit-period and the start of the
subsequent bit-period. A distinction must be made to determine which edges are
in the middle of the bit-period (representing logic-states) and which edges are
boundary transitions. This can be done by placing a synchronising bit at the start
of the serial-byte. The sync or start-bit can be made distinct from the data-bits by
making it assume a logic-state (complementary to the idle state) for a full bit-
period. Bit-period boundaries are then clearly defined at regular bit-period intervals
from the lagging-edge of the sync-bit. By default, an ‘end’ or stop-bit becomes
defined by the persistence of the idle-state for a full bit-period, as per the summary
in figure-2 below.
Note that alternating logic-states (eg. 1010) will produce an alternating sync-stop
pattern. A finer definition of sync incorporates a preceding idle-state, where the
idle-state is defined (as distinct form a stop-bit) where it persists for a duration
exceeding one full bit-period.
This project proceeds on the basis of a self-clocking line-code with first-half bit-
period logic-1-hi and logic-0-lo line-driving states, as outlined in figure-2.
2.5 Consideration of Line-Signal Receiver/Decoder
The line-code outlined above will charge the transmission-line during active-hi
periods and discharge the line during idle-lo periods, producing a net positive
offset on a capacitive-line due to the initial full bit-period ‘charge-cycle’ associated
with the sync-bit. The resulting signal-amplitude presented to the receiver will
depend on the bit-rate and current-driving properties of the transmitter, the length
and characteristic-impedance of the line, and the terminating impedance of the
receiver. A receiver that continually monitors the line-signal will be able to
7
determine (‘resolve’) the direction of the edge-transitions within a self-clocking line-
code as long as it satisfies the following criteria-
 Receiver sampling-frequency must be greater than twice that of the
maximum frequency-component contained within the incoming signal (to
avoid aliasing- Nyquist/Shannon)
 The maximum and minimum absolute signal-amplitudes must not exceed
the range of the receiver/converter to avoid signal-clipping
 The smallest valid localised peak-to-peak amplitude difference within the
incoming signal must be considerably greater than the resolution of the
receiver-converter, to avoid conversion uncertainty at the LSB(s) level from
obscuring signal subtleties
2.6 Selection of Development Hardware
The fundamental project hardware criteria (outlined previously) of minimal
component-count and versatility of configuration can be met by developing the
required hardware functionality on a PIC Microcontroller. PIC’s are low-cost and
physically compact with minimal pin-out and may contain a versatile range of
onboard resources such as comparators, counter-timers, ADC’s, relatively high-
current sink/source I/O (typically 25mA) and internal clocking.
PIC’s are also available in ‘Starter Kits’ for inexperienced developers, and as is the
case in this project, a Starter-Kit meets the previously stipulated criteria of
selecting hardware suited to the experience level of the developer.
In this project hardware development proceeds with the PICKit-1 Flash Starter Kit
from Microchip, which utilises a PIC12F675 containing all the onboard resources
outlined above, and using the devices onboard 4MHz clock.
8
3.0 Design & Working Solution
3.1 Speed Limitation of the Receiving Hardware
The PIC12F675 can execute an instruction every micro-second when utilising the
onboard 4MHz clock (Data-Sheet section-1). Setting and clearing an output-port to
generate line-pulses can be accomplished in two instructions to achieve a
maximum ‘self-clocking’ line-code of 500K bps. This is considerably faster than the
bit-rates supported by the RS232-Interface (AccessPort-1.8 supports 256000
maximum bps). Therefore, bit-transmission does not impose a throughput-limit on
system speed. However, the ability of the PIC to effectively drive an ‘end-useable’
signal over a transmission-line by itself does, ultimately, impose a speed-limitation-
but this is not considered here because the overriding speed-limitation is imposed
by the receiver.
The primary speed-limitation in the system is the sampling-rate of the receiver.
In order to detect a valid sync-bit when it appears on the line, the receiver monitors
the line continuously, comparing consecutive samples to identify an increasing
signal trend that’s indicative of an incoming (slewed but rising) leading-edge.
The PIC12F675 ADC can do a 10-bit conversion in 22us (11TAD, where TAD =
2us with maximum ‘legal’ internal A2D clock-selection- Data-Sheet section-7.1.4).
In addition to doing the conversion, a ‘continuous monitor-cycle’ must also
compare the current-conversion to the previous-conversion to assess the signal
trend. This process requires the following steps-
1 Pull the current-conversion into the working-register
2 Subtract the current-conversion value from the previous-conversion value
3 Store the current-conversion as the legacy-conversion for the next cycle
4 Comparison- did the above subtraction set the status-register carry-bit?
If ‘carry-clear’ then current-conversion is bigger than previous-conversion so
proceed to the next cycle, otherwise go back to the first trend-detection cycle
9
Each of the listed steps takes a 1us instruction-cycle, except step-4, which takes
two cycles because steps that change the program-counter, like conditional-
branches, consume an additional instruction cycle (Data-Sheet section 10.0).
This brings the best-case sample-to-sample monitor-cycle to 27us in length.
Even if the sample-processing steps are performed simultaneously while the ADC
is converting (22us of available space), the requisite conditional-branch on
‘conversion-done’ (+2us) to save the conversion (+1us) and start the next
conversion (+1us) would incur a 4us overhead, bringing the best possible monitor
cycle-time to 26us.
19200 bps RS232 has a bit-period of 52us, twice the frequency of the best-
possible ‘sample-cycle’ available from the hardware configuration. This does not
quite satisfy Nyquist/Shannon. Therefore the next fastest available RS232 speed
of 9600 bps will be used.
Since the PIC12F675 is an 8-bit device, the project will proceed on the basis of
generating and decoding line-code (as previously outlined) based on 8-bit, 9600
bps RS232.
Another speed-limitation of the ADC, inherent to its sample-and hold design, is the
Acquisition Time. Paraphrasing Tompkins & Webster and the PIC Data-Sheet:
“The sample-and-hold capacitor must have time to charge to the level of the input
signal and track it within a specified error-band (Tompkins/Webster 5.1 p146) in
order for the ADC to meet its specified accuracy (Datasheet 7.2 p45)“
The PIC Data-Sheet goes on to calculate the Acquisition-Time at just under 20us
at an operating temperature of 50C and a maximum recommended source-
impedance of 10K. Source impedance (Rs) is fundamental to Acquisition-Time.
Reducing Rs reduces Acquisition-Time. With PIC-I/O source-impedance of 200
Ohms (25mA @ 5v, Datasheet 12.0 p81), typical line-resistance of 100 Ohms and
typical RX termination-resistance of 200 Ohms (Tompkins/Webster 6.5 p170), the
Thevenin-equivalent source-impedance becomes 120 Ohms and Acquisition-Time
comes down to less than 11us (Tacq = 3.25us + (9.15E-10)(8K + Rs)us @ 50C).
10
Acquisition-Time is part of the ADC Sample-Cycle which occupies the period
between the end of the previous-conversion and the start of the subsequent-
conversion. This period is determined by the RX-PIC sampling-cycle code. The
sampling period will be discussed further during overview and of the RX-PIC
sampling-code.
One final limiting-factor arising from the ADC is absolutely fundamental to line-
code generation in this system. The PIC12F675 ADC is not bipolar and can only
handle signals in the range 0v to +5v. The consequence of this is that the line-
code drive-current must ‘source-from’ and ‘sink-back’ to the same I/O-line with
respect to a common 0v-line (as opposed to driving two I/O-lines onto the two
transmission-wires, as a ‘voltage-doubling’ complementary-pair). There is an
important caveat to this point, but it will not be discussed here, having been
seconded to the design appraisal discussion instead.
3.2 Generating Line-Code in a Continuous Loop
For the purposes of developing the receiver algorithm and analysing results in
general, it is useful to have a known bit-pattern line-coded and transmitted in a
continuous loop from a TX-PIC at one end of the line-simulator. A fixed pattern
enables stable and consistent oscilloscope triggering in order to closely examine
the effects of the line on the arriving signal and to directly compare received
waveforms to outputs from test-points on an RX-PIC (displayed on a second
scope-channel).
A full listing of the ‘looping’ line-driving assembly-code is contained in Appendix-1.
The fine-detail of the code-functionality is contained within the embedded
comments in the program and a general overview of the program follows here:
The program utilises the General-Purpose I/O-register (GPIO) to output high and
low line-driving output-states under the direction of a series of nested sub-routines.
The lowest-level (basement) sub-routine is ‘wait-period’ which comprises of a very
crude delay-loop (2 instructions + branch = 3us) which loops ‘waitcount’ (11)
11
times. The loop-branch is skipped on the final loop, shortening the final loop by
1us, so a time-padding null operation (1us) is added to simplify the total loop-time
calculation to ‘waitcount x 3us’. The total time consumed by ‘wait-period’ includes
an additional two instructions (2us) to load the ‘count’ register and the subroutine
‘call & return overhead’ of 4us (2us outbound, 2us return). Hence, the total wait-
period, all-in, is 39us (11 x 3 + 2 + 2 + 2us).
Residing one step up from the basement in the nesting hierarchy are the output
sub-routines ‘hi_out’ and ‘lo_out’. These sub-routines set GPIO bit-4 output high
or low respectively to drive the line-signal accordingly. The ‘load’ and ‘present’
instructions (2 instructions, 2us) at the start of each output routine produce 2us of
‘output-latency’ between the routine starting and the output actually changing.
‘Latency terms’ will become important in the subsequent discussion.
Nested at the top of the subroutine hierarchy are the bit-routines, ‘start’, ‘one’,
‘zero’ and ‘stop’. These routines call the ‘hi’ and ‘lo’ output-routines to generate the
appropriate bit-period line codes (hi-hi, hi-lo, lo-hi and lo-lo respectively).
In the first half of a bit-period, the ‘outbound’ leg of the nested call loop to the bit-
subroutine produces 2us of ‘initial-call-latency’ and the subsequent call to the
output-subroutine produces another 2us of ‘output-call-latency’. Returning from
the output-routine to the bit-routine produces 2us of ‘output-call-return-latency’.
The total period of the output-state in the first-half of a bit-period is the sum of the
wait-period (39us), output-call-return-latency (2us), and output-call-latency plus
output-latency (2us + 2us) from the next half-bit-period. This generates a half-bit-
period output of 45us which is then padded-out to 52us by seven null-operations in
the first-half of the bit-routine (one half-bit-period is 52us at 9600 bps).
The second half-bit-period includes two additional latencies- ‘bit-call-return-
latency’ (2us) and ‘initial-call-latency’ (2us) from the next bit-period, producing
4us of extra latency in total. For this reason the second-half of the bit-routine only
requires three null-operations to pad-out the output time-period to 52us.
The above discussion is complex and is summarised in pseudo-code below for
clarification:
12
Instruction Latency
Call bit-routine 2us initial-call
Call output-routine 2us output-call
Load & present o/p 2us output
(output now in new state at start of output half-bit-period)
Wait 39us
Return to bit-routine 2us output-call-return
Null operations (7) 7us
Call next output-routine 2us output-call
Load & present o/p 2us output
(output now in new state after 39 + 2 + 7 + 2 + 2 = 52us)
Wait 39us
Return to bit-routine 2us output-call-return
Null operations (3) 3us
Return from bit-routine 2us bit-call-return
Call next bit-routine 2us initial-call
Call output-routine 2us output-call
Load & present o/p 2us output
(output now in new state after another 39 + 2 + 3 + 2 + 2 + 2 + 2 = 52us)
And so on…
There is no subsequent bit-routine-call to terminate the end of the stop-bit after
52us but this is of no consequence because the stop-bit output-state is the same
as the idle output-state in this line-code. Similarly, a loop-instruction (to continually
loop a fixed bit-pattern) placed after the stop-bit on the last byte of a looping-string
is inconsequential in respect of line-code functionality.
Clearly system-timing is fundamental, and to this end the PIC12F675 internal clock
is factory calibrated within 1% (Data-Sheet section-1, P1) with the correction-value
stored in memory and loaded into the oscillator-calibration register (OSCAL) on
program-initialisation (the PICKit1 development-board and Flash Programmer
utility provide an option to regenerate the oscillator calibration if required).
13
Additionally, null-operator (nop) time-padding within the TX-PIC bit-call-
subroutines provide scope for ‘fine-tweaking’ the output-waveform time-frame.
The TX-PIC program is inefficient and clumsy in its use of code, but the top-tier bit-
call routines are easily edited to generate any looping line-code bit-pattern as
required, to facilitate closer inspection of signals by oscilloscope.
3.3 Implementation of Line-Code Generator
The PICKit1 development-board and associated Flash-Programming Utility
facilitate ‘in-circuit’ programming and testing of functionality. Only three additional
items of hardware are required at this stage of development-
 Commercial Line-Simulator
 Line-Termination Resistor (RS Resistance Decade Box)
 Oscilloscope
The hardware is illustrated in figure-3 (connected as per schematic in figure-4
below) with 200 Ohm termination-resistance selected and the resulting line-
attenuated signal (continuously looping bit-pattern) displayed on the scope:
14
The TX-PIC code contains routines to continually loop consecutive line-code ones,
zeros and alternating start-stop bit-patterns (to verify timing of output transitions),
as well as looping the line-code byte-pattern (00h-ffh-AAh-C3h) displayed on the
scope in figure-3.
15
Requisite bit-pattern subroutine-selection is made by ‘un-commenting’ the required
routine into the active code and ‘commenting-out’ redundant routines using the in-
circuit-programming and Flash-Programmer Utility. This is not eloquent or efficient
but it is a workable enough solution for this stage of development, so that precious
project-time can be focussed on developing, testing and evaluating the more
complex and technically challenging RX-PIC code.
3.4 Hardware Reconfiguration to Develop Receiver Code
Testing of the TX-PIC through the line-simulator with a range of termination
resistances (from 50 to 500 Ohms) indicates that termination-resistance primarily
affects signal-amplitude in this particular configuration, with no sign whatsoever of
any signal distortion associated with reflections. A transmission-line should
produce reflections unless properly terminated with a pure-resistance equivalent to
its characteristic-impedance (*Tompkins&Webster 6.5 p170). However, the line-
simulator only simulates the properties of resistance and capacitance, neglecting
inductance, and this is the most likely explanation for the signal purity apparent on
the scope (medium-line setting with 200 Ohm termination) illustrated on figure-5
below.
16
Further scope-capture signals for all three line-simulator settings (long, medium
and short) with 200 Ohm termination-resistance are presented on Appendix-2.
The 200 Ohm termination-resistance is a reasonable value to use ‘in practice’
(*Tompkins&Webster 6.5 p170) and clearly produces a signal-amplitude (in
conjunction with the medium-line setting) that is comfortably within the range of a
5v ADC. Despite its ‘cleanliness’ and purity, the resultant signal appears irregular
and slewed enough to provide a good test-signal for the RX-PIC development.
Idealised conditions are more forgiving in the early stages of development, and
this can expedite the process of getting the fundamentals of a solution resolved
initially (leaving the more practical details to a later stage, where the ongoing
‘learning-curve’ should extrapolate to a more enlightened perspective). Hence,
RX-PIC development proceeds with a medium-line and 200 Ohm termination
configuration. The TX-PIC is moved to the Prototype Socked and connected to an
initially ‘blank’ RX-PIC in the Development/Evaluation socked as per Figure-6
below.
17
Note that GPIO-lines RA1 and RA2 have been designated as scope-output test-
points (tp1 and tp2 respectively) for comparing the real-time line-signal on scope
channel-1 to specific RX-PIC state and/or timing-signals (0-5v) presented on
scope channel-2. The state/timing signals are generated by ‘progress’ or ‘state’
markers strategically embedded within the RX-PIC code for de-bugging purposes.
The progress/state markers ‘bit-set’ or ‘bit-clear’ GPIO1 and GPIO2 as required.
3.5 Developing Receiver Code- Analysing Sync Detection
The first part of the line-code which is transmitted to the receiver is the sync-bit.
The scope-trace in figure-5 clearly depicts the prominent sync-transition at the
start of each line-code byte. As discussed/proposed in section 2.5 and 3.1, a
receiver routine which continually samples the incoming-signal should be able to
resolve line-code transitions by comparing successive samples to determine if
there is an upward or downward trend. A sync-bit is transmitted as ‘hi-out’ for a full
bit-period. This condition continually charges the line for the full bit-period to create
a signal at the receiver-end which trends upwards for one full bit-period. Identifying
‘sync’ then becomes the process of checking that the current-sample has greater
magnitude than the previous-sample, for the number of iterations (of the process)
that are expected to complete within the time-interval of the respective bit-period.
Therefore, in order to detect ‘sync’ (or any other bit), it is critical to determine how
many sample-and-compare cycles can be completed in 104us (1 bit-period @
9600 bps). The proposed conversion-and-compare cycle from section 3.1 was
18
27us long in theory, but this didn’t take account of the 3us overhead required to
branch (2us) past a ‘wait-for-conversion-complete’ loop, and then execute the
instruction to start the next conversion (1us).
A practical convert-and-compare cycle, as outlined below, will take 30us:
1. Start the current-conversion
2. Wait for the current-conversion to complete
3. Pull the current-conversion into the working-register
4. Subtract the current-conversion value from the previous-conversion value
5. Store the current-conversion as the legacy-conversion for the next cycle
6. Comparison- did the above subtraction set the status-register carry-bit?
If ‘carry-clear’ then current-conversion is bigger than previous-conversion
so proceed to the next cycle, otherwise go back to the first trend-detection
cycle
Running a prototype version of the above-noted code with scope-markers placed
at the start and end of the cycle reveal that it actually has duration 33us.
The bit-test loop which forms the ‘wait for conversion-complete’ step has a 3us
overhead comprising of the bit-test itself (1us) and its loop-back (2us). The bit-test
is performed on the first and then every third program-step after the ‘conversion
start’ instruction (T+1, 4, 7…22 us). It appears that the ADC ‘busy-bit’ remains set
for the full 22us of conversion-time and then clears on the 23rd
program-step. This
causes the bit-test on the 22nd
program-step to force another 3us loop at T+22us.
A 33us convert-compare cycle means that there is only enough room for 3 cycles
in any given 104us bit-period. This means that two out of every three consecutive
cycles need 2us of time-padding and the third needs 1us in order to space the
sampling evenly across the bit-periods. Time-padding is achieved through null-
operations (nops) or single-step instructions (like scope-output bit-setting) as
required.
Note that the 33us sample-compare cycle with 22us of conversion-time leaves
11us of sample-time in which to accommodate the required 10.7us of Acquisition-
Time (derived in section 3.1) in order for the ADC to meet its specified accuracy.
It would appear that the RX-PIC code is operating the ADC just within its limits.
19
Note also that all sampling is done using only the most-significant byte of the 10-
bit conversion (left-justified, Datasheet 7.1 p43) in order to expedite the
processing-time required to complete the sample-convert-compare cycle. This
gives the ADC a resolution of 19.5mv using the internal-reference.
A full-listing of the developed receiver-code is contained within Appendix-3 while
the main body of the ‘Developing Receiver Code’ text is restricted to outlining the
broader concepts behind the code and highlighting the main challenges that had to
be overcome in the development process.
3.6 Developing Receiver Code- Sync Recovery
With a ‘3-sample per bit-period’ rule established in section-3.5, sync can be
identified as comprising the first three consecutive samples that are successively
incremental (in amplitude), after an idle (no signal) line-state.
Identifying the ‘no signal’ idle-state is achieved using the PIC onboard comparator.
Comparator functionality is achieved through appropriate bit-setting of the
comparator-control and voltage-reference-control registers (Datasheet section-6
p35-40). The comparator is configured to operate on the lowest (non-zero)
internal-reference threshold of 208mv by selecting low-range and using voltage-
reference control-nybble ‘0001’. With the low-range bit set, the Threshold is the
product of the control-nybble and VDD/24 (208mv = 1 * 5v/24).
The sync-detector code is implemented by cascading three of the sample-and-
compare routines outlined previously, behind a continuous comparator wait-loop.
The comparator wait-loop holds the program in a wait-state until the line-signal
rises from the idle-state and passes through the 208mv comparator threshold.
Once the threshold is crossed the program breaks-out of the wait-loop and moves
on to the successive sample-and-compare routines. The rising-edge from a valid
sync will generate successively bigger conversions at each compare-cycle and
program flow should pass through all three cycles unhindered. A corrupt line-
signal which produces a smaller conversion at one of the successive cycles will
cause sync-detection to re-direct to an abort-routine. The abort-routine waits for
the line-signal to return to an idle-state by using the comparator to signal when the
20
line is clear. Once the line is clear/idle the abort-routine re-directs program-flow
back to the start of the sync-detection routine. Note that subroutine-cascading is
used in the sync-detection routine (instead of repeatedly re-looping through the
same subroutine three times) because it’s structurally easier to implement within
the tight time-constraints of the continuously sampling code.
Placing a sync-detection scope-marker (1us pulse) at the end of the sync-
detection subroutine enables the routine functionality to be verified as per figures-
7, 8 and 9 below (for short, medium and long line-simulations respectively).
The sync-detection pulses appear as faint-dots on the lower scope-trace,
underneath the sync-bit to which they relate, at the start of each byte.
21
3.6 Developing Receiver Code- Data Recovery
The Data-Recovery Process can be analysed by creating an idealised line-code
diagram that conceptually presents the received-signal as if it were generated by a
perfect current-source driving a perfectly-capacitive line, as per figure-10 below.
22
The idealised line-code diagram represents successive sampling-cycles
horizontally, with three samples per bit-period, and the ‘hold-and-convert’
converter-transition indicated just after the start of each sampling cycle.
Each marker on the ‘hold-and-convert’ transition line represents non-zero signal-
magnitudes that will be derived by the ADC on completion of the conversion.
(Non-zero in this context refers to a value that’s distinctly bigger than low-end
random noise-floor values)
Four possibilities are considered for a random arrival of sync on a continuously
sampled time-line-
1. ADC-hold catches the very start of sync, just as it breaks from noise-floor
2. ADC-hold just misses the start of sync when it breaks from the noise-floor
3. Sync arrives during an ongoing noise-floor conversion
4. ADC-hold catches the first valid sync-value (very close to the noise floor)
but (randomly) the preceding noise-floor conversion is marginally bigger,
causing the sync-recovery routine to misinterpret it, and reject it as a
random noise-floor (‘zero’) value
Looking closely at the series of markers, a clear and consistent pattern emerges
which forms a solid general rule (with one avoidable exception)-
Taking the third sample, and every third sample thereafter (3,6, 9…) as a
threshold against the average-value of the two samples that follow it, produces a
result which is diagnostic of the bit-period that the samples straddle.
23
For example, if the first threshold (third sync sample) is bigger than the average
of the two subsequent samples then the signal is trending-down in the first-half bit-
period and the full bit-period is diagnosed as logic-0.
If the first threshold (third sync sample) is smaller than the average of the two
subsequent samples then the signal is trending-up in the first-half bit-period and
the full bit-period is diagnosed as logic-1.
The next sample after the second ‘diagnostic’ then becomes the threshold in the
next cycle (repetitively): Threshold/ 1st
-Diagnostic/ 2nd
-Diagnostic/ Threshold…
The exception to the rule arises where the ‘ADC-hold’ catches the very start of a
random sync-arrival, just as it breaks from the noise-floor, generating a very early
‘extraneous’ sync-sample and resulting in four sync-samples over the bit-period.
However, implementation of the idle-state comparator (as outlined earlier in
section 3.6) will discriminate against samples close to the noise-floor, rejecting the
exception-value and ensuring that the established ‘General Rule’ holds true.
(ADC resolves to 20mv but comparator discriminates below 200mv)
The data-processing subroutine uses the ‘General Rule’ to recover all 8-bits of
data. As program flow leaves the Sync-Detection routine a bitcount parameter is
initialised to 8-bits and the legacy conversion from the third sync sample is saved
as the threshold for the first diagnostic comparison. A start-bit (logic-0) is sent to
logic output-pin GPIO2/TP2, effectively lagging the start-bit on the input/line-side
by a full bit-period. Program flow then enters the data-recovery routine and the 1st
-
diagnostic is acquired, then the 2nd
-diagnostic is acquired, added to the 1st
-
diagnostic and the result shifted-right (halved) to form a diagnostic-average. The
bit-count is decremented and the next threshold-conversion is started (the
averaging and bit-count steps complete within a regular 35us cycle). While the
next threshold is being converted the diagnostic-comparison for the previous bit is
performed and the result is sent to a logic-output-pin (GPIO2/TP2) and shifted into
a recovered data-byte register designated databyte. Logic outputs to databyte
and TP2 lag the real-time line-code data on the input/line-side by one bit-period.
This process of acquiring a threshold, diagnostic-average and shifting the result of
the diagnostic-comparison into ‘databyte’ and out of TP2 proceeds (lagging the
line-code by a bit-period) until all 8-bits have been recovered and shifted through.
24
On bitcount decrementing to zero, a final diagnostic-comparison and bit-recovery
cycle is completed and then Program Flow enters the stop-routine as outlined in
figure-11 below.
The stop routine is virtually the same as the sync-detection routine, except that the
stop routine proceeds through three successively decrementing conversions.
The Stop-Routine checks databyte against address (device address mask
defined at start of program) in the second-cycle and outputs an ‘activation’
25
flag/signal on completion of the last stop-cycle. The activation-signal will remain
active until receipt of the next ‘databyte’ that does not match the address mask.
The stop-routine must complete successfully in order for a stop-bit (logic-1) to be
issued from TP2, otherwise a logic-0 will be issued to force a ‘frame-error’ in any
connected RS232-device driven from the TP2-signal. Any inconsistencies with
successive samples in the Sync-Detect or Stop-Detect routines will redirect
program-flow to the Abort-Routine. Abort then issues logic-0 from TP2 and
maintains a wait-loop until the next ‘line-clear’ condition on the transmission-line.
TP2 then issues logic-1 (idle) and program-flow is directed to restart Sync-
Detection.
26
4.0 Testing and Evaluation
4.1 Reviewing Results- Data-Recovery and Addressability
Scoping the recovered serial-output data on TP2 and comparing it against the
incoming line-code indicates that the system is working correctly with the medium-
line simulation as per figure-12 below.
The recovered data is illustrated on the top channel with corresponding line-code
on the bottom channel and the scope triggering on the peak of the first logic-1
transition of data-byte-FFh.
A recovered start-bit (lagging line code by one bit-period) corresponds to each
line-code sync-transition and the subsequent data-patterns, 11111111, 10101010,
11000011, 00000000 and half of the next 11111111 are intact.
Finer scrutiny of the timing (by vertical-shift of the recovered data-stream onto the
mid-screen axis) confirms that the signal returns to the idle-state (or, more
correctly, stop-bit/idle) at the end of the eighth data-bit bit-period.
27
Similar testing of the recovered data-streams in the short and long line-simulator
settings are not as convincing, reference figures-13 and 14 below.
Above, 10101010 has become 10101011 and 11000011 has become 110000?1.
Below, 00000000 has become 10000000, note subtlety of line transition after sync
The long and short line results contain steady and flickering bit-errors.
Furthermore, the medium-line setting also becomes marginal if the termination-
resistance is incremented or decremented to subtly alter signal amplitude.
28
At the time of writing the address Flag/Signal does not appear to be functioning
correctly. The address-mask is FFh by default but the address-flag appears to go
active after line-code 00h. This suggests some erroneous inverted-logic in the
data-byte recovery and masking routine and this code requires further scrutiny.
However, the successful recovery of serial-data utilising the medium-line leads me
to the conclusion that the system basically works under ideal conditions.
29
4.2 Project Appraisal
The medium-line results clearly indicate that the proposed concept of line-code
generation and recovery, with the chosen hard-ware, is workable. The system is
sensitive to changes in line-length and termination-resistance, which is not
acceptable for a practically viable system, but these problems are most likely due
to limitations in the experience and ability of the developer to make the most
effective use the resources available within the PIC on which the project is based.
The long-line results in particular show that subtleties within badly attenuated line-
signals can be the source of errors and this is most likely due to poor utilisation of
the ADC. The developed code only uses the most-significant byte of the 10-bit
ADC-conversion and the resulting loss of resolution clearly has an adverse effect
that’s significant at certain signal-levels. In addition to this, the line-driver only
utilises half of the output voltage-swing available for driving the line (this will be
discussed further below) and this compounds the issues of signal-degradation
over the transmission-line.
The primary limitations of the hardware itself are the speed of the PIC’s internal
clock and the Acquisition and Conversion times of the ADC.
The 4MHz clock limits the complexity of the recovery-algorithm that can be
executed within the bit-period of the incoming signal and the ADC limits the
number of samples that can be acquired over the cycle (the ADC code operates
just within the ADC’s recommended Acquisition Time, as outlined in section 3.5).
More samples and more processing speed would translate into more reliable
operation.
The mono-polar nature of the ADC has not been a limitation because all the
testing has been carried-out with a capacitive-line, over which the sync-bit creates
a positive offset, keeping the rest of the signal above the reference. However, it’s
worth noting that over short connections the system would not be able (and would
not need) to use bi-polar line-driving.
One of the primary limitations of the project itself is that the effects (on the system)
of induced-noise and interference have not been considered. Development of the
project has proceeded using a simulated-line which produces very clean signals
30
with no reflections. The ‘sample-and-hold’ ADC configuration does have inherent
filtering characteristics, but testing needs to be done on a real transmission-line to
asses the effects of inductance and localised sources of EMI.
In summary, the objective of developing a serially-addressable actuator and
suitable line-code for operating it over a long-haul transmission-line utilising
minimal hardware have been achieved with moderate success.
The hardware is indeed minimal and basically works under ideal conditions-
demonstrating the viability of the concept- and the fundamental reliability
limitations that have been identified are understood, and importantly, can be
addressed with more work. However, there is a lot more work to do as outlined in
the following chapter.
31
5.0 Future Development
5.1 Performance Enhancement of Existing Hardware through Firmware
There a number of ways to significantly improve the performance of the system as
currently configured through better programming as outlined below-
1. The output-voltage of the line-driver can be effectively doubled by making
the reference transmission-line active (push-pull) instead of passive. The
hardware is currently configured to support this but the code doesn’t take
advantage of it because of the mono-polar ADC in the receiver. However,
as outlined in section 4.2, over a long capacitive line the sync-pulse creates
a positive-offset which overcomes the mono-polar issue in a long-line
configuration.
2. ADC resolution is poorly utilized- the ADC result should be shifted left one
or two places, as required, when the most-significant bit(s) is/are zero, in
order to improve resolution when handling smaller signals.
3. When the signal amplitude exceeds 90% of the ADC-Range (on very short
lines) the code should switch to comparator-based acquisition which is
faster and more efficient in respect of both the required code and the
required processing-time, and would enable handling of much higher data-
rates on short-connections.
4. Fix the bug in the address decoding code.
5. Better programming in general, by an experienced programmer, could
significantly improve performance by utilising available resources (like the
onboard timers) to control transmission and acquisition timing more
precisely, rather than relying on conversion-times and instruction counts.
5.2 Performance Enhancement through Hardware
The most minimal hardware improvement that could be made to the system would
be to utilise an external clock such as a 20MHz crystal oscillator. Faster speed
would enable development of more complex code to better utilise ADC results in
the restricted time frame.
32
The most fundamental hardware improvement would be to replace the current PIC
with one containing a faster internal clock and faster ADC to increase sampling.
More samples and faster code should produce better results.
5.3 Further Testing
Current testing of the system involves recovery of a looping-string of only four
characters. A full character-set 00-ffh needs to be used to test the system
properly. This can be done by adding code to the TX-PIC to generate a continuous
series of bytes that increment sequentially through all 256 possibilities in a
repeating loop. Alternatively, a PC running AccessPort-1.8 can be connected to
the TX-PIC GPIO3 (utilising the opto-coupler illustrated in figure-1) to send any
desired series of bytes for testing. The code to support this has already been
implemented in the TX-PIC (but only tested as far as checking character-entry
produces line-code on the line-monitoring oscilloscope). The RX-PIC can be
connected back to a separate receiving PC (RX and TX-PIC ‘ground’ must remain
isolated to prevent bypassing one side of the two-wire line simulator, hence
separate TX and RX PC’s). An RS232-TX connection can be made from RX-PIC-
TP2 through the anode of a small-signal diode (with its cathode connected to
RS232 DB9-2 and ‘tied-lo’ to DB9-3 through a 10K resistor) and PIC-GND can be
wired directly to RS232-common (DB9-5). Note that this configuration requires
inverting the logic-polarity of TP2 by flipping the logic-1 and logic-0 definitions in
the RX-code (because +5v in RS232 represents logic-0).
This is currently planned but has not been tested yet.
Assuming performance reliability can be enhanced to an acceptable level as
outlined in sections 5.1, there are two fundamental tests that need to be performed
at the earliest opportunity-
 Testing functionality with actual transmission-lines to assess system
tolerance to inductance and localised sources of electrical-noise.
 Heat-testing to quantify associated clock-drift (and assess the
ramifications thereof) and determine the general system tolerance to the
temperature extremes of the target down-hole or well-head operating
environment
33
6.0 A Brief Note In Conclusion
This project has been technically challenging but ultimately informative and
rewarding. The initial results are encouraging but the bulk of the work still remains
to determine if this can lead to a practically viable device. The ultimate goal is a
device that contains both the TX and RX functionality in one ‘comm-chip’ with
additional DAC and ADC channels to excite and monitor a directly connected
sensor. Implementation on a single chip would make it relatively easy to have
‘comm-chips’ embedded inside an array of sensors and actuators distributed over
a wide geographical area, effectively moving the digitisation to the sensor rather
than running sensor-signals to a digitiser over wires that can degrade signal
quality.
34
7.0 References
Willis J. Tompkins and John G. Webster, 1988, Interfacing Sensors to the IBM PC.
PTR Prentice Hall, Englewood Cliffs, New Jersey 07632.
As indicated in brackets in the body of text
PIC12F629/725 Data Sheet, from PICkit1 Flash Starter Kit installation CD.
As indicated in brackets in body of text
OPI1264A Opto-Coupler Data Sheet, http://www.optekinc.com/
As indicated in brackets in body of text
35
8.0 Bibliography
Willis J. Tompkins and John G. Webster, 1988, Interfacing Sensors to the IBM PC.
PTR Prentice Hall, Englewood Cliffs, New Jersey 07632.
PIC12F629/725 Data Sheet, from PICkit1 Flash Starter Kit installation CD.
Schematic, PICKit1 Flash Starter Kit, from PICkit1 Flash Starter Kit installation CD.
PICKit1 User Guide, from PICkit1 Flash Starter Kit installation CD.
Understanding & Programming the PIC16F84
http://www.talkingelectronics.com/html/PIC-for-Begginners.html
36
Appendix-1
TX-PIC Program Listing
37
;****************************************************************************
;File Name: 232-line-driver.asm
;Author: GS Mackay
;Date: March-09
;
;Description: Long-Haul 9600 Baud Serial Byte Line-Driver
;
;******************************************************************************
;Notes:
;******************************************************************************
;
;******************************************************************************
list p=12F675 ; list directive to define processor
#include <p12f675.inc> ; processor specific variable definitions
__CONFIG _CP_OFF & _WDT_OFF & _BODEN_ON & _PWRTE_ON & _INTRC_OSC_NOCLKOUT &
_MCLRE_OFF & _CPD_OFF
; '__CONFIG' directive is used to embed configuration word within .asm file.
; The labels following the directive are located in the respective .inc file.
; See data sheet for additional information on configuration word settings.
;******************************************************************************
;Defines
;******************************************************************************
#define Bank0 0x00
#define Bank1 0x80
#define rs232in GPIO,3
#define D0_1Tris B'11001111'
#define bit_hi B'00010000'
#define bit_lo B'00000000'
#define waitcount D'11'
;******************************************************************************
;General Purpose Registers (GPR's)
;******************************************************************************
cblock 0x20
count ; wait count
endc
;******************************************************************************
;Reset Vector
;******************************************************************************
ORG 0x000 ; processor reset vector
nop ; required by in circuit debugger
goto Init ; go to beginning of program
;******************************************************************************
38
;Interrupt Vector
;******************************************************************************
ORG 0x004
return ; interrupt trap - returns without re-enabling
;******************************************************************************
;Initialization
;******************************************************************************
Init
call 0x3FF ; retrieve factory calibration value
; comment instruction if using simulator, ICD2, or ICE2000
BANKSEL Bank1 ; BANK1
movwf OSCCAL ; update register with factory cal value
movlw D0_1Tris ; set direction so LEDs D0 & D1 are outputs
movwf TRISIO ; all others are inputs (high-z)
clrf ANSEL ; configure A/D I/O as digital
banksel Bank0 ; change back to PORT memory bank
movlw CM2 | CM1 | CM0 ; configure comparator inputs as digital I/O
movwf CMCON
;******************************************************************************
;Main
;******************************************************************************
Main
btfsc rs232in ; wait in loop until RS232 start-bit
goto Main ; SWITCH closure grounds input pin
;The output to the transmission line is idle-low by default.
;calling another lo_out when on the leading-edge of an RS232 start-bit...
;...offsets RS232-input data-clocking by a half bit-period to centralise...
;data-clocking in the middle of the bit-period.
;all subsequent 'clocking' is synchronised by the line-code generation time-frame
;loop
; call zero
; call one
; call start_bit
; call stop
; goto loop ; extends legacy state by 2us
call lo_out ; offset input-data clocking by half bit-period
call start_bit ; 1us
btfsc rs232in
call one
call zero
btfsc rs232in
call one
call zero
btfsc rs232in
call one
call zero
btfsc rs232in
call one
39
call zero
btfsc rs232in
call one
call zero
btfsc rs232in
call one
call zero
btfsc rs232in
call one
call zero
btfsc rs232in
call one
call zero
call stop
call stop
call stop
goto Main
;test-pattern continuous loop- 00000000-11111111-10101010-1100000011
loop
call start_bit
call zero
call zero
call zero
call zero
call zero
call zero
call zero
call zero
call stop
call stop
call stop
call start_bit
call one
call one
call one
call one
call one
call one
call one
call one
call stop
call stop
call stop
call start_bit
call one
call zero
call one
call zero
call one
40
call zero
call one
call zero
call stop
call stop
call stop
call start_bit
call one
call one
call zero
call zero
call zero
call zero
call one
call one
call stop
call stop
call stop
; goto loop
;******************************************************************************
;Subroutines & Functions
;******************************************************************************
start_bit
call hi_out ;2us
nop
nop
nop
nop
nop
nop
nop
call hi_out
nop
nop
nop
return
zero
call hi_out
nop
nop
nop
nop
nop
nop
nop
call lo_out
nop
nop
41
nop
return
one
call lo_out
nop
nop
nop
nop
nop
nop
nop
call hi_out
nop
nop
nop
return
stop
call lo_out
nop
nop
nop
nop
nop
nop
nop
call lo_out
nop
nop
nop
return
lo_out
movlw bit_lo ; data for outputs low
movwf GPIO ; send data to GPIO port
call wait_period
return ; return to calling routine
hi_out
movlw bit_hi
movwf GPIO
call wait_period
return ; return to calling routine
;******************************************************************************
;Time padding
;******************************************************************************
wait_period
; With 4Mz internal clock each instruction normally takes 1us to execute (4 cycles).
42
; However, bit-test or program-counter redirecting instructions are longer (2us).
movlw waitcount
movwf count
nop
waitloop
decfsz count,f
goto waitloop
return ; full countdown - exit
END ; directive 'end of program'
43
Appendix-2
Scope Capture Signal with Short, Medium and Long Line Simulator-Settings
and 200 Ohm Line Termination Resistance
44
45
46
Appendix-3
RX-PIC Program Listing
47
;****************************************************************************
;File Name: RS232-a2d-RX.asm
;Author: GS Mackay
;Date: March 2009
;Version: 1
;Description:
;
;******************************************************************************
;Notes:
;******************************************************************************
;
;
;******************************************************************************
list p=12F675 ; list directive to define processor
#include <p12f675.inc> ; processor specific variable definitions
__CONFIG _CP_OFF & _WDT_OFF & _BODEN_ON & _PWRTE_ON & _INTRC_OSC_NOCLKOUT &
_MCLRE_OFF & _CPD_OFF
; '__CONFIG' directive is used to embed configuration word within .asm file.
; The labels following the directive are located in the respective .inc file.
; See data sheet for additional information on configuration word settings.
;******************************************************************************
;Defines
;******************************************************************************
#define Bank0 0x00
#define Bank1 0x80
#define SWITCH GPIO,3
#define D0_1Tris B'11001001'
#define logic-0 B'00000000'
#define logic-1 B'00000100'
#define ANSelect B'00010001' ;Used to configure AD
#define ADControl B'00000001' ;Used to configure AD
#define cmpcontrol B'00011110' ;Used to configure comparator
#define refcontrol B'10100001' ;set comparator threshold
#define address B'11111111' ;device address mask
;******************************************************************************
;General Purpose Registers (GPR's)
;******************************************************************************
cblock 0x20
a2dresh ; a2d result, high-byte
bitcount ; received-bit counter, start-bit + 8 data-bits
legacy ; previouse a2d value for start & stop-bit routines
threshold ; a2d value at start of current bit-period
diagnostic ; average a2d value from middle to end of bit-period
databyte ; recovered bits shifted in from right
48
abortfloor ; any abort condition remains valid until 'line clear'
flags ; status flags register
endc
;******************************************************************************
;Reset Vector
;******************************************************************************
ORG 0x000 ; processor reset vector
nop ; required by in circuit debugger
goto Init ; go to beginning of program
;******************************************************************************
;Interrupt Vector
;******************************************************************************
ORG 0x004
return ; interrupt trap - returns without re-enabling
;******************************************************************************
;Initialization
;******************************************************************************
Init
call 0x3FF ; retrieve factory OSCAL value
banksel Bank1 ; BANK1
movwf OSCCAL ; update register with factory cal value
movlw D0_1Tris ; set GPIO directions
movwf TRISIO ; all others are inputs (high-z)
movlw ANSelect
movwf ANSEL ;Configure AN0 & prescale to A/D
movlw refcontrol
movwf VRCON ;Configure AN0 & prescale to A/D
banksel Bank0 ; change back to PORT memory bank0
movlw ADControl
movwf ADCON0 ;Set comparator threshold
movlw cmpcontrol
movwf CMCON ;configure comparator
bsf GPIO,2
bcf GPIO,1
bcf GPIO,4
bcf GPIO,5
clrf databyte
;******************************************************************************
;Main
;******************************************************************************
Main
btfsc SWITCH ;wait in loop until SWITCH closure is sensed
goto Main
bcf GPIO,2 ;clear LED on proram start
restart ;start-bit recovery routine
cmploop
49
btfss CMCON,6
goto cmploop ;wait for signal to cross threshold
;bsf GPIO,1 ;scope out hi for a2d-start
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for conversion start
movlw d'8'
movwf bitcount ;bitcount = 8 data-bits
clrf databyte ;initialise recovered databyte
movlw logic-1 ;prepare logic-1 idle-state
movwf GPIO ;output logic bit
a2dloop1 ;34us period
btfsc ADCON0,GO
goto a2dloop1 ;wait loop until a2d complete
;bcf GPIO,1 ;scope out lo on a2d complete
movf ADRESH,w ;MSByte (a2d result high) into working register
movwf legacy ;save current a2d value as legacy for next comparison
movwf abortfloor ;this level used as threshold for 'line clear' in abort routine
nop
nop
nop
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for conversion start
;bcf GPIO,1 ;scope out hi for conversion start
a2dloop2 ;33us period
btfsc ADCON0,GO
goto a2dloop2 ;wait loop until a2d complete
;bcf GPIO,1 ;scope out lo on a2d complete
movf ADRESH,w ;MSByte (a2d result high) into working register
subwf legacy,f ;subtract current a2d value from previouse
movwf legacy ;save current a2d value as new legacy for next comparison
btfsc STATUS,0 ;if carry clear then 'current' > 'previouse' a2d value
goto abort ;if 'previouse' > 'current' a2d then restart the start-bit search
;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle
;bsf GPIO,1 ;scope out hi for a2d-start
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for conversion start
;bcf GPIO,1 ;scope out lo for conversion start
a2dloop3 ;37us period, a2dloop1+2+3=104us
btfsc ADCON0,GO
goto a2dloop3 ;wait loop until a2d complete
;bcf GPIO,1 ;scope out lo on a2d complete
movf ADRESH,w ;MSByte (a2d result high) into working register
subwf legacy,f ;subtract current a2d value from previouse
movwf threshold ;save current a2d value as threshold for data recovery
50
btfsc STATUS,0 ;if carry clear then 'current' > 'previouse' a2d value
goto abort ;if 'previouse' > 'current' a2d then restart the start-bit search
;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle
movlw logic-0 ;prepare start-bit (logic-0 output)
movwf GPIO ;output logic
;bsf GPIO,1
;bcf GPIO,1 ;1us scope sync-pulse
goto firstdiag ;acquire 1st-diagnostic in data-recovery routine
datarecovery
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for conversion start
;bcf GPIO,1 ;scope out lo for conversion start
movfw threshold
subwf diagnostic,w ;compare diagnostic to threshold by subtraction
btfsc STATUS,0 ;carry clear when 'threshold' > 'diagnostic' on signal slope-down
bsf databyte,0 ;carry set if signal slopes-up indicating logic-1
movlw logic-0 ;prepare rs232 logic-0 output bits
btfsc STATUS,0 ;carry-set/slope-up requires rs232 logic-1 output bits
movlw logic-1 ;prepare rs232 logic-1 output bits
movwf GPIO ;output rs232 bit
rlf databyte,f ;move databyte bit-0 left for next diagnostic cycle
a2dloopa ;35us duration, a2dloopa+b+c= 104us
btfsc ADCON0,GO
goto a2dloopa ;wait for conversion loop
;bcf GPIO,1 ;scope out lo at conversion end
movf ADRESH,w ;grab a2d MSByte
movwf threshold ;current a2d becomes threshold for next two diagnostic samples
nop ;time padding
nop
nop
nop
nop
firstdiag
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for conversion start
;bcf GPIO,1 ;scope out lo for conversion start
a2dloopb ;34us period
btfsc ADCON0,GO
goto a2dloopb ;wait for conversion loop
;bcf GPIO,1 ;scope out lo at conversion end
movf ADRESH,w ;grab a2d MSByte
movwf diagnostic ;first post-threshold diagnostic sample
51
nop ;time padding
nop
nop
nop
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for conversion start
;bcf GPIO,1 ;scope out lo for conversion start
a2dloopc ;35us duration
btfsc ADCON0,GO
goto a2dloopc ;wait for conversion loop
;bcf GPIO,1 ;scope out lo at conversion end
movf ADRESH,w ;grab a2d MSByte
movwf legacy ;reference value for subsequent stop routine
addwf diagnostic,f ;add second diagnostic sample to first...
rrf diagnostic ;...and half result for diagnostic average
decfsz bitcount ;8 data-bits to count
goto datarecovery ;loop bit recovery until all 8 bits acquired
stop
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for a2d-start
;bcf GPIO,1 ;scope out lo for a2d-start
movfw threshold
subwf diagnostic,w ;last data-bit diagnostic comparison
btfsc STATUS,0 ;carry clear when 'threshold' > 'diagnostic' on signal slope-down
bsf databyte,0 ;carry set if signal slopes-up indicating logic-1
movlw logic-0 ;prepare logic-0 output bits
btfsc STATUS,0 ;carry-set/slope-up requires logic-1 output bits
movlw logic-1 ;prepare logic-1 output bits
movwf GPIO ;output logic bit
a2dstop1 ;34us duration
btfsc ADCON0,GO
goto a2dstop1 ;wait loop until a2d complete
;bcf GPIO,1 ;scope out lo on a2d complete
movf ADRESH,w ;MSByte (a2d result high) into working register
movwf legacy ;save current a2d value as legacy for next comparison
nop ;pad timing
nop
nop
nop ;pad timing if line above commented out
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for a2d-start
;bcf GPIO,1 ;scope out lo for a2d-start
a2dstop2 ;35us duration
btfsc ADCON0,GO
goto a2dstop2 ;wait loop until a2d complete
52
;bcf GPIO,1 ;scope out lo on a2d complete
movf ADRESH,w ;MSByte (a2d result high) into working register
subwf legacy,f ;subtract current a2d value from previouse
movwf legacy ;save current a2d value as legacy for next comparison
btfss STATUS,0 ;if carry set then 'current' < 'previouse' a2d value
goto abort ;if 'previouse' < 'current' a2d then abort byte recovery
;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle
nop ;pad timing if line above commented out
nop
bsf ADCON0,GO ;start a2d
;bsf GPIO,1 ;scope out hi for a2d-start
;bcf GPIO,1 ;scope out lo for a2d-start
movlw address ;load device address mask
xorwf databyte,w ;compare address mask to recovered databyte
btfsc STATUS,2 ;if zero then databyte matches address mask
bsf flags,0 ;set 'address match' flag
a2dstop3 ;33us duration- not critical on stop loop
btfsc ADCON0,GO
goto a2dstop3 ;wait loop until a2d complete
;bcf GPIO,1 ;scope out lo on a2d complete
movf ADRESH,w ;MSByte (a2d result high) into working register
subwf legacy,f ;subtract current a2d value from legacy value
movwf legacy ;save current a2d value as legacy for next comparison
btfss STATUS,0 ;if carry set then 'current' < 'previouse' a2d value
goto abort ;if 'previouse' < 'current' a2d then abort byte recovery
bsf GPIO,1 ;output stop-bit indefinately
btfsc flags,0 ;check if 'address match' flag set
bsf GPIO,5 ;output 'activation' signal if addressed
;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle
cmploop2
btfsc CMCON,6
goto cmploop2 ;wait loop- wait for idle-line
goto restart ;restart signal recovery
abort
;bsf GPIO,1 ;scope out hi for a2d-start
bsf ADCON0,GO ;start a2d
movlw logic-0 ;prepare logic-0 output bits to force frame-error
movwf GPIO ;output logic bit
a2dabort
btfsc ADCON0,GO
goto a2dabort ;wait loop until a2d complete
;bcf GPIO,1 ;scope out lo on a2d complete
movf ADRESH,w ;MSByte (a2d result high) into working register
53
subwf abortfloor,w ;subtract current a2d from first sync-detect value
btfss STATUS,0 ;if carry set then 'current' < 'line clear' value
goto abort ;hold loop until 'line clear threshold' > 'current' a2d
;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle
movlw logic-1 ;prepare logic-1 output bit
movwf GPIO ;output idle-state logic bit prior to restart
goto restart
;******************************************************************************
;Subroutines & Functions
;******************************************************************************
END ; directive 'end of program'

More Related Content

What's hot

JESD204B Survival Guide: Practical JESD204B Technical Information, Tips, and ...
JESD204B Survival Guide: Practical JESD204B Technical Information, Tips, and ...JESD204B Survival Guide: Practical JESD204B Technical Information, Tips, and ...
JESD204B Survival Guide: Practical JESD204B Technical Information, Tips, and ...Analog Devices, Inc.
 
Low Power Design flow using Power Format
Low Power Design flow using Power FormatLow Power Design flow using Power Format
Low Power Design flow using Power Formatijsrd.com
 
Configuração modbus yokogawa
Configuração modbus yokogawaConfiguração modbus yokogawa
Configuração modbus yokogawaJohn de Carvalho
 
ETHERNET PACKET PROCESSOR FOR SOC APPLICATION
ETHERNET PACKET PROCESSOR FOR SOC APPLICATIONETHERNET PACKET PROCESSOR FOR SOC APPLICATION
ETHERNET PACKET PROCESSOR FOR SOC APPLICATIONcscpconf
 
Novel fpga design and implementation of digital up
Novel fpga design and implementation of digital upNovel fpga design and implementation of digital up
Novel fpga design and implementation of digital upeSAT Publishing House
 
AREA EFFICIENT 3.3GHZ PHASE LOCKED LOOP WITH FOUR MULTIPLE OUTPUT USING 45NM ...
AREA EFFICIENT 3.3GHZ PHASE LOCKED LOOP WITH FOUR MULTIPLE OUTPUT USING 45NM ...AREA EFFICIENT 3.3GHZ PHASE LOCKED LOOP WITH FOUR MULTIPLE OUTPUT USING 45NM ...
AREA EFFICIENT 3.3GHZ PHASE LOCKED LOOP WITH FOUR MULTIPLE OUTPUT USING 45NM ...VLSICS Design
 
Nathaniel weathers resume linkedin
Nathaniel weathers resume linkedinNathaniel weathers resume linkedin
Nathaniel weathers resume linkedinNathaniel Weathers
 
Pactron , Hardware, Board level & Manufacturing solutions
Pactron , Hardware, Board level & Manufacturing solutions Pactron , Hardware, Board level & Manufacturing solutions
Pactron , Hardware, Board level & Manufacturing solutions Arvind Kumar
 
Architecture of a novel configurable
Architecture of a novel configurableArchitecture of a novel configurable
Architecture of a novel configurableVLSICS Design
 
Demystifying LTE Performance Management and Optimization
Demystifying LTE Performance Management and OptimizationDemystifying LTE Performance Management and Optimization
Demystifying LTE Performance Management and OptimizationOpeyemi Praise
 
DeltaV Electronic Marshalling
DeltaV Electronic MarshallingDeltaV Electronic Marshalling
DeltaV Electronic MarshallingSumeet Goel
 
Implementation and Validation of SAE J1850 (VPW) Protocol Solution for Diagno...
Implementation and Validation of SAE J1850 (VPW) Protocol Solution for Diagno...Implementation and Validation of SAE J1850 (VPW) Protocol Solution for Diagno...
Implementation and Validation of SAE J1850 (VPW) Protocol Solution for Diagno...IRJET Journal
 
Curtiss-Wright Controls Avionics & Electronics Corporate Overview
Curtiss-Wright Controls Avionics & Electronics Corporate OverviewCurtiss-Wright Controls Avionics & Electronics Corporate Overview
Curtiss-Wright Controls Avionics & Electronics Corporate OverviewCurtiss-Wright Defense Solutions
 

What's hot (20)

TDA18204HN_SDS
TDA18204HN_SDSTDA18204HN_SDS
TDA18204HN_SDS
 
PLC
PLCPLC
PLC
 
JESD204B Survival Guide: Practical JESD204B Technical Information, Tips, and ...
JESD204B Survival Guide: Practical JESD204B Technical Information, Tips, and ...JESD204B Survival Guide: Practical JESD204B Technical Information, Tips, and ...
JESD204B Survival Guide: Practical JESD204B Technical Information, Tips, and ...
 
Foundation fieldbus
Foundation fieldbusFoundation fieldbus
Foundation fieldbus
 
In Building Solution
In Building SolutionIn Building Solution
In Building Solution
 
Low Power Design flow using Power Format
Low Power Design flow using Power FormatLow Power Design flow using Power Format
Low Power Design flow using Power Format
 
Configuração modbus yokogawa
Configuração modbus yokogawaConfiguração modbus yokogawa
Configuração modbus yokogawa
 
ETHERNET PACKET PROCESSOR FOR SOC APPLICATION
ETHERNET PACKET PROCESSOR FOR SOC APPLICATIONETHERNET PACKET PROCESSOR FOR SOC APPLICATION
ETHERNET PACKET PROCESSOR FOR SOC APPLICATION
 
Ppt devicenet
Ppt devicenetPpt devicenet
Ppt devicenet
 
Novel fpga design and implementation of digital up
Novel fpga design and implementation of digital upNovel fpga design and implementation of digital up
Novel fpga design and implementation of digital up
 
AREA EFFICIENT 3.3GHZ PHASE LOCKED LOOP WITH FOUR MULTIPLE OUTPUT USING 45NM ...
AREA EFFICIENT 3.3GHZ PHASE LOCKED LOOP WITH FOUR MULTIPLE OUTPUT USING 45NM ...AREA EFFICIENT 3.3GHZ PHASE LOCKED LOOP WITH FOUR MULTIPLE OUTPUT USING 45NM ...
AREA EFFICIENT 3.3GHZ PHASE LOCKED LOOP WITH FOUR MULTIPLE OUTPUT USING 45NM ...
 
Nathaniel weathers resume linkedin
Nathaniel weathers resume linkedinNathaniel weathers resume linkedin
Nathaniel weathers resume linkedin
 
DeltaV Virtualization
DeltaV VirtualizationDeltaV Virtualization
DeltaV Virtualization
 
CDR2(Sajjad Tarahomi)
CDR2(Sajjad Tarahomi)CDR2(Sajjad Tarahomi)
CDR2(Sajjad Tarahomi)
 
Pactron , Hardware, Board level & Manufacturing solutions
Pactron , Hardware, Board level & Manufacturing solutions Pactron , Hardware, Board level & Manufacturing solutions
Pactron , Hardware, Board level & Manufacturing solutions
 
Architecture of a novel configurable
Architecture of a novel configurableArchitecture of a novel configurable
Architecture of a novel configurable
 
Demystifying LTE Performance Management and Optimization
Demystifying LTE Performance Management and OptimizationDemystifying LTE Performance Management and Optimization
Demystifying LTE Performance Management and Optimization
 
DeltaV Electronic Marshalling
DeltaV Electronic MarshallingDeltaV Electronic Marshalling
DeltaV Electronic Marshalling
 
Implementation and Validation of SAE J1850 (VPW) Protocol Solution for Diagno...
Implementation and Validation of SAE J1850 (VPW) Protocol Solution for Diagno...Implementation and Validation of SAE J1850 (VPW) Protocol Solution for Diagno...
Implementation and Validation of SAE J1850 (VPW) Protocol Solution for Diagno...
 
Curtiss-Wright Controls Avionics & Electronics Corporate Overview
Curtiss-Wright Controls Avionics & Electronics Corporate OverviewCurtiss-Wright Controls Avionics & Electronics Corporate Overview
Curtiss-Wright Controls Avionics & Electronics Corporate Overview
 

Similar to gsmackay-en3602-project

LORA BASED DATA ACQUISITION SYSTEM
LORA BASED DATA ACQUISITION SYSTEMLORA BASED DATA ACQUISITION SYSTEM
LORA BASED DATA ACQUISITION SYSTEMIRJET Journal
 
Chandan Kumar_3+_Years _EXP
Chandan Kumar_3+_Years _EXPChandan Kumar_3+_Years _EXP
Chandan Kumar_3+_Years _EXPChandan kumar
 
IRJET- Power Line Carrier Communication
IRJET- Power Line Carrier CommunicationIRJET- Power Line Carrier Communication
IRJET- Power Line Carrier CommunicationIRJET Journal
 
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULEWIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULEEng.Manfred Kibona
 
IRJET- CAN based Data Acquisition and Data Logging System for Vehicular Commu...
IRJET- CAN based Data Acquisition and Data Logging System for Vehicular Commu...IRJET- CAN based Data Acquisition and Data Logging System for Vehicular Commu...
IRJET- CAN based Data Acquisition and Data Logging System for Vehicular Commu...IRJET Journal
 
SandeepKumar _Resume
SandeepKumar _ResumeSandeepKumar _Resume
SandeepKumar _ResumeSandeep Kumar
 
IRJET- Dynamic Adaption of DCF and PCF Mode of IEEE 802.11 WLAN
IRJET-  	  Dynamic Adaption of DCF and PCF Mode of IEEE 802.11 WLANIRJET-  	  Dynamic Adaption of DCF and PCF Mode of IEEE 802.11 WLAN
IRJET- Dynamic Adaption of DCF and PCF Mode of IEEE 802.11 WLANIRJET Journal
 
Electrical Rule Check Verification Methodology For SoC
Electrical Rule Check Verification Methodology For SoCElectrical Rule Check Verification Methodology For SoC
Electrical Rule Check Verification Methodology For SoCIRJET Journal
 
IRJET- Password based Circuit Breaker using DTMF
IRJET-  	  Password based Circuit Breaker using DTMFIRJET-  	  Password based Circuit Breaker using DTMF
IRJET- Password based Circuit Breaker using DTMFIRJET Journal
 
IRJET- Monitoring and Protection of Distribution Transformer using GSM Module
IRJET- Monitoring and Protection of Distribution Transformer using GSM ModuleIRJET- Monitoring and Protection of Distribution Transformer using GSM Module
IRJET- Monitoring and Protection of Distribution Transformer using GSM ModuleIRJET Journal
 
IRJET- An Analysis of CMOS based Low Power 2:4 Decoder at 32nm Node using LEC...
IRJET- An Analysis of CMOS based Low Power 2:4 Decoder at 32nm Node using LEC...IRJET- An Analysis of CMOS based Low Power 2:4 Decoder at 32nm Node using LEC...
IRJET- An Analysis of CMOS based Low Power 2:4 Decoder at 32nm Node using LEC...IRJET Journal
 
IRJET - Monitoring and Protection of Distribution Transformer using GSM Module
IRJET - Monitoring and Protection of Distribution Transformer using GSM ModuleIRJET - Monitoring and Protection of Distribution Transformer using GSM Module
IRJET - Monitoring and Protection of Distribution Transformer using GSM ModuleIRJET Journal
 
Secure remote protocol for fpga reconfiguration
Secure remote protocol for fpga reconfigurationSecure remote protocol for fpga reconfiguration
Secure remote protocol for fpga reconfigurationeSAT Journals
 
Secure remote protocol for fpga reconfiguration
Secure remote protocol for fpga reconfigurationSecure remote protocol for fpga reconfiguration
Secure remote protocol for fpga reconfigurationeSAT Publishing House
 
final project report_full edit
final project report_full editfinal project report_full edit
final project report_full editSayam Roy
 
Implementation of CAN on FPGA for Security Evaluation Purpose
Implementation of CAN on FPGA for Security Evaluation PurposeImplementation of CAN on FPGA for Security Evaluation Purpose
Implementation of CAN on FPGA for Security Evaluation PurposeIRJET Journal
 
Signal Classification and Identification for Cognitive Radio
Signal Classification and Identification for Cognitive RadioSignal Classification and Identification for Cognitive Radio
Signal Classification and Identification for Cognitive RadioIRJET Journal
 
intelligent braking system report
intelligent braking system reportintelligent braking system report
intelligent braking system reportSumit Kumar
 

Similar to gsmackay-en3602-project (20)

LORA BASED DATA ACQUISITION SYSTEM
LORA BASED DATA ACQUISITION SYSTEMLORA BASED DATA ACQUISITION SYSTEM
LORA BASED DATA ACQUISITION SYSTEM
 
Chandan Kumar_3+_Years _EXP
Chandan Kumar_3+_Years _EXPChandan Kumar_3+_Years _EXP
Chandan Kumar_3+_Years _EXP
 
IRJET- Power Line Carrier Communication
IRJET- Power Line Carrier CommunicationIRJET- Power Line Carrier Communication
IRJET- Power Line Carrier Communication
 
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULEWIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
 
IRJET- CAN based Data Acquisition and Data Logging System for Vehicular Commu...
IRJET- CAN based Data Acquisition and Data Logging System for Vehicular Commu...IRJET- CAN based Data Acquisition and Data Logging System for Vehicular Commu...
IRJET- CAN based Data Acquisition and Data Logging System for Vehicular Commu...
 
SandeepKumar _Resume
SandeepKumar _ResumeSandeepKumar _Resume
SandeepKumar _Resume
 
IRJET- Dynamic Adaption of DCF and PCF Mode of IEEE 802.11 WLAN
IRJET-  	  Dynamic Adaption of DCF and PCF Mode of IEEE 802.11 WLANIRJET-  	  Dynamic Adaption of DCF and PCF Mode of IEEE 802.11 WLAN
IRJET- Dynamic Adaption of DCF and PCF Mode of IEEE 802.11 WLAN
 
Electrical Rule Check Verification Methodology For SoC
Electrical Rule Check Verification Methodology For SoCElectrical Rule Check Verification Methodology For SoC
Electrical Rule Check Verification Methodology For SoC
 
IRJET- Password based Circuit Breaker using DTMF
IRJET-  	  Password based Circuit Breaker using DTMFIRJET-  	  Password based Circuit Breaker using DTMF
IRJET- Password based Circuit Breaker using DTMF
 
Acr5 dcb
Acr5 dcbAcr5 dcb
Acr5 dcb
 
IRJET- Monitoring and Protection of Distribution Transformer using GSM Module
IRJET- Monitoring and Protection of Distribution Transformer using GSM ModuleIRJET- Monitoring and Protection of Distribution Transformer using GSM Module
IRJET- Monitoring and Protection of Distribution Transformer using GSM Module
 
IRJET- An Analysis of CMOS based Low Power 2:4 Decoder at 32nm Node using LEC...
IRJET- An Analysis of CMOS based Low Power 2:4 Decoder at 32nm Node using LEC...IRJET- An Analysis of CMOS based Low Power 2:4 Decoder at 32nm Node using LEC...
IRJET- An Analysis of CMOS based Low Power 2:4 Decoder at 32nm Node using LEC...
 
IRJET - Monitoring and Protection of Distribution Transformer using GSM Module
IRJET - Monitoring and Protection of Distribution Transformer using GSM ModuleIRJET - Monitoring and Protection of Distribution Transformer using GSM Module
IRJET - Monitoring and Protection of Distribution Transformer using GSM Module
 
Secure remote protocol for fpga reconfiguration
Secure remote protocol for fpga reconfigurationSecure remote protocol for fpga reconfiguration
Secure remote protocol for fpga reconfiguration
 
Secure remote protocol for fpga reconfiguration
Secure remote protocol for fpga reconfigurationSecure remote protocol for fpga reconfiguration
Secure remote protocol for fpga reconfiguration
 
final project report_full edit
final project report_full editfinal project report_full edit
final project report_full edit
 
Implementation of CAN on FPGA for Security Evaluation Purpose
Implementation of CAN on FPGA for Security Evaluation PurposeImplementation of CAN on FPGA for Security Evaluation Purpose
Implementation of CAN on FPGA for Security Evaluation Purpose
 
Signal Classification and Identification for Cognitive Radio
Signal Classification and Identification for Cognitive RadioSignal Classification and Identification for Cognitive Radio
Signal Classification and Identification for Cognitive Radio
 
Af24220226
Af24220226Af24220226
Af24220226
 
intelligent braking system report
intelligent braking system reportintelligent braking system report
intelligent braking system report
 

gsmackay-en3602-project

  • 1. i The Robert Gordon University, Aberdeen School of Engineering BSc(Eng) in Electronics & Electrical Engineering Remote Serially Addressable Actuator G S Mackay 0708738 April 2009
  • 2. ii Remote Serially Addressable Actuator Gerard Steven Mackay April 2009 This report is submitted in partial fulfilment of the requirements for the degree of BSc(Eng) in Electronics and Electrical Engineering at The Robert Gordon University, Aberdeen
  • 3. iii I declare that this report, except where otherwise stated, is based on my own work. To the best of my knowledge and belief, this report contains no material previously published or written by another person, except where due reference has been made. Signed:……………………………………….. Date:……………………………
  • 4. iv Abstract The project of developing a Serially Addressable Actuator for operation over a long-haul two-wire transmission-line (10K-25K Ft) is being pursued to investigate the feasibility of direct communication with sensors and actuators in remote locations, from a local computer, without the need for an intermediary ‘smart-hub’. A ‘smart-hub’ can be a relatively complex device incorporating CPU-based telemetry systems and its complexity may become the ‘weak-link’ with respect to reliability in hostile environments that are exposed to temperature and vibration extremes. The Actuating-Device is to be developed on minimal hardware for maximum reliability and compactness of design (minimum cost being an associated benefit). The PICKit1 Flash Programmer Starter Kit forms the hardware basis of the project. The project involves development of suitable line-code and firmware to operate the communication link over a simulated transmission-line and to test and assess functionality by transferring data between a transmission and reception device. Progress has been documented by photographic screen-capture of scope-signals. Initial progress has been encouraging, having established a prototype that has demonstrated functional 9600 bps communication over a simulated 10K – 20Kft line. There are some clear and specific limitations in the design, but they have been given due consideration, are well understood, and specific remedial work and a more thorough testing regime have been proposed.
  • 5. i Acknowledgements I would like to thank my Project Supervisor, Mr. Graeme Dunbar in the School of Engineering for his guidance, advice and consideration.
  • 6. ii Table Of Contents Page Number 1.0 Introduction 1 1.1 Background 1 1.2 Objectives 1 2.0 Technical analysis and Formulation of Solution 3 2.1 Basic Elements of the System 3 2.2 Consideration of Control-Station Signal-Source 3 2.3 Consideration of Transmission Medium and Signal 4 2.4 Consideration of Line-Signal Encoder/Transmitter 5 2.5 Consideration of Line-Signal Receiver/Decoder 6 2.6 Selection of Development Hardware 7 3.0 Design & Working Solution 8 3.1 Speed Limitation of the Receiving Hardware 8 3.2 Generating Line-Code in a Continuous Loop 10 3.3 Implementation of Line-Code Generator 13 3.4 Hardware Reconfiguration to Develop Receiver Code 15 3.5 Developing Receiver Code- Analysing Sync Detection 17
  • 7. iii 3.6 Developing Receiver Code- Sync Recovery 19 4.0 Testing and Evaluation 26 4.1 Reviewing Results- Data-Recovery and Addressability 26 4.2 Project Appraisal 29 5.0 Future Development 31 5.1 Performance Enhancement of Existing Hardware via Firmware 31 5.2 Performance Enhancement through Hardware 31 5.3 Further Testing 32 6.0 A Brief Note in Conclusion 33 7.0 References 34 8.0 Bibliography 35 Appendix-1 TX-PIC Program Listing 36 Appendix-2 Short, Medium and Long Line Scope Signals 43 Appendix-3 RX-PIC Program Listing 46
  • 8. iv List of Figures Page Number Figure-1 Opto-Coupler 4 Figure-2 Line-Code 6 Figure-3 Hardware 14 Figure-4 TXER Test Schematic 14 Figure-5 Line-Code Scope Capture 16 Figure-6 RXER PIC Hardware Reconfiguration 17 Figure-7 Short-Line Sync Detection Pulses 20 Figure-8 Medium-Line Sync Detection Pulses 21 Figure-9 Long-Line Sync Detection Pulses 21 Figure-10 Idealised Line-Code Diagram 22 Figure-11 Data Recovery Routine 24 Figure-12 Recovered Serial Data 26 Figure-13 Short Line Data Recovery 27 Figure-14 Long Line Data Recovery 27
  • 9. 1 1.0 Introduction 1.1 Background Control of actuators (electrical, electro-hydraulic or electro-mechanical) in remote sub-sea completions or down-hole equipment is often achieved by communicating with a ‘smart’ hub (usually a CPU based device located in the remote location, like Kvaerner’s Sub-sea Distribution Unit, for example) over a dedicated telemetry link or MODEM. CPU based devices tend to be realized on relatively complex PCB’s, the reliability of which can be severely compromised by the adverse conditions (temperature and vibration extremes) often associated with sub-sea well-head and down-hole operating environments. Communicating directly with the simpler (‘dumber’) devices normally connected below the ‘smart hub’ could offer greater reliability-  minimal component count with fewer inter-connections translates into physically more rugged and compact (and relatively inexpensive) hard-ware  simple, rugged, compact and relatively inexpensive hard-ware units can be easily ganged together (in duplicate) to build redundancy into a specific function 1.2Objectives Investigate the feasibility of direct-communication with simple working-end devices, such as actuators, over an extended transmission-line utilising minimal peripheral/additional hardware. The investigation will be conducted as follows- 1 Implementation of a simple electronic actuator to be located remotely from its control station and operated over a two-wire electrical connection 2 To make the actuator addressable to enable multiple identical devices to be operated (for redundancy and/or multiple alternate actuations) over a single two-wire communication link.
  • 10. 2 3 To implement a suitable serial line-code for transmission of the device-address in a format that produces an easily recoverable signal at the remote-end of a simulated transmission-line (using a commercial line-simulator). 4 To use an oscilloscope to document and assess signal-quality at the remote end and to determine a broadly suitable line-termination resistance and assess its effect on signal-quality. 5 To implement the design on minimal hardware to minimise cost and maximise physical reliability and compactness. 6 To appraise the results of the project objectively, highlighting limitations, assessing practical viability and identifying areas for further investigation and development going forward.
  • 11. 3 2.0 Technical analysis and Formulation of Solution 2.1 Basic Elements of the System There are four basic hardware elements to the proposed system-  Control-Station/Signal-Source  Local encoder/transmitter  Transmission medium  Remote receiver/decoder There is one basic hardware element to the project in general- selection of appropriate transmission and reception hardware to meet the following criteria-  Minimal component count to maximise compactness and reliability (as stated in the project objectives)  Versatility of hardware configuration for ease of reconfiguration as development progresses  Hardware complexity suited to the experience-level of the developer 2.2 Consideration of Control-Station Signal-Source Personal Computers (PC’s) are widely available in the modern workplace and are an obvious and practical choice as a work-station for generating control signals. The RS232 9-Pin Serial-Port is a simple computer I/O-Interface, available as part of the standard PC hard-ware or as an ‘add-on’ through a USB-RS232 Dongle. The port can be operated as a two-wire (one-way) or three-wire (two-way) connection and is accessible to the user through terminal-emulators such as AccessPort-1.8 (which can be down-loaded from the internet, free of charge). Digital logic-states in RS232 are represented serially in dual-polarity voltage- windows within successive fixed-period time-slots, or ‘bit-periods’, (*Tompkins&Webster 6.5 p175, 6.3 p165) and are easily converted to single- ended 5v logic as per figure-1 below (*pin-out from OPI1264 Data-Sheet).
  • 12. 4 The RS232-port can be configured from the AccessPort tool-bar. To simplify the initial development process the Parity-bit will not be used and only one stop-bit will be used (though this effectively ‘legalises’ any number of actual stop-bits). The required number of data-bits per character and baud-rate will become clear after consideration of the performance limits of the transmission and reception hardware. 2.3 Consideration of Transmission Medium and Signal The transmission-medium being utilized ultimately determines the nature of the transmission signals and terminating-hardware appropriate for the system. An electrical-wire medium can be adversely affected by localised sources of electrical noise and interference, but it offers the following advantages over RF and optical-fibre-  Mechanically rugged- umbilical connections may be load-bearing  Ease of connection to, and termination of, the medium at either end  Suitable for subterranean or submarine applications  Steady-State Power can be carried on transient-signal lines The electrically reactive properties of a wire transmission-line become increasingly significant with length and signal-frequency (*Tompkins&Webster section 6.5). For a given line-length, signal attenuation will increase with frequency. Raw RS232 serial-data contains a range of frequency components at the bit-level, from consecutive logic ‘ones’ or ‘zeros’ at the high-end, to alternating logic ‘ones’ and ‘zeros’ at the low-end. A range of signal frequencies translates into a range of signal attenuations, producing inconsistent signal amplitudes and compounding
  • 13. 5 threshold-based data recovery. Furthermore, frequency-attenuation at edge- transitions manifest as slewing that obscures bit-boundary definition and hence, compounds bit-level recovery within the correct time-frame. This project proceeds using a commercial line-simulator (from General Electric Energy Systems Ltd) which simulates short, medium and long (switch-selectable) lines of ~0.25” armoured mono-conductor cable- broadly representing line-lengths up to 15KFt, 20KFt and 25KFt respectively. 2.4 Consideration of Line-Signal Encoder/Transmitter As outlined above, signal-level based communication becomes increasingly impractical for transmission of serial-data over an extended wire-connection as bit- rate increases. A low-speed system may well suffice for a limited number of remote addressable actuators- but a higher speed system with higher bandwidth could be more versatile, supporting an extended array of actuators to a finer degree of timing-precision and potentially handling more complex transfers, such as sending adjustment parameters to variable-output actuators and receiving responses like acknowledgements, alarms or even sensor-data. In short, the more versatile the system, the more practically viable it becomes- but this requires greater bandwidth and this translates into higher bit-rate. Self-Clocking line-encoding techniques use edge-transition polarity to preserve the logic-state and time-frame integrity of a digital-signal, even when the edge- transitions are slewed. In this system, the direction of the edge-transition in the middle of a bit-period (rising/slope-up or falling/slope-down) corresponds to a distinct bit-state (eg. logic-1 or logic-0). This requires a digital level-transition within every bit-period and produces a line-signal frequency which is at least double that of the RS232 equivalent. This higher frequency signal will suffer greater attenuation over a given transmission-line, but the critical point here is that its logic-state and time-frame information are preserved. Converting an RS232 bit-level to an edge-transition is straight-forward- the bit- level can be ‘flipped-over’ half-way through the bit-period.
  • 14. 6 However, in a series of consecutive ‘ones’ or ‘zeros’ edge-transitions are produced on the boundary between the end of the previous bit-period and the start of the subsequent bit-period. A distinction must be made to determine which edges are in the middle of the bit-period (representing logic-states) and which edges are boundary transitions. This can be done by placing a synchronising bit at the start of the serial-byte. The sync or start-bit can be made distinct from the data-bits by making it assume a logic-state (complementary to the idle state) for a full bit- period. Bit-period boundaries are then clearly defined at regular bit-period intervals from the lagging-edge of the sync-bit. By default, an ‘end’ or stop-bit becomes defined by the persistence of the idle-state for a full bit-period, as per the summary in figure-2 below. Note that alternating logic-states (eg. 1010) will produce an alternating sync-stop pattern. A finer definition of sync incorporates a preceding idle-state, where the idle-state is defined (as distinct form a stop-bit) where it persists for a duration exceeding one full bit-period. This project proceeds on the basis of a self-clocking line-code with first-half bit- period logic-1-hi and logic-0-lo line-driving states, as outlined in figure-2. 2.5 Consideration of Line-Signal Receiver/Decoder The line-code outlined above will charge the transmission-line during active-hi periods and discharge the line during idle-lo periods, producing a net positive offset on a capacitive-line due to the initial full bit-period ‘charge-cycle’ associated with the sync-bit. The resulting signal-amplitude presented to the receiver will depend on the bit-rate and current-driving properties of the transmitter, the length and characteristic-impedance of the line, and the terminating impedance of the receiver. A receiver that continually monitors the line-signal will be able to
  • 15. 7 determine (‘resolve’) the direction of the edge-transitions within a self-clocking line- code as long as it satisfies the following criteria-  Receiver sampling-frequency must be greater than twice that of the maximum frequency-component contained within the incoming signal (to avoid aliasing- Nyquist/Shannon)  The maximum and minimum absolute signal-amplitudes must not exceed the range of the receiver/converter to avoid signal-clipping  The smallest valid localised peak-to-peak amplitude difference within the incoming signal must be considerably greater than the resolution of the receiver-converter, to avoid conversion uncertainty at the LSB(s) level from obscuring signal subtleties 2.6 Selection of Development Hardware The fundamental project hardware criteria (outlined previously) of minimal component-count and versatility of configuration can be met by developing the required hardware functionality on a PIC Microcontroller. PIC’s are low-cost and physically compact with minimal pin-out and may contain a versatile range of onboard resources such as comparators, counter-timers, ADC’s, relatively high- current sink/source I/O (typically 25mA) and internal clocking. PIC’s are also available in ‘Starter Kits’ for inexperienced developers, and as is the case in this project, a Starter-Kit meets the previously stipulated criteria of selecting hardware suited to the experience level of the developer. In this project hardware development proceeds with the PICKit-1 Flash Starter Kit from Microchip, which utilises a PIC12F675 containing all the onboard resources outlined above, and using the devices onboard 4MHz clock.
  • 16. 8 3.0 Design & Working Solution 3.1 Speed Limitation of the Receiving Hardware The PIC12F675 can execute an instruction every micro-second when utilising the onboard 4MHz clock (Data-Sheet section-1). Setting and clearing an output-port to generate line-pulses can be accomplished in two instructions to achieve a maximum ‘self-clocking’ line-code of 500K bps. This is considerably faster than the bit-rates supported by the RS232-Interface (AccessPort-1.8 supports 256000 maximum bps). Therefore, bit-transmission does not impose a throughput-limit on system speed. However, the ability of the PIC to effectively drive an ‘end-useable’ signal over a transmission-line by itself does, ultimately, impose a speed-limitation- but this is not considered here because the overriding speed-limitation is imposed by the receiver. The primary speed-limitation in the system is the sampling-rate of the receiver. In order to detect a valid sync-bit when it appears on the line, the receiver monitors the line continuously, comparing consecutive samples to identify an increasing signal trend that’s indicative of an incoming (slewed but rising) leading-edge. The PIC12F675 ADC can do a 10-bit conversion in 22us (11TAD, where TAD = 2us with maximum ‘legal’ internal A2D clock-selection- Data-Sheet section-7.1.4). In addition to doing the conversion, a ‘continuous monitor-cycle’ must also compare the current-conversion to the previous-conversion to assess the signal trend. This process requires the following steps- 1 Pull the current-conversion into the working-register 2 Subtract the current-conversion value from the previous-conversion value 3 Store the current-conversion as the legacy-conversion for the next cycle 4 Comparison- did the above subtraction set the status-register carry-bit? If ‘carry-clear’ then current-conversion is bigger than previous-conversion so proceed to the next cycle, otherwise go back to the first trend-detection cycle
  • 17. 9 Each of the listed steps takes a 1us instruction-cycle, except step-4, which takes two cycles because steps that change the program-counter, like conditional- branches, consume an additional instruction cycle (Data-Sheet section 10.0). This brings the best-case sample-to-sample monitor-cycle to 27us in length. Even if the sample-processing steps are performed simultaneously while the ADC is converting (22us of available space), the requisite conditional-branch on ‘conversion-done’ (+2us) to save the conversion (+1us) and start the next conversion (+1us) would incur a 4us overhead, bringing the best possible monitor cycle-time to 26us. 19200 bps RS232 has a bit-period of 52us, twice the frequency of the best- possible ‘sample-cycle’ available from the hardware configuration. This does not quite satisfy Nyquist/Shannon. Therefore the next fastest available RS232 speed of 9600 bps will be used. Since the PIC12F675 is an 8-bit device, the project will proceed on the basis of generating and decoding line-code (as previously outlined) based on 8-bit, 9600 bps RS232. Another speed-limitation of the ADC, inherent to its sample-and hold design, is the Acquisition Time. Paraphrasing Tompkins & Webster and the PIC Data-Sheet: “The sample-and-hold capacitor must have time to charge to the level of the input signal and track it within a specified error-band (Tompkins/Webster 5.1 p146) in order for the ADC to meet its specified accuracy (Datasheet 7.2 p45)“ The PIC Data-Sheet goes on to calculate the Acquisition-Time at just under 20us at an operating temperature of 50C and a maximum recommended source- impedance of 10K. Source impedance (Rs) is fundamental to Acquisition-Time. Reducing Rs reduces Acquisition-Time. With PIC-I/O source-impedance of 200 Ohms (25mA @ 5v, Datasheet 12.0 p81), typical line-resistance of 100 Ohms and typical RX termination-resistance of 200 Ohms (Tompkins/Webster 6.5 p170), the Thevenin-equivalent source-impedance becomes 120 Ohms and Acquisition-Time comes down to less than 11us (Tacq = 3.25us + (9.15E-10)(8K + Rs)us @ 50C).
  • 18. 10 Acquisition-Time is part of the ADC Sample-Cycle which occupies the period between the end of the previous-conversion and the start of the subsequent- conversion. This period is determined by the RX-PIC sampling-cycle code. The sampling period will be discussed further during overview and of the RX-PIC sampling-code. One final limiting-factor arising from the ADC is absolutely fundamental to line- code generation in this system. The PIC12F675 ADC is not bipolar and can only handle signals in the range 0v to +5v. The consequence of this is that the line- code drive-current must ‘source-from’ and ‘sink-back’ to the same I/O-line with respect to a common 0v-line (as opposed to driving two I/O-lines onto the two transmission-wires, as a ‘voltage-doubling’ complementary-pair). There is an important caveat to this point, but it will not be discussed here, having been seconded to the design appraisal discussion instead. 3.2 Generating Line-Code in a Continuous Loop For the purposes of developing the receiver algorithm and analysing results in general, it is useful to have a known bit-pattern line-coded and transmitted in a continuous loop from a TX-PIC at one end of the line-simulator. A fixed pattern enables stable and consistent oscilloscope triggering in order to closely examine the effects of the line on the arriving signal and to directly compare received waveforms to outputs from test-points on an RX-PIC (displayed on a second scope-channel). A full listing of the ‘looping’ line-driving assembly-code is contained in Appendix-1. The fine-detail of the code-functionality is contained within the embedded comments in the program and a general overview of the program follows here: The program utilises the General-Purpose I/O-register (GPIO) to output high and low line-driving output-states under the direction of a series of nested sub-routines. The lowest-level (basement) sub-routine is ‘wait-period’ which comprises of a very crude delay-loop (2 instructions + branch = 3us) which loops ‘waitcount’ (11)
  • 19. 11 times. The loop-branch is skipped on the final loop, shortening the final loop by 1us, so a time-padding null operation (1us) is added to simplify the total loop-time calculation to ‘waitcount x 3us’. The total time consumed by ‘wait-period’ includes an additional two instructions (2us) to load the ‘count’ register and the subroutine ‘call & return overhead’ of 4us (2us outbound, 2us return). Hence, the total wait- period, all-in, is 39us (11 x 3 + 2 + 2 + 2us). Residing one step up from the basement in the nesting hierarchy are the output sub-routines ‘hi_out’ and ‘lo_out’. These sub-routines set GPIO bit-4 output high or low respectively to drive the line-signal accordingly. The ‘load’ and ‘present’ instructions (2 instructions, 2us) at the start of each output routine produce 2us of ‘output-latency’ between the routine starting and the output actually changing. ‘Latency terms’ will become important in the subsequent discussion. Nested at the top of the subroutine hierarchy are the bit-routines, ‘start’, ‘one’, ‘zero’ and ‘stop’. These routines call the ‘hi’ and ‘lo’ output-routines to generate the appropriate bit-period line codes (hi-hi, hi-lo, lo-hi and lo-lo respectively). In the first half of a bit-period, the ‘outbound’ leg of the nested call loop to the bit- subroutine produces 2us of ‘initial-call-latency’ and the subsequent call to the output-subroutine produces another 2us of ‘output-call-latency’. Returning from the output-routine to the bit-routine produces 2us of ‘output-call-return-latency’. The total period of the output-state in the first-half of a bit-period is the sum of the wait-period (39us), output-call-return-latency (2us), and output-call-latency plus output-latency (2us + 2us) from the next half-bit-period. This generates a half-bit- period output of 45us which is then padded-out to 52us by seven null-operations in the first-half of the bit-routine (one half-bit-period is 52us at 9600 bps). The second half-bit-period includes two additional latencies- ‘bit-call-return- latency’ (2us) and ‘initial-call-latency’ (2us) from the next bit-period, producing 4us of extra latency in total. For this reason the second-half of the bit-routine only requires three null-operations to pad-out the output time-period to 52us. The above discussion is complex and is summarised in pseudo-code below for clarification:
  • 20. 12 Instruction Latency Call bit-routine 2us initial-call Call output-routine 2us output-call Load & present o/p 2us output (output now in new state at start of output half-bit-period) Wait 39us Return to bit-routine 2us output-call-return Null operations (7) 7us Call next output-routine 2us output-call Load & present o/p 2us output (output now in new state after 39 + 2 + 7 + 2 + 2 = 52us) Wait 39us Return to bit-routine 2us output-call-return Null operations (3) 3us Return from bit-routine 2us bit-call-return Call next bit-routine 2us initial-call Call output-routine 2us output-call Load & present o/p 2us output (output now in new state after another 39 + 2 + 3 + 2 + 2 + 2 + 2 = 52us) And so on… There is no subsequent bit-routine-call to terminate the end of the stop-bit after 52us but this is of no consequence because the stop-bit output-state is the same as the idle output-state in this line-code. Similarly, a loop-instruction (to continually loop a fixed bit-pattern) placed after the stop-bit on the last byte of a looping-string is inconsequential in respect of line-code functionality. Clearly system-timing is fundamental, and to this end the PIC12F675 internal clock is factory calibrated within 1% (Data-Sheet section-1, P1) with the correction-value stored in memory and loaded into the oscillator-calibration register (OSCAL) on program-initialisation (the PICKit1 development-board and Flash Programmer utility provide an option to regenerate the oscillator calibration if required).
  • 21. 13 Additionally, null-operator (nop) time-padding within the TX-PIC bit-call- subroutines provide scope for ‘fine-tweaking’ the output-waveform time-frame. The TX-PIC program is inefficient and clumsy in its use of code, but the top-tier bit- call routines are easily edited to generate any looping line-code bit-pattern as required, to facilitate closer inspection of signals by oscilloscope. 3.3 Implementation of Line-Code Generator The PICKit1 development-board and associated Flash-Programming Utility facilitate ‘in-circuit’ programming and testing of functionality. Only three additional items of hardware are required at this stage of development-  Commercial Line-Simulator  Line-Termination Resistor (RS Resistance Decade Box)  Oscilloscope The hardware is illustrated in figure-3 (connected as per schematic in figure-4 below) with 200 Ohm termination-resistance selected and the resulting line- attenuated signal (continuously looping bit-pattern) displayed on the scope:
  • 22. 14 The TX-PIC code contains routines to continually loop consecutive line-code ones, zeros and alternating start-stop bit-patterns (to verify timing of output transitions), as well as looping the line-code byte-pattern (00h-ffh-AAh-C3h) displayed on the scope in figure-3.
  • 23. 15 Requisite bit-pattern subroutine-selection is made by ‘un-commenting’ the required routine into the active code and ‘commenting-out’ redundant routines using the in- circuit-programming and Flash-Programmer Utility. This is not eloquent or efficient but it is a workable enough solution for this stage of development, so that precious project-time can be focussed on developing, testing and evaluating the more complex and technically challenging RX-PIC code. 3.4 Hardware Reconfiguration to Develop Receiver Code Testing of the TX-PIC through the line-simulator with a range of termination resistances (from 50 to 500 Ohms) indicates that termination-resistance primarily affects signal-amplitude in this particular configuration, with no sign whatsoever of any signal distortion associated with reflections. A transmission-line should produce reflections unless properly terminated with a pure-resistance equivalent to its characteristic-impedance (*Tompkins&Webster 6.5 p170). However, the line- simulator only simulates the properties of resistance and capacitance, neglecting inductance, and this is the most likely explanation for the signal purity apparent on the scope (medium-line setting with 200 Ohm termination) illustrated on figure-5 below.
  • 24. 16 Further scope-capture signals for all three line-simulator settings (long, medium and short) with 200 Ohm termination-resistance are presented on Appendix-2. The 200 Ohm termination-resistance is a reasonable value to use ‘in practice’ (*Tompkins&Webster 6.5 p170) and clearly produces a signal-amplitude (in conjunction with the medium-line setting) that is comfortably within the range of a 5v ADC. Despite its ‘cleanliness’ and purity, the resultant signal appears irregular and slewed enough to provide a good test-signal for the RX-PIC development. Idealised conditions are more forgiving in the early stages of development, and this can expedite the process of getting the fundamentals of a solution resolved initially (leaving the more practical details to a later stage, where the ongoing ‘learning-curve’ should extrapolate to a more enlightened perspective). Hence, RX-PIC development proceeds with a medium-line and 200 Ohm termination configuration. The TX-PIC is moved to the Prototype Socked and connected to an initially ‘blank’ RX-PIC in the Development/Evaluation socked as per Figure-6 below.
  • 25. 17 Note that GPIO-lines RA1 and RA2 have been designated as scope-output test- points (tp1 and tp2 respectively) for comparing the real-time line-signal on scope channel-1 to specific RX-PIC state and/or timing-signals (0-5v) presented on scope channel-2. The state/timing signals are generated by ‘progress’ or ‘state’ markers strategically embedded within the RX-PIC code for de-bugging purposes. The progress/state markers ‘bit-set’ or ‘bit-clear’ GPIO1 and GPIO2 as required. 3.5 Developing Receiver Code- Analysing Sync Detection The first part of the line-code which is transmitted to the receiver is the sync-bit. The scope-trace in figure-5 clearly depicts the prominent sync-transition at the start of each line-code byte. As discussed/proposed in section 2.5 and 3.1, a receiver routine which continually samples the incoming-signal should be able to resolve line-code transitions by comparing successive samples to determine if there is an upward or downward trend. A sync-bit is transmitted as ‘hi-out’ for a full bit-period. This condition continually charges the line for the full bit-period to create a signal at the receiver-end which trends upwards for one full bit-period. Identifying ‘sync’ then becomes the process of checking that the current-sample has greater magnitude than the previous-sample, for the number of iterations (of the process) that are expected to complete within the time-interval of the respective bit-period. Therefore, in order to detect ‘sync’ (or any other bit), it is critical to determine how many sample-and-compare cycles can be completed in 104us (1 bit-period @ 9600 bps). The proposed conversion-and-compare cycle from section 3.1 was
  • 26. 18 27us long in theory, but this didn’t take account of the 3us overhead required to branch (2us) past a ‘wait-for-conversion-complete’ loop, and then execute the instruction to start the next conversion (1us). A practical convert-and-compare cycle, as outlined below, will take 30us: 1. Start the current-conversion 2. Wait for the current-conversion to complete 3. Pull the current-conversion into the working-register 4. Subtract the current-conversion value from the previous-conversion value 5. Store the current-conversion as the legacy-conversion for the next cycle 6. Comparison- did the above subtraction set the status-register carry-bit? If ‘carry-clear’ then current-conversion is bigger than previous-conversion so proceed to the next cycle, otherwise go back to the first trend-detection cycle Running a prototype version of the above-noted code with scope-markers placed at the start and end of the cycle reveal that it actually has duration 33us. The bit-test loop which forms the ‘wait for conversion-complete’ step has a 3us overhead comprising of the bit-test itself (1us) and its loop-back (2us). The bit-test is performed on the first and then every third program-step after the ‘conversion start’ instruction (T+1, 4, 7…22 us). It appears that the ADC ‘busy-bit’ remains set for the full 22us of conversion-time and then clears on the 23rd program-step. This causes the bit-test on the 22nd program-step to force another 3us loop at T+22us. A 33us convert-compare cycle means that there is only enough room for 3 cycles in any given 104us bit-period. This means that two out of every three consecutive cycles need 2us of time-padding and the third needs 1us in order to space the sampling evenly across the bit-periods. Time-padding is achieved through null- operations (nops) or single-step instructions (like scope-output bit-setting) as required. Note that the 33us sample-compare cycle with 22us of conversion-time leaves 11us of sample-time in which to accommodate the required 10.7us of Acquisition- Time (derived in section 3.1) in order for the ADC to meet its specified accuracy. It would appear that the RX-PIC code is operating the ADC just within its limits.
  • 27. 19 Note also that all sampling is done using only the most-significant byte of the 10- bit conversion (left-justified, Datasheet 7.1 p43) in order to expedite the processing-time required to complete the sample-convert-compare cycle. This gives the ADC a resolution of 19.5mv using the internal-reference. A full-listing of the developed receiver-code is contained within Appendix-3 while the main body of the ‘Developing Receiver Code’ text is restricted to outlining the broader concepts behind the code and highlighting the main challenges that had to be overcome in the development process. 3.6 Developing Receiver Code- Sync Recovery With a ‘3-sample per bit-period’ rule established in section-3.5, sync can be identified as comprising the first three consecutive samples that are successively incremental (in amplitude), after an idle (no signal) line-state. Identifying the ‘no signal’ idle-state is achieved using the PIC onboard comparator. Comparator functionality is achieved through appropriate bit-setting of the comparator-control and voltage-reference-control registers (Datasheet section-6 p35-40). The comparator is configured to operate on the lowest (non-zero) internal-reference threshold of 208mv by selecting low-range and using voltage- reference control-nybble ‘0001’. With the low-range bit set, the Threshold is the product of the control-nybble and VDD/24 (208mv = 1 * 5v/24). The sync-detector code is implemented by cascading three of the sample-and- compare routines outlined previously, behind a continuous comparator wait-loop. The comparator wait-loop holds the program in a wait-state until the line-signal rises from the idle-state and passes through the 208mv comparator threshold. Once the threshold is crossed the program breaks-out of the wait-loop and moves on to the successive sample-and-compare routines. The rising-edge from a valid sync will generate successively bigger conversions at each compare-cycle and program flow should pass through all three cycles unhindered. A corrupt line- signal which produces a smaller conversion at one of the successive cycles will cause sync-detection to re-direct to an abort-routine. The abort-routine waits for the line-signal to return to an idle-state by using the comparator to signal when the
  • 28. 20 line is clear. Once the line is clear/idle the abort-routine re-directs program-flow back to the start of the sync-detection routine. Note that subroutine-cascading is used in the sync-detection routine (instead of repeatedly re-looping through the same subroutine three times) because it’s structurally easier to implement within the tight time-constraints of the continuously sampling code. Placing a sync-detection scope-marker (1us pulse) at the end of the sync- detection subroutine enables the routine functionality to be verified as per figures- 7, 8 and 9 below (for short, medium and long line-simulations respectively). The sync-detection pulses appear as faint-dots on the lower scope-trace, underneath the sync-bit to which they relate, at the start of each byte.
  • 29. 21 3.6 Developing Receiver Code- Data Recovery The Data-Recovery Process can be analysed by creating an idealised line-code diagram that conceptually presents the received-signal as if it were generated by a perfect current-source driving a perfectly-capacitive line, as per figure-10 below.
  • 30. 22 The idealised line-code diagram represents successive sampling-cycles horizontally, with three samples per bit-period, and the ‘hold-and-convert’ converter-transition indicated just after the start of each sampling cycle. Each marker on the ‘hold-and-convert’ transition line represents non-zero signal- magnitudes that will be derived by the ADC on completion of the conversion. (Non-zero in this context refers to a value that’s distinctly bigger than low-end random noise-floor values) Four possibilities are considered for a random arrival of sync on a continuously sampled time-line- 1. ADC-hold catches the very start of sync, just as it breaks from noise-floor 2. ADC-hold just misses the start of sync when it breaks from the noise-floor 3. Sync arrives during an ongoing noise-floor conversion 4. ADC-hold catches the first valid sync-value (very close to the noise floor) but (randomly) the preceding noise-floor conversion is marginally bigger, causing the sync-recovery routine to misinterpret it, and reject it as a random noise-floor (‘zero’) value Looking closely at the series of markers, a clear and consistent pattern emerges which forms a solid general rule (with one avoidable exception)- Taking the third sample, and every third sample thereafter (3,6, 9…) as a threshold against the average-value of the two samples that follow it, produces a result which is diagnostic of the bit-period that the samples straddle.
  • 31. 23 For example, if the first threshold (third sync sample) is bigger than the average of the two subsequent samples then the signal is trending-down in the first-half bit- period and the full bit-period is diagnosed as logic-0. If the first threshold (third sync sample) is smaller than the average of the two subsequent samples then the signal is trending-up in the first-half bit-period and the full bit-period is diagnosed as logic-1. The next sample after the second ‘diagnostic’ then becomes the threshold in the next cycle (repetitively): Threshold/ 1st -Diagnostic/ 2nd -Diagnostic/ Threshold… The exception to the rule arises where the ‘ADC-hold’ catches the very start of a random sync-arrival, just as it breaks from the noise-floor, generating a very early ‘extraneous’ sync-sample and resulting in four sync-samples over the bit-period. However, implementation of the idle-state comparator (as outlined earlier in section 3.6) will discriminate against samples close to the noise-floor, rejecting the exception-value and ensuring that the established ‘General Rule’ holds true. (ADC resolves to 20mv but comparator discriminates below 200mv) The data-processing subroutine uses the ‘General Rule’ to recover all 8-bits of data. As program flow leaves the Sync-Detection routine a bitcount parameter is initialised to 8-bits and the legacy conversion from the third sync sample is saved as the threshold for the first diagnostic comparison. A start-bit (logic-0) is sent to logic output-pin GPIO2/TP2, effectively lagging the start-bit on the input/line-side by a full bit-period. Program flow then enters the data-recovery routine and the 1st - diagnostic is acquired, then the 2nd -diagnostic is acquired, added to the 1st - diagnostic and the result shifted-right (halved) to form a diagnostic-average. The bit-count is decremented and the next threshold-conversion is started (the averaging and bit-count steps complete within a regular 35us cycle). While the next threshold is being converted the diagnostic-comparison for the previous bit is performed and the result is sent to a logic-output-pin (GPIO2/TP2) and shifted into a recovered data-byte register designated databyte. Logic outputs to databyte and TP2 lag the real-time line-code data on the input/line-side by one bit-period. This process of acquiring a threshold, diagnostic-average and shifting the result of the diagnostic-comparison into ‘databyte’ and out of TP2 proceeds (lagging the line-code by a bit-period) until all 8-bits have been recovered and shifted through.
  • 32. 24 On bitcount decrementing to zero, a final diagnostic-comparison and bit-recovery cycle is completed and then Program Flow enters the stop-routine as outlined in figure-11 below. The stop routine is virtually the same as the sync-detection routine, except that the stop routine proceeds through three successively decrementing conversions. The Stop-Routine checks databyte against address (device address mask defined at start of program) in the second-cycle and outputs an ‘activation’
  • 33. 25 flag/signal on completion of the last stop-cycle. The activation-signal will remain active until receipt of the next ‘databyte’ that does not match the address mask. The stop-routine must complete successfully in order for a stop-bit (logic-1) to be issued from TP2, otherwise a logic-0 will be issued to force a ‘frame-error’ in any connected RS232-device driven from the TP2-signal. Any inconsistencies with successive samples in the Sync-Detect or Stop-Detect routines will redirect program-flow to the Abort-Routine. Abort then issues logic-0 from TP2 and maintains a wait-loop until the next ‘line-clear’ condition on the transmission-line. TP2 then issues logic-1 (idle) and program-flow is directed to restart Sync- Detection.
  • 34. 26 4.0 Testing and Evaluation 4.1 Reviewing Results- Data-Recovery and Addressability Scoping the recovered serial-output data on TP2 and comparing it against the incoming line-code indicates that the system is working correctly with the medium- line simulation as per figure-12 below. The recovered data is illustrated on the top channel with corresponding line-code on the bottom channel and the scope triggering on the peak of the first logic-1 transition of data-byte-FFh. A recovered start-bit (lagging line code by one bit-period) corresponds to each line-code sync-transition and the subsequent data-patterns, 11111111, 10101010, 11000011, 00000000 and half of the next 11111111 are intact. Finer scrutiny of the timing (by vertical-shift of the recovered data-stream onto the mid-screen axis) confirms that the signal returns to the idle-state (or, more correctly, stop-bit/idle) at the end of the eighth data-bit bit-period.
  • 35. 27 Similar testing of the recovered data-streams in the short and long line-simulator settings are not as convincing, reference figures-13 and 14 below. Above, 10101010 has become 10101011 and 11000011 has become 110000?1. Below, 00000000 has become 10000000, note subtlety of line transition after sync The long and short line results contain steady and flickering bit-errors. Furthermore, the medium-line setting also becomes marginal if the termination- resistance is incremented or decremented to subtly alter signal amplitude.
  • 36. 28 At the time of writing the address Flag/Signal does not appear to be functioning correctly. The address-mask is FFh by default but the address-flag appears to go active after line-code 00h. This suggests some erroneous inverted-logic in the data-byte recovery and masking routine and this code requires further scrutiny. However, the successful recovery of serial-data utilising the medium-line leads me to the conclusion that the system basically works under ideal conditions.
  • 37. 29 4.2 Project Appraisal The medium-line results clearly indicate that the proposed concept of line-code generation and recovery, with the chosen hard-ware, is workable. The system is sensitive to changes in line-length and termination-resistance, which is not acceptable for a practically viable system, but these problems are most likely due to limitations in the experience and ability of the developer to make the most effective use the resources available within the PIC on which the project is based. The long-line results in particular show that subtleties within badly attenuated line- signals can be the source of errors and this is most likely due to poor utilisation of the ADC. The developed code only uses the most-significant byte of the 10-bit ADC-conversion and the resulting loss of resolution clearly has an adverse effect that’s significant at certain signal-levels. In addition to this, the line-driver only utilises half of the output voltage-swing available for driving the line (this will be discussed further below) and this compounds the issues of signal-degradation over the transmission-line. The primary limitations of the hardware itself are the speed of the PIC’s internal clock and the Acquisition and Conversion times of the ADC. The 4MHz clock limits the complexity of the recovery-algorithm that can be executed within the bit-period of the incoming signal and the ADC limits the number of samples that can be acquired over the cycle (the ADC code operates just within the ADC’s recommended Acquisition Time, as outlined in section 3.5). More samples and more processing speed would translate into more reliable operation. The mono-polar nature of the ADC has not been a limitation because all the testing has been carried-out with a capacitive-line, over which the sync-bit creates a positive offset, keeping the rest of the signal above the reference. However, it’s worth noting that over short connections the system would not be able (and would not need) to use bi-polar line-driving. One of the primary limitations of the project itself is that the effects (on the system) of induced-noise and interference have not been considered. Development of the project has proceeded using a simulated-line which produces very clean signals
  • 38. 30 with no reflections. The ‘sample-and-hold’ ADC configuration does have inherent filtering characteristics, but testing needs to be done on a real transmission-line to asses the effects of inductance and localised sources of EMI. In summary, the objective of developing a serially-addressable actuator and suitable line-code for operating it over a long-haul transmission-line utilising minimal hardware have been achieved with moderate success. The hardware is indeed minimal and basically works under ideal conditions- demonstrating the viability of the concept- and the fundamental reliability limitations that have been identified are understood, and importantly, can be addressed with more work. However, there is a lot more work to do as outlined in the following chapter.
  • 39. 31 5.0 Future Development 5.1 Performance Enhancement of Existing Hardware through Firmware There a number of ways to significantly improve the performance of the system as currently configured through better programming as outlined below- 1. The output-voltage of the line-driver can be effectively doubled by making the reference transmission-line active (push-pull) instead of passive. The hardware is currently configured to support this but the code doesn’t take advantage of it because of the mono-polar ADC in the receiver. However, as outlined in section 4.2, over a long capacitive line the sync-pulse creates a positive-offset which overcomes the mono-polar issue in a long-line configuration. 2. ADC resolution is poorly utilized- the ADC result should be shifted left one or two places, as required, when the most-significant bit(s) is/are zero, in order to improve resolution when handling smaller signals. 3. When the signal amplitude exceeds 90% of the ADC-Range (on very short lines) the code should switch to comparator-based acquisition which is faster and more efficient in respect of both the required code and the required processing-time, and would enable handling of much higher data- rates on short-connections. 4. Fix the bug in the address decoding code. 5. Better programming in general, by an experienced programmer, could significantly improve performance by utilising available resources (like the onboard timers) to control transmission and acquisition timing more precisely, rather than relying on conversion-times and instruction counts. 5.2 Performance Enhancement through Hardware The most minimal hardware improvement that could be made to the system would be to utilise an external clock such as a 20MHz crystal oscillator. Faster speed would enable development of more complex code to better utilise ADC results in the restricted time frame.
  • 40. 32 The most fundamental hardware improvement would be to replace the current PIC with one containing a faster internal clock and faster ADC to increase sampling. More samples and faster code should produce better results. 5.3 Further Testing Current testing of the system involves recovery of a looping-string of only four characters. A full character-set 00-ffh needs to be used to test the system properly. This can be done by adding code to the TX-PIC to generate a continuous series of bytes that increment sequentially through all 256 possibilities in a repeating loop. Alternatively, a PC running AccessPort-1.8 can be connected to the TX-PIC GPIO3 (utilising the opto-coupler illustrated in figure-1) to send any desired series of bytes for testing. The code to support this has already been implemented in the TX-PIC (but only tested as far as checking character-entry produces line-code on the line-monitoring oscilloscope). The RX-PIC can be connected back to a separate receiving PC (RX and TX-PIC ‘ground’ must remain isolated to prevent bypassing one side of the two-wire line simulator, hence separate TX and RX PC’s). An RS232-TX connection can be made from RX-PIC- TP2 through the anode of a small-signal diode (with its cathode connected to RS232 DB9-2 and ‘tied-lo’ to DB9-3 through a 10K resistor) and PIC-GND can be wired directly to RS232-common (DB9-5). Note that this configuration requires inverting the logic-polarity of TP2 by flipping the logic-1 and logic-0 definitions in the RX-code (because +5v in RS232 represents logic-0). This is currently planned but has not been tested yet. Assuming performance reliability can be enhanced to an acceptable level as outlined in sections 5.1, there are two fundamental tests that need to be performed at the earliest opportunity-  Testing functionality with actual transmission-lines to assess system tolerance to inductance and localised sources of electrical-noise.  Heat-testing to quantify associated clock-drift (and assess the ramifications thereof) and determine the general system tolerance to the temperature extremes of the target down-hole or well-head operating environment
  • 41. 33 6.0 A Brief Note In Conclusion This project has been technically challenging but ultimately informative and rewarding. The initial results are encouraging but the bulk of the work still remains to determine if this can lead to a practically viable device. The ultimate goal is a device that contains both the TX and RX functionality in one ‘comm-chip’ with additional DAC and ADC channels to excite and monitor a directly connected sensor. Implementation on a single chip would make it relatively easy to have ‘comm-chips’ embedded inside an array of sensors and actuators distributed over a wide geographical area, effectively moving the digitisation to the sensor rather than running sensor-signals to a digitiser over wires that can degrade signal quality.
  • 42. 34 7.0 References Willis J. Tompkins and John G. Webster, 1988, Interfacing Sensors to the IBM PC. PTR Prentice Hall, Englewood Cliffs, New Jersey 07632. As indicated in brackets in the body of text PIC12F629/725 Data Sheet, from PICkit1 Flash Starter Kit installation CD. As indicated in brackets in body of text OPI1264A Opto-Coupler Data Sheet, http://www.optekinc.com/ As indicated in brackets in body of text
  • 43. 35 8.0 Bibliography Willis J. Tompkins and John G. Webster, 1988, Interfacing Sensors to the IBM PC. PTR Prentice Hall, Englewood Cliffs, New Jersey 07632. PIC12F629/725 Data Sheet, from PICkit1 Flash Starter Kit installation CD. Schematic, PICKit1 Flash Starter Kit, from PICkit1 Flash Starter Kit installation CD. PICKit1 User Guide, from PICkit1 Flash Starter Kit installation CD. Understanding & Programming the PIC16F84 http://www.talkingelectronics.com/html/PIC-for-Begginners.html
  • 45. 37 ;**************************************************************************** ;File Name: 232-line-driver.asm ;Author: GS Mackay ;Date: March-09 ; ;Description: Long-Haul 9600 Baud Serial Byte Line-Driver ; ;****************************************************************************** ;Notes: ;****************************************************************************** ; ;****************************************************************************** list p=12F675 ; list directive to define processor #include <p12f675.inc> ; processor specific variable definitions __CONFIG _CP_OFF & _WDT_OFF & _BODEN_ON & _PWRTE_ON & _INTRC_OSC_NOCLKOUT & _MCLRE_OFF & _CPD_OFF ; '__CONFIG' directive is used to embed configuration word within .asm file. ; The labels following the directive are located in the respective .inc file. ; See data sheet for additional information on configuration word settings. ;****************************************************************************** ;Defines ;****************************************************************************** #define Bank0 0x00 #define Bank1 0x80 #define rs232in GPIO,3 #define D0_1Tris B'11001111' #define bit_hi B'00010000' #define bit_lo B'00000000' #define waitcount D'11' ;****************************************************************************** ;General Purpose Registers (GPR's) ;****************************************************************************** cblock 0x20 count ; wait count endc ;****************************************************************************** ;Reset Vector ;****************************************************************************** ORG 0x000 ; processor reset vector nop ; required by in circuit debugger goto Init ; go to beginning of program ;******************************************************************************
  • 46. 38 ;Interrupt Vector ;****************************************************************************** ORG 0x004 return ; interrupt trap - returns without re-enabling ;****************************************************************************** ;Initialization ;****************************************************************************** Init call 0x3FF ; retrieve factory calibration value ; comment instruction if using simulator, ICD2, or ICE2000 BANKSEL Bank1 ; BANK1 movwf OSCCAL ; update register with factory cal value movlw D0_1Tris ; set direction so LEDs D0 & D1 are outputs movwf TRISIO ; all others are inputs (high-z) clrf ANSEL ; configure A/D I/O as digital banksel Bank0 ; change back to PORT memory bank movlw CM2 | CM1 | CM0 ; configure comparator inputs as digital I/O movwf CMCON ;****************************************************************************** ;Main ;****************************************************************************** Main btfsc rs232in ; wait in loop until RS232 start-bit goto Main ; SWITCH closure grounds input pin ;The output to the transmission line is idle-low by default. ;calling another lo_out when on the leading-edge of an RS232 start-bit... ;...offsets RS232-input data-clocking by a half bit-period to centralise... ;data-clocking in the middle of the bit-period. ;all subsequent 'clocking' is synchronised by the line-code generation time-frame ;loop ; call zero ; call one ; call start_bit ; call stop ; goto loop ; extends legacy state by 2us call lo_out ; offset input-data clocking by half bit-period call start_bit ; 1us btfsc rs232in call one call zero btfsc rs232in call one call zero btfsc rs232in call one call zero btfsc rs232in call one
  • 47. 39 call zero btfsc rs232in call one call zero btfsc rs232in call one call zero btfsc rs232in call one call zero btfsc rs232in call one call zero call stop call stop call stop goto Main ;test-pattern continuous loop- 00000000-11111111-10101010-1100000011 loop call start_bit call zero call zero call zero call zero call zero call zero call zero call zero call stop call stop call stop call start_bit call one call one call one call one call one call one call one call one call stop call stop call stop call start_bit call one call zero call one call zero call one
  • 48. 40 call zero call one call zero call stop call stop call stop call start_bit call one call one call zero call zero call zero call zero call one call one call stop call stop call stop ; goto loop ;****************************************************************************** ;Subroutines & Functions ;****************************************************************************** start_bit call hi_out ;2us nop nop nop nop nop nop nop call hi_out nop nop nop return zero call hi_out nop nop nop nop nop nop nop call lo_out nop nop
  • 49. 41 nop return one call lo_out nop nop nop nop nop nop nop call hi_out nop nop nop return stop call lo_out nop nop nop nop nop nop nop call lo_out nop nop nop return lo_out movlw bit_lo ; data for outputs low movwf GPIO ; send data to GPIO port call wait_period return ; return to calling routine hi_out movlw bit_hi movwf GPIO call wait_period return ; return to calling routine ;****************************************************************************** ;Time padding ;****************************************************************************** wait_period ; With 4Mz internal clock each instruction normally takes 1us to execute (4 cycles).
  • 50. 42 ; However, bit-test or program-counter redirecting instructions are longer (2us). movlw waitcount movwf count nop waitloop decfsz count,f goto waitloop return ; full countdown - exit END ; directive 'end of program'
  • 51. 43 Appendix-2 Scope Capture Signal with Short, Medium and Long Line Simulator-Settings and 200 Ohm Line Termination Resistance
  • 52. 44
  • 53. 45
  • 55. 47 ;**************************************************************************** ;File Name: RS232-a2d-RX.asm ;Author: GS Mackay ;Date: March 2009 ;Version: 1 ;Description: ; ;****************************************************************************** ;Notes: ;****************************************************************************** ; ; ;****************************************************************************** list p=12F675 ; list directive to define processor #include <p12f675.inc> ; processor specific variable definitions __CONFIG _CP_OFF & _WDT_OFF & _BODEN_ON & _PWRTE_ON & _INTRC_OSC_NOCLKOUT & _MCLRE_OFF & _CPD_OFF ; '__CONFIG' directive is used to embed configuration word within .asm file. ; The labels following the directive are located in the respective .inc file. ; See data sheet for additional information on configuration word settings. ;****************************************************************************** ;Defines ;****************************************************************************** #define Bank0 0x00 #define Bank1 0x80 #define SWITCH GPIO,3 #define D0_1Tris B'11001001' #define logic-0 B'00000000' #define logic-1 B'00000100' #define ANSelect B'00010001' ;Used to configure AD #define ADControl B'00000001' ;Used to configure AD #define cmpcontrol B'00011110' ;Used to configure comparator #define refcontrol B'10100001' ;set comparator threshold #define address B'11111111' ;device address mask ;****************************************************************************** ;General Purpose Registers (GPR's) ;****************************************************************************** cblock 0x20 a2dresh ; a2d result, high-byte bitcount ; received-bit counter, start-bit + 8 data-bits legacy ; previouse a2d value for start & stop-bit routines threshold ; a2d value at start of current bit-period diagnostic ; average a2d value from middle to end of bit-period databyte ; recovered bits shifted in from right
  • 56. 48 abortfloor ; any abort condition remains valid until 'line clear' flags ; status flags register endc ;****************************************************************************** ;Reset Vector ;****************************************************************************** ORG 0x000 ; processor reset vector nop ; required by in circuit debugger goto Init ; go to beginning of program ;****************************************************************************** ;Interrupt Vector ;****************************************************************************** ORG 0x004 return ; interrupt trap - returns without re-enabling ;****************************************************************************** ;Initialization ;****************************************************************************** Init call 0x3FF ; retrieve factory OSCAL value banksel Bank1 ; BANK1 movwf OSCCAL ; update register with factory cal value movlw D0_1Tris ; set GPIO directions movwf TRISIO ; all others are inputs (high-z) movlw ANSelect movwf ANSEL ;Configure AN0 & prescale to A/D movlw refcontrol movwf VRCON ;Configure AN0 & prescale to A/D banksel Bank0 ; change back to PORT memory bank0 movlw ADControl movwf ADCON0 ;Set comparator threshold movlw cmpcontrol movwf CMCON ;configure comparator bsf GPIO,2 bcf GPIO,1 bcf GPIO,4 bcf GPIO,5 clrf databyte ;****************************************************************************** ;Main ;****************************************************************************** Main btfsc SWITCH ;wait in loop until SWITCH closure is sensed goto Main bcf GPIO,2 ;clear LED on proram start restart ;start-bit recovery routine cmploop
  • 57. 49 btfss CMCON,6 goto cmploop ;wait for signal to cross threshold ;bsf GPIO,1 ;scope out hi for a2d-start bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for conversion start movlw d'8' movwf bitcount ;bitcount = 8 data-bits clrf databyte ;initialise recovered databyte movlw logic-1 ;prepare logic-1 idle-state movwf GPIO ;output logic bit a2dloop1 ;34us period btfsc ADCON0,GO goto a2dloop1 ;wait loop until a2d complete ;bcf GPIO,1 ;scope out lo on a2d complete movf ADRESH,w ;MSByte (a2d result high) into working register movwf legacy ;save current a2d value as legacy for next comparison movwf abortfloor ;this level used as threshold for 'line clear' in abort routine nop nop nop bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for conversion start ;bcf GPIO,1 ;scope out hi for conversion start a2dloop2 ;33us period btfsc ADCON0,GO goto a2dloop2 ;wait loop until a2d complete ;bcf GPIO,1 ;scope out lo on a2d complete movf ADRESH,w ;MSByte (a2d result high) into working register subwf legacy,f ;subtract current a2d value from previouse movwf legacy ;save current a2d value as new legacy for next comparison btfsc STATUS,0 ;if carry clear then 'current' > 'previouse' a2d value goto abort ;if 'previouse' > 'current' a2d then restart the start-bit search ;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle ;bsf GPIO,1 ;scope out hi for a2d-start bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for conversion start ;bcf GPIO,1 ;scope out lo for conversion start a2dloop3 ;37us period, a2dloop1+2+3=104us btfsc ADCON0,GO goto a2dloop3 ;wait loop until a2d complete ;bcf GPIO,1 ;scope out lo on a2d complete movf ADRESH,w ;MSByte (a2d result high) into working register subwf legacy,f ;subtract current a2d value from previouse movwf threshold ;save current a2d value as threshold for data recovery
  • 58. 50 btfsc STATUS,0 ;if carry clear then 'current' > 'previouse' a2d value goto abort ;if 'previouse' > 'current' a2d then restart the start-bit search ;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle movlw logic-0 ;prepare start-bit (logic-0 output) movwf GPIO ;output logic ;bsf GPIO,1 ;bcf GPIO,1 ;1us scope sync-pulse goto firstdiag ;acquire 1st-diagnostic in data-recovery routine datarecovery bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for conversion start ;bcf GPIO,1 ;scope out lo for conversion start movfw threshold subwf diagnostic,w ;compare diagnostic to threshold by subtraction btfsc STATUS,0 ;carry clear when 'threshold' > 'diagnostic' on signal slope-down bsf databyte,0 ;carry set if signal slopes-up indicating logic-1 movlw logic-0 ;prepare rs232 logic-0 output bits btfsc STATUS,0 ;carry-set/slope-up requires rs232 logic-1 output bits movlw logic-1 ;prepare rs232 logic-1 output bits movwf GPIO ;output rs232 bit rlf databyte,f ;move databyte bit-0 left for next diagnostic cycle a2dloopa ;35us duration, a2dloopa+b+c= 104us btfsc ADCON0,GO goto a2dloopa ;wait for conversion loop ;bcf GPIO,1 ;scope out lo at conversion end movf ADRESH,w ;grab a2d MSByte movwf threshold ;current a2d becomes threshold for next two diagnostic samples nop ;time padding nop nop nop nop firstdiag bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for conversion start ;bcf GPIO,1 ;scope out lo for conversion start a2dloopb ;34us period btfsc ADCON0,GO goto a2dloopb ;wait for conversion loop ;bcf GPIO,1 ;scope out lo at conversion end movf ADRESH,w ;grab a2d MSByte movwf diagnostic ;first post-threshold diagnostic sample
  • 59. 51 nop ;time padding nop nop nop bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for conversion start ;bcf GPIO,1 ;scope out lo for conversion start a2dloopc ;35us duration btfsc ADCON0,GO goto a2dloopc ;wait for conversion loop ;bcf GPIO,1 ;scope out lo at conversion end movf ADRESH,w ;grab a2d MSByte movwf legacy ;reference value for subsequent stop routine addwf diagnostic,f ;add second diagnostic sample to first... rrf diagnostic ;...and half result for diagnostic average decfsz bitcount ;8 data-bits to count goto datarecovery ;loop bit recovery until all 8 bits acquired stop bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for a2d-start ;bcf GPIO,1 ;scope out lo for a2d-start movfw threshold subwf diagnostic,w ;last data-bit diagnostic comparison btfsc STATUS,0 ;carry clear when 'threshold' > 'diagnostic' on signal slope-down bsf databyte,0 ;carry set if signal slopes-up indicating logic-1 movlw logic-0 ;prepare logic-0 output bits btfsc STATUS,0 ;carry-set/slope-up requires logic-1 output bits movlw logic-1 ;prepare logic-1 output bits movwf GPIO ;output logic bit a2dstop1 ;34us duration btfsc ADCON0,GO goto a2dstop1 ;wait loop until a2d complete ;bcf GPIO,1 ;scope out lo on a2d complete movf ADRESH,w ;MSByte (a2d result high) into working register movwf legacy ;save current a2d value as legacy for next comparison nop ;pad timing nop nop nop ;pad timing if line above commented out bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for a2d-start ;bcf GPIO,1 ;scope out lo for a2d-start a2dstop2 ;35us duration btfsc ADCON0,GO goto a2dstop2 ;wait loop until a2d complete
  • 60. 52 ;bcf GPIO,1 ;scope out lo on a2d complete movf ADRESH,w ;MSByte (a2d result high) into working register subwf legacy,f ;subtract current a2d value from previouse movwf legacy ;save current a2d value as legacy for next comparison btfss STATUS,0 ;if carry set then 'current' < 'previouse' a2d value goto abort ;if 'previouse' < 'current' a2d then abort byte recovery ;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle nop ;pad timing if line above commented out nop bsf ADCON0,GO ;start a2d ;bsf GPIO,1 ;scope out hi for a2d-start ;bcf GPIO,1 ;scope out lo for a2d-start movlw address ;load device address mask xorwf databyte,w ;compare address mask to recovered databyte btfsc STATUS,2 ;if zero then databyte matches address mask bsf flags,0 ;set 'address match' flag a2dstop3 ;33us duration- not critical on stop loop btfsc ADCON0,GO goto a2dstop3 ;wait loop until a2d complete ;bcf GPIO,1 ;scope out lo on a2d complete movf ADRESH,w ;MSByte (a2d result high) into working register subwf legacy,f ;subtract current a2d value from legacy value movwf legacy ;save current a2d value as legacy for next comparison btfss STATUS,0 ;if carry set then 'current' < 'previouse' a2d value goto abort ;if 'previouse' < 'current' a2d then abort byte recovery bsf GPIO,1 ;output stop-bit indefinately btfsc flags,0 ;check if 'address match' flag set bsf GPIO,5 ;output 'activation' signal if addressed ;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle cmploop2 btfsc CMCON,6 goto cmploop2 ;wait loop- wait for idle-line goto restart ;restart signal recovery abort ;bsf GPIO,1 ;scope out hi for a2d-start bsf ADCON0,GO ;start a2d movlw logic-0 ;prepare logic-0 output bits to force frame-error movwf GPIO ;output logic bit a2dabort btfsc ADCON0,GO goto a2dabort ;wait loop until a2d complete ;bcf GPIO,1 ;scope out lo on a2d complete movf ADRESH,w ;MSByte (a2d result high) into working register
  • 61. 53 subwf abortfloor,w ;subtract current a2d from first sync-detect value btfss STATUS,0 ;if carry set then 'current' < 'line clear' value goto abort ;hold loop until 'line clear threshold' > 'current' a2d ;bcf GPIO,1 ;scope out lo for end of a2d comparison cycle movlw logic-1 ;prepare logic-1 output bit movwf GPIO ;output idle-state logic bit prior to restart goto restart ;****************************************************************************** ;Subroutines & Functions ;****************************************************************************** END ; directive 'end of program'