Physics 3150/5190 Electronics Lab Manual University of Virginia Fall 2012 -V Vs Verr Instructor: Cass Sackett CONTENTS CONTENTS Contents 1 Test and Measurement Tools 1.1 ELVIS . . . . . . . . . . . . . . . . . 1.2 Power Supplies . . . . . . . . . . . . 1.3 Virtual DMM . . . . . . . . . . . . . 1.4 Measuring Current . . . . . . . . . . 1.5 Ohm’s Law . . . . . . . . . . . . . . 1.6 Violating Ohm’s Law . . . . . . . . . 1.7 Electrical Safety . . . . . . . . . . . . 1.8 Resistor Properties . . . . . . . . . . 1.9 Oscilloscope and Function Generator 1.10 Triggering Options . . . . . . . . . . 1.11 RC Circuit . . . . . . . . . . . . . . . 1.12 Transformer . . . . . . . . . . . . . . 1.13 Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4 5 5 5 5 6 6 7 7 9 10 11 11 2 Impedance and Transfer Functions 2.1 Voltage Divider . . . . . . . . . . . 2.2 Cascading Circuits . . . . . . . . . 2.3 DMM Impedance . . . . . . . . . . 2.4 RC Filter . . . . . . . . . . . . . . 2.5 Bode Analyzer . . . . . . . . . . . 2.6 Filtering Signals . . . . . . . . . . . 2.7 Cascaded Filter . . . . . . . . . . . 2.8 Scope Impedance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 12 13 13 14 15 15 16 16 3 Diodes 3.1 Current vs. Voltage . 3.2 Diode Drop . . . . . 3.3 Power Diodes . . . . 3.4 Rectifiers . . . . . . . 3.5 Filtering and Ripple 3.6 Zener Diodes . . . . 3.7 Diode Clamps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 18 19 19 20 20 21 21 . . . . . . . 24 24 26 26 28 28 30 31 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Transistors 4.1 IV Relations . . . . . . . . . 4.2 Transistor Switch . . . . . . 4.3 Emitter Follower . . . . . . 4.4 Common-Emitter Amplifier 4.5 Field Effect Transistors . . . 4.6 FET Switch . . . . . . . . . 4.7 FET Follower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CONTENTS CONTENTS 5 Op 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 Amps I Installation . . . . . . . . . . Open-Loop Test . . . . . . . . Inverting Amplifier . . . . . . Non-inverting Amplifier . . . Follower . . . . . . . . . . . . Summing Amplifier . . . . . . Current Sources . . . . . . . . Current to Voltage Converter Logarithmic Amplifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 33 34 34 35 35 36 36 37 38 6 Op 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 Amps II Output Capacity . . Offset Voltage . . . . Bias Current . . . . . Johnson Noise . . . . Slew Rate . . . . . . Frequency Response Integrator . . . . . . Differentiator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 39 40 40 41 41 41 43 44 . . . . . . . 45 45 46 46 47 49 50 50 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Feedback and Control 7.1 LED Driver . . . . . . . . . . . . 7.2 Photodiode . . . . . . . . . . . . 7.3 Summing Amplifier and Set Point 7.4 System Response . . . . . . . . . 7.5 Feedback . . . . . . . . . . . . . . 7.6 Servo Performance . . . . . . . . 7.7 Servo Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Feedback and Control II 8.1 Proportional Control . 8.2 Integral Control . . . . 8.3 PI Control . . . . . . . 8.4 PID Control . . . . . . 8.5 Transient Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 53 54 55 55 57 9 Logic Gates 9.1 Transistor Gates . . 9.2 Integrated Gates . . 9.3 Logic Families . . . . 9.4 CMOS Logic . . . . . 9.5 Combinatorial Logic 9.6 Three-State Logic . . 9.7 Multiplexer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 60 61 62 63 64 64 65 . . . . . . . 2 CONTENTS 9.8 9.9 CONTENTS Monostable Multivibrator . . . . . . . . . . . . . . . . . . . . . . . . . . . . Logic Races . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 67 10 Flip-Flops, Memory, and State Machines 10.1 D-type Flip Flop . . . . . . . . . . . . . . 10.2 State Machines . . . . . . . . . . . . . . . 10.3 Switch Debouncing . . . . . . . . . . . . . 10.4 RAM . . . . . . . . . . . . . . . . . . . . . 10.5 Memory-Based State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 69 70 71 72 75 11 Counters and Oscillators 11.1 Binary Counter . . . . . . 11.2 LED Display . . . . . . . 11.3 Binary-Coded Decimal . . 11.4 Timer . . . . . . . . . . . 11.5 Quartz Crystal Oscillators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 77 78 78 79 80 . . . . . . . 82 82 83 84 85 86 86 87 . . . . . . . . 89 89 90 92 93 94 95 96 97 . . . . 98 98 98 98 99 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Converting Between Digital and Analog 12.1 Comparator . . . . . . . . . . . . . . . . 12.2 Schmitt Trigger . . . . . . . . . . . . . . 12.3 The AD7569 DAC/ADC . . . . . . . . . 12.4 Negative Supply . . . . . . . . . . . . . . 12.5 DAC . . . . . . . . . . . . . . . . . . . . 12.6 ADC . . . . . . . . . . . . . . . . . . . . 12.7 Nyquist Sampling Theorem . . . . . . . 13 Microcontrollers 13.1 The mbed Microcontroller . . . 13.2 Digital Inputs and Outputs . . 13.3 Arbitrary Waveform Generator 13.4 LCD Display . . . . . . . . . . 13.5 Voltmeter . . . . . . . . . . . . 13.6 Communication with PC . . . . 13.7 Multi-Channel Analyzer . . . . 13.8 Wrap Up . . . . . . . . . . . . . A Excel Plots A.1 Creating a Chart . A.2 Modifying a Chart A.3 Fitting Data . . . . A.4 Excel 2007 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 TEST AND MEASUREMENT TOOLS 1 Test and Measurement Tools This exercise is intended to familiarize you with the measurement tools we will be using throughout the course, specifically the ELVIS system, the digital multimeter, and the oscilloscope. It also serves to remind you how resistors and capacitors work. This lab will require two days. Reading: HH sections 1.01–1.15, Appendix A (pgs. 1–28, 1045–1049) 1.1 ELVIS We will be doing most of our work on the NI ELVIS II system, which consists of a breadboard, several built-in interfaces to the computer, and a set of software tools running on the computer that duplicate the functions of some common test instruments. Take a moment to orient yourself with the board. The large white square in the middle is the breadboard proper, where you will set up your circuits by pressing leads into the small holes. The numbered rows are connected internally in horizontal groups of five, while the ‘+’ and ‘-’ buses are connected vertically down the whole board. Note that another manufacturer’s breadboard might be connected differently, even if they look the same. It is always a good idea to check which contacts are connected when working with a new breadboard. Let us do that now with the ELVIS board. A convenient instrument for this purpose is the Fluke 73III Digital Multimeter (DMM). The DMM can measure voltages, currents and resistances. Here we will be interested in resistance, so turn the selector knob the DMM to the resistance (Ω) setting. Plug a pair of test probes into the red (V -Ω-diode) input and the black (COM) inputs of the DMM. Use a pair of short hook-up wires from your wire box to reach two contacts you want to check, and then hook the leads of the DMM to the exposed ends of the wires. The resistance should be zero if the contacts are connected, or infinite (reading ‘O.L’ for overload) if they are not. Are the contacts are connected as described above? Are the different columns labeled ‘+’ connected together? The smaller white rectangles on the edges are interface connections. Each row is hooked up to a device that can interact with the computer, or to one of the connectors on the edge of the board. We will often use the block in the lower left corner, which provides access to the built-in power supplies and connectors. The connectors on the left edge of the box itself are measurement inputs to the virtual DMM and and oscilloscope. The knobs on the right side of the box allow manual adjustment of some of the virtual instruments, but we will not often have occasion to use them. The contact blocks on the right side of the breadboard are for digital measurements, which we will use in the second half of the course. The board has two power switches. The one in the back controls the whole unit. It is easiest to turn this switch on at the beginning of class and leave it on throughout the lab session. The second switch, near the upper right corner of the board, controls the power supplies for your circuitry. It is best to turn that off when assembling a circuit and then turn it on for testing, to avoid damaging circuit components during assembly. 4 1.2 Power Supplies 1.2 1 TEST AND MEASUREMENT TOOLS Power Supplies The ELVIS breadboard has several dc power supplies. Locate the +5 V and ±15 V supply contacts on the breadboard. To verify that they do supply these voltages, use the voltmeter function on your DMM. Turn the selector knob to the dc volts (V̄ ) setting. Keep the probes in the red and black inputs, and hook the red probe to the supply contact and the black probe to ground. (Note that there are several ground connections on the board; they are all the same.) The display will indicate the measured voltage. Record each in your report, and note any discrepancies from expectation. ELVIS also has a pair of variable-voltage supplies that will be useful. They are controlled from the computer. First, find the ELVIS Instrument Launcher icon on the desktop or Start Menu. Start the Launcher and then double-click to start the Variable Power Supply (VPS) virtual instrument. In the resulting window, set the positive supply output to 10 V and press Run. Then locate the positive VPS contact on the breadboard and measure its voltage (again relative to ground); you should see 10 V. Similarly, set the negative supply to -10 V and check it. Measure both supplies across a full range of values, and make a chart in your report showing the measured vs. set voltages. How accurate are the VPS set points? Are there any voltage regions where the accuracy is poor? (Hint: the answer to the second question is yes, and it will be useful for you to know where these regions are.) 1.3 Virtual DMM The ELVIS system provides a virtual DMM you can use in addition to the Fluke. To start it, run the DMM instrument from the launcher and press Run in the DMM window. The input connections are located on the left side of the ELVIS box, and you can use them to hook up probe leads just like on the Fluke. Compare the readings of the Fluke and the ELVIS DMMs for various settings on the VPS supplies. Record your measurements in your report. How well do the Fluke DMM and ELVIS DMM agree? 1.4 Measuring Current The DMM can also serve as a current meter. To test this, set up the circuit of Fig. 1.1, using the Fluke DMM inputs indicated. You can obtain the 1 kΩ resistor from the component cabinets in the back of the lab. Note that when using a DMM as a current meter, it is up to you to make sure that the current rating (here 300 mA) is not exceeded. If you do exceed the limit, you will blow an internal fuse and have to fix it. Power up the circuit and measure the current that flows. The DMM selector knob should be set to dc amps (Ā). Make the same measurement with the ELVIS DMM. How well to the Fluke and ELVIS DMMs agree? 1.5 Ohm’s Law Devise and set up a circuit to simultaneously measure the voltage and current across a 1 kΩ resistor, and describe the circuit in your lab report. Take several points and create a plot 5 1.6 Violating Ohm’s Law 1 TEST AND MEASUREMENT TOOLS 300 mA COM Figure 1.1: Using the DMM current meter. to verify that V = IR. How does the resistance obtained from your data compare to that measured with the DMM ohmmeter? Instead of taking data like this by hand, you can use the ELVIS two-wire IV Analyzer instrument. Put a resistor between the DUT+ and DUT- contacts, near the top of the lower left block. (Here DUT stands for ‘Device Under Test.’) Open up the 2-wire instrument and set the sweep to run from -10 V to +10 V, with a sensible increment. Press Run and admire the nice straight line. To transfer the data to your report, first save the data by pressing the Log button. Pick a file name and save it on the desktop or in a convenient folder. Then open the file using Notepad (or a similar program) and cut and paste the data into your Excel report. Add this data as a new series to the chart you previously made by hand and compare. 1.6 Violating Ohm’s Law Many devices do not follow Ohm’s Law, including an ordinary incandescent lamp. Obtain two 6.3 V/150 mA lamps from the supply cabinet. The lamp resistance is a little too low to measure with the IV Analyzer, so wire two lamps in series to make a larger resistance. Set the analyzer to run from 0 to 1 V with a 0.1 V increment, and make sure the gain is set to Low. (High gain is useful for low-current devices.) If the analyzer complains that you’ve exceeded the current limit, reduce the final voltage. Import the data and plot it in your report. Why do you suppose that Ohm’s law is not obeyed here? 1.7 Electrical Safety Use an ohmmeter to measure to the resistance of your body by holding one lead in each hand. You should obtain a value in the MΩ range. Compare different places on your skin, and measure the effect of wetting your skin with saliva. You can be injured by electrical current. You can typically feel a mA or so, while about 100 mA can be lethal. Given the resistances you measured, you might expect that a quite large voltage would be required to generate a 100 mA current. This may be confusing, since most people are aware that 120 Vac power from a wall socket can be dangerous. The resolution is that your body is not a ohmic resistor. As the voltage increases, the resistance can drop significantly as your skin resistance breaks down. The values you measured with the ohmmeter are not, therefore, usually relevant for safety concerns. 6 1.8 Resistor Properties 1 TEST AND MEASUREMENT TOOLS A good rule to follow is to be careful with any electrical device that can supply more than 2 mA current at more than 20 V voltage. If either the current or voltage are definitely below these values, no special precautions are needed. We should not be encountering any dangerous voltages in this class. Besides the direct effect on your body, high currents can cause electrical components to get very hot. This is unlikely to be lethal in most situations, but you can receive a painful burn if you incautiously touch a hot resistor with your finger. A good rule here is to turn off your circuit power if you start to smell a burning odor. Let everything cool off for a minute before working on it. 1.8 Resistor Properties Obtain a 470 Ω and a 330 Ω resistor, and use your DMM to measure the individual resistances and the total resistance of the two in parallel and in series. Do the results agree with calculations? The resistors we use are rated for a power dissipation of 1/4 W or 1/2 W. Obtain a 39 Ω resistor and test it using the circuit of Fig. 1.2. Start with the VPS voltage low, and slowly turn it up until you smell a burning odor, see smoke, or notice the resistor start to char. Turn off the board power once this occurs. Noting the voltage used, what power cause the resistor to overheat? Discard the overheated resistor once you are done, and try to avoid doing this in the future. A potentiometer (or ‘pot’) is a variable resistor that can be adjusted by turning a knob. Obtain a 10k pot from the supply cabinet. It has three terminals, as illustrated in Fig. 1.3. A small screwdriver or a potentiometer driver is useful for adjusting the knob. Using your DMM, determine which pin corresponds to which terminal. What are the maximum and minimum resistance values achievable? How many full turns of the knob does it take to go from one extreme to the other? 1.9 Oscilloscope and Function Generator We now turn to the measurement of time varying, or ac, signals. You can produce an ac signal using the ELVIS function generator. Find and open the FGEN virtual instrument on your computer. Select a sine wave signal, set the frequency to 50 Hz and the amplitude to Figure 1.2: Measure the power capacity of a resistor. Figure 1.3: Potentiometer configuration. The connection point for pin B moves as the knob is rotated. 7 1.9 Oscilloscope and Function Generator 1 TEST AND MEASUREMENT TOOLS Figure 1.4: Oscilloscope controls. 1 Vpp, and press the Run button. The signal can be output in two places, as determined by the Signal Routing setting. The circuit board output is produced at a contact row on the lower left block of the breadboard. The edge connector output appears on one of the BNC connectors at the left of the board unit. Only one is available at a time, and usually the circuit board output is more convenient. Find this, and measure the voltage between it and ground using your DMM. On the dc voltage setting, the meter should read zero. What does the ac voltage (Ve ) setting read, and does it makes sense given the function generator amplitude? Much more information about an ac signal can be obtained using an oscilloscope. This is a complex instrument, but one that you shall be relying on throughout the course. If you are unfamiliar with oscilloscopes, you should read through Appendix A of Horowitz and Hill. Figure 1.4 shows a picture of your oscilloscope front panel. To monitor the signal with the scope, use a BNC cable with test lead clips. Plug the cable end in to the Channel 1 input (#6 on the left). The black test clip is attached to the shield of the BNC cable and thence to ground through the oscilloscope. Attaching it to ground in your circuit is good practice because it provides better shielding and noise reduction, but the lead is grounded whether you hook it up or not. If you attach it to an arbitrary point in your circuit it will ground that point, which is probably not what you meant to do. Here, attach the clip to your breadboard ground with a wire. Hook the red clip to the FGEN output. Turn the scope on (#1), set the sensitivity (#9) to 1 V/div, and the time base to 1 ms/div, using the rocker switch (#18). Make sure the trigger source (#21) is set to Ch 1 and the 8 1.10 Triggering Options 1 TEST AND MEASUREMENT TOOLS trigger mode (#22) to AUTO. Set the function generator to output a 5 Vpp, 500 Hz sine wave, and run it. You should see the waveform displayed on your scope. Try adjusting the trace position (#11) and trigger level (#23). The horizontal trace position can be changed using the Variables knob (#16) when the “H POS” indicator is selected using the Selector switch (#15). Note that the scope defaults to an input setting for a 10× probe, as can be seen on the screen display of the amplitude calibration. We will introduce these probes in the next lab. For now, change the setting to a 1× probe by holding down the Selector switch and rotating the Variables knob. The Selector switch can also be used to provide vertical and horizontal screen cursors, which are useful for making measurements with the scope. Press the Selector switch down until the Measure indicator is lit. The quantity to be measured is printed in the top line of the CRT display. Set the measurement to ∆V , so that two horizontal cursors are displayed. Pressing the Cursor button (#17) selects which cursor is active, and rotating the Variables knob (#16) adjusts the position of the active cursor. Adjust the cursors to sit at the top and bottom of the waveform, and read off the peak-to-peak amplitude. Does it agree with the function generator setting and with the volts per division scale calibration? Press the Selector switch again to measure ∆T and check the period of the waveform. Then select the Freq measurement, for which the oscilloscope should automatically measure the signal frequency. Record your observations. Try changing the frequency, amplitude, waveform, and DC offset of the function generator. Make sure that you can adjust the scope to compensate. The trigger level (#23) sets the voltage threshold at which the display trace begins each cycle. If you have difficulty obtaining a steady trace, it is probably because the trigger level is set incorrectly. Make sure that you understand how it works. In general, do the the observed signals agrees with the settings? Does anything special happen at high frequencies? The two small buttons next to the Volt/Div knobs, (#7) and (#8), control the input coupling to the scope. In DC mode, the scope displays the voltage directly. In AC mode, the signal is coupled through a high pass filter, which blocks the dc signal component. This is useful when you are looking at a small ac signal on top of a large dc offset, but confusing if you are trying to look at a dc signal and don’t realize the scope is in AC mode. When the GND button is pushed in, the input is ignored and a flat trace at 0 V is displayed. This is useful for locating the 0 V level, but can again be confusing if the button is pushed and you don’t realize it. Explore both of these buttons and make sure you understand their functions. 1.10 Triggering Options It can be tedious to keep adjusting the trigger settings when the signal levels are changing. A convenient solution is to use the Sync output of the function generator. Observe the Sync output on channel 2 of the scope, by applying the signal to the Ch 2 input (#6, on the right) and setting the vertical mode (#13) to DUAL. You should observe that the Sync provides a square wave at the signal frequency with unvarying amplitude and offset. This makes it ideal for triggering the oscilloscope. Since it is not itself interesting to look at, hook the Sync signal up to the EXT input 9 1.11 RC Circuit 1 TEST AND MEASUREMENT TOOLS (#27) and set the trigger source (#21) to EXT DC. Turn the vertical mode back to Ch 1 and adjust the trigger level to provide a steady trace. Now as the function generator parameters are varied, the scope should maintain a stable trigger. Another important trigger option is the mode (#22). Only two options, AUTO and NORM are generally useful. In NORM mode, the scope will start a trace only when it gets a trigger. To see this effect, go to NORM mode and readjust the scope to trigger on the function generator signal (Ch 1). When you adjust the trigger level to a voltage outside the signal range, the scope should not trigger, presenting a blank screen. In AUTO mode, the scope will wait a short time for a trigger, but if none is received, it will automatically start a trace. The waiting time is termed the holdoff, and it can be set with the Selector button and the Variables knob. Put the scope in AUTO mode, and compare what you observe to what you saw in NORM mode. Can you think some reasons it could be useful to have both modes available? Figure 1.5: RC circuit. 1.11 RC Circuit The RC circuit consists of a resistor and capacitor in series, as seen in Fig. 1.5. It finds a variety of uses in electronics. Here you will use an oscilloscope to observe its dynamic response. Set up the circuit, and drive it with a 1 kHz square wave from your function generator. Put the drive signal on the scope channel 1 and the output on channel 2, so you can see both input and response. The response should be an exponential wave form Vout = A + Be−t/RC starting with each input transition. Measure the exponential time constant by determining the time required to decay by 1/e ≈ 63%, and verify that it agrees with expectation. You can check the the value of R with your ohmmeter, and of C using the ELVIS DMM. (Note that you need to use the DUT contacts on the breadboard to measure C.) You can also measure R and C using the component tester at the back of the lab. Try driving the circuit with a triangle wave and a sine wave, and briefly describe what you see in your report. With the sine wave, observe what happens as you increase the drive √ frequency. At what frequency is the amplitude reduced by 2 from its input value? 10 1.12 Transformer 1 TEST AND MEASUREMENT TOOLS Figure 1.6: Combining the transformer with a dc signal. 1.12 Transformer The last piece of equipment we will explore in this exercise is a transformer. This is enclosed in a gray box labeled “6.3 V/1 A.” There are two styles of box: one has white, black and green outputs while the other has blue and brown. The green output is earth ground, while the other pair are the transformer outputs. The two outputs are symmetric and interchangable. The transformer provides a sine wave signal at 60 Hz which will be occasionally required when the function generator is already being used for another purpose. In addition, the transformer output is floating with respect to ground, in much the same way that terminals in a battery are. Because of this, it can be added to another signal by simply placing the two sources in series. Figure 1.6 shows an example. Here the 110 Vac connection is made by plugging the transformer box into a wall socket. Construct this circuit and observe the output on the oscilloscope. Verfiy that the dc level is set by the VPS supply. What is the amplitude of the ac wave component? 1.13 Reporting You should have been recording your data, observations, and question answers in your Excel spreadsheet as you proceeded through the lab. Take a moment now to look over it and make sure it is clear and organized in a coherent way. At the top of the report, indicate the lab number and the names of the students participating. Once you are satisfied, save a copy and email it to the instructor. 11 2 IMPEDANCE AND TRANSFER FUNCTIONS 2 Impedance and Transfer Functions The concepts of impedance and transfer functions are are essential for a clear understanding of analog electronic circuits. This exercise will explore these ideas in both dc and ac contexts, and discuss simple applications in voltage dividers and filters. This lab will require two days. Reading: HH Sections 1.16–1.24 (pgs. 28–44) 2.1 Voltage Divider The voltage divider, Fig. 2.1(a), is a simple but deceptively important circuit. It’s basic use is to reduce a voltage, according to Vout = R2 Vin . R1 + R2 Construct a voltage divider with the values shown. Measure Vout and check that it agrees with the formula. Measure R1 , R2 and Vin so that you can make the comparison with some precision. When the input and output voltages of a circuit can be related in the form Vout = GVin , the proportionality constant G is known as the transfer function. The voltage divider introduces the important concepts of input and output impedance. To understand output impedance, consider the Thevenin equivalent circuit of Fig. 2.1(b). This shows that from the point of view of the output, the divider circuit can be considered as an ideal voltage source at Veff followed by an effective resistance Zout . When no current is flowing out of the circuit, there is no voltage drop across Zout , so Vout = Veff , which here must equal R2 Vin /(R1 + R2 ). So the measurement of the preceeding paragraph tells you Veff . In reference to Fig. 2.1(b), if the output terminal is attached to ground (a ‘short circuit’), a current Iout (short) = Veff /Zout will flow. Test this by shorting your circuit to ground through your current meter. Record the resulting output current, and use it to calculate the output impendance Zout = Veff /Iout (short). Vin = 15 V R1 = 10k Zout Vout Veff Vout R2 = 4.7k (b) (a) Figure 2.1: (a) Voltage divider circuit. (b) Thevenin equivalent circuit. 12 2.2 Cascading Circuits 2 IMPEDANCE AND TRANSFER FUNCTIONS Compare your measurement to the expected value for a voltage divider Zout = R1 k R2 . In general, if a current Iout is extracted from a circuit, the Thevenin model indicates that the output voltage will be Vout = Veff − IZout . Test this by hooking a 6.8 kΩ resistor from the output to ground, and measure the resulting output current and voltage voltage. Compare to what the Thevenin model prediction. Considering instead the input to the circuit, the input impedance Zin is just the net resistance seen from the input of the circuit (Vin ) to ground. It can typically be measured directly using an ohmmeter. For a voltage divider with no load, Zin is evidently R1 + R2 . What is the Zin for your divider circuit with the 6.8 kΩ load resistor? Compare a measurement and calculation. 2.2 Cascading Circuits Suppose we want to divide a signal by 3, and then by 3 again. Design and assemble a pair of voltage dividers to do this to an accuracy of at least 10% at each stage. To avoid drawing too much current, don’t use resistors with R < 100 Ω. If you have trouble, recall that cascading circuits is simple if you ensure that the input impedance of the second circuit is high compared to the output impedance of the first circuit, because then the transfer functions of the two circuits simply multiply. Make sure you understand this point. Describe your circuit and its performance in your report, noting both the intermediate (÷3) and the final (÷9) output voltages. 2.3 DMM Impedance Construct Fig. 2.2 using a Fluke DMM on the voltmeter setting. Because the input impedance of the DMM is finite, some current will flow through the 10 MΩ resistor, and the meter will not read 10 V. Equivalently, the resistor forms a voltage divider with Zin for the DMM, and the voltmeter reads the divided voltage. Use this measurement to determine Zin for the meter. Compare to what you get for the ELVIS DMM. Could you alternatively measure Zin for one DMM using the ohmmeter of the other? What happens if you try? If you made a voltage divider circuit with R1 = 1 MΩ, R2 = 2 MΩ, and Vin = 10 V, what reading would you expect to see if you measured the output with a Fluke DMM? Figure 2.2: Measuring the DMM impedance. The DMM should be on the voltmeter setting. 13 2.4 RC Filter 2 IMPEDANCE AND TRANSFER FUNCTIONS Figure 2.3: RC filter circuit. Devise a method to measure the input impedance of a current meter, and determine its value for both the Fluke and ELVIS meters. In what situation could the finite impedance of the current meter cause a measurement error? 2.4 RC Filter The RC circuit of Fig. 2.3 can also be considered as a voltage divider, with the resistance R2 replaced by the frequency-dependent impedance Z2 = 1/iωC. The output voltage can then be immediately expressed as Vout = Z2 1 Vin = Vin . R 1 + Z2 1 + iωRC Again this defines a transfer function G(ω) via Vout = G(ω)Vin , but here and in general, G is a function of frequency. This means that it is only directly useful for sinusoidal signals, where ω is well-defined. Here the magnitude 1 |G| = √ 1 + ω 2 R2 C 2 is nearly 1 for small ω, but decreases like ω −1 for large ω. This circuit can therefore be used as a low pass filter. The cutoff frequency at which the filtering action begins is fc = (2πRC)−1 . The attenuation |G| can be measured with an oscillocope, since |G| = |Vout |/|Vin | where |Vn | represents the amplitude of signal n. If G is expressed as |G|eiφ , the phase φ represents a phase shift between the input and output. For the RC circuit, φ = − tan−1 (ωRC). The phase shift can be measured by comparing the time delay ∆t between zero crossings of the input and output wave forms: If the input signal varies as cos(ωt) and the output as cos(ωt + φ), then the input will cross zero at ωt1 = π/2 while the output crosses zero at ωt2 + φ = π/2. Solving for φ yields φ = −ω∆t for ∆t = t2 − t1 . (Note that φ is negative when the output lags the input.) This formula gives a value in radians; in degrees, use φ = −360f ∆t for frequency f in Hz. 14 2.5 Bode Analyzer 2 IMPEDANCE AND TRANSFER FUNCTIONS Set up a low pass filter using R = 10k and C = 10 nF. Use the oscilloscope to measure the attenuation and phase shift of a sine wave at frequencies of 10, 100, 300, 1000, 3000, 10k, and 100k Hz. Plot the attenuation and phase vs. frequency. Because of the large range in frequency and amplitude, it is generally more convenient to make plots on a log scale. Conventionally, the amplitude of the transfer function |G| is measured in decibels (dB), given by g = 20 log10 (|Vout /Vin |). Make another pair of plots for your data with the gain in dB and phase shift in degrees vs. log(f ). This representation of a transfer function is termed a Bode plot. For comparison, use Excel to calculate the theoretical values for g and φ, and add them to your Bode plot. 2.5 Bode Analyzer Bode plots are a powerful tool for analyzing circuit performance, but they can be tedious to measure. The ELVIS Bode Analyzer instrument can simplify this process. Find the analyzer instrument on the computer and open it. Set the Stimulus Channel to Scope Ch 0, and the Response Channel to Scope Ch 1. Leave the function generator hooked up to your circuit, but close (or at least turn off) the FGEN tool. Make the following connections to use the analyzer tool: 1. Use a cable to connect the function generator output to the Scope 0 connector on the side of the breadboard. This is how the instrument measures Vin . 2. Hook Vout from the circuit to the Scope 1 connector. This provides a measurement of Vout . Use the Bode tool to take a measurement from 10 Hz to 100 kHz. It should generate a plot similar to the data you took by hand. Save the log file and import it into Excel, and add the data to your previous graph. The graph will be clearest if you use lines for the ELVIS data and points for the data you took by hand. Note any disagreements you observe. Swap the resistor and capacitor, and use the analyzer to observe how the Bode plot changes. What kind of filter is the circuit now? Plot this data in your report, and work out a theoretical calculation for comparison. 2.6 Filtering Signals Filters are mostly used for eliminating noise, so to see them in action we need to create a noisy signal. This can be achieved by adding a high frequency signal from the function generator to the 60 Hz signal from the transformer, using the circuit of Fig. 2.4. (Recall the similar circuit you studied in the first lab.) The 1k resistor sets the output impedance high enough to limit the current flow to a few mA. Assemble the circuit and observe the output on the scope. Depending on the time scale setting, you should see either a 60 Hz signal with high-frequency “noise” or a 20 kHz signal with a fluctuating offset. Suppose first that the low frequency signal is of interest. Pass the composite signal through a low-pass filter with C = 10 nF and R = 10 kΩ and describe the output. Does the filter successfully isolate the low-frequency component? What is the amplitude of the residual high frequency component, and does that amplitude agree with expectations? Repeat these measurements with a high-pass filter using the same R and C. 15 2.7 Cascaded Filter 2.7 2 IMPEDANCE AND TRANSFER FUNCTIONS Cascaded Filter If you want to attenuate high frequency signals more effectively than the circuit of Fig. 2.3 achieves, you can cascade two filters, as in Fig. 2.5. Design such a filter with a cut-off frequency of about 1.5 kHz. There are many ways to achieve this, but the design will be simple if you ensure that the input impedance of the second filter is much larger than the output impedance of the first filter. In that case, the attenuations of the two filters will simply multiply. (Compare to the experiment with cascaded dividers from Section 2.2.) Put your circuit together and measure its Bode plot with the analyzer. Include the data in your report. Compare to what you saw for the filter of Fig. 2.3. Note that when the phase φ drops below -180◦ , the Bode analyzer wraps the phase around to +180◦ . This makes the plot hard to read, but you can fix it by manually subtracting 360◦ from the appropriate points in Excel. Run the composite signal of Fig. 2.4 through the double filter. Does it perform better than the single filter did? 2.8 Scope Impedance We noted earlier that a DMM has a finite input impedance that can affect measurement accuracy. The same is true for oscilloscopes, and the impact is often more significant. The situation here is more complicated because ac signals are involved, so the scope input impedance is complex and frequency dependent. You can measure Zin for the oscilloscope using the circuit of Fig. 2.6(a). Channel 1 monitors the input voltage, while the difference between Ch 1 and Ch 2 reveals the amount of current flowing through the resistor, and thus into the scope. The scope input is typically modeled as a resistor in parallel with a capacitor, as in Fig. 2.6(b). At low drive frequencies, the resistor will dominate the impedance, allowing R to be measured. At high frequencies, the capacitor will dominate and form a low-pass filter with the 1 MΩ resistor. Use this approach at frequencies of 100 Hz and 100 kHz. From the measured amplitudes, calculate values for R and C and note them in your report. For even moderately high impedance sources, the scope impedance can be a significant load on the circuit at high frequencies. This effect can be reduced by using a 10× scope out Figure 2.4: Composite signal generator. 16 2.8 Scope Impedance 2 IMPEDANCE AND TRANSFER FUNCTIONS in out Figure 2.5: Cascaded filters. Input 1M Scope, Ch 2 Scope, Ch 1 (b) (a) Figure 2.6: (a) Circuit for measuring oscilloscope impedance. (b) Model for oscilloscope impedance. probe, described in Appendix A of the text. The probe contains a voltage divider that reduces the signal level by a precise factor of 10. This in itself can be useful when observing signal levels too high for the scope to otherwise display. The main advantage, however, is that the divider also increases the input impedance by about the same factor. Replace the scope cable with a 10× probe and measure the impedance again. Make sure that the probe is on the 10× setting. To get the best performance with a probe, it needs to be properly compensated. (Again, see Appendix A.) Hook your probe up to the Probe Adj terminal on the scope and observe the square wave it produces. Find the calibration adjustment screw on the probe, and adjust it to produce an accurate square wave form. This sets both the capacitive and resistive parts of the voltage divider to 10×, so you get uniform attenuation at all frequencies. Describe what you observe if the adjustment is incorrect. In general, it is a good idea to use a properly compensated probe except when you are looking at small signals for which the 10× attenuation is unacceptable. When using a probe, set the oscilloscope input calibration appropriately so that the scale readings compensate for the probe attenuation. Recall that this is done by holding down the Selector switch and rotating the Variables knob. 17 3 DIODES 3 Diodes A diode is perhaps the simplest non-linear circuit element. To first order, it acts as a one-way valve. It is important, however, for a wide variety of applications, and will also form the starting point for understanding transistors. This lab will require one day. Reading: HH Sections 1.25–1.31 (pgs. 44-53) 3.1 Current vs. Voltage Semiconductor theory predicts that the current through a diode is given by I = Is [exp(V /V0 ) − 1] , where V is the voltage across the diode, Is is a current scale, and V0 is a voltage scale on the order of kT /e for absolute temperature T , Boltzmann constant k and electron charge e. We can verify this prediction using the ELVIS 2-wire analyzer. Obtain a 1N914 diode from the supply cabinet. Note that one end of the diode is marked with a bar; this end is the cathode (see Fig. 3.1). Place the diode into the DUT contacts, with the cathode end in the negative terminal. Run the analyzer from -10 V to 10 V with a 0.5 V step and low gain. The analyzer will quit at some point when the current becomes too high; that is fine. Describe the response you do see in your report. Getting a more detailed plot takes some extra work, because of the large range of currents involved. In particular, the low gain setting on the analyzer doesn’t give an accurate value for small currents, but the high gain setting doesn’t let the current grow large enough to see everything we want. So to get a clear picture, break the plot into three sections: First, run the analyzer from -10 V to 0 V with 1 V steps and high gain. Export this data and paste into your report. Second, run the analyzer from 0 V to 0.5 V with a 0.1 V increment and high gain. Paste this data into your report as well. Finally, run the analyzer from 0.5 V to 1.0 V with a 0.05 V increment and low gain. Paste this data along with the others in your report, and plot all three together on one graph. To compare to the theory prediction, we need to know Is and V0 . To get these, make another plot with just the third section of data, where V > 0.5 V. In this range, the current should scale as I = Is exp(V /V0 ) since the exponential will be much larger than one. So if Figure 3.1: The diode circuit element. 18 3.2 Diode Drop 3 DIODES you plot this on a semilog scale, it should appear as a straight line. Excel can fit this for you: with this chart selected, go to the Chart menu and select Add Trendline. Chose an exponential function, and then go to the Options tab and select “Display equation on chart.” Click OK, and Excel should produce a line through the data. From the parameters in the equation, you can read out Is and V0 . Record these in your report. Is V0 on the order of kT /e as expected? Now that you have Is and V0 , construct a theoretical prediction for I(V ) and plot it along with the full range of your data. How well does the prediction agree? 3.2 Diode Drop Most often, it is not necessary to use the full theoretical model for the diode. Instead, we can approximate the IV relation as ( 0 if V < VD I= ∞ if V > VD for a value VD known as the diode drop. In practice this means that if you try to apply a voltage larger than VD enough current will flow that the applied voltage will be reduced to VD (or until the diode breaks, if the applied source can output a large enough current.) Clearly this is an imprecise model, since the IV curve you measured above is not actually a step function. However, the curve is quite steep and the diode drop model is often adequate. Estimate the diode drop here by determining the voltage drop at which I = 1 mA. (You can do this by reading it off your plot, rather than by measuring it directly.) How much would this change if a current of 2 mA or 5 mA were used instead? This uncertainty indicates the level of accuracy of the diode drop model, typically a few tenths of a volt. If more precision is required, the better model should be used. The diode drop can also be measured using the diode setting on your DMM. What value does it give for the 1N914 diode, and what current does this correspond to? 3.3 Power Diodes According to its datasheet, the 1N914 diode can conduct a forward current of about 75 mA before it overheats and breaks. Larger diodes can carry much larger currents. For instance, the 1N4001 diode is rated for 1 A. There is a tradeoff to using higher power diodes, however, because they generally have a slower response. The limit to a diode’s response speed is primarily due to the effective capacitance of the diode junction, and higher power diodes have a larger capacitance. This causes high-frequency signal components to ‘leak’ through the junction as if it weren’t there. This capacitance can’t be measured directly because of the forward conduction. The circuit of Fig. 3.2 solves this problem by measuring a pair of diodes in series. Wire up this circuit using 1N914 diodes. Given your measurement, what is the capacitance of a single diode? Now set up the circuit using 1N4001 diodes instead, and again determine the single-diode capacitance. How do the two diodes compare? 19 3.4 Rectifiers 3.4 3 DIODES Rectifiers A common use for diodes is rectification, in which an ac signal is converted to dc. For instance, rectification is needed to convert an ac power line to a dc power supply. Fig. 3.3 shows the simplest type of rectifier, often referred to as a half-wave bridge. Assemble this circuit using Rload = 2.2 kΩ. Observe the output. Are the amplitude and polarity of the peaks what you expect? Can you see the effect of the diode drop? The full-wave bridge of Fig. 3.4 is more efficient (and thus more common) than the half-wave bridge. Before building anything, think through the circuit and describe in your report what you expect the output signal to look like. Then wire up the circuit (again with Rload = 2.2 kΩ) and see if you got it right. 3.5 Filtering and Ripple We can reduce the remaining ac component in the output of a rectifier using a capacitor as a filter. Place a 15 µF capacitor in parallel with the load resistor in Fig. 3.4. Notice that this type of capacitor is polar, meaning that the terminal marked with a negative sign should be held at a more negative voltage than the positive terminal. Be sure to orient the capacitor in your circuit correctly. What is the resulting dc output voltage? The output should also have a small ac ‘ripple;’ what is the peak-to-peak amplitude of this ripple? What changes if you change the 2.2 kΩ load resistor to 1 kΩ? The ripple in the output should have a characteristic ‘sawtooth’ shape. We can understand where it comes from with a simple model: During each ac cycle, the capacitor is alternately charged by the supply and then discharged through the load. In the limit of small ripple amplitude, the voltage is nearly constant during the discharge, so the discharge current is nearly constant as well and is simply given by Idischarge = V /Rload for dc output voltage V . The ripple amplitude can then be estimated using dV ∆V ≈C Idischarge = C dt ∆t where ∆V is the variation in V (the ripple amplitude) and ∆t is the discharge time. The charging time of the capacitor is typically short, since the diodes and transformer have a low output impedance. The discharge time is therefore approximately equal to the signal period. Using your circuit’s values for R, C, V and ∆t, what ripple amplitude ∆V is predicted, and how does it compare to your observations? You can use either the 1 kΩ or 2.2 kΩ load resistors, as you prefer, but note your choice. DUT+ DUT- Figure 3.2: Circuit for measurement of diode capacitance. 20 3.6 Zener Diodes 3 DIODES Replace the 15 µF capacitor with a 470 µF capacitor, and again compare the ripple to the prediction. This circuit should now be a respectable dc power supply. However, a real power supply would include a voltage regulator to improve its stability in response to changing loads. Diodes can be used for this purpose as well, as explained below. 3.6 Zener Diodes Obtain a 1N746A (or an equivalent 3.3 V) zener diode from the cabinet, and install it in the IV analyzer with the cathode on the DUT- terminal. If you try to run the analyzer from -10 V to 10 V, you will immediately get an error. Run it instead from 0 V to 1 V. Are there any obvious differences from the 1N914 diode? Now reverse the diode so that the cathode is in the DUT+ terminal, and run the analyzer from 0 V to 10 V on the low gain setting. How is the result different from what you would expect with the 1N914 diode with the leads similarly reversed? The conduction observed at around 3 V is termed reverse breakdown. All diodes will exhibit reverse breakdown if a large enough reverse voltage is applied. For regular diodes, this voltage is normally 50 V or more, but in a zener diode, it is designed to be a specified low value. An important use for a Zener diode is as a voltage reference. For example, wire up the circuit of Fig. 3.5 and measure the output voltage with a VPS setting of 10 V. Due to the nonlinearity of the diode, the output is relatively insensitive to the input voltage and the output current. To demonstrate this, change the input supply voltage to 8 V and note the output change. Also, attach a 1 kΩ resistor from the output to ground as a load. Based on the observed voltage drop, what is the output impedance of the regulator circuit? This type of circuit is useful any time you need a fixed reference voltage. A fancier version with a temperature stabilized zener diode is available as the LM399 integrated circuit. 3.7 Diode Clamps Another use of diodes is for circuit protection. Various configurations of diodes can limit a signal to a specified range, and thus prevent accidental damage to more sensitive and expensive components. For instance, the the circuit of Fig. 3.6 prevents the output signal from exceeding 5 V. Construct the circuit and drive it with a 10 Vpp sine wave from the function generator. Vary the DC offset from -5 to +5 V and verify that the clamp performs as claimed. 6.3 Vac 120 Vac 1N4001's out load Figure 3.3: Half-wave bridge. Figure 3.4: Full-wave bridge. 21 3.7 Diode Clamps 3 DIODES Two other types of voltage clamp are shown in Figs. 3.7, and 3.8. You don’t need to build these circuits, but think about them and explain what they do in your report. Figure 3.5: Voltage reference using zener diode. 22 3.7 Diode Clamps Figure 3.6: 5 V clamp. 3 DIODES Figure 3.7: Zener clamp. 23 Figure 3.8: Limiter. 4 TRANSISTORS 4 Transistors Transistors are the basic building blocks of active electronics. Unlike passive elements, transistor circuits can provide positive gain. This gain can be in the voltage, the current, or the power of a signal. This lab will require two days. Reading (Bipolar transistors): HH sections 2.01-2.07, (pgs. 62–77) Reading (Field effect transistors) : HH sections 3.01-3.03, 3.11-3.12 (pgs. 113–121, 140–151) 4.1 IV Relations This exercise will focus on the 2N3904 npn transistor, shown in Fig. 4.1. Locate and obtain one from the supply cabinet. Before anything else, check that it is functioning correctly using the diode-test setting on your DMM. The transistor should look like a pair of diodes as shown, with a diode drop of about 0.6 V. If it does not, discard it and try another. The transistor is a 3-terminal device, and is therefore more complicated to characterize than a 2-terminal device like a diode. The important aspects, however, can be observed using the circuit of Fig. 4.2. The idea is to measure Vb and Vc as functions of Vin . Ohm’s law and the resistor values Rb and Rc can then be used to determine the base current Ib and collector current Ic . To facilitate this, accurately measure Rb , Rc , and the output voltage of the 5-V supply prior to constructing the circuit. Assemble the circuit using the ELVIS variable power supply as the input. Record Vb and Vc as Vin is varied between 0 and 12 V. Along with knowing Vin and the supply voltage, this lets you calculate the currents Ib and Ic via Ohm’s law. (Recall, however, that the VPS supply is inaccurate near V = 0. You’ll want to check Vin there with a meter.) Take enough data to get a fairly even spread of Ib values; this will probably require more points near Vin = 1 V than required near Vin = 0 V or 10 V. Use your data to prepare three plots: (a) 2N3904 E B C Package Diagram Testing Figure 4.1: Package and schematic of a 2N3904 npn transistor. 24 4.1 IV Relations 4 TRANSISTORS Rc = 100 Vc 5V Ic DMM Rb = 10 k Vin 2N3904 Ic Vb DMM Figure 4.2: Circuit for measuring IV characteristics of a transistor. Ib vs. Vb , (b) Ic vs. Ib , and (c) Vc vs. Ib . The first plot should show that the base-emitter junction behaves essentially like a forward-biased diode. This relation is used to determine the magnitude of the base current, and also implies that, in conduction, the emitter voltage is always about a diode drop lower than the base voltage. The second plot illustrates that the transistor provides current gain: you should see that for small Ib , the collector current satisfies Ic ≈ βIb . What value of β does your transistor exhibit? At larger Ib the curve should flatten out, which could be represented by β decreasing. This effect is termed saturation. The third plot also relates to the saturation effect. As the collector current increases, the collector voltage decreases due to the drop across Rc . This is the reason that the transistor gain saturates: at large base current, there is not enough voltage at the collector to maintain the Ic = βIb relation. When Vc is as small as it can get, we say that the transistor is completely saturated. The minimum voltage is then the saturation voltage Vces . What is this value for your transistor? This argument suggests that the saturation current would be larger if Rc were smaller or if the 5 V supply voltage were larger, since in either case Vc would be larger for a given Ic . This is correct. However, the 2N2904 can only handle currents of up to 200 mA before overheating and breaking. Transistor circuits should always include appropriate currentlimiting resistors to prevent damage. What is the smallest Rc usable here that would still limit Ic to a safe value? 25 4.2 Transistor Switch 4 TRANSISTORS 5V SYNC output of FGEN 0.5 Hz 2N3904 6.3 V/150 mA lamp (a) (b) Figure 4.3: (a) Attempting to turn a lamp on and off using a function generator. (b) Using a transistor as an electrically controlled switch. 4.2 Transistor Switch One simple transistor application is a switch. Here the linear amplification behavior is ignored, and the transistor is operated in only two modes: either with Ib = Ic = 0 (‘off’), or with Ib large enough to saturate to saturate the transistor (‘on’). This configuration allows a small base current to switch a large collector current on and off. To explore this, consider Fig. 4.3(a), which illustrates an attempt to turn a lamp on and off using the function generator SYNC output. Recall that the SYNC output consists of a square wave signal that switches between 0 V and 5 V. Start by verifying that 5 V is sufficient to illuminate the lamp, by installing the lamp between the 5 V power supply terminal and ground. Then construct the circuit of (a). You will find that the lamp remains dark. This is because the lamp requires a current of at least 75 mA to illuminate, significantly more than the SYNC output can provide. Figure 4.3(b) shows how this problem can be solved using a transistor. Only a small base current is required to control the transistor, while the 5 V supply provides plenty of current to run the lamp. Wire up this circuit and verify that it works. Measure the collector voltage using your oscilloscope. Does it drop to your measured Vces when the control signal is high? 4.3 Emitter Follower The switch circuit in the previous section can be considered as a current gain device, since it allows a small current from the function generator to control a large current through the lamp. A more explicit type of current amplifier is the emitter follower. A follower is, in general, a device that boosts that current a signal can provide without significantly changing the signal voltage. We say that the output ‘follows’ the input. Followers are also often called 26 4.3 Emitter Follower 4 TRANSISTORS +5 V 3.3k 3.3k Vout 1 Vpp 1 kHz 10k 1 Vpp 1 kHz 10k RL = 100 (a) (b) Figure 4.4: (a) A voltage divider used to attenuate a signal. (b) An emitter follower on the output of the divider, used to increase the current output capacity. buffers, though a buffer amplifier may provide voltage gain along with current amplification. To see how a follower could be useful, consider the circuit of Fig. 4.4(a), which shows a voltage divider functioning as a variable attenuator for the input signal. This might serve, for instance, as a volume knob for an audio source. Construct this circuit and verify that the potentiometer allows the output signal amplitude to be controlled. However, suppose now that the signal is required to drive a low impedance load (a speaker, for instance). To model this, attach a 100 Ω resistor from the output to ground, and again observe the output voltage. You will see that the high impedance divider is unable to supply enough current to drive the load, so the circuit does not function. Figure 4.4(b) shows how an emitter follower can solve this problem. To analyze the circuit, remember that the emitter of the transistor will always be one diode drop below the base. If the base voltage starts to rise, the base current will rise, causing the collector current to rise via Ic = βIb . Since β is large, a substantial collector current can flow, which eventually passes through the load resistor. This in turn causes the emitter voltage to rise, until it is again about a diode drop below the base. In practice, this just means that the emitter follows the base voltage (neglecting the diode drop), but can supply more current by a factor of roughly β. Equivalently, the output impedance of the attenuator circuit is reduced by β. Construct the circuit, with the 10 kΩ pot set to provide the maximum output level. What do you observe at the output? At first, you will likely see only a flat line at 0 V. This is understandable if you consider what happens when the base voltage is negative or close to zero. You can compensate for this by adjusting the dc offset on the function generator to make the input signal more positive. Do so and note your observations. What is the minimum offset value for which the function generator signal is properly applied to the load? Does this offset make sense, given your previous measurements? The need to keep the base voltage in a suitable range is a generic and sometimes challenging problem. We say that the transistor must be biased correctly. There are a variety of solutions, such as adding circuitry to provide a fixed dc offset, returning the load to a 27 4.4 Common-Emitter Amplifier 4 TRANSISTORS negative power supply, or adding a pnp transistor to the circuit, which can sink current to a negative supply. Further discussion can be found in the text. 4.4 Common-Emitter Amplifier We have considered a transistor as a current amplifier, but the amplifiers we are most familiar with are voltage amplifiers. The common-emitter amplifier of Fig. 4.5 shows one way a transistor can be used to provide voltage gain. To analyze this circuit, take the input voltage to be Vin . The emitter voltage will then be Vin − VD for diode drop VD . This implies an emitter current Ie = (Vin − VD )/Re and an approximately equal collector current Ic . If VS is the collector supply voltage (here 15 V), then the output voltage will be Vout = VS − Ic Rc ≈ VS − Rc (Vin − VD ). Re The dc level of the signal is changed, but the ac part is amplified by Rc /Re , which can be larger than one. Construct the circuit as shown, using Re = 1 kΩ and Rc = 10 kΩ. Drive the input with a 0.1 Vpp sine wave at 1 kHz. It will be necessary to adjust the input dc offset to properly bias the amplifier, similar to what was required for the follower circuit. What ac gain amplitude do you observe? Is there a phase shift between the input and output signals? What is the output impedance of your amplifier? You can check this by hooking up an appropriate resistor to ground as a load, and observing the reduction in the output amplitude. Recall that with a load resistor RL , the nominal output voltage Vout will be reduced to RL Vout . Zout + RL Does the value you obtain for the output impedance make sense? Once again, there are a variety of more general solutions to the biasing problem, as well as several other ways to improve the amplifier performance. Consult the text for further information. 4.5 Field Effect Transistors Field effect transistors (FETs) are are another type of transistor. In most respects, they are typically inferior to the bipolar junction transistors considered up to now. They offer one key advantage, however: they do not require any control current to operate. This leads to many useful applications. There are a several different flavors of FETs, which are discussed in the text. We will work with the 2N5459, an n-channel JFET. The pin configuration is shown in Fig. 4.6. The gate, drain, and source terminal correspond to the base, collector, and emitter terminals of a bipolar transistor. We will focus on the relationships between the gate voltage VGS , the gate current IG , and the drain current ID . The circuits used are shown in Fig. 4.7. Wire up circuit (a) first, and measure the gate current as a function of gate voltage, both positive and negative. Plot the data in your report. The response should look like a diode 28 4.5 Field Effect Transistors 4 TRANSISTORS out Figure 4.5: Common-emitter amplifier Figure 4.6: Pin identification and circuit diagram for the 2N5459 FET. 29 4.6 FET Switch 4 TRANSISTORS +15 V +15 V Current Current 10k 2N5459 VPS 10k 2N5459 VPS Voltage Voltage (a) (b) Figure 4.7: Circuit to measure the IV characteristics of an n-channel JFET. conduction curve; if it doesn’t, your FET may be damaged and you should try another one. Since a large gate current is undesirable, this type of FET should always be operated with negative voltage VGS between the gate and the source. Next wire up circuit (b) and measure the drain current as the gate voltage is varied over a range of negative values. Plot the data in your report. Observe that the gate voltage controls the drain current, but as seen in (a), the gate current itself is negligible here. It is often useful to consider a FET as a transconductance amplifier, where the “transconductance” gm is defined as dID /dVGS . What is the transconductance of your device when VGS = 0, and when VGS is in the middle of its usable range? It can also be useful to think of the FET as a variable resistor controlled by VGS . Given the drain voltage and measured drain currents, what range of source-drain resistances does your FET exhibit? 4.6 FET Switch A key application of FETs is as a voltage controlled switch. This works much the same as the bipolar circuit of Fig. 4.3, with the advantage that no input current is required. The disadvantage is that the switching current capacity is much lower: only about 10 mA for the 2N5459 compared to 200 mA for the 2N3904. Because of this, we will switch an oscillator signal rather than a lamp current. Construct the circuit of Fig. 4.8. Use your 6.3 V transformer as a signal source, with a 10 V dc offset to ensure proper biasing. The function generator serves as a control signal. Set the amplitude and offset of the function generator such that the the minimum value of the control signal is sufficient to reduce ID to zero, while the maximum value gives VGS = 0. (Don’t forget that VGS should never be larger than zero.) Describe what you observe at the output. Does anything change if you place a 1 MΩ resistor between the function generator and the gate? 30 4.7 FET Follower 4 TRANSISTORS out Figure 4.8: Use of a FET as a voltage-controlled switch. 4.7 FET Follower Another important FET circuit is the follower of Fig. 4.9. Compared to the emitter follower of Fig. 4.4, the FET version offers again much lower input current. A variant of this circuit is used in DMMs and oscilloscopes to provide the high impedance input those devices require. It is probably not immediately obvious how this circuit works. To analyze it, assume that some unknown current I is flowing through the lower FET, Q2 . Then Q2 ’s source will be at voltage VS2 = −15 + IR, and the gate-source voltage will be VGS2 = −IR. Since VGS determines I through the FET transconductance, the current I is implicitly determined by the equation VGS (I) = −IR. This could be solved graphically using the data you took in section 4.5, but don’t bother for now. Assuming no load on the output, the same current I flows through both transistors. If the FETs are identical, Q1 will have the same transconductance as Q2 , so for the same current, VGS will be the same as well. We must therefore have VS1 = VG1 + IR. Since Vout = VS1 − IR and VG1 = Vin , we obtain Vout = Vin as desired for a follower. In practice, Vin and Vout won’t match exactly because neither the two FETs nor the two resistors are perfectly identical. Construct the circuit and drive it with your function generator. How well does the output track the input? Over what input voltage range does the circuit work? Determine the FET current I by measuring the voltage drop across one of the resistors with your DMM. Is the relation VGS (I) = −IR satisfied, based on your previous data? What is the output impedance of the circuit? It can be measured the same way as the common-emitter amplifier of Fig. 4.5. Again, does the value you obtain make sense? 31 4.7 FET Follower 4 TRANSISTORS +15 V Q1 Vin R = 1k Vout Q2 R = 1k - 15 V Figure 4.9: FET follower circuit. Both transistors are 2N5459 JFETs 32 5 OP AMPS I 5 Op Amps I The operational amplifier (op amp) is the single most important active circuit component for analog electronics work. It can perform a wide variety of useful functions which we will begin to explore. This lab will require two days. Reading: HH Sections 4.01–4.10 (pgs. 175-188) 5.1 Installation The pin-out designations for a standard 8-pin dual-inline package (DIP) op amp are shown in Fig. 5.1. When counting pins on a DIP device, always start by locating the “top” of the package. This can be identified by a semi-circular indentation, a small circle, or both, as illustrated in Fig. 5.2. The pins are labled starting in the top left corner and proceeding counter-clockwise, as shown. Place an LF411 op amp on your breadboard, top up, straddling one of the central columns. With the board power off, wire the vertical ‘+’ and ‘-’ columns with ±15 V respectively, and then connnect these power buses to the +VS and −VS pins of the package. This is sufficient, but it is always good practice to filter the power supplies connections using a capacitor to ground, as in Fig. 5.3. This helps maintain a steady voltage if the input current changes quickly; without it, the inductance of the line from the power supply can lead to instability. Here, use a 1 µF capacitor, one from the +VS pin to ground and another from the −VS to ground. These capacitors have a polarity, with the lead that must be positive marked with a +. Be careful to install them correctly. Once the chip is installed, use your DMM to measure the supply voltages at each pin, and record them in your report. We will not be using the “offset null” pins today, so you can leave them unattached. 1 offset null inverting non-inverting 8 1 8 no connection 2 7 2 6 3 6 4 5 + 3 7 4 out 5 offset null Figure 5.1: Pin-out diagram for a standard 8-pin op-amp package. + Figure 5.2: How to count pins on an integrated circuit chip. 33 Figure 5.3: Connecting power supplies to an op amp. 5.2 Open-Loop Test 5 OP AMPS I in out Figure 5.4: Op amp as an open loop amplifier. The input circuit is a 10 kΩ potentiometer, which allows fine adjustement of the voltage at the op amp input. 5.2 Open-Loop Test An op-amp is a high gain amplifier with high input impedance. Try to measure this amplification with the circuit of Fig. 5.4: set the input voltage to some small value and measure the resulting output. In principle, this should generate an output voltage of GVin , with G on the order of 105 . What do you actually observe? If you change the input voltage, does the output change? Can you see why an op-amp is essentially never used in this “open loop” configuration? To understand these measurements, it is important to distinguish between the gain and the output range of an amplifier. A functioning amplifier might, for instance, have a gain of 10, but an output range of only ±1 V. This would make it a useful amplifier for input signals with amplitudes below 0.1 V, but a larger input signal would cause the output to saturate, leaving it clamped at one end of its range. Op amps typically have an output range that is within a volt or so of the power supply levels. What output range do you measure for the LF411, and how does it compare to the supply voltages? How small would the input need to be for the output voltage to fall in the usable range, if the gain really is 105 ? 5.3 Inverting Amplifier Assemble the inverting amplifier circuit of Fig. 5.5. Drive it with a 1 kHz sine wave. What is the gain (in dB), and how does it compare to the expected value? Does the gain depend on the signal frequency? Drive the amplifier with a triangle wave and describe the output. Drive it with a square wave and note how it responds to a sharp step. Replace the 10k feedback resistor with a 100k pot, and vary the gain. Can you take the gain all the way to zero (-∞ dB)? Does the highest gain agree with what you expect? If you used a bigger pot to keep increasing the feedback resistance even further, what do you think is the maximum gain you could achieve? Replace the pot with the 10 kΩ resistor again when you are finished. You can measure the input impedance of the amplifier circuit by adding another 1 kΩ resistor in series with the input. The resulting decrease in the output amplitude can be interpreted as coming from a voltage divider at the input formed by the new resistor and the original circuit’s input impedance. What input impedance do you obtain, and does the 34 5.4 Non-inverting Amplifier 5 OP AMPS I in out in out Figure 5.5: Inverting amplifier Figure 5.6: Non-inverting amplifier Vin Vin 10k 10k Vin LF411 Vout 10k 1k 10k LF411 1k Vout Vout 1k 1k (a) (b) (c) Figure 5.7: The follower (a), a pair of voltage dividers (b), and a follower application (c). result make sense? Verify that the output impedance of the circuit is very low by driving a 10 Ω load resistor with a 0.1 Vpp input signal. If the load causes an observable drop in the signal amplitude, you can again use use voltage divider relation to calculate the output impedance. If there is no observable drop, all you can say is that the output impedance is small compared to 10 Ω. 5.4 Non-inverting Amplifier Assemble the non-inverting amplifier shown in Fig. 5.6. What is the voltage gain? Replace the 10k resistor with a 10k pot, and observe the range of gains achievable. Try to measure the circuit’s input impedance by putting a 1 MΩ resistor in series with the input and looking for a voltage drop in the output. You should expect a large value for the impedance. Don’t work too hard at getting an accurate measurement, because eventually it’s not clear whether the input impedance will be limited by the op amp or the breadboard. 5.5 Follower Interestingly, one of the most common op-amp circuits is the follower of Fig. 5.7(a). By applying the op-amp rules, you can readily see that the output of the circuit is equal to the 35 5.6 Summing Amplifier 5 OP AMPS I 1 out 2 Figure 5.8: Summing amplifier. input: Vout = Vin . It thus functions as a follower, like the transistor followers you made in the previous lab. Like any follower, the point of this circuit is to lower the output impedance of a signal, or equivalently to boost the signal’s current. This is useful if you need to hook a low impedance load up to a high impedance source. The op amp follower works better than the transistor followers in most respects. In contrast to the emitter follower, the input level can be both positive and negative without encountering problems with biasing, the input impedance is higher, and there is no baseemitter diode drop between the input and output. Compared to the FET follower, there is no significant offset due to mismatched components and the output current capacity is much higher. For a simple example of using a follower, construct the circuit of Fig. 4.4(b), where two divide-by-two circuits are naively cascaded, expecting a net output of Vin /4. Why is the naive calculation incorrect, and what attenuation factor do you actually measure? In lab 2, you fixed this problem by ensuring that the second divider used much larger resistors than the first, but a follower can be used if that solution is impractical. Construct circuit Fig. 4.4(c) and verify that now the net attenuation is indeed the product of the individual divider attenuations. 5.6 Summing Amplifier Another useful trick is shown in Fig. 5.8. This circuit takes two inputs V1 and V2 and produces the (inverted) sum −(V1 + V2 ). You will analyze this circuit in your homework. To get some practice with the idea, build a circuit to add the voltage from your VPS supply to the +5 V fixed supply. How accurately is the output equal to the negative sum of the inputs? 5.7 Current Sources We usually think of power supplies as voltage sources: a ‘good’ source is one with a low output impedance, so that it can maintain its voltage regardless of what load you apply. However, current sources can also be useful. This describes a supply that produces a constant current, no matter what load you apply. 36 5.8 Current to Voltage Converter 5 OP AMPS I in Figure 5.9: An op-amp current source. The obvious use is in applications that depend specifically on current. For instance, you might want a good current source to produce a stable magnetic field from an electromagnet coil. As the coil heats up, its resistance will change, so a voltage source would not be as desireable. Another common application is to generate a linear voltage ramp by applying a current source to a capacitor. Of course, a real voltage source can’t produce unlimited current when you apply it to a short circuit (= zero resistance) load. Similarly, no real current source can generate infinite voltage in response to an open circuit (= infinite resistance) load. So if you turn on a current source with no load attached, it will simply ramp up to it’s maximum possible voltage and sit there. But if you turn it on with a short circuit load, the current source will drive exactly the current specified, for as long as you like. An op amp can be used to make a simple current source using the circuit of Fig. 5.9. Wire this up with R = 1 kΩ, using a 10 kΩ pot as a load and with your DMM ammeter in series with the pot. You can use the varible power supply to set Vin ; start at Vin = 1 V. Does the circuit accurately maintain Iload = Vin /R as you change the pot? What happens if you set Vin = 5 V? In Fig. 5.9, the load is floating with respect to ground. Unfortunately, loads that must be referenced to ground are fairly common. (An oscilloscope is one example.) You will get to analyze a current source for a load returned to ground in your homework assignment. 5.8 Current to Voltage Converter Another function at which op amps excel is converting a current to a voltage. At first glance, this seems trivial, since that is just the job of a resistor: if you apply a current I, you get a voltage V = IR. However, if you want a large ‘gain’ (ie, a large voltage for a given current), then you need a large resistor. This would, of course, have a large input impedance and for a current source, large load impedances are difficult to handle. An example where this comes up is the detection of light with a photodiode. Photodiodes have the property that, under illumination, they produce a current propotional to the light intensity. The output voltage, however, cannot exceed more than a few tenths of a volt. So if you try to hook a photodiode up to a large resistor, the voltage will saturate and the current will be lower than expected. Figure 5.10 shows how an op amp can boost the voltage produced without presenting a large impedance to the photodiode. In fact, since the inverting input of the op amp is 37 5.9 Logarithmic Amplifier 5 OP AMPS I in out out Figure 5.10: A photodiode amplifier. Figure 5.11: Logarithmic amplifier at ground, the photodiode ‘sees’ a short circuit, the perfect load for a current source. The feedback resistor can be made very large to produce a large signal. Wire up the circuit using a PNZ335 photodiode, and use it to observe the room lights. Describe the signal you observe, including the dc level and the amplitudes and frequencies of any ac components. Given a photocurrent calibration of about 0.5 A/W, how much light power is your circuit detecting? For reference, the formal name of a current to voltage converter is a transimpedance amplifier. The gain of a transimpedance amplifier is specified in ohms. 5.9 Logarithmic Amplifier Recall that the IV curve of a diode has an exponential form. We can use that to make a logarithmic amplifier, where the output voltage is proportional to the log of the input voltage. Analyze the circuit of Fig. 5.11 and verify this. Build the circuit using a 1N914 diode and see how it works, driving it with the variable dc supply. Note that there are an unknown muliplicative constant and offset on the output, so you won’t simply observe Vout = log(Vin ). Instead, measure Vout for a range of Vin and see if you observe a linear relationship on a semi-log graph. In practice, this circuit doesn’t actually perform very well, because the diode curve becomes non-exponential at large voltages, and also because the output voltage drifts with temperature. (Try observing this effect by holding your finger on the diode.) These problems can be fixed using, for example, circuit 4.35 on page 212 of the text. More conveniently, you could simply buy a log amp integrated circuit, like the LOG104 from Texas Instruments. How might you make an exponential amplifier, to take the ‘anti-log’ of a signal? (Again, this is something you’d be better off buying, in practice.) 38 6 OP AMPS II 6 Op Amps II In the previous lab, you explored several applications of op amps. In this exercise, you will look at some of their limitations. You will also examine the op amp integrator and differentiator circuits. This lab will require two days. Reading: HH Sections 4.11–4.13, 4.19–4.20 (pgs. 189-212, 222–224) 6.1 Output Capacity The most significant practical limits to what you can do with an op amp derive from the fact that the output voltage and current are limited. You saw in the previous exercise that the output voltage is constrained by the supply voltages driving the op amp, and that the output cannot generally swing all the way from one supply voltage to the other. In addition, the current that the op amp can supply is limited. These effects can be observed with the circuit of Fig. 6.1. For any practical Vin , the output voltage will be clamped at one of its limits. The voltmeter thus measures how large an output voltage is achievable. As the potentiometer resistance is lowered, the op amp must supply more current to maintain its output. Eventually, this causes the output voltage to decline, necessarily reaching zero when the load resistance is zero. To test this, construct the circuit and measure the output voltage and output current as the potentiometer is varied across its full range. Repeat the measurements for both signs of the input voltage. Plot the voltage vs. current values in your report, and comment on what you observe. Measure and record the power supply voltages, for comparison. Note that the LF411 is designed to withstand being shorted to ground indefinitely, so you shouldn’t damage anything with this test. Not all amplifiers have that property, however, so in general you should check before doing an experiment like this. You should see that at low current, the output should swing to within a volt or so of the supplies (or ‘rails’). Some op amps are designed to minimize this offset, and are called ‘rail-to-rail’ designs. One important application is to ‘single-sided’ operation, where all the signals of interest are positive and VS- is set to ground. If you tried to do that with an LF411, the op amp would be unable to produce 0 V out. in Figure 6.1: Measuring limits on output voltage and current 39 6.2 Offset Voltage 6 OP AMPS II in out Figure 6.2: 60 dB amplifier. Figure 6.3: Offset trimming circuit. If you need more voltage or current than an LF411 can handle, higher power op amps are available or you can boost the output power using a discrete transistor amplifier. 6.2 Offset Voltage Ideally, if you present the same voltage to both inputs of an op amp, the output voltage will be zero. However, a real op amp gives zero output for some small but nonzero input voltage difference, VOS . To observe this, construct the 1000× amplifier of Fig. 6.2. If you ground the input, you should observe a non-zero output, equal to VOS times the amplifier gain. Compare your measured value to the specification VOS < 2 mV. As seen here, the offset voltage is large enough to be significant in a high-gain circuit. When this is a problem, it can be handled using the offset adjustment inputs, pins 1 and 5. Fig. 6.3 shows the standard offset trimming network. Wire this into your circuit and adjust the pot until the output voltage is zero. As handy as this is, VOS unfortunately varies over time and with temperature. You should be able to observe this by warming the chip up with your finger for a few seconds. Record your observations. 6.3 Bias Current An ideal op amp allows no current to enter its inputs. For ac signals, this is subverted by capacitive coupling between the inputs. However, even at dc, a small bias current is present. The size of the current depends very much on the op amp construction; for the LF411 it is specified to be below 100 pA. It can can be observed with the same circuit of Fig. 6.2. First, convince yourself that with the input grounded, any bias current (on the V+ input) makes a neglible contribution to the output signal. That’s why we didn’t need to worry about the bias current while we were measuring VOS . With the offset voltage nulled as well as possible, attach Vin to ground through a 1 MΩ resistor. You should be able to see a shift in the output level when measured with your DMM. Use the measured voltage to determine the bias current. Is it consistent with the op amp specifications? 40 6.4 Johnson Noise 6.4 6 OP AMPS II Johnson Noise If you observe the output voltage from the previous circuit on the oscilloscope, rather than a DMM, you will notice that it appears quite noisy when the 1 MΩ resistor is in place. This isn’t a fault of the op amp, but it is a general problem that arises when you are trying to make a very precise circuit: resistors are noisy. The effect is known as Johnson noise, and comes from thermal excitation of the electromagnetic field in the resistor. Consulting a statistical mechanics text will give you the formula: p Vrms = 4kB T R∆f where kB = 1.38 × 10−23 J/K is Boltzmann’s constant, T is the temperature of the resistor, R is the resistance, and ∆f is the bandwidth of the noise detector (in Hz). (If it ever comes up, you should replace R with the real part of the impedance when you need to find the Johnson noise across a complex network.) Unfortunately, it is difficult to determine the root-mean square noise amplitude from the signal on your scope, and the bandwidth ∆f is not clear. However, by replacing the 1√MΩ input resistor by a 100 kΩ you should see the noise level decrease by about a factor of 10. Include a rough estimate of the noise level for each resistor in your report. We can make a better measurement using ELVIS. Open up the spectrum analyzer instrument, which is labelled DSA in the toolbar. Make sure the source channel is set to SCOPE CH 0, and hook your circuit output (with the 1 MΩ resistor on the input) into the CH 0 input on the side of the ELVIS board. Set the frequency span to 20 kHz, and the voltage range to ±500 mV. Then run the analyzer. It will display the noise spectrum, defined as the amount of noise present at each sampled frequency. The signal is the rms noise, which is what we need to compare to the Johnson noise formula. Here the bandwidth ∆f is the frequency range corresponding to each point displayed. You can determine it by dividing the frequency span by the number of points, here somewhat unfortunately called the “Resolution (lines).” Compare the measured values to the calculation, using the noise level observed around 1 kHz range. (At lower frequencies, you can be fooled by dc offsets, and at higher frequencies, the gain of the amplifier is reduced.) Note that the noise level in dBVrms is defined as 20 log(Vrms /1 V). Here the 1 V appears as a sort of normalization constant specifying what 0 dBVrms means. 6.5 Slew Rate Another important limitation of real op amps is that they can only respond at a finite speed. One reflection of this is the op amp’s slew rate, which measures the rate at which the output voltage can change, typically in V/µs. Measure the slew rate with a simple follower, Fig. 6.4. Observe the output on the scope, at drive amplitudes of both 2 Vpp and 10 Vpp. The datasheet gives a minimum specification of 8 V/µs and typical value of 15 V/µs. Are your observations consistent with this? 6.6 Frequency Response The slew rate is one limit on an op amp’s frequency response, but it is mostly important for large-amplitude output signals. Even for small signals, the op amp can only respond at finite 41 6.6 Frequency Response 6 OP AMPS II Vin 1k LF411 100 Vout out 10k 1k Figure 6.4: Follower for measuring slew rate Figure 6.5: Divider and non-inverting amplifier. speed, which leads to phase delays and reduced gain at high frequencies. This behavior can be quantified using the Bode plots we introduced in Lab 2. Unfortunately, the ELVIS Bode instrument is too slow for what we want to see, so you will need to take the data by hand. Set up the non-inverting amplifier shown in Fig. 6.5. Note the divider on the input, which makes it easier to get a sufficiently small drive signal. Set the function generator amplitude to 1 Vpp, and monitor Vin and Vout on your scope. Measure the gain and phase shift from 50 Hz to 5 MHz. You can take steps of a factor of 10 in regions where the phase is approximately constant, but use factors of 2-3 where something interesting is occuring. Note that you can increase the input amplitude at the higher frequencies, but make sure to keep the output amplitude below 1 V or so. Also, you will need to be careful to keep the traces centered on the scope; the dc level may shift at high frequencies due to nonlinear effects. (Using the scope’s ac coupling feature might be useful here.) Plot your data (both gain in dB and phase in degrees vs. log f ) in your report. The unity gain point is defined as the frequency where the op amp gain drops to 0 dB. Find this point and compare to the op-amp specification of 4 MHz. The bandwidth of the amplifier circuit can be defined as the frequency where the gain drops by 3 dB below its dc value, G. What bandwidth do you observe here? How does it compare to the prediction that the bandwidth is equal to the unity gain point divided by G? Now replace the 10k feedback resistor by a 33k resistor, making it a nominal 34× amplifier. To compensate, turn the function generator amplitude down so that the output doesn’t clip. Measure the gain and phase over the same range as before. Add the data to the same Bode plots as the 11× circuit for comparison. What is the bandwidth now? How do the two circuits’ gains compare at high frequencies? 42 6.7 Integrator 6 OP AMPS II in out Figure 6.6: Integrator. 6.7 Integrator Construct the integrator circuit of Fig. 6.6. Ideally, it produces an output Z 1 Vin (t)dt. Vout = − RC Test it using a 500 Hz square wave from your function generator, but get everything set up before you turn the circuit power on. Make sure your scope is set to dc input coupling. Describe what happens when you do apply power. The level drifts because the circuit is a true integrator, so the output will ramp in response to a dc input. Perhaps the function generator outputs a small dc component, or perhaps it is just the offset voltage we encountered in section 6.2. In any case, the integrator is doing what it is supposed to, but the dc drift makes it hard to look at the waveform that we are interested in. Try to adjust the dc offset on the function generator to keep the output signal near zero. Is it possible? One way to think about this problem is that a true integrator has infinite gain at dc, so it will eventually rail in response to any finite dc input. Instead of trying to eliminate that input, a better fix is to reduce the dc gain. This can be achieved by putting a large resistor in parallel with the capacitor. Try a 1 MΩ resistor. What then is the dc gain? Below what frequency does the circuit stop acting like an integrator? Compare your observations and expectations. If you observe the signal your scope, you can now try various input wave forms and verify that the output is the integral (so long as the input frequency isn’t too low.) Apply a 500 Hz square wave with a 2 Vpp amplitude. Does the amplitude of the output agree with what you calculate from the integral formula? Observe the output produced by triangle wave and sine wave as well. Do they agree with your qualitative expectations? Use the ELVIS tool to obtain the Bode plot for this circuit, including the 1 MΩ “roll-off” resistor, over a frequency range from 1 Hz to 10 kHz. To make the phase easier to interpret, change the Op Amp Polarity setting to Inverted (since the circuit produces the negative integral of the input.) Also, make sure that the input amplitude is set low enough: think about what the maximum gain of the amplifier will be, and make sure the output won’t exceed the supply voltages at that point. 43 6.8 Differentiator 6 OP AMPS II 100 pF R C Vin 1k LF411 10 nF 100k Vin Vout LF411 Vout Figure 6.7: (a) Ideal and (b) practical differentiator circuits. Verify that you understand the features in the plot, and put the data in your report. Take three more Bode plots, under the following conditions: (a) with a 1 nF capacitor instead of 10 nF (b) with a 1 MΩ input resistor instead of 100 kΩ (c) with a 100 kΩ roll-off resistor, instead of 1 MΩ (Only make the one change each time; for instance, in (b) and (c), use a 10 nF capacitor.) Overlay all four plots in Excel, plotting the data with lines to make it legible. Do the differences make sense? 6.8 Differentiator An ideal differentiator circuit is shown in Fig. 6.7(a), implementing Vout = −RC dVin . dt Unfortunately, the circuit as shown is unstable. Nominally, the gain increases at high frequencies, but the since the op-amp can only respond at a finite speed, it will eventually fail. The practical differentiator circuit is shown in Fig. 6.7(b). Here the extra components serve to roll off the gain at high frequencies. Given the component values shown, at what frequency should this circuit stop acting like a differentiator? Construct the circuit, and drive it with a 500 Hz triangle wave with 2 Vpp amplitude. Does the amplitude of the square wave output agree with what you calculate? Do the results for square wave and triangle wave inputs agree qualitatively with what you expect? Use ELVIS to measure the Bode plot for the differentiator, from 100 Hz to 100 kHz. Again, set the op amp polarity to be negative, and again think about what input voltage to use: Determine what frequency will have the largest gain and make sure that the drive level is low enough that the circuit will not clip at that frequency. Plot the data in your report. Does the high frequency roll-off appear where you expect? Does the gain cross zero dB where you expect, based on the differentiator formula? 44 7 FEEDBACK AND CONTROL 7 Feedback and Control An important application of analog electronics, particularly in physics research, is the servomechanical control system. Here the concept of feedback is generalized and used to control almost any physical variable. We shall spend this and the next lab constructing and studying a servo for a simple system consisting of an LED and a photodiode. The concepts, however, are universal and apply to any servo you may need. This lab will require two days. 7.1 LED Driver This exercise will work toward the construction of the circuit in Fig. 7.8. This is considerably more complex than anything we’ve done up to now, so we will build it up gradually. However, plan from the start for what you are doing: think about where you will place the op-amps on your circuit board, and how you will get power to them all. Use short wires where you can, to reduce circuit clutter. Lay out each sub-circuit in a clear and logical way. We will be working with this circuit for the next lab as well, so keep good notes about how the components are laid out and what each sub-circuit does. The next lab will require adding two more op amps to the circuit, so leave enough room for them. The starting point is the sub-circuit of Fig. 7.1, which applies a current to a light-emitting diode (LED) proportional to an input voltage. An LED is an ordinary diode that is optimized and packaged to produce light in response to a forward current, effectively the opposite of a photodiode. By using an op-amp current source, we ensure a linear response to the control voltage. Wire up the circuit using a “standard red” LED. Note that one of the leads is longer than the other: the longer lead is the anode, which requires the more positive voltage. (You can also check which lead is which using your DMM diode tester.) Drive the circuit with your variable power supply and verify that you can adjust the brightness of the light by varying Vin . in Figure 7.1: LED driver circuit. 45 7.2 Photodiode 7 FEEDBACK AND CONTROL cathode out anode anode Figure 7.2: Photodiode detection circuit. The heavy lines indicate where accessible wires should be used. 7.2 cathode Figure 7.3: Identifying the polarity of the PNZ335 photodiode. Photodiode Now that we have a light source, we will build a servomechanism to control it. The first step in that process to measure the light level, which we will do with the circuit of Fig. 7.2. In real life, we would probably use a lens to collect light from the LED and focus it onto the photodiode, but for our purposes, it is sufficient to place the components next to each other and then bend the leads of the LED so that its top is aimed right into the sensing surface of the photodiode. Notice that the 20 pF capacitor on the op-amp feedback forms a low pass filter with a cutoff frequency of about 8 kHz. This simplifies the high-frequency response of the system and makes the servo easier to implement. Also note that the orientation of the photodiode is significant. Only the side with the darker surface is sensitive to light. The pin layout is described in Fig. 7.3, along with the direction of the photocurrent. For now, orient the photodiode so that the circuit output is positive, but you may need to change the polarity later on. Flipping around the photodiode itself would require you to move the LED to keep the correct surface illuminated; instead make sure that the wires connected to the photodiode leads are accessible so you can reverse them, as illustrated in Fig. 7.2. Apply the VPS controller to illuminate the LED. Measure the photodiode output as a function of the input voltage, and plot the relation in your report. Over what range of inputs is the response linear? The proportionality constant should be roughly one, within a factor of two or so. 7.3 Summing Amplifier and Set Point We will drive the LED sub-circuit with the summing amplifier of Fig. 7.4. This provides a constant dc bias using the zener diode, to which can be added the function generator signal and other signals as needed. Construct the sub-circuit and verify that the output provides an ac signal added to an approximately 3 V dc level, as desired. Hook the output of the summer up to the input 46 7.4 System Response 7 FEEDBACK AND CONTROL 10k FGen From photodiode op amp 10k err 10k 1N746A (3.3 V) 10k 10k 10k 10k 2k to LED driver -15 V Figure 7.4: Summing amplifier. Figure 7.5: Set point subtraction. The circuit’s ouput Verr is given by VVPS − Vphotodiode . of the LED driver. Drive the circuit with your function generator at a frequency of 1 kHz and amplitude of 1 Vpp. The photodiode output should show a response with comparable amplitude; note the value in your report. Of course, the summing amplifier inverts the signal; that is why the zener diode is arranged to give a negative voltage reference. In terms of the phase response, this introduces a 180◦ shift. The dc component of the photodiode output indicates the average light level. The servo system will attempt to regulate this level at a desired set point. We will use the VPS supply to establish this set point, through the circuit of Fig. 7.5. Construct this circuit, and set the VPS voltage to within 0.5 V of the the signal produced by the photodiode amplifier, which should be in the 3–5 V range. The output of the sub-circuit indicates the deviation of the light level from the set point, so we call the output the error signal. For now, the magnitude of the error signal should be less than 0.5 V, but it will vary as the light level on the photodiode changes. Rather than attempting to vary the ambient light level in a controllable way, we will use the function generator as an effective noise source. Ideally, the control circuit will counteract the function generator signal, so that the error signal remains fixed even when the generator is applied. 7.4 System Response In order to design the servo system, we need to know the frequency response of the driverdetector combination, defined through Vout = G0 (ω)Vin where here Vin is the function generator signal driving the LED, and Vout is the error signal produced after subtracting the set point. Here G0 is termed the open-loop transfer function, since we have not yet “closed” the feedback loop. 47 7.4 System Response 7 FEEDBACK AND CONTROL 5 Magnitude G (dB) 0 -5 -10 -15 -20 -25 -30 Open loop -35 Closed Loop -40 -45 10 100 1000 10000 100000 1000000 Freq (Hz) 60 Phase G (deg) 0 -60 -120 -180 Open loop -240 Closed loop -300 -360 10 100 1000 10000 100000 1000000 Freq (Hz) Figure 7.6: Sample data for open and closed loop transfer functions. We can measure G0 using the Bode analyzer tool. Hook the circuit input up to the ELVIS Scope 0 connector and the error signal up to ELVIS Scope 1, while leaving the function generator also attached to the circuit input. Use an input amplitude of 1 Vpp, a frequency range from 10 Hz to 200 kHz, and 5 points per division. Choose the polarity setting so that the phase is close to 0◦ at low frequencies. Copy the data (for both phase and gain) into your report and plot it. Explain the features you observe. (It is possible that the phase measurement will fall below -180◦ , in which case the analyzer wraps the phase around to near +180◦ . Your plots will be easier to interpret if you ‘unwrap’ the phase in Excel by subtracting 360◦ from the appropriate points.) In fact, the frequency limit on the Bode tool is a little lower than we would like, and the highest frequency points are sometimes inaccurate. To rectify this, take a few higher frequency points by hand, using the function generator and your scope. Obtain the gain and phase at 100 kHz, 200 kHz, 500 kHz and 1 MHz. Add the values to the Bode plot you already have. Note that if you were using the inverting polarity setting on the Bode tool, you should invert the signal on the scope to get a consistent phase value. A sample plot showing the type of data you should expect is provided in Fig. 7.6. Your data may vary from this in detail, but the general features should be correct. 48 7.5 Feedback 7 FEEDBACK AND CONTROL G0 LED Verr Photodiode Vset H (a) 100k 1k Verr 10k To summing amplifier (b) Figure 7.7: Feedback loop for LED servo. (a) Block diagram. (b) Sub-circuit. 7.5 Feedback If you wave your hand above the photodiode, it should be easy to see how the error signal is affected by the room lights. Use your oscilliscope to estimate the signal variation produced by alternately covering and uncovering the photodiode with your hand, and note the value in your report. We suppose that this is a problem... perhaps we have an experiment at the location of the photodiode that requires constant illumination. The idea of the servomechanism is to feed back the photodiode signal to the LED driver in such a way as to compensate for the noise. If the room lights get brighter, the LED would get dimmer, and vice versa. The system for doing so is shown schematically in Fig. 7.7(a). We have already built and characterized the system function G0 . We shall now set up the feedback H. The feedback circuit we shall use is shown in Fig. 7.7(b). Construct this sub-circuit, and set the 100 kΩ pot to 0 Ω corresponding to zero feedback amplitude. Attach the feedback to the main circuit as in Fig. 7.8. Before turning everything on, however, consider the polarity of the feedback. We require the feedback to be negative: if the room light level increases, the circuit should reduce the LED current to compensate. The actual sign of the feedback depends on whether it passes through an even or odd number of inverting amplifiers in the loop, and also on the polarity of the photodiode itself. Examine Fig. 7.8 and try to determine which photodiode polarity is required. (The polarity shown in the diagram may or may not be correct.) Set the photodiode polarity as you think is necessary, and then turn on the circuit and monitor the error signal on your oscilloscope as you gradually turn up the feedback resistor. The effect may be clearer if you use the function generator to drive the circuit with a 1 kHz, 1 Vpp sine wave. (Recall that that the set point should be adjusted so that the dc level 49 7.6 Servo Performance 7 FEEDBACK AND CONTROL of the error signal is near zero.) If everything is working correctly, the error signal should move toward zero and the noise in it should be reduced as the feedback gain is increased. The noise should continue decreasing to a minimum level, but when you increase the gain further, the error signal will start to oscillate at a high frequency. If the error signal grows as soon as the feedback is increased, then you probably have the photodiode polarity wrong, and you should swap the photodiode wires. Whichever orientation you started with, do reverse the photodiode leads and observe the other orientation as well. Note that when you reverse the photodiode, you will also need to change the sign of the set-point voltage to re-zero the uncontrolled error. Record which diode orientation is correct, and describe what you observe in both cases. With the function generator turned off, increase the gain resistor until the circuit just oscillates and measure the resulting oscillation frequency. Then take out the potentiometer and measure the corresponding resistance value. Replace the pot and reset the resistance to a point where the stabilization is good, which should be slightly below the point where oscillation occurs. Again measure and record the corresponding resistance. Replace the pot at this same setting, and do not change it again for the remainder of the exercise. 7.6 Servo Performance Once you get the servo working, you can characterize how well it works. To start, measure the variation in error signal caused by covering the photodiode with your hand. How does it compare to what you saw with no feedback? To be more quantitative, you can measure how well the servo attenuates noise at a given frequency. Here we will use the simulated noise generated by the function generator as as shown in Fig. 7.8. You have previously measured the open-loop system response G0 , with no feedback. Now measure the closed-loop response, Gc , with the feedback signal in place. The transfer function is the ratio of the error signal to the function generator input, just as before. Use the Bode tool to measure the response from 10 Hz to 200 kHz, and take points from 100 kHz to 1 MHz by hand. Load the data into Excel and plot it on the same graph as G0 . The difference between these curves shows the amount of noise reduction that the servo provides. Sample curves showing what you should expect can be seen in Fig. 7.6. As the figure shows, at some frequencies the noise is actually higher for the closed-loop curve. This is called noise peaking, and occurs when the servo is at the edge of its stability. (Or equivalently, when G0 H is close to -1 at some frequency.) How does the frequency of the noise peak compare to the oscillation frequency you measured in the previous section when the feedback gain was too high? 7.7 Servo Analysis We can compare the servo performance to what we expect. For the open-loop transfer function G0 and feedback transfer function H, theory predicts the closed-loop transfer function to be G0 Gc = . 1 + G0 H 50 7.7 Servo Analysis 7 FEEDBACK AND CONTROL You have measured G0 already, so now measure H for the circuit of Fig. 7.7(b): Without changing the potentiometer setting, replace the input from the error signal with the signal from the function generator, and monitor the output of the feedback amplifier with the Bode analyzer. Set the input amplitude in the analyzer tool to be 0.3 V so the op amp doesn’t saturate. Measure the response from 10 Hz to 1 MHz as before, and plot the data in your your report. Again, make sure the polarity setting is such that the phase is zero at low frequencies. Using this and your earlier data, calculate the theoretical response G0 /(1 + G0 H). To compare to Gc , you will need to obtain both the magnitude and phase of this quantity. This involves some complex algebra that you will get to work through in your next homework assignment. For now, however, you can simply use these results: If G0 = geiφG and H = heiφH , define z = gh and φz = φG + φH . We then obtain G0 g 1 + G0 H = p1 + 2z cos φ + z 2 z and arg G0 1 + G0 H = φG − tan −1 z sin φz 1 + z cos φz . (Recall that arg(q) is the phase of a complex number q.) Here g and h will need to be expressed as dimensionless (×) gains, not in dB, and Excel wants φz in radians. Calculate this magnitude and phase, and add them to your plots of Gc . You should see that the two curves agree reasonably well, though probably not perfectly. Conventionally z = |G0 H| is defined as the loop gain and φz = arg(G0 H) as the loop phase. From your data, estimate the frequency at which the loop phase reaches -180◦ . What is the loop gain at that frequency? The gain should be a bit below zero dB, and the frequency should be slightly higher than where you observed noise peaking and oscillation. This is because instability occurs when the phase is -180◦ at unity gain, and by turning the feedback gain up to nearly the point of oscillation, you put the circuit near the point of instability. The phase margin of a servo is defined as the difference between the loop phase and -180◦ at the frequency where the loop gain reaches 0 dB. What is the phase margin for your circuit? Does the loop phase come primarily from the LED/photodiode subcircuit, or from the feedback amplifier? In the next lab, we will attempt to improve this circuit by using more sophisticated feedback schemes. Hook the feedback amplifier back up and readjust your circuit to again provide stabilization, leaving the circuit set up. 51 7.7 Servo Analysis 7 FEEDBACK AND CONTROL "Noise" input 10k 10k 1N746A 10k 2k -15 V LED controller 10k Summing Amplifier 330 20 pF 10k Set point subtraction 1M 10k Verr VPS Photodiode amplifier 10k 10k 100k 1k Feedback amlifier Figure 7.8: Complete servo circuit. All op amps are LF411s. 52 8 FEEDBACK AND CONTROL II 8 Feedback and Control II In the previous lab, you constructed a circuit to stabilize the light level at a photodiode. We now return to the same circuit and develop more effective ways to implement the servo control, working up to the full PID control mechanism. We also explore the transient response of a servo stabilized system. This lab will require two days. 8.1 Proportional Control Figure 8.1 shows the circuit you should still have from the previous lab. Here the control signal is implemented by multiplying the error signal by a constant, so this type of system is called ‘proportional control’. For reference, we will repeat a few measurements from the previous lab. First, unhook the control signal from the summing amplifier so that the circuit is uncontrolled. Use the Bode tool to measure the open-loop transfer function from the “noise” input to the error signal. Use a frequency range of 100 Hz to 200 kHz. If the response is lower than what you observed in the previous lab, you may need to adjust the alignment of the LED and photodiode. When you have a satisfactory curve, save the data in your report. As before, we will refer to this function as G0 . Now reattach the control signal and set the proportional gain to just below the point "Noise" input 10k 10k 1N746A 10k 2k -15 V LED controller 10k Summing Amplifier 330 20 pF 10k Set point subtraction 1M 10k Verr VPS Photodiode amplifier 10k 10k 100k 1k Feedback amlifier Figure 8.1: Circuit you should have retained from the previous lab. 53 8.2 Integral Control 8 FEEDBACK AND CONTROL II where the circuit oscillates. Again measure the transfer function for the error signal and import it to your report. Also record the oscillation frequency you observe when the gain is too high. Define the period of those oscillations to be TP , which we will use again later. After setting the potentiometer to its maximum stable value, take it out and measure the resistance. Define the corresponding amplifier gain R2 /R1 as HP , and note this in your report as well. Then reduce the gain value by a factor of two and replace the pot in your circuit. Measure the error response again, and plot both closed-loop curves together in your report. Explain the differences between the responses with maximum gain and with half-maximum gain. 8.2 Integral Control Although the proportional gain circuit does reduce the sensitivity of the circuit to errors, it doesn’t do as good a job as it might. At low frequencies, you should see about a factor of 10 noise reduction, but it should still be easy to observe, for instance, the effect of moving your hand around over the photodiode. The performance can be significantly improved using integral control, where the control signal consists of the time integral of the error signal, rather than the error signal itself. Add integral control to your system using the circuit of Fig. 8.2. The output of this circuit is Z 1 Verr dt, RI CI so the choice of τI = RI CI sets the effective gain of the circuit. An appropriate value for τI can be estimated from the response curves you took in Section 1. In the open-loop response G0 , you should see that the response starts out fairly flat, and starts to fall at some frequency fc . A good way to characterize fc is to find the frequency where the phase of the response has decreased by 45◦ . The time constant τI should be set so that the integral gain at fc is about equal to HP , the maximum stable proportional gain measured in Section 1. Select a capacitor and a potentiometer so that when the potentiometer is at its maximum value, the time constant is around ten times larger than the above estimate. Make sure to note the values you choose in your report. Add the integral stage to your circuit. Start out with the potentiometer at its maximum value, and thus at the minimum gain. For now, unhook the proportional control signal from the summing amplifier. CI RI Verr 10k To V- terminal of summing amplifier Figure 8.2: Sub-circuit for implementing integral control. See also Fig. 8.4. 54 8.3 PI Control 8 FEEDBACK AND CONTROL II Power up the circuit, and gradually increase the integral gain. As with the proportional control, you should see the error signal stabilize and then eventually start to oscillate. Now, however, the stabilization should appear much more effective in response to, for instance, waving your hand above the photodiode. With the integral gain set just below the oscillation point, measure the transfer function and plot it in your report. Measure the potentiometer resistance and report that as well. Note that Fig. 8.2 does not include a roll-off resistor to limit the gain at low frequencies. Why doesn’t the output of the op amp eventually increase until it rails, as we have seen before? 8.3 PI Control Often, the control signal consists of a proportional term and an integral term added together. This is usually referred to as PI control. Reattach the proportional control signal, with the proportional gain still set to half its maximum value. (This is usually a reasonable starting point for a PI system.) Measure the combined PI transfer function and add it to the plot of the integral response. Try adjusting the two gains together to achieve the minimum possible noise response. What trade-offs do you observe between higher and lower gains? If you are able to improve the response, plot that data as well. Note in your report the resistor values used. What benefits does PI control provide compared to integral control alone? 8.4 PID Control The noise response can sometimes be improved further yet by adding a third term to the control signal that is proportional to dVerr /dt. This is achieved with the circuit of Fig. 8.3, which provides an output of dVerr . RD CD dt The required τD = RD CD time constant can be estimated as HP TP /8, where HP is the maximum proportional gain value and TP is the oscillation period from Section 1. Use them to select a suitable combination of capacitor and pot, and note them in your report. Note that the capacitor you choose should not be too large: to avoid loading the output of the previous op amp, the input impedance of the derivative amplifier should remain above 100 Ω or so for frequencies up to 100 kHz. RD CD Verr 10k To V- terminal of summing amplifier Figure 8.3: Sub-circuit for implementing derivative control. See also Fig. 8.4. 55 8.4 PID Control 8 FEEDBACK AND CONTROL II "Noise" input 10k 10k 1N746A 10k LED controller 2k Summing Amplifier -15 V 330 20 pF 10k Set point subtraction 1M Control Signal 10k Verr VPS Photodiode amplifier 10k 10k 100k Proportional 1k 10k CI RI Integral 10k RD Derivative CD 10k Figure 8.4: Complete circuit including PID control. 56 8.5 Transient Response 8 FEEDBACK AND CONTROL II 20 pF 10k 1M 10k Verr FGEN Photodiode amplifier 10k Scope Ch 1 10k Scope Ch 2 Figure 8.5: Modifications to circuit for measuring transient response Construct the derivative circuit, leaving the previous PI components in place. Again starting out with the RD resistor turned all the way down to provide minimum gain. Power on the circuit and gradually turn up the derivative gain until the system oscillates. Note in your report the resistor value at which this occurs. Reduce the gain a bit from there and measure the transfer function. Compare to what you achieved with PI control. Do you observe any improvement? Often it is beneficial to decrease the proportional gain when adding derivative control. Try that, and try adjusting all three gains to optimize the response. Plot your best response curve in your report, and note all of the resistor values used. You may or may not get much improvement. In many systems, the benefits of derivative control are limited by the high frequency characteristics of the open-loop response, and PI control does as good a job as possible. At this point, your circuit should appear as in Fig. 8.4. Your report should contain four Bode plots (of gain and phase vs. frequency): (1) the open loop response from Section 1, (2) a plot showing the response with proportional control at both the maximum and half-maximum levels, (3) a plot showing integral control, PI control with the initial resistor values, and PI control with the optimum values, and (4) a plot showing PID control with the optimum values. For each case, you should also have the corresponding gain resistor values. Put together one final plot for comparison, showing the optimum responses for each of the P, PI, and PID control mechanisms, along with the open-loop response for reference. 8.5 Transient Response Up to now, we have focused primarily on the frequency response of the system. It can also be useful to observe the transient response to a sudden step. In practice, this is usually important when the set point of the servo is being changed rapidly. To observe the step response, we will modify the circuit to use the function generator rather than the VPS supply to establish the set point for the servo, as seen in Fig. 8.5. Set the dc offset of the function generator to equal the previous set point (which should be close to the open-loop voltage produced by the photodiode amplifier). This makes the upward and downward steps symmetrical about the previous set point. Set the function generator signal to a 2 kHz square wave with a 1 Vpp amplitude. 57 8.5 Transient Response 8 FEEDBACK AND CONTROL II Monitor both the function generator and the output of the photodiode amplifier on your oscilloscope. You should then see that as the set point changes, the photodiode response follows, perhaps with some delay and/or oscillation. These delays and oscillations are what we will be measuring. To start, unhook the integral and differential control, and use the proportional control only. Observe the behavior as you vary the gain resistor, and note in your report what you see for high (but still stable), low, and intermediate gain values. At high gain values, what oscillation frequency do you observe? To be quantitative, we can characterize the response with two parameters, illustrated in Fig. 8.6. The rise time is the time required for the photodiode signal to rise from 10% to 90% of its total change. The settling time is the time required for the signal to settle to within 5% of its final value, measured from when the function generator changes. For example, if the photodiode signal is changing from 1 V to 2 V, the rise time would be the time need to rise from 1.1 V to 1.9 V (counting just the first time it reaches 1.9 V, if it is oscillating.) The settling time would be the delay between when the function generator rises to the time when the photodiode signal has settled to within a range of 1.95 to 2.05 V. Accurately measuring the rise time and settling time on the scope can difficult. To help, you can use the Delay feature of the scope to zoom in on the transition. Start with the scope showing both the function generator and photodiode signals with a reasonable feedback gain value. Switch both channels to ac coupling, and trigger on the photodiode signal. Now locate the button labelled ‘B’, just below the Variables knob. Press it, and the scope switches to a zoomed in section of the trace with a variable delay after the trigger. (The normal display can be restored by pressing the ‘A’ button.) The values of the time/division and the delay are displayed on the screen. Adjust the delay value using the Variables knob until it is about half a period of the square wave. The scope should then display a transition, specifically the next transition after the one you are triggering on. This lets you see the transition in both signals clearly. You can use the cursors to measure the rise time and settling time, but it is still a little difficult because you can’t see both the horizontal and vertical cursors at once. You can use the fixed division grid on the scope screen to provide a reference point, or you can obtain an erasable marker from the instructor that you can use to draw on the screen. Once you have a measurement technique established, measure the rise time and settling time for gain resistor values near to Rmax , Rmax /2, and Rmax /4, where Rmax is the largest value that maintains the circuit’s stability. Ideally, the upward and downward transitions would be symmetric, but they probably are not here due to nonlinearities in the LED and photodiode. For simplicity, only measure the transient response for the upward transitions. Next, unhook the proportional gain and run the circuit with integral gain only. Set the gain resistor to the maximum stable value. You will find that the settling time is much longer, so you may need to use a lower drive frequency in order to observe the complete response. Finally, look at the PI and PID control schemes. For each, set the gain resistors to the optimum values you found with the Bode plots in the previous sections, and measure the response times at those values. For the PID circuit, try adjusting the gains to minimize the rise time and settling time. You may find the derivative control has a little more impact in this type of measurement than was apparent in the Bode plots. In the PID system, can you 58 8.5 Transient Response 8 FEEDBACK AND CONTROL II t settle 105% 95% 90% t rise 10% 0% Figure 8.6: Definition of rise time and settling time. The dashed line indicates the function generator signal qualitatively describe the effect of each control component? This completes our study of control systems, so you can disassemble this circuit when you are done. 59 9 LOGIC GATES 9 Logic Gates The next few labs will deal with digital logic, a central topic in modern electronics work. This first lab introduces the basic logic gates and the different logic families. This lab will require two days. Reading: HH sections 8.01–8.12, 8.20–8.22 (pgs. 471–492, 517–521) 9.1 Transistor Gates Consider the circuit shown in Fig. 9.1(a). Here the transistors are being used only in their saturated and off states, not in their ‘active’ mode where IC = βIB . Recall that when the base current IB is zero, the collector current IC is also zero, while if the base current is large, there is a large IC , limited by the transistor’s saturation voltage VCES . In reference to the figure, if either signal A or signal B is low, the series collector current will be zero and the output signal Q will therefore be high (about Vcc ). If both A and B are high, then a large collector current will flow and Q will be low. This circuit should therefore implement the NAND gate: the output is true (= high) if and only if (A AND B) is false. Its truth table can be written as: A B Q H H L L H H H L H L L H where ‘H’ stands for high and ‘L’ for low. Construct the circuit on your breadboard, using Vcc = 5 V. Note that most of the logic functions of the ELVIS board are located on the right-hand side, including a hookup to the 5 V supply and ground. To start, use either the supply (H) or ground (L) for the inputs and measure the output voltage with your DMM. Record the output voltage for each combination of inputs in your report. Is it consistent with the NAND truth table given above? What output values does it give for “L” and “H”? In digital circuits, we don’t normally care about the actual voltage level, so the DMM provides more information than necessary. ELVIS has a Digital Reader and a Digital Writer tool that will be more convenient. The pin connections are the DIO pins located on the upper right corner of the board. Change your circuit to take the A input from the DIO 0 connector and the B input from DIO 1. Connect the output Q to DIO 8. Start up the DigIn (Reader) and DigOut (Writer) tools. In the Writer, set the Lines to Write to 0-7, and in the Reader, set Lines to Read to 8-15 and then run the tools. The HI/LO buttons in the Writer set the output levels, and the lights on the Reader indicate the input levels. Measure your circuit’s truth table again and list it in your report. Unhook one of the inputs. Does the ‘floating’ input act like an H signal or like an L signal? 60 9.2 Integrated Gates 9 LOGIC GATES Vcc Vcc 470 470 Q 470 Q A A 470 B 470 B (a) 470 (b) Figure 9.1: (a) Transistor implementation of a NAND gate. (b) What gate is this? All transistors are 2N3904. If you’ve forgotten the pin designations, check Lab 4 or look them up on line. Rewire your circuit to the configuration of Fig. 9.1(b), again using the DIO signals for the inputs and outputs. Measure the truth table. Does it agree with your expectations? What logic function does this circuit implement? Once you are done with this section, disassemble your circuit and return the parts to the supply cabinet. 9.2 Integrated Gates You would not normally want to construct a logic gate from transistors, since integrated circuit chips are available which perform better. Four NAND gates are available in the 7400 chip, shown in Fig. 9.2. Each set of numbered pins (1A, 1B, 1Q) refers to an independent gate. The 7400 series comes in several variants, including the 7400 proper, the 74LS00, the 1 14 2 13 3 12 4 7400 1A 1B 1Q 2A 2B 2Q GND 11 5 10 6 9 7 8 Vcc 4B 4A 4Q 3B 3A 3Q A Q B Figure 9.2: The 7400 quad NAND gate. 61 9.3 Logic Families 9 LOGIC GATES A 5V Q 5V A A Q B Q 5V B NOT 5V AND OR Figure 9.3: Circuits to produce NOT, AND, and OR gates using NAND gates. 74HC00, and the 74HCT00. These all have somewhat different performance characteristics, but the same pin designations. For now, obtain a 7400 chip from the supply cabinet. Wire up the chip with Vcc = 5 V on pin 14 and attach pin 7 to ground. Pick one of the gates and wire the inputs and output to the DIO connectors as before. Measure and record the truth table, and verify that it is indeed a NAND gate. Unhook one of the inputs and determine how a floating input is evaluated. It turns out that the NAND gate is universal, meaning that NAND gates can be combined to produce any other logic gate. Figure 9.3 shows how to implement NOT, AND and OR gates. Using the gates on your 7400 chip, construct each of these gates and check its truth table. List your results in your report. 9.3 Logic Families As mentioned, the 7400 gate chips come in several varieties, known as families. The families are distinguished by the middle letters of the chip name, so the 74LS00 is the LS family and the 74HC00 is the HC family. The initial 74 indicates that these are all logic gate chips, and the final numbers specify which gates are implemented and define the pin layout. Dozens of families are available, but the 7400, 74LS00, and 74HC00 are among the most common. We shall compare two of their most important characteristics, switching speed and power consumption. The switching speed can be measured using the circuit of Fig. 9.4. Here the A input is taken from the Sync output of the function generator, which provides a 0 to 5 V square wave. With B tied to 5 V, the circuit acts as an inverter, as in Fig. 9.3(a). Monitor the Sync signal on your scope along with the output Q. As the input rises and the output falls, measure the “gate delay” time Tsw between when the input rises and the output falls. To be precise, you can use the logic threshold values of 2.0 V for the input and 0.4 V for the output as the start and stop times for the measurement. The delay is very short, so make sure the BW limit button on the scope is out and use scope probes on the 10× setting to minimize the measurement capacitance. You may find the “10× mag” button useful for increasing the time resolution. To measure the power consumption of the chip, hook up an ammeter in series with the Vcc supply voltage. Measure the current drawn when the output is low, when the output is 62 9.4 CMOS Logic 9 LOGIC GATES Figure 9.4: Circuit for observing the timing characteristics of a gate. high, and when the output is switching at 5 MHz. Calculate the power consumed in each case by multiplying the current times the voltage and report your results in mW. Perform these measurements for each of the 7400, 74LS00, and 74HC00 chips. What is the main difference between them? 9.4 CMOS Logic The 7400 and 74LS00 chip both use bipolar transistors to implement the logic gates, and are referred to as ‘transistor-transistor logic,’ or TTL. The 74HC00 chip is different in that it uses FETs instead. This type of gate is often called ‘CMOS’ because it uses complementary MOSFET transistor pairs. You can usually identify a CMOS gate because it will have a ‘C’ somewhere in its family designator. CMOS chips have some signifcant performance differences from bipolar gates. You should have found above that the static (not switching) power dissipation is much lower. This is because FETs don’t draw any gate current. This is obviously an advantage, but offseting it is the fact that CMOS chips are much more easily damage by static discharges and other electrical faults. An important practical consideration when using CMOS chips is that all unused inputs must be tied to a definite level. This is recommended for all logic circuits in any case, but you saw in Section 9.2 that TTL gate inputs generally float high. To compare, wire up a 74HC00 chip with the A1 and B1 inputs high. Wire the other six inputs either high or low, as convenient. (Don’t wire any of the outputs to a fixed value!) Observe the Q1 output on the scope, verifying that it is low. Now unhook the corresponding A input. What do you observe? Run a wire to the input and touch its end with your finger. The output will likely oscillate at 60 Hz due to your acting as an antenna. What happens if you hold the input wire in one hand and touch the grounding pad or a 5 V wire with your other hand? Rather than touching the input wire itself, what if you just hold its plastic insulation in one hand while touching 0 or 5 V with your other hand? Describe your observations in your report. Can you see why it is important to tie all inputs to a definite voltage? 63 9.5 Combinatorial Logic 9 LOGIC GATES A B Q C Figure 9.5: Combinatorial logic circuit. 9.5 Combinatorial Logic By combining various logic gates, you can implement arbitrary logical functions. Figure 9.5 shows a simple example in which the output Q depends on three input bits A, B, and C. Analyze this circuit and construct its truth table. In binary arithmetic, (A, B, C) can be taken as the binary representation of an integer A × 4 + B × 2 + C × 1, where the L state represents zero and the H state represents 1. In this interpretation, what mathematical function does the circuit perform? Construct the circuit on your breadboard using TTL gates. The required chips can be found in the cabinet, and the pin designations can be quickly determined with an internet search on the part number. Either the LS versions or the plain 7400 series can be used. Measure the truth table as implemented, and confirm that it follows your expectations. 9.6 Three-State Logic Another type of logic gate that is often useful is the “three-state” device. At first, this might suggest trinary logic, where three output levels represent the values 0, 1, 2. But in fact, the outputs of a three-state device are 0, 1, and ‘off.’ In the ‘off’ state, the device asserts neither a high nor a low value, but is instead effectively disconnected from the output pin. This is useful when several devices are wired together to a common output. A common output is normally called a ‘bus,’ and is used when multiple devices take turns sending signals to one receiver. The 74HCT125 is a three-state buffer, shown in Fig. 9.6. It has the truth table OE A Q L L L L H H H X off Here ‘X’ stands for any value. The OE input should be read as “output enable” and the bar indicates that you need to supply the inverse of the enable signal. In other words, if ‘output enable’ is supposed to be ‘true,’ then you need to supply a ‘false’ value for OE. As with the NAND gates, there are four separate buffers on each ’125 chip. Set up the circuit shown in Fig 9.6(c). Take the inputs A1 and A2 to represent data signals, while OE 1 and OE 2 control which signal is applied to the output bus. First set OE 1 = L and OE 2 = H. Then you should see that Q follows A1 , while A2 is ignored. Conversely, 64 9.7 Multiplexer 1 14 2 13 3 4 5 74HCT125 OE1 A1 Q1 OE2 A2 Q2 GND 9 LOGIC GATES 12 11 10 6 9 7 8 Vcc OE4 A4 Q4 OE3 A3 Q3 DIO 0 A1 OE1 A Q DIO 6 DIO 1 DIO 8 A2 OE2 OE DIO 7 (a) (b) (c) data Figure 9.6: The 74HCT125 quad three-state buffer. (a) Pinouts. (b) Circuit symbol. (c) Testing circuit. a a b b Q c c X OE 4 Y Q OE 3 d d X X Y address OE 2 Y Figure 9.7: (a) Circuit diagram for a 4input multiplexer. (b) Equivalent switch circuit. Figure 9.8: Partial circuit for translating the address (XY ) to the enable signal (abcd). when OE 1 = H and OE 2 = L, you should see Q = A2 while A1 is ignored. Describe your observations in your report. What do you observe for Q when OE 1 = OE 2 = H? Why would it be a bad idea to set OE 1 = OE 2 = L? 9.7 Multiplexer To demonstrate the use of three-state logic, we will implement a multiplexer (or MUX). This device is shown schematically in Fig. 9.7(a). It has a total of six inputs, four representing data (a, b, c, d) and two representing an “address” (X, Y ). The single output Q is meant to follow one of the four data inputs, and the address selects which input it follows. This can be represented by the truth table: 65 9.8 Monostable Multivibrator 9 LOGIC GATES X Y Q L L a L H b H L c H H d where a, b, c, and d stand for the value at the corresponding input. You might think of the multiplexer like a switch, as in Fig. 9.7(b), with the address bits setting the switch position. Just like switches, multiplexers are useful in many situations. A multiplexer can be constructed using the three-state buffer. Simply hook each input signal (a, b, c, d) to a corresponding buffer input (A1 , A2 , A3 , A4 ), hook all four outputs (Q1 , Q2 , Q3 , Q4 ) together, and then use the OE pins to determine which input is applied to the common output bus. To make this work, we need to use logic gates to convert the two address bits (X, Y ) to one of four enable signals, as follows: X Y OE 1 OE 2 OE 3 OE 4 L L L H H H H L H H L H H L H H L H H H H H H L Figure 9.8 shows one way to implement this for the b, c, and d signals. Determine for yourself how the enable signal for the a channel be derived. (Feel free to use a different chip besides the NAND gate.) Once you understand the design, set up the circuit and verify that the multiplexer works as desired. Test it using the Digital Writer and Reader tools, making sure that for each combination of address bits, the output signal follows the proper input signal and is unaffected by the other inputs. Describe your approach and results in your report. Note that integrated multiplexer circuits are available, such as the 8-input 74151. It would be unusual for you to actually build your own multiplexer in practice. 9.8 Monostable Multivibrator The monostable multivibrator is a digital component that finds many applications in circuits that need to generate pulses and delays. When triggered by a transition on its input, it generates a single output pulse with a duration determined by an RC network attached to the chip. Because of this behavior, another common name for the device is a ‘one-shot.’ A common one-shot is the 74122, shown in Fig. 9.9. It has a fairly complicated input logic arrangement in order to provide maximum triggering flexibility. Referencing the circuit diagram, however, an output pulse will be produced whenever the input to the square block sees a rising edge. If we tie the A2, B1, and B2 inputs high, then what type of transition applied to the A1 terminal will produce a pulse? Wire up the circuit that way. You will also need to tie the CLR terminal high (so that the device is ‘not cleared’). The output pulse duration is given approximately by tw = 0.45RC The resistor R should be in the range of 5 kΩ to 50 kΩ, and the capacitor should be larger than 1 nF. (More detailed information about the timing elements can be found on the 74122 66 9.9 Logic Races 9 LOGIC GATES 5V R 1 14 2 13 3 12 4 7400 A1 A2 B1 B2 CLR Q GND 11 5 10 6 9 7 8 Vcc R/C NC C NC Rint Q C R/C A1 C Q B1 B2 A2 Q CLR Figure 9.9: The 74122 monostable multivibrator. The logic gates at the input are all internal to the chip. data sheet, if needed.) Set up your circuit using a 100k pot and a 10 nF capacitor, and drive the input A1 at 500 Hz with the Sync pulse from the function generator. Observe the input and output (Q) signals on the scope, and verify that the output behaves as claimed when you change the pot resistance. How accurate is the above formula for tw ? One-shots end up being so handy that Horowitz and Hill spend some effort warning against their overuse. The main concern is that the timing they produce is not very precise, so you shouldn’t use them when precision is important. Incidentally, the term ‘multivibrator’ refers to a circuit with two possible states. In a monostable multivibrator, only one of the states is stable: when the circuit is put in the unstable state, it returns to the stable one after time tw . A bistable multivibrator remains in whichever state you place it, and is more commonly called a latch. An astable multivibrator won’t stay put in either state, and thus forms an oscillator. 9.9 Logic Races The 74122 chip can be used to illustrate an important condition known as a logic race. In this condition, the behavior of a circuit depends on the difference in propagation times between two signals. Unless these propagation times are deliberately controlled, unpredictable behavior can result. As an example of a logic race, suppose that you applied the Sync pulse input to both the A1 and B1 inputs of the 74122, leaving the other inputs all high as before. The net input signal applied to the trigger of the multivibrator can then be expressed as A1 · B1, where the bar indicates a NOT operation and the · indicates AND. Figure 9.10 shows how the form of the net trigger signal depends on the order in which the A1 and B1 signals are processed by the circuit. If A1 comes first, an output pulse is triggered on a falling edge of the input, while if B1 comes first, the pulse is triggered on a rising edge. If both signals are evaluated at precisely the same time, no output pulse is produced at all. Without knowing the internal details of the circuit construction, it is impossible to determine what the behavior will be. To prevent this kind of uncertainty, logic races should be avoided in circuit design. To see what actually happens here, modify the circuit as described above. Describe what you observe at the output when the input state changes. 67 9.9 Logic Races 9 LOGIC GATES A1 A1 B1 B1 A1 B1 A1 B1 (a) (b) Figure 9.10: Logic race in a 74122 chip, showing how the effective input signal depends on whether (a) input A1 or (b) input B1 is evaluated first. 68 10 FLIP-FLOPS, MEMORY, AND STATE MACHINES 10 Flip-Flops, Memory, and State Machines A flip-flop is a device whose output state changes in way depending on both the input signals and the current output state. This is the simplest form of memory, which is a key component of digital design. Flip flops also form the basis for a state machine, which is the basic archetype of a digital computer. This lab will require two days. Reading: HH sections 8.15–8.18, 8.24 (pgs. 500–514, 523–524) 10.1 D-type Flip Flop There are several varieties of flip-flop, but the simplest and most useful is the D-type device illustrated in Fig. 10.1. The logic table for the 74LS74 is S R C D Q Q L H X X H L H L X X L H L L X X H H H H ↑ L L H H H ↑ H H L Here ↑ denotes an L-to-H transition on the C (“clock”) input, which triggers Q to change to the state on the D (“data”) input. Also, notice the odd behavior (Q = Q) when S and R are both low. The 74LS74 chip contains two D-flop circuits. Wire up one of the flops, using DIO signals to drive all four inputs. Monitor the outputs using the DIO Reader. Does the device behave as advertised? S 1 14 2 13 3 4 74LS74 1R 1D 1C 1S 1Q 1Q GND 12 11 5 10 6 9 7 8 Vcc 2R 2D 2C 2S 2Q 2Q D Q C Q R Figure 10.1: The 74LS74 dual type-D flip flop. 69 10.2 State Machines 10 FLIP-FLOPS, MEMORY, AND STATE MACHINES Combinatorial Logic A Qn Dn D (a) B C C State Q1 0 A B 0 C 1 D 1 Q2 0 1 0 1 (b) Figure 10.2: (a) Schematic of a state machine. Here the slashes on the signal lines indicate a parallel set of several values. (b) Example of a state diagram, showing a two-bit counter. 10.2 State Machines A basic state machine consists of a register (an array of D-flops) whose outputs are connected back to their inputs via a set of logic gates. With every clock pulse, the state machine’s output progresses through a fixed series of states. The states and their order of progression is determined by the logic gates used. Figure 10.2 illustrates these ideas. The simplest interesting state machine is the divide-by-two circuit of Fig. 10.3(a). Construct it and drive the C input with the Sync output of your function generator. Observe the input and output signals on your scope. Is the output frequency half of the input frequency? For a more interesting example, suppose we wanted a divide-by-three circuit. Here we will need to use two D-flops, and we want their output state to cycle through: Q1 Q2 L L L H H L L L L H ... This divides the input frequency by three since the output cycle repeats once for every three input cycles. Either Q1 or Q2 can be taken as the output when a single signal is required. Note that the output wave form is no longer symmetric, since the signal is low for two-thirds of the period. Nonetheless, the signal is periodic with a period that is three times longer than that of the input. In this state machine, we don’t really care where the (H, H) state goes, as long as it is not back to (H, H). What would be the problem with that? To implement this, we need logic gates to implement the truth table Q1 L L H Q2 L H L D1 L H L D2 H L L 70 10.3 Switch Debouncing D 10 FLIP-FLOPS, MEMORY, AND STATE MACHINES D1 Q Q1 ? D2 Q2 in in Q out (a) (b) Figure 10.3: (a) Divide-by-two circuit. (b) What type of gate at D2 is required to make this circuit divide the input frequency by three? where each state leads to the next on our list. Here we see that we need D1 = Q2 , so we can wire Q2 directly to D1 , as in Fig. 10.3(b). What do we need to generate D2 ? Where does the state (H, H) go in your design? Using your gate, construct the circuit and drive the clock signals of both flops with the Sync signal. Observe the outputs on your scope and describe their behavior in your report. Does everything work as you expected? Is there a maximum frequency for correct operation, or does it work all the way to 5 MHz (the maximum we can apply)? 10.3 Switch Debouncing Sometimes it is convenient to set logic levels by hand, using a switch. For circuits like flip flops that trigger off an edge, this is problematic because manual switches bounce: rather than giving a clean transition from open to closed, the transition makes and breaks several times before settling to the desired state. This can generate spurious triggers. To see this, get a “mini DIP” switch from the cabinet. This is simply an array of SPST switches that fits nicely in your circuit board. The wiring shown in Fig. 10.4(a) configures the switch to provide +5 V when open, or 0 V when closed. It also powers an LED to indicate the signal state, which is helpful in complicated circuits. Wire one switch up to the C input of your divide-by-three circuit (replacing the Sync signal). Observe the outputs and record the (Q1 , Q2 ) states after each flip of the switch, for at least 10 transitions. Does the circuit correctly divide by three? The easiest fix for the bouncing problem is to use a debouncer chip, like the MC14490 in Fig. 10.4(b). This chip uses a set of flip-flops and a self-generated clock signal to detect an input transition, but then ignore any other transitions for the next few ms while the bouncing settles down. The result is one clean transition on the output. Wire up the debouncer as shown in Fig. 10.4(c). The debouncer inputs include an internal pull-up resistor, so you don’t need the connection to 5 V on the input, but the chip doesn’t provide enough current to illuminate the LED. The LED will probably be helpful, so leave it set up as in (a). (The internal pull-ups also mean that you don’t need to connect the 71 10.4 RAM 10 FLIP-FLOPS, MEMORY, AND STATE MACHINES 5 nF 5V C LED 4.7k (a) 1 16 2 15 3 14 4 5 6 MC14490 1k In1 Out2 In3 Out4 In5 Out6 OSCin GND 13 12 11 7 10 8 9 Vcc Out1 In2 Out3 In4 Out5 In6 OSCout (b) 5V 5V OSC In From switch OSC Out In Out To clock (c) Figure 10.4: (a) Using a switch to generate logic levels. (b) MC14490 hex bounce eliminator. (c) Wiring diagram for the MC14490. Use 1N914 diodes. unused inputs to ground.) Use the debouncer output to clock your divide-by-three circuit. As before, record the output sequence you obtain. Does it work correctly now? You can put away your flip-flop circuit now, but keep the switch and debouncer chip set up. 10.4 RAM A register is a simple form of memory, and is useful when you need to store up to a few bytes or so. (Recall one byte = eight bits.) When larger amounts of data storage are required, however, RAM (= random access memory) is more practical. There are several types of RAM, but the simplest is probably SRAM (static RAM), which consists essentially of a huge array of D-flops together with a multiplexer and demultiplexer to allow each flop to be individually accessed. A schematic is shown in Fig. 10.5. The idea here is that you present a value on the Data In line (either H or L), and an address (binary 0 through 7) on the three Address lines. When the Write Enable line is brought high, the demultiplexer passes that signal on to one of the eight D flops, which then activates and sets its output Q to the Data In value. That value is now stored at the specified address. Meanwhile, the Data Out line continually shows the value stored at the D flop identified by the address lines. Real memory chips use this basic scheme, but with many more memory locations. The KM6264AL (Fig. 10.6(a)) is an 8k×8 SRAM chip, meaning that it can store up to 8192 (= 213 ) ‘words’, where each word consists of 8 bits in parallel. (For comparison, the circuit of Fig. 10.5 shows a 8 × 1 RAM, with 8 words of 1 bit each.) The pin out diagram is shown in Fig. 10.6(a). Instead of having separate Data In and Data Out lines, here there are eight data lines Dn which function as outputs when R/W is high (you are Reading data from memory), and as inputs when R/W is low (you are Writing to memory). Thirteen address lines An specify the location in memory to read from or write to. The OE signal (“not output enable”) must be low to activate the data lines at all, otherwise they are in the ‘off’ state of three-state logic. The CS1 and CS2 pins can be used to put the chip in a standby 72 10.4 RAM 10 FLIP-FLOPS, MEMORY, AND STATE MACHINES (8 D-flops) D Data In Q en Write Enable Q 8:1 MUX 1:8 DEMUX D en D Data Out Q Address en Figure 10.5: Schematic of how random access memory works. mode where data is retained but power consumption is minimal. We will not be using any of these features, so you can directly wire OE = L, CS1 = L, and CS2 = H. To demonstrate storing and retrieving a signal, wire up the circuit of Fig. 10.7. A debounced switch from your MC14490 sets R/W . The switch also controls a 74HCT125 three-state buffer (Fig. 10.6(b)). Recall here that when the OE signals are high, the buffer outputs are in the off state, so that the display lines are controlled by the 6264 chip in Read mode. When the EN s are low, the buffer outputs equal the inputs so that data can be input to the chip in Write mode. For simplicity, we will only use four bits for the data lines and addresses, even though the chip could accommodate up to eight and thirteen, respectively. Wire the unused address pins A4 through A12 to ground. 27 3 26 4 25 5 24 6 7 8 9 23 22 21 20 19 10 11 18 12 17 13 16 14 15 Vcc R/W CS2 A8 A9 A11 OE A10 CS1 D7 D6 D5 D4 D3 OE1 A1 Q1 OE2 A2 Q2 GND 1 14 2 13 3 4 5 12 11 10 6 9 7 8 (a) (b) Vcc OE4 A4 Q4 OE3 A3 Q3 OE D0 D1 D2 D3 D4 D5 D6 D7 GND 1 20 2 19 3 18 4 5 6 7 74HCT574 28 2 74HCT125 1 KM6264AL NC A12 A7 A6 A5 A4 A3 A2 A1 A0 D0 D1 D2 GND 17 16 15 14 8 13 9 12 10 11 Vcc Q0 Q1 Q2 Q3 Q4 Q5 Q6 Q7 C (c) Figure 10.6: (a) Pin outs for the KM6264AL memory chip. (b) Pin outs for the 74HCT125 quad buffer. (c) Pin outs for the 74HCT574 octal D-flop register, to be used in the next section. 73 10.4 RAM 10 FLIP-FLOPS, MEMORY, AND STATE MACHINES DIO 8-11 (display) KM6264AL 74HCT125 DIO 0-3 (data) A1 Q1 D0 A0 A2 Q2 D1 A1 A3 Q3 D2 A2 A4 Q4 D3 A3 DIO 4-7 (address) MC14490 OE1 OE2 OE3 OE4 R/W CS2 In1 R/W Out1 +5 V CS1 OE Figure 10.7: Circuit allowing storage and retrieval from random access memory To test the circuit, follow this procedure: First, set R/W low, so that you can write data to the memory. Set the address bits (DIO 4–7) to 0000, and vary each of the data bits (DIO 0–3). When you change the state of a data bit, the corresponding monitor bit (DIO 8–11) should follow it. If it doesn’t, then recheck your wiring. Once this works, enter a pattern of your choice in the data bits and make a note of it. Set the R/W switch high. Now when you change the data bits, the monitors bits should remain fixed in the pattern you saved. Finally, change the address bits to 0001, and set R/W low again. Load a different bit pattern into the data and save it by switching R/W high. Now if you go back to address 0000, the first bit pattern you saved should be displayed, while address 0001 displays the second. After this is working correctly, write several patterns into several different addresses and verify that you can retrieve them without error. Record your stored data and addresses in your report. If you do observe any retrieval errors, note them. What data do you observe at addresses where you have not previously stored anything? 74 10.5 Memory-Based State Machine 10 FLIP-FLOPS, MEMORY, AND STATE MACHINES n n n n Figure 10.8: A programmable state machine, comparable to Fig. 10.2(a). 10.5 Memory-Based State Machine A computer processor is, at its core, what you get when you combine a state machine with memory. The state machine works as in Fig. 10.2, but instead of using combinatorial logic to generate the next state from the current one, you simply look the next state up in memory. Figure 10.8 illustrates the idea. Suppose you require a state machine that proceeds through states A → B → C → . . ., where each state represents a specific pattern of N bits. Further, assume that upon power up, the output of the register in Fig. 10.8 initializes to state 0. Then program the memory so that bit pattern A is stored at address 0, pattern B is stored at address A, pattern C is stored at address B, and so forth. The data from the memory is fed back to the address through the D-flop register, which is controlled by a clock. When the circuit is turned on, the register starts in state 0, which is the address presented to the memory. The memory data outputs therefore start in state A, the first state of the desired sequence. When a clock transition arrives, pattern A is transferred to the address of the memory, so the data output changes to the pattern stored there, which is B. At the next clock transition, the address proceeds to B and the data to C. In this way, the entire state sequence is mapped out. We shall implement a simple version of this scheme, using the circuit of Fig. 10.9. To avoid needing too many wires, it uses just two bits for the data and address. The 74HCT574 chip (Fig. 10.6(c)) serves as the register, and is clocked by the Sync output of the function generator running at 1 Hz. It features an enable pin which can be used to turn its outputs off. Note that the CSS and OE inputs of the 6264 chip must be wired as in Fig. 10.7. The unused address inputs A2–A12 must all be wired to ground. The circuit uses two switches to control the operational mode. When the Program and Run signals are both low, the data and address buffers are enabled, the register is disabled, and the memory chip is in write mode. This allows the memory to be programmed, just like you did in the previous section. When the Program signal is high and Run is low, the data buffer is disabled and the memory is in read mode, but the address buffer and register still allow manual control of the address bits. This lets you check the stored data to make sure it is correct; think of this as “debugging” mode. 75 10.5 Memory-Based State Machine 10 FLIP-FLOPS, MEMORY, AND STATE MACHINES 74HCT574 Data Out (DIO 8,9) Program Data In (DIO 0, 1) Q0 D1 Q1 OE C SYNC KM6264AL 74HCT125 MC14490 D0 A1 Q1 D0 A0 A2 Q2 D1 A1 OE1 In1 Out1 OE2 R/W Address In (DIO 4, 5) Run In2 Out2 Address Out (DIO 12, 13) A3 A4 OE3 Q3 OE4 Q4 74HC04 Figure 10.9: Circuit for memory-based state machine. Finally, when Program and Run are both high, the register provides the memory address and the state machine is running. Why do you need to avoid setting Program low and Run high at the same time? As shown in the circuit, you don’t need any pull up resistors or LEDs on the control switches. The LEDs can again be helpful, however, so feel free to wire them up as in Fig. 10.4 if you find yourself getting confused about what mode the circuit is in. To test the circuit, load the following data into the memory: A0 A1 D0 D1 0 0 1 0 0 1 0 0 1 1 0 0 1 0 0 1 Use the debugging mode to check that the values are correct, and then switch to Run mode. The outputs should cycle through the same states as the divide-by-three circuit you built earlier. Describe your observations in your report. Of course, this circuit is much more flexible than the previous one. Devise a different state sequence of your own and run it. Describe the sequence in your report, and again note your observations. 76 11 COUNTERS AND OSCILLATORS 11 Counters and Oscillators Though specialized, the counter is one of the most likely digital circuits that you will use. We will see how typical counters work, and also how to interface data with an LED display. Counters and many other circuits often require a clock as well, and we will discuss two types of oscillator circuits that can serve this purpose. This lab will require one day. Reading: HH sections 8.03, 8.25, 5.14, 5.19 (pgs. 473–478, 524–525, 286–291, 300-303) 11.1 Binary Counter The 74193 chip is a typical 4-bit binary counter. It has several useful features: it can count up or down, it can be initialized to an arbitary value, and it has outputs to faciliate cascading multiple chips. Figure 11.1 shows the pin designations, with the following descriptions: Vcc, Ground: Supply voltages as usual. Qi : Output bit i. Bit A is the least significant. Up: Increments counter output by one when a rising edge is received. Down: Decrements counter output by one when a rising edge is received. Clear: When high, forces all output low. Load: When low, each output Qi is set to the value at input Di . Carry: Gives rising edge when output wraps from 1111 to 0000 while counting up. Borrow: Gives rising edge when output wraps from 0000 to 1111 while counting down. Note that a trigger input (Up or Down) that is not being used must be held in the high state. We won’t be using the Di inputs, but they should be tied to fixed values to to avoid generating errors. The Load input should be tied high. Wire up the chip with Clear tied to ground and the Down trigger tied to 5 V. Drive the Up trigger with the Sync pulse from your function generator, with a frequency of 1 Hz. Monitor the outputs Qi with channels 0-3 of the digital reader, and verify that they count up at the expected rate. Drive the Down trigger instead and verify that the output counts down. B 1 16 B 2 15 A 3 14 4 13 5 12 C 6 11 D 7 10 C 8 9 D A Figure 11.1: Pin designations for 74193 4-bit binary counter. 77 11.2 LED Display 11 COUNTERS AND OSCILLATORS Note that if you include the trigger signal itself as data, you really have five bits of counting capacity. If more capacity is needed, it is easy to cascade multiple chips. Put your counter back into the upward counting mode. Then get a second 74193 and wire it up like the first, but take the Up trigger from the Carry output of the first chip. Monitor the four new outputs on channels 4-7 of the digital reader. Do the eight output bits correctly count from 0 to 255? 11.2 LED Display Watching the counter output on the Digital Reader is neither satisfying nor practical. Let us instead display the result on an LED numerical display. The HP 5082-7340 display is convenient, because it has built in logic and drivers to convert a binary number to the appropriate combination of illuminated LED bars. It displays one digit in hexadecimal notation (4 bits), so you will need two displays. The pinouts for the 5082 are shown in Fig. 11.2. Here In1 refers to the ones-place bit, In2 refers to the twos-place bit, etc. The Latch input causes the display to hold its current value while the input is high. The Blank input causes the display to go dark while the input is high. For our purpose, they should both be tied low. Wire up both displays, using the four bits from the first counter to drive one and the four bits from the second counter to drive the other. When you run the counters, do the displays properly increment from 00 to FF? Try increasing the frequency of the clock signal. How fast can it go so that you can still tell that the numbers are counting correctly? (This has more to do with your eyes than the circuit, but it is still a useful number to know when setting up a display.) 8 7 6 5 1 2 3 4 In2 In4 In8 Blank Bottom View 1 2 3 4 8 7 6 5 In1 Vcc GND Latch Top View Figure 11.2: Pin designations for the HP 5082-7340 LED hexadecimal display. Note the identifier dot on the bottom of the package. 11.3 Binary-Coded Decimal Of course, people don’t usually work in hexadecimal notation. When interfacing with humans, the normal practice is to use the binary-coded decimal (BCD) convention. Here counting is done in base ten, but the numbers are stored in binary representation. A 4-bit BCD counter’s output would thus go: 78 11.4 Timer 11 COUNTERS AND OSCILLATORS 0000 (0) 0001 (1) 0010 (2) 0011 (3) 0100 (4) 0101 (5) 0110 (6) 0111 (7) 1000 (8) 1001 (9) 0000 (0) etc The four bits are not used as efficiently as in a binary counter, but in many situations bits are cheap. When you need to convert binary data to BCD, you can use chips like the 74184/74185. (The ’184 converts BCD to binary, and the ’185 converts binary to BCD.) For small circuits, however, it is more likely to be convenient to simply work in BCD throughout. For instance, the 74192 is a BCD counter that is pin-compatable with the 74193. Try simply replacing both ’193 chips with ’192s. Does your display now count in decimal? Why you don’t need to change the display chip too? If you were storing data in a RAM chip, would you need to know whether it was binary or BCD? 11.4 Timer So far we have been using the function generator signal for our clock, but if you were building a real circuit, you would not typically want to rely on an external signal. There exist a variety of ways to generate an oscillating signal of your own. One of the most convenient is the 7555 timer chip, shown in Fig. 11.3. The core logic is shown in part (b). Here the op amps are serving as comparators, which we will see more of in the next lab. Since there is no negative feedback, the op amp output simply rails high (5 V) or low (0 V) depending on whether the positive or negative input signal is higher. To operate as an oscillator, the 7555 is wired as in part (c). Also, the Reset signal must be tied high. The connection from the output back to the Trig and Threshold inputs causes the circuit to oscillate, at a theoretical frequency (in Hz) of 0.7/RC. You will get to work through this calculation yourself in a homework assignment. Wire up a 7555 chip, using a 200 pF capacitor and a 100 kΩ resistor. Verify that the output oscillates and compare its frequency to the expected value. You should measure R and C to make an accurate comparison. Replace the resistor with a 100k pot. What is the maximum frequency the circuit can produce? Choose a resistor/capacitor pair to give a signal at approximately 1 Hz, noting that the device manufacturer recommends using a larger R and a smaller C to minimize the output current required. Use your timer signal to drive your counter, so that you have a self-contained circuit. Measure your timer frequency by counting the number of oscillations in one minute, as determined by a watch or the wall clock. How accurate is the 0.7/RC formula? Two notes: First, the 7555 (and a handful of similar chips) are CMOS versions of the original NE555 TTL chip, which is still available. However, the 555 chip draws a substantial 79 11.5 Quartz Crystal Oscillators 11 COUNTERS AND OSCILLATORS Vcc R Threshold Gnd Trig Out Reset 1 8 2 7 3 6 4 5 Out Vcc Discharge Threshold Control Threshold Out Vout Trig C Reset Gnd Vcc 5V Trig (a) (b) (c) Figure 11.3: (a) Pin designations for 7555 timer. (b) Core logic functionality. Note that the Reset, Discharge, and Control signals are not shown; consult the datasheet for more information. (c) External wiring for operation as an oscillator. The Discharge and Control pins should be left open. current spike from the power supply when it switches, and it can be difficult to prevent that spike from affecting other parts of your circuit. The 7555 does not have this problem. Second, the 7555 and its relatives can do considerably more than just oscillate. It can be wired to act as a monostable multivibrator, the oscillation frequency can be modulated and the pulse width can be varied, among various other possibilities. If you have an electronics problem involving the generation of some kind of timed pulses, it would be worth looking through the application notes for the 555 chip for a solution. You will be using the counter and timer circuits in the next lab, so you should leave them set up on your breadboard. You’ll only need one counter chip and you won’t need the displays, so you can put them away to make room. 11.5 Quartz Crystal Oscillators It is difficult to achieve timing precision better than about 0.1% using the 7555 timer, or any other RC-based circuit, due to thermal drifts in the component values. When greater precision is required, the preferred solution is the quartz oscillator. This consists of a quartz crystal that is precisely cut so that it vibrates mechanically at a particular frequency. Quartz is a piezo-electric material, so when it is subject to strain, it generates an voltage at its surface and vice versa. It is therefore possible to drive the mechanical vibration with an electronic signal. The resulting system is somewhat complicated, but it works out that the crystal acts electronically as the circuit of Fig. 11.4(a). Such a circuit could of course be constructed electrically, but the advantage here is that the resonant frequency is stable to typically a few parts per million. Quartz crystal oscillators are used, for instance, to generate the timing in standard wristwatches, where 1 ppm corresponds to an error of about 1 second per week. 80 11.5 Quartz Crystal Oscillators 11 COUNTERS AND OSCILLATORS 74HC04 10M 100k Crystal 20 pF 20 pF (a) (b) Figure 11.4: (a) Equivalent electronic circuit for a quartz crystal. (b) Oscillator circuit based on a quartz crystal. The easiest way to generate an oscillating signal using a quartz crystal is with the circuit of Fig. 11.4(b). It is difficult to analyze this circuit quantitatively, but the basic principle can be understood as follows: the output of the first NOT gate is fed back to its input, making an unstable circuit that inherently tends to oscillate. By passing the feedback signal through the crystal, the circuit oscillation can drive and lock to the oscillation of the crystal. The arrangement of resistors and capacitors ensures that the instability is large enough to permit oscillation but small enough for the crystal to be effective. The second NOT gate serves as a buffer, to ensure that the output signal has standard logic levels and that loads on the circuit do not affect the oscillation. Wire up this circuit using a 74HC04 CMOS chip and a 1-MHz crystal. Also, filter the chip’s power supply pin with a 1 µF capacitor. Adjust the resistor to obtain oscillation. The signal will be clearer if you use a 10× scope probe. Measure the frequency using your oscilloscope, and compare to the expected value. (It is likely that any error you see is due to the scope, rather than the crystal.) When you are finished, clean up the crystal oscillator circuit, but again, leave a counter and timer out for next time. 81 12 CONVERTING BETWEEN DIGITAL AND ANALOG 12 Converting Between Digital and Analog For many applications, it is necessary to convert analog signals from a circuit or sensor to digital signals that can be manipulated by a computer, and vice versa. The simplest such tasks can be be performed by a comparator, but more generally, an ADC (analog-to-digital converter) or DAC (digital-to-analog converter) will be required. In this lab, we will explore a few aspects of these processes. This lab will require two days. Reading: HH sections 4.23–24, 9.15–16, 9.20–22 (pgs. 229–232, 612–618, 621–631) 12.1 Comparator A comparator is a high-gain differential amplifier, much like an op amp. It is not designed, however, to be operated with negative feedback. Instead, it provides a binary output, railing high if the input V+ > V− and low if V+ < V− . In this way, it can serve as a simple interface between analog and digital systems. The pin designations for the LM311 comparator are shown in Fig. 12.1(a). The Balance inputs can be used to adjust the offset voltage, just as in an op amp, while the Strobe input can be used to force the output low, regardless of the inputs. We will not be using either of these features and you can leave pins 5 and 6 unconnected. An interesting feature of the LM311, and most comparators, is that it has an “opencollector” output, represented schematically in 12.1(b). Here an external pull-up resistor must be used to complete the circuit. Typically, a value of 1 kΩ is a good compromise between high speed and low power dissipation. Note that the need for an output resistor is not always made perfectly clear in device datasheets, but the circuit will not function correctly without one. An advantage of the open-collector output scheme is seen in Fig. 12.1(c), where the pullup voltage can be varied. This lets the comparator serve as a very simple DAC: it converts 5V 0-10 V 10k V 1k 2 3 4 8 LM311 Gnd V+ VSupply - 1 7 6 5 Supply + Out Balance/Strobe Balance Vin Vout 10k (a) (b) (c) Figure 12.1: LM311 comparator. (a) Pin designations. (b) Open collector output configuration. (c) Circuit for lab. 82 12.2 Schmitt Trigger 12 CONVERTING BETWEEN DIGITAL AND ANALOG an input digital signal at standard logic levels to an output signal that switches between whatever voltage the analog circuit requires. Construct this circuit, taking Vin from a DIO pin, and using the variable power supply to generate the pull-up voltage. Use 15 V for the positive supply and ground for the negative supply. Pin 1 must also be connected to ground. Observe the output on the scope, and note how you get a digitally controlled version of the VPS voltage. How close to zero does the output get in its low state? Does the low value depend on the VPS voltage? Conversely, if you use 5 V for the pull-up voltage and the variable supply for the input, the circuit serves as a basic ADC. It provides a single-bit output that is low when the input is below the threshold and high when it is above the threshold. Modify the circuit of 12.1(c), accordingly, and observe the output with the Digital Reader while the input level is varied. You might notice that if you slowly step the input across the threshold, the reader display light flickers. When the input is very close to the threshold, even very small noise signals can cause the comparator state to change. To observe this effect more clearly, drive the input with a 500 Hz triangle wave from the function generator, using a 5 Vpp amplitude and a 2.5 V dc offset. Observe both the input and output with the scope. You should see the output switching as expected. Trigger the scope on the input signal, and adjust the trigger level so that the output switches just after the start of the trace. If you now zoom in on the output transition, you should be able to see multiple back-and-forth transitions between states, due to input noise. You can imagine that using a signal such as this as the trigger for a digital circuit would be problematic. Fortunately, the problem has a straightforward fix, the Schmitt trigger. 12.2 Schmitt Trigger A Schmitt trigger consists of a comparator combined with positive feedback, as seen in Fig. 12.2(a). The effect of the feedback is to create hysteresis in the switching behavior. If the circuit output is originally low, then the signal at V+ will be lower than Vin . Therefore, Vin must rise somewhat higher than Vref before the output will switch. Once the output is high, V+ will be higher than Vin , so Vin will have to drop somewhat lower than Vref before the output will switch low again. The difference between the two input thresholds is termed the hysteresis, as illustrated in Fig. 12.2(b). 5V Vout R2 1k R1 Vin 10k 5V Vout Vref 5V hysteresis LM311 10k 0V Vref (a) (b) Figure 12.2: (a) Schmitt trigger circuit. (b) Hysteresis curve. 83 Vin 12.3 The AD7569 DAC/ADC12 CONVERTING BETWEEN DIGITAL AND ANALOG This technique reduces the sensitivity to noise, since the input signal would need to fluctuate by an amount larger than the hysteresis in order to affect the output. Of course, hysteresis also reduces the accuracy of the comparator, since the output no longer precisely measures how Vin compares to Vref . Wire up the circuit using R1 = 10 kΩ and a 100 kΩ potentiometer for R2 , with the pot resistance initially maximum. Use the scope to observe the switching behavior with a 500 Hz triangle wave drive, and compare to what you observed before. Does the output now exhibit a single clean transition? To analyze the circuit and calculate the hysteresis, note that the R1 and R2 resistors form a voltage divider between the output and the input, so that V+ = R2 Vin + R1 Vout . R1 + R2 The output will change states when V+ = Vref . Solving for Vin in that condition gives R1 R1 Vin = 1 + Vref − Vout . R2 R2 If Vout varies by ∆Vout (here 5 V), the corresponding hysteresis ∆Vin will be ∆Vin = R1 ∆Vout . R2 Note this analysis assumes that the output pullup resistor is small compared to R1 + R2 , so that the voltage drop across it is not significant. To measure the the hysteresis in your circuit, you can use the oscilloscope’s XY mode. In this mode, the horizontal sweep is controlled by the Ch 1 signal, rather than a temporal ramp. This allows the scope to diplay the Ch 2 signal as a function of the Ch 1 signal instead of as a function of time. Attach your function generator signal to the scope Ch 1, and the circuit output to Ch 2. Set the trigger source to Ch 1, but display only Ch 2. Then put the scope in XY mode by depressing both the “B” and “Alt” buttons near the cursor control knob. Set the scope to display Ch 2 only. Finally, turn the input signal frequency up to 10 kHz. You should now see the hysteresis curve on the scope, with a noticeable difference between where the output signal drops and rises. The horizontal separation of these points gives ∆Vin . Measure it, and compare to the above formula for your resistor values. (Note that you’ll have to display Ch 1 to see what voltage scale it is set at.) Vary the pot, and describe how the hysteresis responds. When designing a Schmitt trigger, you would set the hysteresis based on the amount of noise in the input signal. Integrated Schmitt triggers circuits are also available, such as the 7414 hex inverter. The nominal hysteresis level for the 7414 is 0.8 V. Once you have completed this section, disassemble the comparator circuit and put it away. 12.3 The AD7569 DAC/ADC When more than one bit of A/D conversion is needed, it is normally best to use an appropriate IC chip. You can choose from a variety of chips using a variety of methods. To give you a 84 12.4 Negative Supply 12 CONVERTING BETWEEN DIGITAL AND ANALOG R2 + + 1 uF 1 uF R1 Adj -15 V Out Vout (a) Out Adj In In (b) Figure 12.3: LM337 negative voltage regulator. (a) Pin designations. (b) Wiring diagram. little familiarity with the topic, we will examine one general purpose chip here, the AD7569 from Analog Devices. The AD7569 is a complicated device. It contains both a DAC and ADC, with 8 bits precision each. The ADC uses the successive approximation register technique. The chip also features a variety of control signals designed to allow flexible interfacing with different systems. A datasheet for the device will be provided to each group, and you should consult it for reference. Note that the datasheet also describes the AD7669, which we are not using. A few things to look at now: Page 1: The functional block diagram gives an overview of what the chip does. Note that the data lines DB0. . . DB7 form a bus that serves as the output for the ADC and the input for the DAC, depending on the control signals applied. Page 6: Pin designations. We have the DIP configuration. Some paper labels with the pin numbers are available that you can tape to the top of the chip, to avoid pin counting errors. Page 7: Pin function descriptions. Note that there are three different grounds provided. In precise work, it would be desirable to keep the digital and analog grounds separate, to avoid putting digital noise on your analog signal. We shall not worry about that here, and just tie all the grounds together. Note also that the CS pin is not described very well. When this pin is high, the data lines are set to the ‘off’ state of three-state logic. This allows the data bus to be shared with other devices. Since we have only one device to worry about, we will keep CS tied low. Page 10–12: The Digital Interface section explains how the DAC and ADC are controlled by the digital signals. This is the key information that explains how to make the chip work. Skim through it now, and refer back to it when constructing the circuits below. Page 15: Unipolar vs Bipolar operation. We will be using bipolar operation, so make sure you understand Table V. This is called two’s-complement encoding, and is the standard way to represent negative values in binary. 12.4 Negative Supply For bipolar operation, the AD7569 requires supply voltages of ±5 V. Our breadboards supply +5 V, but not -5 V. (We could use the variable power supply, but we will want to use that as a signal source.) We can conveniently derive -5 V from our -15 V supply using an LM337 85 12.5 DAC 12 CONVERTING BETWEEN DIGITAL AND ANALOG negative voltage regulator. This device and its wiring diagram are shown in Fig. 12.3. It produces an output voltage R2 Vout = (−1.25 Volts) × 1 + R1 from an input voltage more negative than this. R1 should be around 100 Ω. Obtain a chip and wire up the circuit to produce an output voltage close to -5 V. Record the voltage you obtain. Note that there is a positive voltage version of this device, the LM317. Voltage regulators provide a simple and convenient way to generate various supply voltages from a single source. 12.5 DAC We shall first use the AD7569 to implement a simple DAC. Obtain a chip and wire the supply voltages, noting that VDD is positive and VSS is negative. (The notation refers to the drain and source of a FET.) Wire all three grounds to a common ground, tie CS low, tie Range high, and tie Reset high. We won’t be changing any of these settings. To operate as a DAC, tie Read high, and ST low. Whenever an upward transition ↑ is applied to the WR input, the chip will read the eight data lines, convert them to an analog voltage, and output that voltage on the Vout pin. To start, use a DIP switch to control the WR input. Tie the pin to 5 V through a 1 kΩ resistor, and also to ground through a switch. We don’t need to worry about debouncing the switch here, because we don’t mind if the chip performs the DAC conversion several times whenever we flip the switch. Start with the switch closed (so WR is low). Take the DB0–7 lines (here acting as inputs) from the DIO pins, which will be controlled by the Digital Writer tool. Monitor the output Vout with your scope and a voltmeter. Power up the circuit, and set the DIO signals to all zeros. Switch WR high and then low again. Does the output voltage go to zero? Try several different digital inputs, and verify that that output voltage responds appropriately in each case. Make a table in your report of the signals you applied and the resulting outputs. Be sure to include some negative values in your exploration. What is the minimum step size for the output voltage? More often, the inputs for a DAC are generated electronically. As a simple example, set up a 74193 counter as in Lab 11. Drive its clock with the sync pulse from the function generator. The same signal can drive the WR pin of the AD7569. Use the four outputs of the counter to drive pins DB0–3 of the DAC, and set pins DB4–7 low. Observe the output on the scope. You should see a sawtooth ramp, and at higher speeds, the discrete output levels should be evident. What do you observe at very high clock speeds, for instance 500 kHz to 5 MHz? The DAC is specified to have a 1 µs settling time. Are your observations consistent with that? 12.6 ADC Converting from analog to digital is a little more complicated because there are two different modes of operation. In Mode 1, the conversion timing is controlled with the RD and ST pins, while in Mode 2, only the RD signal is used and the timing is more automatic. 86 12.7 Nyquist Sampling Theorem 12 CONVERTING BETWEEN DIGITAL AND ANALOG Either mode requires a clock signal to drive the successive approximation register circuitry. This can be generated internally, by tying a resistor and capacitor in parallel from the Clk pin to ground. The recommended values (see Fig. 21 on page 15 of the datasheet) are R = 7.3 kΩ and C = 68 pF. If these values aren’t available, try to choose a similar pair with about the same RC. Mode 1 is convenient for manual operation. Connect RD and ST to a pair of DIO pins that are set low. Tie WR low. Apply a voltage to Vin from the variable power supply, but do not exceed ±2.5 V. Monitor all eight DB pins on DIO channels with the Digital Reader. Monitor the input level with a voltmeter. To make a conversion, first toggle RD high, which temporarily disables the DB pins. Then apply a rising edge to ST, which initiates the conversion. Set ST low again, and then set RD low again to display the new data. Try a handful of input levels, both positive and negative. Again, make a table of the results in your report, and make sure they are what you expect. How repeatable are the results, and what does the repeatability indicate about the noise in the circuit? To make a more automatic measurement, let us digitize a sine wave. Here it will be more convenient to use Mode 2 of the ADC. If ST is tied high, then a conversion will start whenever RD goes low. After the conversion, the new values will automatically be updated to the outputs. See for instance Figure 12 in the datasheet. To drive RD, we can use a DIO pin with the digital writer in the “Alternating 1/0’s” configuration, in which the bits automatically toggle at about 7 Hz. Drive the input with a 0.2 Hz sine wave, with 1 Vpp amplitude and 0.6 V offset. Observe the digital outputs on the Digital Reader. The output changes too fast to track directly, but as the input signal oscillates up and down, you should see the bit pattern shift from the left to the right. If we wanted to take the trouble, it would be simple to store such data into a RAM chip for later retrieval. 12.7 Nyquist Sampling Theorem When converting between digital and analog values, the Nyquist Sampling Theorem provides important guidance on the relation between signal bandwidth and sampling frequency. It states that in order to accurately encode a signal of frequency f , the wave form must be sampled at a frequency of at least 2f . Thus if your signal contains frequency components up to 10 kHz, your ADC/DAC system must run at at least 20 kHz. If the sampling rate is slower than this, the digitized wave form will be inaccurate. We can use the AD7569 chip to see this effect in action. We will start with an analog sine wave and digitize it. If the sample rate is too low, Nyquist indicates that our digitized version will be erroneous. It is hard to tell this by looking at the digital values, however, so we will instead try to recreate the analog signal with the ADC. If there are no errors, the initial and final wave forms should be similar. We shall observe what happens when this is not the case. The 7 Hz trigger signal from the Digital Writer is to slow to be convenient here. So first, build a circuit to generate your own trigger using a 7555 timer chip, as in Lab 11. Pick a resistor/capacitor pair to give a clock frequency between 50 kHz and 100 kHz. Measure this frequency using your scope. 87 12.7 Nyquist Sampling Theorem 12 CONVERTING BETWEEN DIGITAL AND ANALOG Using the DAC and ADC together is relatively straightforward. The ADC puts its results on the data bus shortly after the RD signal drops low, and holds them there until the signal goes high. The DAC takes it’s values from the bus when the WR signal goes high. So if we wire RD and WR together, then the DAC will always have the current value available when needed. The data pins can be simply left open. This scheme is not really ideal because it relies on a logic race. In practice, the DAC needs to have its inputs held on the bus for about 10 ns after the WR signal rises, because it takes that long to transfer the data into its internal register. On the other hand, the ADC takes about 10 ns to clear the bus after the RD signal goes high. So our scheme will only work if the clear time of the ADC is a little longer than the hold time of the DAC. In fact, it is. A better design would not leave this to chance, but would instead delay the RD signal slightly by, for instance, passing it through two inverters before applying it to the chip. For simplicity we won’t bother with that here. To implement this, apply the signal from your 7555 timer chip to both the RD and WR pins. (Make sure the ST pin is still held high.) Drive the ADC input with a sine wave with 1 Vpp amplitude, and monitor both the input and the output on the scope. Start with an input frequency of about 1 kHz. You should see the output follows the input nicely. To understand the Nyquist phenomenon, start by observing the output wave only, using it as your trigger source. This is appropriate, because you would not normally have the input signal available when you are later trying to reconstruct it from the digitized data. (For instance, if you digitally recorded a music concert, you would not have the original analog sound signal available when you later tried to play back your recording.) Observe and describe the signal as you gradually increase the input wave frequency. The signals will probably be clearest if you adjust the trigger level to near the top (or bottom) of the wave form. You can locate these points as the edges of the range over which the scope triggers. Does the signal still look like a sine wave as you approach and then exceed half the timer frequency? What happens if the input frequency is close to the timer frequency? To help see what is going on, display the input and output signals together on the scope. Keep using the output signal for the trigger, however. Sweep over the input frequencies again. It should be clear that near the Nyquist frequency, the samples occur at basically random times within the wave form, leading to a jumbled output signal. Can you explain why the output appears as it does when the input frequency is near the timer frequency? Finally, change the scope to trigger on the input signal. In this configuration, does anything special seem to happen as you pass through the Nyquist frequency? By using the input signal as a reference, the scope is able to sort the jumbled output signal levels appropriately, so that it looks like the output is more or less correct. What do you observe at the timer frequency now? The fact that an under-sampled high frequency signal is reconstructed at a lower frequency is called aliasing. It can be a source of confusion, since it causes spurious signals to occur at frequencies you don’t expect. The best solution is to always use a low-pass filter on the input to an ADC so that signal components above the Nyquist frequency are attenuated away rather than aliased. Once you have completed the lab, clean up all the components and your station. 88 13 MICROCONTROLLERS 13 Microcontrollers A microcontroller is a tiny computer system, complete with microprocessor, memory, and a variety of input/output channels including analog converters. The microcontroller is programmed using a high-level language like C or Basic, via a connection to a standard desktop or laptop computer. Microcontrollers are relatively inexpensive and can be a good solution to an electronics problem that would otherwise involve constructing a complex circuit. This lab will require two days. Reading: HH section 10.01 (pgs. 673–678), mbed “tour” http://mbed.org/handbook/Tour 13.1 The mbed Microcontroller There are a wide variety of microcontrollers available, with many different programming requirements. The mbed controller we will be exploring is based on the NXP LPC1768 chip. The emphasis of the mbed system is on ease of use. The controller attaches to a standard breadboard to provide electronic access, it receives power and programming via a USB cable to a host computer, and programs are written and compiled in a simple web-based interface. To set up the controller, carefully install it into your ELVIS breadboard. It fits best if you use two adjacent breadboard columns (from socket B to socket I), rather than straddling a bus column (the +/− connections.) The USB port should be at the top. The mbed board is large and somewhat delicate, so be careful to apply gentle and even pressure while inserting it. Plug the USB cable into the port on the mbed board and one of the ports on the side of your computer monitor. The Status LED on the mbed board should illuminate, another LED should blink, and your computer should interpret the controller as a flash drive (typically E:). To load a program into the controller, it is simply copied or saved onto the flash drive. When the controller is connected, or when the Reset button in the center of the board is pushed, the controller automatically runs the newest program in its memory. The E: drive should currently contain just one program, “HelloWorld LPC1768”, which is causing the LED to flash. The other file in the drive, MBED.HTM, can be used to set up an account for the web-based compiler. In this case, a generic account for your station has already been set up. To access it, point your web browser to http://mbed.org/, and go to the Login link at the top right. If your station number is X, enter the user name UVA3150X and password physics*X. After logging in, click on the Compiler link, also at the top right. This takes you to the compiler application. The mbed controller is programmed in C++, but the programs we will be writing won’t involve any complicated language elements. The Program Workspace panel at the left shows the programs you have written. Right now, there should only be one, HelloWorld. Click on it and go to the main.cpp file. This shows the program listing, which should be fairly self-explanatory. Modify the code to use LED2 rather than LED1, and change the wait times to make the LED blink twice as fast. Compile the new code by pressing the Compile button in the center of the toolbar, and save the resulting file to the E: drive with the same name. Once compilation is complete and the 89 13.2 Digital Inputs and Outputs 13 MICROCONTROLLERS Status light returns to steady illumination, push the Reset button. Describe the results in your report. Note that the DigitalOut variable type and the wait command are not standard C++, but are included as part of the mbed library. The various special mbed functions are described in the Handbook section of the website. In a separate browser tab, find the Handbook and look up the wait command. What are the units of the wait time? The myled variable is particularly interesting. It acts, in many ways, as a function itself. When you assign a value to myled, you are really calling a routine in the mbed library, which directs the hardware on the chip to set the referenced LED appropriately. If you haven’t seen this kind of thing before, it is an example of object-oriented programming. Properly, myled is an object of the class DigitalOut, and consists of a set of functions and variables that work together to implement the LED control. When done correctly, this type of programming is transparent and easy to use, as you have hopefully seen here. 13.2 Digital Inputs and Outputs The HelloWorld program shows one type of digital output, the LED displays. More generally, most of the controller pins can be used as either digital inputs or outputs. The possible uses for the various pins are summarized on the small card included in the controller box, or online under http://mbed.org/handbook/mbed-NXP-LPC1768. All of the blue pin numbers can be used as either digital inputs or outputs. To configure pin 30 as an output, add the line DigitalOut q(p30); to the ‘preamble’ section immediately prior to the int main declaration. This defines a variable q which is bound to the the stated pin. You can read about the DigitalOut declaration in the Handbook. In the main function of the program, replace the LED code with a routine to toggle q: q = 0; while(1) { q = !q; wait(5e-5); } Download and run the code, and observe the output of pin 30 on your scope. Use pin 1 as ground, and attach it to the ELVIS ground as well. Do you observe a 10 kHz square wave as expected? What voltage level is used for a high signal? Remove the wait statement so that the signal toggles as fast as possible, and observe it with a 10× scope probe. What is the resulting output period? How does it compare to the maximum speed of a typical TTL gate chip (as you measured in Lab 9)? In general, the main limitation of microcontrollers compared to conventional circuits is reduced speed. To configure a pin as a digital input, add the line DigitalIn fgen(p29); 90 13.2 Digital Inputs and Outputs 13 MICROCONTROLLERS to your preamble. Implement a NOT gate with the simple code while(1) { q = !fgen; } Hook pin 29 up to the Sync output of your function generator, and observe both it and pin 30 on your scope. While you run the program, does pin 30 act as the inversion of pin 29? For a more complicated example, use the wait function to implement a triggered pulse generator. The code q = 0; while(fgen==1) {}; while(fgen==0) {}; q = 1; wait(100e-6); q = 0; produces a 100 µs output pulse when a rising edge occurs at the input. Implement this code in an infinite loop, and observe the output when applying a 1 kHz input signal. Suppose instead that when a rising edge is detected, the output should stay low for 50 µs and then produce a pair of 20 µs pulses separated by a 10 µs delay. Modify your program to implement this and note your observations. Multiple input and output bits can be controlled together with the BusIn and BusOut variables, which are again described in the Handbook. Add such a variable with the declaration BusIn nibble(p22,p23,p24,p25); (A ‘nibble’ is conventionally 4 bits, or half a byte.) By using the command wait(nibble*1e-5); you can have the duration of the delay following the trigger set to be 10 µs times the decimal value of nibble. For example, if nibble = 1001bin = 9dec , the output will stay low for 90 µs after a rising edge is detected, and then produce the pair of 20 µs pulses. Attach pins 22 through 25 to the ELVIS Digital Writer outputs, and measure the delay vs. set value for a few cases (including nibble = 0). Which of the four nibble pins is the most significant bit, and which is the least significant? This should give you a taste of the capabilities of the microcontroller for digital logic. As long as the speed is sufficient, microcontrollers make digital design fairly trivial. Of course, your ‘HelloWorld’ program no longer has a very appropriate name. In the Compiler, right click on the program and change its name to ‘DigitalFun’ instead. Your online programs will be graded along with your lab report, so make sure to save everything when instructed, and leave your programs in a working state. Comments in the program files are not required, but would be useful in places where you did anything interesting or tricky. 91 13.3 Arbitrary Waveform Generator 13.3 13 MICROCONTROLLERS Arbitrary Waveform Generator The mbed microcontroller is also useful for analog applications. As a first example, you will implement an arbitrary waveform generator. This is a device like a function generator, except that the output waveform can be specified as desired. It can be useful for controlling servomechanisms and other complicated processes. Start by creating a new program. Click the New button in the toolbar of the Compiler. Name the new program ‘Waveform.’ When you go to the main.cpp listing, you will notice that the HelloWorld program is provided as a default skeleton to start from. The first thing we will need for the waveform generator is a DAC. As the mbed summary card indicates, only one pin can be used for an analog output signal, pin 18. To configure that pin, add the line AnalogOut signal(p18); in the preamble section. This defines a variable signal which is bound to the DAC function of pin 18. You can read about the AnalogOut declaration in the Handbook. It works similarly to how the digital variables worked. For example, replace the contents of the main function with the line signal = 0.5; Compile and run your program, and monitor the voltage on pin 18 with your DMM. Again, use the GND pin as your ground reference. An AnalogOut variable can be assigned any floating-point value between 0 and 1, and produces a voltage output equal to the variable’s value times a reference voltage of 3.3 V. Check and record the DAC output for several values of signal. Does it behave as expected? How accurate is it? Is the smallest voltage increment you can produce consistent with the specified 10-bit resolution? For an arbitrary waveform generator, we wish to implement an output voltage V = f (t) for some specified function f of time t. This requires a way to track and determine the time more accurately that we can do with wait. The easiest way to achieve this is with the mbed Timer class. Declare a Timer object t by adding the line Timer t; to your progam’s preamble. Look up the Timer functions in the Handbook, and figure out how to start, reset, and read the timer. Here the output will be a periodic function, so introduce a floating point period variable that is assigned a value at the start of the program. To start, use a 1 ms period. A simple way to control the timing is with a while loop: t.reset(); while(t.read()<period) { signal = t.read()/period; /* The function f(t) */ } where here the signal is a simple sawtooth ramp. This method isn’t perfect since the actual period can vary by the time required for one output update, but this is acceptable when the 92 13.4 LCD Display 13 MICROCONTROLLERS period is long compared to the update time. Implement this scheme, using an infinite outer loop to repeat each period. For convenience, also implement a sync-type signal to serve as a scope trigger: Define pin 30 as a Digital Ouput object sync and toggle its value between high and low at the start of each period. Use this and monitor the DAC output on your scope. Once you have a working program, observe its performance for a range of periods. Does a period of 100 s seem to function correctly? (How can you measure this?) When you make the period short, on the order of 100 µs, you should be able to see discrete steps in the output on your scope corresponding to the finite DAC update time. How long is the update time? What is the discrepancy between the specified and actual waveform periods? Try some more complicated mathematical functions, bearing in mind that the signal value must be between zero and one. A list of functions available in the C math library can be found, for instance, at http://en.wikipedia.org/wiki/Math.h. Both the ‘Pre-C99’ and ‘C99’ functions are available. Craft a few interesting waveforms and note them in your report. For each waveform, find the output update time and deduce the amount of time required to perform the mathematical calculation. You should see that for complicated functions, the calculation time becomes a significant burden. Another interesting function is the random number generator rand(). Implement it using the code signal = rand()/(1.0*RAND_MAX); which produces a random value between zero and one. Run this code and note your observations. A device that produces a random signal like this is called a noise generator, and finds a variety of applications. Note that the calculation-time limit to the update speed can be remedied by precalculating the required values and storing them in an array. While running, the waveform generator can simply read the values from the array and thus run at its maximum rate. This technique can also be used to make the waveform period more precise. 13.4 LCD Display The AnalogOut and DigitalOut objects are two ways for the microcontroller to generate output, but text output is also often convenient. Such output can either be displayed on an electronic display module or transmitted to the host computer. We shall investigate the display module first. A typical LCD module is included in the mbed controller box. It is manufactured by Lumex, part number S01602DTR. It can display 2 lines of text with 16 characters per line, and is therefore commonly referred to as a 16 × 2 display. Functions for handling the display interferace are not built into the mbed compiler. However, a great variety of special-purpose libraries are available through the mbed ‘Cookbook,’ available through a link at the top of the mbed website. Go to the cookbook and find the Text LCD project by Simon Ford. Click on it to find a description. In order to use the TextLCD routines, they must first be imported into your project. Start by creating a new program on the compiler page, and call it ‘MyLCD.’ Click the Import button in the toolbar. Wait for the Programs tab to load, and then search for the TextLCD project by Simon Ford. Select it and click the Import button above the program 93 13.5 Voltmeter LCD pin 1 2 3 4 5 6 7–10 11 12 13 14 mbed pin GND Vu 1k resistor to GND p10 GND p12 no connection p14 p15 p16 p17 13 MICROCONTROLLERS Function Ground 5 V supply Contrast control Register Select R/W Enable Data Data Data Data Table 1: Pin connections for LCD module. The first column gives the LCD pin number, the second column gives the mbed pin, and the third column describes the function. list. This imports the TextLCD library into your program. To use it with your code, add the line #include "TextLCD.h" at the top of your program. We will modify the wiring setup slightly from that described on the web page. First, identify the pin numbers on the LCD module by looking at the back of the card. Numbers 1 and 14 indicate the corresponding pins. Insert the module into your breadboard and hook it up to the mbed controller as shown in Table 1. Given these pin connections, an LCD object must be declared with the parameters TextLCD lcd(p10, p12, p14, p15, p16, p17); Once this is complete, use the cookbook example to display a message on your LCD module. Note that you can use the newline character \n to extend your message across both lines. Convince yourself that the display works as claimed, and describe your observations in your report. 13.5 Voltmeter You can use the LCD display along with the microcontroller’s analog input capability to construct a simple digital voltmeter. Create a new program ‘Voltmeter’ and import the TextLCD code just as you did above. In the preamble to your program, declare an analog input channel using AnalogIn vin(p19); You can read about AnalogIn in the Handbook. It works much like the AnalogOut class you encountered above. In the main routine, set up an infinite loop: 94 13.6 Communication with PC 13 MICROCONTROLLERS while(1) { lcd.printf("V = %f\n\n",3.3*vin); wait(0.5); } (If you are unfamiliar with the printf command, you can find a description on Wikipedia.) This will continually display the measured voltage on the LCD. To test it, hook pin 19 input up to the ELVIS VPS positive supply and monitor it with your voltmeter. Bear in mind that maximum readable voltage is 3.3 V, and to avoid damage don’t let the input exceed 5 V. What do you observe on the LCD display? The mbed uses a 12 bit ADC, so the floating point value of vin should really be considered as a scaled integer. The range from 0 to 1 corresponds to 212 = 4096 different digital values. To display them directly, modify your code to lcd.printf("V = %f\n\n",4095*vin); (Why do you multiply by 4095 rather than 4096?) What do you observe when you run the program? It is useful to know how long it takes to acquire an ADC sample. Modify your program to determine this by looping over 10,000 samples and measuring the elapsed time with a timer. Don’t update the LCD during this loop, since that would add to the time required. At the end, display the elapsed time on the LCD module and calculate the time per measurement. You may have observed previously that your voltmeter readings were rather noisy. If you modify your program to average all 10,000 samples and display the mean value, are the fluctuations reduced? Leave the LCD display set up, you will use it again below. 13.6 Communication with PC If you want to acquire a stream of data and save it on a computer, the LCD display is not adequate. Instead, the microcontroller can communicate with a computer through a RS-232 connection. Here ‘RS-232’ is a simple serial communications protocol that most computers support. In the mbed system, it has been conveniently implemented through the USB cable, but in general it would require a separate cable hooked up to the computer’s serial port. To test the communication routines, create a new program called ‘Communicate.’ In the preamble, insert a declaration Serial pc(USBTX, USBRX); This establishes serial communication channel pc implemented through the USB connection. Writing to the channel is accomplished with the pc.printf() command and reading from it with pc.scanf(), which behave like the ordinary C functions. Once again, you can find more details in the Handbook. For now, simply add a line pc.printf("Hello World\n"); 95 13.7 Multi-Channel Analyzer 13 MICROCONTROLLERS to your program. You also need to set up your computer to listen to the serial channel. This can be done with a variety of terminal programs. Here we will use PuTTY. Locate PuTTY on your pc and run it. In the Session screen, select a Serial connection and enter COM3 for the serial line. Leave the connection speed at 9600 baud. Then go to the Terminal screen and select “Implicit CR in every LF,” “Implicit LF in every CR,” and “Local echo: Force on.” Press Open and a terminal screen should appear. When you run your program on the controller, does the message display on the TeraTerm terminal? To demonstrate communication from the pc to the controller, write a program that echos a line typed on the computer to the LCD display, using char text[16]; while(1) { pc.scanf("%s",text); lcd.printf("%s\n\n",text); } (You will of course need to set up a TextLCD object first.) Note that the LCD display does not automatically clear displayed characters, so if you write a long word followed by a short one, the end of the long word will still be present. This can be fixed by calling the lcd.cls() command prior to lcd.printf. Try writing a few messages, exploring the behavior produced by long words, spaces, back spaces, and other atypical characters. Describe your observations in your report. 13.7 Multi-Channel Analyzer The final microcontroller project that we will implement is a multi-channel analyzer. This is a type of sampling voltmeter, which obtains many values and produces a histogram of their distribution. For instance, the data in Fig. 13.1 shows the result of 10,000 measurements sorted into 100 bins. Each bin’s value shows the number of times that a measurement was within the corresponding voltage range. Multi-channel analyzers are most often useful for characterizing time-varying but non-periodic signals. Here, however, we will simply use our function generator as a signal source. You have seen already most the tools needed to write an MCA program on the microcontroller. Store the bin values in an array int counts[100]; which will need to be initialized to zeros using, for example for(n=0;n<100;++n) counts[n]=0; For the input, set up an AnalogIn object on pin 19. The main part of the program should be a loop over S samples, with a delay time T between each sample. To sort each sample into the correct bin, use d = floor(vin*100); ++counts[d]; 96 13.8 Wrap Up 13 MICROCONTROLLERS 600 Number of Occurences 500 400 300 200 100 0 0 0.33 0.66 0.99 1.32 1.65 1.98 2.31 2.64 2.97 3.3 Signal level (V) Figure 13.1: Data produced by a multichannel analyzer. Once all the samples are accumulated, print out all 100 bin values to the serial channel. It is helpful to precede the output by a header line so that you can find the begining of the data stream on the terminal. For futher convenience, turn on an LED while the program is acquiring data and turn it off when acquistion is done. To test your program, set the number of samples to 100 and the sample time to 0.7 ms. If you run it with no input connected, you should find most of the counts in the lowest few bins. Then take the input from your function generator, running a 1 Vpp sine wave at 100 Hz with a 1 V offset. Now the counts should be spread over the mid-range bins. When everything seems to be working, increase the number of samples to 10000. On your computer, copy and paste the output values into your report and make a column graph as in Fig. 13.1. Compare the amplitude distributions you observe for the function generator set to give a constant value, a sine wave, a triangle wave, and a square wave. Do the distibutions appear as you expect? How easy is it to distinguish the different wave forms? Does anything change if the input period is made to be a multiple of the sampling time? Would you expect anything to change? 13.8 Wrap Up Before finishing, make sure that all six of your programs are present in the online compiler directory: DigitalFun, Waveform, MyLCD, Voltmeter, Communicate, and MCA. To turn the mbed module off, just unplug the USB cable. Remove the LCD module, USB cable, and mbed card and put them back in the controller box. Be particularly careful when removing the mbed card to avoid stressing it. If necessary, ask the instructor for help. Since this is the final lab of the semester, make sure to clean up your station and put all electrical components away. 97 A EXCEL PLOTS A Excel Plots For your lab reports, you will need to prepare data plots using Excel. Here are the instructions for doing so: A.1 Creating a Chart 1. Use the mouse to select the data you want to plot. The data should be in columns, and the leftmost column will be taken as the x-axis. If the the data are not in adjacent columns, select one set of values at at time while holding down the Ctrl key. 2. Under the Insert menu, select Chart. For the chart type, normally select XY (Scatter) and then chose a subtybe depending on whether you want the plot to use lines, curves, or points. 3. Click Next, and under the Series tab, give your dataset a name. 4. Click Next, and give your chart a title and axis labels. 5. Click Finish, and your chart will appear. A.2 Modifying a Chart To add another dataset to a chart, right click on the chart area and select Source Data. Under the Series tab, click Add. Give the new dataset a name. Click in the X Values box and then select the x data on the worksheet using the mouse. Click in the Y Values box, delete the default “={1}” entry, and then select the y data on the worksheet. Click OK and the new data will be added. To change the title or axis labels, right click on the chart and select Chart Options. To modify the axis scales, double click on the axis you want to change. Under the Scale tab, you can change the axis range and switch between linear and log scales. Sometimes the data will lie on top of an axis, making it hard to click. You can also modify the axis using the Chart toolbar, which appears somewhere on the screen when a chart is selected. In the toolbar, select the axis you want to change and click the Format Axis button, which looks like a hand pointing at a piece of paper. To change the data marker style, double click on a data point. You can change the color or style, add error bars, and choose which dataset is plotted on top. Sometimes two data sets are on top of each other, and it is hard to select the one you want. You can also use the Chart toolbar: select the data series you want and click the Format Data Series icon. A.3 Fitting Data Excel provides some support for fitting data, which will occasionally be useful. With an existing chart selected, go to the Chart menu and select Add Trendline. A box comes up allowing you to select the type of fit. On the Options tab, you should normally select the “Display Equation on Chart” box. Click OK to close the box and add the fit. 98 A.4 Excel 2007 A.4 A EXCEL PLOTS Excel 2007 The lab computers use the 2003 version of Excel. If you are using a newer version on your own computer, the process is a little different. To create a chart, click on the Insert tab of the ribbon. The different chart types are listed in the Charts toolbar, and the subtypes form a drop down menu. When you select a chart, the Chart Tools tab appears in the ribbon, and displays the various things you can change. Adding a new dataset is done using the Select Data tool under the Design tab. Trendlines can be added via the Layout tab. 99