	The following text file was part of a college level project.
The report is directed to a computer science student that has minimal
experience in hardware. Any comments are welcome.




      MODEL TRAIN CONTROL WITH AN IBM COMPATIBLE COMPUTER



                    Fred Merker

                    Computer Science 431



























                         Table of Contents


LIST OF ILLUSTRATIONS ..................................... 3

INTRODUCTION .............................................. 4
  Computer Interfacing .................................... 4
  Model Train Interface ................................... 4
  Decisions That Led to Choosing this Project ............. 5
  Limitations and Extensions for the Future ............... 5
  
DESCRIPTION ............................................... 6
  System Used - Hardware .................................. 6
  System Used - Software .................................. 8
  Computer Interfacing and Concepts ...................... 10
  Sensors ................................................ 11
  Choice of Hardware Design .............................. 12
  Alternatives ........................................... 13

IMPLEMENTATION ........................................... 14
  Hardware ............................................... 14
  Software ............................................... 17
  Algorithm for HO Train ................................. 18

ERRORS & PROBLEMS ........................................ 20

CONCLUSIONS .............................................. 20

WORKS CITED .............................................. 22

REFERENCES ............................................... 22
























                       List of Illustrations


Figure 1:  Sensors - mechanical support ................... 23

Figure 2:  Flag fitted to railroad car .................... 24

Figure 3:  Probes for high and low levels ................. 25

Figure 4:  Transistor driving a relay ..................... 25

Figure 5:  DAC and output stage ( version 1 )  ............ 26

Figure 6:  DAC and output stage ( version 2 ) ............. 27

Figure 7:  10% duty cycle ................................. 28

Figure 8:  50% duty cycle ................................. 28

Figure 9:  100% duty cycle ................................ 28

Figure 10: Block diagram of pulse width modulation circuit  29

Figure 11: NE555 wired for pulse width modulation ......... 29                

Figure 12: Diagram 1 infrared sensors ..................... 30

Figure 13: Diagram 2 infrared sensors ..................... 30




























                          INTRODUCTION

Computer Interfacing

      Webster'  Seventh   New Collegiate  Dictionary    describes 
interfacing  as 'the place at which independent systems meet  and 
act  upon  or  communicate  with each other '.  This  is  a  most 
appropriate definition for the discussion of this report. For  in 
actuality  there  are  two  separate  systems  that  I  will   be 
discussing. One is the micro-computer itself and the other can be 
almost  any electrical or electromechanical device. For  example,        
the computer could be controlling an automotive emissions  system 
or  the environmental control equipment for a building. The  list 
of  possibilities is almost infinite.      Specific hardware  and 
software are required for a microprocessor to transfer data to or 
from  the  external  device. A good example of this  would  be  a 
computer controlled manufacturing process. An arc welder may need 
to be turned off and on at precise points during the  fabrication 
of  a  certain  metal tool. A hardware  interface  or  buffer  is 
necessary  for the low voltage ( approximately 5 volts ) and  low 
current  ( several thousandths of an ampere ) capability  of  the 
computer circuit to control several hundred amperes needed during 
welding.  This buffer circuit may consist of a hardware latch  to 
remember  whether  the computer wanted the welder on  or  off.  A 
power  amplifier  would  then be used  to  increase  the  current 
handling  capability  of  the circuit. In this case  it  is  most 
likely that a relay would be the final controlling device for the 
large amount of current involved. The hardware has interfaced  or 
more  accurately protected the computer from destruction  by  the 
welder.  While  at  the same time we now have  an  exact  way  to 
control the manufacturing process.

     Software would have to be written to control this production 
process.  A  single line of an 8 bit I/O port would  be  able  to 
control  this on/off operation. A masking word can output to  the 
port so that seven lines are low level while one is high. This of 
course  is assuming that an active high is required to  turn  the 
arc  welder on. The routine may need to access the  system  clock 
for proper timing or get other outside information such as  metal 
temperature  or the number of tools left in this  batch.  Prompts 
should  be  included  so  that  an  operator  can  interrupt  the 
operation.

Model Train Interface

     I  have  chosen  to  interface an HO  train  to  an  IBM  PC 
compatible  computer system. The computer is used to control  the 
speed  of  the train in the forward and reverse  directions.  The 
train  will  also  stop at one of two  stations  after  traveling 
around the track five times.
 
     The  speed is regulated by approximately sixty 8 bit  words. 
Thirty of the words control the train speed in reverse and thirty 
control  the speed in the forward direction. Each eight bit  word 
that  is output is changed into an analog voltage by an DAC  0806 

integrated  circuit.  The voltage and current level out  of  this 
chip  is amplified by a power amplifier. The  specific  operating 
point  of  the  DAC 0806 is determined by  the  component  values 
selected. The output is then directly connected to the tracks. 

     Infrared sensors are used so the the computer will know  the 
location  of  the train at specific points.  These  sensors  also 
serve as the stations which are the starting and stopping  points 
for  operation  of the railroad. Each detector  is  actually  two 
devices  mounted  on  double-sided printed circuit  board  for  a 
holder.  (  figure 1 ) One is an infrared LED  (  light  emitting 
diode ) and the other is an infrared sensitive photo  transistor. 
The two devices are placed opposite each other with a spacing  of 
about  one  half an inch maximum. When the LED is turned  on  the  
photo  transistor  draws current and its collector  voltage  goes 
low.  A schmitt trigger inverter is used as a buffer between  the 
phototransistor  and  the computer. The schmitt  trigger  ensures 
that all pulses going the DG-148 interface have steep leading and 
trailing  edges  and are of a definite high or  low  level.  This 
eliminates any questionable logic levels going to the  interface. 
The  computer will be looking for a logical one.  This  indicates 
that a train is passing by. When the light is cut off between the 
infrared  LED and the photo transistor , the logic level  on  the 
computer's  input  line will change state. This level  change  is 
what tells the computer that a train has just passed through  the 
sensor.  The  engine of the train has been fitted  with  a  small 
cardboard  flag. The flag is what actually cuts off the  infrared 
light  from  the photo transistor. This is  best  illustrated  by 
referring to figure 2.

Decisions That Led to Choosing This Project

     Initially,  I was given the choice of one of three  possible 
microprocessor  controlled  projects. They were a  traffic  light 
signal,  a scale model elevator or a model train.  Circuit  ideas 
for  each  possible project were submitted to  my  professor  for 
evaluation.  The  traffic light system was  rejected  because  it 
would  be too easy to implement. The elevator was dismissed  only 
because  it  would  have involved an Erector  Set  that  was  not 
readily  available.  The  HO model train seemed to  be  the  best 
choice  because the train was already available for me  at  home. 
This  made  at least part of the hardware  procurement  a  little 
easier.

     Infrared  sensors were chosen over the Hall  Effect  devices 
because  of  problems  mentioned  in  several  magazine  articles 
(McKerrow,Dowsing).  These  articles  were used as  a  basis  for 
decisions  in  the early stages of the project. The  Hall  Effect 
devices  are not easy to obtain through local  electronic  supply 
stores.  These  integrated circuits are also  prone  to  problems 
caused by high noise levels on the power supply. Checking with an 
oscilloscope  proved that the train engine caused high  amplitude 
spiked  noise  on  the supply line. A  6000  ufd.  capacitor  was 
sufficient to reduce problems caused by noise. Cosmetically,  the 
Hall Effect device is much more pleasing for model railroading. A 
magnet  glued under a railroad car is sufficient to  trigger  the 
IC. The device itself can fit nicely between the tracks of an  HO 
layout.  However,  the procurement and noise problems led  me  to 
decide on infrared sensors.

Limitations and Extensions for the Future

     The  type of project selected  allowed for a wide  range  of 
future  additions.  Any number of stations can be  added  to  the 
system  as  well as switches and possibly the control of  two  or 
more engines. A software routine could be written to measure  the 
time  it takes to go between two infrared sensors. The  time  per 
unit  distance could be scaled for a read-out that would  give an 
MPH value to scale with a full size train. In a further extension 
of  the  project,  graphics could be used so that a  map  of  the 
layout  would  be shown on the terminal.  An  enhanced  character 
could be made to move along the map in step with the movement  of 
the train.
 
     The  plan also has a number of limiting factors. One of  the 
largest  limitations  was time. The size of the project  and  the 
research  required  was surprising as time  went  on.  Developing 
hardware  circuits and software to drive  them consumed  a  large 
amount  of  time. The physical size of the track was  limited  by 
what I had available at home. Keeping the train in a simple  loop 
helped  to reduce the magnitude of the project. It  could  easily 
have become an impossibility to complete the project in the  time 
allocated.  The  power  supply  also  limited  the  size  of  the 
endeavor. Originally it was thought that a single polarity supply 
would be fine for control of the engine. However, the requirement 
of  reversing the train made the bipolar supply a necessity.  The 
only  bipolar power supply that I had available was limited to  1 
ampere of current. Considering the current drawn by the TTL logic 
and the current required by the engine ( approximately 300 ma.  ) 
the circuit was just about at its maximum size. 


                           DESCRIPTION    


System Used   Hardware

     My computer system is a Kaypro PC-10. The microprocessor has 
768  kilobytes  of random access memory. The 8088  processor  can 
only  access  1 megabyte of memory. Under  the  MS-DOS  operating 
system  384  kilobytes of memory are used for  numerous  hardware 
items.  This  leaves a maximum addressable memory  limit  of  640 
kilobytes. In the Kaypro I use the extra 128 kilobytes of  memory 
for  a  RAM  disk.  Programs that run  using  the  RAM  disk  are 
extremely  fast  because  there  is no  mechanical  lag  that  is 
associated  with  a floppy drive or a hard disk. Of  course,  any 
data that is left in a RAM disk is lost when the power is  turned 
off.  So  the computer operator must be sure to  save  any  files 
before turning off the power. 

     The  monitor  is  an  RGB ( red-green-blue  )  type  and  is 
compatible  with the CGA ( color graphics adapter ) standard  set 
by  IBM. The original 20 megabyte hard drive that came  with  the 
Kaypro  has  been replaced. I have installed a 30  megabyte  Fuji 
hard drive which has a quicker access time, more memory space and 
generates  a  lower  level of ambient noise.  The  printer  is  a 
Panasonic KXP-1091 which has a 5x7 dot matrix character  on a 9x9 
field. The printer can do graphics and has the feature of a  near 
letter quality mode. 

     During  the preliminary stages of this project a  number  of 
possibilities  were considered for the buffer between the  Kaypro 
data  buss  and the HO train circuitry. A  simple  buffer  system 
using a vector board with an IBM compatible pin configuration was 
considered. The model 4613 manufactured by the Vector Electronics 
Company   uses  wire  wrap  for  connections  between  pins.   In 
applications  similar to this the 74LS273 integrated circuit  has 
been used to protect the data and address busses from damage  due 
to accidental short circuit. The enable line of the chip is  held 
high so that all data is passed to and from the data buss without 
latching.  The sole purpose of the buffer circuit is  to  protect 
the microprocessor system from an external catastrophic accident. 
I also considered a number of prefabricated buffer boards.  Among 
these  were  circuits  manufactured  by  Creative  Microprocessor 
Systems,  Computer Continuum and Qua Tech Inc. After  considering 
the  damage  that  could occur to the Kaypro  by  an  inadvertent 
wiring  mistake with the Vector system, I decided that  a  proven 
commercial  buffer board was the safest thing to use. The  higher 
cost  of  the industrial board was more than offset by  the  fact 
that a small wiring mistake would ruin an IC and not my  computer 
system.  The Alpha Products seemed to offer the most  versatility 
and  expandability  for  its price. Alpha  Products  calls  their 
interface  system the 'A Bus'. The 'A Bus' system will work  with 
almost any computer , from a Radio Shack to an IBM PC AT.This  is 
achieved by using an adapter board which goes to the 'A-Bus'.  If 
a new computer system is purchased only the adapter board need be 
changed not the entire interface. Alpha Products features 14  'A-
Bus'  interface  cards.  They will do  everything  from  drive  a 
stepper  motor  to  decode a touch tone signal.  The  DG-148  was 
chosen in particular because it uses a 8255 for an I/O element.  

     The  8255  chip  is extremely  versatile  for  parallel  I/O 
functions  and is easily programmed for a number  of  operations. 
This  chip actually has three parallel 8 bit ports.   Programming 
information  is sent to the control port of the 8255. This  is  a 
address which is independent of the three ports used for I/O. The 
three  ports  A,  B and C can be  programmed  in  three  possible 
application  of  modes. Mode 0 is simple input  and  output.  All 
three  ports can be programmed to this mode. In this  case,  data 
sent  out of the port is latched until a new data word is  output 
to  the same address. When data is input to the port it  is  also 
latched  and made available for the computer to read  anytime  an 
input  instruction is encountered. Ports A and B can be  set  for 
all  input or all output. The third port ( C ) is split  in  half 
and the two halves can be programmed independently of each other.

      Mode   1  provides  for  strobed  input  or  output.   This 
capability  is available only for ports A and B. The  input  mode 
provides  for  three control signals at port C. They  are  STB  ( 
strobe  ), IBF (input buffer full ) and INTR ( interrupt ).  When 
the  STB signal is brought low, by external circuitry,  the  8255 
reads  and holds the data on the port input. The IBF signal  goes 
high  at  this point to indicate that data is available  for  the 
computer to read. When the computer comes to an input instruction 
and  reads the data the IBF signal goes low indicating  that  the 
buffer  is empty and ready for more data. In the  strobed  output 
mode three signals become available. They are OBF (output  buffer 
full  ), ACK ( acknowledge ) and INTR ( interrupt ). When OBF  is 
low  this indicates that the computer has output one byte and  it 
is  available to read. When the ACK signal is made to go  low  by 
external circuitry the data is placed on the output lines and the 
OBF signal goes high again.

     Mode 2 is strobed bi-directional I/O which is available only 
on  port  A. In this case all five signals which  were  discussed 
earlier  become functional on port C. Each signal STB, IBF,  OBF, 
ACK  and  INTR perform exactly as described  earlier.  This  mode 
makes  effective  use of the 8 bit lines by using them  for  both 
input and output. 

     Up to this point the INTR signal has been mentioned but  not 
explained.  The  computer can enable or  disable  the  interrupts 
which are produced by the DG-148. The interrupts are enabled when 
a particular pin is brought high and they are disabled when  that 
same  pin is low. During the input data process when the IBF  and 
STB are both high and the proper enable pin is high, the  program 
will be interrupted and the data processed. When the data is read 
by the computer the interrupt line will be reset. 
 
System Used Software

     Finding the software to develop the HO train controller  was 
a  process  of trial and error. My last  experience  in  assembly 
language  programming was with an 8080 microprocessor  using  the 
CP/M  operating system. I had grown to like a program called  the 
SFO 8.4. This assembler actually had three programs wrapped  into 
one  nice package. It consisted of a built in editor,  an  object 
code  debugger  and  of course the  assembler  itself.  This  co-
resident environment became a favorable way to develop  programs. 
However  the 8080 and the 8088 are two different  processors  and 
software has been developed to enhance each one. In searching for 
an  assembler, I soon found that the co-resident approach was not 
available with the 8088 software family. 

       The MASM (macro-assembler) by IBM is the industry standard 
but the high price tag put it out of the range of this project. I 
finally settled on two shareware assembler packages. One of  them 
is  called Chasm which stands for Cheap Assembler.  The  software 
was  written  by  David Whitman. As the author  mentions  in  the 
introduction  'CHASM  is simple to use and understand'.  I  found 
this to be absolutely true. The ease of using Chasm helped to get 
me  from  the world of the 8080 processor into  the  8088  realm. 
However,   one  of  the  major  drawbacks  of  Chasm,  for   this 
application,  was that it would not produce object  modules  that 
would link with Pascal.

     Chasm  version  4.1  will  support  24  different  assembler 
directives. A few of these commands are listed below.

BSAVE  -  instructs Chasm to build a header that is  in  the 
          format  of  BASIC'S BSAVE command.  The  resulting 
          object code file can be BLOADed by BASIC programs.
EJECT  -  Tells Chasm to start a new print  page  when  sending 
          output to the printer.
EJECTIF - This is a conditional page break, if fewer  than  the 
          specified  number  of lines are left, Chasm  will           
          start   printing   on  the  next  page. This is useful
          for keeping all procedures on the same page.
INCLUDE - The contents of the specified file are included in  the 
          source file at the point that is specified.
MAP     - This  command  causes a file  to  be  generated  that 
          contains  label  information to be used by  a  symbolic 
          debugger.
STRUC   - Chasm  is directed so that the lines that follow are a
          structure.
CHKJMP  - Chasm will check to see if the JMP commands used  could 
          be changed to JMPS to make the code tighter.

     Chasm  comes in two versions. One is the  shareware  edition 
while the other is an advanced issue which is available to anyone 
who  registers by mailing in a $40.00 fee. The  advanced  version 
supports  macros  and assembled much faster  than  the  shareware 
model.

      The  other shareware assembler that I used  in  programming 
was  the  A86.  Eric  Isaacson is the  author  of  this  software 
package.  The  registration  fee for A86 is $50.00.  This  is  an 
advanced program which rivals the MASM in power and  flexibility. 
The  A86  does not generate the traditional .LST  file  with  the 
hexadecimal  object bytes to the left of each nmemonic.  This  is 
contrary  to  tradition,  which  since  the  advent  of  assembly 
language programming, has always placed the memory address of the 
command next to each nmemonic. However, the intention is that all 
program  debugging be done with a symbolic debugger, such as  the 
D86  , which is available as a shareware program. Mr.  Isaacson's 
contention  is that symbolic debugging is much faster and  easier 
to use than traditional methods.

     Some  of the directives that are supported by A86 are  shown 
below:
DD      -  This tells the A86 to initialize a 32  bit  doubleword 
           pointer  to  locations in arbitrary  segments  of  the 
           memory space.
STRUC   -  Defines  a template to data to be  addressed  by  the 
           8086's  base or index registers.

 '='    -  This is provided to be compatible with the MASM.
PROC    -  Provided  in order to  be  compatible  with  Intel/IBM            
           assemblers.   
PUBLIC  -  Allows  for  explicit listing of  the  symbols  in  a 
           particular assembly that can be used by another module.
EXTRN   -  Allows a type to be attached to a symbol that may  not 
           yet be defined. This is often necessary to ensure that 
           the  assembler  generates the correct  opcode  when  a            
           symbol is used as an operand. 
SEGMENT -  Tells the assembler that the following code  will  be 
           assembled in a particular segment of memory. 
ENDS    -  Closes out assembly of the current segment and returns 
           to  assemble code that was being assembled before  the 
           last SEGMENT directive.
GROUP   -  Instructs A86 that all the listed segments will fit in 
           640  kilobytes of memory. This is sent to  LINK  which 
           in turn attempts to make them fit.

     I  used Chasm for developing all of my initial object  code. 
The  Cease,  Resume and Boost procedures were  all  written  with 
Chasm.  The editor that was used is part of the package  that  is 
available  with  the  program PC Tools Deluxe.  This  editor  has 
limited  cursor control. However, it does feature an easy to  use 
cut  and paste capability that proved to be extremely  useful  in 
moving around various procedures. 

     Turbo  Pascal  version 4 from Borland was used  as  my  high 
level language. The $L directive helped to make linking a  little 
easier. This directive tells the compiler which file name to look 
for when the OBJ function or procedure are called.

                Computer Interfacing and Concepts

     No  matter  which  computer system is used  there  are  many 
common hardware devices used for interfacing. These chips go by a 
number  of  different  names, such as UART,  USART  or  PIO.  The 
integrated  circuits of this type are made by many  manufacturers 
and  come  in many different packaging styles.  The  dual  inline 
package  or  DIP is probably the most common  holder,  while  the 
surface  mount  device  is quickly taking a  large  market  share 
because  of  its small size. In all cases, the  function  of  the 
interface chip is to allow the microcomputer to communicate  with 
an external system. 

     The  USART or Universal Synchronous/ Asynchronous  Receiver/ 
Transmitter is an extremely versatile chip. In particular we will 
take  a  look  at  the 8251, which is  a  member  of  the  MCS-80 
microprocessor  family.  The  primary job of this  device  is  to 
convert  the parallel data from the computer into serial data  to 
be  used in communications systems. This chip can operate in  the 
synchronous, asynchronous and the isosynchronous modes. The  8251 
can  transmit  in half or full duplex and with 5,6,7,  or  8  bit 
characters.   It   is  designed  to  connect  directly   to   the 
microprocessor  data  buss. Modem control is one of many  of  the 
jobs performed by the 8251.

     The various modes of operation are all selected by  software 
control. There is a specific sequence in which the USART must  be 
programmed.   The  chip  configures  itself  according   to   the 
instructions  which are output to it. Therefore it is  imperative 
that all configuration be complete before any attempt is made  to 
transfer data.

     This  is a complex but extremely versatile device which  can 
be used to advantage in many applications. Its primary  advantage 
is software control. The mode of operation can be shifted quickly 
without making any hardware changes.

     The  8212 is a 24 pin 8-bit input/ output port. This  device 
is  intended  for the transfer of parallel data directly  to  and 
from the processors data buss. In contrast to the 8251 this  chip 
is  not  controlled with software. All latching or  buffering  of 
data is done completely with hardware.

     This project takes advantage of the 8255 I/O chip which is a 
software  programmable type. Details of its operation  have  been 
explained under 'System Used - Hardware'.

 Sensors

     Detectors  are  used to measure real world  values  such  as 
temperature, pressure and fluid levels. These parameters are then 
converted  to  a  voltage  that can  be  read  by  the  computer. 
Integrated   circuits   have   greatly   reduced   the   hardware 
requirements   which   are  needed  to  make   these   types   of 
measurements.  National  Semiconductor has an  entire  family  of 
devices which are designed to measure these values. The following 
list  discusses a small number of the chips that are available.

LM135   - This is a highly accurate temperature sensor that has a 
typical error of 1 degree centigrade over a 100 degree centigrade 
temperature  range. The circuit operates as a zenor  diode  whose 
breakdown voltage changes as the ambient temperature changes. The 
output   voltage   changes  10  millivolts/  degree   Kelvin   of 
temperature change.

LM903 - Fluid levels are measured using a thermo-resistive probe. 
This is an on-off type of measurement and is capable of  handling 
600 milliamperes of external current drain. Level changes are not 
measured continuously, so two chips would be required to  measure 
both a high fluid level and a low fluid level.  (see figure 3)         

LM1830  -  Actual  level of a fluid can  be  measured  with  this 
integrated  circuit.   The resistance of a fluid is  measured  by 
passing an alternating current between two probes.  The  measured 
resistance  is  compared  to an internal  value.   If  the  probe 
resistance  increases  to a preset value (indicating  high  fluid 
level)  an  alarm  circuit is triggered.  The  amplitude  of  the 
oscillator  changes  with  the  varying  resistance  between  the 
probes.   By  letting  the  computer measure  the  level  of  the 
oscillator output the actual fluid level can be determined.  

LM1801  -  A  computerized home security system  could  use  this 
device  as a smoke detector.  An external ionization  chamber  is 
necessary  to  complete the hardware requirements.  Up  to  eight 
chips could be paralleled so that each area of a home could  have 
complete smoke sensing capability.  An external 85 db horn can be 
directly driven by this chip.  

LM3911  -  Using  this  chip allows a computer  to  know  when  a 
specific  temperature threshold has been exceeded.  The  on  chip 
operational amplifier can be wired as a comparator so that on-off 
temperature controlling can be accomplished.  The output  voltage 
is  directly proportional to temperature in degrees Kelvin at  10 
millivolts/ K.  
     
     The  output  of  a computer can be made to  control  a  high 
current  device  by using a transistor.  A small current  on  the 
base  of a transistor can be used to control larger  currents  on 
its  collector.  A typical setup is shown in figure 4.  In  order 
to eliminate damage to the transistor, by the collapsing field of 
the  relay,  a diode is placed across the coil to short  out  the 
reverse current flow.  Typically, a reed relay would be used  for 
this  type  of application.  At 5 volts the Radio Shack  model  # 
275-232 only draws 20 ma. in the collector circuit.  The contacts 
of the relay can control 1 ampere at 125 volts.  

Choice of Hardware Design

     A number of factors were involved in choosing the particular 
circuit  that  was  used.  A bipolar power  supply  was  required 
because  the  train needs to be able to go into  reverse  without 
using a relay.  A polarity reversal can be done with a relay  and 
a single polarity supply.  It was decided that  electromechanical 
devices  would be avoided if at all possible.  This requires  the 
use  of a complimentary output stage to drive the  engine.   This 
circuit  is much more complicated than the previous output  stage 
(figure  5),  but  the relay has been eliminated.   In  order  to 
implement  complete train control under software, the DAC had  to 
be  designed so that the full power supply swing ( from  positive 
15 volts to negative 15 volts ) can be completed in a maximum  of 
256 steps.

     At this point, I came to one of several project limitations.  
A second design of the DAC and output stage did not give the full 
power  supply  swing  at  the output of Q2  and  Q3  (figure  6).  
Several  value  changes were tried but the maximum  output  range 
seemed to be limited to 12 volts rather than the expected 30 volt 
total  swing.  Another requirement, is that the center of the  DC 
voltage  swing must pass through zero.  This gives  stopping  and 
starting control in the forward and reverse modes.  Therefore, to 
achieve  the  desired  train control the  center  of  the  output 
voltage  swing must pass through zero.  For example,  as  various 
resistor values were tried the voltage swing would often compress 
to  just the negative voltage.  This would put the center of  the 
software control point at -3 volts. This was not suitable for the 
type of control that was desired.

     A  software  routine  was written that  would  step  quickly 
through all 256 possible digital increments in a small amount  of 
time.  This allowed for rapid evaluation of any hardware changes.  
This  part  of  development was done with  the  train  in  actual 
operating  conditions.  The software routine would spend  several 
hundred  milliseconds  in  a  loop routine at  each  of  the  256 
possible output words.  The length of time spent in the  software 
loop is determined by the following equation:

          delay time = total # clock cycles X clock period
          
               clock frequency = 8 Mhz

               period = 1 / 8,000,000

               period = 125 nanoseconds 

Calculation of clock cycles

     total clock cycles = times thru loop X clock cycles in loop

               clock cycles for instructions

                    instruction    cycles

                         MOV               4
                         DEC               3
                         JNZ              16

     total clock cycles = 2 (( 3 + 16 ) ( 65,536 )

     total clock cycles = 2,490,368

          delay time = 2,490,368 X 125 nanoseconds

                     = 0.311 seconds

     ( Calculations were done for the loop labeled 'time' )      

The  speed of the clock and the number of clock  cycles  required 
for  each instruction are the major determining factors for  time 
in the loop.

Alternatives

     There  are  several other hardware  possibilities  that  are 
worth  considering for this project.  One that has interested  me 
is  the  use of a bipolar high power audio amplifier  IC  as  the 
output  stage.  This would eliminate the tedious design  of  each 
component value as required for a discrete circuit.  The cost  of 
the integrated circuit  and the delay in shipping time  prevented 
any further pursuit in this area. One of my goals was to keep the 
cost of the project as low as possible.

     It seemed that the present design would be more effective if 
the driving current was higher to the complimentary output stage.  
Possibly  a  higher  gain device for Q1  (figure  6)  would  have 
accomplished this.  Since transistors are current driven  devices 
I really feel that the lack of output voltage swing is caused  by 
too little current flow in the circuit. 

     These  alternative  circuit  designs  and  ideas  were   not 
attempted  because of lack of time and money limitations  on  the 
project.   A lot of research can go into determining the  optimum 
output  stage.   A  high  current  gain,  high  power  stage   is 
definitely required.  Direct current coupling is required for all 
stages.

     Another  possibility  for  train  control  is  pulse   width 
modulation.   This  technique  is used  by  many  model  railroad 
manufacturers.   The  more expensive power packs  will  use  this 
method  to  have  a much better  capability  of  controlling  the 
trains' speed.  

     The  idea  of pulse width modulation for  train  control  is 
actually  a  precise control of duty cycle for  the  DC  voltage.  
Figures  7,  8, & 9 can be referred to in explaining  this  idea.  
The  full output voltage is always applied to the track, but  the 
regulating device is modulated with a pulse signal.  As shown  in 
figure  9, 100% duty cycle corresponds to no modulation  at  all.  
As the negative going pulse ( figures 7 & 8 ) increases in  width 
there is less power available for the electric motor.  With  less 
power  available to the electric motor the train will slow  down.  
Therefore, 0 % duty cycle corresponds to a no power or train stop 
condition.

     Originally,  the train was going to be controlled  by  pulse 
width modulation.  My concept was a NE555 timer wired as a  pulse 
width  modulator.   This integrated circuit would  then  drive  a 
series  pass  regulator transistor.  A block diagram of  this  is 
shown  in  figure 10. In order for the computer  to  control  the 
train it would have to control the NE555 timer.  Figure 11  shows 
that  in  the  pulse  width  modulation  mode,  a  NE555  uses  a 
potentiometer as a control element.  The problem then was getting 
an output from a DAC that would substitute for the  potentiometer 
R5.   The  entire idea shortly became an over  complication.   It 
became clear that direct DC control of the series pass transistor 
would be the easiest method.


                         IMPLEMENTATION  

Hardware

     The  major  component of the circuit consists of  a  DAC0806 
digital to analog converter.  This device takes an 8 bit word and 
converts it to a current level.  It features a full scale  output 
settling time of 150 nanoseconds and a relative accuracy of  0.19 
%.   Because this device outputs a current level and not voltage,
an  operational  amplifier  is required  to  generate  a  voltage 
output.

     The resistor R1 provides the reference amplifier with  input 
current  (figure  6). The value of 1.8K was  recommended  by  the 
manufacturer in their technical reference manual.  R2 is tied  to 
the negative supply voltage to provide a voltage corresponding to 
the  lowest  value  of  input  level.   The  resistor  could   be 
eliminated with only a small decrease in conversion accuracy.  R3 
and R4 comprise a voltage divider circuit which is used to offset 
the  output voltage of the operational amplifier U2. The  op  amp 
has  been connected as a differential amplifier.  The  difference 
of  the  (-) and (+) inputs are amplified by  the  circuit.   The 
voltage  divider provides -11.4 volts at the input of pin 3.   R5 
is the negative feedback resistor to set the gain of the op  amp.  
The value of 6.8K ohms was chosen so that the final output of the 
circuit  would have an equal positive and negative voltage  swing 
which was centered on zero volts.

     It should be mentioned at this point that about 60  discrete 
words  were able to control the train from full forward speed  to 
full reverse speed.  An input word of 1f hexadecimal results in a 
zero  output  from  the junction of Q2 and Q3.   A  value  of  40 
hexadecimal input to U1 results in -6 volts output to the  train.  
The voltage corresponds to full reverse speed.  Incrementing  the 
AL  register in thirty steps of one, causes the train to go  from 
stop  to  full speed reverse.  In like manner, the train  went to 
full speed ahead in approximately 30 discrete digital steps.   In 
this  case the AL register is decremented thirty times until  the 
output  voltage is +6 volts or full speed ahead.  A value  of  00 
hexadecimal is equal to an output voltage of +6 volts.

     The software is such an integral part of the hardware design 
that  it  is  necessary to understand part  of  the  software  to 
understand  the  design of the hardware.  As the  values  of  the 
components were changed and optimized a software routine was used 
(  as  previously  mentioned ) to run through  all  255  possible 
inputs  to  U1.  This assured me that the full output  range  was 
exactly  as expected.  It also gave the opportunity to watch  the 
voltage  values  change under actual  operating  conditions.   By 
monitoring  the output voltage of Q2 and Q3, resistor values were 
quickly  chosen  that  maximized the  voltage  swing  while  also 
keeping it centered around zero volts.

     Continuing  our  look at the hardware,  R6  functions  as  a 
current  limiter.  The value of 470 ohms acts to  reduce  current 
drawn  from U2 by the preamplifier Q1.  At this point, we have  a 
voltage swing from -6 volts to -9 volts at pin 1 of U2.  This was 
caused  by placing an 8 bit word on the input pins of U1  between 
the  range of 00 hexadecimal to 40 hexadecimal.  The base  of  Q1 
has  to  be biased in the range of -6 to -9 volts  in  order  for 
proper  output to occur.  The diode D1 and emitter bias  resistor 
R8  were  designed to bring the bias voltage of Q1 to  the  point 
that U1 could control it correctly.  D1 is forward biased so that 
0.7 volts is dropped across it.  The resistor R8 brings the  bias 
up  slightly and includes some negative feedback in the  circuit.  
D2 functions to bias the output transistors Q2 and Q3.  In the no 
signal  mode both transistors are closely biased at their  cutoff 
point.   With  zero  volts on the  output  both  transistors  are 
dissipating  very  little power.  It is only when  the  train  is 
running  that the transistors dissipate power.  R7 completes  the 
bias ladder from the -15 volt supply to the +15 volt supply.       

     The output stage is a complementary type using a PNP and NPN 
pair of transistors.  Phase inversion is not necessary with  this 
type  of  circuit and therefore the driving circuit  is  simpler.  
Design  ideas  for this circuit come from the RCA  Silicon  Power 
Circuits manual.

     Proper  heat  sinking  on the power transistors  had  to  be 
provided.   In actual operation the train engine draws about  300 
milliamperes.   A worse case power dissipation for either of  the 
transistors is 15 volts at the maximum current.

     Power dissipated = Voltage ( across transistor ) X         
                        Current ( in circuit )

     Power = 15 X 0.3
     Power = 4.5 watts

So proper heat sinking had to be provided to dissipate a  maximum 
of 4.5 watts.

     As mentioned earlier, infrared sensors were used as  pickups 
so  the  computer  knows the location of the train. As  shown  in 
figure  12, two different pairs of sensors were used.  The  Radio 
Shack  infrared  (part  #276-142) were much  more  sensitive  and 
easier  to  align. Alignment involved using a  voltmeter  on  the 
collector of the phototransistor to monitor signal level. As  the 
light  received by the phototransistor increased the  voltage  on 
its  collector  decreased.  This  decrease  in  voltage  on   the 
collector indicates the device is drawing more current. Referring 
to  the side view of figure 12, the alignment involved  adjusting 
the  positioning  of the mounting plate in the x axis and  the  z 
axis.  Solder  was used to bond the printed circuit boards  in  a 
properly aligned position.

     The  two  infrared sensors in figure 13 proved  to  be  less 
sensitive.  The  TIL  906-1 has a 82 ohm resistor  as  a  current 
limiter.  This  increased  its photo output as  compared  to  the 
circuit  in figure 12. In order to have proper operation  of  the 
sensor it was necessary to reduce the spacing between the LED and 
its associated phototransistor. The devices in figure 13 required 
a  spacing  of  3/16's of an inch while  the  other  pair  worked 
properly with a spacing of almost 1/2 of an inch.

 


          Parts List

     U1   DAC0806
     U2   LM358
     U3   7414 (schmitt trigger )   
     Q1   2N657
     Q2   TIP3055
     Q3   TIP42
     Q4   RS 276-142
     Q5   TIL414
     LED1 RS 276-142
     LED2 TIL 906-1
     R1   1.8K ohms
     R2   1.8K ohms
     R3   6.8K ohms
     R4   1K ohms
     R5   6.8k ohms
     R6   470 ohms
     R7   2.2K ohms
     R8   680 ohms
     D1   1N914
     D2   1N914
 

Software
     
     All the train control software was written in 8088 assembly 
language  using Chasm and A86.  A full screen menu  program  was 
written  in Pascal which linked to the assembly code.  The  menu 
provides for the following options:
     1. Start train slowly and run continuously
     2. Slow down train slowly and stop
     3. Start slowly, loop the track 5 times, slow gradually  and 
        make a stop at station A
     4. Same as option 3 except stop is made at Station B
     5. Return to DOS

     In  all cases except 5, the assembly code returns control to 
the  menu.   This  allows the user to make  another  menu  choice 
without restarting the program.  The WHILE loop includes an error 
trap for key strokes out of the range of 1 to 5.

     The  assembly code has been broken into four  modules  which 
are  called by the menu driver.  Each of the modules starts  with 
port initialization.  The 8255 is programmed by sending codes  to 
its control port.  A decimal value of 139 will setup the chip for 
port A as simple latched output and port C as latched input.

     The Launch module then calls a procedure named 'start'.  The 
CX  register  is  loaded with a decimal value  of  33.  The  loop 
command will decrement the CX register and break out of the  loop 
when the CX register is zero. The AL register is loaded with an 8 
bit value ( 1f hexadecimal ) which corresponds to a track voltage 
of zero. After the data word is output two procedures are called. 
One  is  'time'  whose  function is  to  pause  the  program.  As 
calculated earlier, it is about 0.3 seconds of delay. This allows 
for settling time of the circuit voltages and compensates for the 
mechanical  hysteresis  of the train. The object of  the  'start' 
procedure is to gradually bring the train up to full speed.  This 
would be much the same way a real train gradually approaches full 
operating speed. Model train motors have so much torque that with 
full  voltage switched to the track, the train seems to  jump  to 
full  speed instantly. This does not come at all close to  actual 
train operation. The software's goal was to make the train  start 
slowly and allow a gradual increase to full speed.

     'Boost' is the next procedure that is called. This  software 
attempts to overcome the mechanical inertia of the train. I found 
that  a  gradual voltage increase did not make  the  train  start 
gradually.  Motor torque had to get high enough to break free  of 
friction.   Unfortunately, in some cases, the software  code  was 
already  outputting almost full track voltage.  This, of  course, 
made the train jump  to full speed.  This is doing  exactly  what 
the   code is written to prevent.  The job of 'Boost'  became  to 
break the friction and inertia of a body at rest.  So a value  of 
40 hexadecimal is output to U1 in order to apply full voltage  to 
the  track  for an instant in time.  The full  output  pulse  was 
measured   with   an  oscilloscope.   The  pulse   duration   was 
approximately  0.02 milliseconds.  The 'Boost' procedure  returns 
to 'Start' which then increments the AL register and continues to 
start train.

     The listing of 'Bindisp' is included in both the Launch  and 
Cease modules.  Its purpose was to display the binary word output 
to  U1.   When the Pascal menu program was  added  the  'bindisp' 
would no longer operate properly.  Pascal has complete control of 
the  screen  and  will not allow an interrupt 21  to  control  to 
output to the terminal.  The binary value would have to be passed 
to Pascal as a variable in order to display it.

     The Cease module slows the train down.  This is much  easier 
to  do because there are no problems with inertia.  In this  case 
it  acts  completely in our favor.  After initialization  of  the 
8255,  the  DAC  is loaded with a value  that  will  output  full 
voltage  on the track.  The same time delay procedure  is  called 
each time the AL register is decremented.



                  Algorithm for Model HO Train


          Launch Procedure
     
     1. initialize the 8255
     2. load 33 into counter
          a. set the output for zero volts
     3. output voltage to the tracks
     4. save registers
     5. call time delay procedure

          a. set up registers to delay 0.3 seconds
     6. call boost
          a. output full voltage to the tracks for 0.02 msec.
     7. restore the registers
     8. increment the data word by one
     9. if the counter is not zero go to step 3
    10. return to Pascal menu


          Cease Procedure

     1. initialize the 8255
     2. load 33 into the counter
          a. set the output for full voltage
     3. output voltage to the tracks
     4. save registers
     5. call time delay
          a. setup registers to delay 0.3 seconds
     6. restore the registers
     7. decrement the data word by one
     8. if the counter is not zero go to step 3
     9. return to Pascal menu


          Stationa Procedure

     1. initialize the 8255
     2. call start procedure
          a. load CX register with 33
          b. output to the tracks (initial value is zero)
          c. call delay (0.3 seconds)
          d. call boost 
          e. increment AL register
          f. decrement CX register
          g. if CX does not equal zero go to (b)
     3. call circle
          a. load CX register with 10
          b. input 8 bits from port 'c'
          c. mask all but the 8th bit
          d. store value in a memory location
          e. input 8 bits from port 'c'
          f. mask all but the 8th bit
          g. compare memory and input data
          h. if the result is zero go to (e)
          i. otherwise decrement CX register
          j. if CX does not equal zero go to (b)
     4. call slwstp (slow stop)
          a. load CX with 10
          b. output value to tracks (initial value is maximum)
          c. call time (delay)
          d. decrement AL register
          e. decrement CX register
          f. if CX does not equal zero go to (b)
          g. otherwise input data from port 'c'
          h. mask all but 8th bit
          i. save value to memory location
          j. input data
          k. mask all but the 8th bit
          l. compare new value and value in memory
          m. if result is zero go to (j)
          n. otherwise output zero volts to the tracks


                        ERRORS & PROBLEMS

     There were a number of problems that were encountered during 
the course of this project.  One problem was finding an assembler 
that would fulfill the needs of the project.  Then of course  one 
had  to learn the syntax requirements of both assemblers and  the 
requirement  of Turbo Pascal V. 4 for linking the programs.   The 
A86 assembler proved to be more difficult to use but its advanced 
capabilities   were  exactly  what  was  required   for   project 
completion.

     The major hardware difficulty was the limitation encountered 
on  output voltage swing.  More work on the design  is  required.  
Possibly  a high gain driver transistor will increase the  output 
voltage swing.

                           CONCLUSIONS

     The  project  is  successful in several  new  and  different 
areas. I gained experience in writing assembly language  routines 
for  the  8088 processor using two different  software  packages. 
Another  frontier for me was linking a program written in  Pascal 
to the files that were in assembly code. The hardware design  and 
the mechanical layout also involved some unique ideas for me.  As 
the  design proceeded the various elements came together  nicely. 
The final result saw the hardware and software working  correctly 
to  control  the  train  as  had  been  hoped  in  the   original 
conception. 
















                         WORKS CITED



Mc Kerrow, Philip  John.     "Microcomputers,   Slotcars,   and 
     Education."  IEEE Micro (Feb. 1983): 62-65

Dowsing, Roy, and Peter Seward. "Computer- controlled model
     railway for use in teaching real-time programming."
     Microprocessors and Microsystems (Dec. 1982): 529-533



                           REFERENCES



Berlin, Howard M. The 555 Timer Applications Sourcebook
     Indianapolis, Indiana: Howard W. Sams ,1976

Intel Corporation. iAPX 86/88, 186/188 User's Manual 
     Santa Clara, CA: Intel Literature Department ,1985

Coffron, James W. The IBM PC Connection
     Berkeley, CA: Sybex, Inc. 1984

Morse, Stephen P. The 8086 Primer
     Hasbrouck Heights, NJ: Hayden Book Co. 1978

Angermeyer, John and others. Tricks of the MS-DOS Masters
     Indianapolis, Indiana: Howard W. Sams, 1987

Rector, Russell, and George Alexy.  The 8086 Book 
     Berkeley, CA: Osborne/McGraw-Hill, 1980

RCA. RCA Silicon Power Circuits Manual
     Harrison, NJ: Radio Corporation of America,  1967

Nation Semiconductor. Linear Databook
     Santa Clara, CA: National Semiconductor Corporation,  1982

Norton, Peter, and John Socha. Peter Norton's Assembly Language
      Book  for the IBM PC   New York, NY:
       Prentice  Hall  Press, 1986
                                                                                
                                           