The Art of Electronics 3rd Edition PDF Free Download


Presentation Description

Download for free at, or copy/paste the link: ==== This book can be used for a full-year electronic circuit design course at the college level, with only a minimum mathematical prerequisite; namely, some acquaintance with trigonometric and exponential functions, and preferably a bit of differential calculus. ==== Tags: art of electronics, art of electronics 3rd edition pdf, art of electronics horowitz, horowitz and hill, the art of electronics 3rd edition, the art of electronics 3rd edition free download, The Art of Electronics 3rd Edition PDF Free Download, the art of electronics 3rd pdf, the art of electronics horowitz, the art of electronics third edition, the art of electronics third edition pdf


Presentation Transcript

slide 2:

The Art of Electronics Third Edition At long last here is the thoroughly revised and updated and long-anticipated third edition of the hugely successful The Art of Electronics. Widely accepted as the best single authoritative text and reference on electronic circuit design both analog and digital the first two editions were translated into eight languages and sold more than a million copies worldwide. The art of electronics is explained by stressing the methods actually used by circuit designers – a combination of some basic laws rules of thumb and a nonmathematical treatment that encourages understanding why and how a circuit works. Paul Horowitz is a Research Professor of Physics and of Electrical Engineering at Harvard University where in 1974 he originated the Laboratory Electronics course from which emerged The Art of Electronics. In addition to his work in circuit design and electronic instrumentation his research interests have included observational astrophysics x-ray and particle microscopy and optical interferometry. He is one of the pioneers of the search for intelligent life beyond Earth SETI. He is the author of some 200 scientific articles and reports has consulted widely for industry and government and is the designer of numerous scientific and photographic instruments. Winfield Hill is by inclination an electronics circuit-design guru. After dropping out of the Chemical Physics graduate program at Harvard University and obtaining an E.E. degree he began his engineering career at Harvard’s Electronics Design Center. After 7 years of learning electronics at Harvard he founded Sea Data Corporation where he spent 16 years designing instruments for Physical Oceanography. In 1988 he was recruited by Edwin Land to join the Rowland Institute for Science. The institute subsequently merged with Harvard University in 2003. As director of the institute’s Electronics Engineering Lab he has designed some 500 scientific instruments. Recent interests include high-voltage RF to 15 kV high-current pulsed electronics to 1200 A low-noise amplifiers to sub-nV and pA and MOSFET pulse generators.

slide 3:


slide 4:

FOUNDATIONS CHAPTER 1 1.1 Introduction The field of electronics is one of the great success stories of the 20th century. From the crude spark-gap transmitters and “cat’s-whisker” detectors at its beginning the first half- century brought an era of vacuum-tube electronics that de- veloped considerable sophistication and found ready ap- plication in areas such as communications navigation in- strumentation control and computation. The latter half- century brought “solid-state” electronics – first as discrete transistors then as magnificent arrays of them within “in- tegrated circuits” ICs – in a flood of stunning advances that shows no sign of abating. Compact and inexpensive consumer products now routinely contain many millions of transistors in VLSI very large-scale integration chips combined with elegant optoelectronics displays lasers and so on they can process sounds images and data and for example permit wireless networking and shirt-pocket access to the pooled capabilities of the Internet. Perhaps as noteworthy is the pleasant trend toward increased perfor- mance per dollar. 1 The cost of an electronic microcircuit routinely decreases to a fraction of its initial cost as the manufacturing process is perfected see Figure 10.87 for an example. In fact it is often the case that the panel con- trols and cabinet hardware of an instrument cost more than the electronics inside. On reading of these exciting new developments in elec- tronics you may get the impression that you should be able to construct powerful elegant yet inexpensive little gad- gets to do almost any conceivable task – all you need to know is how all these miracle devices work. If you’ve had that feeling this book is for you. In it we have attempted to convey the excitement and know-how of the subject of electronics. In this chapter we begin the study of the laws rules of thumb and tricks that constitute the art of electronics as we see it. It is necessary to begin at the beginning – with talk of voltage current power and the components that make up 1 A mid-century computer the IBM 650 cost 300000 weighed 2.7 tons and contained 126 lamps on its control panel in an amusing re- versal a contemporary energy-efficient lamp contains a computer of greater capability within its base and costs about 10. electronic circuits. Because you can’t touch see smell or hear electricity there will be a certain amount of abstrac- tion particularly in the first chapter as well as some de- pendence on such visualizing instruments as oscilloscopes and voltmeters. In many ways the first chapter is also the most mathematical in spite of our efforts to keep math- ematics to a minimum in order to foster a good intuitive understanding of circuit design and behavior. In this new edition we’ve included some intuition-aiding approximations that our students have found helpful. And by introducing one or two “active” components ahead of their time we’re able to jump directly into some applica- tions that are usually impossible in a traditional textbook “passive electronics” chapter this will keep things inter- esting and even exciting. Once we have considered the foundations of electron- ics we will quickly get into the active circuits amplifiers oscillators logic circuits etc. that make electronics the ex- citing field it is. The reader with some background in elec- tronics may wish to skip over this chapter since it assumes no prior knowledge of electronics. Further generalizations at this time would be pointless so let’s just dive right in. 1.2 Voltage current and resistance 1.2.1 Voltage and current There are two quantities that we like to keep track of in electronic circuits: voltage and current. These are usually changing with time otherwise nothing interesting is hap- pening. Voltage symbol V or sometimes E. Officially the volt- age between two points is the cost in energy work done required to move a unit of positive charge from the more negative point lower potential to the more positive point higher potential. Equivalently it is the energy released when a unit charge moves “downhill” from the higher potential to the lower. 2 V oltage is also called 2 These are the definitions but hardly the way circuit designers think of voltage. With time you’ll develop a good intuitive sense of what volt- age really is in an electronic circuit. Roughly very roughly speaking voltages are what you apply to cause currents to flow. 1

slide 5:

2 1.2. Voltage current and resistance Art of Electronics Third Edition potential difference or electromotive force EMF. The unit of measure is the volt with voltages usually ex- pressed in volts V kilovolts 1 kV 10 3 V millivolts 1 mV 10 −3 V or microvolts 1 μV10 −6 V see the box on prefixes. A joule J of work is done in mov- ing a coulomb C of charge through a potential differ- ence of 1 V . The coulomb is the unit of electric charge and it equals the charge of approximately 6×10 18 elec- trons. For reasons that will become clear later the op- portunities to talk about nanovolts 1 nV 10 −9 V and megavolts 1 MV 10 6 V are rare. Current symbol I. Current is the rate of flow of elec- tric charge past a point. The unit of measure is the ampere or amp with currents usually expressed in amperes A milliamperes 1 mA 10 −3 A microam- peres 1 μA10 −6 A nanoamperes 1 nA 10 −9 A or occasionally picoamperes 1 pA 10 −12 A. A cur- rent of 1 amp equals a flow of 1 coulomb of charge per second. By convention current in a circuit is considered to flow from a more positive point to a more negative point even though the actual electron flow is in the op- posite direction. Important: from these definitions you can see that cur- rents flow through things and voltages are applied or ap- pear across things. So you’ve got to say it right: always re- fer to the voltage between two points or across two points in a circuit. Always refer to current through adeviceor connection in a circuit. To say something like “the voltage through a resistor ...” is nonsense. However we do frequently speak of the voltage at a point in a circuit. This is always understood to mean the voltage between that point and “ground” a com- mon point in the circuit that everyone seems to know about. Soon you will too. We generate voltages by doing work on charges in devices such as batteries conversion of electrochemical energy generators conversion of mechanical energy by magnetic forces solar cells photovoltaic conversion of the energy of photons etc. We get currents by placing volt- ages across things. At this point you may well wonder how to “see” volt- ages and currents. The single most useful electronic instru- ment is the oscilloscope which allows you to look at volt- ages or occasionally currents in a circuit as a function of time. 3 We will deal with oscilloscopes and also volt- meters when we discuss signals shortly for a preview see Appendix O and the multimeter box later in this chapter. 3 It has been said that engineers in other disciplines are envious of elec- trical engineers because we have such a splendid visualization tool. In real circuits we connect things together with wires metallic conductors each of which has the same voltage on it everywhere with respect to ground say. 4 We men- tion this now so that you will realize that an actual circuit doesn’t have to look like its schematic diagram because wires can be rearranged. Here are some simple rules about voltage and current: 1. The sum of the currents into a point in a circuit equals the sum of the currents out conservation of charge. This is sometimes called Kirchhoff’s current law KCL. Engineers like to refer to such a point as a node.Itfol- lows that for a series circuit a bunch of two-terminal things all connected end-to-end the current is the same everywhere. A B Figure 1.1. Parallel connection. 2. Things hooked in parallel Figure 1.1 have the same voltage across them. Restated the sum of the “voltage drops” from A to B via one path through a circuit equals the sum by any other route and is simply the voltage between A and B. Another way to say it is that the sum of the voltage drops around any closed circuit is zero. This is Kirchhoff’s voltage law KVL. 3. The power energy per unit time consumed by a circuit device is P VI 1.1 This is simply energy/charge× charge/time. For V in volts and I in amps P comes out in watts. A watt is a joule per second 1W 1 J/s. So for example the cur- rent flowing through a 60W lightbulb running on 120 V is 0.5 A. Power goes into heat usually or sometimes mechan- ical work motors radiated energy lamps transmitters or stored energy batteries capacitors inductors. Manag- ing the heat load in a complicated system e.g. a large computer in which many kilowatts of electrical energy are converted to heat with the energetically insignificant by- product of a few pages of computational results can be a crucial part of the system design. 4 In the domain of high frequencies or low impedances that isn’t strictly true and we will have more to say about this later and in Chapter 1x. For now it’s a good approximation.

slide 6:

Art of Electronics Third Edition 1.2.2. Relationship between voltage and current: resistors 3 Figure 1.2. A selection of common resistor types. Top row left to right wirewound ceramic power resistors: 20W vitreous enamel with leads 20W with mounting studs 30W vitreous enamel 5W and 20W with mounting studs. Middle row wirewound power resistors: 1W 3W and 5W axial ceramic 5W 10W 25W and 50W conduction-cooled “Dale-type”. Bottom row: 2W 1W 1 2 W 1 4 W and 1 8 W carbon composition surface-mount thick-film 2010 1206 0805 0603 and 0402 sizes surface-mount resistor array 6- 8- and 10-pin single in-line package arrays dual in-line package array. The resistor at bottom is the ubiquitous RN55D 1 4 W 1 metal-film type and the pair of resistors above are Victoreen high-resistance types glass 2GΩ ceramic 5GΩ. Soon when we deal with periodically varying voltages and currents we will have to generalize the simple equa- tion P VI to deal with average power but it’s correct as a statement of instantaneous power just as it stands. Incidentally don’t call current “amperage” that’s strictly bush league. 5 The same caution will apply to the term “ohmage” 6 when we get to resistance in the next section. 1.2.2 Relationship between voltage and current: resistors This is a long and interesting story. It is the heart of elec- tronics. Crudely speaking the name of the game is to make and use gadgets that have interesting and useful I-versus- V characteristics. Resistors I simply proportional to V 5 Unless you’re a power engineer working with giant 13 kV transformers and the like – those guys are allowed to say amperage. 6 . . . also Dude “ohmage” is not the preferred nomenclature: resistance please. capacitors I proportional to rate of change of V diodes I flows in only one direction thermistors temperature- dependent resistor photoresistors light-dependent resis- tor strain gauges strain-dependent resistor etc. are ex- amples. Perhaps more interesting still are three-terminal devices such as transistors in which the current that can flow between a pair of terminals is controlled by the volt- age applied to a third terminal. We will gradually get into some of these exotic devices for now we will start with the most mundane and most widely used circuit element the resistor Figure 1.3. Figure 1.3. Resistor. A. Resistance and resistors It is an interesting fact that the current through a metal- lic conductor or other partially conducting material is proportional to the voltage across it. In the case of wire

slide 7:

4 1.2. Voltage current and resistance Art of Electronics Third Edition PREFIXES Multiple Prefix Symbol Derivation 10 24 yotta Y end-1 of Latin alphabet hint of Greek iota 10 21 zetta Z end of Latin alphabet hint of Greek zeta 10 18 exa E Greek hexa six: power of 1000 10 15 peta P Greek penta five: power of 1000 10 12 tera T Greek teras monster 10 9 giga G Greek gigas giant 10 6 mega M Greek megas great 10 3 kilo k Greek khilioi thousand 10 −3 milli m Latin milli thousand 10 −6 micro μ Greek mikros small 10 −9 nano n Greek nanos dwarf 10 −12 pico p from Italian/Spanish piccolo/pico small 10 −15 femto f Danish/Norwegian femten fifteen 10 −18 atto a Danish/Norwegian atten eighteen 10 −21 zepto z end of Latin alphabet mirrors zetta 10 −24 yocto y end-1 of Latin alphabet mirrors yotta These prefixes are universally used to scale units in science and engineering. Their etymological derivations are a matter of some controversy and should not be con- sidered historically reliable. When abbreviating a unit with a prefix the symbol for the unit follows the prefix without space. Be careful about uppercase and lowercase letters especially m and M in both prefix and unit: 1 mW is a milliwatt or one-thousandth of a watt 1 MHz is a megahertz or 1 million hertz. In general units are spelled with lowercase letters even when they are derived from proper names. The unit name is not capitalized when it is spelled out and used with a prefix only when abbre- viated. Thus: hertz and kilohertz but Hz and kHz watt milliwatt and megawatt but W mW and MW. conductors used in circuits we usually choose a thick- enough gauge of wire so that these “voltage drops” will be negligible. This is by no means a universal law for all objects. For instance the current through a neon bulb is a highly nonlinear function of the applied voltage it is zero up to a critical voltage at which point it rises dramatically. The same goes for a variety of interesting special devices – diodes transistors lightbulbs etc. If you are interested in understanding why metallic conductors behave this way read §§4.4–4.5 in Purcell and Morin’s splendid text Elec- tricity and Magnetism. A resistor is made out of some conducting stuff carbon or a thin metal or carbon film or wire of poor conductivity with a wire or contacts at each end. It is characterized by its resistance: R V/I 1.2 R is in ohms for V in volts and I in amps. This is known as Ohm’s law. Typical resistors of the most frequently used type metal-oxide film metal film or carbon film come in values from 1 ohm 1 Ω to about 10 megohms 10 MΩ. Resistors are also characterized by how much power they can safely dissipate the most commonly used ones are rated at 1/4 or 1/8 W their physical size 7 and by other parameters such as tolerance accuracy temperature co- efficient noise voltage coefficient the extent to which R depends on applied V stability with time inductance etc. See the box on resistors Chapter 1x and Appendix C for further details. Figure 1.2 shows a collection of resistors with most of the available morphologies represented. Roughly speaking resistors are used to convert a 7 The sizes of chip resistors and other components intended for surface mounting are specified by a four-digit size code in which each pair of digits specifies a dimension in units of 0.010 0.25 mm. For exam- ple an 0805 size resistor is 2 mm×1.25 mm or 80 mils×50 mils 1 mil is 0.001 the height must be separately specified. To add confusion to this simple scheme the four-digit size code may instead be metric sometimes without saying so in units of 0.1 mm: thus an “0805” English is also a “2012” metric.

slide 8:

Art of Electronics Third Edition 1.2.2. Relationship between voltage and current: resistors 5 RESISTORS Resistors are truly ubiquitous. There are almost as many types as there are applications. Resistors are used in am- plifiers as loads for active devices in bias networks and as feedback elements. In combination with capacitors they establish time constants and act as filters. They are used to set operating currents and signal levels. Resistors are used in power circuits to reduce voltages by dissi- pating power to measure currents and to discharge ca- pacitors after power is removed. They are used in pre- cision circuits to establish currents to provide accurate voltage ratios and to set precise gain values. In logic cir- cuits they act as bus and line terminators and as “pullup” and “pull-down” resistors. In high-voltage circuits they are used to measure voltages and to equalize leakage cur- rents among diodes or capacitors connected in series. In radiofrequency RF circuits they set the bandwidth of resonant circuits and they are even used as coil forms for inductors. Resistors are available with resistances from 0.0002 Ω through 10 12 Ω standard power ratings from 1/8 watt through 250 watts and accuracies from 0.005 through 20. Resistors can be made from metal films metal- oxide films or carbon films from carbon-composition or ceramic-composition moldings from metal foil or metal wire wound on a form or from semiconductor elements similar to field-effect transistors FETs. The most com- monly used resistor type is formed from a carbon metal or oxide film and comes in two widely used “packages”: the cylindrical axial-lead type typified by the generic RN55D 1 1/4 W metal-film resistor 8 and the much smaller surface-mount “chip resistor.” These common types come in 5 2 and 1 tolerances in a standard set of values ranging from 1 Ω to 10 MΩ. The 1 types have 96 values per decade whereas the 2 and 5 types have 48 and 24 values per decade see Appendix C. Fig- ure 1.2 illustrates most of the common resistor packages. Resistors are so easy to use and well behaved that they’re often taken for granted. They’re not perfect though and you should be aware of some of their limita- tions so that you won’t be surprised someday. The princi- pal defects are variations in resistance with temperature voltage time and humidity. Other defects relate to in- ductance which may be serious at high frequencies the development of thermal hot spots in power applications or electrical noise generation in low-noise amplifiers. We treat these in the advanced Chapter 1x. voltage to a current and vice versa. This may sound aw- fully trite but you will soon see what we mean. B. Resistors in series and parallel From the definition of R some simple results follow: 1. The resistance of two resistors in series Figure 1.4 is R R 1 + R 2 . 1.3 By putting resistors in series you always get a larger re- sistor. 2. The resistance of two resistors in parallel Figure 1.5 is R R 1 R 2 R 1 + R 2 or R 1 1 R 1 + 1 R 2 . 1.4 By putting resistors in parallel you always get a smaller resistor. Resistance is measured in ohms Ω but in prac- tice we frequently omit the Ω symbol when referring to resistors that are more than 1000 Ω 1 kΩ. Thus a 4.7 kΩ resistor is often referred to as a 4.7k resistor and a 1 MΩ 8 Conservatively rated at 1/8 watt in its RN55 military grade “MIL- spec” but rated at 1/4 watt in its CMF-55 industrial grade. R 1 R 2 Figure 1.4. Resistors in series. R 1 R 2 Figure 1.5. Resistors in parallel. resistor as a 1M resistor or 1 meg. 9 If these preliminaries bore you please have patience – we’ll soon get to numer- ous amusing applications. Exercise 1.1. You have a 5k resistor and a 10k resistor. What is their combined resistance a in series and b in parallel Exercise 1.2. If you place a 1 ohm resistor across a 12 volt car battery how much power will it dissipate Exercise 1.3. Prove the formulas for series and parallel resistors. 9 A popular “international” alternative notation replaces the decimal point with the unit multiplier thus 4k7 or 1M0. A 2.2 Ω resistor be- comes 2R2. There is an analogous scheme for capacitors and inductors.

slide 9:

MICROCONTROLLERS CHAPTER 15 15.1 Introduction As we remarked in the previous chapter microcontrollers are essentially stand-alone processors intended to be em- bedded into some electronic device that is definitely not a “computer.” 1 They are inexpensive and easy to use and they let you put the intelligence of a computer into pretty much anything electronic. In so doing they trade off some of the terrifying speed of computer-oriented processors in favor of built-in memory and peripherals. To expand on this point nearly all microcontrollers in- cluding those that cost less than a dollar include both data memory static RAM and non-volatile program mem- ory “flash” on-chip many include additional non-volatile EEPROM for holding calibration data system configura- tion settings and so on. 2 Better still you can choose among integrated “peripherals”: communication links such as SPI I 2 C USB Ethernet Bluetooth and ZigBee buses such as PCI and PCIe SATA PCMCIA flash-memory cards and external memory analog interfaces such as comparators multiplexed ADCs DACs and video and imaging sensors and special-purpose interfaces such as pulse-width modu- lators LCD drivers GPS digital audio and WiFi. To put it another way Figure 15.1 a microcontroller includes within it the “CPU + memory + peripherals” that required an external data bus and separate components in the previous chapter. You can implement an external data bus with a microcontroller if you want to but it’s better to choose a microcontroller that has what you want on-chip. 1 A recent publication from Maxim Integrated Products App Note 3967 begins with the sentence “The heart of today’s advanced electronic products is a microcontroller μC that communicates with one or more peripheral devices.” As a friendly amendment we’d probably omit the word “advanced.” 2 EEPROM permits rewriting or erasing individual stored bytes as con- trasted with flash memory in which erasure required before rewriting can be done only on a block of bytes at once. That is why the lower- density EEPROM is better for storing user data whereas the higher- density flash is best for infrequently rewritten program code. Both mem- ory types are non-volatile and in-circuit programmable though flash typically has less rewriting “endurance” e.g. 10000 erase–write cycles for flash versus 100000 for EEPROM. Of course in an embedded system you don’t boot up from a disk – you don’t even have a disk That’s why the program memory is included on the controller and also why it must be non-volatile: your dishwasher needs to know what it is supposed to do even after a power failure. Because microcontrollers are built into the target device and generally not removable from the circuit board they must be programmable and reprogrammable in-circuit. You program them via an “in-circuit serial programming” interface “ICSP” usually SPI or JTAG with a hardware interface “pod” controlled by software running on a host computer. Microcontrollers are fun and easy. Think of them as a circuit “component” like an op-amp. The analogy is good: just as the op-amp is the universal analog component the microcontroller might be thought of as the universal digital component. 3 And a microcontroller plus a few other com- ponents e.g. a USB connector the programming header a few lights and buttons and perhaps an alphanumeric LCD put onto a small circuit board is a “universal block” whose function is flexibly programmed to do whatever you want. The microcontroller manufacturers happily provide such objects sometimes called “development kits” which of- ten include programming hardware and software see Fig- ure 15.24 on page 1090 to encourage you to adopt their wares. There are also third-party and open-source products such as “Ethernut” and “Arduino”. 4 The former includes an Ethernet port the latter offers serial USB SPI and I 2 C ports with an optional stackable Ethernet adapter. Let’s launch into microcontrollers with a concrete ex- ample. 3 Although experienced users of FPGAs might well argue that their chips are “more universal”: you can put a microcontroller “soft core” into an FPGA but not vice versa. 4 Here are a few more: BeagleBoard BeagleBone Odroid Raspberry Pi and Teensy. 1053

slide 10:

1054 15.2. Design example 1: suntan monitor V Art of Electronics Third Edition IN-CKT DEBUG DATA MEMORY SRAM NON-VOLATILE MEMORY EEPROM PWM PARALLEL I/O SPI ETHERNET USB UART TIMERS OSC STATUS REGISTERS INTERNAL DATA BUS CPU MICROCONTROLLER “μC” INSTRUCTION DECODE LOGIC INSTRUCTION REGISTER PROGRAM COUNTER ICSP STACK POINTER GENERAL PURPOSE REGISTERS PROGRAM MEMORY “FLASH” ARITH. LOGIC UNIT DAC ADC I 2 C/TWI MUX Figure 15.1. A microcontroller integrates memory and “peripherals” onto the same chip as the CPU. ICSP stands for “in-circuit serial programming.” 15.2 Design example 1: suntan monitor V We’ve visited this indispensable device for the beachgoer first in Chapter 4 where we explored three purely ana- log implementations then again in Chapter 13 with a photocurrent-integrating ADC. Those illustrated nicely the use of discrete analog and digital electronics. We con- clude our pursuit of the perfect suntan integrator in this chapter with naturally a microcontroller implementation. We take a first stab at it here with a bit of refinement later in the chapter. To review the task is to inform the sunbather when to turn over or go home after having received the de- sired accumulated dose of sunlight using as input a pho- todiode’s current which is proportional to suntanning in- tensity. The beachgoer sets the target FSE full-sunlight- equivalent dose with a pot on a scale of 0–90 min FSE pushes the START button and begins the bake cycle. A piezo buzzer beeps when the job is complete. 15.2.1 Implementation with a microcontroller An classic but uninspired way to approach this is to con- + thresh discharge μC Figure 15.2. Suntan monitor simply implemented with a micro- controller μC. vert the current to a voltage with op-amp and feedback resistor then use the microcontroller’s on-chip ADC to generate digitized samples which are then integrated nu- merically. But there’s a simpler and better way easily im- plemented even in a 50-cent microcontroller. Look at Fig- ure 15.2. The idea is to use the photocurrent to ramp the

slide 11:

Art of Electronics Third Edition 15.2.1. Implementation with a microcontroller 1055 voltage on a capacitor then use the microcontroller’s ana- log comparator to trigger a short discharge pulse on a three- state digital output port. 5 This generates a sawtooth whose frequency is proportional to light intensity the microcon- troller integrates this by simply counting cycles sounding the horn at the desired terminal count which it derives from a measurement of the “dose” pot’s setting. A digital input- port bit senses the START button and a digital output-port bit activates the piezo buzzer. Not only is this simpler than the humdrum I→V→ADC method it is better: converting a current to a proportional voltage requires good dynamic range and therefore very low offset voltages to integrate accurately at low light in- tensities whereas this I→ f oscillator preserves accuracy by generating a fixed-amplitude sawtooth with excellent linearity at low currents. This departure from the usual modular engineering design approach illustrates nicely the sort of “holistic” creativity that microcontrollers stimulate in their devotees. The circuit of Figure 15.2 is by far the simplest of the five iterations of a suntanning circuit though of course there is the task of writing and downloading the embedded code which we’ll look at next. Before we do that let’s flesh out the circuit in all its glory – component values choice of controller PINs etc. There’s plenty to learn by doing this in an important sense dealing with the details and the compromises they compel is the essence of elec- tronic circuit design. + +4.5V nom 100nF 100nF GG 822 PD1 PC1 PD0 BSS 123 PD7 ADC0 PC0 13 24 20 23 3 7 2 100nF 0 G5842 1μF 1μH 1μA 3 × AAA ATmega 48P DONE set FSE: 0–90min R 2 100k C 1 10nF V ref V ref +1.1V AV CC V CC A in 1 Figure 15.3. Detailed circuit of the suntan monitor. See Fig- ure 4.93 for information about the G5842 GaAsP photosensor. 5 You could arrange things to do the discharge on the same pin as the threshold comparison by dynamically changing a bit in the register that sets the port-bit modes. Figure 15.3 is a complete implementation using parts available at the time this is being written. Let’s look at some details. A. Choice of microcontroller This gadget doesn’t demand much in terms of speed or peripherals and nearly all microcontrollers include a com- parator and an ADC. However we want low current con- sumption and we’d like to run directly from a battery with- out a voltage regulator. We chose this part because it is the smallest of the “picoPower” series of Atmel’s A VR con- trollers which have the virtue of low-power operation even when running from +5 V . 6 It operates from 1.8–5.5 V and draws about 35–170 μA supply current over that range of supply voltages when running from its internal 128 kHz oscillator. B. Discharge circuit Although you could probably get away with using a three- state output to discharge the oscillator’s capacitor directly Figure 15.2 the worst-case specifications would deny you the satisfaction of a job well done: they specify a max- imum leakage current of ±1 μA comparable to the pho- tocurrent in sunlight. You could choose a larger photocell with correspondingly higher photocurrent but an external n-channel MOSFET does the job nicely. 7 Here we’ve used a small BSS123 n-channel MOSFET as an external switch. It’s a good choice: it has a satisfyingly low threshold with ∼0.5 A drain current at 2.5 V of gate drive and a worst- case leakage of 10 nA at V DS 20 V . It’s stocked widely priced at 0.05 in quantity. 8 C. Dose-setting potentiometer The simple diagram biased the pot from the positive supply rail. But good design requires its bias current to be large compared with the 1 μA input leakage spec which adds significant power drain. We can do better though by pow- ering the pot only when we need to i.e. when reading its value. That’s easy – just tie its topside to a digital output- port bit when the software sets that bit HIGH the internal p-channel pullup brings it to +V CC . 6 Many controllers run at low power when operated at low supply voltage say 1.8 V but not at 3–5 V as here. 7 You could instead be reasonably confident that the typical leakage cur- rent is probably less than 10 nA particularly since the specifications are given over the full temperature range of−40 ◦ Cto+85 ◦ C furthermore semiconductor manufacturers are notoriously conservative when spec- ifying leakage. You don’t have to worry about the comparator’s input pin though: its specified leakage current is 50 nA max. 8 The BSS123 is similar to the 2N7000 and 2N7002 see Table 3.4a.

slide 12:

1056 15.2. Design example 1: suntan monitor V Art of Electronics Third Edition D. Bypassing and decoupling Figure 15.3 is decorated with decoupling capacitors per- haps a bit conservatively. We decoupled the analog supply rail AV CC from the noisy digital V CC with the LC filter recommended in the datasheet. We also bypassed the pot readout because it is biased from an equally noisy digital output. Finally we used a parallel combination of supply- rail bypass capacitors to maintain low impedance over fre- quencies. The series inductance and resistance of large- value capacitors reduce their effectiveness at high frequen- cies remedied here by the smaller 100 nF ceramic bypass capacitor see Chapter 1x. Once again we could probably get away with less particularly since we need very little accuracy ∼6 bits from the part’s too-good internal 10-bit ADCs for which the bypass specifications were intended. Butweliketoplayitsafe. E. Oscillator There isn’t one That’s because this controller in common with many includes internal oscillator options for this chip there are two internal oscillators 8 MHz and 128 kHz of modest accuracy ±10. 15.2.2 Microcontroller code “firmware” The embedded software called firmware needs to do sev- eral tasks namely a initializations at power-up set up I/O port modes ADC and comparator modes and reset state of output port bits b assert V CC to the pot wait 25 ms read its voltage then disassert c use the measured voltage to compute the terminal count of oscillation cycles from the sawtooth oscillator cor- responding to the integrated sunlight exposure set by the pot d use the comparator output state to increment the cycle counter and to generate capacitor discharge pulses e when the counter reaches the computed terminal count activate the piezo buzzer. In addition there are some operating characteristics for example oscillator frequency that are not under program control and that are set instead at the time the program code is downloaded to the device. More soon about program- ming these so-called “fuses.” A. Pseudocode We’ve written this in somewhat more detail in Pseu- docode 15.1 pseudocode is a less formal substitute to a graphical flowchart with more readable text. A bit of explanation: the code begins with some Setup tasks. That is because contemporary microcontrollers are richly endowed with built-in peripherals operating modes pin function options and the like. 9 This flexibility and power are both a blessing and a curse. The blessings are obvious. The curse extracts its revenge in requiring you to configure all those options. That is done by setting or clearing bits in an array of registers whose function is to configure and control the device’s options. This particu- lar processor has 256 such internal registers with some 40 bytes worth of configuration and control bits. You gener- ally don’t have to worry about most of them because they default to reasonable values but you do have to set up the range and mode of the ADC and comparator and the port bit directions. The program code is executed on power-up and is obliged to do first this fussy up-front housekeeping: mi- crocontroller port bits can individually be configured as in- puts or outputs under program control which you spec- ify by setting bits in a port direction register if an input you can also enable or disable internal pullup. The setup code continues by initializing the buzzer output bit LOW and the discharge pin HIGH and concludes with choice of ADC and comparator voltage references scaling and in- put sources. There are a few other configuration bits that have to be set specifically the clock source external or internal the clock frequency and the clock divider ratio. For this particular microcontroller these “fuse” bits are set during hardware device programming rather than in the executable program code. 10 Next it Initializes LOW the two output port bits beeper discharge transistor drive and defines and clears a register variable that will hold the accumulating COUNT from the sunlight-proportional sawtooth oscillator. Now we Read the pot that sets the target dose: set PC1 to put V CC across the pot wait 25 ms start the ADC hang on its busy flag then read the high byte of the 10-bit conversion we really don’t need better than 0.5 on this job power down the pot and compute the corresponding terminal count. The latter assumes a nominal 100 Hz full-sunlight sawtooth ∼ 1 μA photocurrent and a full-scale setting of 90 minutes. All this has taken a fraction of a second. Now we 9 For example this processor’s pin 28 is bit 5 of byte-wide bidirectional port C it can also be used as an analog input to the ADC via the internal 8-input multiplexer or as the SCL serial clock or as a “pin- change interrupt” source. 10 For high-pincount microcontrollers it’s common to see a few pins used to determine what happens at boot-up with program control then in charge of those parameters.

slide 13:

Art of Electronics Third Edition 15.2.2. Microcontroller code “firmware” 1057 Pseudocode 15.1 Suntan monitor pseudocode Setup Variables: Define 32-bit integerscount andtermcount Low Power: Disable unused peripherals Ports: Set as outputs PC1 pot bias PD0 cap discharge and PD1 buzzer set as analog inputs PC0 pot readout and PD7 cap voltage initialize PD1 LOW buzzer off and PD0 HIGH cap held at gnd Analog modes: Set comparator mode bandgap ref set ADC ref to Vcc ADC mode to left-adjusted and MUX to channel 0 Read “bake” setting Setbits PC1 power to pot and ADEN ADC enable wait 100 ms Start ADC conversion setbit ADSC Wait while ADSC1 busy then read unsigned 8-bit result “bake” Clearbits PC1 and ADEN and disable ADC to save power Computetermcount360000 x bake/256 Count Cycles Wait while comparator is HIGH V cap V ref then: setbit PD0 then clearbit PD0 software discharge pulse incrementcount ifcounttermcount repeat Count Cycles otherwise set bit PD1 buzzer clear 10 sec later Count cycles of the sawtooth whose ramp is generated by the photocurrent abruptly discharged by a software pulse HIGH then LOW to the MOSFET. Because there’s noth- ing else to do anyway we’ve used simple polling of the comparator’s output bit rather than the more elegant alter- native of a counter-driven interrupt our comparator mode setup disabled its interrupt. When the count reaches the computed target we turn on the beeper and hang “forever” that is until the bakee switches the thing off restart at your peril – twice-baked human. B. Detailed C-code Program 15.1 is a listing of the C-language source code. It should be readable by fluent C programmers though there are a few quirks associated with microcontrollers. The io.h and fuse.h files contain the idiosyncratic register definitions functions etc. that deal with pecu- liarities such as fragmented address spaces and with bit variables. Bit twiddling in ports and registers is common in microcontroller applications it’s done here by OR and AND masking getting the bit positions from the defines and creating the OR mask with “1n” and the AND mask with “∼1n”. For example PORTC1 has value 1 as defined in io.h so the program statement “define POT 1PORTC1”sets POT equal to 0x02. And a tricky gotcha: in an application like this in which values are read from memory-mapped ports such as a comparator or ADC it is essential to declare those variables as volatile to prevent the compiler from “optimizing” away the reload from the associated port. This has been done for you in the io.h file for the standard predefined memory locations but you’d need to do it for any custom memory-mapped variables you create. C. Some comments a We used the power-on switch to initiate the timing cy- cle another way to handle this is to use a pushbutton that brings an input pin to ground you could poll that input bit or you could use a level-sensitive interrupt. The lat- ter is more elegant and has the benefit that the processor could put itself into a micropower 1 μA “sleep” state when done the processor would then wake up upon a pin LOW interrupt. In principle you could even omit the power switch We’d advise against that though because the only recovery from a crashed processor would be to remove the battery. We’ve all experienced commercial electronic de- vices answering machines cameras DVRs that occasion- ally freeze up requiring a “cold reboot” by removing the battery or unplugging the device.