Sealevel Support http://www.sealevel.com/support/category/161 en-us KnowlageBase RSS Generator The Digital I/O Handbook http://www.sealevel.com/support/article/AA-00391

The Digital I/O Handbook
A Practical Guide to Industrial Input & Output Applications

Read Featured Chapters, free online.

Digital I/O Hanbook Image

Digital I/O Explained
Renowned technical author Jon Titus and the President and CEO of Sealevel Systems, Tom O'Hanlan, clearly explain real-world digital input/output implementation from both a hardware and software perspective. Whether you are a practicing engineer or a student, The Digital I/O Handbook will provide helpful insight you will use again and again.

  • Covers a wide range of devices including optically isolated inputs, relays, and sensors
  • Shows many helpful circuit diagrams and drawings
  • Includes software code examples
  • Presents common problems and solutions
  • Detailed glossary of common industry terms

"What I like most is its mix of hardware and software. Most pages have a bit of code plus a schematic. All code snippets are in C. This is a great introduction to the tough subject of tying a computer to the real world. It's the sort of quick-start of real value to people with no experience in the field." - Jack Ganssle, The Embedded Muse, January, 2005.

You can purchase the Digital I/O Handbook for $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase.

Chapter Listing
Click on a chapter title link below, to read that chapter. New chapters will be released monthly, starting with the first chapter in June, 2006.

Chapter 1 - Logic Principles

  • Introduction to digital electronics
  • Current Sinks and sources
  • Buffers and drivers
  • Latches
  • Negative and positive logic
  • All in the family

Chapter 2 - Digital Outputs

  • Introduction to output ports
  • Simple on/off control
  • Using drivers and buffers
  • Relay basics
  • Relays handle more power
  • Optical isolation
  • Solid state relays
  • Control bits and bytes with software

Chapter 3 - Digital Inputs

  • Introduction to input ports
  • Basic TTL inputs
  • Circuit isolation
  • Current sinks and sources
  • LED considerations
  • Monitor high voltages
  • Sense bits with software
  • Flags
  • Put it all together
  • A final note about I/O ports

Chapter 4 - Sensor Interfacing

  • Example 1: Thermal switch
  • Example 2: Level switch
  • Example 3: Hall-effect proximity switch
  • Example 4: Photoelectric sensor
  • Example 5: Shaft encoder
  • Example 6: Output more than 8 bits

Appendix

  • Switch and Relay Configurations

Glossary


]]>
Tue, 05 Jan 2010 17:00:51 -0500
The Digital I/O Handbook - Appendix & Glossary http://www.sealevel.com/support/article/AA-00131

The Digital I/O Handbook
A Practical Guide to Industrial Input & Output Applications

Digital I/O Handbook

Digital I/O Explained
Renowned technical author Jon Titus and the President and CEO of Sealevel Systems, Tom O'Hanlan, clearly explain real-world digital input/output implementation from both a hardware and software perspective. Whether you are a practicing engineer or a student, The Digital I/O Handbook will provide helpful insight you will use again and again.

  • Covers a wide range of devices including optically isolated inputs, relays, and sensors
  • Shows many helpful circuit diagrams and drawings
  • Includes software code examples
  • Presents common problems and solutions
  • Detailed glossary of common industry terms

"What I like most is its mix of hardware and software. Most pages have a bit of code plus a schematic. All code snippets are in C. This is a great introduction to the tough subject of tying a computer to the real world. It's the sort of quick-start of real value to people with no experience in the field." - Jack Ganssle, The Embedded Muse, January, 2005.

You can purchase the Digital I/O Handbook for $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase.

Topics Covered

Appendix
Glossary

Appendix

Switch and Relay Configurations
When you look at the specifications for relays and mechanical switches, you'll find a variety of designations, such as DPST and 3C, associated with them. These designations describe electrical contacts and how they work. A basic on-off light switch, for example, controls one circuit (pole), and it provides a switch contact in only one position (throw). So, engineers call this a single-pole, single throw (SPST) switch. (See Figure A-1 for contact configurations.)

Figure A-1

Figure A-1


A single-pole switch may include an additional contact so it can turn off one device and then turn on another. This type of switch contains a set of single-pole, double-throw (SPDT) contacts. The term "double-throw" refers to a switch that can make connections in either of its two positions. Note that the two circuits in an SPDT switch always share a common signal, or pole.

Switches may include electrically separate "gangs" made up of several poles that act in unison. A double-pole, double-throw (DPDT) switch provides two independent SPDT switches operated by a single actuator. A DPDT switch can control two independent and isolated circuits.

Switches can include many poles, although for more than two poles the nomenclature uses numeric designations. So a 4PDT switch comes with four independent and isolated poles, each with two contacts. A single actuator or switch handle moves all four sets of contacts simultaneously. Keep in mind, though, that just because a switch has several poles, an application need not use them all. An SPDT switch, for example, will work just as well a SPST switch in a simple on-off circuit.

Switch nomenclature also may include designations for momentary switches; devices that either momentarily open (break) or close (make) a circuit. A pushbutton used with a doorbell operates as a normally-open switch. Pushing a normally-closed pushbutton on a lawnmower could open the ignition circuit to stop current from flowing to the sparkplug; in effect stopping the mower's gasoline engine. Momentary switches carry the designations NO for normally-open, or NC for normally-closed. Even momentary switches may come with various contact configurations, so you may encounter spring-loaded switches that offer contacts in DPDT arrangements, for example.

Electromechanical relays also provide a variety of contact configurations such as SPST, DPDT, 3PDT, and so on. But suppose you have a relay with an SPST contact. That simple designation doesn't indicate whether the switch contacts open or close when you energize the relay. You just can't tell how a relay's contacts operate without more information. Relay manufacturers use a different shorthand to designate relay contacts and the action a relay causes.

So, although relays come with standard contact configurations, such as SPDT and DPDT, the industry uses letters A, B, C, and so on, to indicate contact arrangements.

A relay with A-type contacts provides an SPST switch that closes when a circuit energizes the relay.

If you want SPST contacts to open when a circuit energizes a relay, choose one with B-type contacts. You can think of A-type contacts as normally-open (NO) and B-type contacts as normally-closed (NC).

A relay with a SPDT set of contacts-probably the most common relay contact arrangement-carries the C notation. A relay's contact diagram shows the contact arrangement and notes which contacts open or close when a circuit energizes the relay. You will find that information printed on the case of an enclosed relay or in accompanying data sheets.

Relays, like manual switches, can provide multiple sets of isolated contacts that operate simultaneously. So a relay designated 2A would provide two separate NO SPST contacts, and a 2C relay would supply the equivalent of DPDT contacts. You may find relays with other letters that designate specialized contact configurations. A set of D contacts, for example, closes one circuit before opening another, also known as a make-before-break operation.

Glossary

* - When used as a suffix on a signal name, an asterisk indicates a logic 0 causes the named action to occur. An input labeled TEST* requires a logic 0 to cause the TEST action to occur. See also: Negative Logic and /.

/ - When used as a prefix on a signal name, a forward slash indicates a logic 0 causes the named action to occur. An input labeled /RUN requires a logic 0 to cause a RUN action. See also: Negative Logic and *.

Active High - A digital signal that represents active, on, or true when its voltage is higher than the other logic state (low). Active-high signals can range from a few volts DC to as high as 24V DC, depending on the logic family or devices in use.

Active Low - A digital signal that represents active, on, or true when its voltage is lower than the other logic state (high). Active-low signals can range from digital ground to a few tenths of a volt.

Analog - A type of signal that varies continuously (lighter to darker, 4 to 20 mA, and so on), as opposed to a digital signal that can exist in only one of two possible states.

Analog Ground - The location in a system that serves as a reference ground for all analog signals. Some circuits may combine analog ground and digital ground, but most circuits separate them to reduce noise and ground currents.

AND - A logical operation in which the result is true only when all inputs are true. See: Logical AND.

AND Gate - A circuit that performs an AND operation based on the state of its inputs.

ASCII - American Standard Code for Information Interchange, an 8-bit binary code that represents characters and symbols in the Roman (English) alphabet. ASCII includes codes that controlled older communication devices, thus the CRTL key on computer keyboards.

BCD - See: Binary Coded Decimal.

Binary - A numbering system that allows for only two states, usually 1 and 0.

Binary-Coded Decimal (BCD) - The encoding of decimal numbers as four-bit binary values from 00002 for 0, to 10012 for 9. BCD uses only 10 of the 16 4-bit combinations.

Bit-Wise - An operation, usually between two bytes or words, in which corresponding bits take part in an operation.

Boolean Logic - A form of mathematics named after George Boole (1815-1864) who devised formal expressions for AND, OR, and INVERT operations.

Blocking Diode - A diode, also called an isolation diode, that stops, or blocks, current from flowing through a circuit. Typically used in a battery circuit to prevent the reverse biasing of a battery by a more positive power supply.

Buffer - An output device that operates high-current or high-voltage devices. Some manufacturers produce drivers specifically to control devices such as stepper motors or displays. See: Driver.

Buffered - A signal that has passed through a buffer. See: Buffer.

Bus - A group of related electrical signals. 1. A control bus, an address, bus, a data bus, and so on. Some buses carry specific names, such as PCI Bus and Universal Serial Bus (USB). 2. A group of conductors that distribute power.

Capacitor - An electronic component that stores a charge and provides a reserve of power in a circuit. Typically used to smooth variations in a power-supply’s output voltage, and to provide power in the event of brief power failures.

Carry Current - The amount of current a relay’s contacts can safely conduct after the contacts close.

Central Processing Unit (CPU) - The decision-making part of a computer, usually found within a computer’s microprocessor.

Chassis Ground - The ground point in a system, typically on a metal chassis, where signals connect to an earth ground. In most cases, a grounded chassis helps shield circuits from EMI and RFI, and provides a safety connection to ground. This type of ground should not carry current. See also: Analog Ground and Digital Ground.

Coil - The wire-wound electromagnetic core of a relay or solenoid. See also: Relay and Solenoid.

Complement - In logic, an operation in which a logic 1 becomes a logic 0, and vice versa. In binary numbers, the complement of 101100 = 010011.

CPU - See: Central Processing Unit.

Current - A measure of the amount of electron flow in a circuit, typically measured in amperes (A) or milliamperes (mA).

Darlington Output - A configuration of output transistors that can handle high currents. Usually found on the outputs of sensors or buffers that drive relays or solenoids.

Derate - A decrease in the rating of device characteristics, depending on operating conditions.

Digital - A system that uses discrete states to represent information.

Digital Ground - A common 0V ground reference for all digital signals. Digital ground and analog ground systems are usually wired separately to avoid introducing digital noise into the analog circuit.

Diode - An electronic component that lets current flow only in one direction.

Driver - 1. A driver circuit, or buffer, that operates high-current or high-voltage devices. 2. Driver software links application programs and specific I/O devices.

Dry Contact - 1. Metallic contacts in a relay or switch that mechanically touch to make a contact. 2. Contacts through which no current flows. See: Wet Contact.

Earth Ground - The ground point in a system that provides the lowest voltage-reference point, or ""earth."" An earth ground usually connects to a power-line ground, a ground rod, or in some cases, cold-water plumbing. An earth ground should not carry current.

Electro Magnetic Interference (EMI) - Energy induced into a circuit by radiated emissions. EMI may cause unpredictable results. See: RFI.

EMI - See: Electro Magnetic Interference.

Excitation Voltage - A voltage that powers a sensor or transducer.

Energize - To provide power to a device or circuit. Typically to power a relay coil, thus forcing it to change the state of its contacts.

Flag - 1. An electronic device, usually with two possible states, that signals an external event to a computer. 2. An internal CPU indicator that signals a condition such as register overflow or error. Sensed with software.

Flip-Flop - A bistable logic circuit that changes state due to an input event, generally a clock or pulse signal. A flip-flop remains in that state until the next input event causes it to ""flip"" or ""flop"" to its other state.

Form-A Relay - A relay that supplies normally-open (NO) SPST contacts.

Form-B Relay - A relay that supplies normally-closed (NC) SPST contacts.

Form-C Relay - A relay that supplies normally-open and normally-closed SPDT contacts.

Gate - A logic device that performs Boolean-logic operations.

Gated - A signal that is enabled, allowed to operate, or allowed to pass through a circuit depending on the state of a separate logic condition or signal.

Ground - A zero-volt reference point in a system. Provides the reference for all other voltages.

High Impedance - 1. A high resistance that reduces current flow. 2. A third state in special logic devices that "disconnects" them from a bus.

High-Side Switch - A switch that makes a connection directly to power at a higher voltage than that at the controlled load.

Impedance - Similar to resistance, an impedance represents the total opposition to the flow of current offered by a circuit. Impedance equals the vector sum of resistance and reactance, which is the complex resistance resulting from inductance and capacitance, not just pure resistance. Measured in ohms, and given the symbol, Z.

Inrush Current - A large charging current that flows into a capacitor or circuit when power is first applied.

Interposing Relay - A relay that isolates the circuit driving it, and switches a higher current or voltage than the driving circuit could provide. See: Relay.

Inverter - A logic device that complements the logic state of its input. See: Complement.

I/O - Input/output, as in I/O port. See: Port.

Isolation - A condition that separates circuits so no current can flow between them. Special devices such as opto-couplers provide a signal path between two circuits, but without current flow between them.

Latch - A logic circuit that takes a ""snapshot"" of information and saves it. Latches operate using an edge-triggered or a level-triggered control signal.

LED - See: Light-Emitting Diode.

Light-Emitting Diode (LED) - A diode that emits light when current passes through it (forward biased). LEDs provide white light as well as most colors. LEDs usually require an external current-limiting resistor.

Logical AND - A Boolean-logic operation that produces a true output only when all the function or circuit inputs exist in the true state.

Logical OR - A Boolean-logic operation that produces a false output only when all the function or circuit inputs exist in the false state.

Logic Ground - A ground-reference point in a circuit for all logic signals. Usually kept separate from other grounds in a system due to noise concerns.

Low Impedance - A low-resistance circuit that usually requires high current to drive it, as opposed to a high-impedance circuit.

Low-Side Switch - A switch that makes a connection directly to ground.

Mask Byte - A combination of 1’s and 0’s used in a bit-wise logical operation to set or clear individual bits. Masks can exist as any integer value, such as byte, word, long word, and so on.

NAND Gate - A circuit that performs a NOT-AND operation based on the state of its inputs. This gate performs an AND operation and inverts (NOTs) its output.

Negative Logic - A notation that indicates a logic 0 represents the active state for a signal.

Non-Buffered - An unbuffered signal that should not drive more than a few inputs within its logic family. See: Buffered.

NOR Gate - A circuit that performs a NOT-OR operation based on the state of its inputs. This gate performs an OR operation and inverts (NOTs) its output.

Normally-Closed (NC) - Relay or switch contacts that normally form a complete low-resistance path for current flow. In an unenergized relay, a set of closed contacts.

Normally-Open (NO) - Relay or switch contacts that normally do not make contact. In an unenergized relay, a set of open contacts.

NOT - The equivalent of an inversion operation, usually applied as part of another logic element or operation. See: Inverter.

NPN - A type of transistor often used as an on-off switch in electronic devices. An NPN switch usually sinks current from a higher potential through a device to ground.

Open Collector - A logic device or sensor that provides an output transistor with an unconnected collector. When turned on, this transistor sinks current to ground, but it cannot source any current. An open-collector output usually serves as a switch to ground.

Optical Coupler - See: Opto-Coupler.

Optical Isolator - See: Opto-Coupler.

Optical Isolation - The use of a light path to transfer a signal from a transmitter, usually a light emitting diode (LED), to a receiver, usually a phototransistor. This technique provides electrical isolation as a signal passes from one circuit to another.

Opto-Coupler - A device that uses light emissions to cause an isolated output stage to turn on. This device allows detection and sensing of potentially dangerous or high voltage signals, while providing isolation and protection to the circuitry sensing them.

Opto-Isolator - See: Opto-Coupler.

OR - A logical operation or circuit in which the result is false only when all inputs are false. See: Logical OR.

OR Gate - A circuit that performs an OR operation based on the state of its inputs.

Overload Protection - The capability to protect a circuit when current exceeds a predetermined value. Devices such as fuses or circuit breakers automatically disconnect a load when they sense an overcurrent.

PNP - A type of transistor often used as an on-off switch in electronic devices. A PNP switch usually sources current from a positive supply to a device at a lower potential.

Port - A collection of signals that go to or from a computer for the input or output of information. For example, an 8-bit input port or a serial port.

Positive Logic - A notation that indicates a logic 1 represents the active state for a signal.

Pull-Down Resistor - A resistor used to pull a logic input ""down"" to the low state, or logic-0 state, thus preventing a disconnected input from floating into an undetermined state.

Pull-Up Resistor - A resistor used to pull a logic input ""up"" to the high state, or logic-1 state, thus preventing a disconnected input from floating into an undetermined state.

Radio Frequency Interference (RFI) - Unwanted high-frequency signals, often generated by switching circuits, power supplies, computer cables, and oscillators. RFI may interfere with the proper operation of other circuits.

Reed Relay - A small relay comprising two magnetic contacts within a sealed glass envelope. When energized, a coil around the envelope moves the contacts to make a low-resistance connection. See: Relay.

Relay - A device that opens or closes a circuit under control of a separate and isolated circuit. A mechanical relay uses a coil to actuate mechanical contacts. A solid state relay uses electronic devices to open or close circuit paths. Both types of relays isolate the controlling circuit from the circuit the relay controls.

Resistance - The total amount of opposition to current in a circuit. Resistance carries the units of ohms and the Greek symbol omega, Ω. Resistance values may have units of kilohms, kΩ or megohms MΩ. See: Resistor.

Resistance Temperature Detector - A stable, linear temperature detector that provides a varying resistance in direct proportion to temperature changes.

Resistor - A device that opposes or limits current flow. Usually noted in schematic diagrams as R. See: Resistance.

RFI - See: Radio Frequency Interference.

RTD - See: Resistance Temperature Detector.

Sensor - A device that monitors or measures phenomena such as temperature, pressure, light intensity, weight, conductivity, and so on. Sensors may provide digital or analog output proportional to the phenomenon measured.

Single-Pole Double-Throw (SPDT) - A three-terminal switch or relay in which one central terminal connects to either one of the other two terminals. This type of switch can alternately connect a signal to one of two devices.

Single-Pole Single-Throw (SPST) - A two-terminal switch or relay that can open or close one circuit.

Sink - The ability to allow current to flow through the circuit, usually to ground.

Snubber - A circuit that suppresses inductive ""kickback"" that may result when inductive loads switch off. Unless snubbed, the kickback voltage can harm the device that drives the load. See: Suppression Diode.

Solenoid - An electrical coil equipped with a magnetic core. Energizing the coil moves the core. Removing the current lets the solenoid core return to its normal position. Solenoids move levers, open valves, and so on.

Solid State Relay (SSR) - A solid state circuit that employs devices such as opto-couplers, transistors, and triacs to perform the function of a mechanical relay. See: Relay.

Source - The ability to provide current flow.

SPDT - See: Single-Pole Double-Throw.

SPST - See: Single-Pole Single-Throw.

SSR - See: Solid State Relay.

Supply Current - The total current that a circuit requires from a power supply.

Suppression Diode - A reverse-biased diode placed across a relay or solenoid coil. When the coil loses power, the diode provides a short circuit that quickly dissipates energy stored in the coil.

Surge Current - A high charging current that flows into a power supply filter capacitor or similar circuit as the power is first turned on. Similar to inrush current.

Surge Suppressor - A circuit that limits the effects of power surges. Devices such as metal-oxide varistors (MOVs), zener diodes, and fuses provide this function.

Switch - An electronic or mechanical device that can connect one signal to a series of connections. Switches ideally have zero impedance when closed and infinite impedance when open.

Thermocouple - A temperature transducer made of two dissimilar metals welded together at one point to form a junction that, whenheated in a complete circuit, generates a small voltage proportional to the junction temperature.

Three State - An output from a logic device that can exist in one of three states; logic 0, logic 1, or a high-impedance (disconnected) state. This latter state allows multiple outputs to connect to one signal, effectively providing a "bus" that many signals can share. Three-state devices will provide an output-enable signal that either connects logic signals to the device’s outputs, or places the outputs in a high-impedance state. (National Semiconductor owns the trademark, "tristate™," although the term finds common use among designers.)

Transistor-Transistor-Logic (TTL) - The type of circuit used in the popular 7400 logic-device families.

Transparent Latch - A latch that passes signals from its inputs to its outputs as long as its Enable signal remains active—usually logic 1. When the Enable signal changes to its inactive state—usually a logic 0—the latch closes and then the outputs remain as they were when the Enable signal changed from logic 1 to logic 0. In effect, this IC acts like a small memory.

Triac - A semiconductor switch that can control devices powered by AC current.

Truth Table - A table that shows all possible input and output conditions for a logic element such as a gate or flip-flop. This table may show binary states as well as clock and signal transitions.

TTL - See: Transistor-Transistor-Logic.

VA - See: Volt-Ampere.

VCC - The symbol for the positive supply voltage in a circuit. Also noted as VCC.

Volt - The unit of potential difference or electromotive force, abbreviated V. One volt represents the potential difference needed to produce one ampere of current through a resistance of one ohm.

Voltage - The term used to designate electrical potential that causes current to flow.

Volt-Ampere - The unit of apparent power in an AC circuit containing capacitive or inductive reactance. The apparent power is the product of source voltage and current. Abbreviated VA.

Watt - The unit of electrical power required to do work at the rate of one joule per second. One watt of power is expended when one ampere of direct current flows through a resistance of one ohm. Abbreviated W.

Wet Contact - 1. Mercury-wetted contacts in sealed reed relays. When the contacts meet, the surface tension of the mercury draws the contacts together and forms a low-resistance path for low-level signals. In effect, the small amount of mercury ensures low-resistance contacts for low-level signals that don’t clean the contacts. 2. Contacts through which current flows. See: Dry Contact.

Zero-Crossing Detector - A circuit that detects when an AC voltage signal has reached zero volts. Switching a circuit at this time reduces inrush currents and minimizes any EMI or RFI produced during switching.


For more information
We hope you found the Appendix & Glossary useful. To go back to the Main Page, click here.

You can purchase the complete Digital I/O Handbook for only $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase. You can find a listing of all Sealevel Digital I/O products by clicking here.


]]>
Wed, 09 Dec 2009 13:53:47 -0500
The Digital I/O Handbook - Chapter 4 http://www.sealevel.com/support/article/AA-00130

The Digital I/O Handbook
A Practical Guide to Industrial Input & Output Applications

Digital I/O Handbook

Digital I/O Explained
Renowned technical author Jon Titus and the President and CEO of Sealevel Systems, Tom O'Hanlan, clearly explain real-world digital input/output implementation from both a hardware and software perspective. Whether you are a practicing engineer or a student, The Digital I/O Handbook will provide helpful insight you will use again and again.

  • Covers a wide range of devices including optically isolated inputs, relays, and sensors
  • Shows many helpful circuit diagrams and drawings
  • Includes software code examples
  • Presents common problems and solutions
  • Detailed glossary of common industry terms

"What I like most is its mix of hardware and software. Most pages have a bit of code plus a schematic. All code snippets are in C. This is a great introduction to the tough subject of tying a computer to the real world. It's the sort of quick-start of real value to people with no experience in the field." - Jack Ganssle, The Embedded Muse, January, 2005.

You can purchase the Digital I/O Handbook for $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase.


Chapter 4 - Sensor Interfacing

In Chapter 3 you learned how to set up a computer to acquire data from electronic devices. In this chapter, you'll learn more about connecting, or interfacing, several types of sensor outputs to a computer.

Topics Covered

  • Example 1: Thermal switch
  • Example 2: Level switch
  • Example 3: Hall-effect proximity switch
  • Example 4: Photoelectric sensor
  • Example 5: Shaft encoder
  • Example 6: Output more than 8 bits


Example 1. Thermal switch
A thermal switch such as a Klixon Series 6786 from Texas Instruments (www.ti.com) provides a snap-action metallic disk that responds to temperature changes. At a specified temperature, the disk either makes or breaks an electrical contact, depending on the model. Buyers can specify an operating temperature and whether the thermal switch provides a normally-open (NO) or normally-closed (NC) contact. When the switch reaches the specified temperature, an NC switch will open and an NO switch will close.

Assume you have a NO switch that operates at 40°C (104°F). When the contacts close, you want a computer to start a process, say, turn on a fan. Because the switch supplies uncommitted contacts — no connections to power or ground — you can connect the switch to a computer in several ways, as shown in Figure 4-1a-d. In this type of application, it’s unlikely the circuit needs to debounce the switch.

Figure 4-1

Figure 4-1
A simple on-off SPST switch can connect to a computer interface either directly or through an optical isolator. The direct connection should limit the distance from the switch and the interface to a few inches.

If the switch forms part of the computer’s circuitry, perhaps as part of a controller that keeps the computer cool, the circuit probably can use a power supply in common with the computer, as shown in Figures 4-1a, -1c and -1d. (Note the use of a Schmitt trigger in one circuit.) This device "cleans up" the edges of the logic transitions produced by the switch to provide a "clean" TTL-compatible signal. If the thermal switch exists at some distance from the computer, consider using an optical isolator, as shown in Figure 4-1b.

Switches with SPST contacts exist in many other devices, such as magnetic sensors, float switches, and air-flow sensors. The circuits developed in this example should work well with them all. Most temperature-sensitive switches exhibit an effect called hysteresis. In a typical switch, the contacts close at, say, 40°C (104°F), but they don’t reopen until the temperature decreases to 35°C (95°F), as shown in Figure 4-2. Thus, the thermal switch will not rapidly open or close as the temperature hovers around 40°C. The temperature must decrease to 35°C to reset the switch. This built-in effect keeps a computer from trying to regulate a temperature within a degree or two of its setpoint. Even home heating and cooling thermostats provide a few degrees of hysteresis. If they didn’t the heat and air conditioner would go on and off in short cycles.

Figure 4-2

Figure 4-2
Many sensors exhibit some form of hysteresis. In this example, a thermal switch closes its contacts at 40°C. As the switch cools, the contacts open only when the switch reaches 35°C. Hysteresis may have a narrower range, depending on the sensor and its application.


Example 2. Level switch
A capacitive level detector provides a SPDT switch as its output indicator. The specification sheet provides information about how the detector works and it shows the switch’s operation when the detector senses a change in capacitance near the probe. The detector operates an internal relay that provided a set of SPDT contacts, so you can treat the sensor’s outputs just as you would the thermal switch shown in Figure 4-1.

Because the switch offers SPDT contacts, you decide to add a cross-coupled NAND gate, as shown previously in Figure 3-4, to debounce the switch. In theory, that circuit will work, but the wires that connect the SPDT switch to the cross-coupled NAND gates may have to run for a considerable distance. Unfortunately, most TTL signals should not run more than about 10 inches from one device to another! So, we recommend you use one of the optically isolated circuits shown in Figure 4-1.

If you sense a level using a float switch, a capacitance switch, or similar sensor, remember that liquids can slosh around in containers and that pumping and draining may cause liquid levels to fluctuate. Without some built-in hysteresis, a level switch can turn on and off when it detects every slight disturbance in liquid level. Sensor specification sheets should specify the hysteresis range for an on-off sensor.

If a sensor does not include some form of hysteresis, software can often "even out" a switch signal to determine whether or not its contacts are closed. When the software detects a switch closure (or opening), instead of immediately taking action, the software can wait briefly and test the switch several more times with a short delay between tests. This type of software filtering or "debouncing" proves helpful when you can’t find a suitable sensor with hysteresis, or if you can’t easily debounce a switch with electronics.

The following program listing shows how software could test a switch several times in a subroutine. In this example, the software must detect a logic 0 from the switch (at bit D2), seven times in a row, with a 10-millisecond delay between tests. The logic-0 state indicates a switch-closed condition. A subroutine (not shown) provides a 10-millisecond delay between tests of the switch’s state.

Dim max_count As Byte
Dim switch_count As Byte
Dim switch_mask As Byte
Dim switch_port As Integer

max_count = 7
switch_mask = &H02 '00000010
switch_port = 135

'Switch-debounce subroutine
Sub Switch_check
switch_count = 0 'Initialize counter
For loop = 1 to max_count


If (inportb(switch_port) AND switch_mask = 0)


Then


(switch_count = switch_count + 1)

End If

milli_sec_delay 10 'Millisecond-delay subroutine call

Next

If max_count = switch_count

Then 'Switch closed, so do this...

End If

End Sub

Each time through the test loop, the software increments a switch_count variable if it detects a logic-0 from the switch. If at the end of seven tests, the switch_count equals the number of passes through the loop, max_count, the software assumes the switch really exists in its closed state.

As an alternate approach, the software could test for, say, five proper states out of seven tries in the loop. To do so, substitute the following four statements for the last four in the listing above:

If (max_count - 2) <= switch_count 'OK if at least



'5 of 7 tests

Then 'Switch closed, so do this... 'detect a switch

'closure
End If

End Sub

Before we leave this example, two notes about programming:

  1. Most switches will stop bouncing in under 10 milliseconds, so your application software may not need to go to the extremes shown above. We included the code as a teaching example. Some switches, though, can bounce for as long as 1/6th or 1/5th of a second! (Refs. 1 and 2.)
  2. If you need to debounce several switches in software, you can set up a subroutine for each one. Or, you can set up a general switch-test subroutine, procedure, or function that can accept arguments (values) transferred to it. These values include max_count, switch_mask, and switch_port for each switch you need to test. This approach makes it easy to change your parameters without having to rewrite the switch-test code for each switch.


Example 3. Hall-effect proximity switch
Semiconductor Hall-effect switches respond to changes in magnetic fields, so designers use them to detect the proximity of ferro-magnetic materials. These solid state switches act rapidly and can detect thousands of changes per second, so they find use in applications that count revolutions on a mechanical shaft, detect the presence of a magnet, and so on.

Several Hall-effect switches from Phoenix America (www.phoenixamerica.com) and Allegro Microsystems (www.allegromicro.com) provide "open collector" outputs. How can this output connect to an input port? This type of output comes from an NPN transistor that connects a circuit to ground, and it will readily provide a signal to an input port.

Many Hall-effect switches require an external power source. For these switches, you can choose to connect the ground from that power source to your computer system ground and directly connect the switch as shown in Figure 4-3a. That circuit will work when you can make a short-distance connection between your computer system and the switch. We recommend using the optically isolated circuit shown in Figure 4-3b because it keeps the Hall-effect switch’s power isolated from the computer. If you use an optical isolator in your interface circuit, the Hall-effect switch’s external power supply can provide current to drive the LED.

Figure 4-3

Figure 4-3
A Hall-effect switch with an NPN output transistor (open collector) sinks current to ground. The switch can use either a direct connection or an optically isolated connection to an input port.


Example 4. Photoelectric sensor
Commercial photoelectric sensor modules, such as those in the CX Series from Automation Direct (www.automationdirect.com), detect the presence or absence of an object in a light beam. Some detectors provide a built-in light source and rely on reflections from an object. Other sensors require a remote light source and detect objects that interrupt a light beam. The sensor manufacturer offers models with four output options: NPN NO, NPN NC, PNP NO, or PNP NC. How can you interface these sensors to a computer?

First, the NC and NO refer to the output as either normally closed or normally open, respectively. So, think in terms of a normally-open or normally-closed switch.

Second, the PNP and NPN refer to the type of transistor on the output. An NPN transistor sinks current to ground while a PNP transistor sources current from a higher potential. Treat these outputs as you would any other NPN or PNP output. The CX Series photoelectric sensors provide a power source, so use an optical isolator to separate the sensor circuits from the computer circuits as shown in Figure 4-4.

Figure 4-4

Figure 4-4
Some photoelectric sensors offer a choice of PNP or NPN outputs. This schematic diagram shows how to connect either output type to an input port through an optical isolator.


Example 5: Shaft encoder
Incremental shaft encoders produce a fixed number of pulses or "counts" per revolution of a central shaft. Manufacturers offer a range of encoder types that offer various counts/revolution (CPR)—from 35 CPR to several thousand CPR. The phase of the output pulses establishes the direction of the shaft’s rotation and its relative position. A 1000 CPR encoder that produces a series of 212 pulses lets you determine the shaft has moved 360° * 212/1000, or 76° from its previous position.

This type of incremental encoder does not provide an absolute position of, say, 95°. It only provides an indication of the distance moved from the previous position. (By measuring the rate at which pulses occur, you can determine the rotational speed of the shaft.)

An incremental encoder produces two square-wave outputs that an external counter can accumulate to determine the relative change in a shaft’s position. The lead-lag phase relationship between the two square waves indicates whether a shaft rotates clockwise or counterclockwise, as shown in Figure 4-5. A D-type flip-flop can use the out-of-phase signals to produce a "rotation" signal. The circuit shown includes two 74HCT4538 monostable circuits that combine to produce a short pulse for each transition on the A or B square wave.

Additional circuitry, perhaps a 10- or 12-bit up-down counter (not shown), can use these pulses and the flip-flop’s direction signal to keep track of the shaft’s position. Microcontrollers that can connect directly to an incremental encoder can handle the counting through software.

Figure 4-5

Figure 4-5
The phase relationship between square waves produced by a shaft encoder lets a flip-flop IC determine rotation direction. A pair of monostable ICs produces a pulse for each transition on the A or B output from the encoder.

Some incremental encoders include an optional index output that produces a single short pulse at one point in a complete rotation. Circuitry can use this pulse to reset a count or increment a separate "turns" counter. US Digital (Vancouver, WA; www.usdigital.com) provides a variety of encoders and interface ICs that can simplify the design of interface circuits. We won’t go into more detail on how rotary encoders operate.

Assume for the moment you have purchased or designed an external counter circuit for an incremental encoder with 1024 counts/revolution. That means each complete rotation of the encoder’s shaft will produce a 10-bit binary count: 210 = 1024. So far, input ports have acquired data in 8-bit bytes, so how can a computer input 10 bits from a counter? You can split the 10 bits into an 8-bit byte at one input port, and route the remaining two bits to another input port, as shown in Figure 4-6. (We have shown the unused bits at input port 202 connecter to logic 1; +5V through a pull-up resistor.)

Figure 4-6

Figure 4-6
Two input ports let software gather data from a device that puts out more than eight bits. If the data can change rapidly, this arrangement can lead to errors.

This arrangement may run into problems because it requires two input operations, separated by a finite time. To illustrate the potential problem, assume a split of a 10-bit value 00111101012 (245) into 00, the two most-significant bits, and 111101012, the eight least-significant bits. Several counts, each incremented by 1 appear as:

00 11110101 (245)
00 11110110 (246)
00 11110111 (247)
00 11111000 (248)
00 11111001 (249)
and so on...

Assume the software first acquires the least-significant eight bits, D7—D0 at input-port 203 and then acquires the two most-significant bits, D9—D8 at input-port 202.

Given a count of 00 111101012 at the encoder’s circuit, you would expect to find those bits in the computer after the two input-port commands execute. As long as the data remain constant between the two input commands, you’ll see the expected result.

But suppose a mechanism moves the shaft between the time the software acquires bits D7—D0 and when it acquires bits D9—D8. The movement adds 20 pulses to the count, which goes from 00 111101012 (245) to 01 000010012 (265). That change represents a rotation of only about 7°. The steps below show what happens in this case:

  1. The computer acquires the eight LSBs: 00 111101012
  2. A mechanism rotates the shaft and the counter increments its count by 20 to produce a new count of: 01 000010012
  3. The computer now acquires the two MSBs: 01 000010012

Now, when the computer combines the binary values, it turns into:
01 111101012, which is WRONG!

The motion of the shaft between the two input operations caused the problem. Granted, this condition won’t occur frequently, but without some way to prevent it, you will never know when it has occurred!

Any circuit that must transfer more than eight bits at a time, from a single source such as a counter, must first latch the entire n-bit value into a set of latches or D flip- flops as shown in Figure 4-7. The 74LS374 inputs provide D flip-flops that latch the data (controlled by the CLK inputs). The 74LS374 ICs also provide three-state outputs (controlled by the /OC inputs). So the same ICs provide the latch and three-state logic functions. Some devices, such as digital meters, may provide latched outputs, but they may lack three-state outputs.

Figure 4-7

Figure 4-7
The 74LS374 ICs in this circuit first latch all 10 bits and then transfer a byte at a time to a computer. Latching the bits provides stable data for the software to acquire.

To start an acquisition, the computer first latches the entire 10-bit value from the counter by strobing both 74LS374 ICs with the OUT231 pulse. In this case, the output-port instruction such as outportb(231, n) simply generates the latch-control pulse. Although the 8-bit value for n goes out on the data bus, no device actually uses it. So it doesn’t matter what value you use for n. Software often uses output-port commands to create a pulse for use in an interface circuit.

After latching the entire 10-bit value simultaneously, the computer can gather the bits from input ports 202 and 203 and reassemble them with software. Any changes of the counter’s outputs will not affect the data saved in the latch. After acquiring the two bytes from input ports 202 and 203, how does the software recombine them into a value an application program can use?

The software below shows the needed operations. The software needs two bytes to save input-port data and an integer value (16 bits) to save the final 10-bit count:

Dim counter_value As Integer
Dim MS_bits As Byte
Dim LS_bits As Byte

outportb(231, 0) 'Latch all bits
MS_bits = inportb(202) 'Get bits D9-D8
LS_bits = inportb(203) 'Get bits D7-D0
MS_bits = MS_bits AND &H03
counter_value = LS_bits + (256 * MS_bits)

The last statement multiplies the decimal value of bits D9 and D8 by 256 to compute the value they represent at the counter. Then the statement adds them to the decimal value of bits D7—D0. The result, counter_value, will have a value of 0 to 1023. Remember, the computer "sees" bits D9 and D8 at positions D1 and D0 at input port 202. The input port and the computer have no knowledge of the "weights" of these bits as they come from the 10-bit counter circuit. You must track their value and reconstruct it using software.

But why does the sequence of commands include a bit-wise AND with a mask of 000000112? That bit-wise AND operation ensures bits D7—D2 in the MS_bits byte get set to zero so they will not get used in calculation of the 10-bit count value. The circuit in Figure 4-7 forced the unused bits at input port 202 to logic 1, so the bit-wise AND clears them to logic 0. Couldn’t the circuit have simply forced the bits to logic 0 (ground) to save the trouble of using a bit-wise AND? Of course. But we would have included the logic operation in any case. Never assume you know the state of unused bits. Always play it safe and mask off any unused or unneeded bits.

At some point, an engineer might decide to use some of the "unused" bits at port 202 to detect flags or input switch data. Masking out those bits while writing the software ensures you won’t have difficulties later due to later unplanned changes in circuits.


Example 6: Output more than 8 bits
Simultaneously transferring more than eight bits to an external device may cause timing problems much like those experienced in the incremental-encoder example. Although two output ports handle 16 bits, software can update only one port at a time. So, if an output device requires that an interface circuit apply more than eight bits simultaneously, first set up an n-bit latch that acquires all n bits at one time. Then use as many output ports as necessary to "feed" data to that latch, one byte at a time.

Figure 4-8 shows a circuit set up as an interface for a 12-bit device. The circuit uses a 74LS374 D-flip-flop IC for output port 003 and another 74LS374 IC as output port 004. The pair of 74LS374 ICs on the right side of the circuit forms an intermediate 16-bit latch that will simultaneously transfer all data from the output ports to the 12-bit device. (The circuit does not use four of the output bits. Never tie unused ports to +5V or ground!)

Figure 4-8

Figure 4-8
A double-buffered interface circuit lets two 8-bit output ports produce data for simultaneous transfer to a 12-bit device. Many output devices come with built-in double buffers.

To perform a transfer, software first sends individual bytes to ports 003 and 004 and then simultaneously transfers all the data to the 12-bit device by using an outportb command for port 005. Keep in mind the needed outportb(005, n) command serves only to generate the OUT005 pulse. Although the command transfers byte n onto the computer’s data bus, no device uses it, so the value of n is immaterial.

This technique often goes by the name "double buffering," and many manufacturers provide the necessary double-buffer circuits in their devices. The Analog Devices (Norwood, MA; www.analog.com) AD5341 12-bit digital-to-analog converter (ADC), for example, includes double buffering in the chip so 8-bit microprocessors and microcontrollers can use the IC without external circuitry.

Before software can send more than eight bits to an external device, it must "split" the data into the various 8-bit bytes, and math and bit-wise-logic operations help. (We’ll assume a 16-bit value, but the techniques apply to higher bit counts, too.)

For this example, start with the 16-bit value 525 or 00000010000011012, which software must split into two bytes: 000000102 and 000011012 for transfer to the output ports. To get the least-significant byte, use the modulus operation: mod in Visual Basic and % in C/C++. This operation performs modulus division and produces the remainder of a division. So, when software performs the operation:

525 Mod 256

the result yields a remainder of 13 (000011012), the lower byte. Then, software can divide the entire value 525 by 256 and force the result of that operation into an integer value to strip off the remainder:

525 / 256 = 2.05078 and then Int(525 / 256) yields 2

to yield the upper byte 000000102.

Logical operations also can split a 16-bit value into two bytes. Again start with the value 525 or 00000010000011012. Perform a bit-wise AND with 255 and the lower byte "falls through" the mask:

0000001000001101
0000000011111111

0000000000001101

Then move the remaining value into an 8-bit integer to obtain the lower byte: 00001101

Next, use a mask on the upper eight bits:

0000001000001101
1111111100000000

0000001000000000

and divide by 256, which in effect shifts all the bits to the right by eight positions:

0000000000000010

Move the result into an 8-bit integer value to obtain 000000102.



CAUTION: Before you apply math or bit-wise logic operations, always check the language specifications to:
  1. Ensure its math operations perform the mod and int functions.
  2. Ensure you can use 16-bit unsigned integer value.
In most cases, you can use other programming steps to perform the same operations, although they may get more complex. Always test your routines with known data. We recommend you always check conversions and I/O operations for any error conditions-such as using an integer instead of a byte value, trying to output a negative value, and so on. Better to check thoroughly with test data than to dump the wrong chemical into a reaction or send a space probe off course due to a software error.


References

  1. Ganssle, Jack G., "The Secret Life of Switches," Embedded Systems Programming, April 2004. pp. 61—64. (www.embedded.com)
  2. Ganssle, Jack G., "Solving Switch Bounce Problems," Embedded Systems Programming, May 2004. pp. 45—64.


For more information
We hope you found the Chapter 4 informative. To go back to the Main Page, click here.

You can purchase the complete Digital I/O Handbook for only $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase. You can find a listing of all Sealevel Digital I/O products by clicking here.


]]>
Wed, 09 Dec 2009 13:53:28 -0500
The Digital I/O Handbook - Chapter 3 http://www.sealevel.com/support/article/AA-00129

The Digital I/O Handbook
A Practical Guide to Industrial Input & Output Applications

Digital I/O Handbook

Digital I/O Explained
Renowned technical author Jon Titus and the President and CEO of Sealevel Systems, Tom O'Hanlan, clearly explain real-world digital input/output implementation from both a hardware and software perspective. Whether you are a practicing engineer or a student, The Digital I/O Handbook will provide helpful insight you will use again and again.

  • Covers a wide range of devices including optically isolated inputs, relays, and sensors
  • Shows many helpful circuit diagrams and drawings
  • Includes software code examples
  • Presents common problems and solutions
  • Detailed glossary of common industry terms

"What I like most is its mix of hardware and software. Most pages have a bit of code plus a schematic. All code snippets are in C. This is a great introduction to the tough subject of tying a computer to the real world. It's the sort of quick-start of real value to people with no experience in the field." - Jack Ganssle, The Embedded Muse, January, 2005.

You can purchase the Digital I/O Handbook for $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase.


Chapter 3 - Digital Inputs

Topics Covered

  • Introduction to input ports
  • Basic TTL inputs
  • Circuit isolation
  • Current sinks and sources
  • LED considerations
  • Monitor high voltages
  • Sense bits with software
  • Flags
  • Put it all together
  • A final note about I/O ports


Introduction to input ports
Few computers can operate without connections to external devices such as sensors, switches, or other equipment that informs software about external conditions. Computers also receive data from keyboards, disk drives, touchscreens, and similar devices, all of which transfer their information to a computer through a device called an input port.

You can think of many practical uses for input ports. Imagine a controller that counts parts on a conveyor belt. An electronic counter in the controller would provide data that a computer could obtain from an input port. Similarly, an input port connected to a digital thermometer would let a computer read temperature values at any time. The computer simply retrieves the specified data as requested by a software command.

At its simplest, an input port acts like a "gate" that lets information pass from an external device to a computer’s data bus at a specific time. The central processing unit (CPU), or its control circuits, provide a unique strobe pulse for each input port. That pulse "tells" a port when to transfer data onto the data bus so the CPU can capture it. To control the transfer of data from an input port to the computer, the computer requires a port-control command that identifies a specific port. Only one device can use the bus at a time.

Figure 3-1 shows a typical input port. Any information present at the port’s eight inputs gets transferred to the CPU when the strobe pulse, IN303*, arrives. The single 74LS244 IC used in the example contains two independent 4-bit circuits. We’ve used them to form a complete 8-bit input port. Other TTL devices work equally well. (Our port-number assignments carry no significance and simply serve as examples. You can use port numbers within the ranges specified for the computer and software you plan to use. Some computers reserve I/O port numbers for internal and future use.)

The input port shown in Figure 3-1 might accept signals from on-off switches or other devices that produce TTL-compatible signals. As always, the external signals, the input-port circuits, and the computer must share a common ground.

Figure 3-1

Figure 3-1
A simple 8-bit input port places information on the bus only when the computer places a short logic-0 pulse on the IN303* line. At other times, the port "disconnects" from the bus using three-state logic.

To avoid conflicts on the CPU bus, input ports must "connect" themselves to the CPU data bus only when they receive the proper strobe pulse. At all other times, they must "disconnect" from the bus. The disconnect operation requires special gates with three-state outputs. These gates provide the normal logic-1 and logic-0 outputs, and they also provide a disconnected or third state. In this state, they appear electrically disconnected from the data bus. You may hear designers refer to similar devices called three-state bus drivers or three-state buffers. These devices provide the capability to disconnect outputs from a bus or other conductor that carries signals from several sources.

Transfer of data from an external device through an input port to a computer requires a software command. This command causes the computer to generate the needed strobe pulse at the input port so that the port data flows onto the bus:

portdata = inportb(input_port_number)

The general command above addresses a specific port (input_port_number) and assigns the data from the port to a variable, in this case, portdata.

The following command would obtain data from the port shown earlier in Figure 3-1:

abcxyz = inportb(303)

Software examples in this chapter illustrate byte transfers, and they assume, unless shown otherwise, that a programmer has defined variables, such as input_port_number, portdata, and abcxyz to hold values. After acquiring the data from an input port, additional software commands can use the information to make decisions.

In essence, an input port takes a "snapshot" of the information present at the port when the port’s strobe pulse arrives from the CPU. The computer does not wait for data to arrive at the port from an external device; it simply says to the input port, "Give me what you have now."

The inportb command shown above does not exist within some programming languages such as Visual Basic. Each manufacturer of add-in cards or devices supplies its own driver software. Drivers come in a library of routines that link a programming language to special operations, such as those that control I/O ports. Thus, drivers define new commands that a programmer can include in code to transfer data from an input port to a CPU.

You must follow instructions included with an I/O board to properly set up accompanying driver software. The setup process lets your application program know how to find and use the drivers on the computer hard drive. (The instructions that accompany a board and its drivers provide installation information and information about how to use drivers in your application program.)


Basic TTL inputs
An 8-bit input port can obtain information from on-off switches, encoded switches, sensors, keyboards, and other devices that produce TTL-compatible signals. As with output ports, you can use the input bits in any way you wish, perhaps using four input bits to get data from a hexadecimal keypad, and the remaining four bits for on-off switches, as shown in Figure 3-2.

Figure 3-2

Figure 3-2
An input port can accept data from many sources, such as individual switches and a hexadecimal keyboard. These external devices provide TTL-compatible logic signals and a common ground to the computer.



CAUTION: Digital signals drawn in books often look perfect, but real-world signals usually include some noise and may not meet the electrical specifications for logic-1 and logic-0 signals in a given logic family. So, external digital signals may require some conditioning prior to connecting them to the TTL-compatible inputs at an input port.

You can use a Schmitt trigger circuit, available in most TTL families, to provide some signal conditioning. But first check the specifications for all input ports you plan to use. Some ports may come with built-in Schmitt triggers.




CAUTION: If you plan to connect simple on-off switches or pushbuttons to an input port, you may need to "debounce" the switch contacts. When a pair of mechanical contacts closes, they have a tendency to bounce for a short time. While doing so, the contacts may open several times as shown in Figure 3-3 for a closing SPST switch. Although these bounces end within a few milliseconds, circuits may detect them as several switch closures in rapid succession. In a double-throw switch, the movable contact DOES NOT bounce back and forth between the two stationary contacts; it simply opens and closes the connection at the contact it was switched to.

Figure 3-3

Figure 3-3
If a mechanical switch bounces momentarily, an attached logic circuit may see each bounce as a logic transition.

If necessary, you can build a switch-debounce circuit using a single-pole double-throw (SPDT) switch or pushbutton, a pair of NAND gates, and two resistors, as shown in Figure 3-4. As soon as the movable contact in the switch touches a NAND gate input, the circuit changes its state and remains in that state until the movable contact touches the other fixed switch contact.

Figure 3-4

Figure 3-4
Two NAND gates form a switch-debounce circuit that offers complementary outputs, Q and Q*.

Because the debounce circuit produces two complementary outputs, one from each NAND gate, you can choose whether you want a logic 1 or a logic 0 to represent the normal output of the switch. Remember, the NAND gate circuit and any circuit it connects to, such as an input port, must share a common ground.



Circuit isolation
Although some sensors, instruments, and other devices produce TTL-compatible signals that can directly connect to an input port, many devices do not. You can convert these non-TTL-compatible signals into TTL levels, or you can buy input-port cards that provide the proper "translation" circuits. The easiest and most flexible translation involves using optical isolators, and many input-port boards and modules include these devices. At an input port, the phototransistor connects to the input port’s TTL inputs as shown in Figure 3-5. An external circuit powers the light-emitting diode (LED).

Figure 3-5

Figure 3-5
An optical isolator IC electrically isolates an external circuit from the signals at an input port. This example shows only one bit, and for clarity, the input port shows only bits for D7–D4.

Because the LED offers no direct electrical connection to the input port, it isolates the port (and the computer it connects to) from external devices. Thus, an external circuit can power the LED without regard to specific TTL levels and without a ground in common with the port and the computer. But the external circuit must supply a voltage and current within a specified range to properly operate the LED. Specifications that accompany an optically isolated input-port board or module will help you determine the maximum voltage and current an LED can accept. Because LEDs operate based on current flow, they are less susceptible to noise than standard TTL-compatible inputs.

Some optical isolators provide two "head-to-tail" LEDs in parallel. This arrangement lets you use low-voltage AC or DC to power the LEDs, regardless of the direction of current flow. Remember, LEDs act as diodes, so they allow current flow in only one direction. When an optical isolator requires a signal with a specific polarity (current-flow direction), the power source must match the required polarity.


CAUTION: DO NOT use small AC optical isolators to detect high-voltage signals, such as those in power-line (120V AC or 220V AC) circuits. Special devices can monitor signals at these voltages. Prior to use, always check suppliers’ specifications for LED voltage and current limits.


If you have difficulty getting an optically isolated input port to operate properly:

  • Ensure the circuit properly matches the polarity of the external circuitry and the polarity of the optical isolator.
  • Ensure you have a complete circuit to drive the LED.
  • Ensure the LED-drive circuit will deliver more than the minimum voltage and current needed to turn the LED on.


Current sinks and sources
Not all devices that connect to a computer provide TTL signals or mechanical switch contacts. A sensor may offer an output labeled as a current sink or current source, terms that may confuse users and lead to nonworking interface circuits. To further confuse the issue, some manufacturers use the term NPN sensor for a current sink, and PNP sensor for a current source. The designations NPN and PNP simply refer to the type of transistor the sensor uses as its on-off switch. The circuits in Figure 3-6 show how NPN and PNP sensor outputs can control optically isolated input ports and TTL-compatible inputs.

Figure 3-6

Figure 3-6
Sensors that furnish NPN or PNP transistors on their outputs can power optical isolators. The bottom diagram shows a circuit in which designers supplied an external power supply.

This nomenclature can get confusing, so here’s a way to keep the PNP and NPN designations straight. Think of the first letter in each abbreviation. A PNP device supplies power from the most Positive side of a circuit. On the other hand, an NPN device sinks current to the most Negative side of a circuit. NPN and PNP sensors operate only with DC power.

If you have a sensor that supplies a current-sink, or NPN output, the sensor provides an on-off switch to ground. An external circuit — sometimes included by the sensor manufacturer — provides the current and voltage to drive an LED in an optical isolator. So, you can choose just about any available power source, say, 5V, 12V, 24V, and so on, depending on what power sources your system already includes. Or you can add an external power supply. The manufacturer of the optically isolated input port should include information about the minimum voltage and current specifications for optical isolators.

A sensor that provides a current source, or PNP, output usually provides a connection to a power supply. Unfortunately, you may not have a choice in the selection of the voltage this current source operates from. So, you must ensure that the sensor’s current capability and output voltage are within the limits specified by the input-port supplier.


LED considerations
All LED circuits require a resistor that controls the current through the LED. Many manufacturers of optically isolated input-port boards and modules include a resistor for each input-port bit. Some boards and modules will require an external user-supplied resistor. Check the manufacturer’s specifications for details. Also, always ensure the voltage you plan to use at an input port meet the board manufacturer’s specifications.

Whether a board provides a resistor or requires an external one, simple calculations will determine the needed resistance value for a given voltage. Here’s an example for the Sealevel Systems M240 Optically Isolated Input Adapter. Each of the eight inputs on the board has the same specifications:

Turn-on current (minimum): 3 mA (0.003 A)
Diode voltage drop: 1.1 V
Maximum resistor power: 1 W

turn-on voltage = (diode voltage drop) +  [(turn-on current) * (resistance)]

So, if a sensor provides a 12V DC source, calculate the needed resistance for a 3 mA current flow:

(turn-on voltage) - (diode voltage drop) = Resistance
(Turn-on current)

12 - 1.1 = 3633 ohms
0.003

The M240 board provides a built-in 3300W (1W) resistor that will work fine. (To ensure operation of the isolator, you can increase the current slightly. The optical coupler on the M240 board, for example, can handle a maximum LED drive current of up to 50 mA.)


Monitor high voltages
The small optical isolators furnished at input ports on commercial modules or boards will work with many types of sensors and data sources. But some applications require input ports that can monitor high voltages such as those that control pumps, solenoids, valves, and other devices. In this type of situation, designers rely on commercial plug-in modules specifically designed to offer optical isolation and to operate with high-voltage AC and DC signals.

Manufacturers of the output modules described in Chapter 2 also supply input modules that produce a TTL-compatible signal that indicates the presence or absence of a voltage on a corresponding input. LEDs on the modules indicate the state of each input.

The 1781-IA5Q module from Western Reserve Controls (www.wrcakron.com) or the IAC5Q module from Opto 22 (www.opto22.com) provides four circuits that monitor AC or DC signals between 90V and 140V. A module includes two pairs of input circuits and the two circuits in a pair share a common connection. If you need to monitor two devices that operate from the same 110V AC power source, and the devices share a common ground, the diagram in Figure 3-7 illustrates typical connections.

Figure 3-7

Figure 3-7
An optically isolated input module provides two pairs of separate circuits (right and left). Do not mix AC and DC signals in one section of a module, and do not mix signals that do not share a common connection.

But within a pair of inputs, you cannot mix circuits that do not share a common ground. Also DO NOT mix AC and DC signals in a pair. Separate pairs of circuits can handle AC and DC signals within a module, though. The sensing circuits in these two models produce a logic 0 when they detect a voltage within the manufacturer’s specified limits.



CAUTION: Always use an input module in parallel with a device; NEVER place a module’s inputs in series with the device. A module detects voltage across a device, not current passing through it. See Figure 3-8 for the types of connections you must avoid!


Figure 3-8

Figure 3-8
DO NOT connect an optically isolated input module in series with devices you want to monitor. The input modules operate in parallel with devices, NOT in series.

If you wish to monitor lower DC voltages, devices such as the WRC 1781-IB5Q and 1781-IT5Q modules will handle inputs between 3.3V and 32V DC. You can use these types of modules to monitor DC voltages such as those found in power supplies or computer circuits. A DC-input module could alert a host computer to the lack of power in a subassembly, or it could let a computer know if a DC motor has power applied to it.

Like its sibling AC-DC input module, each DC input module includes two pairs of sensing circuits, and each pair shares a common signal. The WRC 1781-IB5Q module uses a common +DC input, and the WRC 1781-IT5Q module uses a common -DC input.



CAUTION: Although isolation modules often come with built-in LEDS that indicate the state of an input, not all modules clearly label each LED and the circuit associated with it.  The diagram shown previously in Figure 2-12 notes the proper relationship for the quad-circuit modules in the Opto 22 "Quad Pak" family or in the WRC 1781 Quad I/O line of AC-input and DC-input monitoring modules.



CAUTION: Manufacturers of modules and I/O boards may designate the inputs as "channels" 1—8, although the actual bit designations for the input-port bits usually carry the labels 0—7 (for data bits D0 through D7). Bit 0 represents the right-most of least-significant bit (LSB), and bit 7 represents the left-most or most-significant bit (MSB). Table 1 in Chapter 2 shows the relationships between the inputs, the bits, and the binary weights for each bit. To check the inputs at positions 8, 5, and 3 in a positive-logic system, for example, requires checking for a logic 1 at bits D7, D4, and D2.


Sense bits with software
External devices connected to a computer’s input ports have little value until programs can obtain data from them. As noted earlier, a simple software command such as:

portdata = inportb(input_port_number)

will obtain a byte of data from a selected input port. But because that data may include bits from a variety of devices, such as limit switches, fluid-level sensors, motor monitors, and so on, the software must select only the bits needed to make a decision. You can operate on individual bits by using the same sort of bit-wise logic you learned about in Chapter 2.

To illustrate how to obtain information from an input port, examine the diagram in Figure 3-9. In this circuit, a tank-full float switch connects to bit D5 and a pump monitor connects to bit D3. (Bit D3 does not turn the pump on or off, it only indicates the state of the pump.) Assume other sensors and switches use the remaining bits (D7, D6, D4, and D2–D0) at the input port.

Figure 3-9

Figure 3-9
A control system monitors the state (full or not-full) of a tank’s float switch and the state (on or off) of a pump that feeds liquid to a tank.

The two bits of interest at the input port will independently show these conditions:

Float Switch (D5) Pump Monitor (D3)
1 = Tank full 1 = Pump off
0 = Tank not full 0 = Pump on

To check the state of these devices, software first issues the following commands that set up variables and obtain port data:

Dim sensor_monitor_port As Integer
Dim sensor_data As byte
sensor_monitor_port = 303 'Set up port address

sensor_data = inportb(sensor_monitor_port)

The last command obtains eight bits from input port 303. By applying masks to the sensor_data byte the software can isolate individual bits or sets of bits for testing. You may recall the following rules from Chapter 2. (An X indicates a bit can exist as either a logic 1 or 0.)

  1. If you AND bit X with logic 0, the result is always logic 0.
  2. If you AND bit X with logic 1, you get the X bit’s original state.

Here are the rules in column form:

AND AND
X X
0 1


0 X Result

A bit-wise AND with a 0 will force an "unwanted" bit to a logic 0. But a bit-wise AND with a logic 1 will let the state of a bit simply "fall through" to the result. Thus, to check a bit in position D5, use a mask of 001000002 and perform a bit-wise AND with the sensor_data byte to mask all bits except D5.

D7   D0  
0 0 1 0 0 0 0 0 Mask byte for D5 (32, &H20)
0 0 1 1 0 1 0 1 Input-port data


0 0 1 0 0 0 0 0 Result of bit-wise AND (32, or &H20)

Note that the mask forced all bits except bit D5 to a logic 0. So, the result of the AND can yield only 32 (001000002) or 0 (000000002). The result above indicates a full tank. If the float switch of the tank stays closed, to indicate the tank is not full, the result of the AND operation would show:

D7
D0
0 0 1 0 0 0 0 0 Mask byte for D5 (32, &H20)
0 0 0 1 0 1 0 1 Input-port data


0 0 0 0 0 0 0 0 Result of bit-wise AND (0, or &H00)

Software steps could evaluate the result of the bit-wise AND operation to test for a zero value (tank not full) or a non-zero value (tank full). The software also could look for a specific value: 0 for tank-not-full or 32 for tank-full.

Using the bit masks defined in Chapter 2, software to test the float switch might look like this:

Dim sensor_monitor_port As Integer
Dim sensor_data As byte
Dim mask_result As byte
Dim levelsensor_D5_p As byte 'Set up a mask byte

sensor_monitor_port = 303 'Set up port address
levelsensor_D5_p = D5_1 'Set up mask of 00100000

sensor_data = inportb(sensor_monitor_port)
mask_result = sensor_data AND levelsensor_D5_p

Then, software statements can take actions depending on the tank’s level. You do not have to check for any condition other than 0 (000000002) or 32 (001000002) as a result of the bit-wise AND operation. The bit-wise AND operation allows only those two results.

If mask_result = 0

Then... 'Tank not full, so do this...
ElseIf mask_result = 32

Then... 'Tank full, so do this...
End If

The software could also assume if the result is not 0, it must be 32.

If you don’t need the input-port data in another operation, combine the sensor-port input operation and the bit-wise AND operation in one statement:

mask_result = inportb(sensor_monitor_port) AND levelsensor_D5_p

If the program doesn’t need to take action until the sensor indicates a tank-full condition, the software would look like this:

mask_result = inportb(device_monitor_port) AND levelsensor_D5_p

If mask_result = 32

Then... 'Tank full, so do this...
End If

Likewise, if the program should take no action until the sensor indicates a tank-not-full condition, the software would look like this:

mask_result = inportb(device_monitor_port) AND levelsensor_D5_p

If mask_result = 0

Then... 'Tank not full, so do this...
End If

Similar software steps could monitor the pump using a mask for bit D3 (000010002), a bit-wise AND operation, and If-Then-Else statements. In this case, the result of the bit-wise AND would yield either 0 (000000002) or 8 (000010002). A 0 indicates the pump motor is on, and an 8 indicates the pump motor is off. Remember, the decimal value simply represents the binary result of the bit-wise AND operation. The decimal number has no inherent value that makes a resulting "32" more important or of greater value that a resulting "8."

Suppose software must check for a simultaneous pump-on (bit D3 = 0) and a tank-full condition (bit D5 = 1) so it can signal an emergency condition. In that situation, the software could check the float switch, and if it indicates a full-tank condition, it could then check the pump to see if it is on. But that sort of sequential checking can make a program "messy" and difficult to follow. Instead, software can check both flag bits simultaneously.

A bit-wise AND operation can mask more than one bit at a time. To check bit D5 and bit D3, use a mask of 001010002, as shown below:

D7
D0
0 0 1 0 1 0 0 0 Mask byte for D5 and D3 (40, &H28)
1 1 1 0 0 0 0 1 Input-port data


0 0 1 0 0 0 0 0 Result of bit-wise AND (32, or &H20)

The result of the bit-wise AND can produce four combinations because the pump monitor and the float switch can each exist in two states — 22 = 4:

Possible results:

00000000 = Tank not full, pump on
00001000 = Tank not full, pump off
00100000 = Tank full, pump on
00101000 = Tank full, pump off

When the tank is full and the pump is on, the result of the bit-wise AND operation yields 32 (001000002) and when it detects that result, the software should start emergency actions. This portion of the software does not care about the other three conditions shown above. A single If-Then command will monitor for a tank-full and pump-on emergency condition:

full&pump-on_mask = &H28 '00101000

mask_result = inportb(device_monitor_port) AND full&pump-on_ mask

If mask_result = 32

Then... 'start emergency processes...
End If

(This example assumed the definition of variables and constants as shown earlier.)

Note that in the example above, the software tested for a logic 1 from the float switch and a logic 0 from the pump monitor. This "mixture" of logic-1 and logic-0 states occurs often in computer systems. Don’t expect that sensors will always produce a logic-1 in the "on" state and a logic-0 in the "off" state. However, as the software above shows, software can test for any combination of 1's and 0's.

Just know what bits you want to test and set up the appropriate masks. Then determine the pattern of 1's and 0's that indicate the possible conditions and you can set up software to match specific conditions.

The following example shows how to monitor for a logic-0 output from a sensor. You still use masks and bit-wise AND operations to isolate specific bits, but you change the If-Then-Else statements to match different conditions. Suppose a temperature-limit sensor connected to an input port provides the following signal:

Temperature-limit sensor at bit D1

1 = OK

0 = Over limit

The sample code below monitors for the temperature over-limit condition, represented by a logic-0 from the sensor. (The D1_1 value, 000000102, comes from the mask bytes set up in Chapter 2.)

Dim sensor_monitor_port As Integer
Dim temp_sensor_D1_p As Byte 'Set up a variable for a mask
Dim mask_result As Byte 'Set up byte for mask

temp_sensor_D1_p = D1_1 '00000010
sensor_monitor_port = 123 'Set up port address

mask_result = inportb(sensor_monitor_port) AND temp_sensor_D1_p

If mask_result = 0
  Then... 'Temperature above limit, so do this...
End If

These statements mask off all bits except D1 and then take action only if the resulting bit at D1 equals a logic 0 — temperature over limit. To monitor for a  temperature-OK condition, use an If-Then-Else command and also check for the mask_result = 2 (000000102):

If mask_result = 0

Then... 'Temperature above limit, so do this...
Else If mask_result = 2

Then... 'Temperature OK, so do this...
End If


Flags
In the previous examples, signals remained static, or unchanged, at an input port for some time. In many cases, though, data may exist for only a short period, say for the time an operator presses a key on a control panel. If the key remains closed only briefly, the program may miss "seeing" the key-switch closure because it does not check the switch often enough. Such sources of transient information may require a latch circuit.

A keyboard, for example, may produce a "key-pressed" signal that indicates to external circuitry that the keyboard’s output lines contain new information. A 74LS374 latch circuit (Figure 3-10) can use the key-pressed signal to latch information and hold it so a computer can access it through an input port. The latch circuit makes the keyboard data available even after an operator releases a key.

This circuit will let the computer obtain keyboard data from an input port after a user presses a key, but this scheme has a problem. Suppose the operator presses the "2" key five times in sequence and expects the attached computer to receive five 2’s in a row. Each time the operator presses the "2" key, the keyboard produces the same code, 001100102 for an ASCII 2, and the latch grabs it.

Figure 3-10

Figure 3-10
A 74LS374 latch circuit stores 8-bit data from a keyboard when it received a key-pressed signal. When the user releases a key, the key’s code remains available at the latch’s outputs.

But to an observer looking only at the latch outputs, the code doesn’t change. (The keyboard does not reset the latch between key presses.) Each update of the latch from another push of the "2" keys simply leaves the same code, 001100102, on the latch outputs. So the computer cannot distinguish one 2 from any of the others. And because the latch retains the data, the computer could continue to input "old" data even though no one has pressed any other keys. Obviously, the computer and the keyboard need a way to synchronize their operations. An additional circuit element, called a flag, lets the keyboard circuit tell the computer, "I have new data." In effect, a flag works like this:

  1. The keyboard latches new data and raises a flag.
  2. The computer regularly checks the flag.
  3. If the computer sees the flag is "up", it reads the keyboard’s data and then pulls the flag "down."

If the computer’s software checks the flag and finds it down, the software knows the keyboard has no new information, and it continues to its next task. This sort of arrangement lets the computer accept a series of five 2’s from the keyboard. Each press of the "2" key raises the flag, signaling the computer to get the new data and then clear the flag so it’s ready for the next keyboard operation.

Figure 3-11 includes a flip-flop circuit that serves as a flag. The flip-flop works like a 1-bit memory. It transfers the state of the D input to the Q output during the logic-0 to logic-1 (positive-going) edge of the signal applied to the flip-flop’s clock (CLK) input. In this case, the circuit designers have connected the D input to +5V or logic 1. The CLK signal comes from the keyboard’s key-pressed signal, the same signal that latches the keyboard data. When the flip-flop receives the CLK signal, the logic 1 at the D input gets transferred to the Q output, which provides the flag signal to the computer. A logic 0 at the Q output indicates no keyboard data, while a logic 1 tells the computer the latch has new keyboard data.

Figure 3-11

Figure 3-11
A D-type flip flop serves as a flag that lets a computer know a keyboard has new data available. The computer clears the flag after it gets the keyboard’s new information.

As part of a flag-detecting sequence, the software must clear the flag.  The flip-flop provides a clear input (/CLR) that resets the Q output to a logic 0 state, thus clearing, or "lowering," the flag. A logic 0 on the /CLR input clears the flip-flop back to the Q=0 state. The timing diagram in Figure 3-12 shows the sequence of events.

Figure 3-12

Figure 3-12
The keyboard timing starts when a user presses a key. The key-pressed signal latches new data and sets the flag. After the computer detects a set flag, it grabs the keyboard’s data and resets the flag for the next keystroke.

You may wonder how the computer detects the flag signal. The circuit designers connect the flip-flop’s Q output to a TTL-compatible input-port line so the computer can monitor its state. The signal to clear the flag comes from an output port. A complete keyboard interface circuit (Figure 3-13) uses an 8-bit input port (207) for the keyboard data, one bit on an input port (206) for the keyboard flag, and one bit on an output port (123) to clear the flag. The software must check the keyboard flag regularly to determine when the keyboard latch has new information.

Figure 3-13

Figure 3-13
A complete keyboard circuit includes an input port for the keyboard data, an input port for flags, and an output port to clear flags. The latter two ports may connect to additional flags for other I/O devices.

Although using flags to indicate external activities and putting an application program in a continuous flag-checking loop makes sense in some situations, it can needlessly tie up the computer and can chew up valuable processing time. In Visual Basic, for example, you can use the Timer control to govern reading and testing of external flags. Although Visual Basic provides clock divisions of 1 millisecond, in practice the clock produces intervals of about 1/18th second. This rate for checking flags should suffice in many applications.


Put it all together
Now the keyboard circuit needs software to test and reset the flag and to get data. Assume the flag input port (206) also connects to flags from other devices. To keep a design such as that shown in Figure 3-13 easy to debug and document, we suggest you use the same bit position for a flag and its associated flag-clear signal. Thus, in the keyboard example, the flag appears at input-port bit D7, and at output port (123), bit D7 clears that flag.

In the following example, when the software detects any set flag at input port 206, it checks the flag bits in sequence, starting with D7 and ending with D0. This establishes a built-in priority in servicing devices. So, if you have a device that requires fast service, make its flag the first one checked (D7).

The following software does not maintain an output-port status byte for the port used to clear the flags. We assumed a normal output state of 111111112 for this port. The software will force an individual bit to logic 0 for a few microseconds to clear a corresponding flag bit, and then restore the bit to logic 1.

'Establish mask bytes — See Chapter 2
Dim D7_1 As Byte
Dim D6_1 As Byte
'etc...

'Establish mask-byte values — See Chapter 2
D7_1 = &H80 '10000000
D6_1 = &H40 '01000000
'etc...

'Establish byte variables
Dim clear_all_flags As Byte
Dim normal_all_flags As Byte
Dim keyboard_input_port As Integer
Dim flag_input_port As Integer
Dim flag_clear_port As Integer
Dim flag_status As Byte
Dim D7_flag_clear As Byte
Dim D6_flag_clear As Byte
Dim D5_flag_clear As Byte
Dim D4_flag_clear As Byte
Dim D3_flag_clear As Byte
Dim D2_flag_clear As Byte
Dim D1_flag_clear As Byte
Dim D0_flag_clear As Byte

'Define flag-clearing bit patterns
clear_all_flags = 0 '00000000
normal_all_flags = 255 '11111111
D7_flag_clear = 127 '01111111
D6_flag_clear = 191 '10111111
D5_flag_clear = 223 '11011111
D4_flag_clear = 239 '11101111
D3_flag_clear = 247 '11110111
D2_flag_clear = 251 '11111011
D1_flag_clear = 253 '11111101
D0_flag_clear = 254 '11111110

'Define I/O port addresses
keyboard_input_port = 207
flag_input_port = 206
flag_clear_port = 123

'First clear all flags to initialize the system
'Set all flag-clear signals to logic 0
'Then reset all flag-clear signals logic 1 to make flags ready

outportb(flag_clear_port, clear_all_flags)
outportb(flag_clear_port, normal_all_flags)

'Main flag-checking routine...

'Get all flag bits
flag_status = inportb(flag_input_port)

'Any flags set? If so, check individual flags
If flag_status >0

Then

'Check flag at D7, highest priority = keyboard

If (flag_status AND D7_1 >0)


Then

'Get the keyboard port's data

port_data = inportb(keyboard_input_port)


'...other processing steps go here


'Clear the associated keyboard flag

outportb(flag_clear_port, D7_flag_clear)

outportb(flag_clear_port, normal_all_flags)

End If


'Check flag at D6, next highest priority

If (flag_status AND D6_1 >0)

Then

'Get the input port's data

some_data = inportb(some_port)


'Clear the associated flag

outportb(flag_clear_port, D6_flag_clear)

outportb(flag_clear_port, normal_all_flags)


'...other processing steps go here

End If


‘...and so on for the remaining six flags
End If

Note that the test of individual flags checked for >0, rather than for a specific value. You can use either technique.

Routines can check for individual flags, too. You don’t need to check all eight flags at an input port unless your interface circuits have implemented them. And at times, you will want to monitor some flags more often than others.


A final note about I/O ports
In Chapter 2, a section explained that programmers should maintain a "status byte" for every output port so they can determine the state of the outputs at any time. Some output ports, typically those on I/O cards or built into electronic devices, may provide access to that information through a built-in input port (Figure 3-14). The input port simply reads the bits from the port's output lines. Software can use this information instead of saving a status byte. For clarity, the following example uses values in the port-control statements:

outportb(117, control_byte)
port_status = inportb(117)

Figure 3-14

Figure 3-14
Some output ports provide a means to read the state of the associated output lines. The ports shown in this example actually exist within one IC or device.

You still might want to maintain information in a status byte, though.  In most cases, it requires less time to get status information from a byte of stored data than to retrieve data from an input port. So, if you have software that requires careful timing, use a status byte. Software control of I/O ports in many PCs is not  deterministic. That means you cannot tell exactly how long it will take for an I/O operation to take place after a computer receives a port-control command.

Maintaining status bytes also simplifies debugging and testing. When you debug software, you may have to do so without any connected I/O devices. So, if you rely on an output port with an associated input port to maintain port-status information, you may not have access to the port information until designers have configured and attached the I/O ports. Also, during testing, you may need to compare port operations with variables you track using special "watch" windows in your development-software suite; Visual Basic, C, C++, and so on. If the hardware has problems, it may corrupt, or make unavailable, any data from an output port's built-in input port. So, by maintaining the output port's status information in a variable, you at least know what state the port is supposed to be in.


For more information
We hope you found the Chapter 3 informative. To go back to the Main Page, click here.

You can purchase the complete Digital I/O Handbook for only $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase. You can find a listing of all Sealevel Digital I/O products by clicking here.

]]>
Wed, 09 Dec 2009 13:53:08 -0500
The Digital I/O Handbook - Chapter 2 http://www.sealevel.com/support/article/AA-00128

The Digital I/O Handbook
A Practical Guide to Industrial Input & Output Applications

Digital I/O Handbook

Digital I/O Explained
Renowned technical author Jon Titus and the President and CEO of Sealevel Systems, Tom O'Hanlan, clearly explain real-world digital input/output implementation from both a hardware and software perspective. Whether you are a practicing engineer or a student, The Digital I/O Handbook will provide helpful insight you will use again and again.

  • Covers a wide range of devices including optically isolated inputs, relays, and sensors
  • Shows many helpful circuit diagrams and drawings
  • Includes software code examples
  • Presents common problems and solutions
  • Detailed glossary of common industry terms

"What I like most is its mix of hardware and software. Most pages have a bit of code plus a schematic. All code snippets are in C. This is a great introduction to the tough subject of tying a computer to the real world. It's the sort of quick-start of real value to people with no experience in the field." - Jack Ganssle, The Embedded Muse, January, 2005.

You can purchase the Digital I/O Handbook for $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase.


Chapter 2 - Digital Outputs

Topics Covered

  • Introduction to output ports
  • Simple on/off control
  • Using drivers and buffers
  • Relay basics
  • Relays handle more power
  • Optical isolation
  • Solid state relays
  • Control bits and bytes with software


Introduction to output ports
Electronic devices receive information from computers through a circuit called an output port. That information can control a process, control individual devices, update a display, and so on. Each output port, as shown in Figure 2-1, receives information from a computer’s internal data bus and it also receives a unique strobe signal supplied by the internal circuitry of the computer. Because most people use output ports rather than design them, we won’t discuss port construction further.

Figure 2-1

Figure 2-1
Two output ports connect in parallel to a computer data bus. Each output port receives a unique strobe signal that synchronizes the bus with the port’s operation to capture the data.

In most cases, computers transfer eight bits, or one byte, at a time under software control. The computer generates a unique strobe signal, designated something like OUTxyz, for each output port. A software command such as:

outportb (output_port_number, output_data_byte)

controls the flow of data to an output port.  The command, outportb, transfers a byte of data (output_data_byte) to a specified output port (output_port_number). The computer’s central processing unit (CPU) properly synchronizes the presence of the byte on its data bus with the strobe signal.

The outportb command shown above does not exist within some programming languages such as Visual Basic. Each manufacturer of add-in cards or devices supplies its own driver software. Drivers come in a library of routines that link a programming language to special operations, such as those that control I/O ports. Thus, drivers define many new commands that a programmer can include in code to transfer a byte to an output port.

You must follow instructions included with an I/O board to properly set up accompanying driver software. The setup process lets your application program know how to find and use the drivers on the computer’s hard drive. (The instructions that accompany a board and its drivers provide installation information and information about how to use drivers in your application program.)

An output port’s signals may provide data, such as an 8-bit code for an ASCII character, say, 010001012, which represents the letter E. On the other hand, the outputs from the port may control eight individual on/off devices. Software cannot tell—and doesn’t care—whether the byte it sends to a port represents the letter E or on/off controls for pumps and valves. A port with eight outputs can produce 256 unique binary patterns, 000000002 through 111111112.

Sometimes, an output port will mix control signals and information, as shown in Figure 2-2. A port that controls a numeric display might use four output lines to represent the digits 0 (00002) through 9 (10012) for the display. The remaining four lines from the port could control a decimal-point LED and other devices independent of the display. You can use the lines from an output port in almost any way you wish.

Figure 2-2

Figure 2-2
An output port’s eight lines can operate independently. In this example, four lines control a binary-coded-decimal (BCD) display while the others control individual devices.


Simple on/off control
A simple output port constructed from TTL devices can directly drive TTL inputs.  Driving a display module, for example, may only require connection of the port’s TTL outputs to the TTL inputs on the module. Although TTL outputs can directly sink small currents, circuit designers recommend using driver or buffer circuits to control real-world devices. These drivers, which sink or source current, come with TTL-compatible inputs. Current sinks and current sources often go by the names low-side switch and high-side switch, respectively.

Don’t confuse the hardware drivers that actually operate as part of a circuit with the software drivers that let application software control an I/O port.


Using drivers and buffers
The family of SN7545X devices shown in Figure 2-3 provides four types of gates that drive internal open-collector transistors. Each open-collector output can sink up to 300 mA and can operate with a voltage as high as 30V. This type of driver can control low-current, low-voltage devices such as LEDs, solenoids, relays, stepper motors, and so on. The SN7545X devices act as general-purpose drivers. Manufacturers also supply drivers built specifically to control displays, stepper motors, DC motors, and other devices.

Figure 2-3

Figure 2-3
Devices in the SN7545X family of TTL-compatible drivers provide all four logic functions. The open-collector transistors come as part of the driver ICs.

Drivers that sink current predominate, but at times, an application may call for a current source, or a high-side switch. The UDN2987A integrated circuit from Allegro MicroSystems (Worcester, MA; www.allegromicro.com) represents a typical current source (Figure 2-4). This device supplies eight drivers, each of which can supply up to 100 mA from a supply voltage as high as 35V. The UDN2987A also includes an overload protection circuit for each driver.

Figure 2-4

Figure 2-4
The UDN2987A driver supplies eight individual current-source circuits. Similar current-sink drivers also come eight per package. (Courtesy of Allegro MicroSystems)


Relay Basics
The types of drivers described above work well when the output port, the driver circuit, and the device under control all share a common ground, as shown in Figure 2-5. Often, though, devices cannot or must not share a common ground. When a computer controls a device that operates at a high voltage, for example, no electrical connection should exist between the device and the computer. The interface between the computer and the motor should isolate their circuits. An electromechanical device called a relay offers such isolation.

Figure 2-5

Figure 2-5
Many circuits function with a common ground connection, but some circuits may require separate circuits that have no electrical connection.

A relay contains a small electromagnet that controls an armature—a moving switch contact—held in a "normal" position by a spring. When energized, the electromagnet causes the armature to move to its other position. Remove the energy to the electromagnet and the spring quickly moves the armature back to its normal position (Figure 2-6).

Figure 2-6

Figure 2-6
An electromagnetic relay provides a movable contact (armature) that can switch between two contacts. An electromagnetic coil actuates the armature.

Even though the switch and the electromagnet exist close to each other, they share no electrical connection. This means the relay can turn a completely independent circuit on or off. In this way, a small relay controlled by a TTL driver can operate a motor powered by house current, yet no current flows between them. Manufacturers sell relays in a variety of sizes and with a wide range of voltage and current ratings. (For information on relay and switch contact configurations, see Appendix.)

Reed relays, at the small end of the relay spectrum, handle up to 200V and currents as high as 0.5A. As its name implies, a reed relay contains a small magnetic "reed" that forms the moving part of a switch (Figure 2-7a).

Figure 2-7a

Figure 2-7a
A Reed relay provides two contacts that close a circuit.

Depending on the type of reed relay, one or two other contacts complete the circuit through the switch. Instead of relying on a spring to move the reed, the relay relies on the properties of the metal reed to hold it in its normal position.

Figure 2-7b

Figure 2-7b
A magnetic field applied by a coil controls relay closure.

The reed and the other contacts come sealed in a small glass tube that fits inside an electromagnetic coil (Figure 2-7b). Sealing the reed and the contacts in a glass tube protects them from contamination and helps ensure reliable operation over millions of on-off cycles.

A variety of reed relay types let users choose from a wide range of voltage and current specifications. Reed relay coils operate at 5V, 12V, or 24V, so drivers such as those in the SN7545X family can easily control them. One output port and eight drivers can independently control eight relays (Figure 2-8).

Figure 2-8

Figure 2-8
An output port and drivers can control eight individual relays. For clarity, the diagram shows only four relays and it does not show connections to the relay contacts.

Not all relays control motors, pumps, and heaters.  A series of computer-controlled reed relays can switch one of many sensor signals to the input of a data-acquisition or data-logging system. What you use a relay to control or switch makes no difference as long as you operate it within specified limits. (Note that suppression diodes are not shown in the example schematics. See Glossary.)


Relays handle more power
At the high-power end of the relay spectrum you’ll find relays that switch high voltages and currents (Figure 2-9). Even a small power relay can handle voltages as high as 250V AC and currents as high as 10A; sufficient to control large motors, lamps, heaters, pumps, and so on.  In a power relay, the space between the contacts, the size of the contacts, and the materials used to fabricate them determine current-carrying capacity and operating-voltage limits. Relay manufacturers may reduce, or derate, some specifications depending on the type of load a relay will control. In general, relays can carry more current for a resistive load than for an inductive load, such as a solenoid or motor.

Figure 2-9

Figure 2-9
Relay manufacturers offer varieties of contact configurations, mounting arrangements, contact characteristics, and cases. (Courtesy of IDEC USA.)


Optical isolation
When a design requires isolation and a relay isn’t practical, engineers turn to devices that optically isolate a driver from the circuit under control. In a relay, a magnetic field isolates an electrical coil from a mechanical switch, while in an optical device, light provides the isolation. In an optical isolator a circuit turns on or off an LED that shines on a detector. The detector, usually a phototransistor, then turns on or off a separate—and isolated—circuit. Figure 2-10 shows a cut-away diagram of an optical isolator, also called an optical coupler, opto-coupler, or opto-isolator.

Figure 2-10

Figure 2-10
A cut-away view of an optical isolator shows the separation of an LED and a phototransistor. The separate circuits can provide an isolation of several thousand volts.

Optical isolators come in a variety of forms, from 6-pin dual in-line package (DIP) devices that supply one LED-phototransistor pair, to larger devices that include several such pairs. Electrical isolation between the LED and the phototransistor ranges from about 1500V up as high as 8 kV, more than enough for most real-world applications.

Although some designs use optical-isolator ICs as stand-alone drivers, their utility increases when they control semiconductors that handle high-power loads. An optical isolator can control a triac—a semiconductor device that can switch power-line current—as shown in Figure 2-11. To reduce switching transients, which can cause EMI and RFI, some optical isolators provide a zero-crossing detector. This detector determines when the line voltage signal crosses through 0V, and switches the triac at that time. Switching at the zero-crossing point minimizes the inrush of large currents that would occur if switching took place at other points on the voltage waveform of an AC line-voltage signal.

Figure 2-11

Figure 2-11
A typical solid-state relay circuit uses an Optical isolator to control a triac that switches line voltage to a lamp.


Solid state relays
You don’t have to build your own optically isolated control circuits. Manufacturers supply a wide variety of solid state relays (SSRs) that optically isolate an input from an output that controls high-power AC and DC loads. Modules can provide from one to as many as four control circuits, depending on a user’s needs.

Although solid state relay manufacturers offer a wide array of device types, many conform to standards that allow for the interchange of devices from several manufacturers. You can buy compatible SSR modules from companies such as:



CAUTION: Modules usually include an LED to show the state of each relay. Unfortunately, not all modules clearly label each LED and the circuit associated with it. The diagram in Figure 2-12 identifies the circuits in the quad-circuit modules in the OAC and ODC families of AC- and DC-output modules from Opto 22, and the 1781-OA5Q and 1781-OB5Q families from Western Reserve Controls.



Figure 2-12

Figure 2-12
The top view of an Opto 22 quad OAC or ODC module (or equivalent) shows the relationship between the internal circuits and the LED indicators.


CAUTION: Manufacturers may designate outputs as "channels" numbered 8—1, although the bits at an output port carry the labels 7—0, for data bits D7 through D0. Bit 0 represents the right-most or least-significant bit (LSB), and bit 7 represents the left-most or most-significant bit (MSB). The chart in Table 1 shows the relationships between the outputs, the bits, and the binary weights for each bit.



Module Channel Bit Position Binary Value Decimal Value
1 D0 00000001 1
2 D1 00000010 2
3 D2 00000100 4
4 D3 00001000 8
5 D4 00010000 16
6 D5 00100000 32
7 D6 01000000 64
8 D7 10000000 128

Table 1
Modules, Bits, and Binary Weights.

To turn on the outputs at positions 8, 5, and 3 in a positive logic system, for example, requires a logic 1 at bits 7, 4, and 2, or a binary bit pattern of 100101002, which translates to hexadecimal 94 (&H94) or decimal 148. A negative-logic system would require a binary bit pattern of 011010112, hexadecimal 6B (&H6B), or decimal 107.



CAUTION: A quad-output module in the OAC and ODC and compatible families of AC- and DC-output modules isolates pairs of outputs from one another, but the two circuits within each pair share a common connection. In applications that control devices powered by the same source, a shared common connection works well.  But an application may require controlling 120V AC and 24V AC circuits (Figure 2-13). Although both circuits require AC power, most likely that power doesn’t come from the same source. When in doubt, DO NOT mix voltages within a pair of outputs. Always rely on a manufacturer’s data sheets for complete application information on specific modules.


Figure 2-13

Figure 2-13
Each pair of outputs in an Opto 22 quad OAC or ODC module (or equivalent) provides a single common connection. DO NOT mix circuits in a given pair unless the circuits share a common connection.


CAUTION: You cannot control AC and DC circuits with a single quad module; each type of current requires its own module.


The Sealevel Systems M280 Quad Module Adapter, for example, accepts two of the OAC- and ODC-type modules. The M280 board lets a user employ two AC-output modules, two DC-output modules, or one of each. Modules can plug into either position, and the position determines whether a module controls devices 1—4 or devices 5—8.


Control bits and bytes with software
Now that you understand a bit more about how circuits can turn devices on and off, you’ll learn how software can control bits at output ports to give a computer control over real-world devices. These operations involve manipulating individual bits.

To illustrate how software controls devices, assume you want to turn on or off a pump motor using a solid-state relay connected to bit D4 at output port 207, as shown in Figure 2-14. (The relay would operate at position 5 on a Sealevel Systems’ M280 card.) Table 2-1 below shows the bits needed to control the motor using either positive logic or negative logic:

Figure 2-14

Figure 2-14
A bit at D4 at output port 207 will turn a line-voltage motor on or off. A solid state relay isolates the port from the line current and turns the motor on or off.

Positive Logic Negative Logic
1 = ON
0 = OFF
0 = ON
1 = OFF

Table 2-1
Bits needed to control the motor using either positive logic or negative logic.

For now, assume the card uses negative logic. (A following example will explain how to work with positive logic.) If you send a logic 0 to bit D4 at output port 207, the motor runs. If you send a logic 1 to bit D4, the motor stops.

Controlling the output port involves using the general instruction:

outportb (output_port_number, output_data_byte)

Given the decimal weight of bit D4 (16), and knowing the output-port number, you can use commands such as those below to control the pump motor shown in Figure 2-14:

outportb (207, 0) ‘turn pump motor on
outportb (207, 16) ‘turn pump motor off

The command that turns the motor on assumes it’s OK to set the other bits at output port 207 to logic 0. But in practice, output-port bits D7—D5 and D3—D0 probably control other devices. Software that turns the pump on must not disrupt any other devices controlled by this port! Thus, controlling the motor must NOT change any bits except for D4. How can software do that?

To start, the software that controls the pump motor must know the state of the other bits; that is, what devices at port 207 are already on or off. So, before it first uses an output port, application software should set up a byte to store the bits that will go to that port. Then, software can read at any time the state of the bits at a given port. (Each output port requires its own status byte.)

Once software "knows" an output port’s current state, computer operations can control individual bits. The four rules below, based on the truth tables shown in Chapter 1, show how to control individual bits. An X indicates the state of the bit doesn’t matter. It can be a 1 or a 0.

  1. If you AND bit X with logic 0, the result is always logic 0.
  2. If you AND bit X with logic 1, you simply get the X bit’s original state.
  3. If you OR bit X with logic 0, you simply get the X bit’s original state.
  4. If you OR bit X with logic 1, the result is always logic 1.

Here are the rules in column form:

AND AND OR OR
X X X X
0 1 0 1


0 X X 1 Result


The AND and OR operations can operate on individual bits in the same positions in two bytes of data. These bit-wise AND and OR operations can set individual bits to logic 1 or to logic 0, or leave bits unchanged. Here are examples of a bit-wise AND and a bit-wise OR operation:

Bit-wise AND
D7
D0
0 0 1 0 1 0 1 1 Byte A
0 0 1 1 0 1 0 1 Byte B


0 0 1 0 0 0 0 1 Result byte

Bit-wise OR
D7
D0
0 1 0 0 0 1 0 1 Byte F
0 0 1 1 0 1 0 1 Byte G


0 1 1 1 0 1 0 1 Result byte



CAUTION: Programming languages provide two types of logical operations; the bit-wise operations shown above and "logical" operations. These designations often confuse even knowledgeable programmers! In C, for example, the symbol & produces a bit-wise AND, while the symbols && produce a logical AND of two statements. Check a programming reference manual for the language you plan to use for details. Our programming examples will use AND and OR to stand for bit-wise operations.


Assume the port-status byte for output port 207 already contains 001101012, so some devices are now on (logic 0), and others, including the pump motor (bit D4), are now off (logic 1).

To turn on the pump motor, software must force bit D4 to a logic 0 but leave the other seven bits unchanged. Rules 1 and 2 (above) show that an AND operation can force a bit to a logic 0 or leave bits unchanged. So, set up a byte and insert a logic 1 at each bit position that should remain unchanged. Next, insert a logic 0 for any bit you want to force to a logic 0:

D4
1 1 1 0 1 1 1 1


Programmers call this byte a mask byte. A bit-wise AND of the current port-status byte and the mask byte will set D4 to a logic 0, but leaves all other bits unchanged:

D7
D0
1 1 1 0 1 1 1 1 Mask byte
0 0 1 1 0 1 0 1 Port-status byte for output port 207


0 0 1 0 0 1 0 1 Result of bit-wise AND; the new port-status byte

Remember, a bit-wise operation involves only the two bits in each column. Thus, bit D7 in the mask byte gets ANDed with bit D7 in the port-status byte to produce bit D7 in the result, and so on for each column.

In the example above, only bit D4 changed its state as a result of the bit-wise AND operation. Note the result of the bit-wise AND yields a new port-status byte that the software must store and then send to output port 207. Now, bit D4 will turn the pump motor on, but without affecting any of the other bits at the output port.

To turn the pump motor off, software must now force bit D4 to a logic 1 but leave the other seven bits unchanged. Rules 3 and 4 (above) show that a bit-wise OR operation can force a bit to a logic 1 or leave bits unchanged. So, set up a byte and insert a logic 0 at each bit position that should remain unchanged. Next, insert a logic 1 for any bit you want to force to a logic 1:

D4
0 0 0 1 0 0 0 0

Next, perform a bit-wise OR between this mask byte and the new port-status byte:

D7
D0
0 0 0 1 0 0 0 0 Mask byte
0 0 1 0 0 1 0 1 Port-status byte for output port 207


0 0 1 1 0 1 0 1 Result of bit-wise OR; the new port-status byte

Note that the port-status byte used in this bit-wise OR is the port-status byte produced by the bit-wise AND operation.  When you need to control an output port, always use the current status information! Software must now store the result of the bit-wise OR operation as the new port-status byte.

In the bit-wise OR operation, only bit D4 changed state. When software sends the new status byte information to output port 207, the pump motor will turn off.

If you look closely at the mask bytes used in the AND and the OR operations, you may realize that complementary mask bytes turn the pump motor on or off. In binary numbers, a complementary number simply changes logic 1’s to logic 0’s, and vice versa, for example 001012 is the complement of 110102.

The previous port-control example assumed the motor-control output port employs negative logic (1 = off, 0 = on).  But, suppose the circuit designers provided the wrong specification and the port actually uses positive logic (1 = on, 0 = off).  To control the pump motor, use the SAME logical operations and mask bytes, but use a bit-wise OR to turn the pump motor ON, and use a bit-wise AND to turn it off. Again, software MUST save the port-status byte after each logical operation and the software must send that new status byte to the output port.

The following steps show how to translate the bit-control operations into actual software:
  1. Establish a status byte for each output port.
  2. Establish an ON and an OFF mask byte for each bit the software will control.
  3. Use bit-wise operations and the mask bytes to force individual bits to logic 1 or logic 0.

Here’s how to set up a skeleton pseudo-code program to control an output port.  Pseudo-code shows the program structure and flow, but you’ll have to adapt it to the language you choose for an application.

To get started, "define," or set aside bytes for individual bit masks. A notation such as D7_1 indicates the corresponding mask will set bit D7 to a logic 1. On the other hand, D7_0 will set bit D7 to a logic 0. This sort of variable-naming technique can help you and other programmers decipher a program listing.

The statements directly below set aside storage for 16 byte values:

Dim D7_1 As Byte
Dim D7_1 As Byte
Dim D6_1 As Byte
...
Dim D0_1 As Byte
.
.
.
Dim D7_0 As Byte
Dim D6_0 As Byte
...
Dim D0_0 As Byte

Then establish the bit pattern for each of the masks defined above using their hexadecimal values. The binary values shown as comments in the listing make clear the actual pattern of bits in use:

D7_1 = &H80 ‘10000000
D6_1 = &H40 ‘01000000
D5_1 = &H20 ‘00100000
...
D0_1 = &H01 ‘00000001
.
.
.
D7_0 = &H7F ‘01111111
D6_0 = &HBF ‘10111111
D5_0 = &HDF ‘11011111
...
D0_0 = &HFE ‘11111110

Next, set aside bytes for a port number and port-status byte for each output port, and a "device on" and a "device off" mask byte for each device the software will control. The code below shows only one port-status byte (motor_port_status), and the on and off masks for a single pump motor controlled at a negative-logic output port by bit D4:

Dim motor_control_port_number As Byte
Dim motor_port_status As Byte
Dim pump_motor_D4_on_n As Byte
Dim pump_motor_D4_off_n As Byte

For clarity, the last two variable names above indicate:

What device the mask will control (pump_motor),
The bit used to control it (D4),
The action (on or off), and
The logic used at the output port (n, for negative logic, p for positive logic).

You can choose your own notation for variables, but we like to use variable names that have as much meaning as possible.

Now the program adds commands that establish the actual mask values:

pump_motor_D4_on_n = D4_0 ‘11101111
pump_motor_D4_off_n = D4_1 ‘00010000

Remember, previous software already set up the values for D4_0 and for D4_1.

The program also sets up the motor-control port number, as defined by the system’s hardware:

motor_control_port_number = 207

Should the motor-control port assignment change during development or debugging, it’s easy to change this one assignment of the specific port address. Otherwise you must track down and change every occurrence of "207" in a lengthy code listing!


TIP: After software establishes the bit-mask patterns, such as D4_0, you can use them anywhere in a program when you need to set a bit to logic 0 or 1. So, if you need to control a display that uses output D5 as a control line, simply use D5_0 and D5_1 to set up the two masks to control this bit at the display-control output port. You need not redefine the basic mask patterns again and again.


Finally, the following commands turn on the pump motor:

motor_port_status = motor_port_status AND pump_motor_D4_on_n
outportb (motor_control_port_number, motor_port_status)

The first command forced bit D4 to a logic 0 in the port-status byte and saves that result back in the port-status byte. The next command sends the motor_port_status byte to the output port to control the pump motor.

To turn the pump motor off:

motor_port_status = motor_port_status OR pump_motor_D4_off_n
outportb (motor_control_port_number, motor_port_status)

For a port that uses positive logic, again define the masks, but remember that a logic 1 corresponds to on, and a logic 0 corresponds to off. In this case, the "p" at the end of the mask designated positive logic at the output port:

pump_motor_D4_on_p = D4_1
pump_motor_D4_off_p = D4_0

To turn the pump motor on:

motor_port_status = motor_port_status OR pump_motor_D4_on_p outportb
(motor_control_port_number, motor_port_status)

Then, to turn the pump motor off:

motor_port_status = motor_port_status AND pump_motor_D4_off_p
outportb (motor_control_port_number, motor_port_status)


For more information
We hope you found the Chapter 2 informative. To go back to the Main Page, click here.

You can purchase the complete Digital I/O Handbook for only $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase. You can find a listing of all Sealevel Digital I/O products by clicking here.


]]>
Wed, 09 Dec 2009 13:52:46 -0500
The Digital I/O Handbook - Chapter 1 http://www.sealevel.com/support/article/AA-00127

The Digital I/O Handbook
A Practical Guide to Industrial Input & Output Applications

Digital I/O Handbook

Digital I/O Explained
Renowned technical author Jon Titus and the President and CEO of Sealevel Systems, Tom O'Hanlan, clearly explain real-world digital input/output implementation from both a hardware and software perspective. Whether you are a practicing engineer or a student, The Digital I/O Handbook will provide helpful insight you will use again and again.

  • Covers a wide range of devices including optically isolated inputs, relays, and sensors
  • Shows many helpful circuit diagrams and drawings
  • Includes software code examples
  • Presents common problems and solutions
  • Detailed glossary of common industry terms

"What I like most is its mix of hardware and software. Most pages have a bit of code plus a schematic. All code snippets are in C. This is a great introduction to the tough subject of tying a computer to the real world. It's the sort of quick-start of real value to people with no experience in the field." - Jack Ganssle, The Embedded Muse, January, 2005.

You can purchase the Digital I/O Handbook for $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase.


Chapter 1 - Logic Principles

Topics Covered

  • Introduction to digital electronics
  • Current sinks and sources
  • Buffers and drivers
  • Latches
  • Positive and negative logic
  • Logic families


Introduction to digital electronics
The world of digital electronics allows for only two states, so at a given time, a digital signal can exist in only one of them. Although engineers usually think of these two binary states as logic 0 and logic 1, you can define them as you wish: true and false, black and white, high and low, and so on, as long as everyone else understands your definitions.

Basic Boolean1 logic operations such as AND and OR let electronic circuits make decisions, such as, "If A and B are true, do this..." Figure 1-1 shows the AND and OR logic operations along with the symbol engineers use to represents each operation in a circuit. A truth table shows the output condition produced for each possible set of inputs to the logic circuit, called a "gate." A 2-input gate, for example, has 22, or 4 possible input conditions, while a 5-input gate would allow for 25, or 32 possible binary input combinations.

Figure 1-1

Figure 1-1
Basic AND and OR logic operations follow a set of rules described using truth tables. Even if you substitute "YES" for 1 and "NO" for 0, the rules remain the same.

Note that a 2-input AND gate produces a logic 1 at its output only when a logic 1 exists at input A and at input B. A 2-input OR gate produces a logic 1 when either input A or input B exist in a logic-1 state. On the other hand, when both OR gate inputs change to logic 0, the gate produces a logic 0.

These conditions hold, no matter how many inputs an AND gate or an OR gate has:

  • An AND gate puts out a logic 1 only when ALL its inputs exist in the logic-1 state.
  • An OR gate puts out a logic 0 only when ALL its inputs exist in the logic-0 state.

The inclusion of a third logic operation, inversion, completes the family of fundamental logic functions. In Boolean logic, the inversion function goes by the formal name NOT. An inversion operation simply "inverts" a logic 1 to a logic 0, and vice versa, as shown in Figure 1-2. The small circle at the input (flat side) or at the output (apex) of the triangle symbol represents the inversion operation.

Figure 1-2

Figure 1-2
An inverter simply reverses the logic state of its single input, as shown in the truth table. Inverters appear as small triangles in schematic diagrams and most designers favor drawing the small circle on the output.

So, if a device produces a logic 1 to cause an action, but your circuit requires a logic 0, use an inverter. Likewise, an inverter will change a logic 0 into a logic 1. Digital circuits may include many discrete inverters, as shown in Figure 1-2. Many schematic diagrams also show an inversion by attaching a small circle to an input or output. But these small circles do not exist on their own in circuit diagrams; you’ll always see them attached to another symbol.

Combinations of AND, OR, and NOT functions form the basis for all digital electronic circuits. Many circuits combine AND, OR, and NOT functions to form NOT-AND and NOT-OR circuits. Engineers have adopted the names NAND and NOR for these common functions, shown in Figure 1-3. NAND and NOR gates exist in real circuits.

Figure 1-3

Figure 1-3
Combining AND and OR gates with an inverter function leads to NAND and NOR gates. You can build any digital circuit from these versatile devices.

Combining NAND and NOR gates lets circuit designers produce any digital function. Even the latest microprocessor chips rely on large arrays of these fundamental digital circuits.

In the world of digital electronics, logic 1 and logic 0 correspond to voltages. In the popular family of SN7400-series transistor-transistor logic (TTL) integrated circuits (ICs), a voltage close to 5V represents a logic 1, and a voltage close to 0V, or ground, represents a logic 0. Note that a logic 0 does not mean "nothing" or "unconnected." Voltages that represent a logic 1 and logic 0 may vary from one family of logic ICs to another, but designers always consider a logic 1 as the higher of the two voltages. For the sake of simplicity, we’ll continue to use the 5V TTL levels in our examples.

A simple single-pole double-throw (SPDT) switch can easily switch between 5V DC and ground to produce either a logic 1 or a logic 0 at an input to a TTL IC, as shown in Figure 1-4a. Note that the "logic 1" side of the switch connects to the 5V power source through a pull-up resistor. This resistor limits current through the circuit and offers some protection against an inadvertent short circuit, which could damage logic devices.

Figure 1-4

Figure 1-4
An SPDT switch (a) can change the logic state of an inverter’s input, but the circuit in (b), provides a better alternative. Note the common ground connection between the inverter and the switch circuit.

Unfortunately, the SPDT switch circuit can cause a problem. Actuating the switch moves a contact between the 5V and GND terminals. During the movement, the contact experiences a short "dead time," when it touches neither 5V nor GND. In many circuits, this brief time between terminals wouldn’t cause a problem. But in a digital circuit it means the input to a device will briefly "float," which can cause an input to "see" an undetermined state. That condition should not exist in a digital circuit because it can lead to unexpected results.

To avoid this type of problem, use the circuit shown in Figure 1-4b, which eliminates the switch’s "dead" time. As soon as the switch opens and breaks the  connection to ground, the input to the TTL IC changes to 5V, or logic 1. Likewise, as soon as the switch contacts the ground terminal, the input changes to logic 0.

The simple circuits shown in Figure 1-4 require a common ground connection that furnishes a reference for all voltages in the circuit. Also, to operate properly, all circuits require a common ground, through which current can flow. Unfortunately, schematic diagrams often do not show complete circuit paths for power and ground connections.

If you have doubts about the operation of a circuit, always ensure that it has a complete current path and common ground connections before you proceed. (Schematic diagrams may use symbols shown in Figure 1-4 to designate ground connections.)


Current sinks and sources

The output portion of a typical TTL IC contains two transistors, only one of which can conduct current at any time. These output transistors, as shown in Figure 1-5, internally connect the IC’s output to 5V or to ground to produce a logic 1 or a logic 0 at the output.

Figure 1-5

Figure 1-5
The output of a typical TTL circuit includes two transistors than can switch the output between Vcc or GND to produce a logic 1 or a logic 0. For clarity, this circuit shows only the output transistors, not the entire gate circuit.

To produce a logic 1 at its output, a TTL IC turns on the upper transistor, which allows current to flow from the 5V supply (V+, Vcc, or Vcc) through the output transistor to another circuit. The upper transistor provides a current source to the output, and the lower transistor provides a current-sink from the output to ground (GND).

A TTL input connected to this output will recognize a voltage between about 2.0V to 5.0V as a logic 1. The input will recognize a voltage between about 0.8V and 0.0V as a logic 0. Actual voltage ranges for inputs and outputs vary by logic families, as you’ll see later. The voltages noted above apply to the standard SN7400 family of ICs we use throughout this book.

The circuit in Figure 1-6a shows how a gate output sources current to produce a logic 1. (The diagram shows only the upper transistor and resistor from Figure 1-5.) Current flows from the power source, through the resistor, through the transistor, and through the LED, which lights up. When the IC produces a logic 0, the transistor turns off so no current can flow, and the LED turns off.

Figure 1-6a

Figure 1-6a
The output of a standard TTL IC will source current when it produces a logic 1.

The circuit in Figure 1-6b illustrates how a gate output sinks current to produce a logic 0. (The diagram shows only the lower transistor from Figure 1-5.) In this circuit, current flows from a power source through an LED to ground, so the LED lights whenever the TTL IC produces a logic 0. When the IC output changes to a logic 1, the transistor no longer conducts current, so the LED turns off. In this circuit, an external resistor in series with the LED limits current flow. The internal resistor shown in Figure 1-6a limits current in that circuit.

Figure 1-6b

Figure 1-6b
The output of a standard TTL IC will sink current when it produces a logic 0. Although a standard TTL output may control an LED, other circuits better handle this task.


Buffers and drivers
A standard TTL device, such as an SN7400 NAND gate, can sink about 16 milliamperes (mA) and source about 1 mA. Although TTL devices can operate small LEDs, good designers rely on special driver, or buffer, circuits to control real-world devices such as LEDs, motors, and relays.

A driver, often called a buffer, provides an output transistor designed specifically to operate high-current or high-voltage devices. Some manufacturers also produce drivers to control specific devices, such as stepper motors or displays.

The TTL family of ICs includes several devices with open-collector outputs that can drive low-current loads such as LEDs or small relays. The output circuit of an open-collector IC looks like the circuit shown previously in Figure 1-6b. The transistor’s collector terminal remains "open," or unconnected to any other circuitry. When turned on, this transistor sinks current to ground, but it cannot source any current.

The circuit in Figure 1-7 shows a typical open-collector driver and its truth table. Note that only two logic-1 inputs to the SN7403 open-collector NAND gate cause the IC to sink current. When the output does not conduct current to ground, it appears unconnected to external devices.

Figure 1-7

Figure 1-7
An open-collector output will act as either a disconnected (open) circuit or as a path to ground. Note that this diagram indicates the power and ground connections for the 74ALS03 IC.

Because an open-collector IC simply provides a "switch" that will connect a circuit to ground, an LED, relay, or resistor circuit must provide power. TTL ICs such as the SN7403 have specific current and voltage limits. Always check the data sheet for a device before you use it to drive any circuit outside its immediate logic "family."

Special high-current open-collector devices described in Chapter 2 can drive loads that draw more current than the few tens of milliamperes a standard open-collector gate can handle.


Latches
All of the previous examples show simple gate circuits. As a gate’s inputs change, so does its output. But, logic circuits also rely on latches, devices that take a "snapshot" of information and save it. A typical latch provides eight inputs and eight outputs. The eight inputs connect to a computer, and the eight outputs connect to drivers or other devices that require data to remain stable for long periods. Latches come in two varieties: level-sensitive and edge-sensitive.

Figure 1-8a shows connections to a typical level-sensitive latch IC, the SN74LS373. (For clarity, the figure shows only one data signal.) As long as the IC’s Enable signal remains at logic 1, an input signal (In) will pass through the latch to its corresponding output (Out). But, when the Enable signal becomes a logic 0, the latch snaps shut. Then the output remains as it was when the Enable signal changed from logic 1 to logic 0. In effect, the SN74LS373 IC acts like a small memory. Some designers refer to this type of latch as a transparent latch.

While the Enable signal remains at logic 0, the outputs remain latched. When the Enable signal changes to a logic 1, the In signal again passes directly through to the Out connection.

Figure 1-8a

Figure 1-8a
A level-sensitive latch acts like a gate and lets signals pass through until it receives an Enable signal. Then, it "latches" and holds the data, as long as Enable = 0.

Figure 1-8b
An edge-sensitive latch will update its data only on a transition of its Clock signal, in this case, a positive-going edge.

Figure 1-8b illustrates an edge-sensitive latch, the SN74LS374, also called an edge-sensitive D flip-flop. (For clarity, this figure also shows only one data signal.) This device transfers logic levels from its inputs to its outputs only at the instant its Clock signal changes from a logic 0 to a logic 1. The change, or edge, of the Clock signal causes the transfer to occur. The outputs remain stable until the next logic-0 to logic-1 transition, also called a positive-going edge. A logic-1 to logic-0 change, a negative-going edge, has no effect on the SN74LS374.

Latch circuits find use in many peripheral devices because they can "grab" data from a bus and hold the data until updated by a hardware signal, often generated under software control. In this way, a computer can transfer data to external input/output (I/O) devices that you’ll learn more about later in this booklet.


Positive and negative logic
Some digital circuits require a logic 1 to cause an action, while other circuits require a logic 0. A level-sensitive latch closes when its Enable signal becomes a logic 0. On the other hand, in the open-collector driver circuit (see Figure 1-7), a logic 1 at both inputs causes the output to connect to ground.

When a circuit requires a logic 1 to operate, engineers may refer to this condition as positive logic. Thus, the more positive voltage causes the action to take place. On the other hand, if a circuit requires a logic 0 to cause action, this type circuit is referred to as negative logic.

There’s nothing "negative" or "positive" about these various circuits. The notation simply provides a shorthand that tells engineers and users whether a logic 1 or a logic 0 causes an action.

In the latch circuits shown in Figures 1-8a and 1-8b, each device has an Output Control signal, /OC, that connects to ground, or logic 0. These ICs provide three-state outputs and require a logic 0 at this input to enable the outputs to function. Because a logic 0 causes this action, you can think of the /OC input as a negative-logic input. The small circle on each /OC input indicates a logic 0 will cause the action described by the signal name. Also, signals that have a prefix "/" or a suffix "*", such as START*, RESET*, or /END, often indicate a logic 0 causes the named action to occur.


All in the family
The TTL family tree now includes many varieties of logic circuits, from the plain-vanilla SN74xx TTL series of ICs to newer ICs aimed at high-speed, low-power designs. Table 1-1 lists several of the most widely used families of logic devices, but other families also exist. The notations "growth", "mature", and "decline" used in Table 1-1 simply refer to the type of market for these devices.

Table 1-1

Table 1-1
Logic-Family Descriptions

Check the Texas Instruments (Dallas, TX) Web site at www.ti.com for current information about logic families and characteristics. Look under Digital Logic —> About Logic —> Logic Selection Guide.

Logic families involve several technologies ranging from bipolar semiconductors in the older families to hybrid bipolar-CMOS devices (BiCMOS), and CMOS-only devices. The type of technology will affect the operation of devices as well as their supply voltages, current-sink and current-source capabilities, and operating speed. Each family of devices has its own specifications for voltage outputs and inputs as shown in Table 1-2.

Table 1-2


Chapter Notes
1. Boolean logic operations got their name from George Boole (1815-1864), a self-taught British mathematician. In 1854, Boole published a book that established an algebraic way of thinking about logic and about logical operations such as AND, OR, and NOT. Boole’s algebra provides the basis for all digital circuits.


For more information
We hope you found the Chapter 1 informative. To go back to the Main Page, click here.

You can purchase the complete Digital I/O Handbook for only $19.95 by clicking here. The Digital I/O Handbook is FREE with any qualifying Sealevel Digital I/O product purchase. You can find a listing of all Sealevel Digital I/O products by clicking here.


]]>
Wed, 09 Dec 2009 13:52:28 -0500