CHAPTER 16 RESOURCES prudent for high-current applications, even at lower voltages, simply to avoid the risk of damaging the relatively sensitive circuitry in the Arduino and/or connected devices. Semiconductor and Mechanical Switches For practical applications, there are two broad types of switching devices available: semiconductor and mechanical. Semiconductor devices include a few different types of transistors, optocouplers, and solid state relays (SSRs); mechanical devices come down to different types of relays. Solid state devices are often physically smaller, consume less power, and are able to switch more rapidly than mechanical devices because there are no moving parts. The lack of moving parts nominally makes semiconductors more reliable, but well-designed relay circuits will often last just as long. Only certain classes of semiconductor devices provide electrical isolation between input and output. Some solid state devices are a little trickier to use and less forgiving if used incorrectly. Mechanical switching devices have the advantages of providing electrical isolation, being pretty bulletproof to design with, and are easily understood. On the downside, they tend to need higher drive currents and so can themselves need additional circuitry to be driven from the Arduino. They are also limited in switching frequency. This latter limitation can manifest as either being unable to switch fast enough to support higher frequencies or wearing out too quickly—limited number of cycles. As a rule of thumb, switching frequencies of 1Hz or faster for any continually operated circuit with a mechanical relay is marginal at best. Having discussed some of the general issues in selecting output circuits, we now look at some practical examples. Reed Relays Reed relays consist of a switching element (the “reed”) within a coil of wire. When current flows through the energized coil, the resulting magnetic field closes or, in some cases, opens the contacts. If the switch is open when the coil is off, the relay is said to be “Normally Open” or “NO.” If the switch is closed then the device is “Normally Closed” or “NC.” Some reed relays have both NC and NO contacts. The construction of the relay provides a high degree of electrical isolation, but because the contacts within the reed are quite small, the contacts have limited current- and voltage-handling capability. However, the small size of the contacts has an upside: only quite small currents (typically under 15mA) are needed to keep the coil energized and the contacts closed. Reed relays commonly have coil voltages designed to be compatible with 5V digital circuitry, and so in many cases can be driven directly by the Arduino. Figure 16-5 is a schematic of a reed relay connected in this manner. 389 CHAPTER 16 RESOURCES Figure 16-5. Reed relay driven by an Arduino output pin Note When driving devices that have a coil or filament, such as a relay or incandescent light bulb, bear in mind that such devices have both a peak and steady state current requirement. Peak current is drawn while the magnetic field is stabilizing or the filament heating up before it falls to the steady state value. Your chosen drive circuit (or lack thereof if directly connected to the Arduino) must be able to cope with this current transient. When current is removed from devices with a coil, the magnetic field collapses and a reverse or “Back-EMF” voltage is generated. Depending on the type of device and circuit configuration, this voltage can be several tens of volts and will have the opposite sign of the supply circuit. It is possible for this voltage transient to damage the drive circuit if it is not suitably protected. Notice in Figure 16-5 that there is a diode connected across the coil of the reed relay. This diode soaks up or “quenches” this reverse transient. Relays Relays are a variation on the reed relay previously described and differ primarily in their mechanical construction. Typically, the coil of wire, or solenoid, causes a lever to move that opens and/or closes the relay contacts. Relays typically have higher voltage and current ratings at the expense of slightly slower switching speed and higher coil current. In the advantages column, these higher voltage and current ratings are joined by greater flexibility in contact configurations—multiple poles (separate switches) and changeover (NC + NO) is commonplace. The somewhat higher current demands of a conventional coil relay generally precludes driving them directly from the Arduino. If only one or two relays are being used, then a simple bipolar transistor, as discussed in the next section, will do the job nicely. If four or more relays are being used, it is worth considering a specialized transistor array or driver chip, which we touch on later in the Transistor Arrays section. 390 CHAPTER 16 RESOURCES Figure 16-6 shows a relay being driven from the Arduino using a conventional bipolar transistor to provide additional current-handling capability. Note that like the reed relay circuit in Figure 16-5, a back-EMF diode is used. We describe this circuit further in the next section. Figure 16-6. Bipolar transistor used to drive a relay Note Mechanical contacts like those used in reed relays, conventional relays, and switches have a minor design quirk that you should be aware of if you’re designing for high-reliability applications. With the exception of exotic “wetted” contacts, it’s desirable to ensure at least 10mA or so flows through the contacts when on in order to ensure they stay free of oxidization and corrosion. If you’re just tinkering, it’s pretty safe to ignore this, though! Bipolar Transistors The first semiconductor output device we consider is the humble bipolar transistor. Bipolar transistors come in two basic types: NPN and PNP. The N and P refer to the semiconductor material used to construct the device; in practice it denotes how the device needs to be used. In digital applications, bipolar transistors can be considered an electronic switch allowing something like a low-power microcontroller to control higher currents. A small current flowing through the base (B in Figure 16-6) controls the larger current flowing collector to emitter (C and E, respectively, in Figure 16-6). If the current flowing into the base is sufficiently high, the transistor is said to “saturate,” or turn completely on, and so has very little resistance or power dissipation. 391 CHAPTER 16 RESOURCES Note Transistors are also commonly used in analog circuits outside their saturation region where the collector to emitter current varies proportionally with the base current. This is the basis of virtually all analog circuitry such as amplifiers, oscillators, and so forth. When the transistor is operating in this manner, it will dissipate power (in the form of heat) in proportion to its (now higher) on resistance. Well designed analog circuitry, of course, accounts for this by using heatsinks. We don’t dig into this topic further in Practical Arduino, however. Looking back out our relay drive circuit, we are making use of an NPN transistor in a common emitter or low-side switch configuration. Note that the emitter pin is connected to ground and the collector to the “low” side of the relay coil or load. Common bipolar transistors are capable of switching a few hundred milliamperes up to amps, depending on the type chosen. Switching frequencies can easily run to several megahertz and well beyond this if appropriate devices and circuit configurations are used. For practical applications, bipolar transistors make a good and simple choice for switching currents up to an amp or two. For currents higher than this, it is worth considering FETs which we discuss in a moment. Transistor Arrays Transistor arrays, as the name suggests, are devices that have many transistors in the same package. The principle advantage is packaging density and convenience—a single 18-pin DIP device can provide seven or eight transistors configured as high- or low-side switches. The ULN2003 is perhaps the best known part and provides eight transistors that can switch around 500mA each in a low-side (or common emitter) configuration. Slightly less common is the UDN2981, which provides eight high-side switches that can source around 500mA per output. For both devices, consult the datasheet to check that you are operating them within their limits, particularly if you are getting close to maximum per-pin current as it is possible to exceed overall device limits. FETs FETs, or field effect transistors are, like bipolar transistors, an electronic switch. Their internal construction differs in the way the semiconductor materials are laid out, most notably in the gate, the pin that is functionally similar to the base of a bipolar transistor. The other two pins of a FET, the drain and source pins, roughly correspond to the collector and emitter, respectively, of a bipolar transistor. Metal-oxide–semiconductor field-effect transistors (MOSFETS) are the most common form of FET. At the risk of offending purists, we will use the terms interchangeably hereafter. The internal construction of the MOSFET is such that the gate terminal exhibits a very high resistance (or impedance) relative to the source and drain pins—it is effectively a capacitor. In practice, this means that the device requires very little current to switch on fully. When switched completely on, MOSFETs have a very low on resistance, less than that of a bipolar transistor, making them an excellent choice for high-current applications. The main design considerations with a FET is that it be switched on (or off) very quickly because its ability to cope with being in the intermediate region is limited, and that adequate gate voltage is applied relative to the supply voltage. 392 CHAPTER 16 RESOURCES Optocouplers In practical applications, optocouplers slot into a similar niche as reed relays in being suited to switching relatively low currents in situations where electrical isolation is required. As such, they are useful in situations where a low-power system needs to control a high-power system. If you need to turn on/off a 250V motor, you really don’t want to run the risk of that 250V getting back into your 5V Arduino. Optocouplers allow an Arduino to control scary devices, and limit the risk of blowing out the ICs on the ATMega. Optocouplers are used when good engineering practices dictate isolating a potentially harmful system. Internally, optocouplers have an LED on the “input” side that is optically coupled to a switching device, often an FET or bipolar transistor on the “load” side. This absence of moving parts yields higher switching speeds (typically a few milliseconds or even microseconds for some devices) and higher reliability. Typical optocouplers can switch around 150mA at 40V, so they are really most useful as an isolation device. However, they have a big cousin in the form of solid state relays. Solid State Relays Solid state relays (SSRs) combine the isolation and current-handling capabilities of conventional relays with the lack-of-moving parts benefits of optocouplers. Hence, they can switch high currents and voltages at high speeds (milliseconds) reliably for many on/off cycles and have low drive currents so can be driven directly from the Arduino. There are various different package styles: PCB-mount units handling up to 5A at 240VAC, and larger units designed to bolt to a chassis coping with even greater currents. Most units designed for AC use provide “zero crossing switching,” meaning the output is switched on when the AC supply is at the zero point. This makes for a more gentle on transition, reducing wear on the load and electrical noise. There are a few gotchas when using SSRs. Some devices have a minimum load current below which they might not switch reliably. The leakage current when a device is off can be relatively high—a few milliamperes, which can result in unnecessary power usage for infrequently used devices. Finally, if an SSR fails, they often do so in the “on” state, meaning the load will remain energized in the failure state, which might not be desirable depending on your application. Digital Input/Output Expansion The Arduino has 20 general-purpose I/O pins, which is more than enough for most projects. However, there are situations where more inputs or outputs are required. By making use of the Arduino’s SPI support, we can use a simple logic element—a shift register—to provide virtually unlimited digital input or output capabilities. Shift Registers As Outputs When using a shift register to provide outputs, we must provide three signals from the Arduino: clock (CLK), data (D), and latch (Q). We might also want to provide an output enable (OE) signal so that the outputs remain off until we initialize them properly. 393 CHAPTER 16 RESOURCES Note The small number of signals required to provide additional outputs can also be helpful if the driven devices are located a short distance from the Arduino itself. Thus instead of running, say, eight wires plus power and ground, you can run three or four and power/ground. Taking the example in Figure 16-7, we have a single eight-output serial in parallel out shift register/latch connected to the Arduino. To set Output 3 high and all other outputs low, we would set D low, transition CLK Low-High four times, set D high, transition CLK Low-High once, set D low again, then transition CLK a further three times. Thus, we “shift” in the sequence 00001000 into the register. Finally, we transition the Q (latch) signal Low-High-Low to move this new pattern to the output pins themselves. Figure 16-7. Adding output pins with single eight-output shift register Compare now with Figure 16-8 where we have two eight-output latches connected. The number of pins used on the Arduino stays the same. We simply daisy chain the Data Out from the first latch to the Data In on the second. We now must shift 16 bits to fully define the state of the outputs. This basic arrangement can be repeated many times over. The main limitation is the number of CLK and Q signals that can be driven from the Arduino—anything over 16 could be marginal. 394 CHAPTER 16 RESOURCES Figure 16-8. Cascading multiple shift registers for more output pins This approach to outputs doesn’t come entirely free. As you’ll probably have guessed, each update to the output pins will take a few dozen instructions being executed by the CPU to clock the data out rather than a single write to the relevant port. However, if the Arduino’s internal UART is used in SPI mode, this overhead can be reduced. For practical applications, there are at least a few devices to consider. The 74HC595 is a basic logic level serial in/parallel out shift register. It’s good for about 20mA per pin tops, and is inexpensive and easy to find. A little more expensive, but more versatile, is the TPIC6595, which is essentially a 74HC595 and ULN2003 combined. It’s a serial in/parallel out shift register with high current drivers—about 200mA per pin. Note PWM with shift-register based outputs is still possible, it just requires software to generate the relevant output signals. Look at using a timer to generate an interrupt to run a routine to do the calculations and shift out the new data at regular intervals. Alternatively, if you merely want to do PWM on all outputs the same (such as for dimming an LED display at night), you could use a hardware PWM pin to drive the OE signal of the latches. A caveat to this approach: if the display itself is multiplexed, you could get odd issues with flickering, depending on the phase relationship of the two. Shift Registers As Inputs As you might guess, there is a complementary device to those previously mentioned for output expansion: the parallel-load shift register. An example would be the 74HC165, this being a commonly available part. The principle of operation is very similar to that used for the output circuit. The Arduino provides a clock (CLK) and load (LD) signal using a pair of output pins, and senses the state of the data (D) line back from the shift register using an input pin. 395 CHAPTER 16 RESOURCES The state of the inputs is loaded (or “latched”) into the shift register by transitioning the LD pin High-Low-High. For each of the 16 bits, we transition the CLK pin Low-High-Low, reading the state of the D pin, which the yields the state of each input in turn. Input Conditioning In the previous section, we discussed various techniques for driving external loads that required higher currents and/or operating voltages than those that the Arduino can provide directly. In the same way that the Arduino, or more specifically the ATMega168, can only provide limited output currents/voltages, it can only tolerate limited input voltages, too. Typically, the maximum voltage applied to an input pin should be the same as the supply voltage —5V in most Arduino boards. If it is necessary to deal with inputs that use higher voltages than the supply rail, there are a few techniques at your disposal. The choice largely comes down to whether isolation is required (for example, if mains is involved) or if the environment is electrically noisy. Voltage Dividers and Nonisolated Input Conditioning Figure 16-9 shows two resistors connected in series in what is called a “voltage divider.” The voltage applied to the top of the divider is 15V and, intuitively, we know that all the resultant current must disappear within the divider circuit (ignoring what we tap through the output connection). It follows, then, that the voltage across each resistor must be some fraction of the input voltage—the fraction being dependent on the resistor value. Figure 16-9. A simple voltage divider 396 CHAPTER 16 RESOURCES The values chosen of 20k and 10k mean that for a 15V input, we will get 5V out; for 3V in, 1V out; and so on. We now have a simple way of monitoring voltages or inputs that are greater than the 5V or 3V3 limit on Arduino input pins. This same circuit can be used for digital and analog inputs. While the simple divider shown will work fine in benign environments, in noisier or less controlled situations, such as monitoring a battery or the state of the headlights of your car, it’s prudent to add some additional circuitry. This can be as simple as adding a Zener diode, as shown in Figure 16-10. Zener diodes in this configuration act as a voltage-sensitive switch of sorts. While below their operating voltage, their resistance is very high—essentially they’re “off.” Once the operating voltage is reached, the resistance drops dramatically. In the case of our circuit, this effectively ensures that the voltage is clamped at 5.1V. A word of caution here: Zener diodes used in this manner aren’t perfect and might not catch very fast transients or spikes. Further, if they are used to protect an analogu input, their tendency to start conducting below their rated voltage can have the effect of introducing nonlinearity into the circuit near the maximum input. Figure 16-10. Zener-protected input conditioning circuit Oh, and please don’t even think about using a voltage divider to reduce mains voltage down into an Arduino pin without proper isolation! Note A variable resistor, or “pot,” forms a voltage divider if wired in a similar manner to that in Figure 16-9. One end of the pot goes to 5V, the other end to ground, and the wiper (typically the center pin) to the Arduino input. This can provide an inexpensive way of adding a knob to a project to set some value. 397 CHAPTER 16 RESOURCES Isolated Input Conditioning Earlier in this section we discussed output circuits that electrically isolated the switched device from the Arduino. Often, it’s desirable to go the other direction and isolate a signal we’re monitoring from the Arduino. Once again, optocouplers come to the rescue. The circuit in Figure 16-11 shows a simple isolated digital input. The input side can be virtually any voltage, provided the resistor value is selected so that no more than 10mA flows through the LED side of the optocoupler. We provide a few suggested values in the diagram for various input voltages. Figure 16-11. An optically isolated digital input It’s also possible to isolate analog signals, but this is a more complex topic. As a starting point, if you’re looking to isolate an AC signal consider a small transformer and some filtering circuitry. To deal with an AC or DC signal, dig into purpose-built analog isolation using devices like Isolation Amplifiers— Burr Brown ISO100 being the start of a long line of these specialist devices. Note We can apply the principle of this optocoupler-based isolation circuit to provide a mains synchronised 50Hz/60Hz reference signal. Figure 16-12 shows the general approach: 12 VAC is provided from a plugpack/wall wart to power the LED in the optocoupler. The external diode means that the optocoupler only sees voltage for one half of the mains cycle and so the transistor will be turned on at 50 or 60Hz depending on the local mains frequency. The external diode is preferred to relying on the LEDs own diode action because it ensures the reverse voltage on the optocoupler isn’t exceeded. The plugpack can, of course, be used to power the rest of the circuitry through a suitable bridge rectifier, filter, and regulator. 398 . circuit configurations are used. For practical applications, bipolar transistors make a good and simple choice for switching currents up to an amp or two. For currents higher than this, it. The Arduino has 20 general-purpose I/O pins, which is more than enough for most projects. However, there are situations where more inputs or outputs are required. By making use of the Arduino s. down into an Arduino pin without proper isolation! Note A variable resistor, or pot, ” forms a voltage divider if wired in a similar manner to that in Figure 16-9. One end of the pot goes to